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
Wootric/WootricSDK-Android
androidsdk/src/main/java/com/wootric/androidsdk/network/tasks/CreateEndUserTask.java
// Path: androidsdk/src/main/java/com/wootric/androidsdk/network/WootricApiCallback.java // public interface WootricApiCallback { // void onAuthenticateSuccess(String accessToken); // void onGetEndUserIdSuccess(long endUserId); // void onEndUserNotFound(); // void onCreateEndUserSuccess(long endUserId); // void onApiError(Exception error); // } // // Path: androidsdk/src/main/java/com/wootric/androidsdk/objects/EndUser.java // public class EndUser implements Parcelable { // private static final String UNKNOWN_EMAIL = "Unknown"; // // private long id = -1; // private String email; // private String externalId; // private String phoneNumber; // private long createdAt = -1; // private HashMap properties = new HashMap<>(); // // public EndUser() {} // // public EndUser(EndUser endUser) { // this.id = endUser.id; // this.email = endUser.email; // this.externalId = endUser.externalId; // this.phoneNumber = endUser.phoneNumber; // this.createdAt = endUser.createdAt; // this.properties = endUser.properties; // } // // public EndUser(String email) { // this.email = email; // } // // public EndUser(String email, HashMap properties) { // this.email = email; // this.properties = properties; // } // // public long getId() { // return id; // } // // public String getEmail() { // return email; // } // // public String getExternalId() { // return externalId; // } // // public boolean hasExternalId() { // return Utils.isNotEmpty(externalId); // } // // public String getPhoneNumber() { // return phoneNumber; // } // // public boolean hasPhoneNumber() { // return Utils.isNotEmpty(phoneNumber); // } // // public String getEmailOrUnknown() { // return Utils.isNotEmpty(email) ? email : UNKNOWN_EMAIL; // } // // public long getCreatedAt() { // return createdAt; // } // // public boolean isCreatedAtSet() { // return createdAt != -1; // } // // public void setProperties(HashMap<String, String> properties) { // this.properties = properties; // } // // public HashMap<String, String> getProperties() { // return properties; // } // // public boolean hasProperties() { // return properties != null && properties.size() > 0; // } // // public void setId(long id) { // this.id = id; // } // // public void setEmail(String email) { // this.email = email; // } // // public void setExternalId(String externalId) { // this.externalId = externalId; // } // // public void setPhoneNumber(String phoneNumber) { // this.phoneNumber = phoneNumber; // } // // public void setCreatedAt(long createdAt) { // this.createdAt = createdAt; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeLong(this.id); // dest.writeString(this.email); // dest.writeString(this.externalId); // dest.writeString(this.phoneNumber); // dest.writeLong(this.createdAt); // dest.writeSerializable(this.properties); // } // // private EndUser(Parcel in) { // this.id = in.readLong(); // this.email = in.readString(); // this.externalId = in.readString(); // this.phoneNumber = in.readString(); // this.createdAt = in.readLong(); // this.properties = (HashMap) in.readSerializable(); // } // // public static final Creator<EndUser> CREATOR = new Creator<EndUser>() { // public EndUser createFromParcel(Parcel source) { // return new EndUser(source); // } // public EndUser[] newArray(int size) { // return new EndUser[size]; // } // }; // // public Long getCreatedAtOrNull() { // return isCreatedAtSet() ? getCreatedAt() : null; // } // }
import com.wootric.androidsdk.network.WootricApiCallback; import com.wootric.androidsdk.objects.EndUser; import org.json.JSONException; import org.json.JSONObject; import java.util.Map;
/* * Copyright (c) 2016 Wootric (https://wootric.com) * * 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.wootric.androidsdk.network.tasks; /** * Created by maciejwitowski on 10/13/15. */ public class CreateEndUserTask extends WootricRemoteRequestTask { private final EndUser endUser;
// Path: androidsdk/src/main/java/com/wootric/androidsdk/network/WootricApiCallback.java // public interface WootricApiCallback { // void onAuthenticateSuccess(String accessToken); // void onGetEndUserIdSuccess(long endUserId); // void onEndUserNotFound(); // void onCreateEndUserSuccess(long endUserId); // void onApiError(Exception error); // } // // Path: androidsdk/src/main/java/com/wootric/androidsdk/objects/EndUser.java // public class EndUser implements Parcelable { // private static final String UNKNOWN_EMAIL = "Unknown"; // // private long id = -1; // private String email; // private String externalId; // private String phoneNumber; // private long createdAt = -1; // private HashMap properties = new HashMap<>(); // // public EndUser() {} // // public EndUser(EndUser endUser) { // this.id = endUser.id; // this.email = endUser.email; // this.externalId = endUser.externalId; // this.phoneNumber = endUser.phoneNumber; // this.createdAt = endUser.createdAt; // this.properties = endUser.properties; // } // // public EndUser(String email) { // this.email = email; // } // // public EndUser(String email, HashMap properties) { // this.email = email; // this.properties = properties; // } // // public long getId() { // return id; // } // // public String getEmail() { // return email; // } // // public String getExternalId() { // return externalId; // } // // public boolean hasExternalId() { // return Utils.isNotEmpty(externalId); // } // // public String getPhoneNumber() { // return phoneNumber; // } // // public boolean hasPhoneNumber() { // return Utils.isNotEmpty(phoneNumber); // } // // public String getEmailOrUnknown() { // return Utils.isNotEmpty(email) ? email : UNKNOWN_EMAIL; // } // // public long getCreatedAt() { // return createdAt; // } // // public boolean isCreatedAtSet() { // return createdAt != -1; // } // // public void setProperties(HashMap<String, String> properties) { // this.properties = properties; // } // // public HashMap<String, String> getProperties() { // return properties; // } // // public boolean hasProperties() { // return properties != null && properties.size() > 0; // } // // public void setId(long id) { // this.id = id; // } // // public void setEmail(String email) { // this.email = email; // } // // public void setExternalId(String externalId) { // this.externalId = externalId; // } // // public void setPhoneNumber(String phoneNumber) { // this.phoneNumber = phoneNumber; // } // // public void setCreatedAt(long createdAt) { // this.createdAt = createdAt; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeLong(this.id); // dest.writeString(this.email); // dest.writeString(this.externalId); // dest.writeString(this.phoneNumber); // dest.writeLong(this.createdAt); // dest.writeSerializable(this.properties); // } // // private EndUser(Parcel in) { // this.id = in.readLong(); // this.email = in.readString(); // this.externalId = in.readString(); // this.phoneNumber = in.readString(); // this.createdAt = in.readLong(); // this.properties = (HashMap) in.readSerializable(); // } // // public static final Creator<EndUser> CREATOR = new Creator<EndUser>() { // public EndUser createFromParcel(Parcel source) { // return new EndUser(source); // } // public EndUser[] newArray(int size) { // return new EndUser[size]; // } // }; // // public Long getCreatedAtOrNull() { // return isCreatedAtSet() ? getCreatedAt() : null; // } // } // Path: androidsdk/src/main/java/com/wootric/androidsdk/network/tasks/CreateEndUserTask.java import com.wootric.androidsdk.network.WootricApiCallback; import com.wootric.androidsdk.objects.EndUser; import org.json.JSONException; import org.json.JSONObject; import java.util.Map; /* * Copyright (c) 2016 Wootric (https://wootric.com) * * 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.wootric.androidsdk.network.tasks; /** * Created by maciejwitowski on 10/13/15. */ public class CreateEndUserTask extends WootricRemoteRequestTask { private final EndUser endUser;
public CreateEndUserTask(EndUser endUser, String accessToken, String accountToken, WootricApiCallback wootricApiCallback) {
Wootric/WootricSDK-Android
androidsdk/src/main/java/com/wootric/androidsdk/views/tablet/ScoreView.java
// Path: androidsdk/src/main/java/com/wootric/androidsdk/utils/ScreenUtils.java // public class ScreenUtils { // // private static int screenHeight = 0; // private static int screenWidth = 0; // // public static int getScreenHeight(Context c) { // if (c != null && screenHeight == 0) { // WindowManager wm = (WindowManager) c.getSystemService(Context.WINDOW_SERVICE); // Display display = wm.getDefaultDisplay(); // Point size = new Point(); // display.getSize(size); // screenHeight = size.y; // } // // return screenHeight; // } // // public static int getScreenWidth(Context c) { // if (c != null && screenWidth == 0) { // WindowManager wm = (WindowManager) c.getSystemService(Context.WINDOW_SERVICE); // Display display = wm.getDefaultDisplay(); // Point size = new Point(); // display.getSize(size); // screenWidth = size.x; // } // // return screenWidth; // } // // public static float pxToDp(float px) { // return px / Resources.getSystem().getDisplayMetrics().density; // } // // public static float dpToPx(int dp) { // return dp * Resources.getSystem().getDisplayMetrics().density; // } // // public static void setViewsVisibility(View[] views, boolean visible) { // final int visibility = (visible ? View.VISIBLE : View.GONE); // for(int i = 0; i < views.length; i++) { // views[i].setVisibility(visibility); // } // } // // public static void fadeInView(View view) { // view.animate() // .alpha(1) // .setDuration(1000) // .setInterpolator(new DecelerateInterpolator()) // .start(); // } // }
import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; import com.wootric.androidsdk.R; import com.wootric.androidsdk.utils.ScreenUtils; import android.content.Context; import android.content.res.Resources; import android.graphics.Typeface; import android.graphics.drawable.Drawable; import android.os.Build; import android.util.AttributeSet; import android.util.DisplayMetrics; import android.view.Gravity;
public ScoreView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } private void init() { setGravity(Gravity.CENTER); final Context context = getContext(); final Resources res = context.getResources(); mTextColor = res.getColor(R.color.wootric_tablet_text_score_color); final Resources resources = getResources(); Drawable drawable; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { drawable = resources.getDrawable(R.drawable.score, null); } else { drawable = resources.getDrawable(R.drawable.score); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { setBackground(drawable); } DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics(); int width = displayMetrics.widthPixels; if (width <= 1200){
// Path: androidsdk/src/main/java/com/wootric/androidsdk/utils/ScreenUtils.java // public class ScreenUtils { // // private static int screenHeight = 0; // private static int screenWidth = 0; // // public static int getScreenHeight(Context c) { // if (c != null && screenHeight == 0) { // WindowManager wm = (WindowManager) c.getSystemService(Context.WINDOW_SERVICE); // Display display = wm.getDefaultDisplay(); // Point size = new Point(); // display.getSize(size); // screenHeight = size.y; // } // // return screenHeight; // } // // public static int getScreenWidth(Context c) { // if (c != null && screenWidth == 0) { // WindowManager wm = (WindowManager) c.getSystemService(Context.WINDOW_SERVICE); // Display display = wm.getDefaultDisplay(); // Point size = new Point(); // display.getSize(size); // screenWidth = size.x; // } // // return screenWidth; // } // // public static float pxToDp(float px) { // return px / Resources.getSystem().getDisplayMetrics().density; // } // // public static float dpToPx(int dp) { // return dp * Resources.getSystem().getDisplayMetrics().density; // } // // public static void setViewsVisibility(View[] views, boolean visible) { // final int visibility = (visible ? View.VISIBLE : View.GONE); // for(int i = 0; i < views.length; i++) { // views[i].setVisibility(visibility); // } // } // // public static void fadeInView(View view) { // view.animate() // .alpha(1) // .setDuration(1000) // .setInterpolator(new DecelerateInterpolator()) // .start(); // } // } // Path: androidsdk/src/main/java/com/wootric/androidsdk/views/tablet/ScoreView.java import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; import com.wootric.androidsdk.R; import com.wootric.androidsdk.utils.ScreenUtils; import android.content.Context; import android.content.res.Resources; import android.graphics.Typeface; import android.graphics.drawable.Drawable; import android.os.Build; import android.util.AttributeSet; import android.util.DisplayMetrics; import android.view.Gravity; public ScoreView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } private void init() { setGravity(Gravity.CENTER); final Context context = getContext(); final Resources res = context.getResources(); mTextColor = res.getColor(R.color.wootric_tablet_text_score_color); final Resources resources = getResources(); Drawable drawable; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { drawable = resources.getDrawable(R.drawable.score, null); } else { drawable = resources.getDrawable(R.drawable.score); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { setBackground(drawable); } DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics(); int width = displayMetrics.widthPixels; if (width <= 1200){
setHeight((int) ScreenUtils.dpToPx(32));
Wootric/WootricSDK-Android
androidsdk/src/main/java/com/wootric/androidsdk/views/phone/RatingBar.java
// Path: androidsdk/src/main/java/com/wootric/androidsdk/objects/Score.java // public final class Score { // private final int score; // private final String surveyType; // private final int surveyTypeScale; // // private static final HashMap<String, ArrayList<HashMap<String, Integer>>> scoreRules = new HashMap<String, ArrayList<HashMap<String, Integer>>>(){ // { // put("NPS", new ArrayList<HashMap<String, Integer>>() {{ // add(new HashMap<String, Integer>() {{ // put("min", 0); // put("max", 10); // put("negative_type_max", 6); // put("neutral_type_max", 8); // }}); // }}); // put("CES", new ArrayList<HashMap<String, Integer>>() {{ // add(new HashMap<String, Integer>() {{ // put("min", 1); // put("max", 7); // put("negative_type_max", 3); // put("neutral_type_max", 5); // }}); // }}); // put("CSAT", new ArrayList<HashMap<String, Integer>>() {{ // add(new HashMap<String, Integer>() {{ // put("min", 1); // put("max", 5); // put("negative_type_max", 2); // put("neutral_type_max", 3); // }}); // add(new HashMap<String, Integer>() {{ // put("min", 1); // put("max", 10); // put("negative_type_max", 6); // put("neutral_type_max", 8); // }}); // }}); // } // }; // // public Score(int score, String surveyType, int surveyTypeScale) { // this.score = score; // this.surveyType = surveyType; // if (scoreRules.containsKey(surveyType) && surveyTypeScale >= 0 && surveyTypeScale < scoreRules.get(surveyType).size()){ // this.surveyTypeScale = surveyTypeScale; // } else { // this.surveyTypeScale = 0; // } // } // // public boolean isDetractor() { // if (surveyType != null & scoreRules.containsKey(surveyType)){ // return score >= scoreRules.get(surveyType).get(surveyTypeScale).get("min") && // score <= scoreRules.get(surveyType).get(surveyTypeScale).get("negative_type_max"); // } else { // return score >= scoreRules.get("NPS").get(surveyTypeScale).get("min") && // score <= scoreRules.get("NPS").get(surveyTypeScale).get("negative_type_max"); // } // } // // public boolean isPassive() { // if (surveyType != null & scoreRules.containsKey(surveyType)){ // return score > scoreRules.get(surveyType).get(surveyTypeScale).get("negative_type_max") && // score <= scoreRules.get(surveyType).get(surveyTypeScale).get("neutral_type_max"); // } else { // return score > scoreRules.get("NPS").get(surveyTypeScale).get("negative_type_max") && // score <= scoreRules.get("NPS").get(surveyTypeScale).get("neutral_type_max"); // } // } // // public boolean isPromoter() { // if (surveyType != null & scoreRules.containsKey(surveyType)){ // return score > scoreRules.get(surveyType).get(surveyTypeScale).get("neutral_type_max") && // score <= scoreRules.get(surveyType).get(surveyTypeScale).get("max") ; // } else { // return score > scoreRules.get("NPS").get(surveyTypeScale).get("neutral_type_max") && // score <= scoreRules.get("NPS").get(surveyTypeScale).get("max") ; // } // } // // public int maximumScore() { // if (surveyType != null & scoreRules.containsKey(surveyType)){ // return scoreRules.get(surveyType).get(surveyTypeScale).get("max"); // } else { // return scoreRules.get("NPS").get(surveyTypeScale).get("max"); // } // } // // public int minimumScore() { // if (surveyType != null & scoreRules.containsKey(surveyType)){ // return scoreRules.get(surveyType).get(surveyTypeScale).get("min"); // } else { // return scoreRules.get("NPS").get(surveyTypeScale).get("min"); // } // } // }
import android.view.View; import com.wootric.androidsdk.R; import com.wootric.androidsdk.objects.Score; import android.content.Context; import android.content.res.Resources; import android.graphics.Canvas; import android.graphics.Paint; import android.os.Parcel; import android.os.Parcelable; import android.util.AttributeSet; import android.view.MotionEvent;
private OnScoreChangedListener mOnScoreChangedListener; public RatingBar(Context context) { super(context); init(context); } public RatingBar(Context context, AttributeSet attrs) { super(context, attrs); init(context); } public RatingBar(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context); } private void init(Context context) { mContext = context; initResources(); initPaints(); setPadding(0, mRatingBarPaddingVertical, 0, mRatingBarPaddingVertical); setOnTouchListener(this); } private void initResources() { Resources res = mContext.getResources();
// Path: androidsdk/src/main/java/com/wootric/androidsdk/objects/Score.java // public final class Score { // private final int score; // private final String surveyType; // private final int surveyTypeScale; // // private static final HashMap<String, ArrayList<HashMap<String, Integer>>> scoreRules = new HashMap<String, ArrayList<HashMap<String, Integer>>>(){ // { // put("NPS", new ArrayList<HashMap<String, Integer>>() {{ // add(new HashMap<String, Integer>() {{ // put("min", 0); // put("max", 10); // put("negative_type_max", 6); // put("neutral_type_max", 8); // }}); // }}); // put("CES", new ArrayList<HashMap<String, Integer>>() {{ // add(new HashMap<String, Integer>() {{ // put("min", 1); // put("max", 7); // put("negative_type_max", 3); // put("neutral_type_max", 5); // }}); // }}); // put("CSAT", new ArrayList<HashMap<String, Integer>>() {{ // add(new HashMap<String, Integer>() {{ // put("min", 1); // put("max", 5); // put("negative_type_max", 2); // put("neutral_type_max", 3); // }}); // add(new HashMap<String, Integer>() {{ // put("min", 1); // put("max", 10); // put("negative_type_max", 6); // put("neutral_type_max", 8); // }}); // }}); // } // }; // // public Score(int score, String surveyType, int surveyTypeScale) { // this.score = score; // this.surveyType = surveyType; // if (scoreRules.containsKey(surveyType) && surveyTypeScale >= 0 && surveyTypeScale < scoreRules.get(surveyType).size()){ // this.surveyTypeScale = surveyTypeScale; // } else { // this.surveyTypeScale = 0; // } // } // // public boolean isDetractor() { // if (surveyType != null & scoreRules.containsKey(surveyType)){ // return score >= scoreRules.get(surveyType).get(surveyTypeScale).get("min") && // score <= scoreRules.get(surveyType).get(surveyTypeScale).get("negative_type_max"); // } else { // return score >= scoreRules.get("NPS").get(surveyTypeScale).get("min") && // score <= scoreRules.get("NPS").get(surveyTypeScale).get("negative_type_max"); // } // } // // public boolean isPassive() { // if (surveyType != null & scoreRules.containsKey(surveyType)){ // return score > scoreRules.get(surveyType).get(surveyTypeScale).get("negative_type_max") && // score <= scoreRules.get(surveyType).get(surveyTypeScale).get("neutral_type_max"); // } else { // return score > scoreRules.get("NPS").get(surveyTypeScale).get("negative_type_max") && // score <= scoreRules.get("NPS").get(surveyTypeScale).get("neutral_type_max"); // } // } // // public boolean isPromoter() { // if (surveyType != null & scoreRules.containsKey(surveyType)){ // return score > scoreRules.get(surveyType).get(surveyTypeScale).get("neutral_type_max") && // score <= scoreRules.get(surveyType).get(surveyTypeScale).get("max") ; // } else { // return score > scoreRules.get("NPS").get(surveyTypeScale).get("neutral_type_max") && // score <= scoreRules.get("NPS").get(surveyTypeScale).get("max") ; // } // } // // public int maximumScore() { // if (surveyType != null & scoreRules.containsKey(surveyType)){ // return scoreRules.get(surveyType).get(surveyTypeScale).get("max"); // } else { // return scoreRules.get("NPS").get(surveyTypeScale).get("max"); // } // } // // public int minimumScore() { // if (surveyType != null & scoreRules.containsKey(surveyType)){ // return scoreRules.get(surveyType).get(surveyTypeScale).get("min"); // } else { // return scoreRules.get("NPS").get(surveyTypeScale).get("min"); // } // } // } // Path: androidsdk/src/main/java/com/wootric/androidsdk/views/phone/RatingBar.java import android.view.View; import com.wootric.androidsdk.R; import com.wootric.androidsdk.objects.Score; import android.content.Context; import android.content.res.Resources; import android.graphics.Canvas; import android.graphics.Paint; import android.os.Parcel; import android.os.Parcelable; import android.util.AttributeSet; import android.view.MotionEvent; private OnScoreChangedListener mOnScoreChangedListener; public RatingBar(Context context) { super(context); init(context); } public RatingBar(Context context, AttributeSet attrs) { super(context, attrs); init(context); } public RatingBar(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context); } private void init(Context context) { mContext = context; initResources(); initPaints(); setPadding(0, mRatingBarPaddingVertical, 0, mRatingBarPaddingVertical); setOnTouchListener(this); } private void initResources() { Resources res = mContext.getResources();
Score score = new Score(-1, mSurveyType, mSurveyTypeScale);
Wootric/WootricSDK-Android
androidsdk/src/main/java/com/wootric/androidsdk/network/tasks/UpdateEndUserTask.java
// Path: androidsdk/src/main/java/com/wootric/androidsdk/network/WootricApiCallback.java // public interface WootricApiCallback { // void onAuthenticateSuccess(String accessToken); // void onGetEndUserIdSuccess(long endUserId); // void onEndUserNotFound(); // void onCreateEndUserSuccess(long endUserId); // void onApiError(Exception error); // } // // Path: androidsdk/src/main/java/com/wootric/androidsdk/objects/EndUser.java // public class EndUser implements Parcelable { // private static final String UNKNOWN_EMAIL = "Unknown"; // // private long id = -1; // private String email; // private String externalId; // private String phoneNumber; // private long createdAt = -1; // private HashMap properties = new HashMap<>(); // // public EndUser() {} // // public EndUser(EndUser endUser) { // this.id = endUser.id; // this.email = endUser.email; // this.externalId = endUser.externalId; // this.phoneNumber = endUser.phoneNumber; // this.createdAt = endUser.createdAt; // this.properties = endUser.properties; // } // // public EndUser(String email) { // this.email = email; // } // // public EndUser(String email, HashMap properties) { // this.email = email; // this.properties = properties; // } // // public long getId() { // return id; // } // // public String getEmail() { // return email; // } // // public String getExternalId() { // return externalId; // } // // public boolean hasExternalId() { // return Utils.isNotEmpty(externalId); // } // // public String getPhoneNumber() { // return phoneNumber; // } // // public boolean hasPhoneNumber() { // return Utils.isNotEmpty(phoneNumber); // } // // public String getEmailOrUnknown() { // return Utils.isNotEmpty(email) ? email : UNKNOWN_EMAIL; // } // // public long getCreatedAt() { // return createdAt; // } // // public boolean isCreatedAtSet() { // return createdAt != -1; // } // // public void setProperties(HashMap<String, String> properties) { // this.properties = properties; // } // // public HashMap<String, String> getProperties() { // return properties; // } // // public boolean hasProperties() { // return properties != null && properties.size() > 0; // } // // public void setId(long id) { // this.id = id; // } // // public void setEmail(String email) { // this.email = email; // } // // public void setExternalId(String externalId) { // this.externalId = externalId; // } // // public void setPhoneNumber(String phoneNumber) { // this.phoneNumber = phoneNumber; // } // // public void setCreatedAt(long createdAt) { // this.createdAt = createdAt; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeLong(this.id); // dest.writeString(this.email); // dest.writeString(this.externalId); // dest.writeString(this.phoneNumber); // dest.writeLong(this.createdAt); // dest.writeSerializable(this.properties); // } // // private EndUser(Parcel in) { // this.id = in.readLong(); // this.email = in.readString(); // this.externalId = in.readString(); // this.phoneNumber = in.readString(); // this.createdAt = in.readLong(); // this.properties = (HashMap) in.readSerializable(); // } // // public static final Creator<EndUser> CREATOR = new Creator<EndUser>() { // public EndUser createFromParcel(Parcel source) { // return new EndUser(source); // } // public EndUser[] newArray(int size) { // return new EndUser[size]; // } // }; // // public Long getCreatedAtOrNull() { // return isCreatedAtSet() ? getCreatedAt() : null; // } // }
import com.wootric.androidsdk.network.WootricApiCallback; import com.wootric.androidsdk.objects.EndUser; import java.util.Map;
/* * Copyright (c) 2016 Wootric (https://wootric.com) * * 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.wootric.androidsdk.network.tasks; /** * Created by maciejwitowski on 10/13/15. */ public class UpdateEndUserTask extends WootricRemoteRequestTask { private final EndUser endUser;
// Path: androidsdk/src/main/java/com/wootric/androidsdk/network/WootricApiCallback.java // public interface WootricApiCallback { // void onAuthenticateSuccess(String accessToken); // void onGetEndUserIdSuccess(long endUserId); // void onEndUserNotFound(); // void onCreateEndUserSuccess(long endUserId); // void onApiError(Exception error); // } // // Path: androidsdk/src/main/java/com/wootric/androidsdk/objects/EndUser.java // public class EndUser implements Parcelable { // private static final String UNKNOWN_EMAIL = "Unknown"; // // private long id = -1; // private String email; // private String externalId; // private String phoneNumber; // private long createdAt = -1; // private HashMap properties = new HashMap<>(); // // public EndUser() {} // // public EndUser(EndUser endUser) { // this.id = endUser.id; // this.email = endUser.email; // this.externalId = endUser.externalId; // this.phoneNumber = endUser.phoneNumber; // this.createdAt = endUser.createdAt; // this.properties = endUser.properties; // } // // public EndUser(String email) { // this.email = email; // } // // public EndUser(String email, HashMap properties) { // this.email = email; // this.properties = properties; // } // // public long getId() { // return id; // } // // public String getEmail() { // return email; // } // // public String getExternalId() { // return externalId; // } // // public boolean hasExternalId() { // return Utils.isNotEmpty(externalId); // } // // public String getPhoneNumber() { // return phoneNumber; // } // // public boolean hasPhoneNumber() { // return Utils.isNotEmpty(phoneNumber); // } // // public String getEmailOrUnknown() { // return Utils.isNotEmpty(email) ? email : UNKNOWN_EMAIL; // } // // public long getCreatedAt() { // return createdAt; // } // // public boolean isCreatedAtSet() { // return createdAt != -1; // } // // public void setProperties(HashMap<String, String> properties) { // this.properties = properties; // } // // public HashMap<String, String> getProperties() { // return properties; // } // // public boolean hasProperties() { // return properties != null && properties.size() > 0; // } // // public void setId(long id) { // this.id = id; // } // // public void setEmail(String email) { // this.email = email; // } // // public void setExternalId(String externalId) { // this.externalId = externalId; // } // // public void setPhoneNumber(String phoneNumber) { // this.phoneNumber = phoneNumber; // } // // public void setCreatedAt(long createdAt) { // this.createdAt = createdAt; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeLong(this.id); // dest.writeString(this.email); // dest.writeString(this.externalId); // dest.writeString(this.phoneNumber); // dest.writeLong(this.createdAt); // dest.writeSerializable(this.properties); // } // // private EndUser(Parcel in) { // this.id = in.readLong(); // this.email = in.readString(); // this.externalId = in.readString(); // this.phoneNumber = in.readString(); // this.createdAt = in.readLong(); // this.properties = (HashMap) in.readSerializable(); // } // // public static final Creator<EndUser> CREATOR = new Creator<EndUser>() { // public EndUser createFromParcel(Parcel source) { // return new EndUser(source); // } // public EndUser[] newArray(int size) { // return new EndUser[size]; // } // }; // // public Long getCreatedAtOrNull() { // return isCreatedAtSet() ? getCreatedAt() : null; // } // } // Path: androidsdk/src/main/java/com/wootric/androidsdk/network/tasks/UpdateEndUserTask.java import com.wootric.androidsdk.network.WootricApiCallback; import com.wootric.androidsdk.objects.EndUser; import java.util.Map; /* * Copyright (c) 2016 Wootric (https://wootric.com) * * 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.wootric.androidsdk.network.tasks; /** * Created by maciejwitowski on 10/13/15. */ public class UpdateEndUserTask extends WootricRemoteRequestTask { private final EndUser endUser;
public UpdateEndUserTask(EndUser endUser, String accessToken, String accountToken, WootricApiCallback wootricApiCallback) {
Wootric/WootricSDK-Android
androidsdk/src/main/java/com/wootric/androidsdk/objects/Settings.java
// Path: androidsdk/src/main/java/com/wootric/androidsdk/Constants.java // public class Constants { // // public static final long DAY_IN_MILLIS = 1000L *60L *60L *24L; // // public static final int NOT_SET = -1; // // public static final long DEFAULT_RESURVEY_DAYS = 90L; // // public static final long DEFAULT_DECLINE_RESURVEY_DAYS = 30L; // // public static final String TAG = "WOOTRIC_SDK"; // // public static final String CES = "CES"; // // public static final String CSAT = "CSAT"; // } // // Path: androidsdk/src/main/java/com/wootric/androidsdk/utils/Utils.java // public static boolean isBlank(String s) { // return s == null || (s != null && (s.isEmpty() || isWhitespaceString(s))); // }
import org.json.JSONObject; import java.util.Date; import static com.wootric.androidsdk.utils.Utils.isBlank; import android.net.Uri; import android.os.Parcel; import android.os.Parcelable; import com.wootric.androidsdk.Constants; import com.wootric.androidsdk.R; import org.json.JSONException;
/* * Copyright (c) 2016 Wootric (https://wootric.com) * * 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.wootric.androidsdk.objects; /** * Created by maciejwitowski on 5/5/15. */ public class Settings implements Parcelable { private Long firstSurvey = -1L;
// Path: androidsdk/src/main/java/com/wootric/androidsdk/Constants.java // public class Constants { // // public static final long DAY_IN_MILLIS = 1000L *60L *60L *24L; // // public static final int NOT_SET = -1; // // public static final long DEFAULT_RESURVEY_DAYS = 90L; // // public static final long DEFAULT_DECLINE_RESURVEY_DAYS = 30L; // // public static final String TAG = "WOOTRIC_SDK"; // // public static final String CES = "CES"; // // public static final String CSAT = "CSAT"; // } // // Path: androidsdk/src/main/java/com/wootric/androidsdk/utils/Utils.java // public static boolean isBlank(String s) { // return s == null || (s != null && (s.isEmpty() || isWhitespaceString(s))); // } // Path: androidsdk/src/main/java/com/wootric/androidsdk/objects/Settings.java import org.json.JSONObject; import java.util.Date; import static com.wootric.androidsdk.utils.Utils.isBlank; import android.net.Uri; import android.os.Parcel; import android.os.Parcelable; import com.wootric.androidsdk.Constants; import com.wootric.androidsdk.R; import org.json.JSONException; /* * Copyright (c) 2016 Wootric (https://wootric.com) * * 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.wootric.androidsdk.objects; /** * Created by maciejwitowski on 5/5/15. */ public class Settings implements Parcelable { private Long firstSurvey = -1L;
private int adminPanelTimeDelay = Constants.NOT_SET;
Wootric/WootricSDK-Android
androidsdk/src/main/java/com/wootric/androidsdk/objects/Settings.java
// Path: androidsdk/src/main/java/com/wootric/androidsdk/Constants.java // public class Constants { // // public static final long DAY_IN_MILLIS = 1000L *60L *60L *24L; // // public static final int NOT_SET = -1; // // public static final long DEFAULT_RESURVEY_DAYS = 90L; // // public static final long DEFAULT_DECLINE_RESURVEY_DAYS = 30L; // // public static final String TAG = "WOOTRIC_SDK"; // // public static final String CES = "CES"; // // public static final String CSAT = "CSAT"; // } // // Path: androidsdk/src/main/java/com/wootric/androidsdk/utils/Utils.java // public static boolean isBlank(String s) { // return s == null || (s != null && (s.isEmpty() || isWhitespaceString(s))); // }
import org.json.JSONObject; import java.util.Date; import static com.wootric.androidsdk.utils.Utils.isBlank; import android.net.Uri; import android.os.Parcel; import android.os.Parcelable; import com.wootric.androidsdk.Constants; import com.wootric.androidsdk.R; import org.json.JSONException;
public String getAnchorLikely() { return localizedTexts.getAnchorLikely(); } public String getAnchorNotLikely() { return localizedTexts.getAnchorNotLikely(); } public String getBtnSubmit() { return localizedTexts.getSubmit().toUpperCase(); } public String getBtnDismiss() { return localizedTexts.getDismiss().toUpperCase(); } public String getBtnEditScore() { return localizedTexts.getEditScore().toUpperCase(); } public String getBtnOptOut() { return localizedTexts.getOptOut().toUpperCase(); } public String getFollowupQuestion(int score) { String followupQuestion = null; if (localCustomMessage != null) { followupQuestion = localCustomMessage.getFollowupQuestionForScore(score, surveyType, surveyTypeScale); }
// Path: androidsdk/src/main/java/com/wootric/androidsdk/Constants.java // public class Constants { // // public static final long DAY_IN_MILLIS = 1000L *60L *60L *24L; // // public static final int NOT_SET = -1; // // public static final long DEFAULT_RESURVEY_DAYS = 90L; // // public static final long DEFAULT_DECLINE_RESURVEY_DAYS = 30L; // // public static final String TAG = "WOOTRIC_SDK"; // // public static final String CES = "CES"; // // public static final String CSAT = "CSAT"; // } // // Path: androidsdk/src/main/java/com/wootric/androidsdk/utils/Utils.java // public static boolean isBlank(String s) { // return s == null || (s != null && (s.isEmpty() || isWhitespaceString(s))); // } // Path: androidsdk/src/main/java/com/wootric/androidsdk/objects/Settings.java import org.json.JSONObject; import java.util.Date; import static com.wootric.androidsdk.utils.Utils.isBlank; import android.net.Uri; import android.os.Parcel; import android.os.Parcelable; import com.wootric.androidsdk.Constants; import com.wootric.androidsdk.R; import org.json.JSONException; public String getAnchorLikely() { return localizedTexts.getAnchorLikely(); } public String getAnchorNotLikely() { return localizedTexts.getAnchorNotLikely(); } public String getBtnSubmit() { return localizedTexts.getSubmit().toUpperCase(); } public String getBtnDismiss() { return localizedTexts.getDismiss().toUpperCase(); } public String getBtnEditScore() { return localizedTexts.getEditScore().toUpperCase(); } public String getBtnOptOut() { return localizedTexts.getOptOut().toUpperCase(); } public String getFollowupQuestion(int score) { String followupQuestion = null; if (localCustomMessage != null) { followupQuestion = localCustomMessage.getFollowupQuestionForScore(score, surveyType, surveyTypeScale); }
if (isBlank(followupQuestion) && adminPanelCustomMessage != null) {
Wootric/WootricSDK-Android
androidsdk/src/test/java/com/wootric/androidsdk/objects/WootricCustomThankYouTest.java
// Path: androidsdk/src/test/java/com/wootric/androidsdk/TestHelper.java // public class TestHelper { // private static final String CLIENT_ID = "testClientId"; // private static final String CLIENT_SECRET = "testClientSecret"; // private static final String ACCOUNT_TOKEN = "testAccountToken"; // public static final String ORIGIN_URL = "com.test.app"; // // public static User testUser() { // return new User(CLIENT_ID, CLIENT_SECRET, ACCOUNT_TOKEN); // } // // public static EndUser testEndUser() { // return new EndUser(); // } // // public static PreferencesUtils testPreferenceUtils() { // WeakReference weakContext = new WeakReference<>(TEST_FRAGMENT_ACTIVITY.getApplicationContext()); // return new PreferencesUtils(weakContext); // } // // public static final FragmentActivity TEST_FRAGMENT_ACTIVITY = new FragmentActivity() { // @Override // public PackageManager getPackageManager() { // return getPackageManager(); // } // // @Override // public ApplicationInfo getApplicationInfo() { // return TEST_APPLICATION_INFO; // } // // @Override // public Context getApplicationContext() { // return null; // } // }; // // private static final ApplicationInfo TEST_APPLICATION_INFO = new ApplicationInfo() { // public static final String packageName = ""; // }; // // public String loadJSONFromAsset(String fileName) throws IOException { // String json = null; // try { // String path = "src/test/resources/" + fileName; // File file = new File(path); // InputStream is = new FileInputStream(file); // int size = is.available(); // byte[] buffer = new byte[size]; // is.read(buffer); // is.close(); // json = new String(buffer, "UTF-8"); // } catch (IOException ex) { // ex.printStackTrace(); // return null; // } // return json; // } // }
import android.os.Parcel; import com.wootric.androidsdk.TestHelper; import org.json.JSONException; import org.json.JSONObject; import org.junit.Test; import java.io.IOException; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock;
assertThat(customThankYou.getLinkTextForScore(4, "CSAT", 0)).isEqualTo("promoter"); assertThat(customThankYou.getLinkTextForScore(5, "CSAT", 0)).isEqualTo("promoter"); } @Test public void returnsCSATDefaultLinkText() throws Exception { WootricCustomThankYou customThankYou = new WootricCustomThankYou(); customThankYou.setLinkText("thank you"); assertThat(customThankYou.getLinkTextForScore(1, "CSAT", 0)).isEqualTo("thank you"); assertThat(customThankYou.getLinkTextForScore(5, "CSAT", 0)).isEqualTo("thank you"); } @Test public void testWootricCustomThankYouParcelable(){ doReturn("testing parcel").when(mParcel).readString(); WootricCustomThankYou customThankYou = new WootricCustomThankYou(); customThankYou.setText("testing parcel"); Parcel parcel = mParcel; customThankYou.writeToParcel(parcel, 0); parcel.setDataPosition(0); WootricCustomThankYou createdFromParcel = WootricCustomThankYou.CREATOR.createFromParcel(parcel); assertThat(createdFromParcel.getTextForScore(10, "NPS", 0)).isEqualTo("testing parcel"); } @Test public void testWootricCustomThankYouFromJson() throws IOException, JSONException {
// Path: androidsdk/src/test/java/com/wootric/androidsdk/TestHelper.java // public class TestHelper { // private static final String CLIENT_ID = "testClientId"; // private static final String CLIENT_SECRET = "testClientSecret"; // private static final String ACCOUNT_TOKEN = "testAccountToken"; // public static final String ORIGIN_URL = "com.test.app"; // // public static User testUser() { // return new User(CLIENT_ID, CLIENT_SECRET, ACCOUNT_TOKEN); // } // // public static EndUser testEndUser() { // return new EndUser(); // } // // public static PreferencesUtils testPreferenceUtils() { // WeakReference weakContext = new WeakReference<>(TEST_FRAGMENT_ACTIVITY.getApplicationContext()); // return new PreferencesUtils(weakContext); // } // // public static final FragmentActivity TEST_FRAGMENT_ACTIVITY = new FragmentActivity() { // @Override // public PackageManager getPackageManager() { // return getPackageManager(); // } // // @Override // public ApplicationInfo getApplicationInfo() { // return TEST_APPLICATION_INFO; // } // // @Override // public Context getApplicationContext() { // return null; // } // }; // // private static final ApplicationInfo TEST_APPLICATION_INFO = new ApplicationInfo() { // public static final String packageName = ""; // }; // // public String loadJSONFromAsset(String fileName) throws IOException { // String json = null; // try { // String path = "src/test/resources/" + fileName; // File file = new File(path); // InputStream is = new FileInputStream(file); // int size = is.available(); // byte[] buffer = new byte[size]; // is.read(buffer); // is.close(); // json = new String(buffer, "UTF-8"); // } catch (IOException ex) { // ex.printStackTrace(); // return null; // } // return json; // } // } // Path: androidsdk/src/test/java/com/wootric/androidsdk/objects/WootricCustomThankYouTest.java import android.os.Parcel; import com.wootric.androidsdk.TestHelper; import org.json.JSONException; import org.json.JSONObject; import org.junit.Test; import java.io.IOException; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; assertThat(customThankYou.getLinkTextForScore(4, "CSAT", 0)).isEqualTo("promoter"); assertThat(customThankYou.getLinkTextForScore(5, "CSAT", 0)).isEqualTo("promoter"); } @Test public void returnsCSATDefaultLinkText() throws Exception { WootricCustomThankYou customThankYou = new WootricCustomThankYou(); customThankYou.setLinkText("thank you"); assertThat(customThankYou.getLinkTextForScore(1, "CSAT", 0)).isEqualTo("thank you"); assertThat(customThankYou.getLinkTextForScore(5, "CSAT", 0)).isEqualTo("thank you"); } @Test public void testWootricCustomThankYouParcelable(){ doReturn("testing parcel").when(mParcel).readString(); WootricCustomThankYou customThankYou = new WootricCustomThankYou(); customThankYou.setText("testing parcel"); Parcel parcel = mParcel; customThankYou.writeToParcel(parcel, 0); parcel.setDataPosition(0); WootricCustomThankYou createdFromParcel = WootricCustomThankYou.CREATOR.createFromParcel(parcel); assertThat(createdFromParcel.getTextForScore(10, "NPS", 0)).isEqualTo("testing parcel"); } @Test public void testWootricCustomThankYouFromJson() throws IOException, JSONException {
TestHelper helper = new TestHelper();
Wootric/WootricSDK-Android
androidsdk/src/test/java/com/wootric/androidsdk/network/tasks/GetRegisteredEventsTaskTest.java
// Path: androidsdk/src/main/java/com/wootric/androidsdk/objects/User.java // public class User implements Parcelable { // private String clientId; // private String accountToken; // // public User(User user) { // this.clientId = user.clientId; // this.accountToken = user.accountToken; // } // // public User(String clientId, String clientSecret, String accountToken) { // this.clientId = clientId; // this.accountToken = accountToken; // } // // public User(String clientId, String accountToken) { // this.clientId = clientId; // this.accountToken = accountToken; // } // // public User(String accountToken) { // this.accountToken = accountToken; // } // // public String getClientId() { // return clientId; // } // // public String getAccountToken() { // return accountToken; // } // // public void setClientId(String clientId) { // this.clientId = clientId; // } // // public void setAccountToken(String accountToken) { // this.accountToken = accountToken; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(this.clientId); // dest.writeString(this.accountToken); // } // // private User(Parcel in) { // this.clientId = in.readString(); // this.accountToken = in.readString(); // } // // public static final Parcelable.Creator<User> CREATOR = new Parcelable.Creator<User>() { // public User createFromParcel(Parcel source) { // return new User(source); // } // public User[] newArray(int size) { // return new User[size]; // } // }; // }
import com.wootric.androidsdk.objects.User; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.robolectric.RobolectricTestRunner; import static org.assertj.core.api.Assertions.assertThat;
package com.wootric.androidsdk.network.tasks; @RunWith(RobolectricTestRunner.class) public class GetRegisteredEventsTaskTest { @Mock GetRegisteredEventsTask.Callback surveyCallback; @Test public void testGet_RequestWithEuToken() throws Exception {
// Path: androidsdk/src/main/java/com/wootric/androidsdk/objects/User.java // public class User implements Parcelable { // private String clientId; // private String accountToken; // // public User(User user) { // this.clientId = user.clientId; // this.accountToken = user.accountToken; // } // // public User(String clientId, String clientSecret, String accountToken) { // this.clientId = clientId; // this.accountToken = accountToken; // } // // public User(String clientId, String accountToken) { // this.clientId = clientId; // this.accountToken = accountToken; // } // // public User(String accountToken) { // this.accountToken = accountToken; // } // // public String getClientId() { // return clientId; // } // // public String getAccountToken() { // return accountToken; // } // // public void setClientId(String clientId) { // this.clientId = clientId; // } // // public void setAccountToken(String accountToken) { // this.accountToken = accountToken; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(this.clientId); // dest.writeString(this.accountToken); // } // // private User(Parcel in) { // this.clientId = in.readString(); // this.accountToken = in.readString(); // } // // public static final Parcelable.Creator<User> CREATOR = new Parcelable.Creator<User>() { // public User createFromParcel(Parcel source) { // return new User(source); // } // public User[] newArray(int size) { // return new User[size]; // } // }; // } // Path: androidsdk/src/test/java/com/wootric/androidsdk/network/tasks/GetRegisteredEventsTaskTest.java import com.wootric.androidsdk.objects.User; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.robolectric.RobolectricTestRunner; import static org.assertj.core.api.Assertions.assertThat; package com.wootric.androidsdk.network.tasks; @RunWith(RobolectricTestRunner.class) public class GetRegisteredEventsTaskTest { @Mock GetRegisteredEventsTask.Callback surveyCallback; @Test public void testGet_RequestWithEuToken() throws Exception {
User user = new User("NPS-EU");
Wootric/WootricSDK-Android
androidsdk/src/main/java/com/wootric/androidsdk/network/tasks/GetRegisteredEventsTask.java
// Path: androidsdk/src/main/java/com/wootric/androidsdk/Constants.java // public class Constants { // // public static final long DAY_IN_MILLIS = 1000L *60L *60L *24L; // // public static final int NOT_SET = -1; // // public static final long DEFAULT_RESURVEY_DAYS = 90L; // // public static final long DEFAULT_DECLINE_RESURVEY_DAYS = 30L; // // public static final String TAG = "WOOTRIC_SDK"; // // public static final String CES = "CES"; // // public static final String CSAT = "CSAT"; // } // // Path: androidsdk/src/main/java/com/wootric/androidsdk/network/responses/RegisteredEventsResponse.java // public class RegisteredEventsResponse { // private final ArrayList<String> registeredEvents; // // public RegisteredEventsResponse(ArrayList<String> registeredEvents) { // this.registeredEvents = registeredEvents; // } // // public ArrayList<String> getRegisteredEvents() { // return registeredEvents; // } // } // // Path: androidsdk/src/main/java/com/wootric/androidsdk/objects/User.java // public class User implements Parcelable { // private String clientId; // private String accountToken; // // public User(User user) { // this.clientId = user.clientId; // this.accountToken = user.accountToken; // } // // public User(String clientId, String clientSecret, String accountToken) { // this.clientId = clientId; // this.accountToken = accountToken; // } // // public User(String clientId, String accountToken) { // this.clientId = clientId; // this.accountToken = accountToken; // } // // public User(String accountToken) { // this.accountToken = accountToken; // } // // public String getClientId() { // return clientId; // } // // public String getAccountToken() { // return accountToken; // } // // public void setClientId(String clientId) { // this.clientId = clientId; // } // // public void setAccountToken(String accountToken) { // this.accountToken = accountToken; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(this.clientId); // dest.writeString(this.accountToken); // } // // private User(Parcel in) { // this.clientId = in.readString(); // this.accountToken = in.readString(); // } // // public static final Parcelable.Creator<User> CREATOR = new Parcelable.Creator<User>() { // public User createFromParcel(Parcel source) { // return new User(source); // } // public User[] newArray(int size) { // return new User[size]; // } // }; // }
import java.util.ArrayList; import android.util.Log; import com.wootric.androidsdk.Constants; import com.wootric.androidsdk.network.responses.RegisteredEventsResponse; import com.wootric.androidsdk.objects.User; import org.json.JSONArray; import org.json.JSONException;
/* * Copyright (c) 2016 Wootric (https://wootric.com) * * 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.wootric.androidsdk.network.tasks; public class GetRegisteredEventsTask extends WootricRemoteRequestTask { private final User user; private final GetRegisteredEventsTask.Callback surveyCallback; public GetRegisteredEventsTask(User user, GetRegisteredEventsTask.Callback surveyCallback) { super(REQUEST_TYPE_GET, null, user.getAccountToken(), null); this.user = user; this.surveyCallback = surveyCallback; } @Override protected void buildParams() { paramsMap.put("account_token", user.getAccountToken());
// Path: androidsdk/src/main/java/com/wootric/androidsdk/Constants.java // public class Constants { // // public static final long DAY_IN_MILLIS = 1000L *60L *60L *24L; // // public static final int NOT_SET = -1; // // public static final long DEFAULT_RESURVEY_DAYS = 90L; // // public static final long DEFAULT_DECLINE_RESURVEY_DAYS = 30L; // // public static final String TAG = "WOOTRIC_SDK"; // // public static final String CES = "CES"; // // public static final String CSAT = "CSAT"; // } // // Path: androidsdk/src/main/java/com/wootric/androidsdk/network/responses/RegisteredEventsResponse.java // public class RegisteredEventsResponse { // private final ArrayList<String> registeredEvents; // // public RegisteredEventsResponse(ArrayList<String> registeredEvents) { // this.registeredEvents = registeredEvents; // } // // public ArrayList<String> getRegisteredEvents() { // return registeredEvents; // } // } // // Path: androidsdk/src/main/java/com/wootric/androidsdk/objects/User.java // public class User implements Parcelable { // private String clientId; // private String accountToken; // // public User(User user) { // this.clientId = user.clientId; // this.accountToken = user.accountToken; // } // // public User(String clientId, String clientSecret, String accountToken) { // this.clientId = clientId; // this.accountToken = accountToken; // } // // public User(String clientId, String accountToken) { // this.clientId = clientId; // this.accountToken = accountToken; // } // // public User(String accountToken) { // this.accountToken = accountToken; // } // // public String getClientId() { // return clientId; // } // // public String getAccountToken() { // return accountToken; // } // // public void setClientId(String clientId) { // this.clientId = clientId; // } // // public void setAccountToken(String accountToken) { // this.accountToken = accountToken; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(this.clientId); // dest.writeString(this.accountToken); // } // // private User(Parcel in) { // this.clientId = in.readString(); // this.accountToken = in.readString(); // } // // public static final Parcelable.Creator<User> CREATOR = new Parcelable.Creator<User>() { // public User createFromParcel(Parcel source) { // return new User(source); // } // public User[] newArray(int size) { // return new User[size]; // } // }; // } // Path: androidsdk/src/main/java/com/wootric/androidsdk/network/tasks/GetRegisteredEventsTask.java import java.util.ArrayList; import android.util.Log; import com.wootric.androidsdk.Constants; import com.wootric.androidsdk.network.responses.RegisteredEventsResponse; import com.wootric.androidsdk.objects.User; import org.json.JSONArray; import org.json.JSONException; /* * Copyright (c) 2016 Wootric (https://wootric.com) * * 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.wootric.androidsdk.network.tasks; public class GetRegisteredEventsTask extends WootricRemoteRequestTask { private final User user; private final GetRegisteredEventsTask.Callback surveyCallback; public GetRegisteredEventsTask(User user, GetRegisteredEventsTask.Callback surveyCallback) { super(REQUEST_TYPE_GET, null, user.getAccountToken(), null); this.user = user; this.surveyCallback = surveyCallback; } @Override protected void buildParams() { paramsMap.put("account_token", user.getAccountToken());
Log.d(Constants.TAG, "parameters: " + paramsMap);
Wootric/WootricSDK-Android
androidsdk/src/main/java/com/wootric/androidsdk/network/tasks/GetRegisteredEventsTask.java
// Path: androidsdk/src/main/java/com/wootric/androidsdk/Constants.java // public class Constants { // // public static final long DAY_IN_MILLIS = 1000L *60L *60L *24L; // // public static final int NOT_SET = -1; // // public static final long DEFAULT_RESURVEY_DAYS = 90L; // // public static final long DEFAULT_DECLINE_RESURVEY_DAYS = 30L; // // public static final String TAG = "WOOTRIC_SDK"; // // public static final String CES = "CES"; // // public static final String CSAT = "CSAT"; // } // // Path: androidsdk/src/main/java/com/wootric/androidsdk/network/responses/RegisteredEventsResponse.java // public class RegisteredEventsResponse { // private final ArrayList<String> registeredEvents; // // public RegisteredEventsResponse(ArrayList<String> registeredEvents) { // this.registeredEvents = registeredEvents; // } // // public ArrayList<String> getRegisteredEvents() { // return registeredEvents; // } // } // // Path: androidsdk/src/main/java/com/wootric/androidsdk/objects/User.java // public class User implements Parcelable { // private String clientId; // private String accountToken; // // public User(User user) { // this.clientId = user.clientId; // this.accountToken = user.accountToken; // } // // public User(String clientId, String clientSecret, String accountToken) { // this.clientId = clientId; // this.accountToken = accountToken; // } // // public User(String clientId, String accountToken) { // this.clientId = clientId; // this.accountToken = accountToken; // } // // public User(String accountToken) { // this.accountToken = accountToken; // } // // public String getClientId() { // return clientId; // } // // public String getAccountToken() { // return accountToken; // } // // public void setClientId(String clientId) { // this.clientId = clientId; // } // // public void setAccountToken(String accountToken) { // this.accountToken = accountToken; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(this.clientId); // dest.writeString(this.accountToken); // } // // private User(Parcel in) { // this.clientId = in.readString(); // this.accountToken = in.readString(); // } // // public static final Parcelable.Creator<User> CREATOR = new Parcelable.Creator<User>() { // public User createFromParcel(Parcel source) { // return new User(source); // } // public User[] newArray(int size) { // return new User[size]; // } // }; // }
import java.util.ArrayList; import android.util.Log; import com.wootric.androidsdk.Constants; import com.wootric.androidsdk.network.responses.RegisteredEventsResponse; import com.wootric.androidsdk.objects.User; import org.json.JSONArray; import org.json.JSONException;
@Override protected void buildParams() { paramsMap.put("account_token", user.getAccountToken()); Log.d(Constants.TAG, "parameters: " + paramsMap); } @Override protected String requestUrl() { return getSurveyEndpoint() + REGISTERED_EVENTS_PATH; } @Override protected void onSuccess(String response) { ArrayList<String> registeredEventsList = new ArrayList<>(); if (response != null) { try { JSONArray jsonArray = new JSONArray(response); if (jsonArray != null) { for (int i = 0;i < jsonArray.length(); i++){ registeredEventsList.add(jsonArray.getString(i)); } } } catch (JSONException e) { e.printStackTrace(); } }
// Path: androidsdk/src/main/java/com/wootric/androidsdk/Constants.java // public class Constants { // // public static final long DAY_IN_MILLIS = 1000L *60L *60L *24L; // // public static final int NOT_SET = -1; // // public static final long DEFAULT_RESURVEY_DAYS = 90L; // // public static final long DEFAULT_DECLINE_RESURVEY_DAYS = 30L; // // public static final String TAG = "WOOTRIC_SDK"; // // public static final String CES = "CES"; // // public static final String CSAT = "CSAT"; // } // // Path: androidsdk/src/main/java/com/wootric/androidsdk/network/responses/RegisteredEventsResponse.java // public class RegisteredEventsResponse { // private final ArrayList<String> registeredEvents; // // public RegisteredEventsResponse(ArrayList<String> registeredEvents) { // this.registeredEvents = registeredEvents; // } // // public ArrayList<String> getRegisteredEvents() { // return registeredEvents; // } // } // // Path: androidsdk/src/main/java/com/wootric/androidsdk/objects/User.java // public class User implements Parcelable { // private String clientId; // private String accountToken; // // public User(User user) { // this.clientId = user.clientId; // this.accountToken = user.accountToken; // } // // public User(String clientId, String clientSecret, String accountToken) { // this.clientId = clientId; // this.accountToken = accountToken; // } // // public User(String clientId, String accountToken) { // this.clientId = clientId; // this.accountToken = accountToken; // } // // public User(String accountToken) { // this.accountToken = accountToken; // } // // public String getClientId() { // return clientId; // } // // public String getAccountToken() { // return accountToken; // } // // public void setClientId(String clientId) { // this.clientId = clientId; // } // // public void setAccountToken(String accountToken) { // this.accountToken = accountToken; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(this.clientId); // dest.writeString(this.accountToken); // } // // private User(Parcel in) { // this.clientId = in.readString(); // this.accountToken = in.readString(); // } // // public static final Parcelable.Creator<User> CREATOR = new Parcelable.Creator<User>() { // public User createFromParcel(Parcel source) { // return new User(source); // } // public User[] newArray(int size) { // return new User[size]; // } // }; // } // Path: androidsdk/src/main/java/com/wootric/androidsdk/network/tasks/GetRegisteredEventsTask.java import java.util.ArrayList; import android.util.Log; import com.wootric.androidsdk.Constants; import com.wootric.androidsdk.network.responses.RegisteredEventsResponse; import com.wootric.androidsdk.objects.User; import org.json.JSONArray; import org.json.JSONException; @Override protected void buildParams() { paramsMap.put("account_token", user.getAccountToken()); Log.d(Constants.TAG, "parameters: " + paramsMap); } @Override protected String requestUrl() { return getSurveyEndpoint() + REGISTERED_EVENTS_PATH; } @Override protected void onSuccess(String response) { ArrayList<String> registeredEventsList = new ArrayList<>(); if (response != null) { try { JSONArray jsonArray = new JSONArray(response); if (jsonArray != null) { for (int i = 0;i < jsonArray.length(); i++){ registeredEventsList.add(jsonArray.getString(i)); } } } catch (JSONException e) { e.printStackTrace(); } }
RegisteredEventsResponse registeredEventsResponse = new RegisteredEventsResponse(registeredEventsList);
Wootric/WootricSDK-Android
androidsdk/src/main/java/com/wootric/androidsdk/objects/EndUser.java
// Path: androidsdk/src/main/java/com/wootric/androidsdk/utils/Utils.java // public final class Utils { // // private Utils(){} // // public static <T> T checkNotNull(T object, String objectDescription) { // if(object == null) { // throw new IllegalArgumentException(objectDescription + " must not be null"); // } // // return object; // } // // public static boolean isNotEmpty(String s) { // return s != null && !s.isEmpty() && !isWhitespaceString(s); // } // // public static boolean isBlank(String s) { // return s == null || (s != null && (s.isEmpty() || isWhitespaceString(s))); // } // // private static boolean isWhitespaceString(String s) { // return s.trim().length() == 0; // } // // public static void checkDate(long date) { // if (date > 9999999999L) { // Log.d(Constants.TAG, "WARNING: The created date exceeds the maximum 10 characters allowed. " + // "If you are using System.currentTimeMillis() divide it by 1000."); // } else { // Date d = new Date(date * 1000L); // Date now = new Date(); // if (d.after(now)){ // Log.d(Constants.TAG, "WARNING: The created date is on the future"); // } // } // } // // public static byte getByteValue(Boolean bool) { // if (bool != null) { // return bool ? (byte) 1 : (byte) 0; // } else { // return (byte) 0; // } // } // // public static boolean startsWithEU(String aString) { // return aString.startsWith("NPS-EU"); // } // }
import android.os.Parcel; import android.os.Parcelable; import com.wootric.androidsdk.utils.Utils; import java.util.HashMap;
this.id = endUser.id; this.email = endUser.email; this.externalId = endUser.externalId; this.phoneNumber = endUser.phoneNumber; this.createdAt = endUser.createdAt; this.properties = endUser.properties; } public EndUser(String email) { this.email = email; } public EndUser(String email, HashMap properties) { this.email = email; this.properties = properties; } public long getId() { return id; } public String getEmail() { return email; } public String getExternalId() { return externalId; } public boolean hasExternalId() {
// Path: androidsdk/src/main/java/com/wootric/androidsdk/utils/Utils.java // public final class Utils { // // private Utils(){} // // public static <T> T checkNotNull(T object, String objectDescription) { // if(object == null) { // throw new IllegalArgumentException(objectDescription + " must not be null"); // } // // return object; // } // // public static boolean isNotEmpty(String s) { // return s != null && !s.isEmpty() && !isWhitespaceString(s); // } // // public static boolean isBlank(String s) { // return s == null || (s != null && (s.isEmpty() || isWhitespaceString(s))); // } // // private static boolean isWhitespaceString(String s) { // return s.trim().length() == 0; // } // // public static void checkDate(long date) { // if (date > 9999999999L) { // Log.d(Constants.TAG, "WARNING: The created date exceeds the maximum 10 characters allowed. " + // "If you are using System.currentTimeMillis() divide it by 1000."); // } else { // Date d = new Date(date * 1000L); // Date now = new Date(); // if (d.after(now)){ // Log.d(Constants.TAG, "WARNING: The created date is on the future"); // } // } // } // // public static byte getByteValue(Boolean bool) { // if (bool != null) { // return bool ? (byte) 1 : (byte) 0; // } else { // return (byte) 0; // } // } // // public static boolean startsWithEU(String aString) { // return aString.startsWith("NPS-EU"); // } // } // Path: androidsdk/src/main/java/com/wootric/androidsdk/objects/EndUser.java import android.os.Parcel; import android.os.Parcelable; import com.wootric.androidsdk.utils.Utils; import java.util.HashMap; this.id = endUser.id; this.email = endUser.email; this.externalId = endUser.externalId; this.phoneNumber = endUser.phoneNumber; this.createdAt = endUser.createdAt; this.properties = endUser.properties; } public EndUser(String email) { this.email = email; } public EndUser(String email, HashMap properties) { this.email = email; this.properties = properties; } public long getId() { return id; } public String getEmail() { return email; } public String getExternalId() { return externalId; } public boolean hasExternalId() {
return Utils.isNotEmpty(externalId);
Wootric/WootricSDK-Android
androidsdk/src/test/java/com/wootric/androidsdk/network/tasks/CreateResponseTaskTest.java
// Path: androidsdk/src/main/java/com/wootric/androidsdk/OfflineDataHandler.java // public class OfflineDataHandler { // // private static final String LOG_TAG = OfflineDataHandler.class.getName(); // // private static final String KEY_ORIGIN_URL = "origin_url"; // private static final String KEY_END_USER_ID = "end_user_id"; // private static final String KEY_USER_ID = "user_id"; // private static final String KEY_ACCOUNT_ID = "account_id"; // private static final String KEY_SCORE = "score"; // private static final String KEY_PRIORITY = "priority"; // private static final String KEY_TEXT = "text"; // private static final String KEY_UNIQUE_LINK = "survey[unique_link]"; // // private final PreferencesUtils preferencesUtils; // // public OfflineDataHandler(PreferencesUtils preferencesUtils) { // this.preferencesUtils = preferencesUtils; // } // // public void processOfflineData(WootricRemoteClient wootricRemoteClient, String accessToken) { // processResponse(wootricRemoteClient, accessToken); // processDecline(wootricRemoteClient, accessToken); // } // // private void processResponse(WootricRemoteClient wootricRemoteClient, String accessToken) { // String offlineResponse = preferencesUtils.getResponse(); // if(offlineResponse == null) return; // // try { // JSONObject jsonResponse = new JSONObject(preferencesUtils.getResponse()); // wootricRemoteClient.createResponse( // jsonResponse.getLong(KEY_END_USER_ID), // jsonResponse.getLong(KEY_USER_ID), // jsonResponse.getLong(KEY_ACCOUNT_ID), // accessToken, // jsonResponse.getString(KEY_ORIGIN_URL), // jsonResponse.getInt(KEY_SCORE), // jsonResponse.getInt(KEY_PRIORITY), // jsonResponse.getString(KEY_TEXT), // jsonResponse.getString(KEY_UNIQUE_LINK) // ); // // Log.d(LOG_TAG, "Processed offline Response with data: " + offlineResponse); // } catch (JSONException e) { // e.printStackTrace(); // } // // preferencesUtils.putResponse(null); // } // // private void processDecline(WootricRemoteClient wootricRemoteClient, String accessToken) { // String offlineDecline = preferencesUtils.getDecline(); // if(offlineDecline == null) return; // // try { // JSONObject jsonDecline = new JSONObject(preferencesUtils.getDecline()); // wootricRemoteClient.createDecline( // jsonDecline.getLong(KEY_END_USER_ID), // jsonDecline.getLong(KEY_USER_ID), // jsonDecline.getLong(KEY_ACCOUNT_ID), // jsonDecline.getInt(KEY_PRIORITY), // accessToken, // jsonDecline.getString(KEY_ORIGIN_URL), // jsonDecline.getString(KEY_UNIQUE_LINK) // ); // // Log.d(LOG_TAG, "Processed offline Decline with data: " + offlineDecline); // } catch (JSONException e) { // e.printStackTrace(); // } // // preferencesUtils.putDecline(null); // } // // public void saveOfflineResponse(long endUserId, long userId, long accountId, String originUrl, int score, int priority, String text, String uniqueLink) { // JSONObject jsonResponse = new JSONObject(); // try { // jsonResponse.put(KEY_END_USER_ID, endUserId); // jsonResponse.put(KEY_USER_ID, userId); // jsonResponse.put(KEY_ACCOUNT_ID, accountId); // jsonResponse.put(KEY_ORIGIN_URL, originUrl); // jsonResponse.put(KEY_SCORE, score); // jsonResponse.put(KEY_PRIORITY, priority); // jsonResponse.put(KEY_TEXT, text); // jsonResponse.put(KEY_UNIQUE_LINK, uniqueLink); // } catch (JSONException e) { // e.printStackTrace(); // } // // final String stringResponse = jsonResponse.toString(); // preferencesUtils.putResponse(jsonResponse.toString()); // Log.d(LOG_TAG, "Saved offline Response with data: " + stringResponse); // // } // // public void saveOfflineDecline(long endUserId, long userId, long accountId, int priority, String originUrl, String uniqueLink) { // JSONObject jsonDecline = new JSONObject(); // try { // jsonDecline.put(KEY_END_USER_ID, endUserId); // jsonDecline.put(KEY_USER_ID, userId); // jsonDecline.put(KEY_ACCOUNT_ID, accountId); // jsonDecline.put(KEY_PRIORITY, priority); // jsonDecline.put(KEY_ORIGIN_URL, originUrl); // jsonDecline.put(KEY_UNIQUE_LINK, uniqueLink); // } catch (JSONException e) { // e.printStackTrace(); // } // // final String stringDecline = jsonDecline.toString(); // preferencesUtils.putDecline(stringDecline); // Log.d(LOG_TAG, "Saved offline Decline with data: " + stringDecline); // } // }
import com.wootric.androidsdk.OfflineDataHandler; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.robolectric.RobolectricTestRunner; import static org.assertj.core.api.Assertions.assertThat;
package com.wootric.androidsdk.network.tasks; @RunWith(RobolectricTestRunner.class) public class CreateResponseTaskTest { private static final String ACCESS_TOKEN = "accessToken"; private static final String UNIQUE_LINK = "12345qwerty"; private static final String ORIGIN_URL = "com.test.app"; private static final String TEXT = "Test comment"; private static final long END_USER_ID = 123; private static final long USER_ID = 1234; private static final long ACCOUNT_ID = 100; private static final int PRIORITY = 0; private static final int SCORE = 5;
// Path: androidsdk/src/main/java/com/wootric/androidsdk/OfflineDataHandler.java // public class OfflineDataHandler { // // private static final String LOG_TAG = OfflineDataHandler.class.getName(); // // private static final String KEY_ORIGIN_URL = "origin_url"; // private static final String KEY_END_USER_ID = "end_user_id"; // private static final String KEY_USER_ID = "user_id"; // private static final String KEY_ACCOUNT_ID = "account_id"; // private static final String KEY_SCORE = "score"; // private static final String KEY_PRIORITY = "priority"; // private static final String KEY_TEXT = "text"; // private static final String KEY_UNIQUE_LINK = "survey[unique_link]"; // // private final PreferencesUtils preferencesUtils; // // public OfflineDataHandler(PreferencesUtils preferencesUtils) { // this.preferencesUtils = preferencesUtils; // } // // public void processOfflineData(WootricRemoteClient wootricRemoteClient, String accessToken) { // processResponse(wootricRemoteClient, accessToken); // processDecline(wootricRemoteClient, accessToken); // } // // private void processResponse(WootricRemoteClient wootricRemoteClient, String accessToken) { // String offlineResponse = preferencesUtils.getResponse(); // if(offlineResponse == null) return; // // try { // JSONObject jsonResponse = new JSONObject(preferencesUtils.getResponse()); // wootricRemoteClient.createResponse( // jsonResponse.getLong(KEY_END_USER_ID), // jsonResponse.getLong(KEY_USER_ID), // jsonResponse.getLong(KEY_ACCOUNT_ID), // accessToken, // jsonResponse.getString(KEY_ORIGIN_URL), // jsonResponse.getInt(KEY_SCORE), // jsonResponse.getInt(KEY_PRIORITY), // jsonResponse.getString(KEY_TEXT), // jsonResponse.getString(KEY_UNIQUE_LINK) // ); // // Log.d(LOG_TAG, "Processed offline Response with data: " + offlineResponse); // } catch (JSONException e) { // e.printStackTrace(); // } // // preferencesUtils.putResponse(null); // } // // private void processDecline(WootricRemoteClient wootricRemoteClient, String accessToken) { // String offlineDecline = preferencesUtils.getDecline(); // if(offlineDecline == null) return; // // try { // JSONObject jsonDecline = new JSONObject(preferencesUtils.getDecline()); // wootricRemoteClient.createDecline( // jsonDecline.getLong(KEY_END_USER_ID), // jsonDecline.getLong(KEY_USER_ID), // jsonDecline.getLong(KEY_ACCOUNT_ID), // jsonDecline.getInt(KEY_PRIORITY), // accessToken, // jsonDecline.getString(KEY_ORIGIN_URL), // jsonDecline.getString(KEY_UNIQUE_LINK) // ); // // Log.d(LOG_TAG, "Processed offline Decline with data: " + offlineDecline); // } catch (JSONException e) { // e.printStackTrace(); // } // // preferencesUtils.putDecline(null); // } // // public void saveOfflineResponse(long endUserId, long userId, long accountId, String originUrl, int score, int priority, String text, String uniqueLink) { // JSONObject jsonResponse = new JSONObject(); // try { // jsonResponse.put(KEY_END_USER_ID, endUserId); // jsonResponse.put(KEY_USER_ID, userId); // jsonResponse.put(KEY_ACCOUNT_ID, accountId); // jsonResponse.put(KEY_ORIGIN_URL, originUrl); // jsonResponse.put(KEY_SCORE, score); // jsonResponse.put(KEY_PRIORITY, priority); // jsonResponse.put(KEY_TEXT, text); // jsonResponse.put(KEY_UNIQUE_LINK, uniqueLink); // } catch (JSONException e) { // e.printStackTrace(); // } // // final String stringResponse = jsonResponse.toString(); // preferencesUtils.putResponse(jsonResponse.toString()); // Log.d(LOG_TAG, "Saved offline Response with data: " + stringResponse); // // } // // public void saveOfflineDecline(long endUserId, long userId, long accountId, int priority, String originUrl, String uniqueLink) { // JSONObject jsonDecline = new JSONObject(); // try { // jsonDecline.put(KEY_END_USER_ID, endUserId); // jsonDecline.put(KEY_USER_ID, userId); // jsonDecline.put(KEY_ACCOUNT_ID, accountId); // jsonDecline.put(KEY_PRIORITY, priority); // jsonDecline.put(KEY_ORIGIN_URL, originUrl); // jsonDecline.put(KEY_UNIQUE_LINK, uniqueLink); // } catch (JSONException e) { // e.printStackTrace(); // } // // final String stringDecline = jsonDecline.toString(); // preferencesUtils.putDecline(stringDecline); // Log.d(LOG_TAG, "Saved offline Decline with data: " + stringDecline); // } // } // Path: androidsdk/src/test/java/com/wootric/androidsdk/network/tasks/CreateResponseTaskTest.java import com.wootric.androidsdk.OfflineDataHandler; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.robolectric.RobolectricTestRunner; import static org.assertj.core.api.Assertions.assertThat; package com.wootric.androidsdk.network.tasks; @RunWith(RobolectricTestRunner.class) public class CreateResponseTaskTest { private static final String ACCESS_TOKEN = "accessToken"; private static final String UNIQUE_LINK = "12345qwerty"; private static final String ORIGIN_URL = "com.test.app"; private static final String TEXT = "Test comment"; private static final long END_USER_ID = 123; private static final long USER_ID = 1234; private static final long ACCOUNT_ID = 100; private static final int PRIORITY = 0; private static final int SCORE = 5;
@Mock OfflineDataHandler offlineDataHandler;
sladeware/groningen
src/main/java/org/arbeitspferde/groningen/utility/logstream/format/open/DelimitedFactory.java
// Path: src/main/java/org/arbeitspferde/groningen/utility/logstream/OutputLogStream.java // @NotThreadSafe // public interface OutputLogStream extends Flushable, Closeable { // public void write(final Message message) throws IOException; // }
import com.google.protobuf.Message; import org.arbeitspferde.groningen.utility.logstream.OutputLogStream; import org.arbeitspferde.groningen.utility.logstream.OutputLogStreamFactory; import javax.annotation.concurrent.ThreadSafe; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream;
package org.arbeitspferde.groningen.utility.logstream.format.open; /** * <p>{@link DelimitedFactory} furnishes {@link OutputLogStream}s that use use Protocol Buffers' * underlying delimited encoding per {@link Message#writeDelimitedTo(OutputStream)}. * </p> * * {@inheritDoc} */ @ThreadSafe public class DelimitedFactory implements OutputLogStreamFactory { @Override
// Path: src/main/java/org/arbeitspferde/groningen/utility/logstream/OutputLogStream.java // @NotThreadSafe // public interface OutputLogStream extends Flushable, Closeable { // public void write(final Message message) throws IOException; // } // Path: src/main/java/org/arbeitspferde/groningen/utility/logstream/format/open/DelimitedFactory.java import com.google.protobuf.Message; import org.arbeitspferde.groningen.utility.logstream.OutputLogStream; import org.arbeitspferde.groningen.utility.logstream.OutputLogStreamFactory; import javax.annotation.concurrent.ThreadSafe; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; package org.arbeitspferde.groningen.utility.logstream.format.open; /** * <p>{@link DelimitedFactory} furnishes {@link OutputLogStream}s that use use Protocol Buffers' * underlying delimited encoding per {@link Message#writeDelimitedTo(OutputStream)}. * </p> * * {@inheritDoc} */ @ThreadSafe public class DelimitedFactory implements OutputLogStreamFactory { @Override
public OutputLogStream forStream(final OutputStream stream) throws IOException {
sladeware/groningen
src/test/java/org/arbeitspferde/groningen/config/ProtoBufBinaryFileSourceTest.java
// Path: src/main/java/org/arbeitspferde/groningen/config/open/NullLegacyProgramConfigurationMediator.java // @Singleton // public class NullLegacyProgramConfigurationMediator implements LegacyProgramConfigurationMediator { // @Override // public String migrateLegacyConfiguration(final String legacyConfiguration) { // return legacyConfiguration; // } // }
import java.io.File; import java.io.FileOutputStream; import java.io.OutputStream; import org.arbeitspferde.groningen.Helper; import org.arbeitspferde.groningen.LocalFileFactory; import org.arbeitspferde.groningen.NullFileEventNotifierFactory; import org.arbeitspferde.groningen.config.open.NullLegacyProgramConfigurationMediator; import org.arbeitspferde.groningen.proto.GroningenConfigProto.ProgramConfiguration; import org.arbeitspferde.groningen.proto.GroningenConfigProto.ProgramConfiguration.ClusterConfig; import org.arbeitspferde.groningen.proto.GroningenConfigProto.ProgramConfiguration.ClusterConfig.SubjectGroupConfig; import org.arbeitspferde.groningen.utility.FileEventNotifierFactory; import org.arbeitspferde.groningen.utility.FileFactory; import junit.framework.TestCase; import org.apache.commons.io.FileUtils; import java.io.BufferedOutputStream;
/* Copyright 2012 Google, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.arbeitspferde.groningen.config; /** * Tests for ProtoBufBinaryFileSource specific code. */ public class ProtoBufBinaryFileSourceTest extends TestCase { /** * Test to exercise loading a binary format protobuf. This requires accessing a file and * since there isn't a handy way to make a binary protobuf, just make it fresh each time. */ public void testLoad() throws Exception { ProgramConfiguration config = ProgramConfiguration.newBuilder() .setUser("bigtester") .addCluster(ClusterConfig.newBuilder() .setCluster("xx") .addSubjectGroup(SubjectGroupConfig.newBuilder(). setSubjectGroupName("bigTestingGroup"). setExpSettingsFilesDir("/some/path"). build()) .build()) .build(); File tmpDir = Helper.getTestDirectory(); try { String filename = tmpDir.getAbsolutePath() + "proto-bin.cfg"; OutputStream out = new BufferedOutputStream(new FileOutputStream(filename)); config.writeTo(out); out.close(); final FileFactory fakeFileFactory = new LocalFileFactory(); final FileEventNotifierFactory fakeFileEventNotifier = new NullFileEventNotifierFactory(); ProtoBufBinaryFileSource source = new ProtoBufBinaryFileSource(filename, fakeFileFactory,
// Path: src/main/java/org/arbeitspferde/groningen/config/open/NullLegacyProgramConfigurationMediator.java // @Singleton // public class NullLegacyProgramConfigurationMediator implements LegacyProgramConfigurationMediator { // @Override // public String migrateLegacyConfiguration(final String legacyConfiguration) { // return legacyConfiguration; // } // } // Path: src/test/java/org/arbeitspferde/groningen/config/ProtoBufBinaryFileSourceTest.java import java.io.File; import java.io.FileOutputStream; import java.io.OutputStream; import org.arbeitspferde.groningen.Helper; import org.arbeitspferde.groningen.LocalFileFactory; import org.arbeitspferde.groningen.NullFileEventNotifierFactory; import org.arbeitspferde.groningen.config.open.NullLegacyProgramConfigurationMediator; import org.arbeitspferde.groningen.proto.GroningenConfigProto.ProgramConfiguration; import org.arbeitspferde.groningen.proto.GroningenConfigProto.ProgramConfiguration.ClusterConfig; import org.arbeitspferde.groningen.proto.GroningenConfigProto.ProgramConfiguration.ClusterConfig.SubjectGroupConfig; import org.arbeitspferde.groningen.utility.FileEventNotifierFactory; import org.arbeitspferde.groningen.utility.FileFactory; import junit.framework.TestCase; import org.apache.commons.io.FileUtils; import java.io.BufferedOutputStream; /* Copyright 2012 Google, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.arbeitspferde.groningen.config; /** * Tests for ProtoBufBinaryFileSource specific code. */ public class ProtoBufBinaryFileSourceTest extends TestCase { /** * Test to exercise loading a binary format protobuf. This requires accessing a file and * since there isn't a handy way to make a binary protobuf, just make it fresh each time. */ public void testLoad() throws Exception { ProgramConfiguration config = ProgramConfiguration.newBuilder() .setUser("bigtester") .addCluster(ClusterConfig.newBuilder() .setCluster("xx") .addSubjectGroup(SubjectGroupConfig.newBuilder(). setSubjectGroupName("bigTestingGroup"). setExpSettingsFilesDir("/some/path"). build()) .build()) .build(); File tmpDir = Helper.getTestDirectory(); try { String filename = tmpDir.getAbsolutePath() + "proto-bin.cfg"; OutputStream out = new BufferedOutputStream(new FileOutputStream(filename)); config.writeTo(out); out.close(); final FileFactory fakeFileFactory = new LocalFileFactory(); final FileEventNotifierFactory fakeFileEventNotifier = new NullFileEventNotifierFactory(); ProtoBufBinaryFileSource source = new ProtoBufBinaryFileSource(filename, fakeFileFactory,
fakeFileEventNotifier, new NullLegacyProgramConfigurationMediator());
sladeware/groningen
src/test/java/org/arbeitspferde/groningen/historydatastore/MemoryHistoryDatastoreTest.java
// Path: src/main/java/org/arbeitspferde/groningen/HistoryDatastore.java // public interface HistoryDatastore { // /** // * Base exception class for all HistoryDatastoreException-related exceptions. This exception // * was intentionally made a checked one, because nearly any datastore operation may fail and // * usually we have to recover from the failure in the place of a datastore call. // */ // class HistoryDatastoreException extends Exception { // public HistoryDatastoreException() { // super(); // } // // public HistoryDatastoreException(final String message) { // super(message); // } // // public HistoryDatastoreException(final Throwable cause) { // super(cause); // } // // public HistoryDatastoreException(final String message, final Throwable cause) { // super(message, cause); // } // } // // void writeState(PipelineHistoryState state) throws HistoryDatastoreException; // // List<PipelineId> listPipelinesIds() throws HistoryDatastoreException; // // List<PipelineHistoryState> getStatesForPipelineId(PipelineId pipelineId) // throws HistoryDatastoreException; // // List<PipelineHistoryState> getStatesForPipelineId(PipelineId pipelineId, Instant afterTimestamp) // throws HistoryDatastoreException; // }
import org.arbeitspferde.groningen.HistoryDatastore;
package org.arbeitspferde.groningen.historydatastore; /** * Test for {@link MemoryHistoryDatastore}. */ public class MemoryHistoryDatastoreTest extends HistoryDatastoreTestCase { @Override
// Path: src/main/java/org/arbeitspferde/groningen/HistoryDatastore.java // public interface HistoryDatastore { // /** // * Base exception class for all HistoryDatastoreException-related exceptions. This exception // * was intentionally made a checked one, because nearly any datastore operation may fail and // * usually we have to recover from the failure in the place of a datastore call. // */ // class HistoryDatastoreException extends Exception { // public HistoryDatastoreException() { // super(); // } // // public HistoryDatastoreException(final String message) { // super(message); // } // // public HistoryDatastoreException(final Throwable cause) { // super(cause); // } // // public HistoryDatastoreException(final String message, final Throwable cause) { // super(message, cause); // } // } // // void writeState(PipelineHistoryState state) throws HistoryDatastoreException; // // List<PipelineId> listPipelinesIds() throws HistoryDatastoreException; // // List<PipelineHistoryState> getStatesForPipelineId(PipelineId pipelineId) // throws HistoryDatastoreException; // // List<PipelineHistoryState> getStatesForPipelineId(PipelineId pipelineId, Instant afterTimestamp) // throws HistoryDatastoreException; // } // Path: src/test/java/org/arbeitspferde/groningen/historydatastore/MemoryHistoryDatastoreTest.java import org.arbeitspferde.groningen.HistoryDatastore; package org.arbeitspferde.groningen.historydatastore; /** * Test for {@link MemoryHistoryDatastore}. */ public class MemoryHistoryDatastoreTest extends HistoryDatastoreTestCase { @Override
protected HistoryDatastore createHistoryDatastore() {
sladeware/groningen
src/main/java/org/arbeitspferde/groningen/scorer/GenerationNumberWeightedBestPerformerScorer.java
// Path: src/main/java/org/arbeitspferde/groningen/common/EvaluatedSubject.java // public class EvaluatedSubject implements Comparable<EvaluatedSubject> { // private static final long EXPERIMENT_ID_UNINITIALIZED = 0; // private final SubjectStateBridge bridge; // private final Clock clock; // private Instant timeStamp; // private final Fitness fitness = new Fitness(); // // private long experimentId = EXPERIMENT_ID_UNINITIALIZED; // private boolean isDefault = false; // private String clusterName; // private String subjectGroupName; // private String userName; // private int subjectGroupIndex; // // // /** Constructors */ // public EvaluatedSubject(final Clock clock, final SubjectStateBridge subject, final double score, // final long experimentId) { // this(clock, subject, score); // setExperimentId(experimentId); // } // // public EvaluatedSubject(final Clock clock, final SubjectStateBridge bridge, final double score) { // this.clock = clock; // this.bridge = bridge; // setFitness(score); // setTimeStamp(this.clock.now()); // // if (bridge.getAssociatedSubject() != null) { // setClusterName(bridge.getAssociatedSubject().getGroup().getClusterName()); // setSubjectGroupName(bridge.getAssociatedSubject().getGroup().getName()); // setUserName(bridge.getAssociatedSubject().getGroup().getUserName()); // setSubjectGroupIndex(bridge.getAssociatedSubject().getIndex()); // setDefault(bridge.getAssociatedSubject().isDefault()); // } // } // // public void setClusterName(String clusterName) { // this.clusterName = clusterName; // } // // public String getClusterName() { // return clusterName; // } // // public void setSubjectGroupName(String subjectGroupName) { // this.subjectGroupName = subjectGroupName; // } // // public String getSubjectGroupName() { // return subjectGroupName; // } // // public void setUserName(String userName) { // this.userName = userName; // } // // public String getUserName() { // return userName; // } // // public void setSubjectGroupIndex(int subjectGroupIndex) { // this.subjectGroupIndex = subjectGroupIndex; // } // // public int getSubjectGroupIndex() { // return subjectGroupIndex; // } // // /** Set and get methods */ // public SubjectStateBridge getBridge() { // return bridge; // } // // public void setFitness(double score) { // this.fitness.setFitness(score); // } // // public double getFitness() { // return fitness.getFitness(); // } // // public void setExperimentId(final long experimentId) throws IllegalArgumentException { // Preconditions.checkArgument(experimentId > EXPERIMENT_ID_UNINITIALIZED, // "Invalid experimentId: %s; should have been > %s.", experimentId, // EXPERIMENT_ID_UNINITIALIZED); // // this.experimentId = experimentId; // } // // public long getExperimentId() { // Preconditions.checkState(experimentId != EXPERIMENT_ID_UNINITIALIZED, // "experimentID is unset."); // return experimentId; // } // // public void setTimeStamp(Instant timeStamp) { // this.timeStamp = timeStamp; // } // // public Instant getTimeStamp() { // return timeStamp; // } // // /** Uses natural order to compare */ // @Override // public int compareTo(EvaluatedSubject evaluatedSubject) { // return Double.compare(fitness.getFitness(), evaluatedSubject.getFitness()); // } // // public boolean isDefault() { // return isDefault; // } // // public void setDefault(boolean trueOrFalse) { // isDefault = trueOrFalse; // } // // /** // * A class for Fitness, to be extended later. // */ // private class Fitness { // private double fitnessScore; // // public double getFitness() { // return fitnessScore; // } // // public void setFitness(double fitness) { // this.fitnessScore = fitness; // } // } // }
import com.google.common.annotations.VisibleForTesting; import com.google.inject.Inject; import org.arbeitspferde.groningen.common.EvaluatedSubject; import org.arbeitspferde.groningen.utility.Clock; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry;
package org.arbeitspferde.groningen.scorer; /** * HistoricalBestPerformerScorer that uses the generation number as a major weight in scoring. * * The individual's score for this iteration will be weighted (multiplied) by the iteration * number. * * The best performer scoring will combine individuals both within an experiment if they are * duplicated AND will combine scores across iterations. Namely, within the same generation * individuals with the same command line (args and arg values) will be averaged. * * Across iterations, the individual's previous score will be combined with to its score in this * iteration - the individual will be represented by a single @{link EvaluatedSubject} with the * current iteration number and a score equal to the combination of the previous plus current * scores. */ public class GenerationNumberWeightedBestPerformerScorer implements HistoricalBestPerformerScorer { /** * To create new instances of {@link EvaluatedSubject EvaluatedSubjects} when merging existing * instance in the store. */ private final Clock clock; /** Stores the all-time unique and merged evaluated subjects with greatest to least ordering. */ @VisibleForTesting final
// Path: src/main/java/org/arbeitspferde/groningen/common/EvaluatedSubject.java // public class EvaluatedSubject implements Comparable<EvaluatedSubject> { // private static final long EXPERIMENT_ID_UNINITIALIZED = 0; // private final SubjectStateBridge bridge; // private final Clock clock; // private Instant timeStamp; // private final Fitness fitness = new Fitness(); // // private long experimentId = EXPERIMENT_ID_UNINITIALIZED; // private boolean isDefault = false; // private String clusterName; // private String subjectGroupName; // private String userName; // private int subjectGroupIndex; // // // /** Constructors */ // public EvaluatedSubject(final Clock clock, final SubjectStateBridge subject, final double score, // final long experimentId) { // this(clock, subject, score); // setExperimentId(experimentId); // } // // public EvaluatedSubject(final Clock clock, final SubjectStateBridge bridge, final double score) { // this.clock = clock; // this.bridge = bridge; // setFitness(score); // setTimeStamp(this.clock.now()); // // if (bridge.getAssociatedSubject() != null) { // setClusterName(bridge.getAssociatedSubject().getGroup().getClusterName()); // setSubjectGroupName(bridge.getAssociatedSubject().getGroup().getName()); // setUserName(bridge.getAssociatedSubject().getGroup().getUserName()); // setSubjectGroupIndex(bridge.getAssociatedSubject().getIndex()); // setDefault(bridge.getAssociatedSubject().isDefault()); // } // } // // public void setClusterName(String clusterName) { // this.clusterName = clusterName; // } // // public String getClusterName() { // return clusterName; // } // // public void setSubjectGroupName(String subjectGroupName) { // this.subjectGroupName = subjectGroupName; // } // // public String getSubjectGroupName() { // return subjectGroupName; // } // // public void setUserName(String userName) { // this.userName = userName; // } // // public String getUserName() { // return userName; // } // // public void setSubjectGroupIndex(int subjectGroupIndex) { // this.subjectGroupIndex = subjectGroupIndex; // } // // public int getSubjectGroupIndex() { // return subjectGroupIndex; // } // // /** Set and get methods */ // public SubjectStateBridge getBridge() { // return bridge; // } // // public void setFitness(double score) { // this.fitness.setFitness(score); // } // // public double getFitness() { // return fitness.getFitness(); // } // // public void setExperimentId(final long experimentId) throws IllegalArgumentException { // Preconditions.checkArgument(experimentId > EXPERIMENT_ID_UNINITIALIZED, // "Invalid experimentId: %s; should have been > %s.", experimentId, // EXPERIMENT_ID_UNINITIALIZED); // // this.experimentId = experimentId; // } // // public long getExperimentId() { // Preconditions.checkState(experimentId != EXPERIMENT_ID_UNINITIALIZED, // "experimentID is unset."); // return experimentId; // } // // public void setTimeStamp(Instant timeStamp) { // this.timeStamp = timeStamp; // } // // public Instant getTimeStamp() { // return timeStamp; // } // // /** Uses natural order to compare */ // @Override // public int compareTo(EvaluatedSubject evaluatedSubject) { // return Double.compare(fitness.getFitness(), evaluatedSubject.getFitness()); // } // // public boolean isDefault() { // return isDefault; // } // // public void setDefault(boolean trueOrFalse) { // isDefault = trueOrFalse; // } // // /** // * A class for Fitness, to be extended later. // */ // private class Fitness { // private double fitnessScore; // // public double getFitness() { // return fitnessScore; // } // // public void setFitness(double fitness) { // this.fitnessScore = fitness; // } // } // } // Path: src/main/java/org/arbeitspferde/groningen/scorer/GenerationNumberWeightedBestPerformerScorer.java import com.google.common.annotations.VisibleForTesting; import com.google.inject.Inject; import org.arbeitspferde.groningen.common.EvaluatedSubject; import org.arbeitspferde.groningen.utility.Clock; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; package org.arbeitspferde.groningen.scorer; /** * HistoricalBestPerformerScorer that uses the generation number as a major weight in scoring. * * The individual's score for this iteration will be weighted (multiplied) by the iteration * number. * * The best performer scoring will combine individuals both within an experiment if they are * duplicated AND will combine scores across iterations. Namely, within the same generation * individuals with the same command line (args and arg values) will be averaged. * * Across iterations, the individual's previous score will be combined with to its score in this * iteration - the individual will be represented by a single @{link EvaluatedSubject} with the * current iteration number and a score equal to the combination of the previous plus current * scores. */ public class GenerationNumberWeightedBestPerformerScorer implements HistoricalBestPerformerScorer { /** * To create new instances of {@link EvaluatedSubject EvaluatedSubjects} when merging existing * instance in the store. */ private final Clock clock; /** Stores the all-time unique and merged evaluated subjects with greatest to least ordering. */ @VisibleForTesting final
List<EvaluatedSubject> alltimeEvaluatedSubjects = new ArrayList<>();
sladeware/groningen
src/test/java/org/arbeitspferde/groningen/ServicesModuleTest.java
// Path: src/main/java/org/arbeitspferde/groningen/open/OpenModule.java // public class OpenModule extends AbstractModule { // private static final Logger log = Logger.getLogger(OpenModule.class.getCanonicalName()); // // @Override // protected void configure() { // log.info("Binding open injectables."); // // MapBinder<String, Datastore> datastoreBinder = MapBinder.newMapBinder(binder(), String.class, // Datastore.class); // datastoreBinder.addBinding(InMemoryDatastore.class.getCanonicalName()) // .to(InMemoryDatastore.class); // // MapBinder<String, HistoryDatastore> historyDatastoreBinder = // MapBinder.newMapBinder(binder(), String.class, HistoryDatastore.class); // historyDatastoreBinder.addBinding( // MemoryHistoryDatastore.class.getCanonicalName()).to(MemoryHistoryDatastore.class); // // bind(MetricExporter.class).to(NullMetricExporter.class); // bind(SupplementalSettingsProcessor.class).to(NullSupplementalSettingsProcessor.class); // bind(SubjectInterrogator.class).to(NullSubjectInterrogator.class); // bind(FileFactory.class).to(LocalFileFactory.class); // bind(FileEventNotifierFactory.class).to(NullFileEventNotifierFactory.class); // bind(InputLogStreamFactory.class).to(NullInputLogStreamFactory.class); // bind(OutputLogStreamFactory.class).to(FileOutputLogStreamFactory.class); // bind(HealthQuerier.class).to(ProcessHealthQuerier.class); // bind(SubjectManipulator.class).to(ProcessManipulator.class); // bind(VendorSecurityManager.class).to(NullSecurityManager.class); // bind(ServingAddressGenerator.class).to(ProcessServingAddressGenerator.class); // bind(LegacyProgramConfigurationMediator.class) // .to(NullLegacyProgramConfigurationMediator.class); // bind(CollectionLogAddressor.class).to(NullCollectionLogAddressor.class); // } // // /* // * This is merely a short-term hack, as it will require inclusion of the <em>appropriate</em> // * serving port. // */ // @Provides // @Singleton // @Named("servingAddress") // public String produceServingAddress() { // try { // final Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); // // while (interfaces.hasMoreElements()) { // final NetworkInterface currentInterface = interfaces.nextElement(); // // if (currentInterface.isLoopback()) { // continue; // } // // final Enumeration<InetAddress> addresses = currentInterface.getInetAddresses(); // // while (addresses.hasMoreElements()) { // final InetAddress address = addresses.nextElement(); // final String canonicalName = address.getCanonicalHostName(); // // if (!canonicalName.equalsIgnoreCase(address.getHostAddress())) { // return canonicalName; // } // } // } // } catch (final SocketException e) { // log.log(Level.SEVERE, "Error acquiring hostname due to networking stack problems.", e); // } // // log.severe("Could not acquire hostname due to unknown reasons."); // // return "localhost"; // } // // @Provides // @Singleton // public HashFunction getHashFunction() { // return Hashing.md5(); // } // // @Provides // @Singleton // public Server getJettyServer(Settings settings) { // return new Server(settings.getPort()); // } // }
import com.google.inject.Guice; import com.google.inject.Injector; import org.arbeitspferde.groningen.eventlog.EventLoggerService; import org.arbeitspferde.groningen.open.OpenModule; import junit.framework.TestCase;
/* Copyright 2012 Google, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.arbeitspferde.groningen; /** * Tests for {@link ServicesModule}. */ public class ServicesModuleTest extends TestCase { private Injector injector; @Override protected void setUp() throws Exception { // Use the testing infrastructure's temporary directory management infrastructure. final String[] args = new String[] {}; injector = Guice.createInjector( new BaseModule(args), new GroningenConfigParamsModule(),
// Path: src/main/java/org/arbeitspferde/groningen/open/OpenModule.java // public class OpenModule extends AbstractModule { // private static final Logger log = Logger.getLogger(OpenModule.class.getCanonicalName()); // // @Override // protected void configure() { // log.info("Binding open injectables."); // // MapBinder<String, Datastore> datastoreBinder = MapBinder.newMapBinder(binder(), String.class, // Datastore.class); // datastoreBinder.addBinding(InMemoryDatastore.class.getCanonicalName()) // .to(InMemoryDatastore.class); // // MapBinder<String, HistoryDatastore> historyDatastoreBinder = // MapBinder.newMapBinder(binder(), String.class, HistoryDatastore.class); // historyDatastoreBinder.addBinding( // MemoryHistoryDatastore.class.getCanonicalName()).to(MemoryHistoryDatastore.class); // // bind(MetricExporter.class).to(NullMetricExporter.class); // bind(SupplementalSettingsProcessor.class).to(NullSupplementalSettingsProcessor.class); // bind(SubjectInterrogator.class).to(NullSubjectInterrogator.class); // bind(FileFactory.class).to(LocalFileFactory.class); // bind(FileEventNotifierFactory.class).to(NullFileEventNotifierFactory.class); // bind(InputLogStreamFactory.class).to(NullInputLogStreamFactory.class); // bind(OutputLogStreamFactory.class).to(FileOutputLogStreamFactory.class); // bind(HealthQuerier.class).to(ProcessHealthQuerier.class); // bind(SubjectManipulator.class).to(ProcessManipulator.class); // bind(VendorSecurityManager.class).to(NullSecurityManager.class); // bind(ServingAddressGenerator.class).to(ProcessServingAddressGenerator.class); // bind(LegacyProgramConfigurationMediator.class) // .to(NullLegacyProgramConfigurationMediator.class); // bind(CollectionLogAddressor.class).to(NullCollectionLogAddressor.class); // } // // /* // * This is merely a short-term hack, as it will require inclusion of the <em>appropriate</em> // * serving port. // */ // @Provides // @Singleton // @Named("servingAddress") // public String produceServingAddress() { // try { // final Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); // // while (interfaces.hasMoreElements()) { // final NetworkInterface currentInterface = interfaces.nextElement(); // // if (currentInterface.isLoopback()) { // continue; // } // // final Enumeration<InetAddress> addresses = currentInterface.getInetAddresses(); // // while (addresses.hasMoreElements()) { // final InetAddress address = addresses.nextElement(); // final String canonicalName = address.getCanonicalHostName(); // // if (!canonicalName.equalsIgnoreCase(address.getHostAddress())) { // return canonicalName; // } // } // } // } catch (final SocketException e) { // log.log(Level.SEVERE, "Error acquiring hostname due to networking stack problems.", e); // } // // log.severe("Could not acquire hostname due to unknown reasons."); // // return "localhost"; // } // // @Provides // @Singleton // public HashFunction getHashFunction() { // return Hashing.md5(); // } // // @Provides // @Singleton // public Server getJettyServer(Settings settings) { // return new Server(settings.getPort()); // } // } // Path: src/test/java/org/arbeitspferde/groningen/ServicesModuleTest.java import com.google.inject.Guice; import com.google.inject.Injector; import org.arbeitspferde.groningen.eventlog.EventLoggerService; import org.arbeitspferde.groningen.open.OpenModule; import junit.framework.TestCase; /* Copyright 2012 Google, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.arbeitspferde.groningen; /** * Tests for {@link ServicesModule}. */ public class ServicesModuleTest extends TestCase { private Injector injector; @Override protected void setUp() throws Exception { // Use the testing infrastructure's temporary directory management infrastructure. final String[] args = new String[] {}; injector = Guice.createInjector( new BaseModule(args), new GroningenConfigParamsModule(),
new ServicesModule(), new OpenModule());
sladeware/groningen
src/main/java/org/arbeitspferde/groningen/subject/SubjectGroup.java
// Path: src/main/java/org/arbeitspferde/groningen/config/GroningenConfig.java // public interface SubjectGroupConfig { // // /** // * Returns the {@link ClusterConfig} of which this {@link SubjectGroupConfig} is a child. // * // * @return {@link ClusterConfig} of which this {@link SubjectGroupConfig} is a child. // * Can be null if used outside the GroningenConfig config hierarchy // */ // @Nullable // public ClusterConfig getParentCluster(); // // /** // * Returns the name of the subject group. // * // * @return the name of the subject group. // */ // public String getName(); // // /** // * Returns a {@link String} representing the user that should be used to access the // * subject group. // * // * @return The name of user. // * @throws NullPointerException no user was supplied in the configuration hierarchy // */ // public String getUser(); // // /** // * Returns a {@link String} representing the path where per-subject experiment settings files // * will be stored. These files will be read by jvm_arg_injector and it will inject their // * contents into the experiments' subjects' command line. For every subject group's member, // * Groningen will create a file with a full path looking like this: // * <exp_settings_files_dir>/<subject_index> // * // * @return Full path to the experiments settings files directory for the subjects of this // * subject group // * @throws NullPointerException no experiment settings files directory path was specified for // * this subject group // */ // public String getExperimentSettingsFilesDir(); // // /** // * Returns a {@link List} of {@link SubjectConfig} representing either // * configuration for all of the subjects or none. Groningen will use all subjects in a subject // * group, requiring separation of the test instances from the nontest instances into separate // * subject groups. If the list specifies a partial set of the subjects, the remaining subjects // * will have values chosen at random. This allows for injecting known argument sets to see how // * they fair with randomly chosen values. // * // * @return list of configurations which can be linked to specific or random subjects depending // * on the internals of the SubjectConfig // */ // public ImmutableList<SubjectConfig> getSpecialSubjectConfigs(); // // /** // * Returns an int that represents the number of subjects in a subject group that Groningen is // * permitted to control for experimentation purposes. Setting this to value N implies that // * subjects 0 to N-1 within a subject group are controlled by Groningen. // */ // public int getNumberOfSubjects(); // // /** // * Returns the max number of seconds that an experimental subject is allowed to _not_ return OK // * on health checks probes when running an experiment. Defaulting to 0 implies that Groningen // * will pick a reasonable value for this (currently 300 secs). // */ // public int getSubjectWarmupTimeout(); // // /** // * Returns True if this subject group has a custom restart command. Otherwise, an // * automatically-generated one should be used. // */ // public boolean hasRestartCommand(); // // /** // * Returns the custom restart command if one is specified. // */ // public String[] getRestartCommand(); // // /** // * Returns the number of subjects with default settings. These subjects won't be touched by // * hypothesizer. This number should be less than total number of subjects in experiment. // */ // public int getNumberOfDefaultSubjects(); // } // // Path: src/main/java/org/arbeitspferde/groningen/utility/TemporaryFailure.java // public class TemporaryFailure extends Exception { // public TemporaryFailure(final String message) { // super(message); // } // // public TemporaryFailure(final String message, final Throwable e) { // super(message, e); // } // // public TemporaryFailure(final Throwable e) { // super(e); // } // }
import com.google.common.base.Joiner; import com.google.common.base.Objects; import com.google.common.collect.Lists; import com.google.inject.Inject; import org.arbeitspferde.groningen.config.GroningenConfig.SubjectGroupConfig; import org.arbeitspferde.groningen.config.NamedConfigParam; import org.arbeitspferde.groningen.proto.Params.GroningenParams; import org.arbeitspferde.groningen.utility.PermanentFailure; import org.arbeitspferde.groningen.utility.TemporaryFailure; import java.util.List;
/* Copyright 2012 Google, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.arbeitspferde.groningen.subject; /** * This class represents an experimental population of {@link Subject}s. */ public class SubjectGroup { private static final Joiner slashJoiner = Joiner.on("/"); private static final Joiner commaJoiner = Joiner.on(","); @Inject @NamedConfigParam("subject_manipulation_deadline_ms") private final int populationCensusCollectionDeadline = GroningenParams.getDefaultInstance().getSubjectManipulationDeadlineMs(); private final String clusterName; private final String name; private final String userName;
// Path: src/main/java/org/arbeitspferde/groningen/config/GroningenConfig.java // public interface SubjectGroupConfig { // // /** // * Returns the {@link ClusterConfig} of which this {@link SubjectGroupConfig} is a child. // * // * @return {@link ClusterConfig} of which this {@link SubjectGroupConfig} is a child. // * Can be null if used outside the GroningenConfig config hierarchy // */ // @Nullable // public ClusterConfig getParentCluster(); // // /** // * Returns the name of the subject group. // * // * @return the name of the subject group. // */ // public String getName(); // // /** // * Returns a {@link String} representing the user that should be used to access the // * subject group. // * // * @return The name of user. // * @throws NullPointerException no user was supplied in the configuration hierarchy // */ // public String getUser(); // // /** // * Returns a {@link String} representing the path where per-subject experiment settings files // * will be stored. These files will be read by jvm_arg_injector and it will inject their // * contents into the experiments' subjects' command line. For every subject group's member, // * Groningen will create a file with a full path looking like this: // * <exp_settings_files_dir>/<subject_index> // * // * @return Full path to the experiments settings files directory for the subjects of this // * subject group // * @throws NullPointerException no experiment settings files directory path was specified for // * this subject group // */ // public String getExperimentSettingsFilesDir(); // // /** // * Returns a {@link List} of {@link SubjectConfig} representing either // * configuration for all of the subjects or none. Groningen will use all subjects in a subject // * group, requiring separation of the test instances from the nontest instances into separate // * subject groups. If the list specifies a partial set of the subjects, the remaining subjects // * will have values chosen at random. This allows for injecting known argument sets to see how // * they fair with randomly chosen values. // * // * @return list of configurations which can be linked to specific or random subjects depending // * on the internals of the SubjectConfig // */ // public ImmutableList<SubjectConfig> getSpecialSubjectConfigs(); // // /** // * Returns an int that represents the number of subjects in a subject group that Groningen is // * permitted to control for experimentation purposes. Setting this to value N implies that // * subjects 0 to N-1 within a subject group are controlled by Groningen. // */ // public int getNumberOfSubjects(); // // /** // * Returns the max number of seconds that an experimental subject is allowed to _not_ return OK // * on health checks probes when running an experiment. Defaulting to 0 implies that Groningen // * will pick a reasonable value for this (currently 300 secs). // */ // public int getSubjectWarmupTimeout(); // // /** // * Returns True if this subject group has a custom restart command. Otherwise, an // * automatically-generated one should be used. // */ // public boolean hasRestartCommand(); // // /** // * Returns the custom restart command if one is specified. // */ // public String[] getRestartCommand(); // // /** // * Returns the number of subjects with default settings. These subjects won't be touched by // * hypothesizer. This number should be less than total number of subjects in experiment. // */ // public int getNumberOfDefaultSubjects(); // } // // Path: src/main/java/org/arbeitspferde/groningen/utility/TemporaryFailure.java // public class TemporaryFailure extends Exception { // public TemporaryFailure(final String message) { // super(message); // } // // public TemporaryFailure(final String message, final Throwable e) { // super(message, e); // } // // public TemporaryFailure(final Throwable e) { // super(e); // } // } // Path: src/main/java/org/arbeitspferde/groningen/subject/SubjectGroup.java import com.google.common.base.Joiner; import com.google.common.base.Objects; import com.google.common.collect.Lists; import com.google.inject.Inject; import org.arbeitspferde.groningen.config.GroningenConfig.SubjectGroupConfig; import org.arbeitspferde.groningen.config.NamedConfigParam; import org.arbeitspferde.groningen.proto.Params.GroningenParams; import org.arbeitspferde.groningen.utility.PermanentFailure; import org.arbeitspferde.groningen.utility.TemporaryFailure; import java.util.List; /* Copyright 2012 Google, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.arbeitspferde.groningen.subject; /** * This class represents an experimental population of {@link Subject}s. */ public class SubjectGroup { private static final Joiner slashJoiner = Joiner.on("/"); private static final Joiner commaJoiner = Joiner.on(","); @Inject @NamedConfigParam("subject_manipulation_deadline_ms") private final int populationCensusCollectionDeadline = GroningenParams.getDefaultInstance().getSubjectManipulationDeadlineMs(); private final String clusterName; private final String name; private final String userName;
private final SubjectGroupConfig config;
sladeware/groningen
src/main/java/org/arbeitspferde/groningen/subject/SubjectGroup.java
// Path: src/main/java/org/arbeitspferde/groningen/config/GroningenConfig.java // public interface SubjectGroupConfig { // // /** // * Returns the {@link ClusterConfig} of which this {@link SubjectGroupConfig} is a child. // * // * @return {@link ClusterConfig} of which this {@link SubjectGroupConfig} is a child. // * Can be null if used outside the GroningenConfig config hierarchy // */ // @Nullable // public ClusterConfig getParentCluster(); // // /** // * Returns the name of the subject group. // * // * @return the name of the subject group. // */ // public String getName(); // // /** // * Returns a {@link String} representing the user that should be used to access the // * subject group. // * // * @return The name of user. // * @throws NullPointerException no user was supplied in the configuration hierarchy // */ // public String getUser(); // // /** // * Returns a {@link String} representing the path where per-subject experiment settings files // * will be stored. These files will be read by jvm_arg_injector and it will inject their // * contents into the experiments' subjects' command line. For every subject group's member, // * Groningen will create a file with a full path looking like this: // * <exp_settings_files_dir>/<subject_index> // * // * @return Full path to the experiments settings files directory for the subjects of this // * subject group // * @throws NullPointerException no experiment settings files directory path was specified for // * this subject group // */ // public String getExperimentSettingsFilesDir(); // // /** // * Returns a {@link List} of {@link SubjectConfig} representing either // * configuration for all of the subjects or none. Groningen will use all subjects in a subject // * group, requiring separation of the test instances from the nontest instances into separate // * subject groups. If the list specifies a partial set of the subjects, the remaining subjects // * will have values chosen at random. This allows for injecting known argument sets to see how // * they fair with randomly chosen values. // * // * @return list of configurations which can be linked to specific or random subjects depending // * on the internals of the SubjectConfig // */ // public ImmutableList<SubjectConfig> getSpecialSubjectConfigs(); // // /** // * Returns an int that represents the number of subjects in a subject group that Groningen is // * permitted to control for experimentation purposes. Setting this to value N implies that // * subjects 0 to N-1 within a subject group are controlled by Groningen. // */ // public int getNumberOfSubjects(); // // /** // * Returns the max number of seconds that an experimental subject is allowed to _not_ return OK // * on health checks probes when running an experiment. Defaulting to 0 implies that Groningen // * will pick a reasonable value for this (currently 300 secs). // */ // public int getSubjectWarmupTimeout(); // // /** // * Returns True if this subject group has a custom restart command. Otherwise, an // * automatically-generated one should be used. // */ // public boolean hasRestartCommand(); // // /** // * Returns the custom restart command if one is specified. // */ // public String[] getRestartCommand(); // // /** // * Returns the number of subjects with default settings. These subjects won't be touched by // * hypothesizer. This number should be less than total number of subjects in experiment. // */ // public int getNumberOfDefaultSubjects(); // } // // Path: src/main/java/org/arbeitspferde/groningen/utility/TemporaryFailure.java // public class TemporaryFailure extends Exception { // public TemporaryFailure(final String message) { // super(message); // } // // public TemporaryFailure(final String message, final Throwable e) { // super(message, e); // } // // public TemporaryFailure(final Throwable e) { // super(e); // } // }
import com.google.common.base.Joiner; import com.google.common.base.Objects; import com.google.common.collect.Lists; import com.google.inject.Inject; import org.arbeitspferde.groningen.config.GroningenConfig.SubjectGroupConfig; import org.arbeitspferde.groningen.config.NamedConfigParam; import org.arbeitspferde.groningen.proto.Params.GroningenParams; import org.arbeitspferde.groningen.utility.PermanentFailure; import org.arbeitspferde.groningen.utility.TemporaryFailure; import java.util.List;
/* Copyright 2012 Google, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.arbeitspferde.groningen.subject; /** * This class represents an experimental population of {@link Subject}s. */ public class SubjectGroup { private static final Joiner slashJoiner = Joiner.on("/"); private static final Joiner commaJoiner = Joiner.on(","); @Inject @NamedConfigParam("subject_manipulation_deadline_ms") private final int populationCensusCollectionDeadline = GroningenParams.getDefaultInstance().getSubjectManipulationDeadlineMs(); private final String clusterName; private final String name; private final String userName; private final SubjectGroupConfig config; private final List<Subject> subjects; private final ServingAddressGenerator servingAddressbuilder; public SubjectGroup(final String clusterName, final String name, final String userName, final SubjectGroupConfig groupConfig, final ServingAddressGenerator servingAddressBuilder) { this.clusterName = clusterName; this.name = name; this.userName = userName; this.config = groupConfig; this.subjects = Lists.newArrayList(); this.servingAddressbuilder = servingAddressBuilder; } /** Initializes subject data * * You must call initialize before accessing any of the subject data or you won't find any :) * * @param manipulator The means for manipulating subject state. * @param origSubjectList The original subject list that the new list is concatenated with. * This has the side effect of concatinating the new list onto the * origSubjectList. * * @return The list of subjects within this subject we control concatenated onto the origSubjectList */ public List<Subject> initialize(SubjectManipulator manipulator, List<Subject> origSubjectList)
// Path: src/main/java/org/arbeitspferde/groningen/config/GroningenConfig.java // public interface SubjectGroupConfig { // // /** // * Returns the {@link ClusterConfig} of which this {@link SubjectGroupConfig} is a child. // * // * @return {@link ClusterConfig} of which this {@link SubjectGroupConfig} is a child. // * Can be null if used outside the GroningenConfig config hierarchy // */ // @Nullable // public ClusterConfig getParentCluster(); // // /** // * Returns the name of the subject group. // * // * @return the name of the subject group. // */ // public String getName(); // // /** // * Returns a {@link String} representing the user that should be used to access the // * subject group. // * // * @return The name of user. // * @throws NullPointerException no user was supplied in the configuration hierarchy // */ // public String getUser(); // // /** // * Returns a {@link String} representing the path where per-subject experiment settings files // * will be stored. These files will be read by jvm_arg_injector and it will inject their // * contents into the experiments' subjects' command line. For every subject group's member, // * Groningen will create a file with a full path looking like this: // * <exp_settings_files_dir>/<subject_index> // * // * @return Full path to the experiments settings files directory for the subjects of this // * subject group // * @throws NullPointerException no experiment settings files directory path was specified for // * this subject group // */ // public String getExperimentSettingsFilesDir(); // // /** // * Returns a {@link List} of {@link SubjectConfig} representing either // * configuration for all of the subjects or none. Groningen will use all subjects in a subject // * group, requiring separation of the test instances from the nontest instances into separate // * subject groups. If the list specifies a partial set of the subjects, the remaining subjects // * will have values chosen at random. This allows for injecting known argument sets to see how // * they fair with randomly chosen values. // * // * @return list of configurations which can be linked to specific or random subjects depending // * on the internals of the SubjectConfig // */ // public ImmutableList<SubjectConfig> getSpecialSubjectConfigs(); // // /** // * Returns an int that represents the number of subjects in a subject group that Groningen is // * permitted to control for experimentation purposes. Setting this to value N implies that // * subjects 0 to N-1 within a subject group are controlled by Groningen. // */ // public int getNumberOfSubjects(); // // /** // * Returns the max number of seconds that an experimental subject is allowed to _not_ return OK // * on health checks probes when running an experiment. Defaulting to 0 implies that Groningen // * will pick a reasonable value for this (currently 300 secs). // */ // public int getSubjectWarmupTimeout(); // // /** // * Returns True if this subject group has a custom restart command. Otherwise, an // * automatically-generated one should be used. // */ // public boolean hasRestartCommand(); // // /** // * Returns the custom restart command if one is specified. // */ // public String[] getRestartCommand(); // // /** // * Returns the number of subjects with default settings. These subjects won't be touched by // * hypothesizer. This number should be less than total number of subjects in experiment. // */ // public int getNumberOfDefaultSubjects(); // } // // Path: src/main/java/org/arbeitspferde/groningen/utility/TemporaryFailure.java // public class TemporaryFailure extends Exception { // public TemporaryFailure(final String message) { // super(message); // } // // public TemporaryFailure(final String message, final Throwable e) { // super(message, e); // } // // public TemporaryFailure(final Throwable e) { // super(e); // } // } // Path: src/main/java/org/arbeitspferde/groningen/subject/SubjectGroup.java import com.google.common.base.Joiner; import com.google.common.base.Objects; import com.google.common.collect.Lists; import com.google.inject.Inject; import org.arbeitspferde.groningen.config.GroningenConfig.SubjectGroupConfig; import org.arbeitspferde.groningen.config.NamedConfigParam; import org.arbeitspferde.groningen.proto.Params.GroningenParams; import org.arbeitspferde.groningen.utility.PermanentFailure; import org.arbeitspferde.groningen.utility.TemporaryFailure; import java.util.List; /* Copyright 2012 Google, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.arbeitspferde.groningen.subject; /** * This class represents an experimental population of {@link Subject}s. */ public class SubjectGroup { private static final Joiner slashJoiner = Joiner.on("/"); private static final Joiner commaJoiner = Joiner.on(","); @Inject @NamedConfigParam("subject_manipulation_deadline_ms") private final int populationCensusCollectionDeadline = GroningenParams.getDefaultInstance().getSubjectManipulationDeadlineMs(); private final String clusterName; private final String name; private final String userName; private final SubjectGroupConfig config; private final List<Subject> subjects; private final ServingAddressGenerator servingAddressbuilder; public SubjectGroup(final String clusterName, final String name, final String userName, final SubjectGroupConfig groupConfig, final ServingAddressGenerator servingAddressBuilder) { this.clusterName = clusterName; this.name = name; this.userName = userName; this.config = groupConfig; this.subjects = Lists.newArrayList(); this.servingAddressbuilder = servingAddressBuilder; } /** Initializes subject data * * You must call initialize before accessing any of the subject data or you won't find any :) * * @param manipulator The means for manipulating subject state. * @param origSubjectList The original subject list that the new list is concatenated with. * This has the side effect of concatinating the new list onto the * origSubjectList. * * @return The list of subjects within this subject we control concatenated onto the origSubjectList */ public List<Subject> initialize(SubjectManipulator manipulator, List<Subject> origSubjectList)
throws PermanentFailure, TemporaryFailure {
sladeware/groningen
src/main/java/org/arbeitspferde/groningen/eventlog/SafeProtoLogger.java
// Path: src/main/java/org/arbeitspferde/groningen/utility/logstream/OutputLogStream.java // @NotThreadSafe // public interface OutputLogStream extends Flushable, Closeable { // public void write(final Message message) throws IOException; // }
import com.google.common.base.Preconditions; import com.google.protobuf.GeneratedMessage; import org.arbeitspferde.groningen.utility.logstream.OutputLogStream; import javax.annotation.concurrent.ThreadSafe; import java.io.Flushable; import java.io.IOException; import java.util.concurrent.atomic.AtomicLong; import java.util.logging.Logger;
/* Copyright 2012 Google, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.arbeitspferde.groningen.eventlog; /* [OutputLogStream] -> [SafeProtoLogger] */ /** * A generic RecordIO-based Protocol Buffer logger that supports automatically flushing and rotating * log buffers on given intervals and works around {@link org.arbeitspferde.groningen.utility.logstream.OutputLogStream}'s single-threaded * design. * * @param <T> The type of Protocol Buffer byte message that shall be encoded in each emission to * the underlying file stream. */ @ThreadSafe public class SafeProtoLogger<T extends GeneratedMessage> implements Flushable { private static final Logger log = Logger.getLogger(SafeProtoLogger.class.getCanonicalName());
// Path: src/main/java/org/arbeitspferde/groningen/utility/logstream/OutputLogStream.java // @NotThreadSafe // public interface OutputLogStream extends Flushable, Closeable { // public void write(final Message message) throws IOException; // } // Path: src/main/java/org/arbeitspferde/groningen/eventlog/SafeProtoLogger.java import com.google.common.base.Preconditions; import com.google.protobuf.GeneratedMessage; import org.arbeitspferde.groningen.utility.logstream.OutputLogStream; import javax.annotation.concurrent.ThreadSafe; import java.io.Flushable; import java.io.IOException; import java.util.concurrent.atomic.AtomicLong; import java.util.logging.Logger; /* Copyright 2012 Google, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.arbeitspferde.groningen.eventlog; /* [OutputLogStream] -> [SafeProtoLogger] */ /** * A generic RecordIO-based Protocol Buffer logger that supports automatically flushing and rotating * log buffers on given intervals and works around {@link org.arbeitspferde.groningen.utility.logstream.OutputLogStream}'s single-threaded * design. * * @param <T> The type of Protocol Buffer byte message that shall be encoded in each emission to * the underlying file stream. */ @ThreadSafe public class SafeProtoLogger<T extends GeneratedMessage> implements Flushable { private static final Logger log = Logger.getLogger(SafeProtoLogger.class.getCanonicalName());
private final OutputLogStream stream;
sladeware/groningen
src/test/java/org/arbeitspferde/groningen/eventlog/SafeProtoLoggerTest.java
// Path: src/main/java/org/arbeitspferde/groningen/utility/logstream/OutputLogStream.java // @NotThreadSafe // public interface OutputLogStream extends Flushable, Closeable { // public void write(final Message message) throws IOException; // }
import com.google.protobuf.Message; import org.arbeitspferde.groningen.proto.Event; import org.arbeitspferde.groningen.utility.logstream.OutputLogStream; import junit.framework.TestCase; import org.easymock.EasyMock;
/* Copyright 2012 Google, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.arbeitspferde.groningen.eventlog; /** * Tests for {@link SafeProtoLogger}. */ public class SafeProtoLoggerTest extends TestCase { private SafeProtoLogger<Event.EventEntry> logger;
// Path: src/main/java/org/arbeitspferde/groningen/utility/logstream/OutputLogStream.java // @NotThreadSafe // public interface OutputLogStream extends Flushable, Closeable { // public void write(final Message message) throws IOException; // } // Path: src/test/java/org/arbeitspferde/groningen/eventlog/SafeProtoLoggerTest.java import com.google.protobuf.Message; import org.arbeitspferde.groningen.proto.Event; import org.arbeitspferde.groningen.utility.logstream.OutputLogStream; import junit.framework.TestCase; import org.easymock.EasyMock; /* Copyright 2012 Google, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.arbeitspferde.groningen.eventlog; /** * Tests for {@link SafeProtoLogger}. */ public class SafeProtoLoggerTest extends TestCase { private SafeProtoLogger<Event.EventEntry> logger;
private OutputLogStream mockOutputLogStream;
sladeware/groningen
src/test/java/org/arbeitspferde/groningen/datastore/InMemoryDatastoreTest.java
// Path: src/main/java/org/arbeitspferde/groningen/Datastore.java // public interface Datastore { // // /** // * Base exception class for all Datastore-related exceptions. This exception was intentionally // * made a checked one, because nearly any datastore operation may fail and usually we have // * to recover from the failure in the place of a datastore call. // */ // class DatastoreException extends Exception { // public DatastoreException() { // super(); // } // // public DatastoreException(final String message) { // super(message); // } // // public DatastoreException(final Throwable cause) { // super(cause); // } // // public DatastoreException(final String message, final Throwable cause) { // super(message, cause); // } // } // // /** // * Exception thrown when pipeline in question already exists. // */ // class PipelineAlreadyExists extends DatastoreException { // private final PipelineState existingPipeline; // // public PipelineAlreadyExists(PipelineState existingPipeline) { // this.existingPipeline = existingPipeline; // } // // public PipelineState existingPipeline() { // return existingPipeline; // } // } // // /** // * Exception thrown when pipeline in question conflicts with already existing pipeline. // */ // class PipelineConflictsWithRunningPipelines extends DatastoreException { // private final List<PipelineState> conflictingPipelines; // // public PipelineConflictsWithRunningPipelines(List<PipelineState> conflictingPipelines) { // this.conflictingPipelines = conflictingPipelines; // } // // public List<PipelineState> conflictingPipelines() { // return conflictingPipelines; // } // } // // List<PipelineId> listPipelinesIds() throws DatastoreException; // // List<PipelineState> getPipelines(List<PipelineId> ids) throws DatastoreException; // // void createPipeline(PipelineState pipelineState, boolean checkForConflicts) // throws PipelineAlreadyExists, PipelineConflictsWithRunningPipelines, DatastoreException; // // void writePipelines(List<PipelineState> pipelinesStates) throws DatastoreException; // // void deletePipelines(List<PipelineId> ids) throws DatastoreException; // // List<PipelineState> findConflictingPipelines(GroningenConfig pipelineConfiguration) // throws DatastoreException; // }
import org.arbeitspferde.groningen.Datastore;
package org.arbeitspferde.groningen.datastore; /** * Test for {@link InMemoryDatastore}. */ public class InMemoryDatastoreTest extends DatastoreTestCase { @Override
// Path: src/main/java/org/arbeitspferde/groningen/Datastore.java // public interface Datastore { // // /** // * Base exception class for all Datastore-related exceptions. This exception was intentionally // * made a checked one, because nearly any datastore operation may fail and usually we have // * to recover from the failure in the place of a datastore call. // */ // class DatastoreException extends Exception { // public DatastoreException() { // super(); // } // // public DatastoreException(final String message) { // super(message); // } // // public DatastoreException(final Throwable cause) { // super(cause); // } // // public DatastoreException(final String message, final Throwable cause) { // super(message, cause); // } // } // // /** // * Exception thrown when pipeline in question already exists. // */ // class PipelineAlreadyExists extends DatastoreException { // private final PipelineState existingPipeline; // // public PipelineAlreadyExists(PipelineState existingPipeline) { // this.existingPipeline = existingPipeline; // } // // public PipelineState existingPipeline() { // return existingPipeline; // } // } // // /** // * Exception thrown when pipeline in question conflicts with already existing pipeline. // */ // class PipelineConflictsWithRunningPipelines extends DatastoreException { // private final List<PipelineState> conflictingPipelines; // // public PipelineConflictsWithRunningPipelines(List<PipelineState> conflictingPipelines) { // this.conflictingPipelines = conflictingPipelines; // } // // public List<PipelineState> conflictingPipelines() { // return conflictingPipelines; // } // } // // List<PipelineId> listPipelinesIds() throws DatastoreException; // // List<PipelineState> getPipelines(List<PipelineId> ids) throws DatastoreException; // // void createPipeline(PipelineState pipelineState, boolean checkForConflicts) // throws PipelineAlreadyExists, PipelineConflictsWithRunningPipelines, DatastoreException; // // void writePipelines(List<PipelineState> pipelinesStates) throws DatastoreException; // // void deletePipelines(List<PipelineId> ids) throws DatastoreException; // // List<PipelineState> findConflictingPipelines(GroningenConfig pipelineConfiguration) // throws DatastoreException; // } // Path: src/test/java/org/arbeitspferde/groningen/datastore/InMemoryDatastoreTest.java import org.arbeitspferde.groningen.Datastore; package org.arbeitspferde.groningen.datastore; /** * Test for {@link InMemoryDatastore}. */ public class InMemoryDatastoreTest extends DatastoreTestCase { @Override
protected Datastore createDatastore() {
sladeware/groningen
src/main/java/org/arbeitspferde/groningen/eventlog/SafeProtoLoggerFactory.java
// Path: src/main/java/org/arbeitspferde/groningen/utility/logstream/OutputLogStream.java // @NotThreadSafe // public interface OutputLogStream extends Flushable, Closeable { // public void write(final Message message) throws IOException; // }
import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.google.inject.Inject; import com.google.inject.Provider; import com.google.inject.Singleton; import org.arbeitspferde.groningen.proto.Event; import org.arbeitspferde.groningen.utility.logstream.OutputLogStream; import org.arbeitspferde.groningen.utility.logstream.OutputLogStreamFactory; import org.arbeitspferde.groningen.utility.logstream.OutputLogStreamFactory.Specification; import java.io.IOException; import java.util.Timer; import java.util.TimerTask; import java.util.logging.Logger;
/* Copyright 2012 Google, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.arbeitspferde.groningen.eventlog; /** * A producer of {@link SafeProtoLogger}. * * This class is rather trivial, but it exists to keep the complexity of {@link SafeProtoLogger}'s * constructor to a minimum. */ @Singleton public class SafeProtoLoggerFactory { private static final Logger log = Logger.getLogger(SafeProtoLogger.class.getCanonicalName()); private final Provider<Timer> timerProvider; private final OutputLogStreamFactory outputLogStreamFactory; /** * Create factory that produces safe protocol buffer loggers. * * @param timerProvider The {@link Provider} or {@link Timer} for testability. */ @Inject SafeProtoLoggerFactory(final Provider<Timer> timerProvider, final OutputLogStreamFactory outputLogStreamFactory) { this.timerProvider = timerProvider; this.outputLogStreamFactory = outputLogStreamFactory; } /** * Create a new {@link SafeProtoLogger} of {@link Event.EventEntry}. * * @param basename See {@link Specification#getFilenamePrefix()}. * @param port See {@link Specification#getServingPort()}. * @param rotateSize See {@link Specification#rotateFileUponAtSizeBytes()}. * @param flushIntervalSeconds The interval in seconds between automatic log flush events. * @param loggerName The human-readable canonical name for the log. * * @return A {@link SafeProtoLogger} that meets the supra specifications. * * @throws IOException In the event that the RecordIO cannot be provisioned. */ public SafeProtoLogger<Event.EventEntry> newEventEntryLogger(final String basename, final int port, final long rotateSize, final int flushIntervalSeconds, final String loggerName) throws IOException { Preconditions.checkNotNull(basename, "basename may not be null."); Preconditions.checkArgument(port > 0, "port must be > 0."); Preconditions.checkArgument(rotateSize >= 0, "rotateSize must >= 0."); Preconditions.checkArgument(flushIntervalSeconds >= 0, "flushIntervalSeconds must >= 0."); Preconditions.checkNotNull(loggerName, "loggerName may not be null."); log.info(String.format("Creating RecordIO log around %s.", basename));
// Path: src/main/java/org/arbeitspferde/groningen/utility/logstream/OutputLogStream.java // @NotThreadSafe // public interface OutputLogStream extends Flushable, Closeable { // public void write(final Message message) throws IOException; // } // Path: src/main/java/org/arbeitspferde/groningen/eventlog/SafeProtoLoggerFactory.java import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.google.inject.Inject; import com.google.inject.Provider; import com.google.inject.Singleton; import org.arbeitspferde.groningen.proto.Event; import org.arbeitspferde.groningen.utility.logstream.OutputLogStream; import org.arbeitspferde.groningen.utility.logstream.OutputLogStreamFactory; import org.arbeitspferde.groningen.utility.logstream.OutputLogStreamFactory.Specification; import java.io.IOException; import java.util.Timer; import java.util.TimerTask; import java.util.logging.Logger; /* Copyright 2012 Google, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.arbeitspferde.groningen.eventlog; /** * A producer of {@link SafeProtoLogger}. * * This class is rather trivial, but it exists to keep the complexity of {@link SafeProtoLogger}'s * constructor to a minimum. */ @Singleton public class SafeProtoLoggerFactory { private static final Logger log = Logger.getLogger(SafeProtoLogger.class.getCanonicalName()); private final Provider<Timer> timerProvider; private final OutputLogStreamFactory outputLogStreamFactory; /** * Create factory that produces safe protocol buffer loggers. * * @param timerProvider The {@link Provider} or {@link Timer} for testability. */ @Inject SafeProtoLoggerFactory(final Provider<Timer> timerProvider, final OutputLogStreamFactory outputLogStreamFactory) { this.timerProvider = timerProvider; this.outputLogStreamFactory = outputLogStreamFactory; } /** * Create a new {@link SafeProtoLogger} of {@link Event.EventEntry}. * * @param basename See {@link Specification#getFilenamePrefix()}. * @param port See {@link Specification#getServingPort()}. * @param rotateSize See {@link Specification#rotateFileUponAtSizeBytes()}. * @param flushIntervalSeconds The interval in seconds between automatic log flush events. * @param loggerName The human-readable canonical name for the log. * * @return A {@link SafeProtoLogger} that meets the supra specifications. * * @throws IOException In the event that the RecordIO cannot be provisioned. */ public SafeProtoLogger<Event.EventEntry> newEventEntryLogger(final String basename, final int port, final long rotateSize, final int flushIntervalSeconds, final String loggerName) throws IOException { Preconditions.checkNotNull(basename, "basename may not be null."); Preconditions.checkArgument(port > 0, "port must be > 0."); Preconditions.checkArgument(rotateSize >= 0, "rotateSize must >= 0."); Preconditions.checkArgument(flushIntervalSeconds >= 0, "flushIntervalSeconds must >= 0."); Preconditions.checkNotNull(loggerName, "loggerName may not be null."); log.info(String.format("Creating RecordIO log around %s.", basename));
final OutputLogStream stream = outputLogStreamFactory.rotatingStreamForSpecification(
sladeware/groningen
src/test/java/org/arbeitspferde/groningen/eventlog/SafeProtoLoggerFactoryTest.java
// Path: src/main/java/org/arbeitspferde/groningen/utility/logstream/OutputLogStream.java // @NotThreadSafe // public interface OutputLogStream extends Flushable, Closeable { // public void write(final Message message) throws IOException; // } // // Path: src/main/java/org/arbeitspferde/groningen/utility/logstream/format/open/DelimitedFactory.java // @ThreadSafe // public class DelimitedFactory implements OutputLogStreamFactory { // @Override // public OutputLogStream forStream(final OutputStream stream) throws IOException { // return new Delimited(stream); // } // // @Override // public OutputLogStream rotatingStreamForSpecification(final Specification specification) // throws IOException { // final String baseName = String.format("%s.on_port_%s.log", // specification.getFilenamePrefix(), specification.getServingPort()); // final FileOutputStream outputStream = new FileOutputStream(baseName); // // return new Delimited(outputStream); // } // }
import java.io.IOException; import java.io.OutputStream; import java.util.Timer; import java.util.TimerTask; import java.util.logging.Logger; import com.google.inject.Provider; import org.arbeitspferde.groningen.Helper; import org.arbeitspferde.groningen.proto.Event; import org.arbeitspferde.groningen.utility.logstream.OutputLogStream; import org.arbeitspferde.groningen.utility.logstream.OutputLogStreamFactory; import org.arbeitspferde.groningen.utility.logstream.format.open.DelimitedFactory; import junit.framework.TestCase; import org.apache.commons.io.FileUtils; import org.easymock.EasyMock; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream;
/* Copyright 2012 Google, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.arbeitspferde.groningen.eventlog; /** * Tests for {@link SafeProtoLoggerFactory}. */ public class SafeProtoLoggerFactoryTest extends TestCase { private static final Logger log = Logger.getLogger(SafeProtoLoggerTest.class.getCanonicalName());
// Path: src/main/java/org/arbeitspferde/groningen/utility/logstream/OutputLogStream.java // @NotThreadSafe // public interface OutputLogStream extends Flushable, Closeable { // public void write(final Message message) throws IOException; // } // // Path: src/main/java/org/arbeitspferde/groningen/utility/logstream/format/open/DelimitedFactory.java // @ThreadSafe // public class DelimitedFactory implements OutputLogStreamFactory { // @Override // public OutputLogStream forStream(final OutputStream stream) throws IOException { // return new Delimited(stream); // } // // @Override // public OutputLogStream rotatingStreamForSpecification(final Specification specification) // throws IOException { // final String baseName = String.format("%s.on_port_%s.log", // specification.getFilenamePrefix(), specification.getServingPort()); // final FileOutputStream outputStream = new FileOutputStream(baseName); // // return new Delimited(outputStream); // } // } // Path: src/test/java/org/arbeitspferde/groningen/eventlog/SafeProtoLoggerFactoryTest.java import java.io.IOException; import java.io.OutputStream; import java.util.Timer; import java.util.TimerTask; import java.util.logging.Logger; import com.google.inject.Provider; import org.arbeitspferde.groningen.Helper; import org.arbeitspferde.groningen.proto.Event; import org.arbeitspferde.groningen.utility.logstream.OutputLogStream; import org.arbeitspferde.groningen.utility.logstream.OutputLogStreamFactory; import org.arbeitspferde.groningen.utility.logstream.format.open.DelimitedFactory; import junit.framework.TestCase; import org.apache.commons.io.FileUtils; import org.easymock.EasyMock; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; /* Copyright 2012 Google, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.arbeitspferde.groningen.eventlog; /** * Tests for {@link SafeProtoLoggerFactory}. */ public class SafeProtoLoggerFactoryTest extends TestCase { private static final Logger log = Logger.getLogger(SafeProtoLoggerTest.class.getCanonicalName());
private DelimitedFactory delimitedFactory;
sladeware/groningen
src/test/java/org/arbeitspferde/groningen/eventlog/SafeProtoLoggerFactoryTest.java
// Path: src/main/java/org/arbeitspferde/groningen/utility/logstream/OutputLogStream.java // @NotThreadSafe // public interface OutputLogStream extends Flushable, Closeable { // public void write(final Message message) throws IOException; // } // // Path: src/main/java/org/arbeitspferde/groningen/utility/logstream/format/open/DelimitedFactory.java // @ThreadSafe // public class DelimitedFactory implements OutputLogStreamFactory { // @Override // public OutputLogStream forStream(final OutputStream stream) throws IOException { // return new Delimited(stream); // } // // @Override // public OutputLogStream rotatingStreamForSpecification(final Specification specification) // throws IOException { // final String baseName = String.format("%s.on_port_%s.log", // specification.getFilenamePrefix(), specification.getServingPort()); // final FileOutputStream outputStream = new FileOutputStream(baseName); // // return new Delimited(outputStream); // } // }
import java.io.IOException; import java.io.OutputStream; import java.util.Timer; import java.util.TimerTask; import java.util.logging.Logger; import com.google.inject.Provider; import org.arbeitspferde.groningen.Helper; import org.arbeitspferde.groningen.proto.Event; import org.arbeitspferde.groningen.utility.logstream.OutputLogStream; import org.arbeitspferde.groningen.utility.logstream.OutputLogStreamFactory; import org.arbeitspferde.groningen.utility.logstream.format.open.DelimitedFactory; import junit.framework.TestCase; import org.apache.commons.io.FileUtils; import org.easymock.EasyMock; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream;
/* Copyright 2012 Google, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.arbeitspferde.groningen.eventlog; /** * Tests for {@link SafeProtoLoggerFactory}. */ public class SafeProtoLoggerFactoryTest extends TestCase { private static final Logger log = Logger.getLogger(SafeProtoLoggerTest.class.getCanonicalName()); private DelimitedFactory delimitedFactory; private SafeProtoLoggerFactory factory; private Provider<Timer> mockDaemonTimerProvider; private Timer mockTimer; private OutputLogStreamFactory fakeOutputLogStreamFactory; private File temporaryDirectory; private File temporaryLogFile; @SuppressWarnings("unchecked") @Override protected void setUp() throws Exception { super.setUp(); temporaryDirectory = Helper.getTestDirectory(); temporaryLogFile = File.createTempFile("log", "", temporaryDirectory); mockDaemonTimerProvider = EasyMock.createMock(Provider.class); mockTimer = EasyMock.createMock(Timer.class); delimitedFactory = new DelimitedFactory(); fakeOutputLogStreamFactory = new OutputLogStreamFactory() { @Override
// Path: src/main/java/org/arbeitspferde/groningen/utility/logstream/OutputLogStream.java // @NotThreadSafe // public interface OutputLogStream extends Flushable, Closeable { // public void write(final Message message) throws IOException; // } // // Path: src/main/java/org/arbeitspferde/groningen/utility/logstream/format/open/DelimitedFactory.java // @ThreadSafe // public class DelimitedFactory implements OutputLogStreamFactory { // @Override // public OutputLogStream forStream(final OutputStream stream) throws IOException { // return new Delimited(stream); // } // // @Override // public OutputLogStream rotatingStreamForSpecification(final Specification specification) // throws IOException { // final String baseName = String.format("%s.on_port_%s.log", // specification.getFilenamePrefix(), specification.getServingPort()); // final FileOutputStream outputStream = new FileOutputStream(baseName); // // return new Delimited(outputStream); // } // } // Path: src/test/java/org/arbeitspferde/groningen/eventlog/SafeProtoLoggerFactoryTest.java import java.io.IOException; import java.io.OutputStream; import java.util.Timer; import java.util.TimerTask; import java.util.logging.Logger; import com.google.inject.Provider; import org.arbeitspferde.groningen.Helper; import org.arbeitspferde.groningen.proto.Event; import org.arbeitspferde.groningen.utility.logstream.OutputLogStream; import org.arbeitspferde.groningen.utility.logstream.OutputLogStreamFactory; import org.arbeitspferde.groningen.utility.logstream.format.open.DelimitedFactory; import junit.framework.TestCase; import org.apache.commons.io.FileUtils; import org.easymock.EasyMock; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; /* Copyright 2012 Google, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.arbeitspferde.groningen.eventlog; /** * Tests for {@link SafeProtoLoggerFactory}. */ public class SafeProtoLoggerFactoryTest extends TestCase { private static final Logger log = Logger.getLogger(SafeProtoLoggerTest.class.getCanonicalName()); private DelimitedFactory delimitedFactory; private SafeProtoLoggerFactory factory; private Provider<Timer> mockDaemonTimerProvider; private Timer mockTimer; private OutputLogStreamFactory fakeOutputLogStreamFactory; private File temporaryDirectory; private File temporaryLogFile; @SuppressWarnings("unchecked") @Override protected void setUp() throws Exception { super.setUp(); temporaryDirectory = Helper.getTestDirectory(); temporaryLogFile = File.createTempFile("log", "", temporaryDirectory); mockDaemonTimerProvider = EasyMock.createMock(Provider.class); mockTimer = EasyMock.createMock(Timer.class); delimitedFactory = new DelimitedFactory(); fakeOutputLogStreamFactory = new OutputLogStreamFactory() { @Override
public OutputLogStream forStream(final OutputStream stream) throws IOException {
sladeware/groningen
src/main/java/org/arbeitspferde/groningen/PipelineRestorer.java
// Path: src/main/java/org/arbeitspferde/groningen/Datastore.java // class DatastoreException extends Exception { // public DatastoreException() { // super(); // } // // public DatastoreException(final String message) { // super(message); // } // // public DatastoreException(final Throwable cause) { // super(cause); // } // // public DatastoreException(final String message, final Throwable cause) { // super(message, cause); // } // } // // Path: src/main/java/org/arbeitspferde/groningen/config/DatastoreConfigManager.java // public class DatastoreConfigManager implements ConfigManager { // private final Datastore dataStore; // private final PipelineId pipelineId; // // public DatastoreConfigManager(Datastore dataStore, PipelineId pipelineId) { // this.dataStore = dataStore; // this.pipelineId = pipelineId; // } // // @Override // public void initialize() { // } // // @Override // public void shutdown() { // } // // @Override // public GroningenConfig queryConfig() { // List<PipelineState> states; // try { // states = dataStore.getPipelines(Lists.newArrayList(pipelineId)); // } catch (DatastoreException e) { // throw new RuntimeException(e); // } // // if (states.isEmpty()) { // throw new RuntimeException("No state found."); // } else { // return states.get(0).config(); // } // } // }
import com.google.inject.Inject; import com.google.inject.name.Named; import org.arbeitspferde.groningen.Datastore.DatastoreException; import org.arbeitspferde.groningen.config.DatastoreConfigManager; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger;
package org.arbeitspferde.groningen; /** * PipelineRestorer queries the datastore for the pipelines belonging to the current shard. Then it * starts them via {@link PipelineManager}. */ public class PipelineRestorer { private static final Logger log = Logger.getLogger(PipelineRestorer.class.getCanonicalName()); private final Integer shardIndex; private final Datastore dataStore; private final PipelineManager pipelineManager; private final PipelineIdGenerator pipelineIdGenerator; @Inject public PipelineRestorer(@Named("shardIndex") Integer shardIndex, Datastore dataStore, PipelineManager pipelineManager, PipelineIdGenerator pipelineIdGenerator) { this.shardIndex = shardIndex; this.dataStore = dataStore; this.pipelineManager = pipelineManager; this.pipelineIdGenerator = pipelineIdGenerator; } public void restorePipelines() { List<PipelineId> currentShardIds = new ArrayList<>(); List<PipelineId> allPipelinesIds; try { allPipelinesIds = dataStore.listPipelinesIds();
// Path: src/main/java/org/arbeitspferde/groningen/Datastore.java // class DatastoreException extends Exception { // public DatastoreException() { // super(); // } // // public DatastoreException(final String message) { // super(message); // } // // public DatastoreException(final Throwable cause) { // super(cause); // } // // public DatastoreException(final String message, final Throwable cause) { // super(message, cause); // } // } // // Path: src/main/java/org/arbeitspferde/groningen/config/DatastoreConfigManager.java // public class DatastoreConfigManager implements ConfigManager { // private final Datastore dataStore; // private final PipelineId pipelineId; // // public DatastoreConfigManager(Datastore dataStore, PipelineId pipelineId) { // this.dataStore = dataStore; // this.pipelineId = pipelineId; // } // // @Override // public void initialize() { // } // // @Override // public void shutdown() { // } // // @Override // public GroningenConfig queryConfig() { // List<PipelineState> states; // try { // states = dataStore.getPipelines(Lists.newArrayList(pipelineId)); // } catch (DatastoreException e) { // throw new RuntimeException(e); // } // // if (states.isEmpty()) { // throw new RuntimeException("No state found."); // } else { // return states.get(0).config(); // } // } // } // Path: src/main/java/org/arbeitspferde/groningen/PipelineRestorer.java import com.google.inject.Inject; import com.google.inject.name.Named; import org.arbeitspferde.groningen.Datastore.DatastoreException; import org.arbeitspferde.groningen.config.DatastoreConfigManager; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; package org.arbeitspferde.groningen; /** * PipelineRestorer queries the datastore for the pipelines belonging to the current shard. Then it * starts them via {@link PipelineManager}. */ public class PipelineRestorer { private static final Logger log = Logger.getLogger(PipelineRestorer.class.getCanonicalName()); private final Integer shardIndex; private final Datastore dataStore; private final PipelineManager pipelineManager; private final PipelineIdGenerator pipelineIdGenerator; @Inject public PipelineRestorer(@Named("shardIndex") Integer shardIndex, Datastore dataStore, PipelineManager pipelineManager, PipelineIdGenerator pipelineIdGenerator) { this.shardIndex = shardIndex; this.dataStore = dataStore; this.pipelineManager = pipelineManager; this.pipelineIdGenerator = pipelineIdGenerator; } public void restorePipelines() { List<PipelineId> currentShardIds = new ArrayList<>(); List<PipelineId> allPipelinesIds; try { allPipelinesIds = dataStore.listPipelinesIds();
} catch (DatastoreException e) {
sladeware/groningen
src/main/java/org/arbeitspferde/groningen/PipelineRestorer.java
// Path: src/main/java/org/arbeitspferde/groningen/Datastore.java // class DatastoreException extends Exception { // public DatastoreException() { // super(); // } // // public DatastoreException(final String message) { // super(message); // } // // public DatastoreException(final Throwable cause) { // super(cause); // } // // public DatastoreException(final String message, final Throwable cause) { // super(message, cause); // } // } // // Path: src/main/java/org/arbeitspferde/groningen/config/DatastoreConfigManager.java // public class DatastoreConfigManager implements ConfigManager { // private final Datastore dataStore; // private final PipelineId pipelineId; // // public DatastoreConfigManager(Datastore dataStore, PipelineId pipelineId) { // this.dataStore = dataStore; // this.pipelineId = pipelineId; // } // // @Override // public void initialize() { // } // // @Override // public void shutdown() { // } // // @Override // public GroningenConfig queryConfig() { // List<PipelineState> states; // try { // states = dataStore.getPipelines(Lists.newArrayList(pipelineId)); // } catch (DatastoreException e) { // throw new RuntimeException(e); // } // // if (states.isEmpty()) { // throw new RuntimeException("No state found."); // } else { // return states.get(0).config(); // } // } // }
import com.google.inject.Inject; import com.google.inject.name.Named; import org.arbeitspferde.groningen.Datastore.DatastoreException; import org.arbeitspferde.groningen.config.DatastoreConfigManager; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger;
} public void restorePipelines() { List<PipelineId> currentShardIds = new ArrayList<>(); List<PipelineId> allPipelinesIds; try { allPipelinesIds = dataStore.listPipelinesIds(); } catch (DatastoreException e) { log.log(Level.SEVERE, "can't list pipelines in datastore: " + e.getMessage(), e); throw new RuntimeException(e); } for (PipelineId id : allPipelinesIds) { if (pipelineIdGenerator.shardIndexForPipelineId(id) == shardIndex) { currentShardIds.add(id); } } log.info(String.format("%d out of %d stored pipelines belong to me (shard %d).", currentShardIds.size(), allPipelinesIds.size(), shardIndex)); List<PipelineState> states; try { states = dataStore.getPipelines(currentShardIds); } catch (DatastoreException e) { log.log(Level.SEVERE, "can't get pipelines in datastore: " + e.getMessage(), e); throw new RuntimeException(e); } for (PipelineState state : states) { pipelineManager.restorePipeline(state,
// Path: src/main/java/org/arbeitspferde/groningen/Datastore.java // class DatastoreException extends Exception { // public DatastoreException() { // super(); // } // // public DatastoreException(final String message) { // super(message); // } // // public DatastoreException(final Throwable cause) { // super(cause); // } // // public DatastoreException(final String message, final Throwable cause) { // super(message, cause); // } // } // // Path: src/main/java/org/arbeitspferde/groningen/config/DatastoreConfigManager.java // public class DatastoreConfigManager implements ConfigManager { // private final Datastore dataStore; // private final PipelineId pipelineId; // // public DatastoreConfigManager(Datastore dataStore, PipelineId pipelineId) { // this.dataStore = dataStore; // this.pipelineId = pipelineId; // } // // @Override // public void initialize() { // } // // @Override // public void shutdown() { // } // // @Override // public GroningenConfig queryConfig() { // List<PipelineState> states; // try { // states = dataStore.getPipelines(Lists.newArrayList(pipelineId)); // } catch (DatastoreException e) { // throw new RuntimeException(e); // } // // if (states.isEmpty()) { // throw new RuntimeException("No state found."); // } else { // return states.get(0).config(); // } // } // } // Path: src/main/java/org/arbeitspferde/groningen/PipelineRestorer.java import com.google.inject.Inject; import com.google.inject.name.Named; import org.arbeitspferde.groningen.Datastore.DatastoreException; import org.arbeitspferde.groningen.config.DatastoreConfigManager; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; } public void restorePipelines() { List<PipelineId> currentShardIds = new ArrayList<>(); List<PipelineId> allPipelinesIds; try { allPipelinesIds = dataStore.listPipelinesIds(); } catch (DatastoreException e) { log.log(Level.SEVERE, "can't list pipelines in datastore: " + e.getMessage(), e); throw new RuntimeException(e); } for (PipelineId id : allPipelinesIds) { if (pipelineIdGenerator.shardIndexForPipelineId(id) == shardIndex) { currentShardIds.add(id); } } log.info(String.format("%d out of %d stored pipelines belong to me (shard %d).", currentShardIds.size(), allPipelinesIds.size(), shardIndex)); List<PipelineState> states; try { states = dataStore.getPipelines(currentShardIds); } catch (DatastoreException e) { log.log(Level.SEVERE, "can't get pipelines in datastore: " + e.getMessage(), e); throw new RuntimeException(e); } for (PipelineState state : states) { pipelineManager.restorePipeline(state,
new DatastoreConfigManager(dataStore, state.pipelineId()), false);
sitepoint/Editize
src/com/editize/editorkit/UndoAction.java
// Path: src/com/editize/editorkit/EditizeEditorKit.java // public static class NotifyingUndoManager extends CompoundingUndoManager { // private PropertyChangeSupport pcs; // private boolean active = true; // /** // * NotifyingUndoManager constructor comment. // */ // public NotifyingUndoManager() { // super(); // pcs = new PropertyChangeSupport(this); // } // public void addPropertyChangeListener(PropertyChangeListener l) { // pcs.addPropertyChangeListener(l); // } // /** // * Insert the method's description here. // * Creation date: (28/08/2001 11:43:19 PM) // */ // public void discardAllEdits() { // boolean oldCanUndo = canUndo(); // boolean oldCanRedo = canRedo(); // String oldUndoPresentationName = getUndoPresentationName(); // String oldRedoPresentationName = getRedoPresentationName(); // super.discardAllEdits(); // pcs.firePropertyChange("canUndo",oldCanUndo,canUndo()); // pcs.firePropertyChange("canRedo",oldCanRedo,canRedo()); // pcs.firePropertyChange("undoPresentationName",oldUndoPresentationName,getUndoPresentationName()); // pcs.firePropertyChange("redoPresentationName",oldRedoPresentationName,getRedoPresentationName()); // } // /** // * Insert the method's description here. // * Creation date: (28/08/2001 11:43:19 PM) // */ // public void redo() throws CannotUndoException { // if (!active) return; // boolean oldCanUndo = canUndo(); // boolean oldCanRedo = canRedo(); // String oldUndoPresentationName = getUndoPresentationName(); // String oldRedoPresentationName = getRedoPresentationName(); // super.redo(); // pcs.firePropertyChange("canUndo",oldCanUndo,canUndo()); // pcs.firePropertyChange("canRedo",oldCanRedo,canRedo()); // pcs.firePropertyChange("undoPresentationName",oldUndoPresentationName,getUndoPresentationName()); // pcs.firePropertyChange("redoPresentationName",oldRedoPresentationName,getRedoPresentationName()); // } // public void removePropertyChangeListener(PropertyChangeListener l) { // pcs.removePropertyChangeListener(l); // } // public void undo() throws CannotUndoException { // if (!active) return; // boolean oldCanUndo = canUndo(); // boolean oldCanRedo = canRedo(); // String oldUndoPresentationName = getUndoPresentationName(); // String oldRedoPresentationName = getRedoPresentationName(); // super.undo(); // pcs.firePropertyChange("canUndo",oldCanUndo,canUndo()); // pcs.firePropertyChange("canRedo",oldCanRedo,canRedo()); // pcs.firePropertyChange("undoPresentationName",oldUndoPresentationName,getUndoPresentationName()); // pcs.firePropertyChange("redoPresentationName",oldRedoPresentationName,getRedoPresentationName()); // } // // public boolean addEdit(UndoableEdit e) { // if (!active) return false; // boolean ret; // boolean oldCanUndo = canUndo(); // boolean oldCanRedo = canRedo(); // String oldUndoPresentationName = getUndoPresentationName(); // String oldRedoPresentationName = getRedoPresentationName(); // ret = super.addEdit(e); // pcs.firePropertyChange("canUndo",oldCanUndo,canUndo()); // pcs.firePropertyChange("canRedo",oldCanRedo,canRedo()); // pcs.firePropertyChange("undoPresentationName",oldUndoPresentationName,getUndoPresentationName()); // pcs.firePropertyChange("redoPresentationName",oldRedoPresentationName,getRedoPresentationName()); // return ret; // } // // public void setActive(boolean active) // { // this.active = active; // if (!active) discardAllEdits(); // } // public boolean isActive() // { // return active; // } // }
import javax.swing.text.StyledEditorKit; import java.beans.PropertyChangeListener; import com.editize.editorkit.EditizeEditorKit.NotifyingUndoManager; import java.awt.event.ActionEvent; import java.beans.PropertyChangeEvent;
package com.editize.editorkit; public class UndoAction extends StyledEditorKit.StyledTextAction implements PropertyChangeListener { protected static final int UNDO = 1; protected static final int REDO = 2; private int type; private javax.swing.undo.UndoManager undoMan;
// Path: src/com/editize/editorkit/EditizeEditorKit.java // public static class NotifyingUndoManager extends CompoundingUndoManager { // private PropertyChangeSupport pcs; // private boolean active = true; // /** // * NotifyingUndoManager constructor comment. // */ // public NotifyingUndoManager() { // super(); // pcs = new PropertyChangeSupport(this); // } // public void addPropertyChangeListener(PropertyChangeListener l) { // pcs.addPropertyChangeListener(l); // } // /** // * Insert the method's description here. // * Creation date: (28/08/2001 11:43:19 PM) // */ // public void discardAllEdits() { // boolean oldCanUndo = canUndo(); // boolean oldCanRedo = canRedo(); // String oldUndoPresentationName = getUndoPresentationName(); // String oldRedoPresentationName = getRedoPresentationName(); // super.discardAllEdits(); // pcs.firePropertyChange("canUndo",oldCanUndo,canUndo()); // pcs.firePropertyChange("canRedo",oldCanRedo,canRedo()); // pcs.firePropertyChange("undoPresentationName",oldUndoPresentationName,getUndoPresentationName()); // pcs.firePropertyChange("redoPresentationName",oldRedoPresentationName,getRedoPresentationName()); // } // /** // * Insert the method's description here. // * Creation date: (28/08/2001 11:43:19 PM) // */ // public void redo() throws CannotUndoException { // if (!active) return; // boolean oldCanUndo = canUndo(); // boolean oldCanRedo = canRedo(); // String oldUndoPresentationName = getUndoPresentationName(); // String oldRedoPresentationName = getRedoPresentationName(); // super.redo(); // pcs.firePropertyChange("canUndo",oldCanUndo,canUndo()); // pcs.firePropertyChange("canRedo",oldCanRedo,canRedo()); // pcs.firePropertyChange("undoPresentationName",oldUndoPresentationName,getUndoPresentationName()); // pcs.firePropertyChange("redoPresentationName",oldRedoPresentationName,getRedoPresentationName()); // } // public void removePropertyChangeListener(PropertyChangeListener l) { // pcs.removePropertyChangeListener(l); // } // public void undo() throws CannotUndoException { // if (!active) return; // boolean oldCanUndo = canUndo(); // boolean oldCanRedo = canRedo(); // String oldUndoPresentationName = getUndoPresentationName(); // String oldRedoPresentationName = getRedoPresentationName(); // super.undo(); // pcs.firePropertyChange("canUndo",oldCanUndo,canUndo()); // pcs.firePropertyChange("canRedo",oldCanRedo,canRedo()); // pcs.firePropertyChange("undoPresentationName",oldUndoPresentationName,getUndoPresentationName()); // pcs.firePropertyChange("redoPresentationName",oldRedoPresentationName,getRedoPresentationName()); // } // // public boolean addEdit(UndoableEdit e) { // if (!active) return false; // boolean ret; // boolean oldCanUndo = canUndo(); // boolean oldCanRedo = canRedo(); // String oldUndoPresentationName = getUndoPresentationName(); // String oldRedoPresentationName = getRedoPresentationName(); // ret = super.addEdit(e); // pcs.firePropertyChange("canUndo",oldCanUndo,canUndo()); // pcs.firePropertyChange("canRedo",oldCanRedo,canRedo()); // pcs.firePropertyChange("undoPresentationName",oldUndoPresentationName,getUndoPresentationName()); // pcs.firePropertyChange("redoPresentationName",oldRedoPresentationName,getRedoPresentationName()); // return ret; // } // // public void setActive(boolean active) // { // this.active = active; // if (!active) discardAllEdits(); // } // public boolean isActive() // { // return active; // } // } // Path: src/com/editize/editorkit/UndoAction.java import javax.swing.text.StyledEditorKit; import java.beans.PropertyChangeListener; import com.editize.editorkit.EditizeEditorKit.NotifyingUndoManager; import java.awt.event.ActionEvent; import java.beans.PropertyChangeEvent; package com.editize.editorkit; public class UndoAction extends StyledEditorKit.StyledTextAction implements PropertyChangeListener { protected static final int UNDO = 1; protected static final int REDO = 2; private int type; private javax.swing.undo.UndoManager undoMan;
public UndoAction(int type, NotifyingUndoManager undoMan)
renaudcerrato/static-maps-api
library/src/main/java/com/mypopsy/maps/StaticMap.java
// Path: library/src/main/java/com/mypopsy/maps/internal/PolyLine.java // final public class PolyLine { // // private PolyLine() {} // // public static String encode(StaticMap.GeoPoint[] points) throws IllegalArgumentException { // StringBuilder sb = new StringBuilder(); // int prevLat = 0, prevLng = 0; // for (StaticMap.GeoPoint point: points) { // if(!point.hasCoordinates()) return null; // int lat = (int) (point.latitude()*1E5); // int lng = (int) (point.longitude()*1E5); // sb.append(encodeSigned(lat - prevLat)); // sb.append(encodeSigned(lng - prevLng)); // prevLat = lat; // prevLng = lng; // } // return sb.toString(); // } // // private static StringBuilder encodeSigned(int num) { // int sgn_num = num << 1; // if (num < 0) sgn_num = ~sgn_num; // return encode(sgn_num); // } // // private static StringBuilder encode(int num) { // StringBuilder buffer = new StringBuilder(); // while (num >= 0x20) { // int nextValue = (0x20 | (num & 0x1f)) + 63; // buffer.append((char) (nextValue)); // num >>= 5; // } // num += 63; // buffer.append((char) (num)); // return buffer; // } // } // // Path: library/src/main/java/com/mypopsy/maps/internal/UrlBuilder.java // public class UrlBuilder { // // private static final String UTF8 = "UTF-8"; // private final String url; // private StringBuilder query; // // public UrlBuilder(String url) { // this.url = url; // } // // public UrlBuilder appendQuery(String key, Object object) { // return appendQuery(key, object.toString()); // } // // public UrlBuilder appendQuery(String key, @Nullable String value) { // if(query == null) query = new StringBuilder(); // if(query.length() > 0) query.append('&'); // query.append(encode(key)); // if(value != null) query.append('=').append(encode(value)); // return this; // } // // @Override // public String toString() { // if(query == null || query.length() == 0) return url; // return url + '?' + query; // } // // static private String encode(String text) { // try { // return URLEncoder.encode(text, UTF8); // } catch (UnsupportedEncodingException e) { // throw new RuntimeException(e); // } // } // }
import com.mypopsy.maps.internal.PolyLine; import com.mypopsy.maps.internal.UrlBuilder; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Locale; import javax.annotation.Nonnull; import javax.annotation.Nullable; import static java.lang.Math.asin; import static java.lang.Math.atan2; import static java.lang.Math.cos; import static java.lang.Math.sin;
/** * Force http scheme * @return this instance */ public StaticMap http() { this.https = false; return this; } /** * Force https scheme (default) * @return this instance */ public StaticMap https() { this.https = true; return this; } /** * @see #https() * @return true if the current scheme is https */ public boolean isHttps() { return https; } @Override public String toString() {
// Path: library/src/main/java/com/mypopsy/maps/internal/PolyLine.java // final public class PolyLine { // // private PolyLine() {} // // public static String encode(StaticMap.GeoPoint[] points) throws IllegalArgumentException { // StringBuilder sb = new StringBuilder(); // int prevLat = 0, prevLng = 0; // for (StaticMap.GeoPoint point: points) { // if(!point.hasCoordinates()) return null; // int lat = (int) (point.latitude()*1E5); // int lng = (int) (point.longitude()*1E5); // sb.append(encodeSigned(lat - prevLat)); // sb.append(encodeSigned(lng - prevLng)); // prevLat = lat; // prevLng = lng; // } // return sb.toString(); // } // // private static StringBuilder encodeSigned(int num) { // int sgn_num = num << 1; // if (num < 0) sgn_num = ~sgn_num; // return encode(sgn_num); // } // // private static StringBuilder encode(int num) { // StringBuilder buffer = new StringBuilder(); // while (num >= 0x20) { // int nextValue = (0x20 | (num & 0x1f)) + 63; // buffer.append((char) (nextValue)); // num >>= 5; // } // num += 63; // buffer.append((char) (num)); // return buffer; // } // } // // Path: library/src/main/java/com/mypopsy/maps/internal/UrlBuilder.java // public class UrlBuilder { // // private static final String UTF8 = "UTF-8"; // private final String url; // private StringBuilder query; // // public UrlBuilder(String url) { // this.url = url; // } // // public UrlBuilder appendQuery(String key, Object object) { // return appendQuery(key, object.toString()); // } // // public UrlBuilder appendQuery(String key, @Nullable String value) { // if(query == null) query = new StringBuilder(); // if(query.length() > 0) query.append('&'); // query.append(encode(key)); // if(value != null) query.append('=').append(encode(value)); // return this; // } // // @Override // public String toString() { // if(query == null || query.length() == 0) return url; // return url + '?' + query; // } // // static private String encode(String text) { // try { // return URLEncoder.encode(text, UTF8); // } catch (UnsupportedEncodingException e) { // throw new RuntimeException(e); // } // } // } // Path: library/src/main/java/com/mypopsy/maps/StaticMap.java import com.mypopsy.maps.internal.PolyLine; import com.mypopsy.maps.internal.UrlBuilder; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Locale; import javax.annotation.Nonnull; import javax.annotation.Nullable; import static java.lang.Math.asin; import static java.lang.Math.atan2; import static java.lang.Math.cos; import static java.lang.Math.sin; /** * Force http scheme * @return this instance */ public StaticMap http() { this.https = false; return this; } /** * Force https scheme (default) * @return this instance */ public StaticMap https() { this.https = true; return this; } /** * @see #https() * @return true if the current scheme is https */ public boolean isHttps() { return https; } @Override public String toString() {
UrlBuilder builder = new UrlBuilder(https ? HTTPS : HTTP);
renaudcerrato/static-maps-api
library/src/main/java/com/mypopsy/maps/StaticMap.java
// Path: library/src/main/java/com/mypopsy/maps/internal/PolyLine.java // final public class PolyLine { // // private PolyLine() {} // // public static String encode(StaticMap.GeoPoint[] points) throws IllegalArgumentException { // StringBuilder sb = new StringBuilder(); // int prevLat = 0, prevLng = 0; // for (StaticMap.GeoPoint point: points) { // if(!point.hasCoordinates()) return null; // int lat = (int) (point.latitude()*1E5); // int lng = (int) (point.longitude()*1E5); // sb.append(encodeSigned(lat - prevLat)); // sb.append(encodeSigned(lng - prevLng)); // prevLat = lat; // prevLng = lng; // } // return sb.toString(); // } // // private static StringBuilder encodeSigned(int num) { // int sgn_num = num << 1; // if (num < 0) sgn_num = ~sgn_num; // return encode(sgn_num); // } // // private static StringBuilder encode(int num) { // StringBuilder buffer = new StringBuilder(); // while (num >= 0x20) { // int nextValue = (0x20 | (num & 0x1f)) + 63; // buffer.append((char) (nextValue)); // num >>= 5; // } // num += 63; // buffer.append((char) (num)); // return buffer; // } // } // // Path: library/src/main/java/com/mypopsy/maps/internal/UrlBuilder.java // public class UrlBuilder { // // private static final String UTF8 = "UTF-8"; // private final String url; // private StringBuilder query; // // public UrlBuilder(String url) { // this.url = url; // } // // public UrlBuilder appendQuery(String key, Object object) { // return appendQuery(key, object.toString()); // } // // public UrlBuilder appendQuery(String key, @Nullable String value) { // if(query == null) query = new StringBuilder(); // if(query.length() > 0) query.append('&'); // query.append(encode(key)); // if(value != null) query.append('=').append(encode(value)); // return this; // } // // @Override // public String toString() { // if(query == null || query.length() == 0) return url; // return url + '?' + query; // } // // static private String encode(String text) { // try { // return URLEncoder.encode(text, UTF8); // } catch (UnsupportedEncodingException e) { // throw new RuntimeException(e); // } // } // }
import com.mypopsy.maps.internal.PolyLine; import com.mypopsy.maps.internal.UrlBuilder; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Locale; import javax.annotation.Nonnull; import javax.annotation.Nullable; import static java.lang.Math.asin; import static java.lang.Math.atan2; import static java.lang.Math.cos; import static java.lang.Math.sin;
* If no size parameter is set, the marker will appear in its default (normal) size. * @see Size * @param size of the marker * @return this instance */ public Builder size(Size size) { this.size = size; return this; } public Style build() { return new Style(this); } } } } static public class Path { @Nullable public final Style style; public final GeoPoint[] points; public Path(@Nullable Style style, GeoPoint...points) { if(points == null || points.length == 0) throw new IllegalArgumentException("you must specify geopoints"); this.style = style; this.points = points; } @Override public String toString() {
// Path: library/src/main/java/com/mypopsy/maps/internal/PolyLine.java // final public class PolyLine { // // private PolyLine() {} // // public static String encode(StaticMap.GeoPoint[] points) throws IllegalArgumentException { // StringBuilder sb = new StringBuilder(); // int prevLat = 0, prevLng = 0; // for (StaticMap.GeoPoint point: points) { // if(!point.hasCoordinates()) return null; // int lat = (int) (point.latitude()*1E5); // int lng = (int) (point.longitude()*1E5); // sb.append(encodeSigned(lat - prevLat)); // sb.append(encodeSigned(lng - prevLng)); // prevLat = lat; // prevLng = lng; // } // return sb.toString(); // } // // private static StringBuilder encodeSigned(int num) { // int sgn_num = num << 1; // if (num < 0) sgn_num = ~sgn_num; // return encode(sgn_num); // } // // private static StringBuilder encode(int num) { // StringBuilder buffer = new StringBuilder(); // while (num >= 0x20) { // int nextValue = (0x20 | (num & 0x1f)) + 63; // buffer.append((char) (nextValue)); // num >>= 5; // } // num += 63; // buffer.append((char) (num)); // return buffer; // } // } // // Path: library/src/main/java/com/mypopsy/maps/internal/UrlBuilder.java // public class UrlBuilder { // // private static final String UTF8 = "UTF-8"; // private final String url; // private StringBuilder query; // // public UrlBuilder(String url) { // this.url = url; // } // // public UrlBuilder appendQuery(String key, Object object) { // return appendQuery(key, object.toString()); // } // // public UrlBuilder appendQuery(String key, @Nullable String value) { // if(query == null) query = new StringBuilder(); // if(query.length() > 0) query.append('&'); // query.append(encode(key)); // if(value != null) query.append('=').append(encode(value)); // return this; // } // // @Override // public String toString() { // if(query == null || query.length() == 0) return url; // return url + '?' + query; // } // // static private String encode(String text) { // try { // return URLEncoder.encode(text, UTF8); // } catch (UnsupportedEncodingException e) { // throw new RuntimeException(e); // } // } // } // Path: library/src/main/java/com/mypopsy/maps/StaticMap.java import com.mypopsy.maps.internal.PolyLine; import com.mypopsy.maps.internal.UrlBuilder; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Locale; import javax.annotation.Nonnull; import javax.annotation.Nullable; import static java.lang.Math.asin; import static java.lang.Math.atan2; import static java.lang.Math.cos; import static java.lang.Math.sin; * If no size parameter is set, the marker will appear in its default (normal) size. * @see Size * @param size of the marker * @return this instance */ public Builder size(Size size) { this.size = size; return this; } public Style build() { return new Style(this); } } } } static public class Path { @Nullable public final Style style; public final GeoPoint[] points; public Path(@Nullable Style style, GeoPoint...points) { if(points == null || points.length == 0) throw new IllegalArgumentException("you must specify geopoints"); this.style = style; this.points = points; } @Override public String toString() {
String path = PolyLine.encode(points);
nikkiii/java-webserver
src/org/nikki/http/fastcgi/FastCGIContentHandler.java
// Path: src/org/nikki/http/content/ContentHandler.java // public interface ContentHandler { // // /** // * Handle a request // * // * @param session // * The session which initiated the request // * @return The response, or null // */ // public void handleRequest(HttpSession session) throws HttpResponseException; // } // // Path: src/org/nikki/http/content/HttpResponseException.java // public class HttpResponseException extends Exception { // // /** // * The serial uid // */ // private static final long serialVersionUID = -548587047264963177L; // // /** // * The status // */ // private HttpResponseStatus status; // // /** // * Construct a new exception // * // * @param status // * The HTTP Status to return // */ // public HttpResponseException(HttpResponseStatus status) { // this.status = status; // } // // /** // * Get the status // * // * @return The HTTP Status // */ // public HttpResponseStatus getStatus() { // return status; // } // } // // Path: src/org/nikki/http/net/HttpSession.java // public class HttpSession { // // /** // * The server instance // */ // private HttpServer server; // // /** // * The Virtual Host this session is requesting by // */ // private VirtualHost virtualHost; // // /** // * The request object // */ // private HttpRequest request; // // /** // * The request's channel // */ // private Channel channel; // // /** // * Creates an HTTP Session. // */ // public HttpSession(HttpServer server) { // this.server = server; // } // // /** // * Get the channel // * // * @return The session's channel // */ // public Channel getChannel() { // return channel; // } // // /** // * Get the HTTP Request // * // * @return The request // */ // public HttpRequest getRequest() { // return request; // } // // /** // * Get the server this session belongs to // * // * @return The server // */ // public HttpServer getServer() { // return server; // } // // /** // * Handle the request // * // * @param ctx // * The ChannelHandlerContext of the connectino // * @param request // * The HTTP Request // */ // public void handleRequest(ChannelHandlerContext ctx, HttpRequest request) { // this.request = request; // this.channel = ctx.getChannel(); // // server.handleRequest(this); // } // // /** // * Sends the http response. // * // * @param res // * The http response. // */ // public void sendHttpResponse(HttpResponse res) { // sendHttpResponse(res, true); // } // // /** // * Sends an HTTP Response with a flag whether to close or keep alive // * // * @param res // * The response // * @param close // * The flag // */ // public void sendHttpResponse(HttpResponse res, boolean close) { // if (!res.containsHeader("Server")) { // res.setHeader("Server", HttpServer.SERVER_SOFTWARE + " " // + HttpServer.SERVER_VERSION); // } // ChannelFuture future = channel.write(res); // if (close) { // future.addListener(ChannelFutureListener.CLOSE); // } // } // // public void setVirtualHost(VirtualHost virtualHost) { // this.virtualHost = virtualHost; // } // // public VirtualHost getVirtualHost() { // return virtualHost; // } // }
import org.jboss.netty.handler.codec.http.HttpResponseStatus; import org.nikki.http.content.ContentHandler; import org.nikki.http.content.HttpResponseException; import org.nikki.http.net.HttpSession;
/** * JavaHttpd, the flexible Java webserver * Copyright (C) 2012 Nikki <nikki@nikkii.us> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.nikki.http.fastcgi; /** * A ContentHandler for FastCGI Requests * * @author Nikki * */ public class FastCGIContentHandler implements ContentHandler { /** * The FastCGI Module */ private FastCGIModule module; /** * Construct a new ContentHandler which is set to have the server ignore the * first response, since the handler will respond with the finished request * * @param module * The module */ public FastCGIContentHandler(FastCGIModule module) { this.module = module; } @Override
// Path: src/org/nikki/http/content/ContentHandler.java // public interface ContentHandler { // // /** // * Handle a request // * // * @param session // * The session which initiated the request // * @return The response, or null // */ // public void handleRequest(HttpSession session) throws HttpResponseException; // } // // Path: src/org/nikki/http/content/HttpResponseException.java // public class HttpResponseException extends Exception { // // /** // * The serial uid // */ // private static final long serialVersionUID = -548587047264963177L; // // /** // * The status // */ // private HttpResponseStatus status; // // /** // * Construct a new exception // * // * @param status // * The HTTP Status to return // */ // public HttpResponseException(HttpResponseStatus status) { // this.status = status; // } // // /** // * Get the status // * // * @return The HTTP Status // */ // public HttpResponseStatus getStatus() { // return status; // } // } // // Path: src/org/nikki/http/net/HttpSession.java // public class HttpSession { // // /** // * The server instance // */ // private HttpServer server; // // /** // * The Virtual Host this session is requesting by // */ // private VirtualHost virtualHost; // // /** // * The request object // */ // private HttpRequest request; // // /** // * The request's channel // */ // private Channel channel; // // /** // * Creates an HTTP Session. // */ // public HttpSession(HttpServer server) { // this.server = server; // } // // /** // * Get the channel // * // * @return The session's channel // */ // public Channel getChannel() { // return channel; // } // // /** // * Get the HTTP Request // * // * @return The request // */ // public HttpRequest getRequest() { // return request; // } // // /** // * Get the server this session belongs to // * // * @return The server // */ // public HttpServer getServer() { // return server; // } // // /** // * Handle the request // * // * @param ctx // * The ChannelHandlerContext of the connectino // * @param request // * The HTTP Request // */ // public void handleRequest(ChannelHandlerContext ctx, HttpRequest request) { // this.request = request; // this.channel = ctx.getChannel(); // // server.handleRequest(this); // } // // /** // * Sends the http response. // * // * @param res // * The http response. // */ // public void sendHttpResponse(HttpResponse res) { // sendHttpResponse(res, true); // } // // /** // * Sends an HTTP Response with a flag whether to close or keep alive // * // * @param res // * The response // * @param close // * The flag // */ // public void sendHttpResponse(HttpResponse res, boolean close) { // if (!res.containsHeader("Server")) { // res.setHeader("Server", HttpServer.SERVER_SOFTWARE + " " // + HttpServer.SERVER_VERSION); // } // ChannelFuture future = channel.write(res); // if (close) { // future.addListener(ChannelFutureListener.CLOSE); // } // } // // public void setVirtualHost(VirtualHost virtualHost) { // this.virtualHost = virtualHost; // } // // public VirtualHost getVirtualHost() { // return virtualHost; // } // } // Path: src/org/nikki/http/fastcgi/FastCGIContentHandler.java import org.jboss.netty.handler.codec.http.HttpResponseStatus; import org.nikki.http.content.ContentHandler; import org.nikki.http.content.HttpResponseException; import org.nikki.http.net.HttpSession; /** * JavaHttpd, the flexible Java webserver * Copyright (C) 2012 Nikki <nikki@nikkii.us> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.nikki.http.fastcgi; /** * A ContentHandler for FastCGI Requests * * @author Nikki * */ public class FastCGIContentHandler implements ContentHandler { /** * The FastCGI Module */ private FastCGIModule module; /** * Construct a new ContentHandler which is set to have the server ignore the * first response, since the handler will respond with the finished request * * @param module * The module */ public FastCGIContentHandler(FastCGIModule module) { this.module = module; } @Override
public void handleRequest(HttpSession session) throws HttpResponseException {
nikkiii/java-webserver
src/org/nikki/http/fastcgi/FastCGIContentHandler.java
// Path: src/org/nikki/http/content/ContentHandler.java // public interface ContentHandler { // // /** // * Handle a request // * // * @param session // * The session which initiated the request // * @return The response, or null // */ // public void handleRequest(HttpSession session) throws HttpResponseException; // } // // Path: src/org/nikki/http/content/HttpResponseException.java // public class HttpResponseException extends Exception { // // /** // * The serial uid // */ // private static final long serialVersionUID = -548587047264963177L; // // /** // * The status // */ // private HttpResponseStatus status; // // /** // * Construct a new exception // * // * @param status // * The HTTP Status to return // */ // public HttpResponseException(HttpResponseStatus status) { // this.status = status; // } // // /** // * Get the status // * // * @return The HTTP Status // */ // public HttpResponseStatus getStatus() { // return status; // } // } // // Path: src/org/nikki/http/net/HttpSession.java // public class HttpSession { // // /** // * The server instance // */ // private HttpServer server; // // /** // * The Virtual Host this session is requesting by // */ // private VirtualHost virtualHost; // // /** // * The request object // */ // private HttpRequest request; // // /** // * The request's channel // */ // private Channel channel; // // /** // * Creates an HTTP Session. // */ // public HttpSession(HttpServer server) { // this.server = server; // } // // /** // * Get the channel // * // * @return The session's channel // */ // public Channel getChannel() { // return channel; // } // // /** // * Get the HTTP Request // * // * @return The request // */ // public HttpRequest getRequest() { // return request; // } // // /** // * Get the server this session belongs to // * // * @return The server // */ // public HttpServer getServer() { // return server; // } // // /** // * Handle the request // * // * @param ctx // * The ChannelHandlerContext of the connectino // * @param request // * The HTTP Request // */ // public void handleRequest(ChannelHandlerContext ctx, HttpRequest request) { // this.request = request; // this.channel = ctx.getChannel(); // // server.handleRequest(this); // } // // /** // * Sends the http response. // * // * @param res // * The http response. // */ // public void sendHttpResponse(HttpResponse res) { // sendHttpResponse(res, true); // } // // /** // * Sends an HTTP Response with a flag whether to close or keep alive // * // * @param res // * The response // * @param close // * The flag // */ // public void sendHttpResponse(HttpResponse res, boolean close) { // if (!res.containsHeader("Server")) { // res.setHeader("Server", HttpServer.SERVER_SOFTWARE + " " // + HttpServer.SERVER_VERSION); // } // ChannelFuture future = channel.write(res); // if (close) { // future.addListener(ChannelFutureListener.CLOSE); // } // } // // public void setVirtualHost(VirtualHost virtualHost) { // this.virtualHost = virtualHost; // } // // public VirtualHost getVirtualHost() { // return virtualHost; // } // }
import org.jboss.netty.handler.codec.http.HttpResponseStatus; import org.nikki.http.content.ContentHandler; import org.nikki.http.content.HttpResponseException; import org.nikki.http.net.HttpSession;
/** * JavaHttpd, the flexible Java webserver * Copyright (C) 2012 Nikki <nikki@nikkii.us> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.nikki.http.fastcgi; /** * A ContentHandler for FastCGI Requests * * @author Nikki * */ public class FastCGIContentHandler implements ContentHandler { /** * The FastCGI Module */ private FastCGIModule module; /** * Construct a new ContentHandler which is set to have the server ignore the * first response, since the handler will respond with the finished request * * @param module * The module */ public FastCGIContentHandler(FastCGIModule module) { this.module = module; } @Override
// Path: src/org/nikki/http/content/ContentHandler.java // public interface ContentHandler { // // /** // * Handle a request // * // * @param session // * The session which initiated the request // * @return The response, or null // */ // public void handleRequest(HttpSession session) throws HttpResponseException; // } // // Path: src/org/nikki/http/content/HttpResponseException.java // public class HttpResponseException extends Exception { // // /** // * The serial uid // */ // private static final long serialVersionUID = -548587047264963177L; // // /** // * The status // */ // private HttpResponseStatus status; // // /** // * Construct a new exception // * // * @param status // * The HTTP Status to return // */ // public HttpResponseException(HttpResponseStatus status) { // this.status = status; // } // // /** // * Get the status // * // * @return The HTTP Status // */ // public HttpResponseStatus getStatus() { // return status; // } // } // // Path: src/org/nikki/http/net/HttpSession.java // public class HttpSession { // // /** // * The server instance // */ // private HttpServer server; // // /** // * The Virtual Host this session is requesting by // */ // private VirtualHost virtualHost; // // /** // * The request object // */ // private HttpRequest request; // // /** // * The request's channel // */ // private Channel channel; // // /** // * Creates an HTTP Session. // */ // public HttpSession(HttpServer server) { // this.server = server; // } // // /** // * Get the channel // * // * @return The session's channel // */ // public Channel getChannel() { // return channel; // } // // /** // * Get the HTTP Request // * // * @return The request // */ // public HttpRequest getRequest() { // return request; // } // // /** // * Get the server this session belongs to // * // * @return The server // */ // public HttpServer getServer() { // return server; // } // // /** // * Handle the request // * // * @param ctx // * The ChannelHandlerContext of the connectino // * @param request // * The HTTP Request // */ // public void handleRequest(ChannelHandlerContext ctx, HttpRequest request) { // this.request = request; // this.channel = ctx.getChannel(); // // server.handleRequest(this); // } // // /** // * Sends the http response. // * // * @param res // * The http response. // */ // public void sendHttpResponse(HttpResponse res) { // sendHttpResponse(res, true); // } // // /** // * Sends an HTTP Response with a flag whether to close or keep alive // * // * @param res // * The response // * @param close // * The flag // */ // public void sendHttpResponse(HttpResponse res, boolean close) { // if (!res.containsHeader("Server")) { // res.setHeader("Server", HttpServer.SERVER_SOFTWARE + " " // + HttpServer.SERVER_VERSION); // } // ChannelFuture future = channel.write(res); // if (close) { // future.addListener(ChannelFutureListener.CLOSE); // } // } // // public void setVirtualHost(VirtualHost virtualHost) { // this.virtualHost = virtualHost; // } // // public VirtualHost getVirtualHost() { // return virtualHost; // } // } // Path: src/org/nikki/http/fastcgi/FastCGIContentHandler.java import org.jboss.netty.handler.codec.http.HttpResponseStatus; import org.nikki.http.content.ContentHandler; import org.nikki.http.content.HttpResponseException; import org.nikki.http.net.HttpSession; /** * JavaHttpd, the flexible Java webserver * Copyright (C) 2012 Nikki <nikki@nikkii.us> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.nikki.http.fastcgi; /** * A ContentHandler for FastCGI Requests * * @author Nikki * */ public class FastCGIContentHandler implements ContentHandler { /** * The FastCGI Module */ private FastCGIModule module; /** * Construct a new ContentHandler which is set to have the server ignore the * first response, since the handler will respond with the finished request * * @param module * The module */ public FastCGIContentHandler(FastCGIModule module) { this.module = module; } @Override
public void handleRequest(HttpSession session) throws HttpResponseException {
nikkiii/java-webserver
src/org/nikki/http/scgi/SCGIModule.java
// Path: src/org/nikki/http/configuration/ConfigurationNode.java // public class ConfigurationNode { // // /** // * A map of the children of this node // */ // private Map<String, Object> children = new HashMap<String, Object>(); // // /** // * Get an Object value from the map // * // * @param key // * The key // * @return The value // */ // public Object get(String key) { // return children.get(key); // } // // /** // * Get a boolean value from this node // * // * @param key // * The key of the value // * @return The value, parsed as a boolean // */ // public boolean getBoolean(String key) { // return Boolean.parseBoolean(getString(key)); // } // // /** // * Get a list of the children // * // * @return The map // */ // public Map<String, Object> getChildren() { // return children; // } // // /** // * Get an integer value from this node // * // * @param key // * The key of the value // * @return The value, parsed as an integer // */ // public int getInteger(String key) { // return Integer.parseInt(getString(key)); // } // // /** // * Get a string value from this node // * // * @param string // * The key of the value // * @return The string, or null // */ // public String getString(String string) { // Object value = get(string); // if (value instanceof String) { // return (String) value; // } // return "null"; // } // // /** // * Check if the map contains a key // * // * @param key // * The key to check // * @return true, if found // */ // public boolean has(String key) { // return children.containsKey(key); // } // // /** // * List the sub values // * // * @return A list of all sub values // */ // public String listChildren() { // StringBuilder builder = new StringBuilder(); // builder.append("["); // for (Entry<String, Object> entry : children.entrySet()) { // builder.append(entry.getKey()).append(" => "); // if (entry.getValue() instanceof ConfigurationNode) { // builder.append(((ConfigurationNode) entry.getValue()) // .listChildren()); // } else { // builder.append(entry.getValue()); // } // builder.append(", "); // } // if (builder.length() > 2) { // builder.deleteCharAt(builder.length() - 1); // builder.deleteCharAt(builder.length() - 1); // } // builder.append("]"); // return builder.toString(); // } // // /** // * Get a sub-node for the specified name // * // * @param name // * The name // * @return The node // */ // public ConfigurationNode nodeFor(String name) { // if (children.containsKey(name)) { // Object value = children.get(name); // if (value.getClass() != this.getClass()) { // throw new ConfigurationException("Invalid node " + name + "!"); // } // return (ConfigurationNode) value; // } // return null; // } // // /** // * Set a value // * // * @param key // * The key // * @param value // * The value // */ // public void set(String key, Object value) { // children.put(key, value); // } // // public String toString() { // return listChildren(); // } // } // // Path: src/org/nikki/http/module/ContentModule.java // public abstract class ContentModule extends ServerModule { // // /** // * @see org.nikki.http.content.ContentManager.registerExtension(extension, // * handler) // */ // public void registerExtension(String extension, ContentHandler handler) { // server.getContentManager().registerExtension(extension, handler); // } // } // // Path: src/org/nikki/http/module/ModuleLoadingException.java // public class ModuleLoadingException extends Exception { // // private static final long serialVersionUID = 8722123881811102854L; // // public ModuleLoadingException(String string) { // super(string); // } // // public ModuleLoadingException(Throwable throwable) { // super(throwable); // } // }
import org.nikki.http.configuration.ConfigurationNode; import org.nikki.http.module.ContentModule; import org.nikki.http.module.ModuleLoadingException;
/** * JavaHttpd, the flexible Java webserver * Copyright (C) 2012 Nikki <nikki@nikkii.us> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.nikki.http.scgi; /** * A module for SCGI Interaction, will be finished eventually * * @author Nikki * */ public class SCGIModule extends ContentModule { @Override
// Path: src/org/nikki/http/configuration/ConfigurationNode.java // public class ConfigurationNode { // // /** // * A map of the children of this node // */ // private Map<String, Object> children = new HashMap<String, Object>(); // // /** // * Get an Object value from the map // * // * @param key // * The key // * @return The value // */ // public Object get(String key) { // return children.get(key); // } // // /** // * Get a boolean value from this node // * // * @param key // * The key of the value // * @return The value, parsed as a boolean // */ // public boolean getBoolean(String key) { // return Boolean.parseBoolean(getString(key)); // } // // /** // * Get a list of the children // * // * @return The map // */ // public Map<String, Object> getChildren() { // return children; // } // // /** // * Get an integer value from this node // * // * @param key // * The key of the value // * @return The value, parsed as an integer // */ // public int getInteger(String key) { // return Integer.parseInt(getString(key)); // } // // /** // * Get a string value from this node // * // * @param string // * The key of the value // * @return The string, or null // */ // public String getString(String string) { // Object value = get(string); // if (value instanceof String) { // return (String) value; // } // return "null"; // } // // /** // * Check if the map contains a key // * // * @param key // * The key to check // * @return true, if found // */ // public boolean has(String key) { // return children.containsKey(key); // } // // /** // * List the sub values // * // * @return A list of all sub values // */ // public String listChildren() { // StringBuilder builder = new StringBuilder(); // builder.append("["); // for (Entry<String, Object> entry : children.entrySet()) { // builder.append(entry.getKey()).append(" => "); // if (entry.getValue() instanceof ConfigurationNode) { // builder.append(((ConfigurationNode) entry.getValue()) // .listChildren()); // } else { // builder.append(entry.getValue()); // } // builder.append(", "); // } // if (builder.length() > 2) { // builder.deleteCharAt(builder.length() - 1); // builder.deleteCharAt(builder.length() - 1); // } // builder.append("]"); // return builder.toString(); // } // // /** // * Get a sub-node for the specified name // * // * @param name // * The name // * @return The node // */ // public ConfigurationNode nodeFor(String name) { // if (children.containsKey(name)) { // Object value = children.get(name); // if (value.getClass() != this.getClass()) { // throw new ConfigurationException("Invalid node " + name + "!"); // } // return (ConfigurationNode) value; // } // return null; // } // // /** // * Set a value // * // * @param key // * The key // * @param value // * The value // */ // public void set(String key, Object value) { // children.put(key, value); // } // // public String toString() { // return listChildren(); // } // } // // Path: src/org/nikki/http/module/ContentModule.java // public abstract class ContentModule extends ServerModule { // // /** // * @see org.nikki.http.content.ContentManager.registerExtension(extension, // * handler) // */ // public void registerExtension(String extension, ContentHandler handler) { // server.getContentManager().registerExtension(extension, handler); // } // } // // Path: src/org/nikki/http/module/ModuleLoadingException.java // public class ModuleLoadingException extends Exception { // // private static final long serialVersionUID = 8722123881811102854L; // // public ModuleLoadingException(String string) { // super(string); // } // // public ModuleLoadingException(Throwable throwable) { // super(throwable); // } // } // Path: src/org/nikki/http/scgi/SCGIModule.java import org.nikki.http.configuration.ConfigurationNode; import org.nikki.http.module.ContentModule; import org.nikki.http.module.ModuleLoadingException; /** * JavaHttpd, the flexible Java webserver * Copyright (C) 2012 Nikki <nikki@nikkii.us> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.nikki.http.scgi; /** * A module for SCGI Interaction, will be finished eventually * * @author Nikki * */ public class SCGIModule extends ContentModule { @Override
public void onLoad(ConfigurationNode node) throws ModuleLoadingException {
nikkiii/java-webserver
src/org/nikki/http/scgi/SCGIModule.java
// Path: src/org/nikki/http/configuration/ConfigurationNode.java // public class ConfigurationNode { // // /** // * A map of the children of this node // */ // private Map<String, Object> children = new HashMap<String, Object>(); // // /** // * Get an Object value from the map // * // * @param key // * The key // * @return The value // */ // public Object get(String key) { // return children.get(key); // } // // /** // * Get a boolean value from this node // * // * @param key // * The key of the value // * @return The value, parsed as a boolean // */ // public boolean getBoolean(String key) { // return Boolean.parseBoolean(getString(key)); // } // // /** // * Get a list of the children // * // * @return The map // */ // public Map<String, Object> getChildren() { // return children; // } // // /** // * Get an integer value from this node // * // * @param key // * The key of the value // * @return The value, parsed as an integer // */ // public int getInteger(String key) { // return Integer.parseInt(getString(key)); // } // // /** // * Get a string value from this node // * // * @param string // * The key of the value // * @return The string, or null // */ // public String getString(String string) { // Object value = get(string); // if (value instanceof String) { // return (String) value; // } // return "null"; // } // // /** // * Check if the map contains a key // * // * @param key // * The key to check // * @return true, if found // */ // public boolean has(String key) { // return children.containsKey(key); // } // // /** // * List the sub values // * // * @return A list of all sub values // */ // public String listChildren() { // StringBuilder builder = new StringBuilder(); // builder.append("["); // for (Entry<String, Object> entry : children.entrySet()) { // builder.append(entry.getKey()).append(" => "); // if (entry.getValue() instanceof ConfigurationNode) { // builder.append(((ConfigurationNode) entry.getValue()) // .listChildren()); // } else { // builder.append(entry.getValue()); // } // builder.append(", "); // } // if (builder.length() > 2) { // builder.deleteCharAt(builder.length() - 1); // builder.deleteCharAt(builder.length() - 1); // } // builder.append("]"); // return builder.toString(); // } // // /** // * Get a sub-node for the specified name // * // * @param name // * The name // * @return The node // */ // public ConfigurationNode nodeFor(String name) { // if (children.containsKey(name)) { // Object value = children.get(name); // if (value.getClass() != this.getClass()) { // throw new ConfigurationException("Invalid node " + name + "!"); // } // return (ConfigurationNode) value; // } // return null; // } // // /** // * Set a value // * // * @param key // * The key // * @param value // * The value // */ // public void set(String key, Object value) { // children.put(key, value); // } // // public String toString() { // return listChildren(); // } // } // // Path: src/org/nikki/http/module/ContentModule.java // public abstract class ContentModule extends ServerModule { // // /** // * @see org.nikki.http.content.ContentManager.registerExtension(extension, // * handler) // */ // public void registerExtension(String extension, ContentHandler handler) { // server.getContentManager().registerExtension(extension, handler); // } // } // // Path: src/org/nikki/http/module/ModuleLoadingException.java // public class ModuleLoadingException extends Exception { // // private static final long serialVersionUID = 8722123881811102854L; // // public ModuleLoadingException(String string) { // super(string); // } // // public ModuleLoadingException(Throwable throwable) { // super(throwable); // } // }
import org.nikki.http.configuration.ConfigurationNode; import org.nikki.http.module.ContentModule; import org.nikki.http.module.ModuleLoadingException;
/** * JavaHttpd, the flexible Java webserver * Copyright (C) 2012 Nikki <nikki@nikkii.us> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.nikki.http.scgi; /** * A module for SCGI Interaction, will be finished eventually * * @author Nikki * */ public class SCGIModule extends ContentModule { @Override
// Path: src/org/nikki/http/configuration/ConfigurationNode.java // public class ConfigurationNode { // // /** // * A map of the children of this node // */ // private Map<String, Object> children = new HashMap<String, Object>(); // // /** // * Get an Object value from the map // * // * @param key // * The key // * @return The value // */ // public Object get(String key) { // return children.get(key); // } // // /** // * Get a boolean value from this node // * // * @param key // * The key of the value // * @return The value, parsed as a boolean // */ // public boolean getBoolean(String key) { // return Boolean.parseBoolean(getString(key)); // } // // /** // * Get a list of the children // * // * @return The map // */ // public Map<String, Object> getChildren() { // return children; // } // // /** // * Get an integer value from this node // * // * @param key // * The key of the value // * @return The value, parsed as an integer // */ // public int getInteger(String key) { // return Integer.parseInt(getString(key)); // } // // /** // * Get a string value from this node // * // * @param string // * The key of the value // * @return The string, or null // */ // public String getString(String string) { // Object value = get(string); // if (value instanceof String) { // return (String) value; // } // return "null"; // } // // /** // * Check if the map contains a key // * // * @param key // * The key to check // * @return true, if found // */ // public boolean has(String key) { // return children.containsKey(key); // } // // /** // * List the sub values // * // * @return A list of all sub values // */ // public String listChildren() { // StringBuilder builder = new StringBuilder(); // builder.append("["); // for (Entry<String, Object> entry : children.entrySet()) { // builder.append(entry.getKey()).append(" => "); // if (entry.getValue() instanceof ConfigurationNode) { // builder.append(((ConfigurationNode) entry.getValue()) // .listChildren()); // } else { // builder.append(entry.getValue()); // } // builder.append(", "); // } // if (builder.length() > 2) { // builder.deleteCharAt(builder.length() - 1); // builder.deleteCharAt(builder.length() - 1); // } // builder.append("]"); // return builder.toString(); // } // // /** // * Get a sub-node for the specified name // * // * @param name // * The name // * @return The node // */ // public ConfigurationNode nodeFor(String name) { // if (children.containsKey(name)) { // Object value = children.get(name); // if (value.getClass() != this.getClass()) { // throw new ConfigurationException("Invalid node " + name + "!"); // } // return (ConfigurationNode) value; // } // return null; // } // // /** // * Set a value // * // * @param key // * The key // * @param value // * The value // */ // public void set(String key, Object value) { // children.put(key, value); // } // // public String toString() { // return listChildren(); // } // } // // Path: src/org/nikki/http/module/ContentModule.java // public abstract class ContentModule extends ServerModule { // // /** // * @see org.nikki.http.content.ContentManager.registerExtension(extension, // * handler) // */ // public void registerExtension(String extension, ContentHandler handler) { // server.getContentManager().registerExtension(extension, handler); // } // } // // Path: src/org/nikki/http/module/ModuleLoadingException.java // public class ModuleLoadingException extends Exception { // // private static final long serialVersionUID = 8722123881811102854L; // // public ModuleLoadingException(String string) { // super(string); // } // // public ModuleLoadingException(Throwable throwable) { // super(throwable); // } // } // Path: src/org/nikki/http/scgi/SCGIModule.java import org.nikki.http.configuration.ConfigurationNode; import org.nikki.http.module.ContentModule; import org.nikki.http.module.ModuleLoadingException; /** * JavaHttpd, the flexible Java webserver * Copyright (C) 2012 Nikki <nikki@nikkii.us> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.nikki.http.scgi; /** * A module for SCGI Interaction, will be finished eventually * * @author Nikki * */ public class SCGIModule extends ContentModule { @Override
public void onLoad(ConfigurationNode node) throws ModuleLoadingException {
nikkiii/java-webserver
src/org/nikki/http/fastcgi/net/FastCGIDecoder.java
// Path: src/org/nikki/http/fastcgi/FastCGIConstants.java // public static final int FCGI_END_REQUEST = 3; // // Path: src/org/nikki/http/fastcgi/FastCGIConstants.java // public static final int FCGI_REQUEST_COMPLETE = 0; // // Path: src/org/nikki/http/fastcgi/FastCGIConstants.java // public static final int FCGI_STDERR = 7; // // Path: src/org/nikki/http/fastcgi/FastCGIConstants.java // public static final int FCGI_STDOUT = 6; // // Path: src/org/nikki/http/fastcgi/FastCGIResponse.java // public class FastCGIResponse { // // /** // * The original request id // */ // private int id; // // /** // * The completed data of the request // */ // private ChannelBuffer data; // // /** // * Construct a new response // * // * @param id // * The request id // * @param data // * The response // */ // public FastCGIResponse(int id, ChannelBuffer data) { // this.id = id; // this.data = data; // } // // /** // * Get the data buffer // * // * @return The ChannelBuffer containing the response data // */ // public ChannelBuffer getData() { // return data; // } // // /** // * Get the request id // * // * @return The request id // */ // public int getId() { // return id; // } // }
import org.jboss.netty.handler.codec.replay.ReplayingDecoder; import org.nikki.http.fastcgi.FastCGIResponse; import static org.nikki.http.fastcgi.FastCGIConstants.FCGI_END_REQUEST; import static org.nikki.http.fastcgi.FastCGIConstants.FCGI_REQUEST_COMPLETE; import static org.nikki.http.fastcgi.FastCGIConstants.FCGI_STDERR; import static org.nikki.http.fastcgi.FastCGIConstants.FCGI_STDOUT; import java.util.HashMap; import java.util.logging.Logger; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelHandlerContext;
*/ private HashMap<Integer, ChannelBuffer> dataBuffers = new HashMap<Integer, ChannelBuffer>(); /** * Create a new FastCGIDecoder */ public FastCGIDecoder() { super(ResponseState.VERSION); } @Override protected Object decode(ChannelHandlerContext arg0, Channel arg1, ChannelBuffer buffer, ResponseState state) throws Exception { switch (state) { case VERSION: version = buffer.readByte(); checkpoint(ResponseState.HEADER); case HEADER: // The types are unsigned in the FCGI docs type = buffer.readByte() & 0xFF; id = buffer.readShort() & 0xFFFF; contentLength = buffer.readShort() & 0xFFFF; paddingLength = buffer.readByte() & 0xFFFF; buffer.readByte(); // Reserved byte... logger.finest("Read request header : type=" + type + ",id=" + id + ",contentLength=" + contentLength + ",paddingLength=" + paddingLength); checkpoint(ResponseState.CONTENT); case CONTENT: switch (type) {
// Path: src/org/nikki/http/fastcgi/FastCGIConstants.java // public static final int FCGI_END_REQUEST = 3; // // Path: src/org/nikki/http/fastcgi/FastCGIConstants.java // public static final int FCGI_REQUEST_COMPLETE = 0; // // Path: src/org/nikki/http/fastcgi/FastCGIConstants.java // public static final int FCGI_STDERR = 7; // // Path: src/org/nikki/http/fastcgi/FastCGIConstants.java // public static final int FCGI_STDOUT = 6; // // Path: src/org/nikki/http/fastcgi/FastCGIResponse.java // public class FastCGIResponse { // // /** // * The original request id // */ // private int id; // // /** // * The completed data of the request // */ // private ChannelBuffer data; // // /** // * Construct a new response // * // * @param id // * The request id // * @param data // * The response // */ // public FastCGIResponse(int id, ChannelBuffer data) { // this.id = id; // this.data = data; // } // // /** // * Get the data buffer // * // * @return The ChannelBuffer containing the response data // */ // public ChannelBuffer getData() { // return data; // } // // /** // * Get the request id // * // * @return The request id // */ // public int getId() { // return id; // } // } // Path: src/org/nikki/http/fastcgi/net/FastCGIDecoder.java import org.jboss.netty.handler.codec.replay.ReplayingDecoder; import org.nikki.http.fastcgi.FastCGIResponse; import static org.nikki.http.fastcgi.FastCGIConstants.FCGI_END_REQUEST; import static org.nikki.http.fastcgi.FastCGIConstants.FCGI_REQUEST_COMPLETE; import static org.nikki.http.fastcgi.FastCGIConstants.FCGI_STDERR; import static org.nikki.http.fastcgi.FastCGIConstants.FCGI_STDOUT; import java.util.HashMap; import java.util.logging.Logger; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelHandlerContext; */ private HashMap<Integer, ChannelBuffer> dataBuffers = new HashMap<Integer, ChannelBuffer>(); /** * Create a new FastCGIDecoder */ public FastCGIDecoder() { super(ResponseState.VERSION); } @Override protected Object decode(ChannelHandlerContext arg0, Channel arg1, ChannelBuffer buffer, ResponseState state) throws Exception { switch (state) { case VERSION: version = buffer.readByte(); checkpoint(ResponseState.HEADER); case HEADER: // The types are unsigned in the FCGI docs type = buffer.readByte() & 0xFF; id = buffer.readShort() & 0xFFFF; contentLength = buffer.readShort() & 0xFFFF; paddingLength = buffer.readByte() & 0xFFFF; buffer.readByte(); // Reserved byte... logger.finest("Read request header : type=" + type + ",id=" + id + ",contentLength=" + contentLength + ",paddingLength=" + paddingLength); checkpoint(ResponseState.CONTENT); case CONTENT: switch (type) {
case FCGI_END_REQUEST:
nikkiii/java-webserver
src/org/nikki/http/fastcgi/net/FastCGIDecoder.java
// Path: src/org/nikki/http/fastcgi/FastCGIConstants.java // public static final int FCGI_END_REQUEST = 3; // // Path: src/org/nikki/http/fastcgi/FastCGIConstants.java // public static final int FCGI_REQUEST_COMPLETE = 0; // // Path: src/org/nikki/http/fastcgi/FastCGIConstants.java // public static final int FCGI_STDERR = 7; // // Path: src/org/nikki/http/fastcgi/FastCGIConstants.java // public static final int FCGI_STDOUT = 6; // // Path: src/org/nikki/http/fastcgi/FastCGIResponse.java // public class FastCGIResponse { // // /** // * The original request id // */ // private int id; // // /** // * The completed data of the request // */ // private ChannelBuffer data; // // /** // * Construct a new response // * // * @param id // * The request id // * @param data // * The response // */ // public FastCGIResponse(int id, ChannelBuffer data) { // this.id = id; // this.data = data; // } // // /** // * Get the data buffer // * // * @return The ChannelBuffer containing the response data // */ // public ChannelBuffer getData() { // return data; // } // // /** // * Get the request id // * // * @return The request id // */ // public int getId() { // return id; // } // }
import org.jboss.netty.handler.codec.replay.ReplayingDecoder; import org.nikki.http.fastcgi.FastCGIResponse; import static org.nikki.http.fastcgi.FastCGIConstants.FCGI_END_REQUEST; import static org.nikki.http.fastcgi.FastCGIConstants.FCGI_REQUEST_COMPLETE; import static org.nikki.http.fastcgi.FastCGIConstants.FCGI_STDERR; import static org.nikki.http.fastcgi.FastCGIConstants.FCGI_STDOUT; import java.util.HashMap; import java.util.logging.Logger; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelHandlerContext;
} @Override protected Object decode(ChannelHandlerContext arg0, Channel arg1, ChannelBuffer buffer, ResponseState state) throws Exception { switch (state) { case VERSION: version = buffer.readByte(); checkpoint(ResponseState.HEADER); case HEADER: // The types are unsigned in the FCGI docs type = buffer.readByte() & 0xFF; id = buffer.readShort() & 0xFFFF; contentLength = buffer.readShort() & 0xFFFF; paddingLength = buffer.readByte() & 0xFFFF; buffer.readByte(); // Reserved byte... logger.finest("Read request header : type=" + type + ",id=" + id + ",contentLength=" + contentLength + ",paddingLength=" + paddingLength); checkpoint(ResponseState.CONTENT); case CONTENT: switch (type) { case FCGI_END_REQUEST: // Statuses, don't know what the correct use is, but // FCGI_REQUEST_COMPLETE is one, and there's another status // code... int appStatus = buffer.readInt(); int protocolStatus = buffer.readByte(); // Reserved bytes buffer.skipBytes(3);
// Path: src/org/nikki/http/fastcgi/FastCGIConstants.java // public static final int FCGI_END_REQUEST = 3; // // Path: src/org/nikki/http/fastcgi/FastCGIConstants.java // public static final int FCGI_REQUEST_COMPLETE = 0; // // Path: src/org/nikki/http/fastcgi/FastCGIConstants.java // public static final int FCGI_STDERR = 7; // // Path: src/org/nikki/http/fastcgi/FastCGIConstants.java // public static final int FCGI_STDOUT = 6; // // Path: src/org/nikki/http/fastcgi/FastCGIResponse.java // public class FastCGIResponse { // // /** // * The original request id // */ // private int id; // // /** // * The completed data of the request // */ // private ChannelBuffer data; // // /** // * Construct a new response // * // * @param id // * The request id // * @param data // * The response // */ // public FastCGIResponse(int id, ChannelBuffer data) { // this.id = id; // this.data = data; // } // // /** // * Get the data buffer // * // * @return The ChannelBuffer containing the response data // */ // public ChannelBuffer getData() { // return data; // } // // /** // * Get the request id // * // * @return The request id // */ // public int getId() { // return id; // } // } // Path: src/org/nikki/http/fastcgi/net/FastCGIDecoder.java import org.jboss.netty.handler.codec.replay.ReplayingDecoder; import org.nikki.http.fastcgi.FastCGIResponse; import static org.nikki.http.fastcgi.FastCGIConstants.FCGI_END_REQUEST; import static org.nikki.http.fastcgi.FastCGIConstants.FCGI_REQUEST_COMPLETE; import static org.nikki.http.fastcgi.FastCGIConstants.FCGI_STDERR; import static org.nikki.http.fastcgi.FastCGIConstants.FCGI_STDOUT; import java.util.HashMap; import java.util.logging.Logger; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelHandlerContext; } @Override protected Object decode(ChannelHandlerContext arg0, Channel arg1, ChannelBuffer buffer, ResponseState state) throws Exception { switch (state) { case VERSION: version = buffer.readByte(); checkpoint(ResponseState.HEADER); case HEADER: // The types are unsigned in the FCGI docs type = buffer.readByte() & 0xFF; id = buffer.readShort() & 0xFFFF; contentLength = buffer.readShort() & 0xFFFF; paddingLength = buffer.readByte() & 0xFFFF; buffer.readByte(); // Reserved byte... logger.finest("Read request header : type=" + type + ",id=" + id + ",contentLength=" + contentLength + ",paddingLength=" + paddingLength); checkpoint(ResponseState.CONTENT); case CONTENT: switch (type) { case FCGI_END_REQUEST: // Statuses, don't know what the correct use is, but // FCGI_REQUEST_COMPLETE is one, and there's another status // code... int appStatus = buffer.readInt(); int protocolStatus = buffer.readByte(); // Reserved bytes buffer.skipBytes(3);
if (appStatus != 0 || protocolStatus != FCGI_REQUEST_COMPLETE) {
nikkiii/java-webserver
src/org/nikki/http/fastcgi/net/FastCGIDecoder.java
// Path: src/org/nikki/http/fastcgi/FastCGIConstants.java // public static final int FCGI_END_REQUEST = 3; // // Path: src/org/nikki/http/fastcgi/FastCGIConstants.java // public static final int FCGI_REQUEST_COMPLETE = 0; // // Path: src/org/nikki/http/fastcgi/FastCGIConstants.java // public static final int FCGI_STDERR = 7; // // Path: src/org/nikki/http/fastcgi/FastCGIConstants.java // public static final int FCGI_STDOUT = 6; // // Path: src/org/nikki/http/fastcgi/FastCGIResponse.java // public class FastCGIResponse { // // /** // * The original request id // */ // private int id; // // /** // * The completed data of the request // */ // private ChannelBuffer data; // // /** // * Construct a new response // * // * @param id // * The request id // * @param data // * The response // */ // public FastCGIResponse(int id, ChannelBuffer data) { // this.id = id; // this.data = data; // } // // /** // * Get the data buffer // * // * @return The ChannelBuffer containing the response data // */ // public ChannelBuffer getData() { // return data; // } // // /** // * Get the request id // * // * @return The request id // */ // public int getId() { // return id; // } // }
import org.jboss.netty.handler.codec.replay.ReplayingDecoder; import org.nikki.http.fastcgi.FastCGIResponse; import static org.nikki.http.fastcgi.FastCGIConstants.FCGI_END_REQUEST; import static org.nikki.http.fastcgi.FastCGIConstants.FCGI_REQUEST_COMPLETE; import static org.nikki.http.fastcgi.FastCGIConstants.FCGI_STDERR; import static org.nikki.http.fastcgi.FastCGIConstants.FCGI_STDOUT; import java.util.HashMap; import java.util.logging.Logger; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelHandlerContext;
case HEADER: // The types are unsigned in the FCGI docs type = buffer.readByte() & 0xFF; id = buffer.readShort() & 0xFFFF; contentLength = buffer.readShort() & 0xFFFF; paddingLength = buffer.readByte() & 0xFFFF; buffer.readByte(); // Reserved byte... logger.finest("Read request header : type=" + type + ",id=" + id + ",contentLength=" + contentLength + ",paddingLength=" + paddingLength); checkpoint(ResponseState.CONTENT); case CONTENT: switch (type) { case FCGI_END_REQUEST: // Statuses, don't know what the correct use is, but // FCGI_REQUEST_COMPLETE is one, and there's another status // code... int appStatus = buffer.readInt(); int protocolStatus = buffer.readByte(); // Reserved bytes buffer.skipBytes(3); if (appStatus != 0 || protocolStatus != FCGI_REQUEST_COMPLETE) { // Uh oh, when we run a pool of connections we should close // this one here... logger.warning("Protocol status " + protocolStatus); } else if (protocolStatus == FCGI_REQUEST_COMPLETE) { // Reset the version checkpoint(ResponseState.VERSION); // Merged from ChannelBuffer buffer ... dataBuffers.remove // to this, remove() returns the object
// Path: src/org/nikki/http/fastcgi/FastCGIConstants.java // public static final int FCGI_END_REQUEST = 3; // // Path: src/org/nikki/http/fastcgi/FastCGIConstants.java // public static final int FCGI_REQUEST_COMPLETE = 0; // // Path: src/org/nikki/http/fastcgi/FastCGIConstants.java // public static final int FCGI_STDERR = 7; // // Path: src/org/nikki/http/fastcgi/FastCGIConstants.java // public static final int FCGI_STDOUT = 6; // // Path: src/org/nikki/http/fastcgi/FastCGIResponse.java // public class FastCGIResponse { // // /** // * The original request id // */ // private int id; // // /** // * The completed data of the request // */ // private ChannelBuffer data; // // /** // * Construct a new response // * // * @param id // * The request id // * @param data // * The response // */ // public FastCGIResponse(int id, ChannelBuffer data) { // this.id = id; // this.data = data; // } // // /** // * Get the data buffer // * // * @return The ChannelBuffer containing the response data // */ // public ChannelBuffer getData() { // return data; // } // // /** // * Get the request id // * // * @return The request id // */ // public int getId() { // return id; // } // } // Path: src/org/nikki/http/fastcgi/net/FastCGIDecoder.java import org.jboss.netty.handler.codec.replay.ReplayingDecoder; import org.nikki.http.fastcgi.FastCGIResponse; import static org.nikki.http.fastcgi.FastCGIConstants.FCGI_END_REQUEST; import static org.nikki.http.fastcgi.FastCGIConstants.FCGI_REQUEST_COMPLETE; import static org.nikki.http.fastcgi.FastCGIConstants.FCGI_STDERR; import static org.nikki.http.fastcgi.FastCGIConstants.FCGI_STDOUT; import java.util.HashMap; import java.util.logging.Logger; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelHandlerContext; case HEADER: // The types are unsigned in the FCGI docs type = buffer.readByte() & 0xFF; id = buffer.readShort() & 0xFFFF; contentLength = buffer.readShort() & 0xFFFF; paddingLength = buffer.readByte() & 0xFFFF; buffer.readByte(); // Reserved byte... logger.finest("Read request header : type=" + type + ",id=" + id + ",contentLength=" + contentLength + ",paddingLength=" + paddingLength); checkpoint(ResponseState.CONTENT); case CONTENT: switch (type) { case FCGI_END_REQUEST: // Statuses, don't know what the correct use is, but // FCGI_REQUEST_COMPLETE is one, and there's another status // code... int appStatus = buffer.readInt(); int protocolStatus = buffer.readByte(); // Reserved bytes buffer.skipBytes(3); if (appStatus != 0 || protocolStatus != FCGI_REQUEST_COMPLETE) { // Uh oh, when we run a pool of connections we should close // this one here... logger.warning("Protocol status " + protocolStatus); } else if (protocolStatus == FCGI_REQUEST_COMPLETE) { // Reset the version checkpoint(ResponseState.VERSION); // Merged from ChannelBuffer buffer ... dataBuffers.remove // to this, remove() returns the object
return new FastCGIResponse(id, dataBuffers.remove(id));
nikkiii/java-webserver
src/org/nikki/http/fastcgi/net/FastCGIDecoder.java
// Path: src/org/nikki/http/fastcgi/FastCGIConstants.java // public static final int FCGI_END_REQUEST = 3; // // Path: src/org/nikki/http/fastcgi/FastCGIConstants.java // public static final int FCGI_REQUEST_COMPLETE = 0; // // Path: src/org/nikki/http/fastcgi/FastCGIConstants.java // public static final int FCGI_STDERR = 7; // // Path: src/org/nikki/http/fastcgi/FastCGIConstants.java // public static final int FCGI_STDOUT = 6; // // Path: src/org/nikki/http/fastcgi/FastCGIResponse.java // public class FastCGIResponse { // // /** // * The original request id // */ // private int id; // // /** // * The completed data of the request // */ // private ChannelBuffer data; // // /** // * Construct a new response // * // * @param id // * The request id // * @param data // * The response // */ // public FastCGIResponse(int id, ChannelBuffer data) { // this.id = id; // this.data = data; // } // // /** // * Get the data buffer // * // * @return The ChannelBuffer containing the response data // */ // public ChannelBuffer getData() { // return data; // } // // /** // * Get the request id // * // * @return The request id // */ // public int getId() { // return id; // } // }
import org.jboss.netty.handler.codec.replay.ReplayingDecoder; import org.nikki.http.fastcgi.FastCGIResponse; import static org.nikki.http.fastcgi.FastCGIConstants.FCGI_END_REQUEST; import static org.nikki.http.fastcgi.FastCGIConstants.FCGI_REQUEST_COMPLETE; import static org.nikki.http.fastcgi.FastCGIConstants.FCGI_STDERR; import static org.nikki.http.fastcgi.FastCGIConstants.FCGI_STDOUT; import java.util.HashMap; import java.util.logging.Logger; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelHandlerContext;
contentLength = buffer.readShort() & 0xFFFF; paddingLength = buffer.readByte() & 0xFFFF; buffer.readByte(); // Reserved byte... logger.finest("Read request header : type=" + type + ",id=" + id + ",contentLength=" + contentLength + ",paddingLength=" + paddingLength); checkpoint(ResponseState.CONTENT); case CONTENT: switch (type) { case FCGI_END_REQUEST: // Statuses, don't know what the correct use is, but // FCGI_REQUEST_COMPLETE is one, and there's another status // code... int appStatus = buffer.readInt(); int protocolStatus = buffer.readByte(); // Reserved bytes buffer.skipBytes(3); if (appStatus != 0 || protocolStatus != FCGI_REQUEST_COMPLETE) { // Uh oh, when we run a pool of connections we should close // this one here... logger.warning("Protocol status " + protocolStatus); } else if (protocolStatus == FCGI_REQUEST_COMPLETE) { // Reset the version checkpoint(ResponseState.VERSION); // Merged from ChannelBuffer buffer ... dataBuffers.remove // to this, remove() returns the object return new FastCGIResponse(id, dataBuffers.remove(id)); } checkpoint(ResponseState.VERSION); break;
// Path: src/org/nikki/http/fastcgi/FastCGIConstants.java // public static final int FCGI_END_REQUEST = 3; // // Path: src/org/nikki/http/fastcgi/FastCGIConstants.java // public static final int FCGI_REQUEST_COMPLETE = 0; // // Path: src/org/nikki/http/fastcgi/FastCGIConstants.java // public static final int FCGI_STDERR = 7; // // Path: src/org/nikki/http/fastcgi/FastCGIConstants.java // public static final int FCGI_STDOUT = 6; // // Path: src/org/nikki/http/fastcgi/FastCGIResponse.java // public class FastCGIResponse { // // /** // * The original request id // */ // private int id; // // /** // * The completed data of the request // */ // private ChannelBuffer data; // // /** // * Construct a new response // * // * @param id // * The request id // * @param data // * The response // */ // public FastCGIResponse(int id, ChannelBuffer data) { // this.id = id; // this.data = data; // } // // /** // * Get the data buffer // * // * @return The ChannelBuffer containing the response data // */ // public ChannelBuffer getData() { // return data; // } // // /** // * Get the request id // * // * @return The request id // */ // public int getId() { // return id; // } // } // Path: src/org/nikki/http/fastcgi/net/FastCGIDecoder.java import org.jboss.netty.handler.codec.replay.ReplayingDecoder; import org.nikki.http.fastcgi.FastCGIResponse; import static org.nikki.http.fastcgi.FastCGIConstants.FCGI_END_REQUEST; import static org.nikki.http.fastcgi.FastCGIConstants.FCGI_REQUEST_COMPLETE; import static org.nikki.http.fastcgi.FastCGIConstants.FCGI_STDERR; import static org.nikki.http.fastcgi.FastCGIConstants.FCGI_STDOUT; import java.util.HashMap; import java.util.logging.Logger; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelHandlerContext; contentLength = buffer.readShort() & 0xFFFF; paddingLength = buffer.readByte() & 0xFFFF; buffer.readByte(); // Reserved byte... logger.finest("Read request header : type=" + type + ",id=" + id + ",contentLength=" + contentLength + ",paddingLength=" + paddingLength); checkpoint(ResponseState.CONTENT); case CONTENT: switch (type) { case FCGI_END_REQUEST: // Statuses, don't know what the correct use is, but // FCGI_REQUEST_COMPLETE is one, and there's another status // code... int appStatus = buffer.readInt(); int protocolStatus = buffer.readByte(); // Reserved bytes buffer.skipBytes(3); if (appStatus != 0 || protocolStatus != FCGI_REQUEST_COMPLETE) { // Uh oh, when we run a pool of connections we should close // this one here... logger.warning("Protocol status " + protocolStatus); } else if (protocolStatus == FCGI_REQUEST_COMPLETE) { // Reset the version checkpoint(ResponseState.VERSION); // Merged from ChannelBuffer buffer ... dataBuffers.remove // to this, remove() returns the object return new FastCGIResponse(id, dataBuffers.remove(id)); } checkpoint(ResponseState.VERSION); break;
case FCGI_STDOUT:
nikkiii/java-webserver
src/org/nikki/http/fastcgi/net/FastCGIDecoder.java
// Path: src/org/nikki/http/fastcgi/FastCGIConstants.java // public static final int FCGI_END_REQUEST = 3; // // Path: src/org/nikki/http/fastcgi/FastCGIConstants.java // public static final int FCGI_REQUEST_COMPLETE = 0; // // Path: src/org/nikki/http/fastcgi/FastCGIConstants.java // public static final int FCGI_STDERR = 7; // // Path: src/org/nikki/http/fastcgi/FastCGIConstants.java // public static final int FCGI_STDOUT = 6; // // Path: src/org/nikki/http/fastcgi/FastCGIResponse.java // public class FastCGIResponse { // // /** // * The original request id // */ // private int id; // // /** // * The completed data of the request // */ // private ChannelBuffer data; // // /** // * Construct a new response // * // * @param id // * The request id // * @param data // * The response // */ // public FastCGIResponse(int id, ChannelBuffer data) { // this.id = id; // this.data = data; // } // // /** // * Get the data buffer // * // * @return The ChannelBuffer containing the response data // */ // public ChannelBuffer getData() { // return data; // } // // /** // * Get the request id // * // * @return The request id // */ // public int getId() { // return id; // } // }
import org.jboss.netty.handler.codec.replay.ReplayingDecoder; import org.nikki.http.fastcgi.FastCGIResponse; import static org.nikki.http.fastcgi.FastCGIConstants.FCGI_END_REQUEST; import static org.nikki.http.fastcgi.FastCGIConstants.FCGI_REQUEST_COMPLETE; import static org.nikki.http.fastcgi.FastCGIConstants.FCGI_STDERR; import static org.nikki.http.fastcgi.FastCGIConstants.FCGI_STDOUT; import java.util.HashMap; import java.util.logging.Logger; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelHandlerContext;
if (appStatus != 0 || protocolStatus != FCGI_REQUEST_COMPLETE) { // Uh oh, when we run a pool of connections we should close // this one here... logger.warning("Protocol status " + protocolStatus); } else if (protocolStatus == FCGI_REQUEST_COMPLETE) { // Reset the version checkpoint(ResponseState.VERSION); // Merged from ChannelBuffer buffer ... dataBuffers.remove // to this, remove() returns the object return new FastCGIResponse(id, dataBuffers.remove(id)); } checkpoint(ResponseState.VERSION); break; case FCGI_STDOUT: if (contentLength > 0) { // Have to store it, just in case we get a new request if (!dataBuffers.containsKey(id)) { dataBuffers.put(id, ChannelBuffers.dynamicBuffer()); } logger.finest("Got " + contentLength + " bytes for request " + id); // Write the bytes to the buffer dataBuffers.get(id).writeBytes( buffer.readBytes(contentLength)); // Checkpoint! checkpoint(ResponseState.VERSION); } break; // solaroperator pointed out this never contains HTML, I forgot a // checkpoint so it stayed STDERR even with 0 bytes
// Path: src/org/nikki/http/fastcgi/FastCGIConstants.java // public static final int FCGI_END_REQUEST = 3; // // Path: src/org/nikki/http/fastcgi/FastCGIConstants.java // public static final int FCGI_REQUEST_COMPLETE = 0; // // Path: src/org/nikki/http/fastcgi/FastCGIConstants.java // public static final int FCGI_STDERR = 7; // // Path: src/org/nikki/http/fastcgi/FastCGIConstants.java // public static final int FCGI_STDOUT = 6; // // Path: src/org/nikki/http/fastcgi/FastCGIResponse.java // public class FastCGIResponse { // // /** // * The original request id // */ // private int id; // // /** // * The completed data of the request // */ // private ChannelBuffer data; // // /** // * Construct a new response // * // * @param id // * The request id // * @param data // * The response // */ // public FastCGIResponse(int id, ChannelBuffer data) { // this.id = id; // this.data = data; // } // // /** // * Get the data buffer // * // * @return The ChannelBuffer containing the response data // */ // public ChannelBuffer getData() { // return data; // } // // /** // * Get the request id // * // * @return The request id // */ // public int getId() { // return id; // } // } // Path: src/org/nikki/http/fastcgi/net/FastCGIDecoder.java import org.jboss.netty.handler.codec.replay.ReplayingDecoder; import org.nikki.http.fastcgi.FastCGIResponse; import static org.nikki.http.fastcgi.FastCGIConstants.FCGI_END_REQUEST; import static org.nikki.http.fastcgi.FastCGIConstants.FCGI_REQUEST_COMPLETE; import static org.nikki.http.fastcgi.FastCGIConstants.FCGI_STDERR; import static org.nikki.http.fastcgi.FastCGIConstants.FCGI_STDOUT; import java.util.HashMap; import java.util.logging.Logger; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelHandlerContext; if (appStatus != 0 || protocolStatus != FCGI_REQUEST_COMPLETE) { // Uh oh, when we run a pool of connections we should close // this one here... logger.warning("Protocol status " + protocolStatus); } else if (protocolStatus == FCGI_REQUEST_COMPLETE) { // Reset the version checkpoint(ResponseState.VERSION); // Merged from ChannelBuffer buffer ... dataBuffers.remove // to this, remove() returns the object return new FastCGIResponse(id, dataBuffers.remove(id)); } checkpoint(ResponseState.VERSION); break; case FCGI_STDOUT: if (contentLength > 0) { // Have to store it, just in case we get a new request if (!dataBuffers.containsKey(id)) { dataBuffers.put(id, ChannelBuffers.dynamicBuffer()); } logger.finest("Got " + contentLength + " bytes for request " + id); // Write the bytes to the buffer dataBuffers.get(id).writeBytes( buffer.readBytes(contentLength)); // Checkpoint! checkpoint(ResponseState.VERSION); } break; // solaroperator pointed out this never contains HTML, I forgot a // checkpoint so it stayed STDERR even with 0 bytes
case FCGI_STDERR:
patroklossam/WareHouse
src/main/java/com/storage/mywarehouse/Dao/WarehouseProductDAO.java
// Path: src/main/java/com/storage/mywarehouse/View/WarehouseProduct.java // public class WarehouseProduct implements java.io.Serializable { // // // private int id; // private int productId; // private String brand; // private String type; // private int quantity; // private double price; // private String warehouse; // // public WarehouseProduct() { // } // // // public WarehouseProduct(int id, String brand, String type, double price, String warehouse) { // this.id = id; // this.brand = brand; // this.type = type; // this.price = price; // this.warehouse = warehouse; // } // public WarehouseProduct(int id, int productId, String brand, String type, int quantity, double price, String warehouse) { // this.id = id; // this.productId = productId; // this.brand = brand; // this.type = type; // this.quantity = quantity; // this.price = price; // this.warehouse = warehouse; // } // // public int getId() { // return this.id; // } // // public void setId(int id) { // this.id = id; // } // public int getProductId() { // return this.productId; // } // // public void setProductId(int productId) { // this.productId = productId; // } // public String getBrand() { // return this.brand; // } // // public void setBrand(String brand) { // this.brand = brand; // } // public String getType() { // return this.type; // } // // public void setType(String type) { // this.type = type; // } // public int getQuantity() { // return this.quantity; // } // // public void setQuantity(int quantity) { // this.quantity = quantity; // } // public double getPrice() { // return this.price; // } // // public void setPrice(double price) { // this.price = price; // } // public String getWarehouse() { // return this.warehouse; // } // // public void setWarehouse(String warehouse) { // this.warehouse = warehouse; // } // // // // // }
import com.storage.mywarehouse.View.WarehouseProduct; import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.criterion.Restrictions; import java.util.List;
package com.storage.mywarehouse.Dao; public class WarehouseProductDAO { @SuppressWarnings("unchecked")
// Path: src/main/java/com/storage/mywarehouse/View/WarehouseProduct.java // public class WarehouseProduct implements java.io.Serializable { // // // private int id; // private int productId; // private String brand; // private String type; // private int quantity; // private double price; // private String warehouse; // // public WarehouseProduct() { // } // // // public WarehouseProduct(int id, String brand, String type, double price, String warehouse) { // this.id = id; // this.brand = brand; // this.type = type; // this.price = price; // this.warehouse = warehouse; // } // public WarehouseProduct(int id, int productId, String brand, String type, int quantity, double price, String warehouse) { // this.id = id; // this.productId = productId; // this.brand = brand; // this.type = type; // this.quantity = quantity; // this.price = price; // this.warehouse = warehouse; // } // // public int getId() { // return this.id; // } // // public void setId(int id) { // this.id = id; // } // public int getProductId() { // return this.productId; // } // // public void setProductId(int productId) { // this.productId = productId; // } // public String getBrand() { // return this.brand; // } // // public void setBrand(String brand) { // this.brand = brand; // } // public String getType() { // return this.type; // } // // public void setType(String type) { // this.type = type; // } // public int getQuantity() { // return this.quantity; // } // // public void setQuantity(int quantity) { // this.quantity = quantity; // } // public double getPrice() { // return this.price; // } // // public void setPrice(double price) { // this.price = price; // } // public String getWarehouse() { // return this.warehouse; // } // // public void setWarehouse(String warehouse) { // this.warehouse = warehouse; // } // // // // // } // Path: src/main/java/com/storage/mywarehouse/Dao/WarehouseProductDAO.java import com.storage.mywarehouse.View.WarehouseProduct; import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.criterion.Restrictions; import java.util.List; package com.storage.mywarehouse.Dao; public class WarehouseProductDAO { @SuppressWarnings("unchecked")
public static List<WarehouseProduct> findById(int id) {
patroklossam/WareHouse
src/main/java/com/storage/mywarehouse/clientForm.java
// Path: src/main/java/com/storage/mywarehouse/Dao/CustomerDAO.java // public class CustomerDAO { // @SuppressWarnings("unchecked") // public static List<Customer> findAll() { // Session session = NewHibernateUtil.getSessionFactory().openSession(); // Transaction tx = session.beginTransaction(); // List customers = session.createCriteria(Customer.class).list(); // tx.commit(); // session.close(); // return customers; // } // // public static void save(Customer customer) { // Session session = NewHibernateUtil.getSessionFactory().openSession(); // Transaction tx = session.beginTransaction(); // Customer customerWithHighestId = (Customer) session.createCriteria(Customer.class).addOrder(Order.desc("customerId")).setMaxResults(1).uniqueResult(); // int nextId; // if (customerWithHighestId == null) { // nextId = 0; // } else { // nextId = customerWithHighestId.getCustomerId() + 1; // } // customer.setCustomerId(nextId); // session.save(customer); // tx.commit(); // session.close(); // } // // public static void update(Customer customer) { // Session session = NewHibernateUtil.getSessionFactory().openSession(); // Transaction tx = session.beginTransaction(); // session.update(customer); // tx.commit(); // session.close(); // } // // public static void delete(Customer customer) { // Session session = NewHibernateUtil.getSessionFactory().openSession(); // Transaction tx = session.beginTransaction(); // session.delete(customer); // tx.commit(); // session.close(); // } // // public static void deleteAll(List<Customer> customers) { // Session session = NewHibernateUtil.getSessionFactory().openSession(); // Transaction tx = session.beginTransaction(); // for (Customer c : customers) { // session.delete(c); // } // tx.commit(); // session.close(); // } // } // // Path: src/main/java/com/storage/mywarehouse/Entity/Customer.java // public class Customer implements java.io.Serializable { // // // private int customerId; // private String name; // private String lastName; // private String occupation; // private double discount; // private String email; // private String city; // private String postal; // private String telephone; // // // public Customer() { // } // // public Customer(int customerId, String name, String lastName, String occupation, double discount, // String email, String city, String postal, String telephone) { // this.customerId = customerId; // this.name = name; // this.lastName = lastName; // this.occupation = occupation; // this.discount = discount; // this.email = email; // this.city = city; // this.postal = postal; // this.telephone = telephone; // } // // public int getCustomerId() { // return this.customerId; // } // // public void setCustomerId(int customerId) { // this.customerId = customerId; // } // public String getName() { // return this.name; // } // // public void setName(String name) { // this.name = name; // } // public String getLastName() { // return this.lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // public String getOccupation() { // return this.occupation; // } // // public void setOccupation(String occupation) { // this.occupation = occupation; // } // public double getDiscount() { // return this.discount; // } // // public void setDiscount(double discount) { // this.discount = discount; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getCity() { // return city; // } // // public void setCity(String city) { // this.city = city; // } // // public String getPostal() { // return postal; // } // // public void setPostal(String postal) { // this.postal = postal; // } // // public String getTelephone() { // return telephone; // } // // public void setTelephone(String telephone) { // this.telephone = telephone; // } // }
import com.storage.mywarehouse.Entity.Customer; import java.awt.Component; import javax.swing.JOptionPane; import com.storage.mywarehouse.Dao.CustomerDAO;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.storage.mywarehouse; /** * * @author Patroklos */ public class clientForm extends javax.swing.JFrame { private final MyObservable observable = new MyObservable(); private boolean update;
// Path: src/main/java/com/storage/mywarehouse/Dao/CustomerDAO.java // public class CustomerDAO { // @SuppressWarnings("unchecked") // public static List<Customer> findAll() { // Session session = NewHibernateUtil.getSessionFactory().openSession(); // Transaction tx = session.beginTransaction(); // List customers = session.createCriteria(Customer.class).list(); // tx.commit(); // session.close(); // return customers; // } // // public static void save(Customer customer) { // Session session = NewHibernateUtil.getSessionFactory().openSession(); // Transaction tx = session.beginTransaction(); // Customer customerWithHighestId = (Customer) session.createCriteria(Customer.class).addOrder(Order.desc("customerId")).setMaxResults(1).uniqueResult(); // int nextId; // if (customerWithHighestId == null) { // nextId = 0; // } else { // nextId = customerWithHighestId.getCustomerId() + 1; // } // customer.setCustomerId(nextId); // session.save(customer); // tx.commit(); // session.close(); // } // // public static void update(Customer customer) { // Session session = NewHibernateUtil.getSessionFactory().openSession(); // Transaction tx = session.beginTransaction(); // session.update(customer); // tx.commit(); // session.close(); // } // // public static void delete(Customer customer) { // Session session = NewHibernateUtil.getSessionFactory().openSession(); // Transaction tx = session.beginTransaction(); // session.delete(customer); // tx.commit(); // session.close(); // } // // public static void deleteAll(List<Customer> customers) { // Session session = NewHibernateUtil.getSessionFactory().openSession(); // Transaction tx = session.beginTransaction(); // for (Customer c : customers) { // session.delete(c); // } // tx.commit(); // session.close(); // } // } // // Path: src/main/java/com/storage/mywarehouse/Entity/Customer.java // public class Customer implements java.io.Serializable { // // // private int customerId; // private String name; // private String lastName; // private String occupation; // private double discount; // private String email; // private String city; // private String postal; // private String telephone; // // // public Customer() { // } // // public Customer(int customerId, String name, String lastName, String occupation, double discount, // String email, String city, String postal, String telephone) { // this.customerId = customerId; // this.name = name; // this.lastName = lastName; // this.occupation = occupation; // this.discount = discount; // this.email = email; // this.city = city; // this.postal = postal; // this.telephone = telephone; // } // // public int getCustomerId() { // return this.customerId; // } // // public void setCustomerId(int customerId) { // this.customerId = customerId; // } // public String getName() { // return this.name; // } // // public void setName(String name) { // this.name = name; // } // public String getLastName() { // return this.lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // public String getOccupation() { // return this.occupation; // } // // public void setOccupation(String occupation) { // this.occupation = occupation; // } // public double getDiscount() { // return this.discount; // } // // public void setDiscount(double discount) { // this.discount = discount; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getCity() { // return city; // } // // public void setCity(String city) { // this.city = city; // } // // public String getPostal() { // return postal; // } // // public void setPostal(String postal) { // this.postal = postal; // } // // public String getTelephone() { // return telephone; // } // // public void setTelephone(String telephone) { // this.telephone = telephone; // } // } // Path: src/main/java/com/storage/mywarehouse/clientForm.java import com.storage.mywarehouse.Entity.Customer; import java.awt.Component; import javax.swing.JOptionPane; import com.storage.mywarehouse.Dao.CustomerDAO; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.storage.mywarehouse; /** * * @author Patroklos */ public class clientForm extends javax.swing.JFrame { private final MyObservable observable = new MyObservable(); private boolean update;
private Customer customer;
patroklossam/WareHouse
src/main/java/com/storage/mywarehouse/clientForm.java
// Path: src/main/java/com/storage/mywarehouse/Dao/CustomerDAO.java // public class CustomerDAO { // @SuppressWarnings("unchecked") // public static List<Customer> findAll() { // Session session = NewHibernateUtil.getSessionFactory().openSession(); // Transaction tx = session.beginTransaction(); // List customers = session.createCriteria(Customer.class).list(); // tx.commit(); // session.close(); // return customers; // } // // public static void save(Customer customer) { // Session session = NewHibernateUtil.getSessionFactory().openSession(); // Transaction tx = session.beginTransaction(); // Customer customerWithHighestId = (Customer) session.createCriteria(Customer.class).addOrder(Order.desc("customerId")).setMaxResults(1).uniqueResult(); // int nextId; // if (customerWithHighestId == null) { // nextId = 0; // } else { // nextId = customerWithHighestId.getCustomerId() + 1; // } // customer.setCustomerId(nextId); // session.save(customer); // tx.commit(); // session.close(); // } // // public static void update(Customer customer) { // Session session = NewHibernateUtil.getSessionFactory().openSession(); // Transaction tx = session.beginTransaction(); // session.update(customer); // tx.commit(); // session.close(); // } // // public static void delete(Customer customer) { // Session session = NewHibernateUtil.getSessionFactory().openSession(); // Transaction tx = session.beginTransaction(); // session.delete(customer); // tx.commit(); // session.close(); // } // // public static void deleteAll(List<Customer> customers) { // Session session = NewHibernateUtil.getSessionFactory().openSession(); // Transaction tx = session.beginTransaction(); // for (Customer c : customers) { // session.delete(c); // } // tx.commit(); // session.close(); // } // } // // Path: src/main/java/com/storage/mywarehouse/Entity/Customer.java // public class Customer implements java.io.Serializable { // // // private int customerId; // private String name; // private String lastName; // private String occupation; // private double discount; // private String email; // private String city; // private String postal; // private String telephone; // // // public Customer() { // } // // public Customer(int customerId, String name, String lastName, String occupation, double discount, // String email, String city, String postal, String telephone) { // this.customerId = customerId; // this.name = name; // this.lastName = lastName; // this.occupation = occupation; // this.discount = discount; // this.email = email; // this.city = city; // this.postal = postal; // this.telephone = telephone; // } // // public int getCustomerId() { // return this.customerId; // } // // public void setCustomerId(int customerId) { // this.customerId = customerId; // } // public String getName() { // return this.name; // } // // public void setName(String name) { // this.name = name; // } // public String getLastName() { // return this.lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // public String getOccupation() { // return this.occupation; // } // // public void setOccupation(String occupation) { // this.occupation = occupation; // } // public double getDiscount() { // return this.discount; // } // // public void setDiscount(double discount) { // this.discount = discount; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getCity() { // return city; // } // // public void setCity(String city) { // this.city = city; // } // // public String getPostal() { // return postal; // } // // public void setPostal(String postal) { // this.postal = postal; // } // // public String getTelephone() { // return telephone; // } // // public void setTelephone(String telephone) { // this.telephone = telephone; // } // }
import com.storage.mywarehouse.Entity.Customer; import java.awt.Component; import javax.swing.JOptionPane; import com.storage.mywarehouse.Dao.CustomerDAO;
if (city.getText().length() > 0) { cCity += city.getText(); } if (telephone.getText().length() > 0) { cTelephone += telephone.getText(); } if (clientName.getText().length() > 0) { cName += clientName.getText(); } if (clientJob.getText().length() > 0) { full_job = clientJob.getText(); } else { full_job = ""; } if (discount.getText().length() > 0) { full_dc = Double.parseDouble(discount.getText()); } else { full_dc = 0.0; } customer.setName(cName); customer.setLastName(cLastName); customer.setOccupation(full_job); customer.setDiscount(full_dc); customer.setEmail(cEmial); customer.setPostal(cPostal); customer.setCity(cCity); customer.setTelephone(cTelephone); if (update) {
// Path: src/main/java/com/storage/mywarehouse/Dao/CustomerDAO.java // public class CustomerDAO { // @SuppressWarnings("unchecked") // public static List<Customer> findAll() { // Session session = NewHibernateUtil.getSessionFactory().openSession(); // Transaction tx = session.beginTransaction(); // List customers = session.createCriteria(Customer.class).list(); // tx.commit(); // session.close(); // return customers; // } // // public static void save(Customer customer) { // Session session = NewHibernateUtil.getSessionFactory().openSession(); // Transaction tx = session.beginTransaction(); // Customer customerWithHighestId = (Customer) session.createCriteria(Customer.class).addOrder(Order.desc("customerId")).setMaxResults(1).uniqueResult(); // int nextId; // if (customerWithHighestId == null) { // nextId = 0; // } else { // nextId = customerWithHighestId.getCustomerId() + 1; // } // customer.setCustomerId(nextId); // session.save(customer); // tx.commit(); // session.close(); // } // // public static void update(Customer customer) { // Session session = NewHibernateUtil.getSessionFactory().openSession(); // Transaction tx = session.beginTransaction(); // session.update(customer); // tx.commit(); // session.close(); // } // // public static void delete(Customer customer) { // Session session = NewHibernateUtil.getSessionFactory().openSession(); // Transaction tx = session.beginTransaction(); // session.delete(customer); // tx.commit(); // session.close(); // } // // public static void deleteAll(List<Customer> customers) { // Session session = NewHibernateUtil.getSessionFactory().openSession(); // Transaction tx = session.beginTransaction(); // for (Customer c : customers) { // session.delete(c); // } // tx.commit(); // session.close(); // } // } // // Path: src/main/java/com/storage/mywarehouse/Entity/Customer.java // public class Customer implements java.io.Serializable { // // // private int customerId; // private String name; // private String lastName; // private String occupation; // private double discount; // private String email; // private String city; // private String postal; // private String telephone; // // // public Customer() { // } // // public Customer(int customerId, String name, String lastName, String occupation, double discount, // String email, String city, String postal, String telephone) { // this.customerId = customerId; // this.name = name; // this.lastName = lastName; // this.occupation = occupation; // this.discount = discount; // this.email = email; // this.city = city; // this.postal = postal; // this.telephone = telephone; // } // // public int getCustomerId() { // return this.customerId; // } // // public void setCustomerId(int customerId) { // this.customerId = customerId; // } // public String getName() { // return this.name; // } // // public void setName(String name) { // this.name = name; // } // public String getLastName() { // return this.lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // public String getOccupation() { // return this.occupation; // } // // public void setOccupation(String occupation) { // this.occupation = occupation; // } // public double getDiscount() { // return this.discount; // } // // public void setDiscount(double discount) { // this.discount = discount; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getCity() { // return city; // } // // public void setCity(String city) { // this.city = city; // } // // public String getPostal() { // return postal; // } // // public void setPostal(String postal) { // this.postal = postal; // } // // public String getTelephone() { // return telephone; // } // // public void setTelephone(String telephone) { // this.telephone = telephone; // } // } // Path: src/main/java/com/storage/mywarehouse/clientForm.java import com.storage.mywarehouse.Entity.Customer; import java.awt.Component; import javax.swing.JOptionPane; import com.storage.mywarehouse.Dao.CustomerDAO; if (city.getText().length() > 0) { cCity += city.getText(); } if (telephone.getText().length() > 0) { cTelephone += telephone.getText(); } if (clientName.getText().length() > 0) { cName += clientName.getText(); } if (clientJob.getText().length() > 0) { full_job = clientJob.getText(); } else { full_job = ""; } if (discount.getText().length() > 0) { full_dc = Double.parseDouble(discount.getText()); } else { full_dc = 0.0; } customer.setName(cName); customer.setLastName(cLastName); customer.setOccupation(full_job); customer.setDiscount(full_dc); customer.setEmail(cEmial); customer.setPostal(cPostal); customer.setCity(cCity); customer.setTelephone(cTelephone); if (update) {
CustomerDAO.update(customer);
patroklossam/WareHouse
src/test/java/com/storage/mywarehouse/Dao/QuantityHistoryViewDAOTest.java
// Path: src/main/java/com/storage/mywarehouse/View/QuantityHistoryView.java // public class QuantityHistoryView implements java.io.Serializable { // // // private int id; // private String warehouse; // private String brand; // private String type; // private int quantity; // private Date date; // // public QuantityHistoryView() { // } // // // public QuantityHistoryView(int id, String warehouse, String brand, String type) { // this.id = id; // this.warehouse = warehouse; // this.brand = brand; // this.type = type; // } // public QuantityHistoryView(int id, String warehouse, String brand, String type, int quantity, Date date) { // this.id = id; // this.warehouse = warehouse; // this.brand = brand; // this.type = type; // this.quantity = quantity; // this.date = date; // } // // public int getId() { // return this.id; // } // // public void setId(int id) { // this.id = id; // } // public String getWarehouse() { // return this.warehouse; // } // // public void setWarehouse(String warehouse) { // this.warehouse = warehouse; // } // public String getBrand() { // return this.brand; // } // // public void setBrand(String brand) { // this.brand = brand; // } // public String getType() { // return this.type; // } // // public void setType(String type) { // this.type = type; // } // public int getQuantity() { // return this.quantity; // } // // public void setQuantity(int quantity) { // this.quantity = quantity; // } // public Date getDate() { // return this.date; // } // // public void setDate(Date date) { // this.date = date; // } // // public String toString(){ // return warehouse+"\t"+brand+"\t"+type+"\t"+date+"\t"+quantity; // } // // // // }
import com.storage.mywarehouse.View.QuantityHistoryView; import org.hibernate.Session; import org.hibernate.criterion.Order; import org.junit.Assert; import org.junit.jupiter.api.Test; import java.util.List; import static org.junit.jupiter.api.Assertions.*;
package com.storage.mywarehouse.Dao; class QuantityHistoryViewDAOTest { @Test void findAll() { Session session = NewHibernateUtil.getSessionFactory().openSession();
// Path: src/main/java/com/storage/mywarehouse/View/QuantityHistoryView.java // public class QuantityHistoryView implements java.io.Serializable { // // // private int id; // private String warehouse; // private String brand; // private String type; // private int quantity; // private Date date; // // public QuantityHistoryView() { // } // // // public QuantityHistoryView(int id, String warehouse, String brand, String type) { // this.id = id; // this.warehouse = warehouse; // this.brand = brand; // this.type = type; // } // public QuantityHistoryView(int id, String warehouse, String brand, String type, int quantity, Date date) { // this.id = id; // this.warehouse = warehouse; // this.brand = brand; // this.type = type; // this.quantity = quantity; // this.date = date; // } // // public int getId() { // return this.id; // } // // public void setId(int id) { // this.id = id; // } // public String getWarehouse() { // return this.warehouse; // } // // public void setWarehouse(String warehouse) { // this.warehouse = warehouse; // } // public String getBrand() { // return this.brand; // } // // public void setBrand(String brand) { // this.brand = brand; // } // public String getType() { // return this.type; // } // // public void setType(String type) { // this.type = type; // } // public int getQuantity() { // return this.quantity; // } // // public void setQuantity(int quantity) { // this.quantity = quantity; // } // public Date getDate() { // return this.date; // } // // public void setDate(Date date) { // this.date = date; // } // // public String toString(){ // return warehouse+"\t"+brand+"\t"+type+"\t"+date+"\t"+quantity; // } // // // // } // Path: src/test/java/com/storage/mywarehouse/Dao/QuantityHistoryViewDAOTest.java import com.storage.mywarehouse.View.QuantityHistoryView; import org.hibernate.Session; import org.hibernate.criterion.Order; import org.junit.Assert; import org.junit.jupiter.api.Test; import java.util.List; import static org.junit.jupiter.api.Assertions.*; package com.storage.mywarehouse.Dao; class QuantityHistoryViewDAOTest { @Test void findAll() { Session session = NewHibernateUtil.getSessionFactory().openSession();
List q_history = session.createCriteria(QuantityHistoryView.class)
patroklossam/WareHouse
src/main/java/com/storage/mywarehouse/ClientFrame.java
// Path: src/main/java/com/storage/mywarehouse/Dao/CustomerDAO.java // public class CustomerDAO { // @SuppressWarnings("unchecked") // public static List<Customer> findAll() { // Session session = NewHibernateUtil.getSessionFactory().openSession(); // Transaction tx = session.beginTransaction(); // List customers = session.createCriteria(Customer.class).list(); // tx.commit(); // session.close(); // return customers; // } // // public static void save(Customer customer) { // Session session = NewHibernateUtil.getSessionFactory().openSession(); // Transaction tx = session.beginTransaction(); // Customer customerWithHighestId = (Customer) session.createCriteria(Customer.class).addOrder(Order.desc("customerId")).setMaxResults(1).uniqueResult(); // int nextId; // if (customerWithHighestId == null) { // nextId = 0; // } else { // nextId = customerWithHighestId.getCustomerId() + 1; // } // customer.setCustomerId(nextId); // session.save(customer); // tx.commit(); // session.close(); // } // // public static void update(Customer customer) { // Session session = NewHibernateUtil.getSessionFactory().openSession(); // Transaction tx = session.beginTransaction(); // session.update(customer); // tx.commit(); // session.close(); // } // // public static void delete(Customer customer) { // Session session = NewHibernateUtil.getSessionFactory().openSession(); // Transaction tx = session.beginTransaction(); // session.delete(customer); // tx.commit(); // session.close(); // } // // public static void deleteAll(List<Customer> customers) { // Session session = NewHibernateUtil.getSessionFactory().openSession(); // Transaction tx = session.beginTransaction(); // for (Customer c : customers) { // session.delete(c); // } // tx.commit(); // session.close(); // } // } // // Path: src/main/java/com/storage/mywarehouse/Entity/Customer.java // public class Customer implements java.io.Serializable { // // // private int customerId; // private String name; // private String lastName; // private String occupation; // private double discount; // private String email; // private String city; // private String postal; // private String telephone; // // // public Customer() { // } // // public Customer(int customerId, String name, String lastName, String occupation, double discount, // String email, String city, String postal, String telephone) { // this.customerId = customerId; // this.name = name; // this.lastName = lastName; // this.occupation = occupation; // this.discount = discount; // this.email = email; // this.city = city; // this.postal = postal; // this.telephone = telephone; // } // // public int getCustomerId() { // return this.customerId; // } // // public void setCustomerId(int customerId) { // this.customerId = customerId; // } // public String getName() { // return this.name; // } // // public void setName(String name) { // this.name = name; // } // public String getLastName() { // return this.lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // public String getOccupation() { // return this.occupation; // } // // public void setOccupation(String occupation) { // this.occupation = occupation; // } // public double getDiscount() { // return this.discount; // } // // public void setDiscount(double discount) { // this.discount = discount; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getCity() { // return city; // } // // public void setCity(String city) { // this.city = city; // } // // public String getPostal() { // return postal; // } // // public void setPostal(String postal) { // this.postal = postal; // } // // public String getTelephone() { // return telephone; // } // // public void setTelephone(String telephone) { // this.telephone = telephone; // } // }
import com.storage.mywarehouse.Dao.CustomerDAO; import com.storage.mywarehouse.Entity.Customer; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import javax.swing.JOptionPane; import javax.swing.table.DefaultTableModel;
this.frame = frame; initComponents(); tbmodel = new DefaultTableModel(new Object[]{"Last Name", "First Name", "Occupation", "Discount"}, 0) { @Override public boolean isCellEditable(int row, int column) { return false; } }; jTable1.setModel(tbmodel); refreshClients(customers); setVisible(true); setDefaultCloseOperation(DISPOSE_ON_CLOSE); } public void refreshClients(List customers) { this.customers = customers; int rows = tbmodel.getRowCount(); Collections.sort(customers, new ComparatorImpl()); //empty client table for (int i = 0; i < rows; i++) { tbmodel.removeRow(0); } for (Iterator it = customers.iterator(); it.hasNext();) {
// Path: src/main/java/com/storage/mywarehouse/Dao/CustomerDAO.java // public class CustomerDAO { // @SuppressWarnings("unchecked") // public static List<Customer> findAll() { // Session session = NewHibernateUtil.getSessionFactory().openSession(); // Transaction tx = session.beginTransaction(); // List customers = session.createCriteria(Customer.class).list(); // tx.commit(); // session.close(); // return customers; // } // // public static void save(Customer customer) { // Session session = NewHibernateUtil.getSessionFactory().openSession(); // Transaction tx = session.beginTransaction(); // Customer customerWithHighestId = (Customer) session.createCriteria(Customer.class).addOrder(Order.desc("customerId")).setMaxResults(1).uniqueResult(); // int nextId; // if (customerWithHighestId == null) { // nextId = 0; // } else { // nextId = customerWithHighestId.getCustomerId() + 1; // } // customer.setCustomerId(nextId); // session.save(customer); // tx.commit(); // session.close(); // } // // public static void update(Customer customer) { // Session session = NewHibernateUtil.getSessionFactory().openSession(); // Transaction tx = session.beginTransaction(); // session.update(customer); // tx.commit(); // session.close(); // } // // public static void delete(Customer customer) { // Session session = NewHibernateUtil.getSessionFactory().openSession(); // Transaction tx = session.beginTransaction(); // session.delete(customer); // tx.commit(); // session.close(); // } // // public static void deleteAll(List<Customer> customers) { // Session session = NewHibernateUtil.getSessionFactory().openSession(); // Transaction tx = session.beginTransaction(); // for (Customer c : customers) { // session.delete(c); // } // tx.commit(); // session.close(); // } // } // // Path: src/main/java/com/storage/mywarehouse/Entity/Customer.java // public class Customer implements java.io.Serializable { // // // private int customerId; // private String name; // private String lastName; // private String occupation; // private double discount; // private String email; // private String city; // private String postal; // private String telephone; // // // public Customer() { // } // // public Customer(int customerId, String name, String lastName, String occupation, double discount, // String email, String city, String postal, String telephone) { // this.customerId = customerId; // this.name = name; // this.lastName = lastName; // this.occupation = occupation; // this.discount = discount; // this.email = email; // this.city = city; // this.postal = postal; // this.telephone = telephone; // } // // public int getCustomerId() { // return this.customerId; // } // // public void setCustomerId(int customerId) { // this.customerId = customerId; // } // public String getName() { // return this.name; // } // // public void setName(String name) { // this.name = name; // } // public String getLastName() { // return this.lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // public String getOccupation() { // return this.occupation; // } // // public void setOccupation(String occupation) { // this.occupation = occupation; // } // public double getDiscount() { // return this.discount; // } // // public void setDiscount(double discount) { // this.discount = discount; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getCity() { // return city; // } // // public void setCity(String city) { // this.city = city; // } // // public String getPostal() { // return postal; // } // // public void setPostal(String postal) { // this.postal = postal; // } // // public String getTelephone() { // return telephone; // } // // public void setTelephone(String telephone) { // this.telephone = telephone; // } // } // Path: src/main/java/com/storage/mywarehouse/ClientFrame.java import com.storage.mywarehouse.Dao.CustomerDAO; import com.storage.mywarehouse.Entity.Customer; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import javax.swing.JOptionPane; import javax.swing.table.DefaultTableModel; this.frame = frame; initComponents(); tbmodel = new DefaultTableModel(new Object[]{"Last Name", "First Name", "Occupation", "Discount"}, 0) { @Override public boolean isCellEditable(int row, int column) { return false; } }; jTable1.setModel(tbmodel); refreshClients(customers); setVisible(true); setDefaultCloseOperation(DISPOSE_ON_CLOSE); } public void refreshClients(List customers) { this.customers = customers; int rows = tbmodel.getRowCount(); Collections.sort(customers, new ComparatorImpl()); //empty client table for (int i = 0; i < rows; i++) { tbmodel.removeRow(0); } for (Iterator it = customers.iterator(); it.hasNext();) {
Customer customer = (Customer) it.next();
patroklossam/WareHouse
src/main/java/com/storage/mywarehouse/ClientFrame.java
// Path: src/main/java/com/storage/mywarehouse/Dao/CustomerDAO.java // public class CustomerDAO { // @SuppressWarnings("unchecked") // public static List<Customer> findAll() { // Session session = NewHibernateUtil.getSessionFactory().openSession(); // Transaction tx = session.beginTransaction(); // List customers = session.createCriteria(Customer.class).list(); // tx.commit(); // session.close(); // return customers; // } // // public static void save(Customer customer) { // Session session = NewHibernateUtil.getSessionFactory().openSession(); // Transaction tx = session.beginTransaction(); // Customer customerWithHighestId = (Customer) session.createCriteria(Customer.class).addOrder(Order.desc("customerId")).setMaxResults(1).uniqueResult(); // int nextId; // if (customerWithHighestId == null) { // nextId = 0; // } else { // nextId = customerWithHighestId.getCustomerId() + 1; // } // customer.setCustomerId(nextId); // session.save(customer); // tx.commit(); // session.close(); // } // // public static void update(Customer customer) { // Session session = NewHibernateUtil.getSessionFactory().openSession(); // Transaction tx = session.beginTransaction(); // session.update(customer); // tx.commit(); // session.close(); // } // // public static void delete(Customer customer) { // Session session = NewHibernateUtil.getSessionFactory().openSession(); // Transaction tx = session.beginTransaction(); // session.delete(customer); // tx.commit(); // session.close(); // } // // public static void deleteAll(List<Customer> customers) { // Session session = NewHibernateUtil.getSessionFactory().openSession(); // Transaction tx = session.beginTransaction(); // for (Customer c : customers) { // session.delete(c); // } // tx.commit(); // session.close(); // } // } // // Path: src/main/java/com/storage/mywarehouse/Entity/Customer.java // public class Customer implements java.io.Serializable { // // // private int customerId; // private String name; // private String lastName; // private String occupation; // private double discount; // private String email; // private String city; // private String postal; // private String telephone; // // // public Customer() { // } // // public Customer(int customerId, String name, String lastName, String occupation, double discount, // String email, String city, String postal, String telephone) { // this.customerId = customerId; // this.name = name; // this.lastName = lastName; // this.occupation = occupation; // this.discount = discount; // this.email = email; // this.city = city; // this.postal = postal; // this.telephone = telephone; // } // // public int getCustomerId() { // return this.customerId; // } // // public void setCustomerId(int customerId) { // this.customerId = customerId; // } // public String getName() { // return this.name; // } // // public void setName(String name) { // this.name = name; // } // public String getLastName() { // return this.lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // public String getOccupation() { // return this.occupation; // } // // public void setOccupation(String occupation) { // this.occupation = occupation; // } // public double getDiscount() { // return this.discount; // } // // public void setDiscount(double discount) { // this.discount = discount; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getCity() { // return city; // } // // public void setCity(String city) { // this.city = city; // } // // public String getPostal() { // return postal; // } // // public void setPostal(String postal) { // this.postal = postal; // } // // public String getTelephone() { // return telephone; // } // // public void setTelephone(String telephone) { // this.telephone = telephone; // } // }
import com.storage.mywarehouse.Dao.CustomerDAO; import com.storage.mywarehouse.Entity.Customer; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import javax.swing.JOptionPane; import javax.swing.table.DefaultTableModel;
getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents private void newClientActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newClientActionPerformed clientForm clf = new clientForm(frame); clf.setVisible(true); clf.setAlwaysOnTop(true); clf.requestFocusInWindow(); }//GEN-LAST:event_newClientActionPerformed private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed int row = jTable1.getSelectedRow(); if (row != -1) { int sel = JOptionPane.showConfirmDialog(this, "Are you sure you want to delete this customer?", "Confirm", JOptionPane.OK_CANCEL_OPTION); if (sel == 0) { tbmodel.removeRow(row); } Customer c = (Customer) customers.get(row); customers.remove(c);
// Path: src/main/java/com/storage/mywarehouse/Dao/CustomerDAO.java // public class CustomerDAO { // @SuppressWarnings("unchecked") // public static List<Customer> findAll() { // Session session = NewHibernateUtil.getSessionFactory().openSession(); // Transaction tx = session.beginTransaction(); // List customers = session.createCriteria(Customer.class).list(); // tx.commit(); // session.close(); // return customers; // } // // public static void save(Customer customer) { // Session session = NewHibernateUtil.getSessionFactory().openSession(); // Transaction tx = session.beginTransaction(); // Customer customerWithHighestId = (Customer) session.createCriteria(Customer.class).addOrder(Order.desc("customerId")).setMaxResults(1).uniqueResult(); // int nextId; // if (customerWithHighestId == null) { // nextId = 0; // } else { // nextId = customerWithHighestId.getCustomerId() + 1; // } // customer.setCustomerId(nextId); // session.save(customer); // tx.commit(); // session.close(); // } // // public static void update(Customer customer) { // Session session = NewHibernateUtil.getSessionFactory().openSession(); // Transaction tx = session.beginTransaction(); // session.update(customer); // tx.commit(); // session.close(); // } // // public static void delete(Customer customer) { // Session session = NewHibernateUtil.getSessionFactory().openSession(); // Transaction tx = session.beginTransaction(); // session.delete(customer); // tx.commit(); // session.close(); // } // // public static void deleteAll(List<Customer> customers) { // Session session = NewHibernateUtil.getSessionFactory().openSession(); // Transaction tx = session.beginTransaction(); // for (Customer c : customers) { // session.delete(c); // } // tx.commit(); // session.close(); // } // } // // Path: src/main/java/com/storage/mywarehouse/Entity/Customer.java // public class Customer implements java.io.Serializable { // // // private int customerId; // private String name; // private String lastName; // private String occupation; // private double discount; // private String email; // private String city; // private String postal; // private String telephone; // // // public Customer() { // } // // public Customer(int customerId, String name, String lastName, String occupation, double discount, // String email, String city, String postal, String telephone) { // this.customerId = customerId; // this.name = name; // this.lastName = lastName; // this.occupation = occupation; // this.discount = discount; // this.email = email; // this.city = city; // this.postal = postal; // this.telephone = telephone; // } // // public int getCustomerId() { // return this.customerId; // } // // public void setCustomerId(int customerId) { // this.customerId = customerId; // } // public String getName() { // return this.name; // } // // public void setName(String name) { // this.name = name; // } // public String getLastName() { // return this.lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // public String getOccupation() { // return this.occupation; // } // // public void setOccupation(String occupation) { // this.occupation = occupation; // } // public double getDiscount() { // return this.discount; // } // // public void setDiscount(double discount) { // this.discount = discount; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getCity() { // return city; // } // // public void setCity(String city) { // this.city = city; // } // // public String getPostal() { // return postal; // } // // public void setPostal(String postal) { // this.postal = postal; // } // // public String getTelephone() { // return telephone; // } // // public void setTelephone(String telephone) { // this.telephone = telephone; // } // } // Path: src/main/java/com/storage/mywarehouse/ClientFrame.java import com.storage.mywarehouse.Dao.CustomerDAO; import com.storage.mywarehouse.Entity.Customer; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import javax.swing.JOptionPane; import javax.swing.table.DefaultTableModel; getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents private void newClientActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newClientActionPerformed clientForm clf = new clientForm(frame); clf.setVisible(true); clf.setAlwaysOnTop(true); clf.requestFocusInWindow(); }//GEN-LAST:event_newClientActionPerformed private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed int row = jTable1.getSelectedRow(); if (row != -1) { int sel = JOptionPane.showConfirmDialog(this, "Are you sure you want to delete this customer?", "Confirm", JOptionPane.OK_CANCEL_OPTION); if (sel == 0) { tbmodel.removeRow(row); } Customer c = (Customer) customers.get(row); customers.remove(c);
CustomerDAO.delete(c);
patroklossam/WareHouse
src/test/java/com/storage/mywarehouse/Dao/EntryDaoTest.java
// Path: src/main/java/com/storage/mywarehouse/Entity/Warehouse.java // public class Warehouse implements java.io.Serializable { // // // private int warehouseId; // private String name; // // public Warehouse() { // } // // public Warehouse(int warehouseId, String name) { // this.warehouseId = warehouseId; // this.name = name; // } // // public Warehouse(String name) { // this.name = name; // } // // public int getWarehouseId() { // return this.warehouseId; // } // // public void setWarehouseId(int warehouseId) { // this.warehouseId = warehouseId; // } // public String getName() { // return this.name; // } // // public void setName(String name) { // this.name = name; // } // // // // // } // // Path: src/main/java/com/storage/mywarehouse/Entity/Product.java // public class Product implements java.io.Serializable { // // private static final long serialVersionUID = 1L; // // private int productId; // private String brand; // private String type; // private String description; // private double price; // // public Product() { // } // // public Product(int productId, String brand, String type, double price) { // this.productId = productId; // this.brand = brand; // this.type = type; // this.price = price; // } // // public Product(int productId, String brand, String type, String description, double price) { // this.productId = productId; // this.brand = brand; // this.type = type; // this.description = description; // this.price = price; // } // // public Product(String brand, String type, String description, double price) { // this.brand = brand; // this.type = type; // this.description = description; // this.price = price; // } // // public int getProductId() { // return this.productId; // } // // public void setProductId(int productId) { // this.productId = productId; // } // // public String getBrand() { // return this.brand; // } // // public void setBrand(String brand) { // this.brand = brand; // } // // public String getType() { // return this.type; // } // // public void setType(String type) { // this.type = type; // } // // public String getDescription() { // return this.description; // } // // public void setDescription(String description) { // this.description = description; // } // // public double getPrice() { // return this.price; // } // // public void setPrice(double price) { // this.price = price; // } // // } // // Path: src/main/java/com/storage/mywarehouse/Entity/Entry.java // public class Entry implements java.io.Serializable { // // // private int entryId; // private int warehouseId; // private int productId; // private int quantity; // // public Entry() { // } // // public Entry(int entryId, int warehouseId, int productId, int quantity) { // this.entryId = entryId; // this.warehouseId = warehouseId; // this.productId = productId; // this.quantity = quantity; // } // // public Entry(int warehouseId, int productId, int quantity) { // this.warehouseId = warehouseId; // this.productId = productId; // this.quantity = quantity; // } // // public int getEntryId() { // return this.entryId; // } // // public void setEntryId(int entryId) { // this.entryId = entryId; // } // public int getWarehouseId() { // return this.warehouseId; // } // // public void setWarehouseId(int warehouseId) { // this.warehouseId = warehouseId; // } // public int getProductId() { // return this.productId; // } // // public void setProductId(int productId) { // this.productId = productId; // } // public int getQuantity() { // return this.quantity; // } // // public void setQuantity(int quantity) { // this.quantity = quantity; // } // // // // // }
import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.assertAll; import com.storage.mywarehouse.Entity.Warehouse; import com.storage.mywarehouse.Entity.Product; import com.storage.mywarehouse.Entity.Entry; import java.util.List; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.AfterEach;
package com.storage.mywarehouse.Dao; public class EntryDaoTest { private static final int ZERO = 0; private static final int ONE = 1; private static final int TWO = 2; private static final int THREE = 3; private static final int NINE = 9; private static final String ANY = "ANY"; private static final String ANY2 = "ANY2"; private static final String ANY3 = "ANY3"; private static final double DOUBLE_VAL = 1.1;
// Path: src/main/java/com/storage/mywarehouse/Entity/Warehouse.java // public class Warehouse implements java.io.Serializable { // // // private int warehouseId; // private String name; // // public Warehouse() { // } // // public Warehouse(int warehouseId, String name) { // this.warehouseId = warehouseId; // this.name = name; // } // // public Warehouse(String name) { // this.name = name; // } // // public int getWarehouseId() { // return this.warehouseId; // } // // public void setWarehouseId(int warehouseId) { // this.warehouseId = warehouseId; // } // public String getName() { // return this.name; // } // // public void setName(String name) { // this.name = name; // } // // // // // } // // Path: src/main/java/com/storage/mywarehouse/Entity/Product.java // public class Product implements java.io.Serializable { // // private static final long serialVersionUID = 1L; // // private int productId; // private String brand; // private String type; // private String description; // private double price; // // public Product() { // } // // public Product(int productId, String brand, String type, double price) { // this.productId = productId; // this.brand = brand; // this.type = type; // this.price = price; // } // // public Product(int productId, String brand, String type, String description, double price) { // this.productId = productId; // this.brand = brand; // this.type = type; // this.description = description; // this.price = price; // } // // public Product(String brand, String type, String description, double price) { // this.brand = brand; // this.type = type; // this.description = description; // this.price = price; // } // // public int getProductId() { // return this.productId; // } // // public void setProductId(int productId) { // this.productId = productId; // } // // public String getBrand() { // return this.brand; // } // // public void setBrand(String brand) { // this.brand = brand; // } // // public String getType() { // return this.type; // } // // public void setType(String type) { // this.type = type; // } // // public String getDescription() { // return this.description; // } // // public void setDescription(String description) { // this.description = description; // } // // public double getPrice() { // return this.price; // } // // public void setPrice(double price) { // this.price = price; // } // // } // // Path: src/main/java/com/storage/mywarehouse/Entity/Entry.java // public class Entry implements java.io.Serializable { // // // private int entryId; // private int warehouseId; // private int productId; // private int quantity; // // public Entry() { // } // // public Entry(int entryId, int warehouseId, int productId, int quantity) { // this.entryId = entryId; // this.warehouseId = warehouseId; // this.productId = productId; // this.quantity = quantity; // } // // public Entry(int warehouseId, int productId, int quantity) { // this.warehouseId = warehouseId; // this.productId = productId; // this.quantity = quantity; // } // // public int getEntryId() { // return this.entryId; // } // // public void setEntryId(int entryId) { // this.entryId = entryId; // } // public int getWarehouseId() { // return this.warehouseId; // } // // public void setWarehouseId(int warehouseId) { // this.warehouseId = warehouseId; // } // public int getProductId() { // return this.productId; // } // // public void setProductId(int productId) { // this.productId = productId; // } // public int getQuantity() { // return this.quantity; // } // // public void setQuantity(int quantity) { // this.quantity = quantity; // } // // // // // } // Path: src/test/java/com/storage/mywarehouse/Dao/EntryDaoTest.java import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.assertAll; import com.storage.mywarehouse.Entity.Warehouse; import com.storage.mywarehouse.Entity.Product; import com.storage.mywarehouse.Entity.Entry; import java.util.List; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.AfterEach; package com.storage.mywarehouse.Dao; public class EntryDaoTest { private static final int ZERO = 0; private static final int ONE = 1; private static final int TWO = 2; private static final int THREE = 3; private static final int NINE = 9; private static final String ANY = "ANY"; private static final String ANY2 = "ANY2"; private static final String ANY3 = "ANY3"; private static final double DOUBLE_VAL = 1.1;
private Warehouse w1;
patroklossam/WareHouse
src/test/java/com/storage/mywarehouse/Dao/EntryDaoTest.java
// Path: src/main/java/com/storage/mywarehouse/Entity/Warehouse.java // public class Warehouse implements java.io.Serializable { // // // private int warehouseId; // private String name; // // public Warehouse() { // } // // public Warehouse(int warehouseId, String name) { // this.warehouseId = warehouseId; // this.name = name; // } // // public Warehouse(String name) { // this.name = name; // } // // public int getWarehouseId() { // return this.warehouseId; // } // // public void setWarehouseId(int warehouseId) { // this.warehouseId = warehouseId; // } // public String getName() { // return this.name; // } // // public void setName(String name) { // this.name = name; // } // // // // // } // // Path: src/main/java/com/storage/mywarehouse/Entity/Product.java // public class Product implements java.io.Serializable { // // private static final long serialVersionUID = 1L; // // private int productId; // private String brand; // private String type; // private String description; // private double price; // // public Product() { // } // // public Product(int productId, String brand, String type, double price) { // this.productId = productId; // this.brand = brand; // this.type = type; // this.price = price; // } // // public Product(int productId, String brand, String type, String description, double price) { // this.productId = productId; // this.brand = brand; // this.type = type; // this.description = description; // this.price = price; // } // // public Product(String brand, String type, String description, double price) { // this.brand = brand; // this.type = type; // this.description = description; // this.price = price; // } // // public int getProductId() { // return this.productId; // } // // public void setProductId(int productId) { // this.productId = productId; // } // // public String getBrand() { // return this.brand; // } // // public void setBrand(String brand) { // this.brand = brand; // } // // public String getType() { // return this.type; // } // // public void setType(String type) { // this.type = type; // } // // public String getDescription() { // return this.description; // } // // public void setDescription(String description) { // this.description = description; // } // // public double getPrice() { // return this.price; // } // // public void setPrice(double price) { // this.price = price; // } // // } // // Path: src/main/java/com/storage/mywarehouse/Entity/Entry.java // public class Entry implements java.io.Serializable { // // // private int entryId; // private int warehouseId; // private int productId; // private int quantity; // // public Entry() { // } // // public Entry(int entryId, int warehouseId, int productId, int quantity) { // this.entryId = entryId; // this.warehouseId = warehouseId; // this.productId = productId; // this.quantity = quantity; // } // // public Entry(int warehouseId, int productId, int quantity) { // this.warehouseId = warehouseId; // this.productId = productId; // this.quantity = quantity; // } // // public int getEntryId() { // return this.entryId; // } // // public void setEntryId(int entryId) { // this.entryId = entryId; // } // public int getWarehouseId() { // return this.warehouseId; // } // // public void setWarehouseId(int warehouseId) { // this.warehouseId = warehouseId; // } // public int getProductId() { // return this.productId; // } // // public void setProductId(int productId) { // this.productId = productId; // } // public int getQuantity() { // return this.quantity; // } // // public void setQuantity(int quantity) { // this.quantity = quantity; // } // // // // // }
import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.assertAll; import com.storage.mywarehouse.Entity.Warehouse; import com.storage.mywarehouse.Entity.Product; import com.storage.mywarehouse.Entity.Entry; import java.util.List; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.AfterEach;
package com.storage.mywarehouse.Dao; public class EntryDaoTest { private static final int ZERO = 0; private static final int ONE = 1; private static final int TWO = 2; private static final int THREE = 3; private static final int NINE = 9; private static final String ANY = "ANY"; private static final String ANY2 = "ANY2"; private static final String ANY3 = "ANY3"; private static final double DOUBLE_VAL = 1.1; private Warehouse w1;
// Path: src/main/java/com/storage/mywarehouse/Entity/Warehouse.java // public class Warehouse implements java.io.Serializable { // // // private int warehouseId; // private String name; // // public Warehouse() { // } // // public Warehouse(int warehouseId, String name) { // this.warehouseId = warehouseId; // this.name = name; // } // // public Warehouse(String name) { // this.name = name; // } // // public int getWarehouseId() { // return this.warehouseId; // } // // public void setWarehouseId(int warehouseId) { // this.warehouseId = warehouseId; // } // public String getName() { // return this.name; // } // // public void setName(String name) { // this.name = name; // } // // // // // } // // Path: src/main/java/com/storage/mywarehouse/Entity/Product.java // public class Product implements java.io.Serializable { // // private static final long serialVersionUID = 1L; // // private int productId; // private String brand; // private String type; // private String description; // private double price; // // public Product() { // } // // public Product(int productId, String brand, String type, double price) { // this.productId = productId; // this.brand = brand; // this.type = type; // this.price = price; // } // // public Product(int productId, String brand, String type, String description, double price) { // this.productId = productId; // this.brand = brand; // this.type = type; // this.description = description; // this.price = price; // } // // public Product(String brand, String type, String description, double price) { // this.brand = brand; // this.type = type; // this.description = description; // this.price = price; // } // // public int getProductId() { // return this.productId; // } // // public void setProductId(int productId) { // this.productId = productId; // } // // public String getBrand() { // return this.brand; // } // // public void setBrand(String brand) { // this.brand = brand; // } // // public String getType() { // return this.type; // } // // public void setType(String type) { // this.type = type; // } // // public String getDescription() { // return this.description; // } // // public void setDescription(String description) { // this.description = description; // } // // public double getPrice() { // return this.price; // } // // public void setPrice(double price) { // this.price = price; // } // // } // // Path: src/main/java/com/storage/mywarehouse/Entity/Entry.java // public class Entry implements java.io.Serializable { // // // private int entryId; // private int warehouseId; // private int productId; // private int quantity; // // public Entry() { // } // // public Entry(int entryId, int warehouseId, int productId, int quantity) { // this.entryId = entryId; // this.warehouseId = warehouseId; // this.productId = productId; // this.quantity = quantity; // } // // public Entry(int warehouseId, int productId, int quantity) { // this.warehouseId = warehouseId; // this.productId = productId; // this.quantity = quantity; // } // // public int getEntryId() { // return this.entryId; // } // // public void setEntryId(int entryId) { // this.entryId = entryId; // } // public int getWarehouseId() { // return this.warehouseId; // } // // public void setWarehouseId(int warehouseId) { // this.warehouseId = warehouseId; // } // public int getProductId() { // return this.productId; // } // // public void setProductId(int productId) { // this.productId = productId; // } // public int getQuantity() { // return this.quantity; // } // // public void setQuantity(int quantity) { // this.quantity = quantity; // } // // // // // } // Path: src/test/java/com/storage/mywarehouse/Dao/EntryDaoTest.java import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.assertAll; import com.storage.mywarehouse.Entity.Warehouse; import com.storage.mywarehouse.Entity.Product; import com.storage.mywarehouse.Entity.Entry; import java.util.List; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.AfterEach; package com.storage.mywarehouse.Dao; public class EntryDaoTest { private static final int ZERO = 0; private static final int ONE = 1; private static final int TWO = 2; private static final int THREE = 3; private static final int NINE = 9; private static final String ANY = "ANY"; private static final String ANY2 = "ANY2"; private static final String ANY3 = "ANY3"; private static final double DOUBLE_VAL = 1.1; private Warehouse w1;
private Product p1;
patroklossam/WareHouse
src/test/java/com/storage/mywarehouse/Dao/EntryDaoTest.java
// Path: src/main/java/com/storage/mywarehouse/Entity/Warehouse.java // public class Warehouse implements java.io.Serializable { // // // private int warehouseId; // private String name; // // public Warehouse() { // } // // public Warehouse(int warehouseId, String name) { // this.warehouseId = warehouseId; // this.name = name; // } // // public Warehouse(String name) { // this.name = name; // } // // public int getWarehouseId() { // return this.warehouseId; // } // // public void setWarehouseId(int warehouseId) { // this.warehouseId = warehouseId; // } // public String getName() { // return this.name; // } // // public void setName(String name) { // this.name = name; // } // // // // // } // // Path: src/main/java/com/storage/mywarehouse/Entity/Product.java // public class Product implements java.io.Serializable { // // private static final long serialVersionUID = 1L; // // private int productId; // private String brand; // private String type; // private String description; // private double price; // // public Product() { // } // // public Product(int productId, String brand, String type, double price) { // this.productId = productId; // this.brand = brand; // this.type = type; // this.price = price; // } // // public Product(int productId, String brand, String type, String description, double price) { // this.productId = productId; // this.brand = brand; // this.type = type; // this.description = description; // this.price = price; // } // // public Product(String brand, String type, String description, double price) { // this.brand = brand; // this.type = type; // this.description = description; // this.price = price; // } // // public int getProductId() { // return this.productId; // } // // public void setProductId(int productId) { // this.productId = productId; // } // // public String getBrand() { // return this.brand; // } // // public void setBrand(String brand) { // this.brand = brand; // } // // public String getType() { // return this.type; // } // // public void setType(String type) { // this.type = type; // } // // public String getDescription() { // return this.description; // } // // public void setDescription(String description) { // this.description = description; // } // // public double getPrice() { // return this.price; // } // // public void setPrice(double price) { // this.price = price; // } // // } // // Path: src/main/java/com/storage/mywarehouse/Entity/Entry.java // public class Entry implements java.io.Serializable { // // // private int entryId; // private int warehouseId; // private int productId; // private int quantity; // // public Entry() { // } // // public Entry(int entryId, int warehouseId, int productId, int quantity) { // this.entryId = entryId; // this.warehouseId = warehouseId; // this.productId = productId; // this.quantity = quantity; // } // // public Entry(int warehouseId, int productId, int quantity) { // this.warehouseId = warehouseId; // this.productId = productId; // this.quantity = quantity; // } // // public int getEntryId() { // return this.entryId; // } // // public void setEntryId(int entryId) { // this.entryId = entryId; // } // public int getWarehouseId() { // return this.warehouseId; // } // // public void setWarehouseId(int warehouseId) { // this.warehouseId = warehouseId; // } // public int getProductId() { // return this.productId; // } // // public void setProductId(int productId) { // this.productId = productId; // } // public int getQuantity() { // return this.quantity; // } // // public void setQuantity(int quantity) { // this.quantity = quantity; // } // // // // // }
import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.assertAll; import com.storage.mywarehouse.Entity.Warehouse; import com.storage.mywarehouse.Entity.Product; import com.storage.mywarehouse.Entity.Entry; import java.util.List; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.AfterEach;
package com.storage.mywarehouse.Dao; public class EntryDaoTest { private static final int ZERO = 0; private static final int ONE = 1; private static final int TWO = 2; private static final int THREE = 3; private static final int NINE = 9; private static final String ANY = "ANY"; private static final String ANY2 = "ANY2"; private static final String ANY3 = "ANY3"; private static final double DOUBLE_VAL = 1.1; private Warehouse w1; private Product p1; private Product p2;
// Path: src/main/java/com/storage/mywarehouse/Entity/Warehouse.java // public class Warehouse implements java.io.Serializable { // // // private int warehouseId; // private String name; // // public Warehouse() { // } // // public Warehouse(int warehouseId, String name) { // this.warehouseId = warehouseId; // this.name = name; // } // // public Warehouse(String name) { // this.name = name; // } // // public int getWarehouseId() { // return this.warehouseId; // } // // public void setWarehouseId(int warehouseId) { // this.warehouseId = warehouseId; // } // public String getName() { // return this.name; // } // // public void setName(String name) { // this.name = name; // } // // // // // } // // Path: src/main/java/com/storage/mywarehouse/Entity/Product.java // public class Product implements java.io.Serializable { // // private static final long serialVersionUID = 1L; // // private int productId; // private String brand; // private String type; // private String description; // private double price; // // public Product() { // } // // public Product(int productId, String brand, String type, double price) { // this.productId = productId; // this.brand = brand; // this.type = type; // this.price = price; // } // // public Product(int productId, String brand, String type, String description, double price) { // this.productId = productId; // this.brand = brand; // this.type = type; // this.description = description; // this.price = price; // } // // public Product(String brand, String type, String description, double price) { // this.brand = brand; // this.type = type; // this.description = description; // this.price = price; // } // // public int getProductId() { // return this.productId; // } // // public void setProductId(int productId) { // this.productId = productId; // } // // public String getBrand() { // return this.brand; // } // // public void setBrand(String brand) { // this.brand = brand; // } // // public String getType() { // return this.type; // } // // public void setType(String type) { // this.type = type; // } // // public String getDescription() { // return this.description; // } // // public void setDescription(String description) { // this.description = description; // } // // public double getPrice() { // return this.price; // } // // public void setPrice(double price) { // this.price = price; // } // // } // // Path: src/main/java/com/storage/mywarehouse/Entity/Entry.java // public class Entry implements java.io.Serializable { // // // private int entryId; // private int warehouseId; // private int productId; // private int quantity; // // public Entry() { // } // // public Entry(int entryId, int warehouseId, int productId, int quantity) { // this.entryId = entryId; // this.warehouseId = warehouseId; // this.productId = productId; // this.quantity = quantity; // } // // public Entry(int warehouseId, int productId, int quantity) { // this.warehouseId = warehouseId; // this.productId = productId; // this.quantity = quantity; // } // // public int getEntryId() { // return this.entryId; // } // // public void setEntryId(int entryId) { // this.entryId = entryId; // } // public int getWarehouseId() { // return this.warehouseId; // } // // public void setWarehouseId(int warehouseId) { // this.warehouseId = warehouseId; // } // public int getProductId() { // return this.productId; // } // // public void setProductId(int productId) { // this.productId = productId; // } // public int getQuantity() { // return this.quantity; // } // // public void setQuantity(int quantity) { // this.quantity = quantity; // } // // // // // } // Path: src/test/java/com/storage/mywarehouse/Dao/EntryDaoTest.java import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.assertAll; import com.storage.mywarehouse.Entity.Warehouse; import com.storage.mywarehouse.Entity.Product; import com.storage.mywarehouse.Entity.Entry; import java.util.List; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.AfterEach; package com.storage.mywarehouse.Dao; public class EntryDaoTest { private static final int ZERO = 0; private static final int ONE = 1; private static final int TWO = 2; private static final int THREE = 3; private static final int NINE = 9; private static final String ANY = "ANY"; private static final String ANY2 = "ANY2"; private static final String ANY3 = "ANY3"; private static final double DOUBLE_VAL = 1.1; private Warehouse w1; private Product p1; private Product p2;
private Entry e1;
patroklossam/WareHouse
src/test/java/com/storage/mywarehouse/Dao/ProductDaoTest.java
// Path: src/main/java/com/storage/mywarehouse/Entity/Product.java // public class Product implements java.io.Serializable { // // private static final long serialVersionUID = 1L; // // private int productId; // private String brand; // private String type; // private String description; // private double price; // // public Product() { // } // // public Product(int productId, String brand, String type, double price) { // this.productId = productId; // this.brand = brand; // this.type = type; // this.price = price; // } // // public Product(int productId, String brand, String type, String description, double price) { // this.productId = productId; // this.brand = brand; // this.type = type; // this.description = description; // this.price = price; // } // // public Product(String brand, String type, String description, double price) { // this.brand = brand; // this.type = type; // this.description = description; // this.price = price; // } // // public int getProductId() { // return this.productId; // } // // public void setProductId(int productId) { // this.productId = productId; // } // // public String getBrand() { // return this.brand; // } // // public void setBrand(String brand) { // this.brand = brand; // } // // public String getType() { // return this.type; // } // // public void setType(String type) { // this.type = type; // } // // public String getDescription() { // return this.description; // } // // public void setDescription(String description) { // this.description = description; // } // // public double getPrice() { // return this.price; // } // // public void setPrice(double price) { // this.price = price; // } // // }
import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.assertAll; import com.storage.mywarehouse.Entity.Product; import java.util.List; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.AfterEach;
package com.storage.mywarehouse.Dao; public class ProductDaoTest { private static final int ZERO = 0; private static final int ONE = 1; private static final int TWO = 2; private static final String ANY = "ANY"; private static final String ANY2 = "ANY2"; private static final double DOUBLE_VAL = 1.1;
// Path: src/main/java/com/storage/mywarehouse/Entity/Product.java // public class Product implements java.io.Serializable { // // private static final long serialVersionUID = 1L; // // private int productId; // private String brand; // private String type; // private String description; // private double price; // // public Product() { // } // // public Product(int productId, String brand, String type, double price) { // this.productId = productId; // this.brand = brand; // this.type = type; // this.price = price; // } // // public Product(int productId, String brand, String type, String description, double price) { // this.productId = productId; // this.brand = brand; // this.type = type; // this.description = description; // this.price = price; // } // // public Product(String brand, String type, String description, double price) { // this.brand = brand; // this.type = type; // this.description = description; // this.price = price; // } // // public int getProductId() { // return this.productId; // } // // public void setProductId(int productId) { // this.productId = productId; // } // // public String getBrand() { // return this.brand; // } // // public void setBrand(String brand) { // this.brand = brand; // } // // public String getType() { // return this.type; // } // // public void setType(String type) { // this.type = type; // } // // public String getDescription() { // return this.description; // } // // public void setDescription(String description) { // this.description = description; // } // // public double getPrice() { // return this.price; // } // // public void setPrice(double price) { // this.price = price; // } // // } // Path: src/test/java/com/storage/mywarehouse/Dao/ProductDaoTest.java import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.assertAll; import com.storage.mywarehouse.Entity.Product; import java.util.List; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.AfterEach; package com.storage.mywarehouse.Dao; public class ProductDaoTest { private static final int ZERO = 0; private static final int ONE = 1; private static final int TWO = 2; private static final String ANY = "ANY"; private static final String ANY2 = "ANY2"; private static final double DOUBLE_VAL = 1.1;
private Product sut1;
patroklossam/WareHouse
src/test/java/com/storage/mywarehouse/Dao/CustomerDaoTest.java
// Path: src/main/java/com/storage/mywarehouse/Entity/Customer.java // public class Customer implements java.io.Serializable { // // // private int customerId; // private String name; // private String lastName; // private String occupation; // private double discount; // private String email; // private String city; // private String postal; // private String telephone; // // // public Customer() { // } // // public Customer(int customerId, String name, String lastName, String occupation, double discount, // String email, String city, String postal, String telephone) { // this.customerId = customerId; // this.name = name; // this.lastName = lastName; // this.occupation = occupation; // this.discount = discount; // this.email = email; // this.city = city; // this.postal = postal; // this.telephone = telephone; // } // // public int getCustomerId() { // return this.customerId; // } // // public void setCustomerId(int customerId) { // this.customerId = customerId; // } // public String getName() { // return this.name; // } // // public void setName(String name) { // this.name = name; // } // public String getLastName() { // return this.lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // public String getOccupation() { // return this.occupation; // } // // public void setOccupation(String occupation) { // this.occupation = occupation; // } // public double getDiscount() { // return this.discount; // } // // public void setDiscount(double discount) { // this.discount = discount; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getCity() { // return city; // } // // public void setCity(String city) { // this.city = city; // } // // public String getPostal() { // return postal; // } // // public void setPostal(String postal) { // this.postal = postal; // } // // public String getTelephone() { // return telephone; // } // // public void setTelephone(String telephone) { // this.telephone = telephone; // } // }
import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.assertAll; import com.storage.mywarehouse.Entity.Customer; import java.util.List; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.AfterEach;
package com.storage.mywarehouse.Dao; public class CustomerDaoTest { private static final int ZERO = 0; private static final int ONE = 1; private static final int TWO = 2; private static final String ANY = "ANY"; private static final String ANY2 = "ANY2"; private static final double DOUBLE_VAL = 1.1;
// Path: src/main/java/com/storage/mywarehouse/Entity/Customer.java // public class Customer implements java.io.Serializable { // // // private int customerId; // private String name; // private String lastName; // private String occupation; // private double discount; // private String email; // private String city; // private String postal; // private String telephone; // // // public Customer() { // } // // public Customer(int customerId, String name, String lastName, String occupation, double discount, // String email, String city, String postal, String telephone) { // this.customerId = customerId; // this.name = name; // this.lastName = lastName; // this.occupation = occupation; // this.discount = discount; // this.email = email; // this.city = city; // this.postal = postal; // this.telephone = telephone; // } // // public int getCustomerId() { // return this.customerId; // } // // public void setCustomerId(int customerId) { // this.customerId = customerId; // } // public String getName() { // return this.name; // } // // public void setName(String name) { // this.name = name; // } // public String getLastName() { // return this.lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // public String getOccupation() { // return this.occupation; // } // // public void setOccupation(String occupation) { // this.occupation = occupation; // } // public double getDiscount() { // return this.discount; // } // // public void setDiscount(double discount) { // this.discount = discount; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getCity() { // return city; // } // // public void setCity(String city) { // this.city = city; // } // // public String getPostal() { // return postal; // } // // public void setPostal(String postal) { // this.postal = postal; // } // // public String getTelephone() { // return telephone; // } // // public void setTelephone(String telephone) { // this.telephone = telephone; // } // } // Path: src/test/java/com/storage/mywarehouse/Dao/CustomerDaoTest.java import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.assertAll; import com.storage.mywarehouse.Entity.Customer; import java.util.List; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.AfterEach; package com.storage.mywarehouse.Dao; public class CustomerDaoTest { private static final int ZERO = 0; private static final int ONE = 1; private static final int TWO = 2; private static final String ANY = "ANY"; private static final String ANY2 = "ANY2"; private static final double DOUBLE_VAL = 1.1;
private Customer sut1;
patroklossam/WareHouse
src/main/java/com/storage/mywarehouse/Dao/CustomerDAO.java
// Path: src/main/java/com/storage/mywarehouse/Entity/Customer.java // public class Customer implements java.io.Serializable { // // // private int customerId; // private String name; // private String lastName; // private String occupation; // private double discount; // private String email; // private String city; // private String postal; // private String telephone; // // // public Customer() { // } // // public Customer(int customerId, String name, String lastName, String occupation, double discount, // String email, String city, String postal, String telephone) { // this.customerId = customerId; // this.name = name; // this.lastName = lastName; // this.occupation = occupation; // this.discount = discount; // this.email = email; // this.city = city; // this.postal = postal; // this.telephone = telephone; // } // // public int getCustomerId() { // return this.customerId; // } // // public void setCustomerId(int customerId) { // this.customerId = customerId; // } // public String getName() { // return this.name; // } // // public void setName(String name) { // this.name = name; // } // public String getLastName() { // return this.lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // public String getOccupation() { // return this.occupation; // } // // public void setOccupation(String occupation) { // this.occupation = occupation; // } // public double getDiscount() { // return this.discount; // } // // public void setDiscount(double discount) { // this.discount = discount; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getCity() { // return city; // } // // public void setCity(String city) { // this.city = city; // } // // public String getPostal() { // return postal; // } // // public void setPostal(String postal) { // this.postal = postal; // } // // public String getTelephone() { // return telephone; // } // // public void setTelephone(String telephone) { // this.telephone = telephone; // } // }
import com.storage.mywarehouse.Entity.Customer; import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.criterion.Order; import java.util.List;
package com.storage.mywarehouse.Dao; public class CustomerDAO { @SuppressWarnings("unchecked")
// Path: src/main/java/com/storage/mywarehouse/Entity/Customer.java // public class Customer implements java.io.Serializable { // // // private int customerId; // private String name; // private String lastName; // private String occupation; // private double discount; // private String email; // private String city; // private String postal; // private String telephone; // // // public Customer() { // } // // public Customer(int customerId, String name, String lastName, String occupation, double discount, // String email, String city, String postal, String telephone) { // this.customerId = customerId; // this.name = name; // this.lastName = lastName; // this.occupation = occupation; // this.discount = discount; // this.email = email; // this.city = city; // this.postal = postal; // this.telephone = telephone; // } // // public int getCustomerId() { // return this.customerId; // } // // public void setCustomerId(int customerId) { // this.customerId = customerId; // } // public String getName() { // return this.name; // } // // public void setName(String name) { // this.name = name; // } // public String getLastName() { // return this.lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // public String getOccupation() { // return this.occupation; // } // // public void setOccupation(String occupation) { // this.occupation = occupation; // } // public double getDiscount() { // return this.discount; // } // // public void setDiscount(double discount) { // this.discount = discount; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getCity() { // return city; // } // // public void setCity(String city) { // this.city = city; // } // // public String getPostal() { // return postal; // } // // public void setPostal(String postal) { // this.postal = postal; // } // // public String getTelephone() { // return telephone; // } // // public void setTelephone(String telephone) { // this.telephone = telephone; // } // } // Path: src/main/java/com/storage/mywarehouse/Dao/CustomerDAO.java import com.storage.mywarehouse.Entity.Customer; import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.criterion.Order; import java.util.List; package com.storage.mywarehouse.Dao; public class CustomerDAO { @SuppressWarnings("unchecked")
public static List<Customer> findAll() {
patroklossam/WareHouse
src/test/java/com/storage/mywarehouse/UtilsImportProductsFromCsvTest.java
// Path: src/main/java/com/storage/mywarehouse/Dao/ProductDAO.java // public class ProductDAO { // // @SuppressWarnings("unchecked") // public static List<Product> findAll() { // Session session = NewHibernateUtil.getSessionFactory().openSession(); // Transaction transaction = session.beginTransaction(); // List products = session.createCriteria(Product.class).list(); // transaction.commit(); // session.close(); // return products; // } // // @SuppressWarnings("unchecked") // public static List<Product> findAllByBrandAndTypeStartLike(String brand, String type) { // Session session = NewHibernateUtil.getSessionFactory().openSession(); // List products = session.createCriteria(Product.class).add( // and(eq("brand", brand), // Restrictions.like("type", type, MatchMode.START))) // .list(); // session.close(); // return products; // } // // public static Product findById(int productId) { // Session session = NewHibernateUtil.getSessionFactory().openSession(); // Transaction transaction = session.beginTransaction(); // List products = session.createCriteria(Product.class) // .add(Restrictions.eq("productId", productId)) // .list(); // Product pr = (Product) products.get(0); // transaction.commit(); // session.close(); // return pr; // } // // public static Product findByBrandAndName(String brand, String type) { // Session session = NewHibernateUtil.getSessionFactory().openSession(); // Transaction transaction = session.beginTransaction(); // Product existingProduct = (Product) session.createCriteria(Product.class) // .add(and(eq("brand", brand), eq("type", type))) // .uniqueResult(); // transaction.commit(); // session.close(); // return existingProduct; // } // // public static Product save(Product product) { // int productId; // Session session = NewHibernateUtil.getSessionFactory().openSession(); // Transaction transaction = session.beginTransaction(); // Product productWithHighestId = (Product) session.createCriteria(Product.class) // .addOrder(Order.desc("productId")) // .setMaxResults(1) // .uniqueResult(); // transaction.commit(); // if (productWithHighestId == null) { // productId = 0; // } else { // productId = productWithHighestId.getProductId() + 1; // } // product.setProductId(productId); // transaction = session.beginTransaction(); // session.save(product); // transaction.commit(); // session.close(); // return product; // } // // public static void deleteAll(List<Product> products) { // Session session = NewHibernateUtil.getSessionFactory().openSession(); // Transaction transaction = session.beginTransaction(); // for (Product p : products) { // session.delete(p); // } // transaction.commit(); // session.close(); // } // // public static void delete(Product product) { // Session session = NewHibernateUtil.getSessionFactory().openSession(); // Transaction transaction = session.beginTransaction(); // session.delete(product); // transaction.commit(); // session.close(); // } // } // // Path: src/main/java/com/storage/mywarehouse/Entity/Product.java // public class Product implements java.io.Serializable { // // private static final long serialVersionUID = 1L; // // private int productId; // private String brand; // private String type; // private String description; // private double price; // // public Product() { // } // // public Product(int productId, String brand, String type, double price) { // this.productId = productId; // this.brand = brand; // this.type = type; // this.price = price; // } // // public Product(int productId, String brand, String type, String description, double price) { // this.productId = productId; // this.brand = brand; // this.type = type; // this.description = description; // this.price = price; // } // // public Product(String brand, String type, String description, double price) { // this.brand = brand; // this.type = type; // this.description = description; // this.price = price; // } // // public int getProductId() { // return this.productId; // } // // public void setProductId(int productId) { // this.productId = productId; // } // // public String getBrand() { // return this.brand; // } // // public void setBrand(String brand) { // this.brand = brand; // } // // public String getType() { // return this.type; // } // // public void setType(String type) { // this.type = type; // } // // public String getDescription() { // return this.description; // } // // public void setDescription(String description) { // this.description = description; // } // // public double getPrice() { // return this.price; // } // // public void setPrice(double price) { // this.price = price; // } // // }
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasSize; import java.io.File; import java.io.IOException; import java.util.List; import com.storage.mywarehouse.Dao.ProductDAO; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import com.storage.mywarehouse.Entity.Product;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.storage.mywarehouse; /** * * @author veruz */ public class UtilsImportProductsFromCsvTest { private File file = new File("src/test/resources/products.csv"); @AfterEach public void tearDown() { deleteTestEntries(); } @Test public void testExistence() {
// Path: src/main/java/com/storage/mywarehouse/Dao/ProductDAO.java // public class ProductDAO { // // @SuppressWarnings("unchecked") // public static List<Product> findAll() { // Session session = NewHibernateUtil.getSessionFactory().openSession(); // Transaction transaction = session.beginTransaction(); // List products = session.createCriteria(Product.class).list(); // transaction.commit(); // session.close(); // return products; // } // // @SuppressWarnings("unchecked") // public static List<Product> findAllByBrandAndTypeStartLike(String brand, String type) { // Session session = NewHibernateUtil.getSessionFactory().openSession(); // List products = session.createCriteria(Product.class).add( // and(eq("brand", brand), // Restrictions.like("type", type, MatchMode.START))) // .list(); // session.close(); // return products; // } // // public static Product findById(int productId) { // Session session = NewHibernateUtil.getSessionFactory().openSession(); // Transaction transaction = session.beginTransaction(); // List products = session.createCriteria(Product.class) // .add(Restrictions.eq("productId", productId)) // .list(); // Product pr = (Product) products.get(0); // transaction.commit(); // session.close(); // return pr; // } // // public static Product findByBrandAndName(String brand, String type) { // Session session = NewHibernateUtil.getSessionFactory().openSession(); // Transaction transaction = session.beginTransaction(); // Product existingProduct = (Product) session.createCriteria(Product.class) // .add(and(eq("brand", brand), eq("type", type))) // .uniqueResult(); // transaction.commit(); // session.close(); // return existingProduct; // } // // public static Product save(Product product) { // int productId; // Session session = NewHibernateUtil.getSessionFactory().openSession(); // Transaction transaction = session.beginTransaction(); // Product productWithHighestId = (Product) session.createCriteria(Product.class) // .addOrder(Order.desc("productId")) // .setMaxResults(1) // .uniqueResult(); // transaction.commit(); // if (productWithHighestId == null) { // productId = 0; // } else { // productId = productWithHighestId.getProductId() + 1; // } // product.setProductId(productId); // transaction = session.beginTransaction(); // session.save(product); // transaction.commit(); // session.close(); // return product; // } // // public static void deleteAll(List<Product> products) { // Session session = NewHibernateUtil.getSessionFactory().openSession(); // Transaction transaction = session.beginTransaction(); // for (Product p : products) { // session.delete(p); // } // transaction.commit(); // session.close(); // } // // public static void delete(Product product) { // Session session = NewHibernateUtil.getSessionFactory().openSession(); // Transaction transaction = session.beginTransaction(); // session.delete(product); // transaction.commit(); // session.close(); // } // } // // Path: src/main/java/com/storage/mywarehouse/Entity/Product.java // public class Product implements java.io.Serializable { // // private static final long serialVersionUID = 1L; // // private int productId; // private String brand; // private String type; // private String description; // private double price; // // public Product() { // } // // public Product(int productId, String brand, String type, double price) { // this.productId = productId; // this.brand = brand; // this.type = type; // this.price = price; // } // // public Product(int productId, String brand, String type, String description, double price) { // this.productId = productId; // this.brand = brand; // this.type = type; // this.description = description; // this.price = price; // } // // public Product(String brand, String type, String description, double price) { // this.brand = brand; // this.type = type; // this.description = description; // this.price = price; // } // // public int getProductId() { // return this.productId; // } // // public void setProductId(int productId) { // this.productId = productId; // } // // public String getBrand() { // return this.brand; // } // // public void setBrand(String brand) { // this.brand = brand; // } // // public String getType() { // return this.type; // } // // public void setType(String type) { // this.type = type; // } // // public String getDescription() { // return this.description; // } // // public void setDescription(String description) { // this.description = description; // } // // public double getPrice() { // return this.price; // } // // public void setPrice(double price) { // this.price = price; // } // // } // Path: src/test/java/com/storage/mywarehouse/UtilsImportProductsFromCsvTest.java import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasSize; import java.io.File; import java.io.IOException; import java.util.List; import com.storage.mywarehouse.Dao.ProductDAO; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import com.storage.mywarehouse.Entity.Product; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.storage.mywarehouse; /** * * @author veruz */ public class UtilsImportProductsFromCsvTest { private File file = new File("src/test/resources/products.csv"); @AfterEach public void tearDown() { deleteTestEntries(); } @Test public void testExistence() {
List<Product> products = ProductDAO.findAllByBrandAndTypeStartLike("unit", "test");
patroklossam/WareHouse
src/test/java/com/storage/mywarehouse/UtilsImportProductsFromCsvTest.java
// Path: src/main/java/com/storage/mywarehouse/Dao/ProductDAO.java // public class ProductDAO { // // @SuppressWarnings("unchecked") // public static List<Product> findAll() { // Session session = NewHibernateUtil.getSessionFactory().openSession(); // Transaction transaction = session.beginTransaction(); // List products = session.createCriteria(Product.class).list(); // transaction.commit(); // session.close(); // return products; // } // // @SuppressWarnings("unchecked") // public static List<Product> findAllByBrandAndTypeStartLike(String brand, String type) { // Session session = NewHibernateUtil.getSessionFactory().openSession(); // List products = session.createCriteria(Product.class).add( // and(eq("brand", brand), // Restrictions.like("type", type, MatchMode.START))) // .list(); // session.close(); // return products; // } // // public static Product findById(int productId) { // Session session = NewHibernateUtil.getSessionFactory().openSession(); // Transaction transaction = session.beginTransaction(); // List products = session.createCriteria(Product.class) // .add(Restrictions.eq("productId", productId)) // .list(); // Product pr = (Product) products.get(0); // transaction.commit(); // session.close(); // return pr; // } // // public static Product findByBrandAndName(String brand, String type) { // Session session = NewHibernateUtil.getSessionFactory().openSession(); // Transaction transaction = session.beginTransaction(); // Product existingProduct = (Product) session.createCriteria(Product.class) // .add(and(eq("brand", brand), eq("type", type))) // .uniqueResult(); // transaction.commit(); // session.close(); // return existingProduct; // } // // public static Product save(Product product) { // int productId; // Session session = NewHibernateUtil.getSessionFactory().openSession(); // Transaction transaction = session.beginTransaction(); // Product productWithHighestId = (Product) session.createCriteria(Product.class) // .addOrder(Order.desc("productId")) // .setMaxResults(1) // .uniqueResult(); // transaction.commit(); // if (productWithHighestId == null) { // productId = 0; // } else { // productId = productWithHighestId.getProductId() + 1; // } // product.setProductId(productId); // transaction = session.beginTransaction(); // session.save(product); // transaction.commit(); // session.close(); // return product; // } // // public static void deleteAll(List<Product> products) { // Session session = NewHibernateUtil.getSessionFactory().openSession(); // Transaction transaction = session.beginTransaction(); // for (Product p : products) { // session.delete(p); // } // transaction.commit(); // session.close(); // } // // public static void delete(Product product) { // Session session = NewHibernateUtil.getSessionFactory().openSession(); // Transaction transaction = session.beginTransaction(); // session.delete(product); // transaction.commit(); // session.close(); // } // } // // Path: src/main/java/com/storage/mywarehouse/Entity/Product.java // public class Product implements java.io.Serializable { // // private static final long serialVersionUID = 1L; // // private int productId; // private String brand; // private String type; // private String description; // private double price; // // public Product() { // } // // public Product(int productId, String brand, String type, double price) { // this.productId = productId; // this.brand = brand; // this.type = type; // this.price = price; // } // // public Product(int productId, String brand, String type, String description, double price) { // this.productId = productId; // this.brand = brand; // this.type = type; // this.description = description; // this.price = price; // } // // public Product(String brand, String type, String description, double price) { // this.brand = brand; // this.type = type; // this.description = description; // this.price = price; // } // // public int getProductId() { // return this.productId; // } // // public void setProductId(int productId) { // this.productId = productId; // } // // public String getBrand() { // return this.brand; // } // // public void setBrand(String brand) { // this.brand = brand; // } // // public String getType() { // return this.type; // } // // public void setType(String type) { // this.type = type; // } // // public String getDescription() { // return this.description; // } // // public void setDescription(String description) { // this.description = description; // } // // public double getPrice() { // return this.price; // } // // public void setPrice(double price) { // this.price = price; // } // // }
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasSize; import java.io.File; import java.io.IOException; import java.util.List; import com.storage.mywarehouse.Dao.ProductDAO; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import com.storage.mywarehouse.Entity.Product;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.storage.mywarehouse; /** * * @author veruz */ public class UtilsImportProductsFromCsvTest { private File file = new File("src/test/resources/products.csv"); @AfterEach public void tearDown() { deleteTestEntries(); } @Test public void testExistence() {
// Path: src/main/java/com/storage/mywarehouse/Dao/ProductDAO.java // public class ProductDAO { // // @SuppressWarnings("unchecked") // public static List<Product> findAll() { // Session session = NewHibernateUtil.getSessionFactory().openSession(); // Transaction transaction = session.beginTransaction(); // List products = session.createCriteria(Product.class).list(); // transaction.commit(); // session.close(); // return products; // } // // @SuppressWarnings("unchecked") // public static List<Product> findAllByBrandAndTypeStartLike(String brand, String type) { // Session session = NewHibernateUtil.getSessionFactory().openSession(); // List products = session.createCriteria(Product.class).add( // and(eq("brand", brand), // Restrictions.like("type", type, MatchMode.START))) // .list(); // session.close(); // return products; // } // // public static Product findById(int productId) { // Session session = NewHibernateUtil.getSessionFactory().openSession(); // Transaction transaction = session.beginTransaction(); // List products = session.createCriteria(Product.class) // .add(Restrictions.eq("productId", productId)) // .list(); // Product pr = (Product) products.get(0); // transaction.commit(); // session.close(); // return pr; // } // // public static Product findByBrandAndName(String brand, String type) { // Session session = NewHibernateUtil.getSessionFactory().openSession(); // Transaction transaction = session.beginTransaction(); // Product existingProduct = (Product) session.createCriteria(Product.class) // .add(and(eq("brand", brand), eq("type", type))) // .uniqueResult(); // transaction.commit(); // session.close(); // return existingProduct; // } // // public static Product save(Product product) { // int productId; // Session session = NewHibernateUtil.getSessionFactory().openSession(); // Transaction transaction = session.beginTransaction(); // Product productWithHighestId = (Product) session.createCriteria(Product.class) // .addOrder(Order.desc("productId")) // .setMaxResults(1) // .uniqueResult(); // transaction.commit(); // if (productWithHighestId == null) { // productId = 0; // } else { // productId = productWithHighestId.getProductId() + 1; // } // product.setProductId(productId); // transaction = session.beginTransaction(); // session.save(product); // transaction.commit(); // session.close(); // return product; // } // // public static void deleteAll(List<Product> products) { // Session session = NewHibernateUtil.getSessionFactory().openSession(); // Transaction transaction = session.beginTransaction(); // for (Product p : products) { // session.delete(p); // } // transaction.commit(); // session.close(); // } // // public static void delete(Product product) { // Session session = NewHibernateUtil.getSessionFactory().openSession(); // Transaction transaction = session.beginTransaction(); // session.delete(product); // transaction.commit(); // session.close(); // } // } // // Path: src/main/java/com/storage/mywarehouse/Entity/Product.java // public class Product implements java.io.Serializable { // // private static final long serialVersionUID = 1L; // // private int productId; // private String brand; // private String type; // private String description; // private double price; // // public Product() { // } // // public Product(int productId, String brand, String type, double price) { // this.productId = productId; // this.brand = brand; // this.type = type; // this.price = price; // } // // public Product(int productId, String brand, String type, String description, double price) { // this.productId = productId; // this.brand = brand; // this.type = type; // this.description = description; // this.price = price; // } // // public Product(String brand, String type, String description, double price) { // this.brand = brand; // this.type = type; // this.description = description; // this.price = price; // } // // public int getProductId() { // return this.productId; // } // // public void setProductId(int productId) { // this.productId = productId; // } // // public String getBrand() { // return this.brand; // } // // public void setBrand(String brand) { // this.brand = brand; // } // // public String getType() { // return this.type; // } // // public void setType(String type) { // this.type = type; // } // // public String getDescription() { // return this.description; // } // // public void setDescription(String description) { // this.description = description; // } // // public double getPrice() { // return this.price; // } // // public void setPrice(double price) { // this.price = price; // } // // } // Path: src/test/java/com/storage/mywarehouse/UtilsImportProductsFromCsvTest.java import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasSize; import java.io.File; import java.io.IOException; import java.util.List; import com.storage.mywarehouse.Dao.ProductDAO; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import com.storage.mywarehouse.Entity.Product; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.storage.mywarehouse; /** * * @author veruz */ public class UtilsImportProductsFromCsvTest { private File file = new File("src/test/resources/products.csv"); @AfterEach public void tearDown() { deleteTestEntries(); } @Test public void testExistence() {
List<Product> products = ProductDAO.findAllByBrandAndTypeStartLike("unit", "test");
patroklossam/WareHouse
src/main/java/com/storage/mywarehouse/Dao/ProductDAO.java
// Path: src/main/java/com/storage/mywarehouse/Entity/Product.java // public class Product implements java.io.Serializable { // // private static final long serialVersionUID = 1L; // // private int productId; // private String brand; // private String type; // private String description; // private double price; // // public Product() { // } // // public Product(int productId, String brand, String type, double price) { // this.productId = productId; // this.brand = brand; // this.type = type; // this.price = price; // } // // public Product(int productId, String brand, String type, String description, double price) { // this.productId = productId; // this.brand = brand; // this.type = type; // this.description = description; // this.price = price; // } // // public Product(String brand, String type, String description, double price) { // this.brand = brand; // this.type = type; // this.description = description; // this.price = price; // } // // public int getProductId() { // return this.productId; // } // // public void setProductId(int productId) { // this.productId = productId; // } // // public String getBrand() { // return this.brand; // } // // public void setBrand(String brand) { // this.brand = brand; // } // // public String getType() { // return this.type; // } // // public void setType(String type) { // this.type = type; // } // // public String getDescription() { // return this.description; // } // // public void setDescription(String description) { // this.description = description; // } // // public double getPrice() { // return this.price; // } // // public void setPrice(double price) { // this.price = price; // } // // }
import com.storage.mywarehouse.Entity.Product; import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.criterion.MatchMode; import org.hibernate.criterion.Order; import org.hibernate.criterion.Restrictions; import java.util.List; import static org.hibernate.criterion.Restrictions.and; import static org.hibernate.criterion.Restrictions.eq;
package com.storage.mywarehouse.Dao; public class ProductDAO { @SuppressWarnings("unchecked")
// Path: src/main/java/com/storage/mywarehouse/Entity/Product.java // public class Product implements java.io.Serializable { // // private static final long serialVersionUID = 1L; // // private int productId; // private String brand; // private String type; // private String description; // private double price; // // public Product() { // } // // public Product(int productId, String brand, String type, double price) { // this.productId = productId; // this.brand = brand; // this.type = type; // this.price = price; // } // // public Product(int productId, String brand, String type, String description, double price) { // this.productId = productId; // this.brand = brand; // this.type = type; // this.description = description; // this.price = price; // } // // public Product(String brand, String type, String description, double price) { // this.brand = brand; // this.type = type; // this.description = description; // this.price = price; // } // // public int getProductId() { // return this.productId; // } // // public void setProductId(int productId) { // this.productId = productId; // } // // public String getBrand() { // return this.brand; // } // // public void setBrand(String brand) { // this.brand = brand; // } // // public String getType() { // return this.type; // } // // public void setType(String type) { // this.type = type; // } // // public String getDescription() { // return this.description; // } // // public void setDescription(String description) { // this.description = description; // } // // public double getPrice() { // return this.price; // } // // public void setPrice(double price) { // this.price = price; // } // // } // Path: src/main/java/com/storage/mywarehouse/Dao/ProductDAO.java import com.storage.mywarehouse.Entity.Product; import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.criterion.MatchMode; import org.hibernate.criterion.Order; import org.hibernate.criterion.Restrictions; import java.util.List; import static org.hibernate.criterion.Restrictions.and; import static org.hibernate.criterion.Restrictions.eq; package com.storage.mywarehouse.Dao; public class ProductDAO { @SuppressWarnings("unchecked")
public static List<Product> findAll() {
patroklossam/WareHouse
src/main/java/com/storage/mywarehouse/Dao/EntryDAO.java
// Path: src/main/java/com/storage/mywarehouse/Entity/Entry.java // public class Entry implements java.io.Serializable { // // // private int entryId; // private int warehouseId; // private int productId; // private int quantity; // // public Entry() { // } // // public Entry(int entryId, int warehouseId, int productId, int quantity) { // this.entryId = entryId; // this.warehouseId = warehouseId; // this.productId = productId; // this.quantity = quantity; // } // // public Entry(int warehouseId, int productId, int quantity) { // this.warehouseId = warehouseId; // this.productId = productId; // this.quantity = quantity; // } // // public int getEntryId() { // return this.entryId; // } // // public void setEntryId(int entryId) { // this.entryId = entryId; // } // public int getWarehouseId() { // return this.warehouseId; // } // // public void setWarehouseId(int warehouseId) { // this.warehouseId = warehouseId; // } // public int getProductId() { // return this.productId; // } // // public void setProductId(int productId) { // this.productId = productId; // } // public int getQuantity() { // return this.quantity; // } // // public void setQuantity(int quantity) { // this.quantity = quantity; // } // // // // // } // // Path: src/main/java/com/storage/mywarehouse/Entity/Product.java // public class Product implements java.io.Serializable { // // private static final long serialVersionUID = 1L; // // private int productId; // private String brand; // private String type; // private String description; // private double price; // // public Product() { // } // // public Product(int productId, String brand, String type, double price) { // this.productId = productId; // this.brand = brand; // this.type = type; // this.price = price; // } // // public Product(int productId, String brand, String type, String description, double price) { // this.productId = productId; // this.brand = brand; // this.type = type; // this.description = description; // this.price = price; // } // // public Product(String brand, String type, String description, double price) { // this.brand = brand; // this.type = type; // this.description = description; // this.price = price; // } // // public int getProductId() { // return this.productId; // } // // public void setProductId(int productId) { // this.productId = productId; // } // // public String getBrand() { // return this.brand; // } // // public void setBrand(String brand) { // this.brand = brand; // } // // public String getType() { // return this.type; // } // // public void setType(String type) { // this.type = type; // } // // public String getDescription() { // return this.description; // } // // public void setDescription(String description) { // this.description = description; // } // // public double getPrice() { // return this.price; // } // // public void setPrice(double price) { // this.price = price; // } // // }
import com.storage.mywarehouse.Entity.Entry; import com.storage.mywarehouse.Entity.Product; import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.criterion.MatchMode; import org.hibernate.criterion.Order; import org.hibernate.criterion.Restrictions; import java.util.List; import static org.hibernate.criterion.Restrictions.and; import static org.hibernate.criterion.Restrictions.eq;
package com.storage.mywarehouse.Dao; public class EntryDAO { @SuppressWarnings("unchecked")
// Path: src/main/java/com/storage/mywarehouse/Entity/Entry.java // public class Entry implements java.io.Serializable { // // // private int entryId; // private int warehouseId; // private int productId; // private int quantity; // // public Entry() { // } // // public Entry(int entryId, int warehouseId, int productId, int quantity) { // this.entryId = entryId; // this.warehouseId = warehouseId; // this.productId = productId; // this.quantity = quantity; // } // // public Entry(int warehouseId, int productId, int quantity) { // this.warehouseId = warehouseId; // this.productId = productId; // this.quantity = quantity; // } // // public int getEntryId() { // return this.entryId; // } // // public void setEntryId(int entryId) { // this.entryId = entryId; // } // public int getWarehouseId() { // return this.warehouseId; // } // // public void setWarehouseId(int warehouseId) { // this.warehouseId = warehouseId; // } // public int getProductId() { // return this.productId; // } // // public void setProductId(int productId) { // this.productId = productId; // } // public int getQuantity() { // return this.quantity; // } // // public void setQuantity(int quantity) { // this.quantity = quantity; // } // // // // // } // // Path: src/main/java/com/storage/mywarehouse/Entity/Product.java // public class Product implements java.io.Serializable { // // private static final long serialVersionUID = 1L; // // private int productId; // private String brand; // private String type; // private String description; // private double price; // // public Product() { // } // // public Product(int productId, String brand, String type, double price) { // this.productId = productId; // this.brand = brand; // this.type = type; // this.price = price; // } // // public Product(int productId, String brand, String type, String description, double price) { // this.productId = productId; // this.brand = brand; // this.type = type; // this.description = description; // this.price = price; // } // // public Product(String brand, String type, String description, double price) { // this.brand = brand; // this.type = type; // this.description = description; // this.price = price; // } // // public int getProductId() { // return this.productId; // } // // public void setProductId(int productId) { // this.productId = productId; // } // // public String getBrand() { // return this.brand; // } // // public void setBrand(String brand) { // this.brand = brand; // } // // public String getType() { // return this.type; // } // // public void setType(String type) { // this.type = type; // } // // public String getDescription() { // return this.description; // } // // public void setDescription(String description) { // this.description = description; // } // // public double getPrice() { // return this.price; // } // // public void setPrice(double price) { // this.price = price; // } // // } // Path: src/main/java/com/storage/mywarehouse/Dao/EntryDAO.java import com.storage.mywarehouse.Entity.Entry; import com.storage.mywarehouse.Entity.Product; import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.criterion.MatchMode; import org.hibernate.criterion.Order; import org.hibernate.criterion.Restrictions; import java.util.List; import static org.hibernate.criterion.Restrictions.and; import static org.hibernate.criterion.Restrictions.eq; package com.storage.mywarehouse.Dao; public class EntryDAO { @SuppressWarnings("unchecked")
public static List<Entry> findByWarehouseId(int warehouseId) {
patroklossam/WareHouse
src/main/java/com/storage/mywarehouse/Dao/QuantityHistoryViewDAO.java
// Path: src/main/java/com/storage/mywarehouse/View/QuantityHistoryView.java // public class QuantityHistoryView implements java.io.Serializable { // // // private int id; // private String warehouse; // private String brand; // private String type; // private int quantity; // private Date date; // // public QuantityHistoryView() { // } // // // public QuantityHistoryView(int id, String warehouse, String brand, String type) { // this.id = id; // this.warehouse = warehouse; // this.brand = brand; // this.type = type; // } // public QuantityHistoryView(int id, String warehouse, String brand, String type, int quantity, Date date) { // this.id = id; // this.warehouse = warehouse; // this.brand = brand; // this.type = type; // this.quantity = quantity; // this.date = date; // } // // public int getId() { // return this.id; // } // // public void setId(int id) { // this.id = id; // } // public String getWarehouse() { // return this.warehouse; // } // // public void setWarehouse(String warehouse) { // this.warehouse = warehouse; // } // public String getBrand() { // return this.brand; // } // // public void setBrand(String brand) { // this.brand = brand; // } // public String getType() { // return this.type; // } // // public void setType(String type) { // this.type = type; // } // public int getQuantity() { // return this.quantity; // } // // public void setQuantity(int quantity) { // this.quantity = quantity; // } // public Date getDate() { // return this.date; // } // // public void setDate(Date date) { // this.date = date; // } // // public String toString(){ // return warehouse+"\t"+brand+"\t"+type+"\t"+date+"\t"+quantity; // } // // // // }
import com.storage.mywarehouse.View.QuantityHistoryView; import org.hibernate.Session; import org.hibernate.criterion.Order; import java.util.List;
package com.storage.mywarehouse.Dao; public class QuantityHistoryViewDAO { @SuppressWarnings("unchecked")
// Path: src/main/java/com/storage/mywarehouse/View/QuantityHistoryView.java // public class QuantityHistoryView implements java.io.Serializable { // // // private int id; // private String warehouse; // private String brand; // private String type; // private int quantity; // private Date date; // // public QuantityHistoryView() { // } // // // public QuantityHistoryView(int id, String warehouse, String brand, String type) { // this.id = id; // this.warehouse = warehouse; // this.brand = brand; // this.type = type; // } // public QuantityHistoryView(int id, String warehouse, String brand, String type, int quantity, Date date) { // this.id = id; // this.warehouse = warehouse; // this.brand = brand; // this.type = type; // this.quantity = quantity; // this.date = date; // } // // public int getId() { // return this.id; // } // // public void setId(int id) { // this.id = id; // } // public String getWarehouse() { // return this.warehouse; // } // // public void setWarehouse(String warehouse) { // this.warehouse = warehouse; // } // public String getBrand() { // return this.brand; // } // // public void setBrand(String brand) { // this.brand = brand; // } // public String getType() { // return this.type; // } // // public void setType(String type) { // this.type = type; // } // public int getQuantity() { // return this.quantity; // } // // public void setQuantity(int quantity) { // this.quantity = quantity; // } // public Date getDate() { // return this.date; // } // // public void setDate(Date date) { // this.date = date; // } // // public String toString(){ // return warehouse+"\t"+brand+"\t"+type+"\t"+date+"\t"+quantity; // } // // // // } // Path: src/main/java/com/storage/mywarehouse/Dao/QuantityHistoryViewDAO.java import com.storage.mywarehouse.View.QuantityHistoryView; import org.hibernate.Session; import org.hibernate.criterion.Order; import java.util.List; package com.storage.mywarehouse.Dao; public class QuantityHistoryViewDAO { @SuppressWarnings("unchecked")
public static List<QuantityHistoryView> findAll() {
patroklossam/WareHouse
src/main/java/com/storage/mywarehouse/Dao/WarehouseEntryDAO.java
// Path: src/main/java/com/storage/mywarehouse/View/WarehouseEntry.java // public class WarehouseEntry implements java.io.Serializable { // // // private int id; // private int productId; // private String brand; // private String type; // private int quantity; // private double price; // private int warehouseId; // // public WarehouseEntry() { // } // // // public WarehouseEntry(int id, String brand, String type, double price) { // this.id = id; // this.brand = brand; // this.type = type; // this.price = price; // } // public WarehouseEntry(int id, int productId, String brand, String type, int quantity, double price, int warehouseId) { // this.id = id; // this.productId = productId; // this.brand = brand; // this.type = type; // this.quantity = quantity; // this.price = price; // this.warehouseId = warehouseId; // } // // public int getId() { // return this.id; // } // // public void setId(int id) { // this.id = id; // } // public int getProductId() { // return this.productId; // } // // public void setProductId(int productId) { // this.productId = productId; // } // public String getBrand() { // return this.brand; // } // // public void setBrand(String brand) { // this.brand = brand; // } // public String getType() { // return this.type; // } // // public void setType(String type) { // this.type = type; // } // public int getQuantity() { // return this.quantity; // } // // public void setQuantity(int quantity) { // this.quantity = quantity; // } // public double getPrice() { // return this.price; // } // // public void setPrice(double price) { // this.price = price; // } // public int getWarehouseId() { // return this.warehouseId; // } // // public void setWarehouseId(int warehouseId) { // this.warehouseId = warehouseId; // } // // // // // }
import com.storage.mywarehouse.View.WarehouseEntry; import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.criterion.Restrictions; import java.util.List;
package com.storage.mywarehouse.Dao; public class WarehouseEntryDAO { @SuppressWarnings("unchecked")
// Path: src/main/java/com/storage/mywarehouse/View/WarehouseEntry.java // public class WarehouseEntry implements java.io.Serializable { // // // private int id; // private int productId; // private String brand; // private String type; // private int quantity; // private double price; // private int warehouseId; // // public WarehouseEntry() { // } // // // public WarehouseEntry(int id, String brand, String type, double price) { // this.id = id; // this.brand = brand; // this.type = type; // this.price = price; // } // public WarehouseEntry(int id, int productId, String brand, String type, int quantity, double price, int warehouseId) { // this.id = id; // this.productId = productId; // this.brand = brand; // this.type = type; // this.quantity = quantity; // this.price = price; // this.warehouseId = warehouseId; // } // // public int getId() { // return this.id; // } // // public void setId(int id) { // this.id = id; // } // public int getProductId() { // return this.productId; // } // // public void setProductId(int productId) { // this.productId = productId; // } // public String getBrand() { // return this.brand; // } // // public void setBrand(String brand) { // this.brand = brand; // } // public String getType() { // return this.type; // } // // public void setType(String type) { // this.type = type; // } // public int getQuantity() { // return this.quantity; // } // // public void setQuantity(int quantity) { // this.quantity = quantity; // } // public double getPrice() { // return this.price; // } // // public void setPrice(double price) { // this.price = price; // } // public int getWarehouseId() { // return this.warehouseId; // } // // public void setWarehouseId(int warehouseId) { // this.warehouseId = warehouseId; // } // // // // // } // Path: src/main/java/com/storage/mywarehouse/Dao/WarehouseEntryDAO.java import com.storage.mywarehouse.View.WarehouseEntry; import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.criterion.Restrictions; import java.util.List; package com.storage.mywarehouse.Dao; public class WarehouseEntryDAO { @SuppressWarnings("unchecked")
public static List<WarehouseEntry> findByWarehouseId(int warehouseId) {
patroklossam/WareHouse
src/test/java/com/storage/mywarehouse/Dao/WarehouseDaoTest.java
// Path: src/main/java/com/storage/mywarehouse/Entity/Warehouse.java // public class Warehouse implements java.io.Serializable { // // // private int warehouseId; // private String name; // // public Warehouse() { // } // // public Warehouse(int warehouseId, String name) { // this.warehouseId = warehouseId; // this.name = name; // } // // public Warehouse(String name) { // this.name = name; // } // // public int getWarehouseId() { // return this.warehouseId; // } // // public void setWarehouseId(int warehouseId) { // this.warehouseId = warehouseId; // } // public String getName() { // return this.name; // } // // public void setName(String name) { // this.name = name; // } // // // // // }
import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.assertAll; import com.storage.mywarehouse.Entity.Warehouse; import java.util.List; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.AfterEach;
package com.storage.mywarehouse.Dao; public class WarehouseDaoTest { private static final int ZERO = 0; private static final int ONE = 1; private static final int TWO = 2; private static final int THREE = 3; private static final String ANY = "ANY"; private static final String ANY2 = "ANY2"; private static final String ANY3 = "ANY3"; private static final double DOUBLE_VAL = 1.1;
// Path: src/main/java/com/storage/mywarehouse/Entity/Warehouse.java // public class Warehouse implements java.io.Serializable { // // // private int warehouseId; // private String name; // // public Warehouse() { // } // // public Warehouse(int warehouseId, String name) { // this.warehouseId = warehouseId; // this.name = name; // } // // public Warehouse(String name) { // this.name = name; // } // // public int getWarehouseId() { // return this.warehouseId; // } // // public void setWarehouseId(int warehouseId) { // this.warehouseId = warehouseId; // } // public String getName() { // return this.name; // } // // public void setName(String name) { // this.name = name; // } // // // // // } // Path: src/test/java/com/storage/mywarehouse/Dao/WarehouseDaoTest.java import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.assertAll; import com.storage.mywarehouse.Entity.Warehouse; import java.util.List; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.AfterEach; package com.storage.mywarehouse.Dao; public class WarehouseDaoTest { private static final int ZERO = 0; private static final int ONE = 1; private static final int TWO = 2; private static final int THREE = 3; private static final String ANY = "ANY"; private static final String ANY2 = "ANY2"; private static final String ANY3 = "ANY3"; private static final double DOUBLE_VAL = 1.1;
private Warehouse sut1;
patroklossam/WareHouse
src/main/java/com/storage/mywarehouse/Dao/WarehouseDAO.java
// Path: src/main/java/com/storage/mywarehouse/Entity/Warehouse.java // public class Warehouse implements java.io.Serializable { // // // private int warehouseId; // private String name; // // public Warehouse() { // } // // public Warehouse(int warehouseId, String name) { // this.warehouseId = warehouseId; // this.name = name; // } // // public Warehouse(String name) { // this.name = name; // } // // public int getWarehouseId() { // return this.warehouseId; // } // // public void setWarehouseId(int warehouseId) { // this.warehouseId = warehouseId; // } // public String getName() { // return this.name; // } // // public void setName(String name) { // this.name = name; // } // // // // // }
import com.storage.mywarehouse.Entity.Warehouse; import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.criterion.Order; import java.util.List; import static org.hibernate.criterion.Restrictions.and; import static org.hibernate.criterion.Restrictions.eq;
package com.storage.mywarehouse.Dao; public class WarehouseDAO { @SuppressWarnings("unchecked")
// Path: src/main/java/com/storage/mywarehouse/Entity/Warehouse.java // public class Warehouse implements java.io.Serializable { // // // private int warehouseId; // private String name; // // public Warehouse() { // } // // public Warehouse(int warehouseId, String name) { // this.warehouseId = warehouseId; // this.name = name; // } // // public Warehouse(String name) { // this.name = name; // } // // public int getWarehouseId() { // return this.warehouseId; // } // // public void setWarehouseId(int warehouseId) { // this.warehouseId = warehouseId; // } // public String getName() { // return this.name; // } // // public void setName(String name) { // this.name = name; // } // // // // // } // Path: src/main/java/com/storage/mywarehouse/Dao/WarehouseDAO.java import com.storage.mywarehouse.Entity.Warehouse; import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.criterion.Order; import java.util.List; import static org.hibernate.criterion.Restrictions.and; import static org.hibernate.criterion.Restrictions.eq; package com.storage.mywarehouse.Dao; public class WarehouseDAO { @SuppressWarnings("unchecked")
public static List<Warehouse> findAll() {
asher-stern/CRF
src/main/java/com/asher_stern/crf/crf/CrfModel.java
// Path: src/main/java/com/asher_stern/crf/crf/filters/CrfFeaturesAndFilters.java // public class CrfFeaturesAndFilters<K, G> implements Serializable // { // private static final long serialVersionUID = 5815029007668803039L; // // public CrfFeaturesAndFilters(FilterFactory<K, G> filterFactory, // CrfFilteredFeature<K, G>[] filteredFeatures, // Map<Filter<K, G>, Set<Integer>> mapActiveFeatures, // Set<Integer> indexesOfFeaturesWithNoFilter) // { // super(); // this.filterFactory = filterFactory; // this.filteredFeatures = filteredFeatures; // this.mapActiveFeatures = mapActiveFeatures; // this.indexesOfFeaturesWithNoFilter = indexesOfFeaturesWithNoFilter; // } // // // /** // * Returns the {@link FilterFactory} to be used with the features encapsulated here, for efficient feature-value calculations. // */ // public FilterFactory<K, G> getFilterFactory() // { // return filterFactory; // } // // /** // * An array of all the features in the CRF model. // */ // public CrfFilteredFeature<K, G>[] getFilteredFeatures() // { // return filteredFeatures; // } // // /** // * Returns a map from each filter to a set of indexes of features, that might be active if their filters are equal to // * this filter. "Active" means that they might return non-zero. // */ // public Map<Filter<K, G>, Set<Integer>> getMapActiveFeatures() // { // return mapActiveFeatures; // } // // /** // * Returns a set of indexes of features that might be active for any type of input. These features have no filters. // */ // public Set<Integer> getIndexesOfFeaturesWithNoFilter() // { // return indexesOfFeaturesWithNoFilter; // } // // // // // private final FilterFactory<K, G> filterFactory; // private final CrfFilteredFeature<K, G>[] filteredFeatures; // private final Map<Filter<K, G>, Set<Integer>> mapActiveFeatures; // private final Set<Integer> indexesOfFeaturesWithNoFilter; // }
import java.io.Serializable; import java.math.BigDecimal; import java.util.ArrayList; import com.asher_stern.crf.crf.filters.CrfFeaturesAndFilters;
package com.asher_stern.crf.crf; /** * This class encapsulates the set of all possible tags, the list of features (f_i), and the list of parameters (\theta_i). * * @author Asher Stern * Date: Nov 8, 2014 * * @param <K> token type - must implement equals() and hashCode() * @param <G> tag type - must implement equals() and hashCode() */ public class CrfModel<K,G> implements Serializable // K = token, G = tag { private static final long serialVersionUID = -5703467522848303660L;
// Path: src/main/java/com/asher_stern/crf/crf/filters/CrfFeaturesAndFilters.java // public class CrfFeaturesAndFilters<K, G> implements Serializable // { // private static final long serialVersionUID = 5815029007668803039L; // // public CrfFeaturesAndFilters(FilterFactory<K, G> filterFactory, // CrfFilteredFeature<K, G>[] filteredFeatures, // Map<Filter<K, G>, Set<Integer>> mapActiveFeatures, // Set<Integer> indexesOfFeaturesWithNoFilter) // { // super(); // this.filterFactory = filterFactory; // this.filteredFeatures = filteredFeatures; // this.mapActiveFeatures = mapActiveFeatures; // this.indexesOfFeaturesWithNoFilter = indexesOfFeaturesWithNoFilter; // } // // // /** // * Returns the {@link FilterFactory} to be used with the features encapsulated here, for efficient feature-value calculations. // */ // public FilterFactory<K, G> getFilterFactory() // { // return filterFactory; // } // // /** // * An array of all the features in the CRF model. // */ // public CrfFilteredFeature<K, G>[] getFilteredFeatures() // { // return filteredFeatures; // } // // /** // * Returns a map from each filter to a set of indexes of features, that might be active if their filters are equal to // * this filter. "Active" means that they might return non-zero. // */ // public Map<Filter<K, G>, Set<Integer>> getMapActiveFeatures() // { // return mapActiveFeatures; // } // // /** // * Returns a set of indexes of features that might be active for any type of input. These features have no filters. // */ // public Set<Integer> getIndexesOfFeaturesWithNoFilter() // { // return indexesOfFeaturesWithNoFilter; // } // // // // // private final FilterFactory<K, G> filterFactory; // private final CrfFilteredFeature<K, G>[] filteredFeatures; // private final Map<Filter<K, G>, Set<Integer>> mapActiveFeatures; // private final Set<Integer> indexesOfFeaturesWithNoFilter; // } // Path: src/main/java/com/asher_stern/crf/crf/CrfModel.java import java.io.Serializable; import java.math.BigDecimal; import java.util.ArrayList; import com.asher_stern.crf.crf.filters.CrfFeaturesAndFilters; package com.asher_stern.crf.crf; /** * This class encapsulates the set of all possible tags, the list of features (f_i), and the list of parameters (\theta_i). * * @author Asher Stern * Date: Nov 8, 2014 * * @param <K> token type - must implement equals() and hashCode() * @param <G> tag type - must implement equals() and hashCode() */ public class CrfModel<K,G> implements Serializable // K = token, G = tag { private static final long serialVersionUID = -5703467522848303660L;
public CrfModel(CrfTags<G> crfTags, CrfFeaturesAndFilters<K, G> features, ArrayList<BigDecimal> parameters)
asher-stern/CRF
src/main/java/com/asher_stern/crf/crf/CrfRememberActiveFeatures.java
// Path: src/main/java/com/asher_stern/crf/crf/filters/CrfFeaturesAndFilters.java // public class CrfFeaturesAndFilters<K, G> implements Serializable // { // private static final long serialVersionUID = 5815029007668803039L; // // public CrfFeaturesAndFilters(FilterFactory<K, G> filterFactory, // CrfFilteredFeature<K, G>[] filteredFeatures, // Map<Filter<K, G>, Set<Integer>> mapActiveFeatures, // Set<Integer> indexesOfFeaturesWithNoFilter) // { // super(); // this.filterFactory = filterFactory; // this.filteredFeatures = filteredFeatures; // this.mapActiveFeatures = mapActiveFeatures; // this.indexesOfFeaturesWithNoFilter = indexesOfFeaturesWithNoFilter; // } // // // /** // * Returns the {@link FilterFactory} to be used with the features encapsulated here, for efficient feature-value calculations. // */ // public FilterFactory<K, G> getFilterFactory() // { // return filterFactory; // } // // /** // * An array of all the features in the CRF model. // */ // public CrfFilteredFeature<K, G>[] getFilteredFeatures() // { // return filteredFeatures; // } // // /** // * Returns a map from each filter to a set of indexes of features, that might be active if their filters are equal to // * this filter. "Active" means that they might return non-zero. // */ // public Map<Filter<K, G>, Set<Integer>> getMapActiveFeatures() // { // return mapActiveFeatures; // } // // /** // * Returns a set of indexes of features that might be active for any type of input. These features have no filters. // */ // public Set<Integer> getIndexesOfFeaturesWithNoFilter() // { // return indexesOfFeaturesWithNoFilter; // } // // // // // private final FilterFactory<K, G> filterFactory; // private final CrfFilteredFeature<K, G>[] filteredFeatures; // private final Map<Filter<K, G>, Set<Integer>> mapActiveFeatures; // private final Set<Integer> indexesOfFeaturesWithNoFilter; // }
import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; import com.asher_stern.crf.crf.filters.CrfFeaturesAndFilters;
package com.asher_stern.crf.crf; /** * Holds sets of active features for every token, and every pair of tags (for this token and the preceding token) in the given input. * * @author Asher Stern * Date: Nov 13, 2014 * * @param <K> * @param <G> */ public class CrfRememberActiveFeatures<K, G> { /** * Creates an instance of {@link CrfRememberActiveFeatures} for the given sentence, calls its {@link #findActiveFeaturesForAllTokens()} * method, and returns it. With the returned object, the method {@link #getOneTokenActiveFeatures(int, Object, Object)} can be * used to retrieve active features for any token/tag/tag-of-previous in the sentence. * * @param features * @param crfTags * @param sentence * @return */
// Path: src/main/java/com/asher_stern/crf/crf/filters/CrfFeaturesAndFilters.java // public class CrfFeaturesAndFilters<K, G> implements Serializable // { // private static final long serialVersionUID = 5815029007668803039L; // // public CrfFeaturesAndFilters(FilterFactory<K, G> filterFactory, // CrfFilteredFeature<K, G>[] filteredFeatures, // Map<Filter<K, G>, Set<Integer>> mapActiveFeatures, // Set<Integer> indexesOfFeaturesWithNoFilter) // { // super(); // this.filterFactory = filterFactory; // this.filteredFeatures = filteredFeatures; // this.mapActiveFeatures = mapActiveFeatures; // this.indexesOfFeaturesWithNoFilter = indexesOfFeaturesWithNoFilter; // } // // // /** // * Returns the {@link FilterFactory} to be used with the features encapsulated here, for efficient feature-value calculations. // */ // public FilterFactory<K, G> getFilterFactory() // { // return filterFactory; // } // // /** // * An array of all the features in the CRF model. // */ // public CrfFilteredFeature<K, G>[] getFilteredFeatures() // { // return filteredFeatures; // } // // /** // * Returns a map from each filter to a set of indexes of features, that might be active if their filters are equal to // * this filter. "Active" means that they might return non-zero. // */ // public Map<Filter<K, G>, Set<Integer>> getMapActiveFeatures() // { // return mapActiveFeatures; // } // // /** // * Returns a set of indexes of features that might be active for any type of input. These features have no filters. // */ // public Set<Integer> getIndexesOfFeaturesWithNoFilter() // { // return indexesOfFeaturesWithNoFilter; // } // // // // // private final FilterFactory<K, G> filterFactory; // private final CrfFilteredFeature<K, G>[] filteredFeatures; // private final Map<Filter<K, G>, Set<Integer>> mapActiveFeatures; // private final Set<Integer> indexesOfFeaturesWithNoFilter; // } // Path: src/main/java/com/asher_stern/crf/crf/CrfRememberActiveFeatures.java import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; import com.asher_stern.crf.crf.filters.CrfFeaturesAndFilters; package com.asher_stern.crf.crf; /** * Holds sets of active features for every token, and every pair of tags (for this token and the preceding token) in the given input. * * @author Asher Stern * Date: Nov 13, 2014 * * @param <K> * @param <G> */ public class CrfRememberActiveFeatures<K, G> { /** * Creates an instance of {@link CrfRememberActiveFeatures} for the given sentence, calls its {@link #findActiveFeaturesForAllTokens()} * method, and returns it. With the returned object, the method {@link #getOneTokenActiveFeatures(int, Object, Object)} can be * used to retrieve active features for any token/tag/tag-of-previous in the sentence. * * @param features * @param crfTags * @param sentence * @return */
public static <K, G> CrfRememberActiveFeatures<K, G> findForSentence(CrfFeaturesAndFilters<K, G> features, CrfTags<G> crfTags, K[] sentence)
asher-stern/CRF
src/main/java/com/asher_stern/crf/function/optimization/ConstantLineSearch.java
// Path: src/main/java/com/asher_stern/crf/function/Function.java // public abstract class Function // { // /** // * Returns the f(x) -- the value of the function in the given x. // * @param point the "point" is x -- the input for the function. // * @return the value of f(x) // */ // public abstract BigDecimal value(BigDecimal[] point); // // /** // * The size (dimension) of the input vector (x). // * @return the size (dimension) of the input vector (x). // */ // public abstract int size(); // } // // Path: src/main/java/com/asher_stern/crf/utilities/ArithmeticUtilities.java // public class ArithmeticUtilities // { // public static final MathContext MC = MathContext.DECIMAL128; // // public static final BigDecimal DOUBLE_MAX = big(Double.MAX_VALUE); // // public static final BigDecimal BIG_DECIMAL_E = big(Math.E); // public static final BigDecimal BIG_DECIMAL_TWO = new BigDecimal("2.0", MC); // public static final BigDecimal BIG_DECIMAL_E_TO_512 = BIG_DECIMAL_E.pow(512); // public static final BigDecimal BIG_DECIMAL_512 = new BigDecimal("512", MC); // public static final BigDecimal BIG_DECIMAL_LOG_DOUBLE_MAX = big(Math.log(Double.MAX_VALUE)); // // public static BigDecimal big(double d) // { // return new BigDecimal(d, MC); // } // // // public static BigDecimal log(BigDecimal d) // { // // long debug_counter = 0; // BigDecimal ret = BigDecimal.ZERO; // while (d.compareTo(DOUBLE_MAX)>0) // { // ret = safeAdd(ret, BIG_DECIMAL_512); // d = safeDivide(d, BIG_DECIMAL_E_TO_512); // if (d.compareTo(BigDecimal.ONE)<0) {throw new CrfException("Anomaly");} // // ++debug_counter; // } // ret = safeAdd(ret, big(Math.log(d.doubleValue()))); // // if ( logger.isDebugEnabled() && (debug_counter>0) ) {logger.debug("log() performed "+debug_counter+" iterations.");} // return ret; // } // // // public static BigDecimal exp(BigDecimal d) // { // if (d.compareTo(BIG_DECIMAL_LOG_DOUBLE_MAX)<=0) // { // return big(Math.exp(d.doubleValue())); // } // else // { // BigDecimal half = safeDivide(d, BIG_DECIMAL_TWO); // BigDecimal halfExp = exp(half); // return safeMultiply(halfExp, halfExp); // } // } // // public static BigDecimal safeAdd(final BigDecimal d1, final BigDecimal d2) // { // return d1.add(d2, MC); // } // // public static BigDecimal safeSubtract(final BigDecimal d1, final BigDecimal d2) // { // return d1.subtract(d2, MC); // } // // public static BigDecimal safeMultiply(final BigDecimal d1, final BigDecimal d2) // { // return d1.multiply(d2, MC); // } // // public static BigDecimal safeMultiply(final BigDecimal d1, final BigDecimal d2, BigDecimal...ds) // { // BigDecimal ret = safeMultiply(d1, d2); // for (BigDecimal d : ds) // { // ret = safeMultiply(ret, d); // } // return ret; // } // // public static BigDecimal safeDivide(final BigDecimal d1, final BigDecimal d2) // { // return d1.divide(d2, MC); // } // // @SuppressWarnings("unused") // private static final Logger logger = Logger.getLogger(ArithmeticUtilities.class); // }
import java.math.BigDecimal; import com.asher_stern.crf.function.Function; import com.asher_stern.crf.utilities.ArithmeticUtilities;
package com.asher_stern.crf.function.optimization; /** * A simple inexact and inaccurate non-efficient line search which merely returns a small * constant for any input. * * @author Asher Stern * Date: Nov 7, 2014 * */ public class ConstantLineSearch<F extends Function> implements LineSearch<F> {
// Path: src/main/java/com/asher_stern/crf/function/Function.java // public abstract class Function // { // /** // * Returns the f(x) -- the value of the function in the given x. // * @param point the "point" is x -- the input for the function. // * @return the value of f(x) // */ // public abstract BigDecimal value(BigDecimal[] point); // // /** // * The size (dimension) of the input vector (x). // * @return the size (dimension) of the input vector (x). // */ // public abstract int size(); // } // // Path: src/main/java/com/asher_stern/crf/utilities/ArithmeticUtilities.java // public class ArithmeticUtilities // { // public static final MathContext MC = MathContext.DECIMAL128; // // public static final BigDecimal DOUBLE_MAX = big(Double.MAX_VALUE); // // public static final BigDecimal BIG_DECIMAL_E = big(Math.E); // public static final BigDecimal BIG_DECIMAL_TWO = new BigDecimal("2.0", MC); // public static final BigDecimal BIG_DECIMAL_E_TO_512 = BIG_DECIMAL_E.pow(512); // public static final BigDecimal BIG_DECIMAL_512 = new BigDecimal("512", MC); // public static final BigDecimal BIG_DECIMAL_LOG_DOUBLE_MAX = big(Math.log(Double.MAX_VALUE)); // // public static BigDecimal big(double d) // { // return new BigDecimal(d, MC); // } // // // public static BigDecimal log(BigDecimal d) // { // // long debug_counter = 0; // BigDecimal ret = BigDecimal.ZERO; // while (d.compareTo(DOUBLE_MAX)>0) // { // ret = safeAdd(ret, BIG_DECIMAL_512); // d = safeDivide(d, BIG_DECIMAL_E_TO_512); // if (d.compareTo(BigDecimal.ONE)<0) {throw new CrfException("Anomaly");} // // ++debug_counter; // } // ret = safeAdd(ret, big(Math.log(d.doubleValue()))); // // if ( logger.isDebugEnabled() && (debug_counter>0) ) {logger.debug("log() performed "+debug_counter+" iterations.");} // return ret; // } // // // public static BigDecimal exp(BigDecimal d) // { // if (d.compareTo(BIG_DECIMAL_LOG_DOUBLE_MAX)<=0) // { // return big(Math.exp(d.doubleValue())); // } // else // { // BigDecimal half = safeDivide(d, BIG_DECIMAL_TWO); // BigDecimal halfExp = exp(half); // return safeMultiply(halfExp, halfExp); // } // } // // public static BigDecimal safeAdd(final BigDecimal d1, final BigDecimal d2) // { // return d1.add(d2, MC); // } // // public static BigDecimal safeSubtract(final BigDecimal d1, final BigDecimal d2) // { // return d1.subtract(d2, MC); // } // // public static BigDecimal safeMultiply(final BigDecimal d1, final BigDecimal d2) // { // return d1.multiply(d2, MC); // } // // public static BigDecimal safeMultiply(final BigDecimal d1, final BigDecimal d2, BigDecimal...ds) // { // BigDecimal ret = safeMultiply(d1, d2); // for (BigDecimal d : ds) // { // ret = safeMultiply(ret, d); // } // return ret; // } // // public static BigDecimal safeDivide(final BigDecimal d1, final BigDecimal d2) // { // return d1.divide(d2, MC); // } // // @SuppressWarnings("unused") // private static final Logger logger = Logger.getLogger(ArithmeticUtilities.class); // } // Path: src/main/java/com/asher_stern/crf/function/optimization/ConstantLineSearch.java import java.math.BigDecimal; import com.asher_stern.crf.function.Function; import com.asher_stern.crf.utilities.ArithmeticUtilities; package com.asher_stern.crf.function.optimization; /** * A simple inexact and inaccurate non-efficient line search which merely returns a small * constant for any input. * * @author Asher Stern * Date: Nov 7, 2014 * */ public class ConstantLineSearch<F extends Function> implements LineSearch<F> {
public static final BigDecimal DEFAULT_RATE = new BigDecimal(0.01, ArithmeticUtilities.MC);
asher-stern/CRF
src/main/java/com/asher_stern/crf/smalltests/DemoTopK_DS.java
// Path: src/main/java/com/asher_stern/crf/utilities/TopK_DateStructure.java // public class TopK_DateStructure<T> // { // public TopK_DateStructure(int k) // { // this(k, null); // } // // // @SuppressWarnings("unchecked") // public TopK_DateStructure(int k, Comparator<T> comparator) // { // super(); // this.k = k; // this.comparator = comparator; // // this.array_length = k*k + k; // this.storage = (T[]) Array.newInstance(Object.class, array_length); // // if (k<=0) {throw new CrfException("k <= 0");} // // index = 0; // } // // // // /** // * Insert an item to this data-structure. This item might be discarded later when it is absolutely sure that it is not // * one of the top-k items that were inserted to this data-structure. // * @param item // */ // public void insert(T item) // { // storage[index] = item; // ++index; // // if (index>array_length) {throw new CrfException("BUG");} // if (index==array_length) // { // sortAndShrink(); // } // } // // /** // * Get the top-k items among all the items that were inserted to this data-structure so far. // * <B>Note that this method has time complexity of O(k*log(k)).</B> // * @return // */ // public ArrayList<T> getTopK() // { // if (index>k) // { // sortAndShrink(); // } // // ArrayList<T> topKAsList = new ArrayList<T>(); // for (int i=0;i<k;++i) // { // topKAsList.add(storage[i]); // } // return topKAsList; // } // // // private void sortAndShrink() // { // if (null==comparator) // { // Arrays.sort(storage, 0, index, Collections.reverseOrder()); // } // else // { // Arrays.sort(storage, 0, index, Collections.reverseOrder(comparator)); // } // // index = k; // } // // private final int k; // private final int array_length; // private final T[] storage; // // private int index = 0; // the index of the next item to insert // private Comparator<T> comparator = null; // }
import java.util.List; import com.asher_stern.crf.utilities.TopK_DateStructure;
package com.asher_stern.crf.smalltests; /** * * @author Asher Stern * Date: Nov 19, 2014 * */ public class DemoTopK_DS { public static void main(String[] args) { try { new DemoTopK_DS().go(); } catch(Throwable t) { t.printStackTrace(System.out); } } public void go() { int k = 3;
// Path: src/main/java/com/asher_stern/crf/utilities/TopK_DateStructure.java // public class TopK_DateStructure<T> // { // public TopK_DateStructure(int k) // { // this(k, null); // } // // // @SuppressWarnings("unchecked") // public TopK_DateStructure(int k, Comparator<T> comparator) // { // super(); // this.k = k; // this.comparator = comparator; // // this.array_length = k*k + k; // this.storage = (T[]) Array.newInstance(Object.class, array_length); // // if (k<=0) {throw new CrfException("k <= 0");} // // index = 0; // } // // // // /** // * Insert an item to this data-structure. This item might be discarded later when it is absolutely sure that it is not // * one of the top-k items that were inserted to this data-structure. // * @param item // */ // public void insert(T item) // { // storage[index] = item; // ++index; // // if (index>array_length) {throw new CrfException("BUG");} // if (index==array_length) // { // sortAndShrink(); // } // } // // /** // * Get the top-k items among all the items that were inserted to this data-structure so far. // * <B>Note that this method has time complexity of O(k*log(k)).</B> // * @return // */ // public ArrayList<T> getTopK() // { // if (index>k) // { // sortAndShrink(); // } // // ArrayList<T> topKAsList = new ArrayList<T>(); // for (int i=0;i<k;++i) // { // topKAsList.add(storage[i]); // } // return topKAsList; // } // // // private void sortAndShrink() // { // if (null==comparator) // { // Arrays.sort(storage, 0, index, Collections.reverseOrder()); // } // else // { // Arrays.sort(storage, 0, index, Collections.reverseOrder(comparator)); // } // // index = k; // } // // private final int k; // private final int array_length; // private final T[] storage; // // private int index = 0; // the index of the next item to insert // private Comparator<T> comparator = null; // } // Path: src/main/java/com/asher_stern/crf/smalltests/DemoTopK_DS.java import java.util.List; import com.asher_stern.crf.utilities.TopK_DateStructure; package com.asher_stern.crf.smalltests; /** * * @author Asher Stern * Date: Nov 19, 2014 * */ public class DemoTopK_DS { public static void main(String[] args) { try { new DemoTopK_DS().go(); } catch(Throwable t) { t.printStackTrace(System.out); } } public void go() { int k = 3;
TopK_DateStructure<Integer> ds = new TopK_DateStructure<Integer>(k);
asher-stern/CRF
src/main/java/com/asher_stern/crf/function/optimization/NegatedFunction.java
// Path: src/main/java/com/asher_stern/crf/function/DerivableFunction.java // public abstract class DerivableFunction extends Function // { // /** // * Returns the gradient of the function in the given point. // * For example, if the function is f(x_1,x_2) = (x_1)^2 + x_1*x_2, then for [3,5] the returned gradient is [11 , 3]. // * @param point the point is "x", the input for the function, for which the user needs the gradient. // * @return the gradient of the function in the given point. // */ // public abstract BigDecimal[] gradient(BigDecimal[] point); // } // // Path: src/main/java/com/asher_stern/crf/function/Function.java // public abstract class Function // { // /** // * Returns the f(x) -- the value of the function in the given x. // * @param point the "point" is x -- the input for the function. // * @return the value of f(x) // */ // public abstract BigDecimal value(BigDecimal[] point); // // /** // * The size (dimension) of the input vector (x). // * @return the size (dimension) of the input vector (x). // */ // public abstract int size(); // } // // Path: src/main/java/com/asher_stern/crf/function/TwiceDerivableFunction.java // public abstract class TwiceDerivableFunction extends DerivableFunction // { // /** // * Returns the Hessian matrix for the given function in the given point (point is "x" -- the function input). // * @param point "point" is "x" -- the input for the function. // * @return the Hessian matrix -- the matrix of partial second derivations. // */ // public abstract BigDecimal[][] hessian(BigDecimal[] point); // } // // Path: src/main/java/com/asher_stern/crf/utilities/CrfException.java // public class CrfException extends RuntimeException // { // private static final long serialVersionUID = 5414394233000815286L; // // public CrfException() // { // super(); // } // // public CrfException(String message, Throwable cause, // boolean enableSuppression, boolean writableStackTrace) // { // super(message, cause, enableSuppression, writableStackTrace); // } // // public CrfException(String message, Throwable cause) // { // super(message, cause); // } // // public CrfException(String message) // { // super(message); // } // // public CrfException(Throwable cause) // { // super(cause); // } // // // }
import java.math.BigDecimal; import com.asher_stern.crf.function.DerivableFunction; import com.asher_stern.crf.function.Function; import com.asher_stern.crf.function.TwiceDerivableFunction; import com.asher_stern.crf.utilities.CrfException;
package com.asher_stern.crf.function.optimization; /** * Represent "-f(x)" for a given function "f(x)". * <BR> * This negated function can be used when maximization of a function is needed, but a minimization algorithm is available. * Just minimize "-f(x)", and the resulting "x" is the point of the maximum for "f(x)". * * @author Asher Stern * Date: Nov 6, 2014 * */ public class NegatedFunction extends TwiceDerivableFunction {
// Path: src/main/java/com/asher_stern/crf/function/DerivableFunction.java // public abstract class DerivableFunction extends Function // { // /** // * Returns the gradient of the function in the given point. // * For example, if the function is f(x_1,x_2) = (x_1)^2 + x_1*x_2, then for [3,5] the returned gradient is [11 , 3]. // * @param point the point is "x", the input for the function, for which the user needs the gradient. // * @return the gradient of the function in the given point. // */ // public abstract BigDecimal[] gradient(BigDecimal[] point); // } // // Path: src/main/java/com/asher_stern/crf/function/Function.java // public abstract class Function // { // /** // * Returns the f(x) -- the value of the function in the given x. // * @param point the "point" is x -- the input for the function. // * @return the value of f(x) // */ // public abstract BigDecimal value(BigDecimal[] point); // // /** // * The size (dimension) of the input vector (x). // * @return the size (dimension) of the input vector (x). // */ // public abstract int size(); // } // // Path: src/main/java/com/asher_stern/crf/function/TwiceDerivableFunction.java // public abstract class TwiceDerivableFunction extends DerivableFunction // { // /** // * Returns the Hessian matrix for the given function in the given point (point is "x" -- the function input). // * @param point "point" is "x" -- the input for the function. // * @return the Hessian matrix -- the matrix of partial second derivations. // */ // public abstract BigDecimal[][] hessian(BigDecimal[] point); // } // // Path: src/main/java/com/asher_stern/crf/utilities/CrfException.java // public class CrfException extends RuntimeException // { // private static final long serialVersionUID = 5414394233000815286L; // // public CrfException() // { // super(); // } // // public CrfException(String message, Throwable cause, // boolean enableSuppression, boolean writableStackTrace) // { // super(message, cause, enableSuppression, writableStackTrace); // } // // public CrfException(String message, Throwable cause) // { // super(message, cause); // } // // public CrfException(String message) // { // super(message); // } // // public CrfException(Throwable cause) // { // super(cause); // } // // // } // Path: src/main/java/com/asher_stern/crf/function/optimization/NegatedFunction.java import java.math.BigDecimal; import com.asher_stern.crf.function.DerivableFunction; import com.asher_stern.crf.function.Function; import com.asher_stern.crf.function.TwiceDerivableFunction; import com.asher_stern.crf.utilities.CrfException; package com.asher_stern.crf.function.optimization; /** * Represent "-f(x)" for a given function "f(x)". * <BR> * This negated function can be used when maximization of a function is needed, but a minimization algorithm is available. * Just minimize "-f(x)", and the resulting "x" is the point of the maximum for "f(x)". * * @author Asher Stern * Date: Nov 6, 2014 * */ public class NegatedFunction extends TwiceDerivableFunction {
public static NegatedFunction fromFunction(Function function)
asher-stern/CRF
src/main/java/com/asher_stern/crf/function/optimization/NegatedFunction.java
// Path: src/main/java/com/asher_stern/crf/function/DerivableFunction.java // public abstract class DerivableFunction extends Function // { // /** // * Returns the gradient of the function in the given point. // * For example, if the function is f(x_1,x_2) = (x_1)^2 + x_1*x_2, then for [3,5] the returned gradient is [11 , 3]. // * @param point the point is "x", the input for the function, for which the user needs the gradient. // * @return the gradient of the function in the given point. // */ // public abstract BigDecimal[] gradient(BigDecimal[] point); // } // // Path: src/main/java/com/asher_stern/crf/function/Function.java // public abstract class Function // { // /** // * Returns the f(x) -- the value of the function in the given x. // * @param point the "point" is x -- the input for the function. // * @return the value of f(x) // */ // public abstract BigDecimal value(BigDecimal[] point); // // /** // * The size (dimension) of the input vector (x). // * @return the size (dimension) of the input vector (x). // */ // public abstract int size(); // } // // Path: src/main/java/com/asher_stern/crf/function/TwiceDerivableFunction.java // public abstract class TwiceDerivableFunction extends DerivableFunction // { // /** // * Returns the Hessian matrix for the given function in the given point (point is "x" -- the function input). // * @param point "point" is "x" -- the input for the function. // * @return the Hessian matrix -- the matrix of partial second derivations. // */ // public abstract BigDecimal[][] hessian(BigDecimal[] point); // } // // Path: src/main/java/com/asher_stern/crf/utilities/CrfException.java // public class CrfException extends RuntimeException // { // private static final long serialVersionUID = 5414394233000815286L; // // public CrfException() // { // super(); // } // // public CrfException(String message, Throwable cause, // boolean enableSuppression, boolean writableStackTrace) // { // super(message, cause, enableSuppression, writableStackTrace); // } // // public CrfException(String message, Throwable cause) // { // super(message, cause); // } // // public CrfException(String message) // { // super(message); // } // // public CrfException(Throwable cause) // { // super(cause); // } // // // }
import java.math.BigDecimal; import com.asher_stern.crf.function.DerivableFunction; import com.asher_stern.crf.function.Function; import com.asher_stern.crf.function.TwiceDerivableFunction; import com.asher_stern.crf.utilities.CrfException;
package com.asher_stern.crf.function.optimization; /** * Represent "-f(x)" for a given function "f(x)". * <BR> * This negated function can be used when maximization of a function is needed, but a minimization algorithm is available. * Just minimize "-f(x)", and the resulting "x" is the point of the maximum for "f(x)". * * @author Asher Stern * Date: Nov 6, 2014 * */ public class NegatedFunction extends TwiceDerivableFunction { public static NegatedFunction fromFunction(Function function) { return new NegatedFunction(function, null, null); }
// Path: src/main/java/com/asher_stern/crf/function/DerivableFunction.java // public abstract class DerivableFunction extends Function // { // /** // * Returns the gradient of the function in the given point. // * For example, if the function is f(x_1,x_2) = (x_1)^2 + x_1*x_2, then for [3,5] the returned gradient is [11 , 3]. // * @param point the point is "x", the input for the function, for which the user needs the gradient. // * @return the gradient of the function in the given point. // */ // public abstract BigDecimal[] gradient(BigDecimal[] point); // } // // Path: src/main/java/com/asher_stern/crf/function/Function.java // public abstract class Function // { // /** // * Returns the f(x) -- the value of the function in the given x. // * @param point the "point" is x -- the input for the function. // * @return the value of f(x) // */ // public abstract BigDecimal value(BigDecimal[] point); // // /** // * The size (dimension) of the input vector (x). // * @return the size (dimension) of the input vector (x). // */ // public abstract int size(); // } // // Path: src/main/java/com/asher_stern/crf/function/TwiceDerivableFunction.java // public abstract class TwiceDerivableFunction extends DerivableFunction // { // /** // * Returns the Hessian matrix for the given function in the given point (point is "x" -- the function input). // * @param point "point" is "x" -- the input for the function. // * @return the Hessian matrix -- the matrix of partial second derivations. // */ // public abstract BigDecimal[][] hessian(BigDecimal[] point); // } // // Path: src/main/java/com/asher_stern/crf/utilities/CrfException.java // public class CrfException extends RuntimeException // { // private static final long serialVersionUID = 5414394233000815286L; // // public CrfException() // { // super(); // } // // public CrfException(String message, Throwable cause, // boolean enableSuppression, boolean writableStackTrace) // { // super(message, cause, enableSuppression, writableStackTrace); // } // // public CrfException(String message, Throwable cause) // { // super(message, cause); // } // // public CrfException(String message) // { // super(message); // } // // public CrfException(Throwable cause) // { // super(cause); // } // // // } // Path: src/main/java/com/asher_stern/crf/function/optimization/NegatedFunction.java import java.math.BigDecimal; import com.asher_stern.crf.function.DerivableFunction; import com.asher_stern.crf.function.Function; import com.asher_stern.crf.function.TwiceDerivableFunction; import com.asher_stern.crf.utilities.CrfException; package com.asher_stern.crf.function.optimization; /** * Represent "-f(x)" for a given function "f(x)". * <BR> * This negated function can be used when maximization of a function is needed, but a minimization algorithm is available. * Just minimize "-f(x)", and the resulting "x" is the point of the maximum for "f(x)". * * @author Asher Stern * Date: Nov 6, 2014 * */ public class NegatedFunction extends TwiceDerivableFunction { public static NegatedFunction fromFunction(Function function) { return new NegatedFunction(function, null, null); }
public static NegatedFunction fromDerivableFunction(DerivableFunction derivableFunction)
asher-stern/CRF
src/main/java/com/asher_stern/crf/function/optimization/NegatedFunction.java
// Path: src/main/java/com/asher_stern/crf/function/DerivableFunction.java // public abstract class DerivableFunction extends Function // { // /** // * Returns the gradient of the function in the given point. // * For example, if the function is f(x_1,x_2) = (x_1)^2 + x_1*x_2, then for [3,5] the returned gradient is [11 , 3]. // * @param point the point is "x", the input for the function, for which the user needs the gradient. // * @return the gradient of the function in the given point. // */ // public abstract BigDecimal[] gradient(BigDecimal[] point); // } // // Path: src/main/java/com/asher_stern/crf/function/Function.java // public abstract class Function // { // /** // * Returns the f(x) -- the value of the function in the given x. // * @param point the "point" is x -- the input for the function. // * @return the value of f(x) // */ // public abstract BigDecimal value(BigDecimal[] point); // // /** // * The size (dimension) of the input vector (x). // * @return the size (dimension) of the input vector (x). // */ // public abstract int size(); // } // // Path: src/main/java/com/asher_stern/crf/function/TwiceDerivableFunction.java // public abstract class TwiceDerivableFunction extends DerivableFunction // { // /** // * Returns the Hessian matrix for the given function in the given point (point is "x" -- the function input). // * @param point "point" is "x" -- the input for the function. // * @return the Hessian matrix -- the matrix of partial second derivations. // */ // public abstract BigDecimal[][] hessian(BigDecimal[] point); // } // // Path: src/main/java/com/asher_stern/crf/utilities/CrfException.java // public class CrfException extends RuntimeException // { // private static final long serialVersionUID = 5414394233000815286L; // // public CrfException() // { // super(); // } // // public CrfException(String message, Throwable cause, // boolean enableSuppression, boolean writableStackTrace) // { // super(message, cause, enableSuppression, writableStackTrace); // } // // public CrfException(String message, Throwable cause) // { // super(message, cause); // } // // public CrfException(String message) // { // super(message); // } // // public CrfException(Throwable cause) // { // super(cause); // } // // // }
import java.math.BigDecimal; import com.asher_stern.crf.function.DerivableFunction; import com.asher_stern.crf.function.Function; import com.asher_stern.crf.function.TwiceDerivableFunction; import com.asher_stern.crf.utilities.CrfException;
package com.asher_stern.crf.function.optimization; /** * Represent "-f(x)" for a given function "f(x)". * <BR> * This negated function can be used when maximization of a function is needed, but a minimization algorithm is available. * Just minimize "-f(x)", and the resulting "x" is the point of the maximum for "f(x)". * * @author Asher Stern * Date: Nov 6, 2014 * */ public class NegatedFunction extends TwiceDerivableFunction { public static NegatedFunction fromFunction(Function function) { return new NegatedFunction(function, null, null); } public static NegatedFunction fromDerivableFunction(DerivableFunction derivableFunction) { return new NegatedFunction(null,derivableFunction,null); } public static NegatedFunction fromTwiceDerivableFunction(TwiceDerivableFunction twiceDerivableFunction) { return new NegatedFunction(null,null,twiceDerivableFunction); } @Override public int size() { return this.theSize; } @Override public BigDecimal value(BigDecimal[] point) { if (function!=null){return function.value(point).negate();} else if (derivableFunction!=null){return derivableFunction.value(point).negate();} else if (twiceDerivableFunction!=null){return twiceDerivableFunction.value(point).negate();}
// Path: src/main/java/com/asher_stern/crf/function/DerivableFunction.java // public abstract class DerivableFunction extends Function // { // /** // * Returns the gradient of the function in the given point. // * For example, if the function is f(x_1,x_2) = (x_1)^2 + x_1*x_2, then for [3,5] the returned gradient is [11 , 3]. // * @param point the point is "x", the input for the function, for which the user needs the gradient. // * @return the gradient of the function in the given point. // */ // public abstract BigDecimal[] gradient(BigDecimal[] point); // } // // Path: src/main/java/com/asher_stern/crf/function/Function.java // public abstract class Function // { // /** // * Returns the f(x) -- the value of the function in the given x. // * @param point the "point" is x -- the input for the function. // * @return the value of f(x) // */ // public abstract BigDecimal value(BigDecimal[] point); // // /** // * The size (dimension) of the input vector (x). // * @return the size (dimension) of the input vector (x). // */ // public abstract int size(); // } // // Path: src/main/java/com/asher_stern/crf/function/TwiceDerivableFunction.java // public abstract class TwiceDerivableFunction extends DerivableFunction // { // /** // * Returns the Hessian matrix for the given function in the given point (point is "x" -- the function input). // * @param point "point" is "x" -- the input for the function. // * @return the Hessian matrix -- the matrix of partial second derivations. // */ // public abstract BigDecimal[][] hessian(BigDecimal[] point); // } // // Path: src/main/java/com/asher_stern/crf/utilities/CrfException.java // public class CrfException extends RuntimeException // { // private static final long serialVersionUID = 5414394233000815286L; // // public CrfException() // { // super(); // } // // public CrfException(String message, Throwable cause, // boolean enableSuppression, boolean writableStackTrace) // { // super(message, cause, enableSuppression, writableStackTrace); // } // // public CrfException(String message, Throwable cause) // { // super(message, cause); // } // // public CrfException(String message) // { // super(message); // } // // public CrfException(Throwable cause) // { // super(cause); // } // // // } // Path: src/main/java/com/asher_stern/crf/function/optimization/NegatedFunction.java import java.math.BigDecimal; import com.asher_stern.crf.function.DerivableFunction; import com.asher_stern.crf.function.Function; import com.asher_stern.crf.function.TwiceDerivableFunction; import com.asher_stern.crf.utilities.CrfException; package com.asher_stern.crf.function.optimization; /** * Represent "-f(x)" for a given function "f(x)". * <BR> * This negated function can be used when maximization of a function is needed, but a minimization algorithm is available. * Just minimize "-f(x)", and the resulting "x" is the point of the maximum for "f(x)". * * @author Asher Stern * Date: Nov 6, 2014 * */ public class NegatedFunction extends TwiceDerivableFunction { public static NegatedFunction fromFunction(Function function) { return new NegatedFunction(function, null, null); } public static NegatedFunction fromDerivableFunction(DerivableFunction derivableFunction) { return new NegatedFunction(null,derivableFunction,null); } public static NegatedFunction fromTwiceDerivableFunction(TwiceDerivableFunction twiceDerivableFunction) { return new NegatedFunction(null,null,twiceDerivableFunction); } @Override public int size() { return this.theSize; } @Override public BigDecimal value(BigDecimal[] point) { if (function!=null){return function.value(point).negate();} else if (derivableFunction!=null){return derivableFunction.value(point).negate();} else if (twiceDerivableFunction!=null){return twiceDerivableFunction.value(point).negate();}
else throw new CrfException("BUG");
asher-stern/CRF
src/main/java/com/asher_stern/crf/crf/run/ExampleMain.java
// Path: src/main/java/com/asher_stern/crf/crf/CrfModel.java // public class CrfModel<K,G> implements Serializable // K = token, G = tag // { // private static final long serialVersionUID = -5703467522848303660L; // // public CrfModel(CrfTags<G> crfTags, CrfFeaturesAndFilters<K, G> features, ArrayList<BigDecimal> parameters) // { // super(); // this.crfTags = crfTags; // this.features = features; // this.parameters = parameters; // } // // // // public CrfTags<G> getCrfTags() // { // return crfTags; // } // public CrfFeaturesAndFilters<K, G> getFeatures() // { // return features; // } // public ArrayList<BigDecimal> getParameters() // { // return parameters; // } // // // // private final CrfTags<G> crfTags; // private final CrfFeaturesAndFilters<K, G> features; // private final ArrayList<BigDecimal> parameters; // } // // Path: src/main/java/com/asher_stern/crf/crf/filters/FilterFactory.java // public interface FilterFactory<K, G> extends Serializable // { // /** // * Creates a set of filters for the given token,tag, and tag-of-previous-token. // * The convention is as follows: // * Let each feature f be a feature that <B>might</B> return non-zero for the given token,tag,previous-tag. // * That feature is encapsulated with a {@link Filter} in a {@link CrfFilteredFeature}. Let's call this filter "t". // * For that filter there exist one filter in the set returned by this function, name it "t'", such that "t'" equals to "t". // * // * // * @param sequence A sequence of tokens // * @param tokenIndex An index of a token in that sequence // * @param currentTag A tag for that token // * @param previousTag A tag for the token which immediately precedes that token. // * @return A set of filters as described above. // */ // public Set<Filter<K, G>> createFilters(K[] sequence, int tokenIndex, G currentTag, G previousTag); // } // // Path: src/main/java/com/asher_stern/crf/utilities/TaggedToken.java // public class TaggedToken<K,G> // { // public TaggedToken(K token, G tag) // { // super(); // this.token = token; // this.tag = tag; // } // // // // public K getToken() // { // return token; // } // public G getTag() // { // return tag; // } // // // // // @Override // public String toString() // { // return "CrfTaggedToken [getToken()=" + getToken() + ", getTag()=" // + getTag() + "]"; // } // // // // // // // @Override // public int hashCode() // { // final int prime = 31; // int result = 1; // result = prime * result + ((tag == null) ? 0 : tag.hashCode()); // result = prime * result + ((token == null) ? 0 : token.hashCode()); // return result; // } // // // // @Override // public boolean equals(Object obj) // { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // TaggedToken<?,?> other = (TaggedToken<?,?>) obj; // if (tag == null) // { // if (other.tag != null) // return false; // } else if (!tag.equals(other.tag)) // return false; // if (token == null) // { // if (other.token != null) // return false; // } else if (!token.equals(other.token)) // return false; // return true; // } // // // // // // // private final K token; // private final G tag; // }
import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Arrays; import java.util.List; import java.util.Set; import com.asher_stern.crf.crf.CrfModel; import com.asher_stern.crf.crf.filters.FilterFactory; import com.asher_stern.crf.utilities.TaggedToken;
package com.asher_stern.crf.crf.run; /** * An example for usage of CRF. Don't run this class, but use it as a template for writing your own main class. * * @author Asher Stern * Date: Nov 23, 2014 * */ public class ExampleMain { @SuppressWarnings("unchecked") public static void main(String[] args) { // Load a corpus into the memory
// Path: src/main/java/com/asher_stern/crf/crf/CrfModel.java // public class CrfModel<K,G> implements Serializable // K = token, G = tag // { // private static final long serialVersionUID = -5703467522848303660L; // // public CrfModel(CrfTags<G> crfTags, CrfFeaturesAndFilters<K, G> features, ArrayList<BigDecimal> parameters) // { // super(); // this.crfTags = crfTags; // this.features = features; // this.parameters = parameters; // } // // // // public CrfTags<G> getCrfTags() // { // return crfTags; // } // public CrfFeaturesAndFilters<K, G> getFeatures() // { // return features; // } // public ArrayList<BigDecimal> getParameters() // { // return parameters; // } // // // // private final CrfTags<G> crfTags; // private final CrfFeaturesAndFilters<K, G> features; // private final ArrayList<BigDecimal> parameters; // } // // Path: src/main/java/com/asher_stern/crf/crf/filters/FilterFactory.java // public interface FilterFactory<K, G> extends Serializable // { // /** // * Creates a set of filters for the given token,tag, and tag-of-previous-token. // * The convention is as follows: // * Let each feature f be a feature that <B>might</B> return non-zero for the given token,tag,previous-tag. // * That feature is encapsulated with a {@link Filter} in a {@link CrfFilteredFeature}. Let's call this filter "t". // * For that filter there exist one filter in the set returned by this function, name it "t'", such that "t'" equals to "t". // * // * // * @param sequence A sequence of tokens // * @param tokenIndex An index of a token in that sequence // * @param currentTag A tag for that token // * @param previousTag A tag for the token which immediately precedes that token. // * @return A set of filters as described above. // */ // public Set<Filter<K, G>> createFilters(K[] sequence, int tokenIndex, G currentTag, G previousTag); // } // // Path: src/main/java/com/asher_stern/crf/utilities/TaggedToken.java // public class TaggedToken<K,G> // { // public TaggedToken(K token, G tag) // { // super(); // this.token = token; // this.tag = tag; // } // // // // public K getToken() // { // return token; // } // public G getTag() // { // return tag; // } // // // // // @Override // public String toString() // { // return "CrfTaggedToken [getToken()=" + getToken() + ", getTag()=" // + getTag() + "]"; // } // // // // // // // @Override // public int hashCode() // { // final int prime = 31; // int result = 1; // result = prime * result + ((tag == null) ? 0 : tag.hashCode()); // result = prime * result + ((token == null) ? 0 : token.hashCode()); // return result; // } // // // // @Override // public boolean equals(Object obj) // { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // TaggedToken<?,?> other = (TaggedToken<?,?>) obj; // if (tag == null) // { // if (other.tag != null) // return false; // } else if (!tag.equals(other.tag)) // return false; // if (token == null) // { // if (other.token != null) // return false; // } else if (!token.equals(other.token)) // return false; // return true; // } // // // // // // // private final K token; // private final G tag; // } // Path: src/main/java/com/asher_stern/crf/crf/run/ExampleMain.java import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Arrays; import java.util.List; import java.util.Set; import com.asher_stern.crf.crf.CrfModel; import com.asher_stern.crf.crf.filters.FilterFactory; import com.asher_stern.crf.utilities.TaggedToken; package com.asher_stern.crf.crf.run; /** * An example for usage of CRF. Don't run this class, but use it as a template for writing your own main class. * * @author Asher Stern * Date: Nov 23, 2014 * */ public class ExampleMain { @SuppressWarnings("unchecked") public static void main(String[] args) { // Load a corpus into the memory
List<List<? extends TaggedToken<String, String> >> corpus = loadCorpusWhereTokensAndTagsAreStrings();
asher-stern/CRF
src/main/java/com/asher_stern/crf/crf/run/ExampleMain.java
// Path: src/main/java/com/asher_stern/crf/crf/CrfModel.java // public class CrfModel<K,G> implements Serializable // K = token, G = tag // { // private static final long serialVersionUID = -5703467522848303660L; // // public CrfModel(CrfTags<G> crfTags, CrfFeaturesAndFilters<K, G> features, ArrayList<BigDecimal> parameters) // { // super(); // this.crfTags = crfTags; // this.features = features; // this.parameters = parameters; // } // // // // public CrfTags<G> getCrfTags() // { // return crfTags; // } // public CrfFeaturesAndFilters<K, G> getFeatures() // { // return features; // } // public ArrayList<BigDecimal> getParameters() // { // return parameters; // } // // // // private final CrfTags<G> crfTags; // private final CrfFeaturesAndFilters<K, G> features; // private final ArrayList<BigDecimal> parameters; // } // // Path: src/main/java/com/asher_stern/crf/crf/filters/FilterFactory.java // public interface FilterFactory<K, G> extends Serializable // { // /** // * Creates a set of filters for the given token,tag, and tag-of-previous-token. // * The convention is as follows: // * Let each feature f be a feature that <B>might</B> return non-zero for the given token,tag,previous-tag. // * That feature is encapsulated with a {@link Filter} in a {@link CrfFilteredFeature}. Let's call this filter "t". // * For that filter there exist one filter in the set returned by this function, name it "t'", such that "t'" equals to "t". // * // * // * @param sequence A sequence of tokens // * @param tokenIndex An index of a token in that sequence // * @param currentTag A tag for that token // * @param previousTag A tag for the token which immediately precedes that token. // * @return A set of filters as described above. // */ // public Set<Filter<K, G>> createFilters(K[] sequence, int tokenIndex, G currentTag, G previousTag); // } // // Path: src/main/java/com/asher_stern/crf/utilities/TaggedToken.java // public class TaggedToken<K,G> // { // public TaggedToken(K token, G tag) // { // super(); // this.token = token; // this.tag = tag; // } // // // // public K getToken() // { // return token; // } // public G getTag() // { // return tag; // } // // // // // @Override // public String toString() // { // return "CrfTaggedToken [getToken()=" + getToken() + ", getTag()=" // + getTag() + "]"; // } // // // // // // // @Override // public int hashCode() // { // final int prime = 31; // int result = 1; // result = prime * result + ((tag == null) ? 0 : tag.hashCode()); // result = prime * result + ((token == null) ? 0 : token.hashCode()); // return result; // } // // // // @Override // public boolean equals(Object obj) // { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // TaggedToken<?,?> other = (TaggedToken<?,?>) obj; // if (tag == null) // { // if (other.tag != null) // return false; // } else if (!tag.equals(other.tag)) // return false; // if (token == null) // { // if (other.token != null) // return false; // } else if (!token.equals(other.token)) // return false; // return true; // } // // // // // // // private final K token; // private final G tag; // }
import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Arrays; import java.util.List; import java.util.Set; import com.asher_stern.crf.crf.CrfModel; import com.asher_stern.crf.crf.filters.FilterFactory; import com.asher_stern.crf.utilities.TaggedToken;
package com.asher_stern.crf.crf.run; /** * An example for usage of CRF. Don't run this class, but use it as a template for writing your own main class. * * @author Asher Stern * Date: Nov 23, 2014 * */ public class ExampleMain { @SuppressWarnings("unchecked") public static void main(String[] args) { // Load a corpus into the memory List<List<? extends TaggedToken<String, String> >> corpus = loadCorpusWhereTokensAndTagsAreStrings(); // Create trainer factory CrfTrainerFactory<String, String> trainerFactory = new CrfTrainerFactory<String, String>(); // Optionally call trainerFactory.setRegularizationSigmaSquareFactor() to override the default regularization factor. // Create trainer CrfTrainer<String,String> trainer = trainerFactory.createTrainer( corpus, (Iterable<? extends List<? extends TaggedToken<String, String> >> theCorpus, Set<String> tags) -> createFeatureGeneratorForGivenCorpus(theCorpus,tags), createFilterFactory()); // Run training with the loaded corpus. trainer.train(corpus); // Get the model
// Path: src/main/java/com/asher_stern/crf/crf/CrfModel.java // public class CrfModel<K,G> implements Serializable // K = token, G = tag // { // private static final long serialVersionUID = -5703467522848303660L; // // public CrfModel(CrfTags<G> crfTags, CrfFeaturesAndFilters<K, G> features, ArrayList<BigDecimal> parameters) // { // super(); // this.crfTags = crfTags; // this.features = features; // this.parameters = parameters; // } // // // // public CrfTags<G> getCrfTags() // { // return crfTags; // } // public CrfFeaturesAndFilters<K, G> getFeatures() // { // return features; // } // public ArrayList<BigDecimal> getParameters() // { // return parameters; // } // // // // private final CrfTags<G> crfTags; // private final CrfFeaturesAndFilters<K, G> features; // private final ArrayList<BigDecimal> parameters; // } // // Path: src/main/java/com/asher_stern/crf/crf/filters/FilterFactory.java // public interface FilterFactory<K, G> extends Serializable // { // /** // * Creates a set of filters for the given token,tag, and tag-of-previous-token. // * The convention is as follows: // * Let each feature f be a feature that <B>might</B> return non-zero for the given token,tag,previous-tag. // * That feature is encapsulated with a {@link Filter} in a {@link CrfFilteredFeature}. Let's call this filter "t". // * For that filter there exist one filter in the set returned by this function, name it "t'", such that "t'" equals to "t". // * // * // * @param sequence A sequence of tokens // * @param tokenIndex An index of a token in that sequence // * @param currentTag A tag for that token // * @param previousTag A tag for the token which immediately precedes that token. // * @return A set of filters as described above. // */ // public Set<Filter<K, G>> createFilters(K[] sequence, int tokenIndex, G currentTag, G previousTag); // } // // Path: src/main/java/com/asher_stern/crf/utilities/TaggedToken.java // public class TaggedToken<K,G> // { // public TaggedToken(K token, G tag) // { // super(); // this.token = token; // this.tag = tag; // } // // // // public K getToken() // { // return token; // } // public G getTag() // { // return tag; // } // // // // // @Override // public String toString() // { // return "CrfTaggedToken [getToken()=" + getToken() + ", getTag()=" // + getTag() + "]"; // } // // // // // // // @Override // public int hashCode() // { // final int prime = 31; // int result = 1; // result = prime * result + ((tag == null) ? 0 : tag.hashCode()); // result = prime * result + ((token == null) ? 0 : token.hashCode()); // return result; // } // // // // @Override // public boolean equals(Object obj) // { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // TaggedToken<?,?> other = (TaggedToken<?,?>) obj; // if (tag == null) // { // if (other.tag != null) // return false; // } else if (!tag.equals(other.tag)) // return false; // if (token == null) // { // if (other.token != null) // return false; // } else if (!token.equals(other.token)) // return false; // return true; // } // // // // // // // private final K token; // private final G tag; // } // Path: src/main/java/com/asher_stern/crf/crf/run/ExampleMain.java import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Arrays; import java.util.List; import java.util.Set; import com.asher_stern.crf.crf.CrfModel; import com.asher_stern.crf.crf.filters.FilterFactory; import com.asher_stern.crf.utilities.TaggedToken; package com.asher_stern.crf.crf.run; /** * An example for usage of CRF. Don't run this class, but use it as a template for writing your own main class. * * @author Asher Stern * Date: Nov 23, 2014 * */ public class ExampleMain { @SuppressWarnings("unchecked") public static void main(String[] args) { // Load a corpus into the memory List<List<? extends TaggedToken<String, String> >> corpus = loadCorpusWhereTokensAndTagsAreStrings(); // Create trainer factory CrfTrainerFactory<String, String> trainerFactory = new CrfTrainerFactory<String, String>(); // Optionally call trainerFactory.setRegularizationSigmaSquareFactor() to override the default regularization factor. // Create trainer CrfTrainer<String,String> trainer = trainerFactory.createTrainer( corpus, (Iterable<? extends List<? extends TaggedToken<String, String> >> theCorpus, Set<String> tags) -> createFeatureGeneratorForGivenCorpus(theCorpus,tags), createFilterFactory()); // Run training with the loaded corpus. trainer.train(corpus); // Get the model
CrfModel<String, String> crfModel = trainer.getLearnedModel();
asher-stern/CRF
src/main/java/com/asher_stern/crf/crf/run/ExampleMain.java
// Path: src/main/java/com/asher_stern/crf/crf/CrfModel.java // public class CrfModel<K,G> implements Serializable // K = token, G = tag // { // private static final long serialVersionUID = -5703467522848303660L; // // public CrfModel(CrfTags<G> crfTags, CrfFeaturesAndFilters<K, G> features, ArrayList<BigDecimal> parameters) // { // super(); // this.crfTags = crfTags; // this.features = features; // this.parameters = parameters; // } // // // // public CrfTags<G> getCrfTags() // { // return crfTags; // } // public CrfFeaturesAndFilters<K, G> getFeatures() // { // return features; // } // public ArrayList<BigDecimal> getParameters() // { // return parameters; // } // // // // private final CrfTags<G> crfTags; // private final CrfFeaturesAndFilters<K, G> features; // private final ArrayList<BigDecimal> parameters; // } // // Path: src/main/java/com/asher_stern/crf/crf/filters/FilterFactory.java // public interface FilterFactory<K, G> extends Serializable // { // /** // * Creates a set of filters for the given token,tag, and tag-of-previous-token. // * The convention is as follows: // * Let each feature f be a feature that <B>might</B> return non-zero for the given token,tag,previous-tag. // * That feature is encapsulated with a {@link Filter} in a {@link CrfFilteredFeature}. Let's call this filter "t". // * For that filter there exist one filter in the set returned by this function, name it "t'", such that "t'" equals to "t". // * // * // * @param sequence A sequence of tokens // * @param tokenIndex An index of a token in that sequence // * @param currentTag A tag for that token // * @param previousTag A tag for the token which immediately precedes that token. // * @return A set of filters as described above. // */ // public Set<Filter<K, G>> createFilters(K[] sequence, int tokenIndex, G currentTag, G previousTag); // } // // Path: src/main/java/com/asher_stern/crf/utilities/TaggedToken.java // public class TaggedToken<K,G> // { // public TaggedToken(K token, G tag) // { // super(); // this.token = token; // this.tag = tag; // } // // // // public K getToken() // { // return token; // } // public G getTag() // { // return tag; // } // // // // // @Override // public String toString() // { // return "CrfTaggedToken [getToken()=" + getToken() + ", getTag()=" // + getTag() + "]"; // } // // // // // // // @Override // public int hashCode() // { // final int prime = 31; // int result = 1; // result = prime * result + ((tag == null) ? 0 : tag.hashCode()); // result = prime * result + ((token == null) ? 0 : token.hashCode()); // return result; // } // // // // @Override // public boolean equals(Object obj) // { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // TaggedToken<?,?> other = (TaggedToken<?,?>) obj; // if (tag == null) // { // if (other.tag != null) // return false; // } else if (!tag.equals(other.tag)) // return false; // if (token == null) // { // if (other.token != null) // return false; // } else if (!token.equals(other.token)) // return false; // return true; // } // // // // // // // private final K token; // private final G tag; // }
import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Arrays; import java.util.List; import java.util.Set; import com.asher_stern.crf.crf.CrfModel; import com.asher_stern.crf.crf.filters.FilterFactory; import com.asher_stern.crf.utilities.TaggedToken;
// Later... Load the model from the disk crfModel = (CrfModel<String, String>) load(file); // Create a CrfInferencePerformer, to find tags for test data CrfInferencePerformer<String, String> inferencePerformer = new CrfInferencePerformer<String, String>(crfModel); // Test: List<String> test = Arrays.asList( "This is a sequence for test data".split("\\s+") ); List<TaggedToken<String, String>> result = inferencePerformer.tagSequence(test); // Print the result: for (TaggedToken<String, String> taggedToken : result) { System.out.println("Tag for: "+taggedToken.getToken()+" is "+taggedToken.getTag()); } } public static List<List<? extends TaggedToken<String, String> >> loadCorpusWhereTokensAndTagsAreStrings() { // Implement this method return null; } public static CrfFeatureGenerator<String, String> createFeatureGeneratorForGivenCorpus(Iterable<? extends List<? extends TaggedToken<String, String> >> corpus, Set<String> tags) { // Implement this method return null; }
// Path: src/main/java/com/asher_stern/crf/crf/CrfModel.java // public class CrfModel<K,G> implements Serializable // K = token, G = tag // { // private static final long serialVersionUID = -5703467522848303660L; // // public CrfModel(CrfTags<G> crfTags, CrfFeaturesAndFilters<K, G> features, ArrayList<BigDecimal> parameters) // { // super(); // this.crfTags = crfTags; // this.features = features; // this.parameters = parameters; // } // // // // public CrfTags<G> getCrfTags() // { // return crfTags; // } // public CrfFeaturesAndFilters<K, G> getFeatures() // { // return features; // } // public ArrayList<BigDecimal> getParameters() // { // return parameters; // } // // // // private final CrfTags<G> crfTags; // private final CrfFeaturesAndFilters<K, G> features; // private final ArrayList<BigDecimal> parameters; // } // // Path: src/main/java/com/asher_stern/crf/crf/filters/FilterFactory.java // public interface FilterFactory<K, G> extends Serializable // { // /** // * Creates a set of filters for the given token,tag, and tag-of-previous-token. // * The convention is as follows: // * Let each feature f be a feature that <B>might</B> return non-zero for the given token,tag,previous-tag. // * That feature is encapsulated with a {@link Filter} in a {@link CrfFilteredFeature}. Let's call this filter "t". // * For that filter there exist one filter in the set returned by this function, name it "t'", such that "t'" equals to "t". // * // * // * @param sequence A sequence of tokens // * @param tokenIndex An index of a token in that sequence // * @param currentTag A tag for that token // * @param previousTag A tag for the token which immediately precedes that token. // * @return A set of filters as described above. // */ // public Set<Filter<K, G>> createFilters(K[] sequence, int tokenIndex, G currentTag, G previousTag); // } // // Path: src/main/java/com/asher_stern/crf/utilities/TaggedToken.java // public class TaggedToken<K,G> // { // public TaggedToken(K token, G tag) // { // super(); // this.token = token; // this.tag = tag; // } // // // // public K getToken() // { // return token; // } // public G getTag() // { // return tag; // } // // // // // @Override // public String toString() // { // return "CrfTaggedToken [getToken()=" + getToken() + ", getTag()=" // + getTag() + "]"; // } // // // // // // // @Override // public int hashCode() // { // final int prime = 31; // int result = 1; // result = prime * result + ((tag == null) ? 0 : tag.hashCode()); // result = prime * result + ((token == null) ? 0 : token.hashCode()); // return result; // } // // // // @Override // public boolean equals(Object obj) // { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // TaggedToken<?,?> other = (TaggedToken<?,?>) obj; // if (tag == null) // { // if (other.tag != null) // return false; // } else if (!tag.equals(other.tag)) // return false; // if (token == null) // { // if (other.token != null) // return false; // } else if (!token.equals(other.token)) // return false; // return true; // } // // // // // // // private final K token; // private final G tag; // } // Path: src/main/java/com/asher_stern/crf/crf/run/ExampleMain.java import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Arrays; import java.util.List; import java.util.Set; import com.asher_stern.crf.crf.CrfModel; import com.asher_stern.crf.crf.filters.FilterFactory; import com.asher_stern.crf.utilities.TaggedToken; // Later... Load the model from the disk crfModel = (CrfModel<String, String>) load(file); // Create a CrfInferencePerformer, to find tags for test data CrfInferencePerformer<String, String> inferencePerformer = new CrfInferencePerformer<String, String>(crfModel); // Test: List<String> test = Arrays.asList( "This is a sequence for test data".split("\\s+") ); List<TaggedToken<String, String>> result = inferencePerformer.tagSequence(test); // Print the result: for (TaggedToken<String, String> taggedToken : result) { System.out.println("Tag for: "+taggedToken.getToken()+" is "+taggedToken.getTag()); } } public static List<List<? extends TaggedToken<String, String> >> loadCorpusWhereTokensAndTagsAreStrings() { // Implement this method return null; } public static CrfFeatureGenerator<String, String> createFeatureGeneratorForGivenCorpus(Iterable<? extends List<? extends TaggedToken<String, String> >> corpus, Set<String> tags) { // Implement this method return null; }
public static FilterFactory<String, String> createFilterFactory()
asher-stern/CRF
src/main/java/com/asher_stern/crf/postagging/postaggers/crf/features/CaseInsensitiveTokenAndTagFeature.java
// Path: src/main/java/com/asher_stern/crf/utilities/MiscellaneousUtilities.java // public static <T> boolean equalObjects(T t1, T t2) // { // if (t1==t2) return true; // if ( (t1==null) || (t2==null) ) return false; // return t1.equals(t2); // } // // Path: src/main/java/com/asher_stern/crf/crf/CrfFeature.java // public abstract class CrfFeature<K,G> implements Serializable // K = token, G = tag // { // private static final long serialVersionUID = 5422105702440104947L; // // public abstract double value(K[] sequence, int indexInSequence, G currentTag, G previousTag); // // public abstract boolean equals(Object obj); // public abstract int hashCode(); // }
import static com.asher_stern.crf.utilities.MiscellaneousUtilities.equalObjects; import com.asher_stern.crf.crf.CrfFeature;
package com.asher_stern.crf.postagging.postaggers.crf.features; /** * A CRF feature the models that a certain token is assigned a certain tag. * The token is considered in a case-insensitivity manner, i.e., "AbC" is considered equal to "abc". * * @author Asher Stern * Date: Nov 20, 2014 * */ public class CaseInsensitiveTokenAndTagFeature extends CrfFeature<String, String> { private static final long serialVersionUID = 2767104089617969815L; public CaseInsensitiveTokenAndTagFeature(String token, String tag) { super(); this.tokenLowerCase = ( (token==null)?null:token.toLowerCase() ); this.tag = tag; } @Override public double value(String[] sequence, int indexInSequence, String currentTag, String previousTag) { String tokenInSentence_lowerCase = sequence[indexInSequence]; if (tokenInSentence_lowerCase!=null) { tokenInSentence_lowerCase = tokenInSentence_lowerCase.toLowerCase(); } double ret = 0.0;
// Path: src/main/java/com/asher_stern/crf/utilities/MiscellaneousUtilities.java // public static <T> boolean equalObjects(T t1, T t2) // { // if (t1==t2) return true; // if ( (t1==null) || (t2==null) ) return false; // return t1.equals(t2); // } // // Path: src/main/java/com/asher_stern/crf/crf/CrfFeature.java // public abstract class CrfFeature<K,G> implements Serializable // K = token, G = tag // { // private static final long serialVersionUID = 5422105702440104947L; // // public abstract double value(K[] sequence, int indexInSequence, G currentTag, G previousTag); // // public abstract boolean equals(Object obj); // public abstract int hashCode(); // } // Path: src/main/java/com/asher_stern/crf/postagging/postaggers/crf/features/CaseInsensitiveTokenAndTagFeature.java import static com.asher_stern.crf.utilities.MiscellaneousUtilities.equalObjects; import com.asher_stern.crf.crf.CrfFeature; package com.asher_stern.crf.postagging.postaggers.crf.features; /** * A CRF feature the models that a certain token is assigned a certain tag. * The token is considered in a case-insensitivity manner, i.e., "AbC" is considered equal to "abc". * * @author Asher Stern * Date: Nov 20, 2014 * */ public class CaseInsensitiveTokenAndTagFeature extends CrfFeature<String, String> { private static final long serialVersionUID = 2767104089617969815L; public CaseInsensitiveTokenAndTagFeature(String token, String tag) { super(); this.tokenLowerCase = ( (token==null)?null:token.toLowerCase() ); this.tag = tag; } @Override public double value(String[] sequence, int indexInSequence, String currentTag, String previousTag) { String tokenInSentence_lowerCase = sequence[indexInSequence]; if (tokenInSentence_lowerCase!=null) { tokenInSentence_lowerCase = tokenInSentence_lowerCase.toLowerCase(); } double ret = 0.0;
if ( equalObjects(tokenInSentence_lowerCase, tokenLowerCase) && equalObjects(currentTag, tag))
asher-stern/CRF
src/main/java/com/asher_stern/crf/postagging/evaluation/AccuracyEvaluator.java
// Path: src/main/java/com/asher_stern/crf/postagging/postaggers/PosTagger.java // public interface PosTagger // { // /** // * Assigns tags for each token in the given sentence. // * @param sentence An input sentence, given as a list of tokens. // * @return The tagged sentence. // */ // public List<TaggedToken<String,String>> tagSentence(List<String> sentence); // } // // Path: src/main/java/com/asher_stern/crf/utilities/CrfException.java // public class CrfException extends RuntimeException // { // private static final long serialVersionUID = 5414394233000815286L; // // public CrfException() // { // super(); // } // // public CrfException(String message, Throwable cause, // boolean enableSuppression, boolean writableStackTrace) // { // super(message, cause, enableSuppression, writableStackTrace); // } // // public CrfException(String message, Throwable cause) // { // super(message, cause); // } // // public CrfException(String message) // { // super(message); // } // // public CrfException(Throwable cause) // { // super(cause); // } // // // } // // Path: src/main/java/com/asher_stern/crf/utilities/TaggedToken.java // public class TaggedToken<K,G> // { // public TaggedToken(K token, G tag) // { // super(); // this.token = token; // this.tag = tag; // } // // // // public K getToken() // { // return token; // } // public G getTag() // { // return tag; // } // // // // // @Override // public String toString() // { // return "CrfTaggedToken [getToken()=" + getToken() + ", getTag()=" // + getTag() + "]"; // } // // // // // // // @Override // public int hashCode() // { // final int prime = 31; // int result = 1; // result = prime * result + ((tag == null) ? 0 : tag.hashCode()); // result = prime * result + ((token == null) ? 0 : token.hashCode()); // return result; // } // // // // @Override // public boolean equals(Object obj) // { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // TaggedToken<?,?> other = (TaggedToken<?,?>) obj; // if (tag == null) // { // if (other.tag != null) // return false; // } else if (!tag.equals(other.tag)) // return false; // if (token == null) // { // if (other.token != null) // return false; // } else if (!token.equals(other.token)) // return false; // return true; // } // // // // // // // private final K token; // private final G tag; // }
import java.io.PrintWriter; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.apache.log4j.Logger; import com.asher_stern.crf.postagging.postaggers.PosTagger; import com.asher_stern.crf.utilities.CrfException; import com.asher_stern.crf.utilities.TaggedToken;
package com.asher_stern.crf.postagging.evaluation; /** * Evaluates the accuracy of a given {@link PosTagger} on a given test corpus. * * @author Asher Stern * Date: Nov 4, 2014 * */ public class AccuracyEvaluator {
// Path: src/main/java/com/asher_stern/crf/postagging/postaggers/PosTagger.java // public interface PosTagger // { // /** // * Assigns tags for each token in the given sentence. // * @param sentence An input sentence, given as a list of tokens. // * @return The tagged sentence. // */ // public List<TaggedToken<String,String>> tagSentence(List<String> sentence); // } // // Path: src/main/java/com/asher_stern/crf/utilities/CrfException.java // public class CrfException extends RuntimeException // { // private static final long serialVersionUID = 5414394233000815286L; // // public CrfException() // { // super(); // } // // public CrfException(String message, Throwable cause, // boolean enableSuppression, boolean writableStackTrace) // { // super(message, cause, enableSuppression, writableStackTrace); // } // // public CrfException(String message, Throwable cause) // { // super(message, cause); // } // // public CrfException(String message) // { // super(message); // } // // public CrfException(Throwable cause) // { // super(cause); // } // // // } // // Path: src/main/java/com/asher_stern/crf/utilities/TaggedToken.java // public class TaggedToken<K,G> // { // public TaggedToken(K token, G tag) // { // super(); // this.token = token; // this.tag = tag; // } // // // // public K getToken() // { // return token; // } // public G getTag() // { // return tag; // } // // // // // @Override // public String toString() // { // return "CrfTaggedToken [getToken()=" + getToken() + ", getTag()=" // + getTag() + "]"; // } // // // // // // // @Override // public int hashCode() // { // final int prime = 31; // int result = 1; // result = prime * result + ((tag == null) ? 0 : tag.hashCode()); // result = prime * result + ((token == null) ? 0 : token.hashCode()); // return result; // } // // // // @Override // public boolean equals(Object obj) // { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // TaggedToken<?,?> other = (TaggedToken<?,?>) obj; // if (tag == null) // { // if (other.tag != null) // return false; // } else if (!tag.equals(other.tag)) // return false; // if (token == null) // { // if (other.token != null) // return false; // } else if (!token.equals(other.token)) // return false; // return true; // } // // // // // // // private final K token; // private final G tag; // } // Path: src/main/java/com/asher_stern/crf/postagging/evaluation/AccuracyEvaluator.java import java.io.PrintWriter; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.apache.log4j.Logger; import com.asher_stern.crf.postagging.postaggers.PosTagger; import com.asher_stern.crf.utilities.CrfException; import com.asher_stern.crf.utilities.TaggedToken; package com.asher_stern.crf.postagging.evaluation; /** * Evaluates the accuracy of a given {@link PosTagger} on a given test corpus. * * @author Asher Stern * Date: Nov 4, 2014 * */ public class AccuracyEvaluator {
public AccuracyEvaluator(Iterable<? extends List<? extends TaggedToken<String, String>>> corpus, PosTagger posTagger)
asher-stern/CRF
src/main/java/com/asher_stern/crf/postagging/evaluation/AccuracyEvaluator.java
// Path: src/main/java/com/asher_stern/crf/postagging/postaggers/PosTagger.java // public interface PosTagger // { // /** // * Assigns tags for each token in the given sentence. // * @param sentence An input sentence, given as a list of tokens. // * @return The tagged sentence. // */ // public List<TaggedToken<String,String>> tagSentence(List<String> sentence); // } // // Path: src/main/java/com/asher_stern/crf/utilities/CrfException.java // public class CrfException extends RuntimeException // { // private static final long serialVersionUID = 5414394233000815286L; // // public CrfException() // { // super(); // } // // public CrfException(String message, Throwable cause, // boolean enableSuppression, boolean writableStackTrace) // { // super(message, cause, enableSuppression, writableStackTrace); // } // // public CrfException(String message, Throwable cause) // { // super(message, cause); // } // // public CrfException(String message) // { // super(message); // } // // public CrfException(Throwable cause) // { // super(cause); // } // // // } // // Path: src/main/java/com/asher_stern/crf/utilities/TaggedToken.java // public class TaggedToken<K,G> // { // public TaggedToken(K token, G tag) // { // super(); // this.token = token; // this.tag = tag; // } // // // // public K getToken() // { // return token; // } // public G getTag() // { // return tag; // } // // // // // @Override // public String toString() // { // return "CrfTaggedToken [getToken()=" + getToken() + ", getTag()=" // + getTag() + "]"; // } // // // // // // // @Override // public int hashCode() // { // final int prime = 31; // int result = 1; // result = prime * result + ((tag == null) ? 0 : tag.hashCode()); // result = prime * result + ((token == null) ? 0 : token.hashCode()); // return result; // } // // // // @Override // public boolean equals(Object obj) // { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // TaggedToken<?,?> other = (TaggedToken<?,?>) obj; // if (tag == null) // { // if (other.tag != null) // return false; // } else if (!tag.equals(other.tag)) // return false; // if (token == null) // { // if (other.token != null) // return false; // } else if (!token.equals(other.token)) // return false; // return true; // } // // // // // // // private final K token; // private final G tag; // }
import java.io.PrintWriter; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.apache.log4j.Logger; import com.asher_stern.crf.postagging.postaggers.PosTagger; import com.asher_stern.crf.utilities.CrfException; import com.asher_stern.crf.utilities.TaggedToken;
package com.asher_stern.crf.postagging.evaluation; /** * Evaluates the accuracy of a given {@link PosTagger} on a given test corpus. * * @author Asher Stern * Date: Nov 4, 2014 * */ public class AccuracyEvaluator {
// Path: src/main/java/com/asher_stern/crf/postagging/postaggers/PosTagger.java // public interface PosTagger // { // /** // * Assigns tags for each token in the given sentence. // * @param sentence An input sentence, given as a list of tokens. // * @return The tagged sentence. // */ // public List<TaggedToken<String,String>> tagSentence(List<String> sentence); // } // // Path: src/main/java/com/asher_stern/crf/utilities/CrfException.java // public class CrfException extends RuntimeException // { // private static final long serialVersionUID = 5414394233000815286L; // // public CrfException() // { // super(); // } // // public CrfException(String message, Throwable cause, // boolean enableSuppression, boolean writableStackTrace) // { // super(message, cause, enableSuppression, writableStackTrace); // } // // public CrfException(String message, Throwable cause) // { // super(message, cause); // } // // public CrfException(String message) // { // super(message); // } // // public CrfException(Throwable cause) // { // super(cause); // } // // // } // // Path: src/main/java/com/asher_stern/crf/utilities/TaggedToken.java // public class TaggedToken<K,G> // { // public TaggedToken(K token, G tag) // { // super(); // this.token = token; // this.tag = tag; // } // // // // public K getToken() // { // return token; // } // public G getTag() // { // return tag; // } // // // // // @Override // public String toString() // { // return "CrfTaggedToken [getToken()=" + getToken() + ", getTag()=" // + getTag() + "]"; // } // // // // // // // @Override // public int hashCode() // { // final int prime = 31; // int result = 1; // result = prime * result + ((tag == null) ? 0 : tag.hashCode()); // result = prime * result + ((token == null) ? 0 : token.hashCode()); // return result; // } // // // // @Override // public boolean equals(Object obj) // { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // TaggedToken<?,?> other = (TaggedToken<?,?>) obj; // if (tag == null) // { // if (other.tag != null) // return false; // } else if (!tag.equals(other.tag)) // return false; // if (token == null) // { // if (other.token != null) // return false; // } else if (!token.equals(other.token)) // return false; // return true; // } // // // // // // // private final K token; // private final G tag; // } // Path: src/main/java/com/asher_stern/crf/postagging/evaluation/AccuracyEvaluator.java import java.io.PrintWriter; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.apache.log4j.Logger; import com.asher_stern.crf.postagging.postaggers.PosTagger; import com.asher_stern.crf.utilities.CrfException; import com.asher_stern.crf.utilities.TaggedToken; package com.asher_stern.crf.postagging.evaluation; /** * Evaluates the accuracy of a given {@link PosTagger} on a given test corpus. * * @author Asher Stern * Date: Nov 4, 2014 * */ public class AccuracyEvaluator {
public AccuracyEvaluator(Iterable<? extends List<? extends TaggedToken<String, String>>> corpus, PosTagger posTagger)
asher-stern/CRF
src/main/java/com/asher_stern/crf/postagging/evaluation/AccuracyEvaluator.java
// Path: src/main/java/com/asher_stern/crf/postagging/postaggers/PosTagger.java // public interface PosTagger // { // /** // * Assigns tags for each token in the given sentence. // * @param sentence An input sentence, given as a list of tokens. // * @return The tagged sentence. // */ // public List<TaggedToken<String,String>> tagSentence(List<String> sentence); // } // // Path: src/main/java/com/asher_stern/crf/utilities/CrfException.java // public class CrfException extends RuntimeException // { // private static final long serialVersionUID = 5414394233000815286L; // // public CrfException() // { // super(); // } // // public CrfException(String message, Throwable cause, // boolean enableSuppression, boolean writableStackTrace) // { // super(message, cause, enableSuppression, writableStackTrace); // } // // public CrfException(String message, Throwable cause) // { // super(message, cause); // } // // public CrfException(String message) // { // super(message); // } // // public CrfException(Throwable cause) // { // super(cause); // } // // // } // // Path: src/main/java/com/asher_stern/crf/utilities/TaggedToken.java // public class TaggedToken<K,G> // { // public TaggedToken(K token, G tag) // { // super(); // this.token = token; // this.tag = tag; // } // // // // public K getToken() // { // return token; // } // public G getTag() // { // return tag; // } // // // // // @Override // public String toString() // { // return "CrfTaggedToken [getToken()=" + getToken() + ", getTag()=" // + getTag() + "]"; // } // // // // // // // @Override // public int hashCode() // { // final int prime = 31; // int result = 1; // result = prime * result + ((tag == null) ? 0 : tag.hashCode()); // result = prime * result + ((token == null) ? 0 : token.hashCode()); // return result; // } // // // // @Override // public boolean equals(Object obj) // { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // TaggedToken<?,?> other = (TaggedToken<?,?>) obj; // if (tag == null) // { // if (other.tag != null) // return false; // } else if (!tag.equals(other.tag)) // return false; // if (token == null) // { // if (other.token != null) // return false; // } else if (!token.equals(other.token)) // return false; // return true; // } // // // // // // // private final K token; // private final G tag; // }
import java.io.PrintWriter; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.apache.log4j.Logger; import com.asher_stern.crf.postagging.postaggers.PosTagger; import com.asher_stern.crf.utilities.CrfException; import com.asher_stern.crf.utilities.TaggedToken;
/** * Returns how many tags were incorrectly annotated by the {@link PosTagger}. * @return */ public long getIncorrect() { return incorrect; } /** * Returns the accuracy over tag-annotations in the given corpus of the {@link PosTagger}. * @return */ public double getAccuracy() { return accuracy; } private void evaluateSentence(List<? extends TaggedToken<String,String>> taggedSentence, List<TaggedToken<String,String>> taggedByPosTagger) { Iterator<? extends TaggedToken<String,String>> iteratorTaggedOriginal = taggedSentence.iterator(); Iterator<? extends TaggedToken<String,String>> iteratorTaggedByPosTagger = taggedByPosTagger.iterator(); while (iteratorTaggedOriginal.hasNext() && iteratorTaggedByPosTagger.hasNext()) { TaggedToken<String,String> original = iteratorTaggedOriginal.next(); TaggedToken<String,String> byPosTagger = iteratorTaggedByPosTagger.next();
// Path: src/main/java/com/asher_stern/crf/postagging/postaggers/PosTagger.java // public interface PosTagger // { // /** // * Assigns tags for each token in the given sentence. // * @param sentence An input sentence, given as a list of tokens. // * @return The tagged sentence. // */ // public List<TaggedToken<String,String>> tagSentence(List<String> sentence); // } // // Path: src/main/java/com/asher_stern/crf/utilities/CrfException.java // public class CrfException extends RuntimeException // { // private static final long serialVersionUID = 5414394233000815286L; // // public CrfException() // { // super(); // } // // public CrfException(String message, Throwable cause, // boolean enableSuppression, boolean writableStackTrace) // { // super(message, cause, enableSuppression, writableStackTrace); // } // // public CrfException(String message, Throwable cause) // { // super(message, cause); // } // // public CrfException(String message) // { // super(message); // } // // public CrfException(Throwable cause) // { // super(cause); // } // // // } // // Path: src/main/java/com/asher_stern/crf/utilities/TaggedToken.java // public class TaggedToken<K,G> // { // public TaggedToken(K token, G tag) // { // super(); // this.token = token; // this.tag = tag; // } // // // // public K getToken() // { // return token; // } // public G getTag() // { // return tag; // } // // // // // @Override // public String toString() // { // return "CrfTaggedToken [getToken()=" + getToken() + ", getTag()=" // + getTag() + "]"; // } // // // // // // // @Override // public int hashCode() // { // final int prime = 31; // int result = 1; // result = prime * result + ((tag == null) ? 0 : tag.hashCode()); // result = prime * result + ((token == null) ? 0 : token.hashCode()); // return result; // } // // // // @Override // public boolean equals(Object obj) // { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // TaggedToken<?,?> other = (TaggedToken<?,?>) obj; // if (tag == null) // { // if (other.tag != null) // return false; // } else if (!tag.equals(other.tag)) // return false; // if (token == null) // { // if (other.token != null) // return false; // } else if (!token.equals(other.token)) // return false; // return true; // } // // // // // // // private final K token; // private final G tag; // } // Path: src/main/java/com/asher_stern/crf/postagging/evaluation/AccuracyEvaluator.java import java.io.PrintWriter; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.apache.log4j.Logger; import com.asher_stern.crf.postagging.postaggers.PosTagger; import com.asher_stern.crf.utilities.CrfException; import com.asher_stern.crf.utilities.TaggedToken; /** * Returns how many tags were incorrectly annotated by the {@link PosTagger}. * @return */ public long getIncorrect() { return incorrect; } /** * Returns the accuracy over tag-annotations in the given corpus of the {@link PosTagger}. * @return */ public double getAccuracy() { return accuracy; } private void evaluateSentence(List<? extends TaggedToken<String,String>> taggedSentence, List<TaggedToken<String,String>> taggedByPosTagger) { Iterator<? extends TaggedToken<String,String>> iteratorTaggedOriginal = taggedSentence.iterator(); Iterator<? extends TaggedToken<String,String>> iteratorTaggedByPosTagger = taggedByPosTagger.iterator(); while (iteratorTaggedOriginal.hasNext() && iteratorTaggedByPosTagger.hasNext()) { TaggedToken<String,String> original = iteratorTaggedOriginal.next(); TaggedToken<String,String> byPosTagger = iteratorTaggedByPosTagger.next();
if (!(equals(original.getToken(),byPosTagger.getToken()))) {throw new CrfException("Tokens not equal in evaluation.");}
asher-stern/CRF
src/main/java/com/asher_stern/crf/postagging/data/TrainTestPosTagCorpus.java
// Path: src/main/java/com/asher_stern/crf/utilities/TaggedToken.java // public class TaggedToken<K,G> // { // public TaggedToken(K token, G tag) // { // super(); // this.token = token; // this.tag = tag; // } // // // // public K getToken() // { // return token; // } // public G getTag() // { // return tag; // } // // // // // @Override // public String toString() // { // return "CrfTaggedToken [getToken()=" + getToken() + ", getTag()=" // + getTag() + "]"; // } // // // // // // // @Override // public int hashCode() // { // final int prime = 31; // int result = 1; // result = prime * result + ((tag == null) ? 0 : tag.hashCode()); // result = prime * result + ((token == null) ? 0 : token.hashCode()); // return result; // } // // // // @Override // public boolean equals(Object obj) // { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // TaggedToken<?,?> other = (TaggedToken<?,?>) obj; // if (tag == null) // { // if (other.tag != null) // return false; // } else if (!tag.equals(other.tag)) // return false; // if (token == null) // { // if (other.token != null) // return false; // } else if (!token.equals(other.token)) // return false; // return true; // } // // // // // // // private final K token; // private final G tag; // }
import java.util.Iterator; import java.util.List; import com.asher_stern.crf.utilities.TaggedToken;
package com.asher_stern.crf.postagging.data; /** * Splits a given corpus into a train corpus and a test corpus. * <P> * If train-size is provided, and is larger than zero, then the first "train-size" sentences are returned as the train corpus. * Otherwise, the whole corpus is provided as the train corpus. * <P> * If the "train-size" is provided, then the test corpus contains <B>only</B> sentences that are not included in the train corpus. * If "test-size" is provided, then only the first "test-size" sentences are included in the test corpus, where "the first sentences" * means those which immediately the last sentence in the training (if "train-size" > 0), or the first sentences in the original * corpus (if "train-size<=0). * * * @author Asher Stern * Date: Nov 5, 2014 * */ public class TrainTestPosTagCorpus<K,G> {
// Path: src/main/java/com/asher_stern/crf/utilities/TaggedToken.java // public class TaggedToken<K,G> // { // public TaggedToken(K token, G tag) // { // super(); // this.token = token; // this.tag = tag; // } // // // // public K getToken() // { // return token; // } // public G getTag() // { // return tag; // } // // // // // @Override // public String toString() // { // return "CrfTaggedToken [getToken()=" + getToken() + ", getTag()=" // + getTag() + "]"; // } // // // // // // // @Override // public int hashCode() // { // final int prime = 31; // int result = 1; // result = prime * result + ((tag == null) ? 0 : tag.hashCode()); // result = prime * result + ((token == null) ? 0 : token.hashCode()); // return result; // } // // // // @Override // public boolean equals(Object obj) // { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // TaggedToken<?,?> other = (TaggedToken<?,?>) obj; // if (tag == null) // { // if (other.tag != null) // return false; // } else if (!tag.equals(other.tag)) // return false; // if (token == null) // { // if (other.token != null) // return false; // } else if (!token.equals(other.token)) // return false; // return true; // } // // // // // // // private final K token; // private final G tag; // } // Path: src/main/java/com/asher_stern/crf/postagging/data/TrainTestPosTagCorpus.java import java.util.Iterator; import java.util.List; import com.asher_stern.crf.utilities.TaggedToken; package com.asher_stern.crf.postagging.data; /** * Splits a given corpus into a train corpus and a test corpus. * <P> * If train-size is provided, and is larger than zero, then the first "train-size" sentences are returned as the train corpus. * Otherwise, the whole corpus is provided as the train corpus. * <P> * If the "train-size" is provided, then the test corpus contains <B>only</B> sentences that are not included in the train corpus. * If "test-size" is provided, then only the first "test-size" sentences are included in the test corpus, where "the first sentences" * means those which immediately the last sentence in the training (if "train-size" > 0), or the first sentences in the original * corpus (if "train-size<=0). * * * @author Asher Stern * Date: Nov 5, 2014 * */ public class TrainTestPosTagCorpus<K,G> {
public TrainTestPosTagCorpus(int trainSize, Iterable<List<TaggedToken<K, G>>> realCorpus)
asher-stern/CRF
src/main/java/com/asher_stern/crf/postagging/postaggers/crf/features/TokenAndTagFeature.java
// Path: src/main/java/com/asher_stern/crf/utilities/MiscellaneousUtilities.java // public static <T> boolean equalObjects(T t1, T t2) // { // if (t1==t2) return true; // if ( (t1==null) || (t2==null) ) return false; // return t1.equals(t2); // } // // Path: src/main/java/com/asher_stern/crf/crf/CrfFeature.java // public abstract class CrfFeature<K,G> implements Serializable // K = token, G = tag // { // private static final long serialVersionUID = 5422105702440104947L; // // public abstract double value(K[] sequence, int indexInSequence, G currentTag, G previousTag); // // public abstract boolean equals(Object obj); // public abstract int hashCode(); // }
import static com.asher_stern.crf.utilities.MiscellaneousUtilities.equalObjects; import com.asher_stern.crf.crf.CrfFeature;
package com.asher_stern.crf.postagging.postaggers.crf.features; /** * A feature that models that the given token is assigned the given tag. Tokens are considered case-sensitive, i.e., * "AbC" is <B>NOT</B> equal to "abc". * <BR> * In practice, this feature is not used. Rather {@link CaseInsensitiveTokenAndTagFeature} is used. * * @author Asher Stern * Date: Nov 10, 2014 * */ public class TokenAndTagFeature extends CrfFeature<String, String> { private static final long serialVersionUID = -3196603759120595624L; public TokenAndTagFeature(String forToken, String forTag) { super(); this.forToken = forToken; this.forTag = forTag; } @Override public double value(String[] sequence, int indexInSequence, String currentTag, String previousTag) { double ret = 0.0;
// Path: src/main/java/com/asher_stern/crf/utilities/MiscellaneousUtilities.java // public static <T> boolean equalObjects(T t1, T t2) // { // if (t1==t2) return true; // if ( (t1==null) || (t2==null) ) return false; // return t1.equals(t2); // } // // Path: src/main/java/com/asher_stern/crf/crf/CrfFeature.java // public abstract class CrfFeature<K,G> implements Serializable // K = token, G = tag // { // private static final long serialVersionUID = 5422105702440104947L; // // public abstract double value(K[] sequence, int indexInSequence, G currentTag, G previousTag); // // public abstract boolean equals(Object obj); // public abstract int hashCode(); // } // Path: src/main/java/com/asher_stern/crf/postagging/postaggers/crf/features/TokenAndTagFeature.java import static com.asher_stern.crf.utilities.MiscellaneousUtilities.equalObjects; import com.asher_stern.crf.crf.CrfFeature; package com.asher_stern.crf.postagging.postaggers.crf.features; /** * A feature that models that the given token is assigned the given tag. Tokens are considered case-sensitive, i.e., * "AbC" is <B>NOT</B> equal to "abc". * <BR> * In practice, this feature is not used. Rather {@link CaseInsensitiveTokenAndTagFeature} is used. * * @author Asher Stern * Date: Nov 10, 2014 * */ public class TokenAndTagFeature extends CrfFeature<String, String> { private static final long serialVersionUID = -3196603759120595624L; public TokenAndTagFeature(String forToken, String forTag) { super(); this.forToken = forToken; this.forTag = forTag; } @Override public double value(String[] sequence, int indexInSequence, String currentTag, String previousTag) { double ret = 0.0;
if (equalObjects(sequence[indexInSequence],forToken) && equalObjects(currentTag,forTag))
asher-stern/CRF
src/main/java/com/asher_stern/crf/postagging/postaggers/crf/CrfPosTagger.java
// Path: src/main/java/com/asher_stern/crf/crf/run/CrfInferencePerformer.java // public class CrfInferencePerformer<K, G> // { // public CrfInferencePerformer(CrfModel<K, G> model) // { // super(); // this.model = model; // } // // /** // * Finds the most likely sequence of tags for the given sequence of tokens // * @param sequence A sequence of tokens // * @return A list in which each element is a {@link TaggedToken}, which encapsulates a token and its tag. // */ // public List<TaggedToken<K,G>> tagSequence(List<K> sequence) // { // if (null==sequence) {return null;} // if (sequence.size()==0) {return Collections.<TaggedToken<K,G>>emptyList();} // // @SuppressWarnings("unchecked") // K[] sentenceAsArray = sequence.toArray( (K[]) Array.newInstance(sequence.get(0).getClass(), sequence.size()) ); // CrfInferenceViterbi<K, G> crfInference = new CrfInferenceViterbi<K, G>(model, sentenceAsArray); // G[] bestTags = crfInference.inferBestTagSequence(); // // if (sentenceAsArray.length!=bestTags.length) {throw new CrfException("Inference failed. Array of tags differs in length from array of tokens.");} // // List<TaggedToken<K,G>> ret = new ArrayList<TaggedToken<K,G>>(); // for (int index=0;index<sentenceAsArray.length;++index) // { // ret.add(new TaggedToken<K,G>(sentenceAsArray[index], bestTags[index])); // } // return ret; // // } // // private final CrfModel<K, G> model; // } // // Path: src/main/java/com/asher_stern/crf/postagging/postaggers/PosTagger.java // public interface PosTagger // { // /** // * Assigns tags for each token in the given sentence. // * @param sentence An input sentence, given as a list of tokens. // * @return The tagged sentence. // */ // public List<TaggedToken<String,String>> tagSentence(List<String> sentence); // } // // Path: src/main/java/com/asher_stern/crf/utilities/TaggedToken.java // public class TaggedToken<K,G> // { // public TaggedToken(K token, G tag) // { // super(); // this.token = token; // this.tag = tag; // } // // // // public K getToken() // { // return token; // } // public G getTag() // { // return tag; // } // // // // // @Override // public String toString() // { // return "CrfTaggedToken [getToken()=" + getToken() + ", getTag()=" // + getTag() + "]"; // } // // // // // // // @Override // public int hashCode() // { // final int prime = 31; // int result = 1; // result = prime * result + ((tag == null) ? 0 : tag.hashCode()); // result = prime * result + ((token == null) ? 0 : token.hashCode()); // return result; // } // // // // @Override // public boolean equals(Object obj) // { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // TaggedToken<?,?> other = (TaggedToken<?,?>) obj; // if (tag == null) // { // if (other.tag != null) // return false; // } else if (!tag.equals(other.tag)) // return false; // if (token == null) // { // if (other.token != null) // return false; // } else if (!token.equals(other.token)) // return false; // return true; // } // // // // // // // private final K token; // private final G tag; // }
import java.util.List; import com.asher_stern.crf.crf.run.CrfInferencePerformer; import com.asher_stern.crf.postagging.postaggers.PosTagger; import com.asher_stern.crf.utilities.TaggedToken;
package com.asher_stern.crf.postagging.postaggers.crf; /** * A part-of-speech tagger which assigns the tags using CRF inference. CRF is an acronym of Conditional Random Fields. * * @author Asher Stern * Date: Nov 10, 2014 * */ public class CrfPosTagger implements PosTagger {
// Path: src/main/java/com/asher_stern/crf/crf/run/CrfInferencePerformer.java // public class CrfInferencePerformer<K, G> // { // public CrfInferencePerformer(CrfModel<K, G> model) // { // super(); // this.model = model; // } // // /** // * Finds the most likely sequence of tags for the given sequence of tokens // * @param sequence A sequence of tokens // * @return A list in which each element is a {@link TaggedToken}, which encapsulates a token and its tag. // */ // public List<TaggedToken<K,G>> tagSequence(List<K> sequence) // { // if (null==sequence) {return null;} // if (sequence.size()==0) {return Collections.<TaggedToken<K,G>>emptyList();} // // @SuppressWarnings("unchecked") // K[] sentenceAsArray = sequence.toArray( (K[]) Array.newInstance(sequence.get(0).getClass(), sequence.size()) ); // CrfInferenceViterbi<K, G> crfInference = new CrfInferenceViterbi<K, G>(model, sentenceAsArray); // G[] bestTags = crfInference.inferBestTagSequence(); // // if (sentenceAsArray.length!=bestTags.length) {throw new CrfException("Inference failed. Array of tags differs in length from array of tokens.");} // // List<TaggedToken<K,G>> ret = new ArrayList<TaggedToken<K,G>>(); // for (int index=0;index<sentenceAsArray.length;++index) // { // ret.add(new TaggedToken<K,G>(sentenceAsArray[index], bestTags[index])); // } // return ret; // // } // // private final CrfModel<K, G> model; // } // // Path: src/main/java/com/asher_stern/crf/postagging/postaggers/PosTagger.java // public interface PosTagger // { // /** // * Assigns tags for each token in the given sentence. // * @param sentence An input sentence, given as a list of tokens. // * @return The tagged sentence. // */ // public List<TaggedToken<String,String>> tagSentence(List<String> sentence); // } // // Path: src/main/java/com/asher_stern/crf/utilities/TaggedToken.java // public class TaggedToken<K,G> // { // public TaggedToken(K token, G tag) // { // super(); // this.token = token; // this.tag = tag; // } // // // // public K getToken() // { // return token; // } // public G getTag() // { // return tag; // } // // // // // @Override // public String toString() // { // return "CrfTaggedToken [getToken()=" + getToken() + ", getTag()=" // + getTag() + "]"; // } // // // // // // // @Override // public int hashCode() // { // final int prime = 31; // int result = 1; // result = prime * result + ((tag == null) ? 0 : tag.hashCode()); // result = prime * result + ((token == null) ? 0 : token.hashCode()); // return result; // } // // // // @Override // public boolean equals(Object obj) // { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // TaggedToken<?,?> other = (TaggedToken<?,?>) obj; // if (tag == null) // { // if (other.tag != null) // return false; // } else if (!tag.equals(other.tag)) // return false; // if (token == null) // { // if (other.token != null) // return false; // } else if (!token.equals(other.token)) // return false; // return true; // } // // // // // // // private final K token; // private final G tag; // } // Path: src/main/java/com/asher_stern/crf/postagging/postaggers/crf/CrfPosTagger.java import java.util.List; import com.asher_stern.crf.crf.run.CrfInferencePerformer; import com.asher_stern.crf.postagging.postaggers.PosTagger; import com.asher_stern.crf.utilities.TaggedToken; package com.asher_stern.crf.postagging.postaggers.crf; /** * A part-of-speech tagger which assigns the tags using CRF inference. CRF is an acronym of Conditional Random Fields. * * @author Asher Stern * Date: Nov 10, 2014 * */ public class CrfPosTagger implements PosTagger {
public CrfPosTagger(CrfInferencePerformer<String, String> inferencePerformer)
asher-stern/CRF
src/main/java/com/asher_stern/crf/postagging/postaggers/crf/CrfPosTagger.java
// Path: src/main/java/com/asher_stern/crf/crf/run/CrfInferencePerformer.java // public class CrfInferencePerformer<K, G> // { // public CrfInferencePerformer(CrfModel<K, G> model) // { // super(); // this.model = model; // } // // /** // * Finds the most likely sequence of tags for the given sequence of tokens // * @param sequence A sequence of tokens // * @return A list in which each element is a {@link TaggedToken}, which encapsulates a token and its tag. // */ // public List<TaggedToken<K,G>> tagSequence(List<K> sequence) // { // if (null==sequence) {return null;} // if (sequence.size()==0) {return Collections.<TaggedToken<K,G>>emptyList();} // // @SuppressWarnings("unchecked") // K[] sentenceAsArray = sequence.toArray( (K[]) Array.newInstance(sequence.get(0).getClass(), sequence.size()) ); // CrfInferenceViterbi<K, G> crfInference = new CrfInferenceViterbi<K, G>(model, sentenceAsArray); // G[] bestTags = crfInference.inferBestTagSequence(); // // if (sentenceAsArray.length!=bestTags.length) {throw new CrfException("Inference failed. Array of tags differs in length from array of tokens.");} // // List<TaggedToken<K,G>> ret = new ArrayList<TaggedToken<K,G>>(); // for (int index=0;index<sentenceAsArray.length;++index) // { // ret.add(new TaggedToken<K,G>(sentenceAsArray[index], bestTags[index])); // } // return ret; // // } // // private final CrfModel<K, G> model; // } // // Path: src/main/java/com/asher_stern/crf/postagging/postaggers/PosTagger.java // public interface PosTagger // { // /** // * Assigns tags for each token in the given sentence. // * @param sentence An input sentence, given as a list of tokens. // * @return The tagged sentence. // */ // public List<TaggedToken<String,String>> tagSentence(List<String> sentence); // } // // Path: src/main/java/com/asher_stern/crf/utilities/TaggedToken.java // public class TaggedToken<K,G> // { // public TaggedToken(K token, G tag) // { // super(); // this.token = token; // this.tag = tag; // } // // // // public K getToken() // { // return token; // } // public G getTag() // { // return tag; // } // // // // // @Override // public String toString() // { // return "CrfTaggedToken [getToken()=" + getToken() + ", getTag()=" // + getTag() + "]"; // } // // // // // // // @Override // public int hashCode() // { // final int prime = 31; // int result = 1; // result = prime * result + ((tag == null) ? 0 : tag.hashCode()); // result = prime * result + ((token == null) ? 0 : token.hashCode()); // return result; // } // // // // @Override // public boolean equals(Object obj) // { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // TaggedToken<?,?> other = (TaggedToken<?,?>) obj; // if (tag == null) // { // if (other.tag != null) // return false; // } else if (!tag.equals(other.tag)) // return false; // if (token == null) // { // if (other.token != null) // return false; // } else if (!token.equals(other.token)) // return false; // return true; // } // // // // // // // private final K token; // private final G tag; // }
import java.util.List; import com.asher_stern.crf.crf.run.CrfInferencePerformer; import com.asher_stern.crf.postagging.postaggers.PosTagger; import com.asher_stern.crf.utilities.TaggedToken;
package com.asher_stern.crf.postagging.postaggers.crf; /** * A part-of-speech tagger which assigns the tags using CRF inference. CRF is an acronym of Conditional Random Fields. * * @author Asher Stern * Date: Nov 10, 2014 * */ public class CrfPosTagger implements PosTagger { public CrfPosTagger(CrfInferencePerformer<String, String> inferencePerformer) { this.inferencePerformer = inferencePerformer; } @Override
// Path: src/main/java/com/asher_stern/crf/crf/run/CrfInferencePerformer.java // public class CrfInferencePerformer<K, G> // { // public CrfInferencePerformer(CrfModel<K, G> model) // { // super(); // this.model = model; // } // // /** // * Finds the most likely sequence of tags for the given sequence of tokens // * @param sequence A sequence of tokens // * @return A list in which each element is a {@link TaggedToken}, which encapsulates a token and its tag. // */ // public List<TaggedToken<K,G>> tagSequence(List<K> sequence) // { // if (null==sequence) {return null;} // if (sequence.size()==0) {return Collections.<TaggedToken<K,G>>emptyList();} // // @SuppressWarnings("unchecked") // K[] sentenceAsArray = sequence.toArray( (K[]) Array.newInstance(sequence.get(0).getClass(), sequence.size()) ); // CrfInferenceViterbi<K, G> crfInference = new CrfInferenceViterbi<K, G>(model, sentenceAsArray); // G[] bestTags = crfInference.inferBestTagSequence(); // // if (sentenceAsArray.length!=bestTags.length) {throw new CrfException("Inference failed. Array of tags differs in length from array of tokens.");} // // List<TaggedToken<K,G>> ret = new ArrayList<TaggedToken<K,G>>(); // for (int index=0;index<sentenceAsArray.length;++index) // { // ret.add(new TaggedToken<K,G>(sentenceAsArray[index], bestTags[index])); // } // return ret; // // } // // private final CrfModel<K, G> model; // } // // Path: src/main/java/com/asher_stern/crf/postagging/postaggers/PosTagger.java // public interface PosTagger // { // /** // * Assigns tags for each token in the given sentence. // * @param sentence An input sentence, given as a list of tokens. // * @return The tagged sentence. // */ // public List<TaggedToken<String,String>> tagSentence(List<String> sentence); // } // // Path: src/main/java/com/asher_stern/crf/utilities/TaggedToken.java // public class TaggedToken<K,G> // { // public TaggedToken(K token, G tag) // { // super(); // this.token = token; // this.tag = tag; // } // // // // public K getToken() // { // return token; // } // public G getTag() // { // return tag; // } // // // // // @Override // public String toString() // { // return "CrfTaggedToken [getToken()=" + getToken() + ", getTag()=" // + getTag() + "]"; // } // // // // // // // @Override // public int hashCode() // { // final int prime = 31; // int result = 1; // result = prime * result + ((tag == null) ? 0 : tag.hashCode()); // result = prime * result + ((token == null) ? 0 : token.hashCode()); // return result; // } // // // // @Override // public boolean equals(Object obj) // { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // TaggedToken<?,?> other = (TaggedToken<?,?>) obj; // if (tag == null) // { // if (other.tag != null) // return false; // } else if (!tag.equals(other.tag)) // return false; // if (token == null) // { // if (other.token != null) // return false; // } else if (!token.equals(other.token)) // return false; // return true; // } // // // // // // // private final K token; // private final G tag; // } // Path: src/main/java/com/asher_stern/crf/postagging/postaggers/crf/CrfPosTagger.java import java.util.List; import com.asher_stern.crf.crf.run.CrfInferencePerformer; import com.asher_stern.crf.postagging.postaggers.PosTagger; import com.asher_stern.crf.utilities.TaggedToken; package com.asher_stern.crf.postagging.postaggers.crf; /** * A part-of-speech tagger which assigns the tags using CRF inference. CRF is an acronym of Conditional Random Fields. * * @author Asher Stern * Date: Nov 10, 2014 * */ public class CrfPosTagger implements PosTagger { public CrfPosTagger(CrfInferencePerformer<String, String> inferencePerformer) { this.inferencePerformer = inferencePerformer; } @Override
public List<TaggedToken<String,String>> tagSentence(List<String> sentence)
asher-stern/CRF
src/main/java/com/asher_stern/crf/crf/CrfInferenceViterbi.java
// Path: src/main/java/com/asher_stern/crf/utilities/CrfException.java // public class CrfException extends RuntimeException // { // private static final long serialVersionUID = 5414394233000815286L; // // public CrfException() // { // super(); // } // // public CrfException(String message, Throwable cause, // boolean enableSuppression, boolean writableStackTrace) // { // super(message, cause, enableSuppression, writableStackTrace); // } // // public CrfException(String message, Throwable cause) // { // super(message, cause); // } // // public CrfException(String message) // { // super(message); // } // // public CrfException(Throwable cause) // { // super(cause); // } // // // } // // Path: src/main/java/com/asher_stern/crf/utilities/ArithmeticUtilities.java // public class ArithmeticUtilities // { // public static final MathContext MC = MathContext.DECIMAL128; // // public static final BigDecimal DOUBLE_MAX = big(Double.MAX_VALUE); // // public static final BigDecimal BIG_DECIMAL_E = big(Math.E); // public static final BigDecimal BIG_DECIMAL_TWO = new BigDecimal("2.0", MC); // public static final BigDecimal BIG_DECIMAL_E_TO_512 = BIG_DECIMAL_E.pow(512); // public static final BigDecimal BIG_DECIMAL_512 = new BigDecimal("512", MC); // public static final BigDecimal BIG_DECIMAL_LOG_DOUBLE_MAX = big(Math.log(Double.MAX_VALUE)); // // public static BigDecimal big(double d) // { // return new BigDecimal(d, MC); // } // // // public static BigDecimal log(BigDecimal d) // { // // long debug_counter = 0; // BigDecimal ret = BigDecimal.ZERO; // while (d.compareTo(DOUBLE_MAX)>0) // { // ret = safeAdd(ret, BIG_DECIMAL_512); // d = safeDivide(d, BIG_DECIMAL_E_TO_512); // if (d.compareTo(BigDecimal.ONE)<0) {throw new CrfException("Anomaly");} // // ++debug_counter; // } // ret = safeAdd(ret, big(Math.log(d.doubleValue()))); // // if ( logger.isDebugEnabled() && (debug_counter>0) ) {logger.debug("log() performed "+debug_counter+" iterations.");} // return ret; // } // // // public static BigDecimal exp(BigDecimal d) // { // if (d.compareTo(BIG_DECIMAL_LOG_DOUBLE_MAX)<=0) // { // return big(Math.exp(d.doubleValue())); // } // else // { // BigDecimal half = safeDivide(d, BIG_DECIMAL_TWO); // BigDecimal halfExp = exp(half); // return safeMultiply(halfExp, halfExp); // } // } // // public static BigDecimal safeAdd(final BigDecimal d1, final BigDecimal d2) // { // return d1.add(d2, MC); // } // // public static BigDecimal safeSubtract(final BigDecimal d1, final BigDecimal d2) // { // return d1.subtract(d2, MC); // } // // public static BigDecimal safeMultiply(final BigDecimal d1, final BigDecimal d2) // { // return d1.multiply(d2, MC); // } // // public static BigDecimal safeMultiply(final BigDecimal d1, final BigDecimal d2, BigDecimal...ds) // { // BigDecimal ret = safeMultiply(d1, d2); // for (BigDecimal d : ds) // { // ret = safeMultiply(ret, d); // } // return ret; // } // // public static BigDecimal safeDivide(final BigDecimal d1, final BigDecimal d2) // { // return d1.divide(d2, MC); // } // // @SuppressWarnings("unused") // private static final Logger logger = Logger.getLogger(ArithmeticUtilities.class); // }
import java.lang.reflect.Array; import java.math.BigDecimal; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; import com.asher_stern.crf.utilities.CrfException; import static com.asher_stern.crf.utilities.ArithmeticUtilities.*;
if (index>0) { valueByPrevious = safeMultiply(valueByPrevious, delta_viterbiForward[index-1].get(tagOfPrevious)); } boolean maxSoFarDetected = false; if (null==maxValueByPrevious) {maxSoFarDetected=true;} else if (maxValueByPrevious.compareTo(valueByPrevious) < 0) {maxSoFarDetected=true;} if (maxSoFarDetected) { maxValueByPrevious=valueByPrevious; tagOfPreviousWithMaxValue=tagOfPrevious; } } // end for-each previous-tag argmaxTags[index].put(tag,tagOfPreviousWithMaxValue); // i.e. If the tag for token number "index" is "tag", then the tag for token "index-1" is "tagOfPreviousWithMaxValue". delta_viterbiForwardCurrentToken.put(tag,maxValueByPrevious); } // end for-each current-tag delta_viterbiForward[index]=delta_viterbiForwardCurrentToken; } // end for-each token-in-sentence G tagOfLastToken = getArgMax(delta_viterbiForward[sentence.length-1]); result = (G[]) Array.newInstance(tagOfLastToken.getClass(), sentence.length); // new G[sentence.length]; G bestTagCurrentIndex = tagOfLastToken; for (int tokenIndex=sentence.length-1;tokenIndex>=0;--tokenIndex) { result[tokenIndex] = bestTagCurrentIndex; bestTagCurrentIndex = argmaxTags[tokenIndex].get(bestTagCurrentIndex); }
// Path: src/main/java/com/asher_stern/crf/utilities/CrfException.java // public class CrfException extends RuntimeException // { // private static final long serialVersionUID = 5414394233000815286L; // // public CrfException() // { // super(); // } // // public CrfException(String message, Throwable cause, // boolean enableSuppression, boolean writableStackTrace) // { // super(message, cause, enableSuppression, writableStackTrace); // } // // public CrfException(String message, Throwable cause) // { // super(message, cause); // } // // public CrfException(String message) // { // super(message); // } // // public CrfException(Throwable cause) // { // super(cause); // } // // // } // // Path: src/main/java/com/asher_stern/crf/utilities/ArithmeticUtilities.java // public class ArithmeticUtilities // { // public static final MathContext MC = MathContext.DECIMAL128; // // public static final BigDecimal DOUBLE_MAX = big(Double.MAX_VALUE); // // public static final BigDecimal BIG_DECIMAL_E = big(Math.E); // public static final BigDecimal BIG_DECIMAL_TWO = new BigDecimal("2.0", MC); // public static final BigDecimal BIG_DECIMAL_E_TO_512 = BIG_DECIMAL_E.pow(512); // public static final BigDecimal BIG_DECIMAL_512 = new BigDecimal("512", MC); // public static final BigDecimal BIG_DECIMAL_LOG_DOUBLE_MAX = big(Math.log(Double.MAX_VALUE)); // // public static BigDecimal big(double d) // { // return new BigDecimal(d, MC); // } // // // public static BigDecimal log(BigDecimal d) // { // // long debug_counter = 0; // BigDecimal ret = BigDecimal.ZERO; // while (d.compareTo(DOUBLE_MAX)>0) // { // ret = safeAdd(ret, BIG_DECIMAL_512); // d = safeDivide(d, BIG_DECIMAL_E_TO_512); // if (d.compareTo(BigDecimal.ONE)<0) {throw new CrfException("Anomaly");} // // ++debug_counter; // } // ret = safeAdd(ret, big(Math.log(d.doubleValue()))); // // if ( logger.isDebugEnabled() && (debug_counter>0) ) {logger.debug("log() performed "+debug_counter+" iterations.");} // return ret; // } // // // public static BigDecimal exp(BigDecimal d) // { // if (d.compareTo(BIG_DECIMAL_LOG_DOUBLE_MAX)<=0) // { // return big(Math.exp(d.doubleValue())); // } // else // { // BigDecimal half = safeDivide(d, BIG_DECIMAL_TWO); // BigDecimal halfExp = exp(half); // return safeMultiply(halfExp, halfExp); // } // } // // public static BigDecimal safeAdd(final BigDecimal d1, final BigDecimal d2) // { // return d1.add(d2, MC); // } // // public static BigDecimal safeSubtract(final BigDecimal d1, final BigDecimal d2) // { // return d1.subtract(d2, MC); // } // // public static BigDecimal safeMultiply(final BigDecimal d1, final BigDecimal d2) // { // return d1.multiply(d2, MC); // } // // public static BigDecimal safeMultiply(final BigDecimal d1, final BigDecimal d2, BigDecimal...ds) // { // BigDecimal ret = safeMultiply(d1, d2); // for (BigDecimal d : ds) // { // ret = safeMultiply(ret, d); // } // return ret; // } // // public static BigDecimal safeDivide(final BigDecimal d1, final BigDecimal d2) // { // return d1.divide(d2, MC); // } // // @SuppressWarnings("unused") // private static final Logger logger = Logger.getLogger(ArithmeticUtilities.class); // } // Path: src/main/java/com/asher_stern/crf/crf/CrfInferenceViterbi.java import java.lang.reflect.Array; import java.math.BigDecimal; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; import com.asher_stern.crf.utilities.CrfException; import static com.asher_stern.crf.utilities.ArithmeticUtilities.*; if (index>0) { valueByPrevious = safeMultiply(valueByPrevious, delta_viterbiForward[index-1].get(tagOfPrevious)); } boolean maxSoFarDetected = false; if (null==maxValueByPrevious) {maxSoFarDetected=true;} else if (maxValueByPrevious.compareTo(valueByPrevious) < 0) {maxSoFarDetected=true;} if (maxSoFarDetected) { maxValueByPrevious=valueByPrevious; tagOfPreviousWithMaxValue=tagOfPrevious; } } // end for-each previous-tag argmaxTags[index].put(tag,tagOfPreviousWithMaxValue); // i.e. If the tag for token number "index" is "tag", then the tag for token "index-1" is "tagOfPreviousWithMaxValue". delta_viterbiForwardCurrentToken.put(tag,maxValueByPrevious); } // end for-each current-tag delta_viterbiForward[index]=delta_viterbiForwardCurrentToken; } // end for-each token-in-sentence G tagOfLastToken = getArgMax(delta_viterbiForward[sentence.length-1]); result = (G[]) Array.newInstance(tagOfLastToken.getClass(), sentence.length); // new G[sentence.length]; G bestTagCurrentIndex = tagOfLastToken; for (int tokenIndex=sentence.length-1;tokenIndex>=0;--tokenIndex) { result[tokenIndex] = bestTagCurrentIndex; bestTagCurrentIndex = argmaxTags[tokenIndex].get(bestTagCurrentIndex); }
if (bestTagCurrentIndex!=null) {throw new CrfException("BUG");} // the tag of "before the first token" must be null.
asher-stern/CRF
src/main/java/com/asher_stern/crf/crf/run/CrfFeatureGenerator.java
// Path: src/main/java/com/asher_stern/crf/crf/filters/CrfFilteredFeature.java // public class CrfFilteredFeature<K, G> implements Serializable // { // private static final long serialVersionUID = -5835863638916635217L; // // public CrfFilteredFeature(CrfFeature<K, G> feature, Filter<K, G> filter, boolean whenNotFilteredIsAlwaysOne) // { // super(); // this.feature = feature; // this.filter = filter; // this.whenNotFilteredIsAlwaysOne = whenNotFilteredIsAlwaysOne; // } // // public CrfFeature<K, G> getFeature() // { // return feature; // } // // public Filter<K, G> getFilter() // { // return filter; // } // // /** // * Returns true if it is <B>guaranteed</B> that the feature returns 1.0 for any input for which its filter // * is equal to the filter returned by {@link #getFilter()}. // * @return // */ // public boolean isWhenNotFilteredIsAlwaysOne() // { // return whenNotFilteredIsAlwaysOne; // } // // // // // // @Override // public int hashCode() // { // final int prime = 31; // int result = 1; // result = prime * result + ((feature == null) ? 0 : feature.hashCode()); // result = prime * result + ((filter == null) ? 0 : filter.hashCode()); // result = prime * result + (whenNotFilteredIsAlwaysOne ? 1231 : 1237); // return result; // } // // @Override // public boolean equals(Object obj) // { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // CrfFilteredFeature<?,?> other = (CrfFilteredFeature<?,?>) obj; // if (feature == null) // { // if (other.feature != null) // return false; // } else if (!feature.equals(other.feature)) // return false; // if (filter == null) // { // if (other.filter != null) // return false; // } else if (!filter.equals(other.filter)) // return false; // if (whenNotFilteredIsAlwaysOne != other.whenNotFilteredIsAlwaysOne) // return false; // return true; // } // // // // protected final CrfFeature<K, G> feature; // protected final Filter<K, G> filter; // protected final boolean whenNotFilteredIsAlwaysOne; // } // // Path: src/main/java/com/asher_stern/crf/postagging/postaggers/crf/CrfPosTagger.java // public class CrfPosTagger implements PosTagger // { // public CrfPosTagger(CrfInferencePerformer<String, String> inferencePerformer) // { // this.inferencePerformer = inferencePerformer; // } // // @Override // public List<TaggedToken<String,String>> tagSentence(List<String> sentence) // { // return inferencePerformer.tagSequence(sentence); // } // // // private final CrfInferencePerformer<String, String> inferencePerformer; // // } // // Path: src/main/java/com/asher_stern/crf/utilities/TaggedToken.java // public class TaggedToken<K,G> // { // public TaggedToken(K token, G tag) // { // super(); // this.token = token; // this.tag = tag; // } // // // // public K getToken() // { // return token; // } // public G getTag() // { // return tag; // } // // // // // @Override // public String toString() // { // return "CrfTaggedToken [getToken()=" + getToken() + ", getTag()=" // + getTag() + "]"; // } // // // // // // // @Override // public int hashCode() // { // final int prime = 31; // int result = 1; // result = prime * result + ((tag == null) ? 0 : tag.hashCode()); // result = prime * result + ((token == null) ? 0 : token.hashCode()); // return result; // } // // // // @Override // public boolean equals(Object obj) // { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // TaggedToken<?,?> other = (TaggedToken<?,?>) obj; // if (tag == null) // { // if (other.tag != null) // return false; // } else if (!tag.equals(other.tag)) // return false; // if (token == null) // { // if (other.token != null) // return false; // } else if (!token.equals(other.token)) // return false; // return true; // } // // // // // // // private final K token; // private final G tag; // }
import java.util.List; import java.util.Set; import com.asher_stern.crf.crf.filters.CrfFilteredFeature; import com.asher_stern.crf.postagging.postaggers.crf.CrfPosTagger; import com.asher_stern.crf.utilities.TaggedToken;
package com.asher_stern.crf.crf.run; /** * Generates set of features to be used by the CRF algorithm for training and inference of {@link CrfPosTagger}. * * @author Asher Stern * Date: Nov 10, 2014 * */ public abstract class CrfFeatureGenerator<K,G> {
// Path: src/main/java/com/asher_stern/crf/crf/filters/CrfFilteredFeature.java // public class CrfFilteredFeature<K, G> implements Serializable // { // private static final long serialVersionUID = -5835863638916635217L; // // public CrfFilteredFeature(CrfFeature<K, G> feature, Filter<K, G> filter, boolean whenNotFilteredIsAlwaysOne) // { // super(); // this.feature = feature; // this.filter = filter; // this.whenNotFilteredIsAlwaysOne = whenNotFilteredIsAlwaysOne; // } // // public CrfFeature<K, G> getFeature() // { // return feature; // } // // public Filter<K, G> getFilter() // { // return filter; // } // // /** // * Returns true if it is <B>guaranteed</B> that the feature returns 1.0 for any input for which its filter // * is equal to the filter returned by {@link #getFilter()}. // * @return // */ // public boolean isWhenNotFilteredIsAlwaysOne() // { // return whenNotFilteredIsAlwaysOne; // } // // // // // // @Override // public int hashCode() // { // final int prime = 31; // int result = 1; // result = prime * result + ((feature == null) ? 0 : feature.hashCode()); // result = prime * result + ((filter == null) ? 0 : filter.hashCode()); // result = prime * result + (whenNotFilteredIsAlwaysOne ? 1231 : 1237); // return result; // } // // @Override // public boolean equals(Object obj) // { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // CrfFilteredFeature<?,?> other = (CrfFilteredFeature<?,?>) obj; // if (feature == null) // { // if (other.feature != null) // return false; // } else if (!feature.equals(other.feature)) // return false; // if (filter == null) // { // if (other.filter != null) // return false; // } else if (!filter.equals(other.filter)) // return false; // if (whenNotFilteredIsAlwaysOne != other.whenNotFilteredIsAlwaysOne) // return false; // return true; // } // // // // protected final CrfFeature<K, G> feature; // protected final Filter<K, G> filter; // protected final boolean whenNotFilteredIsAlwaysOne; // } // // Path: src/main/java/com/asher_stern/crf/postagging/postaggers/crf/CrfPosTagger.java // public class CrfPosTagger implements PosTagger // { // public CrfPosTagger(CrfInferencePerformer<String, String> inferencePerformer) // { // this.inferencePerformer = inferencePerformer; // } // // @Override // public List<TaggedToken<String,String>> tagSentence(List<String> sentence) // { // return inferencePerformer.tagSequence(sentence); // } // // // private final CrfInferencePerformer<String, String> inferencePerformer; // // } // // Path: src/main/java/com/asher_stern/crf/utilities/TaggedToken.java // public class TaggedToken<K,G> // { // public TaggedToken(K token, G tag) // { // super(); // this.token = token; // this.tag = tag; // } // // // // public K getToken() // { // return token; // } // public G getTag() // { // return tag; // } // // // // // @Override // public String toString() // { // return "CrfTaggedToken [getToken()=" + getToken() + ", getTag()=" // + getTag() + "]"; // } // // // // // // // @Override // public int hashCode() // { // final int prime = 31; // int result = 1; // result = prime * result + ((tag == null) ? 0 : tag.hashCode()); // result = prime * result + ((token == null) ? 0 : token.hashCode()); // return result; // } // // // // @Override // public boolean equals(Object obj) // { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // TaggedToken<?,?> other = (TaggedToken<?,?>) obj; // if (tag == null) // { // if (other.tag != null) // return false; // } else if (!tag.equals(other.tag)) // return false; // if (token == null) // { // if (other.token != null) // return false; // } else if (!token.equals(other.token)) // return false; // return true; // } // // // // // // // private final K token; // private final G tag; // } // Path: src/main/java/com/asher_stern/crf/crf/run/CrfFeatureGenerator.java import java.util.List; import java.util.Set; import com.asher_stern.crf.crf.filters.CrfFilteredFeature; import com.asher_stern.crf.postagging.postaggers.crf.CrfPosTagger; import com.asher_stern.crf.utilities.TaggedToken; package com.asher_stern.crf.crf.run; /** * Generates set of features to be used by the CRF algorithm for training and inference of {@link CrfPosTagger}. * * @author Asher Stern * Date: Nov 10, 2014 * */ public abstract class CrfFeatureGenerator<K,G> {
public CrfFeatureGenerator(Iterable<? extends List<? extends TaggedToken<K, G> >> corpus, Set<G> tags)
asher-stern/CRF
src/main/java/com/asher_stern/crf/postagging/postaggers/crf/CrfPosTaggerLoader.java
// Path: src/main/java/com/asher_stern/crf/crf/CrfModel.java // public class CrfModel<K,G> implements Serializable // K = token, G = tag // { // private static final long serialVersionUID = -5703467522848303660L; // // public CrfModel(CrfTags<G> crfTags, CrfFeaturesAndFilters<K, G> features, ArrayList<BigDecimal> parameters) // { // super(); // this.crfTags = crfTags; // this.features = features; // this.parameters = parameters; // } // // // // public CrfTags<G> getCrfTags() // { // return crfTags; // } // public CrfFeaturesAndFilters<K, G> getFeatures() // { // return features; // } // public ArrayList<BigDecimal> getParameters() // { // return parameters; // } // // // // private final CrfTags<G> crfTags; // private final CrfFeaturesAndFilters<K, G> features; // private final ArrayList<BigDecimal> parameters; // } // // Path: src/main/java/com/asher_stern/crf/crf/run/CrfInferencePerformer.java // public class CrfInferencePerformer<K, G> // { // public CrfInferencePerformer(CrfModel<K, G> model) // { // super(); // this.model = model; // } // // /** // * Finds the most likely sequence of tags for the given sequence of tokens // * @param sequence A sequence of tokens // * @return A list in which each element is a {@link TaggedToken}, which encapsulates a token and its tag. // */ // public List<TaggedToken<K,G>> tagSequence(List<K> sequence) // { // if (null==sequence) {return null;} // if (sequence.size()==0) {return Collections.<TaggedToken<K,G>>emptyList();} // // @SuppressWarnings("unchecked") // K[] sentenceAsArray = sequence.toArray( (K[]) Array.newInstance(sequence.get(0).getClass(), sequence.size()) ); // CrfInferenceViterbi<K, G> crfInference = new CrfInferenceViterbi<K, G>(model, sentenceAsArray); // G[] bestTags = crfInference.inferBestTagSequence(); // // if (sentenceAsArray.length!=bestTags.length) {throw new CrfException("Inference failed. Array of tags differs in length from array of tokens.");} // // List<TaggedToken<K,G>> ret = new ArrayList<TaggedToken<K,G>>(); // for (int index=0;index<sentenceAsArray.length;++index) // { // ret.add(new TaggedToken<K,G>(sentenceAsArray[index], bestTags[index])); // } // return ret; // // } // // private final CrfModel<K, G> model; // } // // Path: src/main/java/com/asher_stern/crf/postagging/postaggers/PosTaggerLoader.java // public interface PosTaggerLoader // { // /** // * Load the {@link PosTagger} from the file-system and return it. // * @param directory A directory in the file-system which contains the model of the {@link PosTagger}. // * This model was earlier created and saved by {@link PosTaggerTrainer#save(File)}. // * // * @return // */ // public PosTagger load(File directory); // // } // // Path: src/main/java/com/asher_stern/crf/utilities/CrfException.java // public class CrfException extends RuntimeException // { // private static final long serialVersionUID = 5414394233000815286L; // // public CrfException() // { // super(); // } // // public CrfException(String message, Throwable cause, // boolean enableSuppression, boolean writableStackTrace) // { // super(message, cause, enableSuppression, writableStackTrace); // } // // public CrfException(String message, Throwable cause) // { // super(message, cause); // } // // public CrfException(String message) // { // super(message); // } // // public CrfException(Throwable cause) // { // super(cause); // } // // // }
import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.ObjectInputStream; import com.asher_stern.crf.crf.CrfModel; import com.asher_stern.crf.crf.run.CrfInferencePerformer; import com.asher_stern.crf.postagging.postaggers.PosTaggerLoader; import com.asher_stern.crf.utilities.CrfException;
package com.asher_stern.crf.postagging.postaggers.crf; /** * Loads a {@link CrfPosTagger} from a model that is stored in a directory in the file-system. * The model was earlier saved in the file-system by {@link CrfPosTaggerTrainer#save(File)}. * * @author Asher Stern * Date: Nov 20, 2014 * */ public class CrfPosTaggerLoader implements PosTaggerLoader { /* * (non-Javadoc) * @see org.postagging.postaggers.PosTaggerLoader#load(java.io.File) */ @Override public CrfPosTagger load(File directory) {
// Path: src/main/java/com/asher_stern/crf/crf/CrfModel.java // public class CrfModel<K,G> implements Serializable // K = token, G = tag // { // private static final long serialVersionUID = -5703467522848303660L; // // public CrfModel(CrfTags<G> crfTags, CrfFeaturesAndFilters<K, G> features, ArrayList<BigDecimal> parameters) // { // super(); // this.crfTags = crfTags; // this.features = features; // this.parameters = parameters; // } // // // // public CrfTags<G> getCrfTags() // { // return crfTags; // } // public CrfFeaturesAndFilters<K, G> getFeatures() // { // return features; // } // public ArrayList<BigDecimal> getParameters() // { // return parameters; // } // // // // private final CrfTags<G> crfTags; // private final CrfFeaturesAndFilters<K, G> features; // private final ArrayList<BigDecimal> parameters; // } // // Path: src/main/java/com/asher_stern/crf/crf/run/CrfInferencePerformer.java // public class CrfInferencePerformer<K, G> // { // public CrfInferencePerformer(CrfModel<K, G> model) // { // super(); // this.model = model; // } // // /** // * Finds the most likely sequence of tags for the given sequence of tokens // * @param sequence A sequence of tokens // * @return A list in which each element is a {@link TaggedToken}, which encapsulates a token and its tag. // */ // public List<TaggedToken<K,G>> tagSequence(List<K> sequence) // { // if (null==sequence) {return null;} // if (sequence.size()==0) {return Collections.<TaggedToken<K,G>>emptyList();} // // @SuppressWarnings("unchecked") // K[] sentenceAsArray = sequence.toArray( (K[]) Array.newInstance(sequence.get(0).getClass(), sequence.size()) ); // CrfInferenceViterbi<K, G> crfInference = new CrfInferenceViterbi<K, G>(model, sentenceAsArray); // G[] bestTags = crfInference.inferBestTagSequence(); // // if (sentenceAsArray.length!=bestTags.length) {throw new CrfException("Inference failed. Array of tags differs in length from array of tokens.");} // // List<TaggedToken<K,G>> ret = new ArrayList<TaggedToken<K,G>>(); // for (int index=0;index<sentenceAsArray.length;++index) // { // ret.add(new TaggedToken<K,G>(sentenceAsArray[index], bestTags[index])); // } // return ret; // // } // // private final CrfModel<K, G> model; // } // // Path: src/main/java/com/asher_stern/crf/postagging/postaggers/PosTaggerLoader.java // public interface PosTaggerLoader // { // /** // * Load the {@link PosTagger} from the file-system and return it. // * @param directory A directory in the file-system which contains the model of the {@link PosTagger}. // * This model was earlier created and saved by {@link PosTaggerTrainer#save(File)}. // * // * @return // */ // public PosTagger load(File directory); // // } // // Path: src/main/java/com/asher_stern/crf/utilities/CrfException.java // public class CrfException extends RuntimeException // { // private static final long serialVersionUID = 5414394233000815286L; // // public CrfException() // { // super(); // } // // public CrfException(String message, Throwable cause, // boolean enableSuppression, boolean writableStackTrace) // { // super(message, cause, enableSuppression, writableStackTrace); // } // // public CrfException(String message, Throwable cause) // { // super(message, cause); // } // // public CrfException(String message) // { // super(message); // } // // public CrfException(Throwable cause) // { // super(cause); // } // // // } // Path: src/main/java/com/asher_stern/crf/postagging/postaggers/crf/CrfPosTaggerLoader.java import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.ObjectInputStream; import com.asher_stern.crf.crf.CrfModel; import com.asher_stern.crf.crf.run.CrfInferencePerformer; import com.asher_stern.crf.postagging.postaggers.PosTaggerLoader; import com.asher_stern.crf.utilities.CrfException; package com.asher_stern.crf.postagging.postaggers.crf; /** * Loads a {@link CrfPosTagger} from a model that is stored in a directory in the file-system. * The model was earlier saved in the file-system by {@link CrfPosTaggerTrainer#save(File)}. * * @author Asher Stern * Date: Nov 20, 2014 * */ public class CrfPosTaggerLoader implements PosTaggerLoader { /* * (non-Javadoc) * @see org.postagging.postaggers.PosTaggerLoader#load(java.io.File) */ @Override public CrfPosTagger load(File directory) {
if (!directory.exists()) {throw new CrfException("Given directory: "+directory.getAbsolutePath()+" does not exist.");}
asher-stern/CRF
src/main/java/com/asher_stern/crf/postagging/postaggers/crf/CrfPosTaggerLoader.java
// Path: src/main/java/com/asher_stern/crf/crf/CrfModel.java // public class CrfModel<K,G> implements Serializable // K = token, G = tag // { // private static final long serialVersionUID = -5703467522848303660L; // // public CrfModel(CrfTags<G> crfTags, CrfFeaturesAndFilters<K, G> features, ArrayList<BigDecimal> parameters) // { // super(); // this.crfTags = crfTags; // this.features = features; // this.parameters = parameters; // } // // // // public CrfTags<G> getCrfTags() // { // return crfTags; // } // public CrfFeaturesAndFilters<K, G> getFeatures() // { // return features; // } // public ArrayList<BigDecimal> getParameters() // { // return parameters; // } // // // // private final CrfTags<G> crfTags; // private final CrfFeaturesAndFilters<K, G> features; // private final ArrayList<BigDecimal> parameters; // } // // Path: src/main/java/com/asher_stern/crf/crf/run/CrfInferencePerformer.java // public class CrfInferencePerformer<K, G> // { // public CrfInferencePerformer(CrfModel<K, G> model) // { // super(); // this.model = model; // } // // /** // * Finds the most likely sequence of tags for the given sequence of tokens // * @param sequence A sequence of tokens // * @return A list in which each element is a {@link TaggedToken}, which encapsulates a token and its tag. // */ // public List<TaggedToken<K,G>> tagSequence(List<K> sequence) // { // if (null==sequence) {return null;} // if (sequence.size()==0) {return Collections.<TaggedToken<K,G>>emptyList();} // // @SuppressWarnings("unchecked") // K[] sentenceAsArray = sequence.toArray( (K[]) Array.newInstance(sequence.get(0).getClass(), sequence.size()) ); // CrfInferenceViterbi<K, G> crfInference = new CrfInferenceViterbi<K, G>(model, sentenceAsArray); // G[] bestTags = crfInference.inferBestTagSequence(); // // if (sentenceAsArray.length!=bestTags.length) {throw new CrfException("Inference failed. Array of tags differs in length from array of tokens.");} // // List<TaggedToken<K,G>> ret = new ArrayList<TaggedToken<K,G>>(); // for (int index=0;index<sentenceAsArray.length;++index) // { // ret.add(new TaggedToken<K,G>(sentenceAsArray[index], bestTags[index])); // } // return ret; // // } // // private final CrfModel<K, G> model; // } // // Path: src/main/java/com/asher_stern/crf/postagging/postaggers/PosTaggerLoader.java // public interface PosTaggerLoader // { // /** // * Load the {@link PosTagger} from the file-system and return it. // * @param directory A directory in the file-system which contains the model of the {@link PosTagger}. // * This model was earlier created and saved by {@link PosTaggerTrainer#save(File)}. // * // * @return // */ // public PosTagger load(File directory); // // } // // Path: src/main/java/com/asher_stern/crf/utilities/CrfException.java // public class CrfException extends RuntimeException // { // private static final long serialVersionUID = 5414394233000815286L; // // public CrfException() // { // super(); // } // // public CrfException(String message, Throwable cause, // boolean enableSuppression, boolean writableStackTrace) // { // super(message, cause, enableSuppression, writableStackTrace); // } // // public CrfException(String message, Throwable cause) // { // super(message, cause); // } // // public CrfException(String message) // { // super(message); // } // // public CrfException(Throwable cause) // { // super(cause); // } // // // }
import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.ObjectInputStream; import com.asher_stern.crf.crf.CrfModel; import com.asher_stern.crf.crf.run.CrfInferencePerformer; import com.asher_stern.crf.postagging.postaggers.PosTaggerLoader; import com.asher_stern.crf.utilities.CrfException;
package com.asher_stern.crf.postagging.postaggers.crf; /** * Loads a {@link CrfPosTagger} from a model that is stored in a directory in the file-system. * The model was earlier saved in the file-system by {@link CrfPosTaggerTrainer#save(File)}. * * @author Asher Stern * Date: Nov 20, 2014 * */ public class CrfPosTaggerLoader implements PosTaggerLoader { /* * (non-Javadoc) * @see org.postagging.postaggers.PosTaggerLoader#load(java.io.File) */ @Override public CrfPosTagger load(File directory) { if (!directory.exists()) {throw new CrfException("Given directory: "+directory.getAbsolutePath()+" does not exist.");} if (!directory.isDirectory()) {throw new CrfException("The loader requires a directory, but was provided with a file: "+directory.getAbsolutePath()+".");} try(ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream(new File(directory, CrfPosTaggerTrainer.SAVE_LOAD_FILE_NAME )))) { @SuppressWarnings("unchecked")
// Path: src/main/java/com/asher_stern/crf/crf/CrfModel.java // public class CrfModel<K,G> implements Serializable // K = token, G = tag // { // private static final long serialVersionUID = -5703467522848303660L; // // public CrfModel(CrfTags<G> crfTags, CrfFeaturesAndFilters<K, G> features, ArrayList<BigDecimal> parameters) // { // super(); // this.crfTags = crfTags; // this.features = features; // this.parameters = parameters; // } // // // // public CrfTags<G> getCrfTags() // { // return crfTags; // } // public CrfFeaturesAndFilters<K, G> getFeatures() // { // return features; // } // public ArrayList<BigDecimal> getParameters() // { // return parameters; // } // // // // private final CrfTags<G> crfTags; // private final CrfFeaturesAndFilters<K, G> features; // private final ArrayList<BigDecimal> parameters; // } // // Path: src/main/java/com/asher_stern/crf/crf/run/CrfInferencePerformer.java // public class CrfInferencePerformer<K, G> // { // public CrfInferencePerformer(CrfModel<K, G> model) // { // super(); // this.model = model; // } // // /** // * Finds the most likely sequence of tags for the given sequence of tokens // * @param sequence A sequence of tokens // * @return A list in which each element is a {@link TaggedToken}, which encapsulates a token and its tag. // */ // public List<TaggedToken<K,G>> tagSequence(List<K> sequence) // { // if (null==sequence) {return null;} // if (sequence.size()==0) {return Collections.<TaggedToken<K,G>>emptyList();} // // @SuppressWarnings("unchecked") // K[] sentenceAsArray = sequence.toArray( (K[]) Array.newInstance(sequence.get(0).getClass(), sequence.size()) ); // CrfInferenceViterbi<K, G> crfInference = new CrfInferenceViterbi<K, G>(model, sentenceAsArray); // G[] bestTags = crfInference.inferBestTagSequence(); // // if (sentenceAsArray.length!=bestTags.length) {throw new CrfException("Inference failed. Array of tags differs in length from array of tokens.");} // // List<TaggedToken<K,G>> ret = new ArrayList<TaggedToken<K,G>>(); // for (int index=0;index<sentenceAsArray.length;++index) // { // ret.add(new TaggedToken<K,G>(sentenceAsArray[index], bestTags[index])); // } // return ret; // // } // // private final CrfModel<K, G> model; // } // // Path: src/main/java/com/asher_stern/crf/postagging/postaggers/PosTaggerLoader.java // public interface PosTaggerLoader // { // /** // * Load the {@link PosTagger} from the file-system and return it. // * @param directory A directory in the file-system which contains the model of the {@link PosTagger}. // * This model was earlier created and saved by {@link PosTaggerTrainer#save(File)}. // * // * @return // */ // public PosTagger load(File directory); // // } // // Path: src/main/java/com/asher_stern/crf/utilities/CrfException.java // public class CrfException extends RuntimeException // { // private static final long serialVersionUID = 5414394233000815286L; // // public CrfException() // { // super(); // } // // public CrfException(String message, Throwable cause, // boolean enableSuppression, boolean writableStackTrace) // { // super(message, cause, enableSuppression, writableStackTrace); // } // // public CrfException(String message, Throwable cause) // { // super(message, cause); // } // // public CrfException(String message) // { // super(message); // } // // public CrfException(Throwable cause) // { // super(cause); // } // // // } // Path: src/main/java/com/asher_stern/crf/postagging/postaggers/crf/CrfPosTaggerLoader.java import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.ObjectInputStream; import com.asher_stern.crf.crf.CrfModel; import com.asher_stern.crf.crf.run.CrfInferencePerformer; import com.asher_stern.crf.postagging.postaggers.PosTaggerLoader; import com.asher_stern.crf.utilities.CrfException; package com.asher_stern.crf.postagging.postaggers.crf; /** * Loads a {@link CrfPosTagger} from a model that is stored in a directory in the file-system. * The model was earlier saved in the file-system by {@link CrfPosTaggerTrainer#save(File)}. * * @author Asher Stern * Date: Nov 20, 2014 * */ public class CrfPosTaggerLoader implements PosTaggerLoader { /* * (non-Javadoc) * @see org.postagging.postaggers.PosTaggerLoader#load(java.io.File) */ @Override public CrfPosTagger load(File directory) { if (!directory.exists()) {throw new CrfException("Given directory: "+directory.getAbsolutePath()+" does not exist.");} if (!directory.isDirectory()) {throw new CrfException("The loader requires a directory, but was provided with a file: "+directory.getAbsolutePath()+".");} try(ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream(new File(directory, CrfPosTaggerTrainer.SAVE_LOAD_FILE_NAME )))) { @SuppressWarnings("unchecked")
CrfModel<String, String> model = (CrfModel<String, String>) inputStream.readObject();
asher-stern/CRF
src/main/java/com/asher_stern/crf/postagging/postaggers/crf/CrfPosTaggerLoader.java
// Path: src/main/java/com/asher_stern/crf/crf/CrfModel.java // public class CrfModel<K,G> implements Serializable // K = token, G = tag // { // private static final long serialVersionUID = -5703467522848303660L; // // public CrfModel(CrfTags<G> crfTags, CrfFeaturesAndFilters<K, G> features, ArrayList<BigDecimal> parameters) // { // super(); // this.crfTags = crfTags; // this.features = features; // this.parameters = parameters; // } // // // // public CrfTags<G> getCrfTags() // { // return crfTags; // } // public CrfFeaturesAndFilters<K, G> getFeatures() // { // return features; // } // public ArrayList<BigDecimal> getParameters() // { // return parameters; // } // // // // private final CrfTags<G> crfTags; // private final CrfFeaturesAndFilters<K, G> features; // private final ArrayList<BigDecimal> parameters; // } // // Path: src/main/java/com/asher_stern/crf/crf/run/CrfInferencePerformer.java // public class CrfInferencePerformer<K, G> // { // public CrfInferencePerformer(CrfModel<K, G> model) // { // super(); // this.model = model; // } // // /** // * Finds the most likely sequence of tags for the given sequence of tokens // * @param sequence A sequence of tokens // * @return A list in which each element is a {@link TaggedToken}, which encapsulates a token and its tag. // */ // public List<TaggedToken<K,G>> tagSequence(List<K> sequence) // { // if (null==sequence) {return null;} // if (sequence.size()==0) {return Collections.<TaggedToken<K,G>>emptyList();} // // @SuppressWarnings("unchecked") // K[] sentenceAsArray = sequence.toArray( (K[]) Array.newInstance(sequence.get(0).getClass(), sequence.size()) ); // CrfInferenceViterbi<K, G> crfInference = new CrfInferenceViterbi<K, G>(model, sentenceAsArray); // G[] bestTags = crfInference.inferBestTagSequence(); // // if (sentenceAsArray.length!=bestTags.length) {throw new CrfException("Inference failed. Array of tags differs in length from array of tokens.");} // // List<TaggedToken<K,G>> ret = new ArrayList<TaggedToken<K,G>>(); // for (int index=0;index<sentenceAsArray.length;++index) // { // ret.add(new TaggedToken<K,G>(sentenceAsArray[index], bestTags[index])); // } // return ret; // // } // // private final CrfModel<K, G> model; // } // // Path: src/main/java/com/asher_stern/crf/postagging/postaggers/PosTaggerLoader.java // public interface PosTaggerLoader // { // /** // * Load the {@link PosTagger} from the file-system and return it. // * @param directory A directory in the file-system which contains the model of the {@link PosTagger}. // * This model was earlier created and saved by {@link PosTaggerTrainer#save(File)}. // * // * @return // */ // public PosTagger load(File directory); // // } // // Path: src/main/java/com/asher_stern/crf/utilities/CrfException.java // public class CrfException extends RuntimeException // { // private static final long serialVersionUID = 5414394233000815286L; // // public CrfException() // { // super(); // } // // public CrfException(String message, Throwable cause, // boolean enableSuppression, boolean writableStackTrace) // { // super(message, cause, enableSuppression, writableStackTrace); // } // // public CrfException(String message, Throwable cause) // { // super(message, cause); // } // // public CrfException(String message) // { // super(message); // } // // public CrfException(Throwable cause) // { // super(cause); // } // // // }
import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.ObjectInputStream; import com.asher_stern.crf.crf.CrfModel; import com.asher_stern.crf.crf.run.CrfInferencePerformer; import com.asher_stern.crf.postagging.postaggers.PosTaggerLoader; import com.asher_stern.crf.utilities.CrfException;
package com.asher_stern.crf.postagging.postaggers.crf; /** * Loads a {@link CrfPosTagger} from a model that is stored in a directory in the file-system. * The model was earlier saved in the file-system by {@link CrfPosTaggerTrainer#save(File)}. * * @author Asher Stern * Date: Nov 20, 2014 * */ public class CrfPosTaggerLoader implements PosTaggerLoader { /* * (non-Javadoc) * @see org.postagging.postaggers.PosTaggerLoader#load(java.io.File) */ @Override public CrfPosTagger load(File directory) { if (!directory.exists()) {throw new CrfException("Given directory: "+directory.getAbsolutePath()+" does not exist.");} if (!directory.isDirectory()) {throw new CrfException("The loader requires a directory, but was provided with a file: "+directory.getAbsolutePath()+".");} try(ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream(new File(directory, CrfPosTaggerTrainer.SAVE_LOAD_FILE_NAME )))) { @SuppressWarnings("unchecked") CrfModel<String, String> model = (CrfModel<String, String>) inputStream.readObject();
// Path: src/main/java/com/asher_stern/crf/crf/CrfModel.java // public class CrfModel<K,G> implements Serializable // K = token, G = tag // { // private static final long serialVersionUID = -5703467522848303660L; // // public CrfModel(CrfTags<G> crfTags, CrfFeaturesAndFilters<K, G> features, ArrayList<BigDecimal> parameters) // { // super(); // this.crfTags = crfTags; // this.features = features; // this.parameters = parameters; // } // // // // public CrfTags<G> getCrfTags() // { // return crfTags; // } // public CrfFeaturesAndFilters<K, G> getFeatures() // { // return features; // } // public ArrayList<BigDecimal> getParameters() // { // return parameters; // } // // // // private final CrfTags<G> crfTags; // private final CrfFeaturesAndFilters<K, G> features; // private final ArrayList<BigDecimal> parameters; // } // // Path: src/main/java/com/asher_stern/crf/crf/run/CrfInferencePerformer.java // public class CrfInferencePerformer<K, G> // { // public CrfInferencePerformer(CrfModel<K, G> model) // { // super(); // this.model = model; // } // // /** // * Finds the most likely sequence of tags for the given sequence of tokens // * @param sequence A sequence of tokens // * @return A list in which each element is a {@link TaggedToken}, which encapsulates a token and its tag. // */ // public List<TaggedToken<K,G>> tagSequence(List<K> sequence) // { // if (null==sequence) {return null;} // if (sequence.size()==0) {return Collections.<TaggedToken<K,G>>emptyList();} // // @SuppressWarnings("unchecked") // K[] sentenceAsArray = sequence.toArray( (K[]) Array.newInstance(sequence.get(0).getClass(), sequence.size()) ); // CrfInferenceViterbi<K, G> crfInference = new CrfInferenceViterbi<K, G>(model, sentenceAsArray); // G[] bestTags = crfInference.inferBestTagSequence(); // // if (sentenceAsArray.length!=bestTags.length) {throw new CrfException("Inference failed. Array of tags differs in length from array of tokens.");} // // List<TaggedToken<K,G>> ret = new ArrayList<TaggedToken<K,G>>(); // for (int index=0;index<sentenceAsArray.length;++index) // { // ret.add(new TaggedToken<K,G>(sentenceAsArray[index], bestTags[index])); // } // return ret; // // } // // private final CrfModel<K, G> model; // } // // Path: src/main/java/com/asher_stern/crf/postagging/postaggers/PosTaggerLoader.java // public interface PosTaggerLoader // { // /** // * Load the {@link PosTagger} from the file-system and return it. // * @param directory A directory in the file-system which contains the model of the {@link PosTagger}. // * This model was earlier created and saved by {@link PosTaggerTrainer#save(File)}. // * // * @return // */ // public PosTagger load(File directory); // // } // // Path: src/main/java/com/asher_stern/crf/utilities/CrfException.java // public class CrfException extends RuntimeException // { // private static final long serialVersionUID = 5414394233000815286L; // // public CrfException() // { // super(); // } // // public CrfException(String message, Throwable cause, // boolean enableSuppression, boolean writableStackTrace) // { // super(message, cause, enableSuppression, writableStackTrace); // } // // public CrfException(String message, Throwable cause) // { // super(message, cause); // } // // public CrfException(String message) // { // super(message); // } // // public CrfException(Throwable cause) // { // super(cause); // } // // // } // Path: src/main/java/com/asher_stern/crf/postagging/postaggers/crf/CrfPosTaggerLoader.java import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.ObjectInputStream; import com.asher_stern.crf.crf.CrfModel; import com.asher_stern.crf.crf.run.CrfInferencePerformer; import com.asher_stern.crf.postagging.postaggers.PosTaggerLoader; import com.asher_stern.crf.utilities.CrfException; package com.asher_stern.crf.postagging.postaggers.crf; /** * Loads a {@link CrfPosTagger} from a model that is stored in a directory in the file-system. * The model was earlier saved in the file-system by {@link CrfPosTaggerTrainer#save(File)}. * * @author Asher Stern * Date: Nov 20, 2014 * */ public class CrfPosTaggerLoader implements PosTaggerLoader { /* * (non-Javadoc) * @see org.postagging.postaggers.PosTaggerLoader#load(java.io.File) */ @Override public CrfPosTagger load(File directory) { if (!directory.exists()) {throw new CrfException("Given directory: "+directory.getAbsolutePath()+" does not exist.");} if (!directory.isDirectory()) {throw new CrfException("The loader requires a directory, but was provided with a file: "+directory.getAbsolutePath()+".");} try(ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream(new File(directory, CrfPosTaggerTrainer.SAVE_LOAD_FILE_NAME )))) { @SuppressWarnings("unchecked") CrfModel<String, String> model = (CrfModel<String, String>) inputStream.readObject();
return new CrfPosTagger(new CrfInferencePerformer<String, String>(model));
asher-stern/CRF
src/main/java/com/asher_stern/crf/crf/CrfTags.java
// Path: src/main/java/com/asher_stern/crf/utilities/CrfException.java // public class CrfException extends RuntimeException // { // private static final long serialVersionUID = 5414394233000815286L; // // public CrfException() // { // super(); // } // // public CrfException(String message, Throwable cause, // boolean enableSuppression, boolean writableStackTrace) // { // super(message, cause, enableSuppression, writableStackTrace); // } // // public CrfException(String message, Throwable cause) // { // super(message, cause); // } // // public CrfException(String message) // { // super(message); // } // // public CrfException(Throwable cause) // { // super(cause); // } // // // }
import java.io.Serializable; import java.util.Collections; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import com.asher_stern.crf.utilities.CrfException;
for (G tag : canPrecede.keySet()) { Set<G> newSet = new LinkedHashSet<G>(); for (G precede : canPrecede.get(tag)) { if (precede!=null) { newSet.add(precede); } } canPrecedeNonNull.put(tag, newSet); } } private void initPrecedeWhenFirst() { precedeWhenFirst = new LinkedHashMap<G, Set<G>>(); boolean debug_firstDetected = false; for (G tag : canPrecede.keySet()) { if (canPrecede.get(tag).contains(null)) { precedeWhenFirst.put(tag, Collections.singleton(null)); debug_firstDetected = true; } else { precedeWhenFirst.put(tag, Collections.emptySet()); } }
// Path: src/main/java/com/asher_stern/crf/utilities/CrfException.java // public class CrfException extends RuntimeException // { // private static final long serialVersionUID = 5414394233000815286L; // // public CrfException() // { // super(); // } // // public CrfException(String message, Throwable cause, // boolean enableSuppression, boolean writableStackTrace) // { // super(message, cause, enableSuppression, writableStackTrace); // } // // public CrfException(String message, Throwable cause) // { // super(message, cause); // } // // public CrfException(String message) // { // super(message); // } // // public CrfException(Throwable cause) // { // super(cause); // } // // // } // Path: src/main/java/com/asher_stern/crf/crf/CrfTags.java import java.io.Serializable; import java.util.Collections; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import com.asher_stern.crf.utilities.CrfException; for (G tag : canPrecede.keySet()) { Set<G> newSet = new LinkedHashSet<G>(); for (G precede : canPrecede.get(tag)) { if (precede!=null) { newSet.add(precede); } } canPrecedeNonNull.put(tag, newSet); } } private void initPrecedeWhenFirst() { precedeWhenFirst = new LinkedHashMap<G, Set<G>>(); boolean debug_firstDetected = false; for (G tag : canPrecede.keySet()) { if (canPrecede.get(tag).contains(null)) { precedeWhenFirst.put(tag, Collections.singleton(null)); debug_firstDetected = true; } else { precedeWhenFirst.put(tag, Collections.emptySet()); } }
if (!debug_firstDetected) {throw new CrfException("Error: no tag has null in its can-precede set. This means that no tag can appear as the first tag in a sentence, which is an error.");}
asher-stern/CRF
src/main/java/com/asher_stern/crf/smalltests/DemoPennCorpus.java
// Path: src/main/java/com/asher_stern/crf/postagging/data/LimitedSizePosTagCorpusReader.java // public class LimitedSizePosTagCorpusReader<K,G> implements Iterator<List<TaggedToken<K, G>>> // { // public LimitedSizePosTagCorpusReader(Iterator<List<TaggedToken<K, G>>> realCorpus, int size) // { // super(); // this.realCorpus = realCorpus; // this.size = size; // } // // @Override // public boolean hasNext() // { // return (realCorpus.hasNext()&&(index<size)); // } // // @Override // public List<TaggedToken<K, G> > next() // { // if (index<size) // { // ++index; // return realCorpus.next(); // } // else throw new NoSuchElementException(); // } // // // private final Iterator<List<TaggedToken<K, G>>> realCorpus; // private final int size; // // private int index=0; // } // // Path: src/main/java/com/asher_stern/crf/postagging/data/penn/PennCorpus.java // public class PennCorpus implements Iterable<List<TaggedToken<String, String>>> // { // // // note for myself Size of corpus = 49208 sentences // // // /** // * Constructs the Iterable with the Penn TreeBank directory, as specified in the main comment. // * @param directory A directory in the file-system, which contains the files of the Penn TreeBank // */ // public PennCorpus(File directory) // { // super(); // this.directory = directory; // } // // @Override // public PennCorpusReader iterator() // { // return new PennCorpusReader(directory); // } // // private final File directory; // } // // Path: src/main/java/com/asher_stern/crf/utilities/TaggedToken.java // public class TaggedToken<K,G> // { // public TaggedToken(K token, G tag) // { // super(); // this.token = token; // this.tag = tag; // } // // // // public K getToken() // { // return token; // } // public G getTag() // { // return tag; // } // // // // // @Override // public String toString() // { // return "CrfTaggedToken [getToken()=" + getToken() + ", getTag()=" // + getTag() + "]"; // } // // // // // // // @Override // public int hashCode() // { // final int prime = 31; // int result = 1; // result = prime * result + ((tag == null) ? 0 : tag.hashCode()); // result = prime * result + ((token == null) ? 0 : token.hashCode()); // return result; // } // // // // @Override // public boolean equals(Object obj) // { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // TaggedToken<?,?> other = (TaggedToken<?,?>) obj; // if (tag == null) // { // if (other.tag != null) // return false; // } else if (!tag.equals(other.tag)) // return false; // if (token == null) // { // if (other.token != null) // return false; // } else if (!token.equals(other.token)) // return false; // return true; // } // // // // // // // private final K token; // private final G tag; // } // // Path: src/main/java/com/asher_stern/crf/utilities/log4j/Log4jInit.java // public class Log4jInit // { // // public static void init() // { // init(Level.INFO); // } // // public static void init(Level level) // { // if (!alreadyInitialized) // { // synchronized(Log4jInit.class) // { // if (!alreadyInitialized) // { // final Layout layout = new VerySimpleLayout(); // new PatternLayout("%p [%t] %m%n"); // BasicConfigurator.configure(); // Logger.getRootLogger().setLevel(level); // // Enumeration<?> enumAppenders = Logger.getRootLogger().getAllAppenders(); // while (enumAppenders.hasMoreElements()) // { // Appender appender = (Appender) enumAppenders.nextElement(); // appender.setLayout(layout); // } // // alreadyInitialized = true; // } // } // } // // } // // private static boolean alreadyInitialized = false; // }
import java.io.File; import java.util.List; import org.apache.log4j.Level; import com.asher_stern.crf.postagging.data.LimitedSizePosTagCorpusReader; import com.asher_stern.crf.postagging.data.penn.PennCorpus; import com.asher_stern.crf.utilities.TaggedToken; import com.asher_stern.crf.utilities.log4j.Log4jInit;
package com.asher_stern.crf.smalltests; public class DemoPennCorpus { public static void main(String[] args) { try {
// Path: src/main/java/com/asher_stern/crf/postagging/data/LimitedSizePosTagCorpusReader.java // public class LimitedSizePosTagCorpusReader<K,G> implements Iterator<List<TaggedToken<K, G>>> // { // public LimitedSizePosTagCorpusReader(Iterator<List<TaggedToken<K, G>>> realCorpus, int size) // { // super(); // this.realCorpus = realCorpus; // this.size = size; // } // // @Override // public boolean hasNext() // { // return (realCorpus.hasNext()&&(index<size)); // } // // @Override // public List<TaggedToken<K, G> > next() // { // if (index<size) // { // ++index; // return realCorpus.next(); // } // else throw new NoSuchElementException(); // } // // // private final Iterator<List<TaggedToken<K, G>>> realCorpus; // private final int size; // // private int index=0; // } // // Path: src/main/java/com/asher_stern/crf/postagging/data/penn/PennCorpus.java // public class PennCorpus implements Iterable<List<TaggedToken<String, String>>> // { // // // note for myself Size of corpus = 49208 sentences // // // /** // * Constructs the Iterable with the Penn TreeBank directory, as specified in the main comment. // * @param directory A directory in the file-system, which contains the files of the Penn TreeBank // */ // public PennCorpus(File directory) // { // super(); // this.directory = directory; // } // // @Override // public PennCorpusReader iterator() // { // return new PennCorpusReader(directory); // } // // private final File directory; // } // // Path: src/main/java/com/asher_stern/crf/utilities/TaggedToken.java // public class TaggedToken<K,G> // { // public TaggedToken(K token, G tag) // { // super(); // this.token = token; // this.tag = tag; // } // // // // public K getToken() // { // return token; // } // public G getTag() // { // return tag; // } // // // // // @Override // public String toString() // { // return "CrfTaggedToken [getToken()=" + getToken() + ", getTag()=" // + getTag() + "]"; // } // // // // // // // @Override // public int hashCode() // { // final int prime = 31; // int result = 1; // result = prime * result + ((tag == null) ? 0 : tag.hashCode()); // result = prime * result + ((token == null) ? 0 : token.hashCode()); // return result; // } // // // // @Override // public boolean equals(Object obj) // { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // TaggedToken<?,?> other = (TaggedToken<?,?>) obj; // if (tag == null) // { // if (other.tag != null) // return false; // } else if (!tag.equals(other.tag)) // return false; // if (token == null) // { // if (other.token != null) // return false; // } else if (!token.equals(other.token)) // return false; // return true; // } // // // // // // // private final K token; // private final G tag; // } // // Path: src/main/java/com/asher_stern/crf/utilities/log4j/Log4jInit.java // public class Log4jInit // { // // public static void init() // { // init(Level.INFO); // } // // public static void init(Level level) // { // if (!alreadyInitialized) // { // synchronized(Log4jInit.class) // { // if (!alreadyInitialized) // { // final Layout layout = new VerySimpleLayout(); // new PatternLayout("%p [%t] %m%n"); // BasicConfigurator.configure(); // Logger.getRootLogger().setLevel(level); // // Enumeration<?> enumAppenders = Logger.getRootLogger().getAllAppenders(); // while (enumAppenders.hasMoreElements()) // { // Appender appender = (Appender) enumAppenders.nextElement(); // appender.setLayout(layout); // } // // alreadyInitialized = true; // } // } // } // // } // // private static boolean alreadyInitialized = false; // } // Path: src/main/java/com/asher_stern/crf/smalltests/DemoPennCorpus.java import java.io.File; import java.util.List; import org.apache.log4j.Level; import com.asher_stern.crf.postagging.data.LimitedSizePosTagCorpusReader; import com.asher_stern.crf.postagging.data.penn.PennCorpus; import com.asher_stern.crf.utilities.TaggedToken; import com.asher_stern.crf.utilities.log4j.Log4jInit; package com.asher_stern.crf.smalltests; public class DemoPennCorpus { public static void main(String[] args) { try {
Log4jInit.init(Level.DEBUG);
asher-stern/CRF
src/main/java/com/asher_stern/crf/smalltests/DemoPennCorpus.java
// Path: src/main/java/com/asher_stern/crf/postagging/data/LimitedSizePosTagCorpusReader.java // public class LimitedSizePosTagCorpusReader<K,G> implements Iterator<List<TaggedToken<K, G>>> // { // public LimitedSizePosTagCorpusReader(Iterator<List<TaggedToken<K, G>>> realCorpus, int size) // { // super(); // this.realCorpus = realCorpus; // this.size = size; // } // // @Override // public boolean hasNext() // { // return (realCorpus.hasNext()&&(index<size)); // } // // @Override // public List<TaggedToken<K, G> > next() // { // if (index<size) // { // ++index; // return realCorpus.next(); // } // else throw new NoSuchElementException(); // } // // // private final Iterator<List<TaggedToken<K, G>>> realCorpus; // private final int size; // // private int index=0; // } // // Path: src/main/java/com/asher_stern/crf/postagging/data/penn/PennCorpus.java // public class PennCorpus implements Iterable<List<TaggedToken<String, String>>> // { // // // note for myself Size of corpus = 49208 sentences // // // /** // * Constructs the Iterable with the Penn TreeBank directory, as specified in the main comment. // * @param directory A directory in the file-system, which contains the files of the Penn TreeBank // */ // public PennCorpus(File directory) // { // super(); // this.directory = directory; // } // // @Override // public PennCorpusReader iterator() // { // return new PennCorpusReader(directory); // } // // private final File directory; // } // // Path: src/main/java/com/asher_stern/crf/utilities/TaggedToken.java // public class TaggedToken<K,G> // { // public TaggedToken(K token, G tag) // { // super(); // this.token = token; // this.tag = tag; // } // // // // public K getToken() // { // return token; // } // public G getTag() // { // return tag; // } // // // // // @Override // public String toString() // { // return "CrfTaggedToken [getToken()=" + getToken() + ", getTag()=" // + getTag() + "]"; // } // // // // // // // @Override // public int hashCode() // { // final int prime = 31; // int result = 1; // result = prime * result + ((tag == null) ? 0 : tag.hashCode()); // result = prime * result + ((token == null) ? 0 : token.hashCode()); // return result; // } // // // // @Override // public boolean equals(Object obj) // { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // TaggedToken<?,?> other = (TaggedToken<?,?>) obj; // if (tag == null) // { // if (other.tag != null) // return false; // } else if (!tag.equals(other.tag)) // return false; // if (token == null) // { // if (other.token != null) // return false; // } else if (!token.equals(other.token)) // return false; // return true; // } // // // // // // // private final K token; // private final G tag; // } // // Path: src/main/java/com/asher_stern/crf/utilities/log4j/Log4jInit.java // public class Log4jInit // { // // public static void init() // { // init(Level.INFO); // } // // public static void init(Level level) // { // if (!alreadyInitialized) // { // synchronized(Log4jInit.class) // { // if (!alreadyInitialized) // { // final Layout layout = new VerySimpleLayout(); // new PatternLayout("%p [%t] %m%n"); // BasicConfigurator.configure(); // Logger.getRootLogger().setLevel(level); // // Enumeration<?> enumAppenders = Logger.getRootLogger().getAllAppenders(); // while (enumAppenders.hasMoreElements()) // { // Appender appender = (Appender) enumAppenders.nextElement(); // appender.setLayout(layout); // } // // alreadyInitialized = true; // } // } // } // // } // // private static boolean alreadyInitialized = false; // }
import java.io.File; import java.util.List; import org.apache.log4j.Level; import com.asher_stern.crf.postagging.data.LimitedSizePosTagCorpusReader; import com.asher_stern.crf.postagging.data.penn.PennCorpus; import com.asher_stern.crf.utilities.TaggedToken; import com.asher_stern.crf.utilities.log4j.Log4jInit;
package com.asher_stern.crf.smalltests; public class DemoPennCorpus { public static void main(String[] args) { try { Log4jInit.init(Level.DEBUG); new DemoPennCorpus().go(new File(args[0])); } catch(Throwable t) { t.printStackTrace(System.out); } } public void go(File directory) {
// Path: src/main/java/com/asher_stern/crf/postagging/data/LimitedSizePosTagCorpusReader.java // public class LimitedSizePosTagCorpusReader<K,G> implements Iterator<List<TaggedToken<K, G>>> // { // public LimitedSizePosTagCorpusReader(Iterator<List<TaggedToken<K, G>>> realCorpus, int size) // { // super(); // this.realCorpus = realCorpus; // this.size = size; // } // // @Override // public boolean hasNext() // { // return (realCorpus.hasNext()&&(index<size)); // } // // @Override // public List<TaggedToken<K, G> > next() // { // if (index<size) // { // ++index; // return realCorpus.next(); // } // else throw new NoSuchElementException(); // } // // // private final Iterator<List<TaggedToken<K, G>>> realCorpus; // private final int size; // // private int index=0; // } // // Path: src/main/java/com/asher_stern/crf/postagging/data/penn/PennCorpus.java // public class PennCorpus implements Iterable<List<TaggedToken<String, String>>> // { // // // note for myself Size of corpus = 49208 sentences // // // /** // * Constructs the Iterable with the Penn TreeBank directory, as specified in the main comment. // * @param directory A directory in the file-system, which contains the files of the Penn TreeBank // */ // public PennCorpus(File directory) // { // super(); // this.directory = directory; // } // // @Override // public PennCorpusReader iterator() // { // return new PennCorpusReader(directory); // } // // private final File directory; // } // // Path: src/main/java/com/asher_stern/crf/utilities/TaggedToken.java // public class TaggedToken<K,G> // { // public TaggedToken(K token, G tag) // { // super(); // this.token = token; // this.tag = tag; // } // // // // public K getToken() // { // return token; // } // public G getTag() // { // return tag; // } // // // // // @Override // public String toString() // { // return "CrfTaggedToken [getToken()=" + getToken() + ", getTag()=" // + getTag() + "]"; // } // // // // // // // @Override // public int hashCode() // { // final int prime = 31; // int result = 1; // result = prime * result + ((tag == null) ? 0 : tag.hashCode()); // result = prime * result + ((token == null) ? 0 : token.hashCode()); // return result; // } // // // // @Override // public boolean equals(Object obj) // { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // TaggedToken<?,?> other = (TaggedToken<?,?>) obj; // if (tag == null) // { // if (other.tag != null) // return false; // } else if (!tag.equals(other.tag)) // return false; // if (token == null) // { // if (other.token != null) // return false; // } else if (!token.equals(other.token)) // return false; // return true; // } // // // // // // // private final K token; // private final G tag; // } // // Path: src/main/java/com/asher_stern/crf/utilities/log4j/Log4jInit.java // public class Log4jInit // { // // public static void init() // { // init(Level.INFO); // } // // public static void init(Level level) // { // if (!alreadyInitialized) // { // synchronized(Log4jInit.class) // { // if (!alreadyInitialized) // { // final Layout layout = new VerySimpleLayout(); // new PatternLayout("%p [%t] %m%n"); // BasicConfigurator.configure(); // Logger.getRootLogger().setLevel(level); // // Enumeration<?> enumAppenders = Logger.getRootLogger().getAllAppenders(); // while (enumAppenders.hasMoreElements()) // { // Appender appender = (Appender) enumAppenders.nextElement(); // appender.setLayout(layout); // } // // alreadyInitialized = true; // } // } // } // // } // // private static boolean alreadyInitialized = false; // } // Path: src/main/java/com/asher_stern/crf/smalltests/DemoPennCorpus.java import java.io.File; import java.util.List; import org.apache.log4j.Level; import com.asher_stern.crf.postagging.data.LimitedSizePosTagCorpusReader; import com.asher_stern.crf.postagging.data.penn.PennCorpus; import com.asher_stern.crf.utilities.TaggedToken; import com.asher_stern.crf.utilities.log4j.Log4jInit; package com.asher_stern.crf.smalltests; public class DemoPennCorpus { public static void main(String[] args) { try { Log4jInit.init(Level.DEBUG); new DemoPennCorpus().go(new File(args[0])); } catch(Throwable t) { t.printStackTrace(System.out); } } public void go(File directory) {
PennCorpus corpus = new PennCorpus(directory);
asher-stern/CRF
src/main/java/com/asher_stern/crf/smalltests/DemoPennCorpus.java
// Path: src/main/java/com/asher_stern/crf/postagging/data/LimitedSizePosTagCorpusReader.java // public class LimitedSizePosTagCorpusReader<K,G> implements Iterator<List<TaggedToken<K, G>>> // { // public LimitedSizePosTagCorpusReader(Iterator<List<TaggedToken<K, G>>> realCorpus, int size) // { // super(); // this.realCorpus = realCorpus; // this.size = size; // } // // @Override // public boolean hasNext() // { // return (realCorpus.hasNext()&&(index<size)); // } // // @Override // public List<TaggedToken<K, G> > next() // { // if (index<size) // { // ++index; // return realCorpus.next(); // } // else throw new NoSuchElementException(); // } // // // private final Iterator<List<TaggedToken<K, G>>> realCorpus; // private final int size; // // private int index=0; // } // // Path: src/main/java/com/asher_stern/crf/postagging/data/penn/PennCorpus.java // public class PennCorpus implements Iterable<List<TaggedToken<String, String>>> // { // // // note for myself Size of corpus = 49208 sentences // // // /** // * Constructs the Iterable with the Penn TreeBank directory, as specified in the main comment. // * @param directory A directory in the file-system, which contains the files of the Penn TreeBank // */ // public PennCorpus(File directory) // { // super(); // this.directory = directory; // } // // @Override // public PennCorpusReader iterator() // { // return new PennCorpusReader(directory); // } // // private final File directory; // } // // Path: src/main/java/com/asher_stern/crf/utilities/TaggedToken.java // public class TaggedToken<K,G> // { // public TaggedToken(K token, G tag) // { // super(); // this.token = token; // this.tag = tag; // } // // // // public K getToken() // { // return token; // } // public G getTag() // { // return tag; // } // // // // // @Override // public String toString() // { // return "CrfTaggedToken [getToken()=" + getToken() + ", getTag()=" // + getTag() + "]"; // } // // // // // // // @Override // public int hashCode() // { // final int prime = 31; // int result = 1; // result = prime * result + ((tag == null) ? 0 : tag.hashCode()); // result = prime * result + ((token == null) ? 0 : token.hashCode()); // return result; // } // // // // @Override // public boolean equals(Object obj) // { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // TaggedToken<?,?> other = (TaggedToken<?,?>) obj; // if (tag == null) // { // if (other.tag != null) // return false; // } else if (!tag.equals(other.tag)) // return false; // if (token == null) // { // if (other.token != null) // return false; // } else if (!token.equals(other.token)) // return false; // return true; // } // // // // // // // private final K token; // private final G tag; // } // // Path: src/main/java/com/asher_stern/crf/utilities/log4j/Log4jInit.java // public class Log4jInit // { // // public static void init() // { // init(Level.INFO); // } // // public static void init(Level level) // { // if (!alreadyInitialized) // { // synchronized(Log4jInit.class) // { // if (!alreadyInitialized) // { // final Layout layout = new VerySimpleLayout(); // new PatternLayout("%p [%t] %m%n"); // BasicConfigurator.configure(); // Logger.getRootLogger().setLevel(level); // // Enumeration<?> enumAppenders = Logger.getRootLogger().getAllAppenders(); // while (enumAppenders.hasMoreElements()) // { // Appender appender = (Appender) enumAppenders.nextElement(); // appender.setLayout(layout); // } // // alreadyInitialized = true; // } // } // } // // } // // private static boolean alreadyInitialized = false; // }
import java.io.File; import java.util.List; import org.apache.log4j.Level; import com.asher_stern.crf.postagging.data.LimitedSizePosTagCorpusReader; import com.asher_stern.crf.postagging.data.penn.PennCorpus; import com.asher_stern.crf.utilities.TaggedToken; import com.asher_stern.crf.utilities.log4j.Log4jInit;
package com.asher_stern.crf.smalltests; public class DemoPennCorpus { public static void main(String[] args) { try { Log4jInit.init(Level.DEBUG); new DemoPennCorpus().go(new File(args[0])); } catch(Throwable t) { t.printStackTrace(System.out); } } public void go(File directory) { PennCorpus corpus = new PennCorpus(directory);
// Path: src/main/java/com/asher_stern/crf/postagging/data/LimitedSizePosTagCorpusReader.java // public class LimitedSizePosTagCorpusReader<K,G> implements Iterator<List<TaggedToken<K, G>>> // { // public LimitedSizePosTagCorpusReader(Iterator<List<TaggedToken<K, G>>> realCorpus, int size) // { // super(); // this.realCorpus = realCorpus; // this.size = size; // } // // @Override // public boolean hasNext() // { // return (realCorpus.hasNext()&&(index<size)); // } // // @Override // public List<TaggedToken<K, G> > next() // { // if (index<size) // { // ++index; // return realCorpus.next(); // } // else throw new NoSuchElementException(); // } // // // private final Iterator<List<TaggedToken<K, G>>> realCorpus; // private final int size; // // private int index=0; // } // // Path: src/main/java/com/asher_stern/crf/postagging/data/penn/PennCorpus.java // public class PennCorpus implements Iterable<List<TaggedToken<String, String>>> // { // // // note for myself Size of corpus = 49208 sentences // // // /** // * Constructs the Iterable with the Penn TreeBank directory, as specified in the main comment. // * @param directory A directory in the file-system, which contains the files of the Penn TreeBank // */ // public PennCorpus(File directory) // { // super(); // this.directory = directory; // } // // @Override // public PennCorpusReader iterator() // { // return new PennCorpusReader(directory); // } // // private final File directory; // } // // Path: src/main/java/com/asher_stern/crf/utilities/TaggedToken.java // public class TaggedToken<K,G> // { // public TaggedToken(K token, G tag) // { // super(); // this.token = token; // this.tag = tag; // } // // // // public K getToken() // { // return token; // } // public G getTag() // { // return tag; // } // // // // // @Override // public String toString() // { // return "CrfTaggedToken [getToken()=" + getToken() + ", getTag()=" // + getTag() + "]"; // } // // // // // // // @Override // public int hashCode() // { // final int prime = 31; // int result = 1; // result = prime * result + ((tag == null) ? 0 : tag.hashCode()); // result = prime * result + ((token == null) ? 0 : token.hashCode()); // return result; // } // // // // @Override // public boolean equals(Object obj) // { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // TaggedToken<?,?> other = (TaggedToken<?,?>) obj; // if (tag == null) // { // if (other.tag != null) // return false; // } else if (!tag.equals(other.tag)) // return false; // if (token == null) // { // if (other.token != null) // return false; // } else if (!token.equals(other.token)) // return false; // return true; // } // // // // // // // private final K token; // private final G tag; // } // // Path: src/main/java/com/asher_stern/crf/utilities/log4j/Log4jInit.java // public class Log4jInit // { // // public static void init() // { // init(Level.INFO); // } // // public static void init(Level level) // { // if (!alreadyInitialized) // { // synchronized(Log4jInit.class) // { // if (!alreadyInitialized) // { // final Layout layout = new VerySimpleLayout(); // new PatternLayout("%p [%t] %m%n"); // BasicConfigurator.configure(); // Logger.getRootLogger().setLevel(level); // // Enumeration<?> enumAppenders = Logger.getRootLogger().getAllAppenders(); // while (enumAppenders.hasMoreElements()) // { // Appender appender = (Appender) enumAppenders.nextElement(); // appender.setLayout(layout); // } // // alreadyInitialized = true; // } // } // } // // } // // private static boolean alreadyInitialized = false; // } // Path: src/main/java/com/asher_stern/crf/smalltests/DemoPennCorpus.java import java.io.File; import java.util.List; import org.apache.log4j.Level; import com.asher_stern.crf.postagging.data.LimitedSizePosTagCorpusReader; import com.asher_stern.crf.postagging.data.penn.PennCorpus; import com.asher_stern.crf.utilities.TaggedToken; import com.asher_stern.crf.utilities.log4j.Log4jInit; package com.asher_stern.crf.smalltests; public class DemoPennCorpus { public static void main(String[] args) { try { Log4jInit.init(Level.DEBUG); new DemoPennCorpus().go(new File(args[0])); } catch(Throwable t) { t.printStackTrace(System.out); } } public void go(File directory) { PennCorpus corpus = new PennCorpus(directory);
LimitedSizePosTagCorpusReader<String,String> reader = new LimitedSizePosTagCorpusReader<String,String>(corpus.iterator(),10);
asher-stern/CRF
src/main/java/com/asher_stern/crf/smalltests/DemoPennCorpus.java
// Path: src/main/java/com/asher_stern/crf/postagging/data/LimitedSizePosTagCorpusReader.java // public class LimitedSizePosTagCorpusReader<K,G> implements Iterator<List<TaggedToken<K, G>>> // { // public LimitedSizePosTagCorpusReader(Iterator<List<TaggedToken<K, G>>> realCorpus, int size) // { // super(); // this.realCorpus = realCorpus; // this.size = size; // } // // @Override // public boolean hasNext() // { // return (realCorpus.hasNext()&&(index<size)); // } // // @Override // public List<TaggedToken<K, G> > next() // { // if (index<size) // { // ++index; // return realCorpus.next(); // } // else throw new NoSuchElementException(); // } // // // private final Iterator<List<TaggedToken<K, G>>> realCorpus; // private final int size; // // private int index=0; // } // // Path: src/main/java/com/asher_stern/crf/postagging/data/penn/PennCorpus.java // public class PennCorpus implements Iterable<List<TaggedToken<String, String>>> // { // // // note for myself Size of corpus = 49208 sentences // // // /** // * Constructs the Iterable with the Penn TreeBank directory, as specified in the main comment. // * @param directory A directory in the file-system, which contains the files of the Penn TreeBank // */ // public PennCorpus(File directory) // { // super(); // this.directory = directory; // } // // @Override // public PennCorpusReader iterator() // { // return new PennCorpusReader(directory); // } // // private final File directory; // } // // Path: src/main/java/com/asher_stern/crf/utilities/TaggedToken.java // public class TaggedToken<K,G> // { // public TaggedToken(K token, G tag) // { // super(); // this.token = token; // this.tag = tag; // } // // // // public K getToken() // { // return token; // } // public G getTag() // { // return tag; // } // // // // // @Override // public String toString() // { // return "CrfTaggedToken [getToken()=" + getToken() + ", getTag()=" // + getTag() + "]"; // } // // // // // // // @Override // public int hashCode() // { // final int prime = 31; // int result = 1; // result = prime * result + ((tag == null) ? 0 : tag.hashCode()); // result = prime * result + ((token == null) ? 0 : token.hashCode()); // return result; // } // // // // @Override // public boolean equals(Object obj) // { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // TaggedToken<?,?> other = (TaggedToken<?,?>) obj; // if (tag == null) // { // if (other.tag != null) // return false; // } else if (!tag.equals(other.tag)) // return false; // if (token == null) // { // if (other.token != null) // return false; // } else if (!token.equals(other.token)) // return false; // return true; // } // // // // // // // private final K token; // private final G tag; // } // // Path: src/main/java/com/asher_stern/crf/utilities/log4j/Log4jInit.java // public class Log4jInit // { // // public static void init() // { // init(Level.INFO); // } // // public static void init(Level level) // { // if (!alreadyInitialized) // { // synchronized(Log4jInit.class) // { // if (!alreadyInitialized) // { // final Layout layout = new VerySimpleLayout(); // new PatternLayout("%p [%t] %m%n"); // BasicConfigurator.configure(); // Logger.getRootLogger().setLevel(level); // // Enumeration<?> enumAppenders = Logger.getRootLogger().getAllAppenders(); // while (enumAppenders.hasMoreElements()) // { // Appender appender = (Appender) enumAppenders.nextElement(); // appender.setLayout(layout); // } // // alreadyInitialized = true; // } // } // } // // } // // private static boolean alreadyInitialized = false; // }
import java.io.File; import java.util.List; import org.apache.log4j.Level; import com.asher_stern.crf.postagging.data.LimitedSizePosTagCorpusReader; import com.asher_stern.crf.postagging.data.penn.PennCorpus; import com.asher_stern.crf.utilities.TaggedToken; import com.asher_stern.crf.utilities.log4j.Log4jInit;
package com.asher_stern.crf.smalltests; public class DemoPennCorpus { public static void main(String[] args) { try { Log4jInit.init(Level.DEBUG); new DemoPennCorpus().go(new File(args[0])); } catch(Throwable t) { t.printStackTrace(System.out); } } public void go(File directory) { PennCorpus corpus = new PennCorpus(directory); LimitedSizePosTagCorpusReader<String,String> reader = new LimitedSizePosTagCorpusReader<String,String>(corpus.iterator(),10); while (reader.hasNext()) {
// Path: src/main/java/com/asher_stern/crf/postagging/data/LimitedSizePosTagCorpusReader.java // public class LimitedSizePosTagCorpusReader<K,G> implements Iterator<List<TaggedToken<K, G>>> // { // public LimitedSizePosTagCorpusReader(Iterator<List<TaggedToken<K, G>>> realCorpus, int size) // { // super(); // this.realCorpus = realCorpus; // this.size = size; // } // // @Override // public boolean hasNext() // { // return (realCorpus.hasNext()&&(index<size)); // } // // @Override // public List<TaggedToken<K, G> > next() // { // if (index<size) // { // ++index; // return realCorpus.next(); // } // else throw new NoSuchElementException(); // } // // // private final Iterator<List<TaggedToken<K, G>>> realCorpus; // private final int size; // // private int index=0; // } // // Path: src/main/java/com/asher_stern/crf/postagging/data/penn/PennCorpus.java // public class PennCorpus implements Iterable<List<TaggedToken<String, String>>> // { // // // note for myself Size of corpus = 49208 sentences // // // /** // * Constructs the Iterable with the Penn TreeBank directory, as specified in the main comment. // * @param directory A directory in the file-system, which contains the files of the Penn TreeBank // */ // public PennCorpus(File directory) // { // super(); // this.directory = directory; // } // // @Override // public PennCorpusReader iterator() // { // return new PennCorpusReader(directory); // } // // private final File directory; // } // // Path: src/main/java/com/asher_stern/crf/utilities/TaggedToken.java // public class TaggedToken<K,G> // { // public TaggedToken(K token, G tag) // { // super(); // this.token = token; // this.tag = tag; // } // // // // public K getToken() // { // return token; // } // public G getTag() // { // return tag; // } // // // // // @Override // public String toString() // { // return "CrfTaggedToken [getToken()=" + getToken() + ", getTag()=" // + getTag() + "]"; // } // // // // // // // @Override // public int hashCode() // { // final int prime = 31; // int result = 1; // result = prime * result + ((tag == null) ? 0 : tag.hashCode()); // result = prime * result + ((token == null) ? 0 : token.hashCode()); // return result; // } // // // // @Override // public boolean equals(Object obj) // { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // TaggedToken<?,?> other = (TaggedToken<?,?>) obj; // if (tag == null) // { // if (other.tag != null) // return false; // } else if (!tag.equals(other.tag)) // return false; // if (token == null) // { // if (other.token != null) // return false; // } else if (!token.equals(other.token)) // return false; // return true; // } // // // // // // // private final K token; // private final G tag; // } // // Path: src/main/java/com/asher_stern/crf/utilities/log4j/Log4jInit.java // public class Log4jInit // { // // public static void init() // { // init(Level.INFO); // } // // public static void init(Level level) // { // if (!alreadyInitialized) // { // synchronized(Log4jInit.class) // { // if (!alreadyInitialized) // { // final Layout layout = new VerySimpleLayout(); // new PatternLayout("%p [%t] %m%n"); // BasicConfigurator.configure(); // Logger.getRootLogger().setLevel(level); // // Enumeration<?> enumAppenders = Logger.getRootLogger().getAllAppenders(); // while (enumAppenders.hasMoreElements()) // { // Appender appender = (Appender) enumAppenders.nextElement(); // appender.setLayout(layout); // } // // alreadyInitialized = true; // } // } // } // // } // // private static boolean alreadyInitialized = false; // } // Path: src/main/java/com/asher_stern/crf/smalltests/DemoPennCorpus.java import java.io.File; import java.util.List; import org.apache.log4j.Level; import com.asher_stern.crf.postagging.data.LimitedSizePosTagCorpusReader; import com.asher_stern.crf.postagging.data.penn.PennCorpus; import com.asher_stern.crf.utilities.TaggedToken; import com.asher_stern.crf.utilities.log4j.Log4jInit; package com.asher_stern.crf.smalltests; public class DemoPennCorpus { public static void main(String[] args) { try { Log4jInit.init(Level.DEBUG); new DemoPennCorpus().go(new File(args[0])); } catch(Throwable t) { t.printStackTrace(System.out); } } public void go(File directory) { PennCorpus corpus = new PennCorpus(directory); LimitedSizePosTagCorpusReader<String,String> reader = new LimitedSizePosTagCorpusReader<String,String>(corpus.iterator(),10); while (reader.hasNext()) {
List<? extends TaggedToken<String, String>> sentence = reader.next();
asher-stern/CRF
src/main/java/com/asher_stern/crf/postagging/data/penn/PennFileContentsParser.java
// Path: src/main/java/com/asher_stern/crf/utilities/CrfException.java // public class CrfException extends RuntimeException // { // private static final long serialVersionUID = 5414394233000815286L; // // public CrfException() // { // super(); // } // // public CrfException(String message, Throwable cause, // boolean enableSuppression, boolean writableStackTrace) // { // super(message, cause, enableSuppression, writableStackTrace); // } // // public CrfException(String message, Throwable cause) // { // super(message, cause); // } // // public CrfException(String message) // { // super(message); // } // // public CrfException(Throwable cause) // { // super(cause); // } // // // }
import java.util.LinkedList; import java.util.List; import java.util.Stack; import com.asher_stern.crf.utilities.CrfException;
{ PennParserTreeNode node = new PennParserTreeNode(activeNodeContent.toString()); if (!activeStack.isEmpty()) { activeStack.peek().addChild(node); } activeStack.push(node); } activeNodeContent = new StringBuilder(); } else if (c==')') { if (activeNodeContent!=null) { PennParserTreeNode node = new PennParserTreeNode(activeNodeContent.toString()); if (!activeStack.isEmpty()) { activeStack.peek().addChild(node); } activeStack.push(node); } PennParserTreeNode poped = activeStack.pop(); if (activeStack.isEmpty()) { trees.add(poped); } activeNodeContent = null; } else {
// Path: src/main/java/com/asher_stern/crf/utilities/CrfException.java // public class CrfException extends RuntimeException // { // private static final long serialVersionUID = 5414394233000815286L; // // public CrfException() // { // super(); // } // // public CrfException(String message, Throwable cause, // boolean enableSuppression, boolean writableStackTrace) // { // super(message, cause, enableSuppression, writableStackTrace); // } // // public CrfException(String message, Throwable cause) // { // super(message, cause); // } // // public CrfException(String message) // { // super(message); // } // // public CrfException(Throwable cause) // { // super(cause); // } // // // } // Path: src/main/java/com/asher_stern/crf/postagging/data/penn/PennFileContentsParser.java import java.util.LinkedList; import java.util.List; import java.util.Stack; import com.asher_stern.crf.utilities.CrfException; { PennParserTreeNode node = new PennParserTreeNode(activeNodeContent.toString()); if (!activeStack.isEmpty()) { activeStack.peek().addChild(node); } activeStack.push(node); } activeNodeContent = new StringBuilder(); } else if (c==')') { if (activeNodeContent!=null) { PennParserTreeNode node = new PennParserTreeNode(activeNodeContent.toString()); if (!activeStack.isEmpty()) { activeStack.peek().addChild(node); } activeStack.push(node); } PennParserTreeNode poped = activeStack.pop(); if (activeStack.isEmpty()) { trees.add(poped); } activeNodeContent = null; } else {
if (activeNodeContent==null) {throw new CrfException("Malformed PTB file contents.");}
asher-stern/CRF
src/main/java/com/asher_stern/crf/postagging/postaggers/crf/features/StandardFilterFactory.java
// Path: src/main/java/com/asher_stern/crf/crf/filters/Filter.java // public abstract class Filter<K,G> implements Serializable // { // private static final long serialVersionUID = 5563671313834518710L; // // public abstract int hashCode(); // public abstract boolean equals(Object obj); // } // // Path: src/main/java/com/asher_stern/crf/crf/filters/FilterFactory.java // public interface FilterFactory<K, G> extends Serializable // { // /** // * Creates a set of filters for the given token,tag, and tag-of-previous-token. // * The convention is as follows: // * Let each feature f be a feature that <B>might</B> return non-zero for the given token,tag,previous-tag. // * That feature is encapsulated with a {@link Filter} in a {@link CrfFilteredFeature}. Let's call this filter "t". // * For that filter there exist one filter in the set returned by this function, name it "t'", such that "t'" equals to "t". // * // * // * @param sequence A sequence of tokens // * @param tokenIndex An index of a token in that sequence // * @param currentTag A tag for that token // * @param previousTag A tag for the token which immediately precedes that token. // * @return A set of filters as described above. // */ // public Set<Filter<K, G>> createFilters(K[] sequence, int tokenIndex, G currentTag, G previousTag); // } // // Path: src/main/java/com/asher_stern/crf/crf/filters/TwoTagsFilter.java // public class TwoTagsFilter<K, G> extends Filter<K, G> // { // private static final long serialVersionUID = -4850947891058236177L; // // public TwoTagsFilter(G currentTag, G previousTag) // { // this.currentTag = currentTag; // this.previousTag = previousTag; // } // // // // @Override // public int hashCode() // { // if (hashCodeCalculated) // { // return hashCodeValue; // } // else // { // final int prime = 31; // int result = 1; // result = prime * result // + ((currentTag == null) ? 0 : currentTag.hashCode()); // result = prime * result // + ((previousTag == null) ? 0 : previousTag.hashCode()); // hashCodeValue = result; // hashCodeCalculated = true; // return result; // } // } // // @Override // public boolean equals(Object obj) // { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // TwoTagsFilter<?,?> other = (TwoTagsFilter<?,?>) obj; // if (currentTag == null) // { // if (other.currentTag != null) // return false; // } else if (!currentTag.equals(other.currentTag)) // return false; // if (previousTag == null) // { // if (other.previousTag != null) // return false; // } else if (!previousTag.equals(other.previousTag)) // return false; // return true; // } // // // // private final G currentTag; // private final G previousTag; // // private transient int hashCodeValue = 0; // private transient boolean hashCodeCalculated = false; // }
import java.util.LinkedHashSet; import java.util.Set; import com.asher_stern.crf.crf.filters.Filter; import com.asher_stern.crf.crf.filters.FilterFactory; import com.asher_stern.crf.crf.filters.TwoTagsFilter;
package com.asher_stern.crf.postagging.postaggers.crf.features; /** * A {@link FilterFactory} for the features generated by the {@link StandardFeatureGenerator}. * * @author Asher Stern * Date: Nov 11, 2014 * */ public class StandardFilterFactory implements FilterFactory<String, String> { private static final long serialVersionUID = 6283122214266870374L; @Override
// Path: src/main/java/com/asher_stern/crf/crf/filters/Filter.java // public abstract class Filter<K,G> implements Serializable // { // private static final long serialVersionUID = 5563671313834518710L; // // public abstract int hashCode(); // public abstract boolean equals(Object obj); // } // // Path: src/main/java/com/asher_stern/crf/crf/filters/FilterFactory.java // public interface FilterFactory<K, G> extends Serializable // { // /** // * Creates a set of filters for the given token,tag, and tag-of-previous-token. // * The convention is as follows: // * Let each feature f be a feature that <B>might</B> return non-zero for the given token,tag,previous-tag. // * That feature is encapsulated with a {@link Filter} in a {@link CrfFilteredFeature}. Let's call this filter "t". // * For that filter there exist one filter in the set returned by this function, name it "t'", such that "t'" equals to "t". // * // * // * @param sequence A sequence of tokens // * @param tokenIndex An index of a token in that sequence // * @param currentTag A tag for that token // * @param previousTag A tag for the token which immediately precedes that token. // * @return A set of filters as described above. // */ // public Set<Filter<K, G>> createFilters(K[] sequence, int tokenIndex, G currentTag, G previousTag); // } // // Path: src/main/java/com/asher_stern/crf/crf/filters/TwoTagsFilter.java // public class TwoTagsFilter<K, G> extends Filter<K, G> // { // private static final long serialVersionUID = -4850947891058236177L; // // public TwoTagsFilter(G currentTag, G previousTag) // { // this.currentTag = currentTag; // this.previousTag = previousTag; // } // // // // @Override // public int hashCode() // { // if (hashCodeCalculated) // { // return hashCodeValue; // } // else // { // final int prime = 31; // int result = 1; // result = prime * result // + ((currentTag == null) ? 0 : currentTag.hashCode()); // result = prime * result // + ((previousTag == null) ? 0 : previousTag.hashCode()); // hashCodeValue = result; // hashCodeCalculated = true; // return result; // } // } // // @Override // public boolean equals(Object obj) // { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // TwoTagsFilter<?,?> other = (TwoTagsFilter<?,?>) obj; // if (currentTag == null) // { // if (other.currentTag != null) // return false; // } else if (!currentTag.equals(other.currentTag)) // return false; // if (previousTag == null) // { // if (other.previousTag != null) // return false; // } else if (!previousTag.equals(other.previousTag)) // return false; // return true; // } // // // // private final G currentTag; // private final G previousTag; // // private transient int hashCodeValue = 0; // private transient boolean hashCodeCalculated = false; // } // Path: src/main/java/com/asher_stern/crf/postagging/postaggers/crf/features/StandardFilterFactory.java import java.util.LinkedHashSet; import java.util.Set; import com.asher_stern.crf.crf.filters.Filter; import com.asher_stern.crf.crf.filters.FilterFactory; import com.asher_stern.crf.crf.filters.TwoTagsFilter; package com.asher_stern.crf.postagging.postaggers.crf.features; /** * A {@link FilterFactory} for the features generated by the {@link StandardFeatureGenerator}. * * @author Asher Stern * Date: Nov 11, 2014 * */ public class StandardFilterFactory implements FilterFactory<String, String> { private static final long serialVersionUID = 6283122214266870374L; @Override
public Set<Filter<String, String>> createFilters(String[] sequence, int tokenIndex, String currentTag, String previousTag)
asher-stern/CRF
src/main/java/com/asher_stern/crf/postagging/postaggers/crf/features/StandardFilterFactory.java
// Path: src/main/java/com/asher_stern/crf/crf/filters/Filter.java // public abstract class Filter<K,G> implements Serializable // { // private static final long serialVersionUID = 5563671313834518710L; // // public abstract int hashCode(); // public abstract boolean equals(Object obj); // } // // Path: src/main/java/com/asher_stern/crf/crf/filters/FilterFactory.java // public interface FilterFactory<K, G> extends Serializable // { // /** // * Creates a set of filters for the given token,tag, and tag-of-previous-token. // * The convention is as follows: // * Let each feature f be a feature that <B>might</B> return non-zero for the given token,tag,previous-tag. // * That feature is encapsulated with a {@link Filter} in a {@link CrfFilteredFeature}. Let's call this filter "t". // * For that filter there exist one filter in the set returned by this function, name it "t'", such that "t'" equals to "t". // * // * // * @param sequence A sequence of tokens // * @param tokenIndex An index of a token in that sequence // * @param currentTag A tag for that token // * @param previousTag A tag for the token which immediately precedes that token. // * @return A set of filters as described above. // */ // public Set<Filter<K, G>> createFilters(K[] sequence, int tokenIndex, G currentTag, G previousTag); // } // // Path: src/main/java/com/asher_stern/crf/crf/filters/TwoTagsFilter.java // public class TwoTagsFilter<K, G> extends Filter<K, G> // { // private static final long serialVersionUID = -4850947891058236177L; // // public TwoTagsFilter(G currentTag, G previousTag) // { // this.currentTag = currentTag; // this.previousTag = previousTag; // } // // // // @Override // public int hashCode() // { // if (hashCodeCalculated) // { // return hashCodeValue; // } // else // { // final int prime = 31; // int result = 1; // result = prime * result // + ((currentTag == null) ? 0 : currentTag.hashCode()); // result = prime * result // + ((previousTag == null) ? 0 : previousTag.hashCode()); // hashCodeValue = result; // hashCodeCalculated = true; // return result; // } // } // // @Override // public boolean equals(Object obj) // { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // TwoTagsFilter<?,?> other = (TwoTagsFilter<?,?>) obj; // if (currentTag == null) // { // if (other.currentTag != null) // return false; // } else if (!currentTag.equals(other.currentTag)) // return false; // if (previousTag == null) // { // if (other.previousTag != null) // return false; // } else if (!previousTag.equals(other.previousTag)) // return false; // return true; // } // // // // private final G currentTag; // private final G previousTag; // // private transient int hashCodeValue = 0; // private transient boolean hashCodeCalculated = false; // }
import java.util.LinkedHashSet; import java.util.Set; import com.asher_stern.crf.crf.filters.Filter; import com.asher_stern.crf.crf.filters.FilterFactory; import com.asher_stern.crf.crf.filters.TwoTagsFilter;
package com.asher_stern.crf.postagging.postaggers.crf.features; /** * A {@link FilterFactory} for the features generated by the {@link StandardFeatureGenerator}. * * @author Asher Stern * Date: Nov 11, 2014 * */ public class StandardFilterFactory implements FilterFactory<String, String> { private static final long serialVersionUID = 6283122214266870374L; @Override public Set<Filter<String, String>> createFilters(String[] sequence, int tokenIndex, String currentTag, String previousTag) { String token = sequence[tokenIndex]; Set<Filter<String, String>> ret = new LinkedHashSet<Filter<String,String>>();
// Path: src/main/java/com/asher_stern/crf/crf/filters/Filter.java // public abstract class Filter<K,G> implements Serializable // { // private static final long serialVersionUID = 5563671313834518710L; // // public abstract int hashCode(); // public abstract boolean equals(Object obj); // } // // Path: src/main/java/com/asher_stern/crf/crf/filters/FilterFactory.java // public interface FilterFactory<K, G> extends Serializable // { // /** // * Creates a set of filters for the given token,tag, and tag-of-previous-token. // * The convention is as follows: // * Let each feature f be a feature that <B>might</B> return non-zero for the given token,tag,previous-tag. // * That feature is encapsulated with a {@link Filter} in a {@link CrfFilteredFeature}. Let's call this filter "t". // * For that filter there exist one filter in the set returned by this function, name it "t'", such that "t'" equals to "t". // * // * // * @param sequence A sequence of tokens // * @param tokenIndex An index of a token in that sequence // * @param currentTag A tag for that token // * @param previousTag A tag for the token which immediately precedes that token. // * @return A set of filters as described above. // */ // public Set<Filter<K, G>> createFilters(K[] sequence, int tokenIndex, G currentTag, G previousTag); // } // // Path: src/main/java/com/asher_stern/crf/crf/filters/TwoTagsFilter.java // public class TwoTagsFilter<K, G> extends Filter<K, G> // { // private static final long serialVersionUID = -4850947891058236177L; // // public TwoTagsFilter(G currentTag, G previousTag) // { // this.currentTag = currentTag; // this.previousTag = previousTag; // } // // // // @Override // public int hashCode() // { // if (hashCodeCalculated) // { // return hashCodeValue; // } // else // { // final int prime = 31; // int result = 1; // result = prime * result // + ((currentTag == null) ? 0 : currentTag.hashCode()); // result = prime * result // + ((previousTag == null) ? 0 : previousTag.hashCode()); // hashCodeValue = result; // hashCodeCalculated = true; // return result; // } // } // // @Override // public boolean equals(Object obj) // { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // TwoTagsFilter<?,?> other = (TwoTagsFilter<?,?>) obj; // if (currentTag == null) // { // if (other.currentTag != null) // return false; // } else if (!currentTag.equals(other.currentTag)) // return false; // if (previousTag == null) // { // if (other.previousTag != null) // return false; // } else if (!previousTag.equals(other.previousTag)) // return false; // return true; // } // // // // private final G currentTag; // private final G previousTag; // // private transient int hashCodeValue = 0; // private transient boolean hashCodeCalculated = false; // } // Path: src/main/java/com/asher_stern/crf/postagging/postaggers/crf/features/StandardFilterFactory.java import java.util.LinkedHashSet; import java.util.Set; import com.asher_stern.crf.crf.filters.Filter; import com.asher_stern.crf.crf.filters.FilterFactory; import com.asher_stern.crf.crf.filters.TwoTagsFilter; package com.asher_stern.crf.postagging.postaggers.crf.features; /** * A {@link FilterFactory} for the features generated by the {@link StandardFeatureGenerator}. * * @author Asher Stern * Date: Nov 11, 2014 * */ public class StandardFilterFactory implements FilterFactory<String, String> { private static final long serialVersionUID = 6283122214266870374L; @Override public Set<Filter<String, String>> createFilters(String[] sequence, int tokenIndex, String currentTag, String previousTag) { String token = sequence[tokenIndex]; Set<Filter<String, String>> ret = new LinkedHashSet<Filter<String,String>>();
ret.add(new TwoTagsFilter<String, String>(currentTag, previousTag));
asher-stern/CRF
src/main/java/com/asher_stern/crf/postagging/postaggers/majority/MajorityPosTaggerTrainer.java
// Path: src/main/java/com/asher_stern/crf/postagging/postaggers/PosTagger.java // public interface PosTagger // { // /** // * Assigns tags for each token in the given sentence. // * @param sentence An input sentence, given as a list of tokens. // * @return The tagged sentence. // */ // public List<TaggedToken<String,String>> tagSentence(List<String> sentence); // } // // Path: src/main/java/com/asher_stern/crf/postagging/postaggers/PosTaggerTrainer.java // public interface PosTaggerTrainer<C extends Iterable<? extends List<? extends TaggedToken<String, String>>>> // { // /** // * Train the pos-tagger with the given corpus. // * @param corpus // */ // public void train(C corpus); // // /** // * Get the trained pos-tagger, which has been created earlier by the method {@link #train(PosTagCorpus)}. // * @return // */ // public PosTagger getTrainedPosTagger(); // // /** // * Save the pos-tagger model which has been learned earlier by the method {@link #train(PosTagCorpus)}. // * @param modelDirectory // */ // public void save(File modelDirectory); // // } // // Path: src/main/java/com/asher_stern/crf/utilities/CrfException.java // public class CrfException extends RuntimeException // { // private static final long serialVersionUID = 5414394233000815286L; // // public CrfException() // { // super(); // } // // public CrfException(String message, Throwable cause, // boolean enableSuppression, boolean writableStackTrace) // { // super(message, cause, enableSuppression, writableStackTrace); // } // // public CrfException(String message, Throwable cause) // { // super(message, cause); // } // // public CrfException(String message) // { // super(message); // } // // public CrfException(Throwable cause) // { // super(cause); // } // // // } // // Path: src/main/java/com/asher_stern/crf/utilities/TaggedToken.java // public class TaggedToken<K,G> // { // public TaggedToken(K token, G tag) // { // super(); // this.token = token; // this.tag = tag; // } // // // // public K getToken() // { // return token; // } // public G getTag() // { // return tag; // } // // // // // @Override // public String toString() // { // return "CrfTaggedToken [getToken()=" + getToken() + ", getTag()=" // + getTag() + "]"; // } // // // // // // // @Override // public int hashCode() // { // final int prime = 31; // int result = 1; // result = prime * result + ((tag == null) ? 0 : tag.hashCode()); // result = prime * result + ((token == null) ? 0 : token.hashCode()); // return result; // } // // // // @Override // public boolean equals(Object obj) // { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // TaggedToken<?,?> other = (TaggedToken<?,?>) obj; // if (tag == null) // { // if (other.tag != null) // return false; // } else if (!tag.equals(other.tag)) // return false; // if (token == null) // { // if (other.token != null) // return false; // } else if (!token.equals(other.token)) // return false; // return true; // } // // // // // // // private final K token; // private final G tag; // }
import java.io.File; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.apache.log4j.Logger; import com.asher_stern.crf.postagging.postaggers.PosTagger; import com.asher_stern.crf.postagging.postaggers.PosTaggerTrainer; import com.asher_stern.crf.utilities.CrfException; import com.asher_stern.crf.utilities.TaggedToken;
package com.asher_stern.crf.postagging.postaggers.majority; /** * Trains a {@link MajorityPosTagger} from a given corpus. * For each token the trainer counts how many times each tag was assigned to that token in the corpus. * Then, for each token, the tag that was the most frequent for that token is considered as the tag to be used in * annotating a test example. * * @author Asher Stern * Date: Nov 4, 2014 * */ public class MajorityPosTaggerTrainer implements PosTaggerTrainer<Iterable<List<TaggedToken<String, String>>>> { @Override public void train(Iterable<List<TaggedToken<String, String>>> corpus) { processCorpus(corpus); majorityForToken = calculateMajorityForTokens(); majorGeneralTag = getMajority(majorityMapGeneralTag); posTagger = new MajorityPosTagger(majorityForToken, majorGeneralTag); } @Override
// Path: src/main/java/com/asher_stern/crf/postagging/postaggers/PosTagger.java // public interface PosTagger // { // /** // * Assigns tags for each token in the given sentence. // * @param sentence An input sentence, given as a list of tokens. // * @return The tagged sentence. // */ // public List<TaggedToken<String,String>> tagSentence(List<String> sentence); // } // // Path: src/main/java/com/asher_stern/crf/postagging/postaggers/PosTaggerTrainer.java // public interface PosTaggerTrainer<C extends Iterable<? extends List<? extends TaggedToken<String, String>>>> // { // /** // * Train the pos-tagger with the given corpus. // * @param corpus // */ // public void train(C corpus); // // /** // * Get the trained pos-tagger, which has been created earlier by the method {@link #train(PosTagCorpus)}. // * @return // */ // public PosTagger getTrainedPosTagger(); // // /** // * Save the pos-tagger model which has been learned earlier by the method {@link #train(PosTagCorpus)}. // * @param modelDirectory // */ // public void save(File modelDirectory); // // } // // Path: src/main/java/com/asher_stern/crf/utilities/CrfException.java // public class CrfException extends RuntimeException // { // private static final long serialVersionUID = 5414394233000815286L; // // public CrfException() // { // super(); // } // // public CrfException(String message, Throwable cause, // boolean enableSuppression, boolean writableStackTrace) // { // super(message, cause, enableSuppression, writableStackTrace); // } // // public CrfException(String message, Throwable cause) // { // super(message, cause); // } // // public CrfException(String message) // { // super(message); // } // // public CrfException(Throwable cause) // { // super(cause); // } // // // } // // Path: src/main/java/com/asher_stern/crf/utilities/TaggedToken.java // public class TaggedToken<K,G> // { // public TaggedToken(K token, G tag) // { // super(); // this.token = token; // this.tag = tag; // } // // // // public K getToken() // { // return token; // } // public G getTag() // { // return tag; // } // // // // // @Override // public String toString() // { // return "CrfTaggedToken [getToken()=" + getToken() + ", getTag()=" // + getTag() + "]"; // } // // // // // // // @Override // public int hashCode() // { // final int prime = 31; // int result = 1; // result = prime * result + ((tag == null) ? 0 : tag.hashCode()); // result = prime * result + ((token == null) ? 0 : token.hashCode()); // return result; // } // // // // @Override // public boolean equals(Object obj) // { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // TaggedToken<?,?> other = (TaggedToken<?,?>) obj; // if (tag == null) // { // if (other.tag != null) // return false; // } else if (!tag.equals(other.tag)) // return false; // if (token == null) // { // if (other.token != null) // return false; // } else if (!token.equals(other.token)) // return false; // return true; // } // // // // // // // private final K token; // private final G tag; // } // Path: src/main/java/com/asher_stern/crf/postagging/postaggers/majority/MajorityPosTaggerTrainer.java import java.io.File; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.apache.log4j.Logger; import com.asher_stern.crf.postagging.postaggers.PosTagger; import com.asher_stern.crf.postagging.postaggers.PosTaggerTrainer; import com.asher_stern.crf.utilities.CrfException; import com.asher_stern.crf.utilities.TaggedToken; package com.asher_stern.crf.postagging.postaggers.majority; /** * Trains a {@link MajorityPosTagger} from a given corpus. * For each token the trainer counts how many times each tag was assigned to that token in the corpus. * Then, for each token, the tag that was the most frequent for that token is considered as the tag to be used in * annotating a test example. * * @author Asher Stern * Date: Nov 4, 2014 * */ public class MajorityPosTaggerTrainer implements PosTaggerTrainer<Iterable<List<TaggedToken<String, String>>>> { @Override public void train(Iterable<List<TaggedToken<String, String>>> corpus) { processCorpus(corpus); majorityForToken = calculateMajorityForTokens(); majorGeneralTag = getMajority(majorityMapGeneralTag); posTagger = new MajorityPosTagger(majorityForToken, majorGeneralTag); } @Override
public PosTagger getTrainedPosTagger()
asher-stern/CRF
src/main/java/com/asher_stern/crf/postagging/postaggers/majority/MajorityPosTaggerTrainer.java
// Path: src/main/java/com/asher_stern/crf/postagging/postaggers/PosTagger.java // public interface PosTagger // { // /** // * Assigns tags for each token in the given sentence. // * @param sentence An input sentence, given as a list of tokens. // * @return The tagged sentence. // */ // public List<TaggedToken<String,String>> tagSentence(List<String> sentence); // } // // Path: src/main/java/com/asher_stern/crf/postagging/postaggers/PosTaggerTrainer.java // public interface PosTaggerTrainer<C extends Iterable<? extends List<? extends TaggedToken<String, String>>>> // { // /** // * Train the pos-tagger with the given corpus. // * @param corpus // */ // public void train(C corpus); // // /** // * Get the trained pos-tagger, which has been created earlier by the method {@link #train(PosTagCorpus)}. // * @return // */ // public PosTagger getTrainedPosTagger(); // // /** // * Save the pos-tagger model which has been learned earlier by the method {@link #train(PosTagCorpus)}. // * @param modelDirectory // */ // public void save(File modelDirectory); // // } // // Path: src/main/java/com/asher_stern/crf/utilities/CrfException.java // public class CrfException extends RuntimeException // { // private static final long serialVersionUID = 5414394233000815286L; // // public CrfException() // { // super(); // } // // public CrfException(String message, Throwable cause, // boolean enableSuppression, boolean writableStackTrace) // { // super(message, cause, enableSuppression, writableStackTrace); // } // // public CrfException(String message, Throwable cause) // { // super(message, cause); // } // // public CrfException(String message) // { // super(message); // } // // public CrfException(Throwable cause) // { // super(cause); // } // // // } // // Path: src/main/java/com/asher_stern/crf/utilities/TaggedToken.java // public class TaggedToken<K,G> // { // public TaggedToken(K token, G tag) // { // super(); // this.token = token; // this.tag = tag; // } // // // // public K getToken() // { // return token; // } // public G getTag() // { // return tag; // } // // // // // @Override // public String toString() // { // return "CrfTaggedToken [getToken()=" + getToken() + ", getTag()=" // + getTag() + "]"; // } // // // // // // // @Override // public int hashCode() // { // final int prime = 31; // int result = 1; // result = prime * result + ((tag == null) ? 0 : tag.hashCode()); // result = prime * result + ((token == null) ? 0 : token.hashCode()); // return result; // } // // // // @Override // public boolean equals(Object obj) // { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // TaggedToken<?,?> other = (TaggedToken<?,?>) obj; // if (tag == null) // { // if (other.tag != null) // return false; // } else if (!tag.equals(other.tag)) // return false; // if (token == null) // { // if (other.token != null) // return false; // } else if (!token.equals(other.token)) // return false; // return true; // } // // // // // // // private final K token; // private final G tag; // }
import java.io.File; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.apache.log4j.Logger; import com.asher_stern.crf.postagging.postaggers.PosTagger; import com.asher_stern.crf.postagging.postaggers.PosTaggerTrainer; import com.asher_stern.crf.utilities.CrfException; import com.asher_stern.crf.utilities.TaggedToken;
package com.asher_stern.crf.postagging.postaggers.majority; /** * Trains a {@link MajorityPosTagger} from a given corpus. * For each token the trainer counts how many times each tag was assigned to that token in the corpus. * Then, for each token, the tag that was the most frequent for that token is considered as the tag to be used in * annotating a test example. * * @author Asher Stern * Date: Nov 4, 2014 * */ public class MajorityPosTaggerTrainer implements PosTaggerTrainer<Iterable<List<TaggedToken<String, String>>>> { @Override public void train(Iterable<List<TaggedToken<String, String>>> corpus) { processCorpus(corpus); majorityForToken = calculateMajorityForTokens(); majorGeneralTag = getMajority(majorityMapGeneralTag); posTagger = new MajorityPosTagger(majorityForToken, majorGeneralTag); } @Override public PosTagger getTrainedPosTagger() {
// Path: src/main/java/com/asher_stern/crf/postagging/postaggers/PosTagger.java // public interface PosTagger // { // /** // * Assigns tags for each token in the given sentence. // * @param sentence An input sentence, given as a list of tokens. // * @return The tagged sentence. // */ // public List<TaggedToken<String,String>> tagSentence(List<String> sentence); // } // // Path: src/main/java/com/asher_stern/crf/postagging/postaggers/PosTaggerTrainer.java // public interface PosTaggerTrainer<C extends Iterable<? extends List<? extends TaggedToken<String, String>>>> // { // /** // * Train the pos-tagger with the given corpus. // * @param corpus // */ // public void train(C corpus); // // /** // * Get the trained pos-tagger, which has been created earlier by the method {@link #train(PosTagCorpus)}. // * @return // */ // public PosTagger getTrainedPosTagger(); // // /** // * Save the pos-tagger model which has been learned earlier by the method {@link #train(PosTagCorpus)}. // * @param modelDirectory // */ // public void save(File modelDirectory); // // } // // Path: src/main/java/com/asher_stern/crf/utilities/CrfException.java // public class CrfException extends RuntimeException // { // private static final long serialVersionUID = 5414394233000815286L; // // public CrfException() // { // super(); // } // // public CrfException(String message, Throwable cause, // boolean enableSuppression, boolean writableStackTrace) // { // super(message, cause, enableSuppression, writableStackTrace); // } // // public CrfException(String message, Throwable cause) // { // super(message, cause); // } // // public CrfException(String message) // { // super(message); // } // // public CrfException(Throwable cause) // { // super(cause); // } // // // } // // Path: src/main/java/com/asher_stern/crf/utilities/TaggedToken.java // public class TaggedToken<K,G> // { // public TaggedToken(K token, G tag) // { // super(); // this.token = token; // this.tag = tag; // } // // // // public K getToken() // { // return token; // } // public G getTag() // { // return tag; // } // // // // // @Override // public String toString() // { // return "CrfTaggedToken [getToken()=" + getToken() + ", getTag()=" // + getTag() + "]"; // } // // // // // // // @Override // public int hashCode() // { // final int prime = 31; // int result = 1; // result = prime * result + ((tag == null) ? 0 : tag.hashCode()); // result = prime * result + ((token == null) ? 0 : token.hashCode()); // return result; // } // // // // @Override // public boolean equals(Object obj) // { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // TaggedToken<?,?> other = (TaggedToken<?,?>) obj; // if (tag == null) // { // if (other.tag != null) // return false; // } else if (!tag.equals(other.tag)) // return false; // if (token == null) // { // if (other.token != null) // return false; // } else if (!token.equals(other.token)) // return false; // return true; // } // // // // // // // private final K token; // private final G tag; // } // Path: src/main/java/com/asher_stern/crf/postagging/postaggers/majority/MajorityPosTaggerTrainer.java import java.io.File; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.apache.log4j.Logger; import com.asher_stern.crf.postagging.postaggers.PosTagger; import com.asher_stern.crf.postagging.postaggers.PosTaggerTrainer; import com.asher_stern.crf.utilities.CrfException; import com.asher_stern.crf.utilities.TaggedToken; package com.asher_stern.crf.postagging.postaggers.majority; /** * Trains a {@link MajorityPosTagger} from a given corpus. * For each token the trainer counts how many times each tag was assigned to that token in the corpus. * Then, for each token, the tag that was the most frequent for that token is considered as the tag to be used in * annotating a test example. * * @author Asher Stern * Date: Nov 4, 2014 * */ public class MajorityPosTaggerTrainer implements PosTaggerTrainer<Iterable<List<TaggedToken<String, String>>>> { @Override public void train(Iterable<List<TaggedToken<String, String>>> corpus) { processCorpus(corpus); majorityForToken = calculateMajorityForTokens(); majorGeneralTag = getMajority(majorityMapGeneralTag); posTagger = new MajorityPosTagger(majorityForToken, majorGeneralTag); } @Override public PosTagger getTrainedPosTagger() {
if (null==posTagger) {throw new CrfException("Not yet trained.");}
asher-stern/CRF
src/main/java/com/asher_stern/crf/postagging/data/brown/BrownTaggedSentenceReader.java
// Path: src/main/java/com/asher_stern/crf/utilities/CrfException.java // public class CrfException extends RuntimeException // { // private static final long serialVersionUID = 5414394233000815286L; // // public CrfException() // { // super(); // } // // public CrfException(String message, Throwable cause, // boolean enableSuppression, boolean writableStackTrace) // { // super(message, cause, enableSuppression, writableStackTrace); // } // // public CrfException(String message, Throwable cause) // { // super(message, cause); // } // // public CrfException(String message) // { // super(message); // } // // public CrfException(Throwable cause) // { // super(cause); // } // // // } // // Path: src/main/java/com/asher_stern/crf/utilities/TaggedToken.java // public class TaggedToken<K,G> // { // public TaggedToken(K token, G tag) // { // super(); // this.token = token; // this.tag = tag; // } // // // // public K getToken() // { // return token; // } // public G getTag() // { // return tag; // } // // // // // @Override // public String toString() // { // return "CrfTaggedToken [getToken()=" + getToken() + ", getTag()=" // + getTag() + "]"; // } // // // // // // // @Override // public int hashCode() // { // final int prime = 31; // int result = 1; // result = prime * result + ((tag == null) ? 0 : tag.hashCode()); // result = prime * result + ((token == null) ? 0 : token.hashCode()); // return result; // } // // // // @Override // public boolean equals(Object obj) // { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // TaggedToken<?,?> other = (TaggedToken<?,?>) obj; // if (tag == null) // { // if (other.tag != null) // return false; // } else if (!tag.equals(other.tag)) // return false; // if (token == null) // { // if (other.token != null) // return false; // } else if (!token.equals(other.token)) // return false; // return true; // } // // // // // // // private final K token; // private final G tag; // }
import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import com.asher_stern.crf.utilities.CrfException; import com.asher_stern.crf.utilities.TaggedToken;
TAGS.add("RN"); TAGS.add("RP"); TAGS.add("TL"); TAGS.add("TO"); TAGS.add("UH"); TAGS.add("VB"); TAGS.add("VBD"); TAGS.add("VBG"); TAGS.add("VBN"); TAGS.add("VBZ"); TAGS.add("WDT"); TAGS.add("WP"); // Not in the original list. Add for WP$ which does appear in the original list. //TAGS.add("WP$"); TAGS.add("WPO"); TAGS.add("WPS"); TAGS.add("WQL"); TAGS.add("WRB"); IGNORE = new LinkedHashSet<String>(); IGNORE.add("NIL"); } public BrownTaggedSentenceReader(String annotatedSentence) { this.annotatedSentence = annotatedSentence; }
// Path: src/main/java/com/asher_stern/crf/utilities/CrfException.java // public class CrfException extends RuntimeException // { // private static final long serialVersionUID = 5414394233000815286L; // // public CrfException() // { // super(); // } // // public CrfException(String message, Throwable cause, // boolean enableSuppression, boolean writableStackTrace) // { // super(message, cause, enableSuppression, writableStackTrace); // } // // public CrfException(String message, Throwable cause) // { // super(message, cause); // } // // public CrfException(String message) // { // super(message); // } // // public CrfException(Throwable cause) // { // super(cause); // } // // // } // // Path: src/main/java/com/asher_stern/crf/utilities/TaggedToken.java // public class TaggedToken<K,G> // { // public TaggedToken(K token, G tag) // { // super(); // this.token = token; // this.tag = tag; // } // // // // public K getToken() // { // return token; // } // public G getTag() // { // return tag; // } // // // // // @Override // public String toString() // { // return "CrfTaggedToken [getToken()=" + getToken() + ", getTag()=" // + getTag() + "]"; // } // // // // // // // @Override // public int hashCode() // { // final int prime = 31; // int result = 1; // result = prime * result + ((tag == null) ? 0 : tag.hashCode()); // result = prime * result + ((token == null) ? 0 : token.hashCode()); // return result; // } // // // // @Override // public boolean equals(Object obj) // { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // TaggedToken<?,?> other = (TaggedToken<?,?>) obj; // if (tag == null) // { // if (other.tag != null) // return false; // } else if (!tag.equals(other.tag)) // return false; // if (token == null) // { // if (other.token != null) // return false; // } else if (!token.equals(other.token)) // return false; // return true; // } // // // // // // // private final K token; // private final G tag; // } // Path: src/main/java/com/asher_stern/crf/postagging/data/brown/BrownTaggedSentenceReader.java import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import com.asher_stern.crf.utilities.CrfException; import com.asher_stern.crf.utilities.TaggedToken; TAGS.add("RN"); TAGS.add("RP"); TAGS.add("TL"); TAGS.add("TO"); TAGS.add("UH"); TAGS.add("VB"); TAGS.add("VBD"); TAGS.add("VBG"); TAGS.add("VBN"); TAGS.add("VBZ"); TAGS.add("WDT"); TAGS.add("WP"); // Not in the original list. Add for WP$ which does appear in the original list. //TAGS.add("WP$"); TAGS.add("WPO"); TAGS.add("WPS"); TAGS.add("WQL"); TAGS.add("WRB"); IGNORE = new LinkedHashSet<String>(); IGNORE.add("NIL"); } public BrownTaggedSentenceReader(String annotatedSentence) { this.annotatedSentence = annotatedSentence; }
public List<TaggedToken<String,String>> read()
asher-stern/CRF
src/main/java/com/asher_stern/crf/postagging/data/brown/BrownTaggedSentenceReader.java
// Path: src/main/java/com/asher_stern/crf/utilities/CrfException.java // public class CrfException extends RuntimeException // { // private static final long serialVersionUID = 5414394233000815286L; // // public CrfException() // { // super(); // } // // public CrfException(String message, Throwable cause, // boolean enableSuppression, boolean writableStackTrace) // { // super(message, cause, enableSuppression, writableStackTrace); // } // // public CrfException(String message, Throwable cause) // { // super(message, cause); // } // // public CrfException(String message) // { // super(message); // } // // public CrfException(Throwable cause) // { // super(cause); // } // // // } // // Path: src/main/java/com/asher_stern/crf/utilities/TaggedToken.java // public class TaggedToken<K,G> // { // public TaggedToken(K token, G tag) // { // super(); // this.token = token; // this.tag = tag; // } // // // // public K getToken() // { // return token; // } // public G getTag() // { // return tag; // } // // // // // @Override // public String toString() // { // return "CrfTaggedToken [getToken()=" + getToken() + ", getTag()=" // + getTag() + "]"; // } // // // // // // // @Override // public int hashCode() // { // final int prime = 31; // int result = 1; // result = prime * result + ((tag == null) ? 0 : tag.hashCode()); // result = prime * result + ((token == null) ? 0 : token.hashCode()); // return result; // } // // // // @Override // public boolean equals(Object obj) // { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // TaggedToken<?,?> other = (TaggedToken<?,?>) obj; // if (tag == null) // { // if (other.tag != null) // return false; // } else if (!tag.equals(other.tag)) // return false; // if (token == null) // { // if (other.token != null) // return false; // } else if (!token.equals(other.token)) // return false; // return true; // } // // // // // // // private final K token; // private final G tag; // }
import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import com.asher_stern.crf.utilities.CrfException; import com.asher_stern.crf.utilities.TaggedToken;
tag = tag.toUpperCase(); if (letterDetected) { int starIndex = tag.indexOf('*'); if (starIndex>=1) { tag = tag.substring(0, starIndex); } int possessiveIndex = tag.indexOf(POSSESSIVE_INDICATOR); if (possessiveIndex>=1) { tag = tag.substring(0, possessiveIndex); } if (IGNORE.contains(tag)) { shouldBeIgnored = true; ret = null; } if (TAGS.contains(tag)) { ret = tag; } } else { ret = PUNC_TAG; } if ( (ret == null) && (!shouldBeIgnored) ) {
// Path: src/main/java/com/asher_stern/crf/utilities/CrfException.java // public class CrfException extends RuntimeException // { // private static final long serialVersionUID = 5414394233000815286L; // // public CrfException() // { // super(); // } // // public CrfException(String message, Throwable cause, // boolean enableSuppression, boolean writableStackTrace) // { // super(message, cause, enableSuppression, writableStackTrace); // } // // public CrfException(String message, Throwable cause) // { // super(message, cause); // } // // public CrfException(String message) // { // super(message); // } // // public CrfException(Throwable cause) // { // super(cause); // } // // // } // // Path: src/main/java/com/asher_stern/crf/utilities/TaggedToken.java // public class TaggedToken<K,G> // { // public TaggedToken(K token, G tag) // { // super(); // this.token = token; // this.tag = tag; // } // // // // public K getToken() // { // return token; // } // public G getTag() // { // return tag; // } // // // // // @Override // public String toString() // { // return "CrfTaggedToken [getToken()=" + getToken() + ", getTag()=" // + getTag() + "]"; // } // // // // // // // @Override // public int hashCode() // { // final int prime = 31; // int result = 1; // result = prime * result + ((tag == null) ? 0 : tag.hashCode()); // result = prime * result + ((token == null) ? 0 : token.hashCode()); // return result; // } // // // // @Override // public boolean equals(Object obj) // { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // TaggedToken<?,?> other = (TaggedToken<?,?>) obj; // if (tag == null) // { // if (other.tag != null) // return false; // } else if (!tag.equals(other.tag)) // return false; // if (token == null) // { // if (other.token != null) // return false; // } else if (!token.equals(other.token)) // return false; // return true; // } // // // // // // // private final K token; // private final G tag; // } // Path: src/main/java/com/asher_stern/crf/postagging/data/brown/BrownTaggedSentenceReader.java import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import com.asher_stern.crf.utilities.CrfException; import com.asher_stern.crf.utilities.TaggedToken; tag = tag.toUpperCase(); if (letterDetected) { int starIndex = tag.indexOf('*'); if (starIndex>=1) { tag = tag.substring(0, starIndex); } int possessiveIndex = tag.indexOf(POSSESSIVE_INDICATOR); if (possessiveIndex>=1) { tag = tag.substring(0, possessiveIndex); } if (IGNORE.contains(tag)) { shouldBeIgnored = true; ret = null; } if (TAGS.contains(tag)) { ret = tag; } } else { ret = PUNC_TAG; } if ( (ret == null) && (!shouldBeIgnored) ) {
throw new CrfException("Unrecognized tag in Brown corpus: "+tag+". Original tag: "+originalTag+".\n"
asher-stern/CRF
src/main/java/com/asher_stern/crf/postagging/postaggers/crf/features/TagTransitionFeature.java
// Path: src/main/java/com/asher_stern/crf/utilities/MiscellaneousUtilities.java // public static <T> boolean equalObjects(T t1, T t2) // { // if (t1==t2) return true; // if ( (t1==null) || (t2==null) ) return false; // return t1.equals(t2); // } // // Path: src/main/java/com/asher_stern/crf/crf/CrfFeature.java // public abstract class CrfFeature<K,G> implements Serializable // K = token, G = tag // { // private static final long serialVersionUID = 5422105702440104947L; // // public abstract double value(K[] sequence, int indexInSequence, G currentTag, G previousTag); // // public abstract boolean equals(Object obj); // public abstract int hashCode(); // }
import static com.asher_stern.crf.utilities.MiscellaneousUtilities.equalObjects; import com.asher_stern.crf.crf.CrfFeature;
package com.asher_stern.crf.postagging.postaggers.crf.features; /** * A feature that models the transition from one tag to another (possibly the same) tag. * * @author Asher Stern * Date: Nov 10, 2014 * */ public class TagTransitionFeature extends CrfFeature<String, String> { private static final long serialVersionUID = -61200838311988363L; public TagTransitionFeature(String forPreviousTag, String forCurrentTag) { super(); this.forPreviousTag = forPreviousTag; this.forCurrentTag = forCurrentTag; } @Override public double value(String[] sequence, int indexInSequence, String currentTag, String previousTag) { double ret = 0.0;
// Path: src/main/java/com/asher_stern/crf/utilities/MiscellaneousUtilities.java // public static <T> boolean equalObjects(T t1, T t2) // { // if (t1==t2) return true; // if ( (t1==null) || (t2==null) ) return false; // return t1.equals(t2); // } // // Path: src/main/java/com/asher_stern/crf/crf/CrfFeature.java // public abstract class CrfFeature<K,G> implements Serializable // K = token, G = tag // { // private static final long serialVersionUID = 5422105702440104947L; // // public abstract double value(K[] sequence, int indexInSequence, G currentTag, G previousTag); // // public abstract boolean equals(Object obj); // public abstract int hashCode(); // } // Path: src/main/java/com/asher_stern/crf/postagging/postaggers/crf/features/TagTransitionFeature.java import static com.asher_stern.crf.utilities.MiscellaneousUtilities.equalObjects; import com.asher_stern.crf.crf.CrfFeature; package com.asher_stern.crf.postagging.postaggers.crf.features; /** * A feature that models the transition from one tag to another (possibly the same) tag. * * @author Asher Stern * Date: Nov 10, 2014 * */ public class TagTransitionFeature extends CrfFeature<String, String> { private static final long serialVersionUID = -61200838311988363L; public TagTransitionFeature(String forPreviousTag, String forCurrentTag) { super(); this.forPreviousTag = forPreviousTag; this.forCurrentTag = forCurrentTag; } @Override public double value(String[] sequence, int indexInSequence, String currentTag, String previousTag) { double ret = 0.0;
if ( equalObjects(previousTag, forPreviousTag) && equalObjects(currentTag, forCurrentTag) )
asher-stern/CRF
src/main/java/com/asher_stern/crf/function/optimization/LineSearchUtilities.java
// Path: src/main/java/com/asher_stern/crf/utilities/VectorUtilities.java // public class VectorUtilities // { // /** // * Returns the inner product of the two given vectors. // * @param rowVector // * @param columnVector // * @return // */ // public static BigDecimal product(BigDecimal[] rowVector, BigDecimal[] columnVector) // { // if (rowVector.length!=columnVector.length) throw new CrfException("Cannot multiply vector of different sizes."); // BigDecimal ret = BigDecimal.ZERO; // for (int i=0;i<rowVector.length;++i) // { // ret = safeAdd(ret, safeMultiply(rowVector[i], columnVector[i])); // } // return ret; // } // // /** // * Returns a new vector which is the multiplication of the given vector by a scalar. // * @param scalar // * @param vector // * @return // */ // public static BigDecimal[] multiplyByScalar(BigDecimal scalar, BigDecimal[] vector) // { // BigDecimal[] ret = new BigDecimal[vector.length]; // for (int i=0;i<vector.length;++i) // { // ret[i] = safeMultiply(scalar, vector[i]); // } // return ret; // } // // /** // * Returns the sum of the two vectors, as a new vector. For example [1,2]+[3,4] = [4,6]. // * @param vector1 // * @param vector2 // * @return // */ // public static BigDecimal[] addVectors(BigDecimal[] vector1, BigDecimal[] vector2) // { // if (vector1.length!=vector2.length) throw new CrfException("Cannot add two vectors of different sizes."); // BigDecimal[] ret = new BigDecimal[vector1.length]; // for (int i=0;i<vector1.length;++i) // { // ret[i] = safeAdd(vector1[i], vector2[i]); // } // return ret; // } // // /** // * Returns the substraction of the given two vectors. For example [10,20]-[5,6] = [5,14]. // * @param vector1 // * @param vector2 // * @return // */ // public static BigDecimal[] subtractVectors(BigDecimal[] vector1, BigDecimal[] vector2) // { // if (vector1.length!=vector2.length) throw new CrfException("Cannot substract vectors of difference sizes."); // BigDecimal[] ret = new BigDecimal[vector1.length]; // for (int i=0;i<vector1.length;++i) // { // ret[i] = safeSubtract(vector1[i], vector2[i]); // } // return ret; // } // // public static BigDecimal euclideanNormSquare(BigDecimal[] vector) // { // return product(vector, vector); // } // // // public static double euclideanNorm(double[] vector) // // { // // return Math.sqrt(euclideanNormSquare(vector)); // // } // // // /** // * Changes every infinity value in the array to Double.MAX_VALUE (or -Double.MAX_VALUE for negative infinity). // * @param array a given array. // */ // @Deprecated // public static final double[] changeInfinityToDoubleMax(final double[] array) // { // double[] ret = new double[array.length]; // for (int i=0; i<array.length; ++i) // { // if (Double.POSITIVE_INFINITY==array[i]) // { // ret[i] = Double.MAX_VALUE; // } // else if (Double.NEGATIVE_INFINITY==array[i]) // { // ret[i] = -Double.MAX_VALUE; // } // else // { // ret[i] = array[i]; // } // } // return ret; // } // // } // // Path: src/main/java/com/asher_stern/crf/function/DerivableFunction.java // public abstract class DerivableFunction extends Function // { // /** // * Returns the gradient of the function in the given point. // * For example, if the function is f(x_1,x_2) = (x_1)^2 + x_1*x_2, then for [3,5] the returned gradient is [11 , 3]. // * @param point the point is "x", the input for the function, for which the user needs the gradient. // * @return the gradient of the function in the given point. // */ // public abstract BigDecimal[] gradient(BigDecimal[] point); // }
import static com.asher_stern.crf.utilities.VectorUtilities.*; import java.math.BigDecimal; import com.asher_stern.crf.function.DerivableFunction;
package com.asher_stern.crf.function.optimization; /** * A collection of static helper functions, needed for some implementations of {@link LineSearch}. * * @author Asher Stern * Date: Nov 7, 2014 * */ public class LineSearchUtilities { /** * Returns f(x+\alpha*d), where "x" is the given point, "d" is the given direction, and "\alpha" is some scalar. */
// Path: src/main/java/com/asher_stern/crf/utilities/VectorUtilities.java // public class VectorUtilities // { // /** // * Returns the inner product of the two given vectors. // * @param rowVector // * @param columnVector // * @return // */ // public static BigDecimal product(BigDecimal[] rowVector, BigDecimal[] columnVector) // { // if (rowVector.length!=columnVector.length) throw new CrfException("Cannot multiply vector of different sizes."); // BigDecimal ret = BigDecimal.ZERO; // for (int i=0;i<rowVector.length;++i) // { // ret = safeAdd(ret, safeMultiply(rowVector[i], columnVector[i])); // } // return ret; // } // // /** // * Returns a new vector which is the multiplication of the given vector by a scalar. // * @param scalar // * @param vector // * @return // */ // public static BigDecimal[] multiplyByScalar(BigDecimal scalar, BigDecimal[] vector) // { // BigDecimal[] ret = new BigDecimal[vector.length]; // for (int i=0;i<vector.length;++i) // { // ret[i] = safeMultiply(scalar, vector[i]); // } // return ret; // } // // /** // * Returns the sum of the two vectors, as a new vector. For example [1,2]+[3,4] = [4,6]. // * @param vector1 // * @param vector2 // * @return // */ // public static BigDecimal[] addVectors(BigDecimal[] vector1, BigDecimal[] vector2) // { // if (vector1.length!=vector2.length) throw new CrfException("Cannot add two vectors of different sizes."); // BigDecimal[] ret = new BigDecimal[vector1.length]; // for (int i=0;i<vector1.length;++i) // { // ret[i] = safeAdd(vector1[i], vector2[i]); // } // return ret; // } // // /** // * Returns the substraction of the given two vectors. For example [10,20]-[5,6] = [5,14]. // * @param vector1 // * @param vector2 // * @return // */ // public static BigDecimal[] subtractVectors(BigDecimal[] vector1, BigDecimal[] vector2) // { // if (vector1.length!=vector2.length) throw new CrfException("Cannot substract vectors of difference sizes."); // BigDecimal[] ret = new BigDecimal[vector1.length]; // for (int i=0;i<vector1.length;++i) // { // ret[i] = safeSubtract(vector1[i], vector2[i]); // } // return ret; // } // // public static BigDecimal euclideanNormSquare(BigDecimal[] vector) // { // return product(vector, vector); // } // // // public static double euclideanNorm(double[] vector) // // { // // return Math.sqrt(euclideanNormSquare(vector)); // // } // // // /** // * Changes every infinity value in the array to Double.MAX_VALUE (or -Double.MAX_VALUE for negative infinity). // * @param array a given array. // */ // @Deprecated // public static final double[] changeInfinityToDoubleMax(final double[] array) // { // double[] ret = new double[array.length]; // for (int i=0; i<array.length; ++i) // { // if (Double.POSITIVE_INFINITY==array[i]) // { // ret[i] = Double.MAX_VALUE; // } // else if (Double.NEGATIVE_INFINITY==array[i]) // { // ret[i] = -Double.MAX_VALUE; // } // else // { // ret[i] = array[i]; // } // } // return ret; // } // // } // // Path: src/main/java/com/asher_stern/crf/function/DerivableFunction.java // public abstract class DerivableFunction extends Function // { // /** // * Returns the gradient of the function in the given point. // * For example, if the function is f(x_1,x_2) = (x_1)^2 + x_1*x_2, then for [3,5] the returned gradient is [11 , 3]. // * @param point the point is "x", the input for the function, for which the user needs the gradient. // * @return the gradient of the function in the given point. // */ // public abstract BigDecimal[] gradient(BigDecimal[] point); // } // Path: src/main/java/com/asher_stern/crf/function/optimization/LineSearchUtilities.java import static com.asher_stern.crf.utilities.VectorUtilities.*; import java.math.BigDecimal; import com.asher_stern.crf.function.DerivableFunction; package com.asher_stern.crf.function.optimization; /** * A collection of static helper functions, needed for some implementations of {@link LineSearch}. * * @author Asher Stern * Date: Nov 7, 2014 * */ public class LineSearchUtilities { /** * Returns f(x+\alpha*d), where "x" is the given point, "d" is the given direction, and "\alpha" is some scalar. */
public static BigDecimal valueForAlpha(DerivableFunction function, BigDecimal[] point, BigDecimal[] direction, BigDecimal alpha)
asher-stern/CRF
src/main/java/com/asher_stern/crf/postagging/postaggers/PosTagger.java
// Path: src/main/java/com/asher_stern/crf/utilities/TaggedToken.java // public class TaggedToken<K,G> // { // public TaggedToken(K token, G tag) // { // super(); // this.token = token; // this.tag = tag; // } // // // // public K getToken() // { // return token; // } // public G getTag() // { // return tag; // } // // // // // @Override // public String toString() // { // return "CrfTaggedToken [getToken()=" + getToken() + ", getTag()=" // + getTag() + "]"; // } // // // // // // // @Override // public int hashCode() // { // final int prime = 31; // int result = 1; // result = prime * result + ((tag == null) ? 0 : tag.hashCode()); // result = prime * result + ((token == null) ? 0 : token.hashCode()); // return result; // } // // // // @Override // public boolean equals(Object obj) // { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // TaggedToken<?,?> other = (TaggedToken<?,?>) obj; // if (tag == null) // { // if (other.tag != null) // return false; // } else if (!tag.equals(other.tag)) // return false; // if (token == null) // { // if (other.token != null) // return false; // } else if (!token.equals(other.token)) // return false; // return true; // } // // // // // // // private final K token; // private final G tag; // }
import java.util.List; import com.asher_stern.crf.utilities.TaggedToken;
package com.asher_stern.crf.postagging.postaggers; /** * Assigns part-of-speech tags for a given sentence. * * @author Asher Stern * Date: Nov 4, 2014 * */ public interface PosTagger { /** * Assigns tags for each token in the given sentence. * @param sentence An input sentence, given as a list of tokens. * @return The tagged sentence. */
// Path: src/main/java/com/asher_stern/crf/utilities/TaggedToken.java // public class TaggedToken<K,G> // { // public TaggedToken(K token, G tag) // { // super(); // this.token = token; // this.tag = tag; // } // // // // public K getToken() // { // return token; // } // public G getTag() // { // return tag; // } // // // // // @Override // public String toString() // { // return "CrfTaggedToken [getToken()=" + getToken() + ", getTag()=" // + getTag() + "]"; // } // // // // // // // @Override // public int hashCode() // { // final int prime = 31; // int result = 1; // result = prime * result + ((tag == null) ? 0 : tag.hashCode()); // result = prime * result + ((token == null) ? 0 : token.hashCode()); // return result; // } // // // // @Override // public boolean equals(Object obj) // { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // TaggedToken<?,?> other = (TaggedToken<?,?>) obj; // if (tag == null) // { // if (other.tag != null) // return false; // } else if (!tag.equals(other.tag)) // return false; // if (token == null) // { // if (other.token != null) // return false; // } else if (!token.equals(other.token)) // return false; // return true; // } // // // // // // // private final K token; // private final G tag; // } // Path: src/main/java/com/asher_stern/crf/postagging/postaggers/PosTagger.java import java.util.List; import com.asher_stern.crf.utilities.TaggedToken; package com.asher_stern.crf.postagging.postaggers; /** * Assigns part-of-speech tags for a given sentence. * * @author Asher Stern * Date: Nov 4, 2014 * */ public interface PosTagger { /** * Assigns tags for each token in the given sentence. * @param sentence An input sentence, given as a list of tokens. * @return The tagged sentence. */
public List<TaggedToken<String,String>> tagSentence(List<String> sentence);
asher-stern/CRF
src/main/java/com/asher_stern/crf/postagging/postaggers/majority/MajorityPosTagger.java
// Path: src/main/java/com/asher_stern/crf/postagging/postaggers/PosTagger.java // public interface PosTagger // { // /** // * Assigns tags for each token in the given sentence. // * @param sentence An input sentence, given as a list of tokens. // * @return The tagged sentence. // */ // public List<TaggedToken<String,String>> tagSentence(List<String> sentence); // } // // Path: src/main/java/com/asher_stern/crf/utilities/TaggedToken.java // public class TaggedToken<K,G> // { // public TaggedToken(K token, G tag) // { // super(); // this.token = token; // this.tag = tag; // } // // // // public K getToken() // { // return token; // } // public G getTag() // { // return tag; // } // // // // // @Override // public String toString() // { // return "CrfTaggedToken [getToken()=" + getToken() + ", getTag()=" // + getTag() + "]"; // } // // // // // // // @Override // public int hashCode() // { // final int prime = 31; // int result = 1; // result = prime * result + ((tag == null) ? 0 : tag.hashCode()); // result = prime * result + ((token == null) ? 0 : token.hashCode()); // return result; // } // // // // @Override // public boolean equals(Object obj) // { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // TaggedToken<?,?> other = (TaggedToken<?,?>) obj; // if (tag == null) // { // if (other.tag != null) // return false; // } else if (!tag.equals(other.tag)) // return false; // if (token == null) // { // if (other.token != null) // return false; // } else if (!token.equals(other.token)) // return false; // return true; // } // // // // // // // private final K token; // private final G tag; // }
import java.util.ArrayList; import java.util.List; import java.util.Map; import com.asher_stern.crf.postagging.postaggers.PosTagger; import com.asher_stern.crf.utilities.TaggedToken;
package com.asher_stern.crf.postagging.postaggers.majority; /** * A {@link PosTagger} which assigns for each word the tag that occurs mostly with that word. * For words that were not seen in the training corpus, this pos-tagger assigns that tag that is most frequent in the * training corpus. * @author Asher Stern * Date: Nov 4, 2014 * */ public class MajorityPosTagger implements PosTagger { public MajorityPosTagger(Map<String, String> majorityMap, String generalMajorTag) { super(); this.majorityMap = majorityMap; this.generalMajorTag = generalMajorTag; } @Override
// Path: src/main/java/com/asher_stern/crf/postagging/postaggers/PosTagger.java // public interface PosTagger // { // /** // * Assigns tags for each token in the given sentence. // * @param sentence An input sentence, given as a list of tokens. // * @return The tagged sentence. // */ // public List<TaggedToken<String,String>> tagSentence(List<String> sentence); // } // // Path: src/main/java/com/asher_stern/crf/utilities/TaggedToken.java // public class TaggedToken<K,G> // { // public TaggedToken(K token, G tag) // { // super(); // this.token = token; // this.tag = tag; // } // // // // public K getToken() // { // return token; // } // public G getTag() // { // return tag; // } // // // // // @Override // public String toString() // { // return "CrfTaggedToken [getToken()=" + getToken() + ", getTag()=" // + getTag() + "]"; // } // // // // // // // @Override // public int hashCode() // { // final int prime = 31; // int result = 1; // result = prime * result + ((tag == null) ? 0 : tag.hashCode()); // result = prime * result + ((token == null) ? 0 : token.hashCode()); // return result; // } // // // // @Override // public boolean equals(Object obj) // { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // TaggedToken<?,?> other = (TaggedToken<?,?>) obj; // if (tag == null) // { // if (other.tag != null) // return false; // } else if (!tag.equals(other.tag)) // return false; // if (token == null) // { // if (other.token != null) // return false; // } else if (!token.equals(other.token)) // return false; // return true; // } // // // // // // // private final K token; // private final G tag; // } // Path: src/main/java/com/asher_stern/crf/postagging/postaggers/majority/MajorityPosTagger.java import java.util.ArrayList; import java.util.List; import java.util.Map; import com.asher_stern.crf.postagging.postaggers.PosTagger; import com.asher_stern.crf.utilities.TaggedToken; package com.asher_stern.crf.postagging.postaggers.majority; /** * A {@link PosTagger} which assigns for each word the tag that occurs mostly with that word. * For words that were not seen in the training corpus, this pos-tagger assigns that tag that is most frequent in the * training corpus. * @author Asher Stern * Date: Nov 4, 2014 * */ public class MajorityPosTagger implements PosTagger { public MajorityPosTagger(Map<String, String> majorityMap, String generalMajorTag) { super(); this.majorityMap = majorityMap; this.generalMajorTag = generalMajorTag; } @Override
public List<TaggedToken<String,String>> tagSentence(List<String> sentence)
asher-stern/CRF
src/main/java/com/asher_stern/crf/postagging/data/brown/BrownCorpusReader.java
// Path: src/main/java/com/asher_stern/crf/utilities/CrfException.java // public class CrfException extends RuntimeException // { // private static final long serialVersionUID = 5414394233000815286L; // // public CrfException() // { // super(); // } // // public CrfException(String message, Throwable cause, // boolean enableSuppression, boolean writableStackTrace) // { // super(message, cause, enableSuppression, writableStackTrace); // } // // public CrfException(String message, Throwable cause) // { // super(message, cause); // } // // public CrfException(String message) // { // super(message); // } // // public CrfException(Throwable cause) // { // super(cause); // } // // // } // // Path: src/main/java/com/asher_stern/crf/utilities/FileUtilities.java // public class FileUtilities // { // /** // * Returns an array of File, sorted by their name (alphabetically). // * @param files // * @return // */ // public static File[] getSortedByName(File[] files) // { // ArrayList<File> list = new ArrayList<File>(files.length); // for (File file : files) {list.add(file);} // Collections.sort(list,new FilenameComparator()); // // File[] ret = new File[list.size()]; // int index=0; // for (File file : list) // { // ret[index] = file; // ++index; // } // return ret; // } // // /** // * Reads all the contents of the given text file into a string, and returns that string. // * @param file // * @return // */ // public static String readTextFile(File file) // { // StringBuilder sb = new StringBuilder(); // try(BufferedReader reader = new BufferedReader(new FileReader(file))) // { // String line = reader.readLine(); // while (line != null) // { // sb.append(line).append("\n"); // line = reader.readLine(); // } // } // catch (IOException e) // { // throw new CrfException("IO problem.",e); // } // // return sb.toString(); // } // // /** // * A comparator of two files, where the comparison is by the lexicographic ordering of their names. // * // */ // private static class FilenameComparator implements Comparator<File> // { // @Override // public int compare(File o1, File o2) // { // return o1.getName().compareTo(o2.getName()); // } // } // // // // } // // Path: src/main/java/com/asher_stern/crf/utilities/TaggedToken.java // public class TaggedToken<K,G> // { // public TaggedToken(K token, G tag) // { // super(); // this.token = token; // this.tag = tag; // } // // // // public K getToken() // { // return token; // } // public G getTag() // { // return tag; // } // // // // // @Override // public String toString() // { // return "CrfTaggedToken [getToken()=" + getToken() + ", getTag()=" // + getTag() + "]"; // } // // // // // // // @Override // public int hashCode() // { // final int prime = 31; // int result = 1; // result = prime * result + ((tag == null) ? 0 : tag.hashCode()); // result = prime * result + ((token == null) ? 0 : token.hashCode()); // return result; // } // // // // @Override // public boolean equals(Object obj) // { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // TaggedToken<?,?> other = (TaggedToken<?,?>) obj; // if (tag == null) // { // if (other.tag != null) // return false; // } else if (!tag.equals(other.tag)) // return false; // if (token == null) // { // if (other.token != null) // return false; // } else if (!token.equals(other.token)) // return false; // return true; // } // // // // // // // private final K token; // private final G tag; // }
import java.io.BufferedReader; import java.io.File; import java.io.FileFilter; import java.io.FileReader; import java.io.IOException; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import com.asher_stern.crf.utilities.CrfException; import com.asher_stern.crf.utilities.FileUtilities; import com.asher_stern.crf.utilities.TaggedToken;
{ goToNextFile(); } return ret; } private void goToNextFile() { thereIsNext = false; sentencesIterator = null; boolean stop = false; while (!stop) { File nextFile = getNextFile(); if (nextFile!=null) { createSentenceIterator(nextFile); stop = sentencesIterator.hasNext(); } else { sentencesIterator = null; stop = true; } } if (sentencesIterator!=null) {
// Path: src/main/java/com/asher_stern/crf/utilities/CrfException.java // public class CrfException extends RuntimeException // { // private static final long serialVersionUID = 5414394233000815286L; // // public CrfException() // { // super(); // } // // public CrfException(String message, Throwable cause, // boolean enableSuppression, boolean writableStackTrace) // { // super(message, cause, enableSuppression, writableStackTrace); // } // // public CrfException(String message, Throwable cause) // { // super(message, cause); // } // // public CrfException(String message) // { // super(message); // } // // public CrfException(Throwable cause) // { // super(cause); // } // // // } // // Path: src/main/java/com/asher_stern/crf/utilities/FileUtilities.java // public class FileUtilities // { // /** // * Returns an array of File, sorted by their name (alphabetically). // * @param files // * @return // */ // public static File[] getSortedByName(File[] files) // { // ArrayList<File> list = new ArrayList<File>(files.length); // for (File file : files) {list.add(file);} // Collections.sort(list,new FilenameComparator()); // // File[] ret = new File[list.size()]; // int index=0; // for (File file : list) // { // ret[index] = file; // ++index; // } // return ret; // } // // /** // * Reads all the contents of the given text file into a string, and returns that string. // * @param file // * @return // */ // public static String readTextFile(File file) // { // StringBuilder sb = new StringBuilder(); // try(BufferedReader reader = new BufferedReader(new FileReader(file))) // { // String line = reader.readLine(); // while (line != null) // { // sb.append(line).append("\n"); // line = reader.readLine(); // } // } // catch (IOException e) // { // throw new CrfException("IO problem.",e); // } // // return sb.toString(); // } // // /** // * A comparator of two files, where the comparison is by the lexicographic ordering of their names. // * // */ // private static class FilenameComparator implements Comparator<File> // { // @Override // public int compare(File o1, File o2) // { // return o1.getName().compareTo(o2.getName()); // } // } // // // // } // // Path: src/main/java/com/asher_stern/crf/utilities/TaggedToken.java // public class TaggedToken<K,G> // { // public TaggedToken(K token, G tag) // { // super(); // this.token = token; // this.tag = tag; // } // // // // public K getToken() // { // return token; // } // public G getTag() // { // return tag; // } // // // // // @Override // public String toString() // { // return "CrfTaggedToken [getToken()=" + getToken() + ", getTag()=" // + getTag() + "]"; // } // // // // // // // @Override // public int hashCode() // { // final int prime = 31; // int result = 1; // result = prime * result + ((tag == null) ? 0 : tag.hashCode()); // result = prime * result + ((token == null) ? 0 : token.hashCode()); // return result; // } // // // // @Override // public boolean equals(Object obj) // { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // TaggedToken<?,?> other = (TaggedToken<?,?>) obj; // if (tag == null) // { // if (other.tag != null) // return false; // } else if (!tag.equals(other.tag)) // return false; // if (token == null) // { // if (other.token != null) // return false; // } else if (!token.equals(other.token)) // return false; // return true; // } // // // // // // // private final K token; // private final G tag; // } // Path: src/main/java/com/asher_stern/crf/postagging/data/brown/BrownCorpusReader.java import java.io.BufferedReader; import java.io.File; import java.io.FileFilter; import java.io.FileReader; import java.io.IOException; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import com.asher_stern.crf.utilities.CrfException; import com.asher_stern.crf.utilities.FileUtilities; import com.asher_stern.crf.utilities.TaggedToken; { goToNextFile(); } return ret; } private void goToNextFile() { thereIsNext = false; sentencesIterator = null; boolean stop = false; while (!stop) { File nextFile = getNextFile(); if (nextFile!=null) { createSentenceIterator(nextFile); stop = sentencesIterator.hasNext(); } else { sentencesIterator = null; stop = true; } } if (sentencesIterator!=null) {
if (!sentencesIterator.hasNext()) {throw new CrfException("BUG");}
asher-stern/CRF
src/main/java/com/asher_stern/crf/crf/run/CrfFeatureGeneratorFactory.java
// Path: src/main/java/com/asher_stern/crf/utilities/TaggedToken.java // public class TaggedToken<K,G> // { // public TaggedToken(K token, G tag) // { // super(); // this.token = token; // this.tag = tag; // } // // // // public K getToken() // { // return token; // } // public G getTag() // { // return tag; // } // // // // // @Override // public String toString() // { // return "CrfTaggedToken [getToken()=" + getToken() + ", getTag()=" // + getTag() + "]"; // } // // // // // // // @Override // public int hashCode() // { // final int prime = 31; // int result = 1; // result = prime * result + ((tag == null) ? 0 : tag.hashCode()); // result = prime * result + ((token == null) ? 0 : token.hashCode()); // return result; // } // // // // @Override // public boolean equals(Object obj) // { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // TaggedToken<?,?> other = (TaggedToken<?,?>) obj; // if (tag == null) // { // if (other.tag != null) // return false; // } else if (!tag.equals(other.tag)) // return false; // if (token == null) // { // if (other.token != null) // return false; // } else if (!token.equals(other.token)) // return false; // return true; // } // // // // // // // private final K token; // private final G tag; // }
import java.util.List; import java.util.Set; import com.asher_stern.crf.utilities.TaggedToken;
package com.asher_stern.crf.crf.run; /** * A factory which creates a {@link CrfFeatureGenerator}. * * @author Asher Stern * Date: November 2014 * */ public interface CrfFeatureGeneratorFactory<K,G> { /** * Create the {@link CrfFeatureGenerator}. * @param corpus * @param tags * @return */
// Path: src/main/java/com/asher_stern/crf/utilities/TaggedToken.java // public class TaggedToken<K,G> // { // public TaggedToken(K token, G tag) // { // super(); // this.token = token; // this.tag = tag; // } // // // // public K getToken() // { // return token; // } // public G getTag() // { // return tag; // } // // // // // @Override // public String toString() // { // return "CrfTaggedToken [getToken()=" + getToken() + ", getTag()=" // + getTag() + "]"; // } // // // // // // // @Override // public int hashCode() // { // final int prime = 31; // int result = 1; // result = prime * result + ((tag == null) ? 0 : tag.hashCode()); // result = prime * result + ((token == null) ? 0 : token.hashCode()); // return result; // } // // // // @Override // public boolean equals(Object obj) // { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // TaggedToken<?,?> other = (TaggedToken<?,?>) obj; // if (tag == null) // { // if (other.tag != null) // return false; // } else if (!tag.equals(other.tag)) // return false; // if (token == null) // { // if (other.token != null) // return false; // } else if (!token.equals(other.token)) // return false; // return true; // } // // // // // // // private final K token; // private final G tag; // } // Path: src/main/java/com/asher_stern/crf/crf/run/CrfFeatureGeneratorFactory.java import java.util.List; import java.util.Set; import com.asher_stern.crf.utilities.TaggedToken; package com.asher_stern.crf.crf.run; /** * A factory which creates a {@link CrfFeatureGenerator}. * * @author Asher Stern * Date: November 2014 * */ public interface CrfFeatureGeneratorFactory<K,G> { /** * Create the {@link CrfFeatureGenerator}. * @param corpus * @param tags * @return */
public CrfFeatureGenerator<K,G> create(Iterable<? extends List<? extends TaggedToken<K, G> >> corpus, Set<G> tags);