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
prolificinteractive/material-calendarview
library/src/main/java/com/prolificinteractive/materialcalendarview/CalendarPagerView.java
// Path: library/src/main/java/com/prolificinteractive/materialcalendarview/format/DayFormatter.java // public interface DayFormatter { // // /** // * Default format for displaying the day. // */ // String DEFAULT_FORMAT = "d"; // // /** // * Default implementation used by {@linkplain com.prolificinteractive.materialcalendarview.MaterialCalendarView} // */ // DayFormatter DEFAULT = new DateFormatDayFormatter(); // // /** // * Format a given day into a string // * // * @param day the day // * @return a label for the day // */ // @NonNull String format(@NonNull CalendarDay day); // } // // Path: library/src/main/java/com/prolificinteractive/materialcalendarview/format/WeekDayFormatter.java // public interface WeekDayFormatter { // /** // * Convert a given day of the week into a label. // * // * @param dayOfWeek the day of the week as returned by {@linkplain DayOfWeek#getValue()}. // * @return a label for the day of week. // */ // CharSequence format(DayOfWeek dayOfWeek); // // /** // * Default implementation used by {@linkplain com.prolificinteractive.materialcalendarview.MaterialCalendarView} // */ // WeekDayFormatter DEFAULT = new CalendarWeekDayFormatter(); // } // // Path: library/src/main/java/com/prolificinteractive/materialcalendarview/MaterialCalendarView.java // public static boolean showOtherMonths(@ShowOtherDates int showOtherDates) { // return (showOtherDates & SHOW_OTHER_MONTHS) != 0; // }
import android.os.Build; import android.support.annotation.NonNull; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; import android.view.accessibility.AccessibilityEvent; import android.view.accessibility.AccessibilityNodeInfo; import com.prolificinteractive.materialcalendarview.MaterialCalendarView.ShowOtherDates; import com.prolificinteractive.materialcalendarview.format.DayFormatter; import com.prolificinteractive.materialcalendarview.format.WeekDayFormatter; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.threeten.bp.DayOfWeek; import org.threeten.bp.LocalDate; import org.threeten.bp.temporal.TemporalField; import org.threeten.bp.temporal.WeekFields; import static com.prolificinteractive.materialcalendarview.MaterialCalendarView.SHOW_DEFAULTS; import static com.prolificinteractive.materialcalendarview.MaterialCalendarView.showOtherMonths;
public void setDateTextAppearance(int taId) { for (DayView dayView : dayViews) { dayView.setTextAppearance(getContext(), taId); } } public void setShowOtherDates(@ShowOtherDates int showFlags) { this.showOtherDates = showFlags; updateUi(); } public void setSelectionEnabled(boolean selectionEnabled) { for (DayView dayView : dayViews) { dayView.setOnClickListener(selectionEnabled ? this : null); dayView.setClickable(selectionEnabled); } } public void setSelectionColor(int color) { for (DayView dayView : dayViews) { dayView.setSelectionColor(color); } } public void setWeekDayFormatter(WeekDayFormatter formatter) { for (WeekDayView dayView : weekDayViews) { dayView.setWeekDayFormatter(formatter); } }
// Path: library/src/main/java/com/prolificinteractive/materialcalendarview/format/DayFormatter.java // public interface DayFormatter { // // /** // * Default format for displaying the day. // */ // String DEFAULT_FORMAT = "d"; // // /** // * Default implementation used by {@linkplain com.prolificinteractive.materialcalendarview.MaterialCalendarView} // */ // DayFormatter DEFAULT = new DateFormatDayFormatter(); // // /** // * Format a given day into a string // * // * @param day the day // * @return a label for the day // */ // @NonNull String format(@NonNull CalendarDay day); // } // // Path: library/src/main/java/com/prolificinteractive/materialcalendarview/format/WeekDayFormatter.java // public interface WeekDayFormatter { // /** // * Convert a given day of the week into a label. // * // * @param dayOfWeek the day of the week as returned by {@linkplain DayOfWeek#getValue()}. // * @return a label for the day of week. // */ // CharSequence format(DayOfWeek dayOfWeek); // // /** // * Default implementation used by {@linkplain com.prolificinteractive.materialcalendarview.MaterialCalendarView} // */ // WeekDayFormatter DEFAULT = new CalendarWeekDayFormatter(); // } // // Path: library/src/main/java/com/prolificinteractive/materialcalendarview/MaterialCalendarView.java // public static boolean showOtherMonths(@ShowOtherDates int showOtherDates) { // return (showOtherDates & SHOW_OTHER_MONTHS) != 0; // } // Path: library/src/main/java/com/prolificinteractive/materialcalendarview/CalendarPagerView.java import android.os.Build; import android.support.annotation.NonNull; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; import android.view.accessibility.AccessibilityEvent; import android.view.accessibility.AccessibilityNodeInfo; import com.prolificinteractive.materialcalendarview.MaterialCalendarView.ShowOtherDates; import com.prolificinteractive.materialcalendarview.format.DayFormatter; import com.prolificinteractive.materialcalendarview.format.WeekDayFormatter; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.threeten.bp.DayOfWeek; import org.threeten.bp.LocalDate; import org.threeten.bp.temporal.TemporalField; import org.threeten.bp.temporal.WeekFields; import static com.prolificinteractive.materialcalendarview.MaterialCalendarView.SHOW_DEFAULTS; import static com.prolificinteractive.materialcalendarview.MaterialCalendarView.showOtherMonths; public void setDateTextAppearance(int taId) { for (DayView dayView : dayViews) { dayView.setTextAppearance(getContext(), taId); } } public void setShowOtherDates(@ShowOtherDates int showFlags) { this.showOtherDates = showFlags; updateUi(); } public void setSelectionEnabled(boolean selectionEnabled) { for (DayView dayView : dayViews) { dayView.setOnClickListener(selectionEnabled ? this : null); dayView.setClickable(selectionEnabled); } } public void setSelectionColor(int color) { for (DayView dayView : dayViews) { dayView.setSelectionColor(color); } } public void setWeekDayFormatter(WeekDayFormatter formatter) { for (WeekDayView dayView : weekDayViews) { dayView.setWeekDayFormatter(formatter); } }
public void setDayFormatter(DayFormatter formatter) {
prolificinteractive/material-calendarview
library/src/main/java/com/prolificinteractive/materialcalendarview/format/TitleFormatter.java
// Path: library/src/main/java/com/prolificinteractive/materialcalendarview/CalendarDay.java // public final class CalendarDay implements Parcelable { // // /** // * Everything is based on this variable for {@link CalendarDay}. // */ // @NonNull private final LocalDate date; // // /** // * @param year new instance's year // * @param month new instance's month as defined by {@linkplain java.util.Calendar} // * @param day new instance's day of month // */ // private CalendarDay(final int year, final int month, final int day) { // date = LocalDate.of(year, month, day); // } // // /** // * @param date {@link LocalDate} instance // */ // private CalendarDay(@NonNull final LocalDate date) { // this.date = date; // } // // /** // * Get a new instance set to today // * // * @return CalendarDay set to today's date // */ // @NonNull public static CalendarDay today() { // return from(LocalDate.now()); // } // // /** // * Get a new instance set to the specified day // * // * @param year new instance's year // * @param month new instance's month as defined by {@linkplain java.util.Calendar} // * @param day new instance's day of month // * @return CalendarDay set to the specified date // */ // @NonNull public static CalendarDay from(int year, int month, int day) { // return new CalendarDay(year, month, day); // } // // /** // * Get a new instance set to the specified day // * // * @param date {@linkplain LocalDate} to pull date information from. Passing null will return null // * @return CalendarDay set to the specified date // */ // public static CalendarDay from(@Nullable LocalDate date) { // if (date == null) { // return null; // } // return new CalendarDay(date); // } // // /** // * Get the year // * // * @return the year for this day // */ // public int getYear() { // return date.getYear(); // } // // /** // * Get the month, represented by values from {@linkplain LocalDate} // * // * @return the month of the year as defined by {@linkplain LocalDate} // */ // public int getMonth() { // return date.getMonthValue(); // } // // /** // * Get the day // * // * @return the day of the month for this day // */ // public int getDay() { // return date.getDayOfMonth(); // } // // /** // * Get this day as a {@linkplain LocalDate} // * // * @return a date with this days information // */ // @NonNull public LocalDate getDate() { // return date; // } // // /** // * Determine if this day is within a specified range // * // * @param minDate the earliest day, may be null // * @param maxDate the latest day, may be null // * @return true if the between (inclusive) the min and max dates. // */ // public boolean isInRange(@Nullable CalendarDay minDate, @Nullable CalendarDay maxDate) { // return !(minDate != null && minDate.isAfter(this)) && // !(maxDate != null && maxDate.isBefore(this)); // } // // /** // * Determine if this day is before the given instance // * // * @param other the other day to test // * @return true if this is before other, false if equal or after // */ // public boolean isBefore(@NonNull final CalendarDay other) { // return date.isBefore(other.getDate()); // } // // /** // * Determine if this day is after the given instance // * // * @param other the other day to test // * @return true if this is after other, false if equal or before // */ // public boolean isAfter(@NonNull final CalendarDay other) { // return date.isAfter(other.getDate()); // } // // @Override public boolean equals(Object o) { // return o instanceof CalendarDay && date.equals(((CalendarDay) o).getDate()); // } // // @Override // public int hashCode() { // return hashCode(date.getYear(), date.getMonthValue(), date.getDayOfMonth()); // } // // private static int hashCode(int year, int month, int day) { // //Should produce hashes like "20150401" // return (year * 10000) + (month * 100) + day; // } // // @Override // public String toString() { // return "CalendarDay{" + date.getYear() + "-" + date.getMonthValue() + "-" // + date.getDayOfMonth() + "}"; // } // // /* // * Parcelable Stuff // */ // // public CalendarDay(Parcel in) { // this(in.readInt(), in.readInt(), in.readInt()); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(date.getYear()); // dest.writeInt(date.getMonthValue()); // dest.writeInt(date.getDayOfMonth()); // } // // public static final Creator<CalendarDay> CREATOR = new Creator<CalendarDay>() { // public CalendarDay createFromParcel(Parcel in) { // return new CalendarDay(in); // } // // public CalendarDay[] newArray(int size) { // return new CalendarDay[size]; // } // }; // }
import com.prolificinteractive.materialcalendarview.CalendarDay;
package com.prolificinteractive.materialcalendarview.format; /** * Used to format a {@linkplain com.prolificinteractive.materialcalendarview.CalendarDay} to a string for the month/year title */ public interface TitleFormatter { String DEFAULT_FORMAT = "LLLL yyyy"; TitleFormatter DEFAULT = new DateFormatTitleFormatter(); /** * Converts the supplied day to a suitable month/year title * * @param day the day containing relevant month and year information * @return a label to display for the given month/year */
// Path: library/src/main/java/com/prolificinteractive/materialcalendarview/CalendarDay.java // public final class CalendarDay implements Parcelable { // // /** // * Everything is based on this variable for {@link CalendarDay}. // */ // @NonNull private final LocalDate date; // // /** // * @param year new instance's year // * @param month new instance's month as defined by {@linkplain java.util.Calendar} // * @param day new instance's day of month // */ // private CalendarDay(final int year, final int month, final int day) { // date = LocalDate.of(year, month, day); // } // // /** // * @param date {@link LocalDate} instance // */ // private CalendarDay(@NonNull final LocalDate date) { // this.date = date; // } // // /** // * Get a new instance set to today // * // * @return CalendarDay set to today's date // */ // @NonNull public static CalendarDay today() { // return from(LocalDate.now()); // } // // /** // * Get a new instance set to the specified day // * // * @param year new instance's year // * @param month new instance's month as defined by {@linkplain java.util.Calendar} // * @param day new instance's day of month // * @return CalendarDay set to the specified date // */ // @NonNull public static CalendarDay from(int year, int month, int day) { // return new CalendarDay(year, month, day); // } // // /** // * Get a new instance set to the specified day // * // * @param date {@linkplain LocalDate} to pull date information from. Passing null will return null // * @return CalendarDay set to the specified date // */ // public static CalendarDay from(@Nullable LocalDate date) { // if (date == null) { // return null; // } // return new CalendarDay(date); // } // // /** // * Get the year // * // * @return the year for this day // */ // public int getYear() { // return date.getYear(); // } // // /** // * Get the month, represented by values from {@linkplain LocalDate} // * // * @return the month of the year as defined by {@linkplain LocalDate} // */ // public int getMonth() { // return date.getMonthValue(); // } // // /** // * Get the day // * // * @return the day of the month for this day // */ // public int getDay() { // return date.getDayOfMonth(); // } // // /** // * Get this day as a {@linkplain LocalDate} // * // * @return a date with this days information // */ // @NonNull public LocalDate getDate() { // return date; // } // // /** // * Determine if this day is within a specified range // * // * @param minDate the earliest day, may be null // * @param maxDate the latest day, may be null // * @return true if the between (inclusive) the min and max dates. // */ // public boolean isInRange(@Nullable CalendarDay minDate, @Nullable CalendarDay maxDate) { // return !(minDate != null && minDate.isAfter(this)) && // !(maxDate != null && maxDate.isBefore(this)); // } // // /** // * Determine if this day is before the given instance // * // * @param other the other day to test // * @return true if this is before other, false if equal or after // */ // public boolean isBefore(@NonNull final CalendarDay other) { // return date.isBefore(other.getDate()); // } // // /** // * Determine if this day is after the given instance // * // * @param other the other day to test // * @return true if this is after other, false if equal or before // */ // public boolean isAfter(@NonNull final CalendarDay other) { // return date.isAfter(other.getDate()); // } // // @Override public boolean equals(Object o) { // return o instanceof CalendarDay && date.equals(((CalendarDay) o).getDate()); // } // // @Override // public int hashCode() { // return hashCode(date.getYear(), date.getMonthValue(), date.getDayOfMonth()); // } // // private static int hashCode(int year, int month, int day) { // //Should produce hashes like "20150401" // return (year * 10000) + (month * 100) + day; // } // // @Override // public String toString() { // return "CalendarDay{" + date.getYear() + "-" + date.getMonthValue() + "-" // + date.getDayOfMonth() + "}"; // } // // /* // * Parcelable Stuff // */ // // public CalendarDay(Parcel in) { // this(in.readInt(), in.readInt(), in.readInt()); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(date.getYear()); // dest.writeInt(date.getMonthValue()); // dest.writeInt(date.getDayOfMonth()); // } // // public static final Creator<CalendarDay> CREATOR = new Creator<CalendarDay>() { // public CalendarDay createFromParcel(Parcel in) { // return new CalendarDay(in); // } // // public CalendarDay[] newArray(int size) { // return new CalendarDay[size]; // } // }; // } // Path: library/src/main/java/com/prolificinteractive/materialcalendarview/format/TitleFormatter.java import com.prolificinteractive.materialcalendarview.CalendarDay; package com.prolificinteractive.materialcalendarview.format; /** * Used to format a {@linkplain com.prolificinteractive.materialcalendarview.CalendarDay} to a string for the month/year title */ public interface TitleFormatter { String DEFAULT_FORMAT = "LLLL yyyy"; TitleFormatter DEFAULT = new DateFormatTitleFormatter(); /** * Converts the supplied day to a suitable month/year title * * @param day the day containing relevant month and year information * @return a label to display for the given month/year */
CharSequence format(CalendarDay day);
prolificinteractive/material-calendarview
library/src/main/java/com/prolificinteractive/materialcalendarview/DayView.java
// Path: library/src/main/java/com/prolificinteractive/materialcalendarview/format/DayFormatter.java // public interface DayFormatter { // // /** // * Default format for displaying the day. // */ // String DEFAULT_FORMAT = "d"; // // /** // * Default implementation used by {@linkplain com.prolificinteractive.materialcalendarview.MaterialCalendarView} // */ // DayFormatter DEFAULT = new DateFormatDayFormatter(); // // /** // * Format a given day into a string // * // * @param day the day // * @return a label for the day // */ // @NonNull String format(@NonNull CalendarDay day); // } // // Path: library/src/main/java/com/prolificinteractive/materialcalendarview/MaterialCalendarView.java // public static boolean showDecoratedDisabled(@ShowOtherDates int showOtherDates) { // return (showOtherDates & SHOW_DECORATED_DISABLED) != 0; // } // // Path: library/src/main/java/com/prolificinteractive/materialcalendarview/MaterialCalendarView.java // public static boolean showOtherMonths(@ShowOtherDates int showOtherDates) { // return (showOtherDates & SHOW_OTHER_MONTHS) != 0; // } // // Path: library/src/main/java/com/prolificinteractive/materialcalendarview/MaterialCalendarView.java // public static boolean showOutOfRange(@ShowOtherDates int showOtherDates) { // return (showOtherDates & SHOW_OUT_OF_RANGE) != 0; // }
import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.content.Context; import android.content.res.ColorStateList; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.graphics.drawable.RippleDrawable; import android.graphics.drawable.ShapeDrawable; import android.graphics.drawable.StateListDrawable; import android.graphics.drawable.shapes.OvalShape; import android.os.Build; import android.support.annotation.NonNull; import android.support.v7.widget.AppCompatCheckedTextView; import android.text.SpannableString; import android.text.Spanned; import android.view.Gravity; import android.view.View; import com.prolificinteractive.materialcalendarview.MaterialCalendarView.ShowOtherDates; import com.prolificinteractive.materialcalendarview.format.DayFormatter; import java.util.List; import static com.prolificinteractive.materialcalendarview.MaterialCalendarView.showDecoratedDisabled; import static com.prolificinteractive.materialcalendarview.MaterialCalendarView.showOtherMonths; import static com.prolificinteractive.materialcalendarview.MaterialCalendarView.showOutOfRange;
package com.prolificinteractive.materialcalendarview; /** * Display one day of a {@linkplain MaterialCalendarView} */ @SuppressLint("ViewConstructor") class DayView extends AppCompatCheckedTextView { private CalendarDay date; private int selectionColor = Color.GRAY; private final int fadeTime; private Drawable customBackground = null; private Drawable selectionDrawable; private Drawable mCircleDrawable;
// Path: library/src/main/java/com/prolificinteractive/materialcalendarview/format/DayFormatter.java // public interface DayFormatter { // // /** // * Default format for displaying the day. // */ // String DEFAULT_FORMAT = "d"; // // /** // * Default implementation used by {@linkplain com.prolificinteractive.materialcalendarview.MaterialCalendarView} // */ // DayFormatter DEFAULT = new DateFormatDayFormatter(); // // /** // * Format a given day into a string // * // * @param day the day // * @return a label for the day // */ // @NonNull String format(@NonNull CalendarDay day); // } // // Path: library/src/main/java/com/prolificinteractive/materialcalendarview/MaterialCalendarView.java // public static boolean showDecoratedDisabled(@ShowOtherDates int showOtherDates) { // return (showOtherDates & SHOW_DECORATED_DISABLED) != 0; // } // // Path: library/src/main/java/com/prolificinteractive/materialcalendarview/MaterialCalendarView.java // public static boolean showOtherMonths(@ShowOtherDates int showOtherDates) { // return (showOtherDates & SHOW_OTHER_MONTHS) != 0; // } // // Path: library/src/main/java/com/prolificinteractive/materialcalendarview/MaterialCalendarView.java // public static boolean showOutOfRange(@ShowOtherDates int showOtherDates) { // return (showOtherDates & SHOW_OUT_OF_RANGE) != 0; // } // Path: library/src/main/java/com/prolificinteractive/materialcalendarview/DayView.java import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.content.Context; import android.content.res.ColorStateList; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.graphics.drawable.RippleDrawable; import android.graphics.drawable.ShapeDrawable; import android.graphics.drawable.StateListDrawable; import android.graphics.drawable.shapes.OvalShape; import android.os.Build; import android.support.annotation.NonNull; import android.support.v7.widget.AppCompatCheckedTextView; import android.text.SpannableString; import android.text.Spanned; import android.view.Gravity; import android.view.View; import com.prolificinteractive.materialcalendarview.MaterialCalendarView.ShowOtherDates; import com.prolificinteractive.materialcalendarview.format.DayFormatter; import java.util.List; import static com.prolificinteractive.materialcalendarview.MaterialCalendarView.showDecoratedDisabled; import static com.prolificinteractive.materialcalendarview.MaterialCalendarView.showOtherMonths; import static com.prolificinteractive.materialcalendarview.MaterialCalendarView.showOutOfRange; package com.prolificinteractive.materialcalendarview; /** * Display one day of a {@linkplain MaterialCalendarView} */ @SuppressLint("ViewConstructor") class DayView extends AppCompatCheckedTextView { private CalendarDay date; private int selectionColor = Color.GRAY; private final int fadeTime; private Drawable customBackground = null; private Drawable selectionDrawable; private Drawable mCircleDrawable;
private DayFormatter formatter = DayFormatter.DEFAULT;
prolificinteractive/material-calendarview
library/src/main/java/com/prolificinteractive/materialcalendarview/DayView.java
// Path: library/src/main/java/com/prolificinteractive/materialcalendarview/format/DayFormatter.java // public interface DayFormatter { // // /** // * Default format for displaying the day. // */ // String DEFAULT_FORMAT = "d"; // // /** // * Default implementation used by {@linkplain com.prolificinteractive.materialcalendarview.MaterialCalendarView} // */ // DayFormatter DEFAULT = new DateFormatDayFormatter(); // // /** // * Format a given day into a string // * // * @param day the day // * @return a label for the day // */ // @NonNull String format(@NonNull CalendarDay day); // } // // Path: library/src/main/java/com/prolificinteractive/materialcalendarview/MaterialCalendarView.java // public static boolean showDecoratedDisabled(@ShowOtherDates int showOtherDates) { // return (showOtherDates & SHOW_DECORATED_DISABLED) != 0; // } // // Path: library/src/main/java/com/prolificinteractive/materialcalendarview/MaterialCalendarView.java // public static boolean showOtherMonths(@ShowOtherDates int showOtherDates) { // return (showOtherDates & SHOW_OTHER_MONTHS) != 0; // } // // Path: library/src/main/java/com/prolificinteractive/materialcalendarview/MaterialCalendarView.java // public static boolean showOutOfRange(@ShowOtherDates int showOtherDates) { // return (showOtherDates & SHOW_OUT_OF_RANGE) != 0; // }
import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.content.Context; import android.content.res.ColorStateList; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.graphics.drawable.RippleDrawable; import android.graphics.drawable.ShapeDrawable; import android.graphics.drawable.StateListDrawable; import android.graphics.drawable.shapes.OvalShape; import android.os.Build; import android.support.annotation.NonNull; import android.support.v7.widget.AppCompatCheckedTextView; import android.text.SpannableString; import android.text.Spanned; import android.view.Gravity; import android.view.View; import com.prolificinteractive.materialcalendarview.MaterialCalendarView.ShowOtherDates; import com.prolificinteractive.materialcalendarview.format.DayFormatter; import java.util.List; import static com.prolificinteractive.materialcalendarview.MaterialCalendarView.showDecoratedDisabled; import static com.prolificinteractive.materialcalendarview.MaterialCalendarView.showOtherMonths; import static com.prolificinteractive.materialcalendarview.MaterialCalendarView.showOutOfRange;
*/ public void setSelectionDrawable(Drawable drawable) { if (drawable == null) { this.selectionDrawable = null; } else { this.selectionDrawable = drawable.getConstantState().newDrawable(getResources()); } regenerateBackground(); } /** * @param drawable background to draw behind everything else */ public void setCustomBackground(Drawable drawable) { if (drawable == null) { this.customBackground = null; } else { this.customBackground = drawable.getConstantState().newDrawable(getResources()); } invalidate(); } public CalendarDay getDate() { return date; } private void setEnabled() { boolean enabled = isInMonth && isInRange && !isDecoratedDisabled; super.setEnabled(isInRange && !isDecoratedDisabled);
// Path: library/src/main/java/com/prolificinteractive/materialcalendarview/format/DayFormatter.java // public interface DayFormatter { // // /** // * Default format for displaying the day. // */ // String DEFAULT_FORMAT = "d"; // // /** // * Default implementation used by {@linkplain com.prolificinteractive.materialcalendarview.MaterialCalendarView} // */ // DayFormatter DEFAULT = new DateFormatDayFormatter(); // // /** // * Format a given day into a string // * // * @param day the day // * @return a label for the day // */ // @NonNull String format(@NonNull CalendarDay day); // } // // Path: library/src/main/java/com/prolificinteractive/materialcalendarview/MaterialCalendarView.java // public static boolean showDecoratedDisabled(@ShowOtherDates int showOtherDates) { // return (showOtherDates & SHOW_DECORATED_DISABLED) != 0; // } // // Path: library/src/main/java/com/prolificinteractive/materialcalendarview/MaterialCalendarView.java // public static boolean showOtherMonths(@ShowOtherDates int showOtherDates) { // return (showOtherDates & SHOW_OTHER_MONTHS) != 0; // } // // Path: library/src/main/java/com/prolificinteractive/materialcalendarview/MaterialCalendarView.java // public static boolean showOutOfRange(@ShowOtherDates int showOtherDates) { // return (showOtherDates & SHOW_OUT_OF_RANGE) != 0; // } // Path: library/src/main/java/com/prolificinteractive/materialcalendarview/DayView.java import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.content.Context; import android.content.res.ColorStateList; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.graphics.drawable.RippleDrawable; import android.graphics.drawable.ShapeDrawable; import android.graphics.drawable.StateListDrawable; import android.graphics.drawable.shapes.OvalShape; import android.os.Build; import android.support.annotation.NonNull; import android.support.v7.widget.AppCompatCheckedTextView; import android.text.SpannableString; import android.text.Spanned; import android.view.Gravity; import android.view.View; import com.prolificinteractive.materialcalendarview.MaterialCalendarView.ShowOtherDates; import com.prolificinteractive.materialcalendarview.format.DayFormatter; import java.util.List; import static com.prolificinteractive.materialcalendarview.MaterialCalendarView.showDecoratedDisabled; import static com.prolificinteractive.materialcalendarview.MaterialCalendarView.showOtherMonths; import static com.prolificinteractive.materialcalendarview.MaterialCalendarView.showOutOfRange; */ public void setSelectionDrawable(Drawable drawable) { if (drawable == null) { this.selectionDrawable = null; } else { this.selectionDrawable = drawable.getConstantState().newDrawable(getResources()); } regenerateBackground(); } /** * @param drawable background to draw behind everything else */ public void setCustomBackground(Drawable drawable) { if (drawable == null) { this.customBackground = null; } else { this.customBackground = drawable.getConstantState().newDrawable(getResources()); } invalidate(); } public CalendarDay getDate() { return date; } private void setEnabled() { boolean enabled = isInMonth && isInRange && !isDecoratedDisabled; super.setEnabled(isInRange && !isDecoratedDisabled);
boolean showOtherMonths = showOtherMonths(showOtherDates);
prolificinteractive/material-calendarview
library/src/main/java/com/prolificinteractive/materialcalendarview/DayView.java
// Path: library/src/main/java/com/prolificinteractive/materialcalendarview/format/DayFormatter.java // public interface DayFormatter { // // /** // * Default format for displaying the day. // */ // String DEFAULT_FORMAT = "d"; // // /** // * Default implementation used by {@linkplain com.prolificinteractive.materialcalendarview.MaterialCalendarView} // */ // DayFormatter DEFAULT = new DateFormatDayFormatter(); // // /** // * Format a given day into a string // * // * @param day the day // * @return a label for the day // */ // @NonNull String format(@NonNull CalendarDay day); // } // // Path: library/src/main/java/com/prolificinteractive/materialcalendarview/MaterialCalendarView.java // public static boolean showDecoratedDisabled(@ShowOtherDates int showOtherDates) { // return (showOtherDates & SHOW_DECORATED_DISABLED) != 0; // } // // Path: library/src/main/java/com/prolificinteractive/materialcalendarview/MaterialCalendarView.java // public static boolean showOtherMonths(@ShowOtherDates int showOtherDates) { // return (showOtherDates & SHOW_OTHER_MONTHS) != 0; // } // // Path: library/src/main/java/com/prolificinteractive/materialcalendarview/MaterialCalendarView.java // public static boolean showOutOfRange(@ShowOtherDates int showOtherDates) { // return (showOtherDates & SHOW_OUT_OF_RANGE) != 0; // }
import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.content.Context; import android.content.res.ColorStateList; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.graphics.drawable.RippleDrawable; import android.graphics.drawable.ShapeDrawable; import android.graphics.drawable.StateListDrawable; import android.graphics.drawable.shapes.OvalShape; import android.os.Build; import android.support.annotation.NonNull; import android.support.v7.widget.AppCompatCheckedTextView; import android.text.SpannableString; import android.text.Spanned; import android.view.Gravity; import android.view.View; import com.prolificinteractive.materialcalendarview.MaterialCalendarView.ShowOtherDates; import com.prolificinteractive.materialcalendarview.format.DayFormatter; import java.util.List; import static com.prolificinteractive.materialcalendarview.MaterialCalendarView.showDecoratedDisabled; import static com.prolificinteractive.materialcalendarview.MaterialCalendarView.showOtherMonths; import static com.prolificinteractive.materialcalendarview.MaterialCalendarView.showOutOfRange;
public void setSelectionDrawable(Drawable drawable) { if (drawable == null) { this.selectionDrawable = null; } else { this.selectionDrawable = drawable.getConstantState().newDrawable(getResources()); } regenerateBackground(); } /** * @param drawable background to draw behind everything else */ public void setCustomBackground(Drawable drawable) { if (drawable == null) { this.customBackground = null; } else { this.customBackground = drawable.getConstantState().newDrawable(getResources()); } invalidate(); } public CalendarDay getDate() { return date; } private void setEnabled() { boolean enabled = isInMonth && isInRange && !isDecoratedDisabled; super.setEnabled(isInRange && !isDecoratedDisabled); boolean showOtherMonths = showOtherMonths(showOtherDates);
// Path: library/src/main/java/com/prolificinteractive/materialcalendarview/format/DayFormatter.java // public interface DayFormatter { // // /** // * Default format for displaying the day. // */ // String DEFAULT_FORMAT = "d"; // // /** // * Default implementation used by {@linkplain com.prolificinteractive.materialcalendarview.MaterialCalendarView} // */ // DayFormatter DEFAULT = new DateFormatDayFormatter(); // // /** // * Format a given day into a string // * // * @param day the day // * @return a label for the day // */ // @NonNull String format(@NonNull CalendarDay day); // } // // Path: library/src/main/java/com/prolificinteractive/materialcalendarview/MaterialCalendarView.java // public static boolean showDecoratedDisabled(@ShowOtherDates int showOtherDates) { // return (showOtherDates & SHOW_DECORATED_DISABLED) != 0; // } // // Path: library/src/main/java/com/prolificinteractive/materialcalendarview/MaterialCalendarView.java // public static boolean showOtherMonths(@ShowOtherDates int showOtherDates) { // return (showOtherDates & SHOW_OTHER_MONTHS) != 0; // } // // Path: library/src/main/java/com/prolificinteractive/materialcalendarview/MaterialCalendarView.java // public static boolean showOutOfRange(@ShowOtherDates int showOtherDates) { // return (showOtherDates & SHOW_OUT_OF_RANGE) != 0; // } // Path: library/src/main/java/com/prolificinteractive/materialcalendarview/DayView.java import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.content.Context; import android.content.res.ColorStateList; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.graphics.drawable.RippleDrawable; import android.graphics.drawable.ShapeDrawable; import android.graphics.drawable.StateListDrawable; import android.graphics.drawable.shapes.OvalShape; import android.os.Build; import android.support.annotation.NonNull; import android.support.v7.widget.AppCompatCheckedTextView; import android.text.SpannableString; import android.text.Spanned; import android.view.Gravity; import android.view.View; import com.prolificinteractive.materialcalendarview.MaterialCalendarView.ShowOtherDates; import com.prolificinteractive.materialcalendarview.format.DayFormatter; import java.util.List; import static com.prolificinteractive.materialcalendarview.MaterialCalendarView.showDecoratedDisabled; import static com.prolificinteractive.materialcalendarview.MaterialCalendarView.showOtherMonths; import static com.prolificinteractive.materialcalendarview.MaterialCalendarView.showOutOfRange; public void setSelectionDrawable(Drawable drawable) { if (drawable == null) { this.selectionDrawable = null; } else { this.selectionDrawable = drawable.getConstantState().newDrawable(getResources()); } regenerateBackground(); } /** * @param drawable background to draw behind everything else */ public void setCustomBackground(Drawable drawable) { if (drawable == null) { this.customBackground = null; } else { this.customBackground = drawable.getConstantState().newDrawable(getResources()); } invalidate(); } public CalendarDay getDate() { return date; } private void setEnabled() { boolean enabled = isInMonth && isInRange && !isDecoratedDisabled; super.setEnabled(isInRange && !isDecoratedDisabled); boolean showOtherMonths = showOtherMonths(showOtherDates);
boolean showOutOfRange = showOutOfRange(showOtherDates) || showOtherMonths;
prolificinteractive/material-calendarview
library/src/main/java/com/prolificinteractive/materialcalendarview/DayView.java
// Path: library/src/main/java/com/prolificinteractive/materialcalendarview/format/DayFormatter.java // public interface DayFormatter { // // /** // * Default format for displaying the day. // */ // String DEFAULT_FORMAT = "d"; // // /** // * Default implementation used by {@linkplain com.prolificinteractive.materialcalendarview.MaterialCalendarView} // */ // DayFormatter DEFAULT = new DateFormatDayFormatter(); // // /** // * Format a given day into a string // * // * @param day the day // * @return a label for the day // */ // @NonNull String format(@NonNull CalendarDay day); // } // // Path: library/src/main/java/com/prolificinteractive/materialcalendarview/MaterialCalendarView.java // public static boolean showDecoratedDisabled(@ShowOtherDates int showOtherDates) { // return (showOtherDates & SHOW_DECORATED_DISABLED) != 0; // } // // Path: library/src/main/java/com/prolificinteractive/materialcalendarview/MaterialCalendarView.java // public static boolean showOtherMonths(@ShowOtherDates int showOtherDates) { // return (showOtherDates & SHOW_OTHER_MONTHS) != 0; // } // // Path: library/src/main/java/com/prolificinteractive/materialcalendarview/MaterialCalendarView.java // public static boolean showOutOfRange(@ShowOtherDates int showOtherDates) { // return (showOtherDates & SHOW_OUT_OF_RANGE) != 0; // }
import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.content.Context; import android.content.res.ColorStateList; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.graphics.drawable.RippleDrawable; import android.graphics.drawable.ShapeDrawable; import android.graphics.drawable.StateListDrawable; import android.graphics.drawable.shapes.OvalShape; import android.os.Build; import android.support.annotation.NonNull; import android.support.v7.widget.AppCompatCheckedTextView; import android.text.SpannableString; import android.text.Spanned; import android.view.Gravity; import android.view.View; import com.prolificinteractive.materialcalendarview.MaterialCalendarView.ShowOtherDates; import com.prolificinteractive.materialcalendarview.format.DayFormatter; import java.util.List; import static com.prolificinteractive.materialcalendarview.MaterialCalendarView.showDecoratedDisabled; import static com.prolificinteractive.materialcalendarview.MaterialCalendarView.showOtherMonths; import static com.prolificinteractive.materialcalendarview.MaterialCalendarView.showOutOfRange;
if (drawable == null) { this.selectionDrawable = null; } else { this.selectionDrawable = drawable.getConstantState().newDrawable(getResources()); } regenerateBackground(); } /** * @param drawable background to draw behind everything else */ public void setCustomBackground(Drawable drawable) { if (drawable == null) { this.customBackground = null; } else { this.customBackground = drawable.getConstantState().newDrawable(getResources()); } invalidate(); } public CalendarDay getDate() { return date; } private void setEnabled() { boolean enabled = isInMonth && isInRange && !isDecoratedDisabled; super.setEnabled(isInRange && !isDecoratedDisabled); boolean showOtherMonths = showOtherMonths(showOtherDates); boolean showOutOfRange = showOutOfRange(showOtherDates) || showOtherMonths;
// Path: library/src/main/java/com/prolificinteractive/materialcalendarview/format/DayFormatter.java // public interface DayFormatter { // // /** // * Default format for displaying the day. // */ // String DEFAULT_FORMAT = "d"; // // /** // * Default implementation used by {@linkplain com.prolificinteractive.materialcalendarview.MaterialCalendarView} // */ // DayFormatter DEFAULT = new DateFormatDayFormatter(); // // /** // * Format a given day into a string // * // * @param day the day // * @return a label for the day // */ // @NonNull String format(@NonNull CalendarDay day); // } // // Path: library/src/main/java/com/prolificinteractive/materialcalendarview/MaterialCalendarView.java // public static boolean showDecoratedDisabled(@ShowOtherDates int showOtherDates) { // return (showOtherDates & SHOW_DECORATED_DISABLED) != 0; // } // // Path: library/src/main/java/com/prolificinteractive/materialcalendarview/MaterialCalendarView.java // public static boolean showOtherMonths(@ShowOtherDates int showOtherDates) { // return (showOtherDates & SHOW_OTHER_MONTHS) != 0; // } // // Path: library/src/main/java/com/prolificinteractive/materialcalendarview/MaterialCalendarView.java // public static boolean showOutOfRange(@ShowOtherDates int showOtherDates) { // return (showOtherDates & SHOW_OUT_OF_RANGE) != 0; // } // Path: library/src/main/java/com/prolificinteractive/materialcalendarview/DayView.java import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.content.Context; import android.content.res.ColorStateList; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.graphics.drawable.RippleDrawable; import android.graphics.drawable.ShapeDrawable; import android.graphics.drawable.StateListDrawable; import android.graphics.drawable.shapes.OvalShape; import android.os.Build; import android.support.annotation.NonNull; import android.support.v7.widget.AppCompatCheckedTextView; import android.text.SpannableString; import android.text.Spanned; import android.view.Gravity; import android.view.View; import com.prolificinteractive.materialcalendarview.MaterialCalendarView.ShowOtherDates; import com.prolificinteractive.materialcalendarview.format.DayFormatter; import java.util.List; import static com.prolificinteractive.materialcalendarview.MaterialCalendarView.showDecoratedDisabled; import static com.prolificinteractive.materialcalendarview.MaterialCalendarView.showOtherMonths; import static com.prolificinteractive.materialcalendarview.MaterialCalendarView.showOutOfRange; if (drawable == null) { this.selectionDrawable = null; } else { this.selectionDrawable = drawable.getConstantState().newDrawable(getResources()); } regenerateBackground(); } /** * @param drawable background to draw behind everything else */ public void setCustomBackground(Drawable drawable) { if (drawable == null) { this.customBackground = null; } else { this.customBackground = drawable.getConstantState().newDrawable(getResources()); } invalidate(); } public CalendarDay getDate() { return date; } private void setEnabled() { boolean enabled = isInMonth && isInRange && !isDecoratedDisabled; super.setEnabled(isInRange && !isDecoratedDisabled); boolean showOtherMonths = showOtherMonths(showOtherDates); boolean showOutOfRange = showOutOfRange(showOtherDates) || showOtherMonths;
boolean showDecoratedDisabled = showDecoratedDisabled(showOtherDates);
prolificinteractive/material-calendarview
library/src/main/java/com/prolificinteractive/materialcalendarview/CalendarPagerAdapter.java
// Path: library/src/main/java/com/prolificinteractive/materialcalendarview/format/DayFormatter.java // public interface DayFormatter { // // /** // * Default format for displaying the day. // */ // String DEFAULT_FORMAT = "d"; // // /** // * Default implementation used by {@linkplain com.prolificinteractive.materialcalendarview.MaterialCalendarView} // */ // DayFormatter DEFAULT = new DateFormatDayFormatter(); // // /** // * Format a given day into a string // * // * @param day the day // * @return a label for the day // */ // @NonNull String format(@NonNull CalendarDay day); // } // // Path: library/src/main/java/com/prolificinteractive/materialcalendarview/format/TitleFormatter.java // public interface TitleFormatter { // // String DEFAULT_FORMAT = "LLLL yyyy"; // // TitleFormatter DEFAULT = new DateFormatTitleFormatter(); // // /** // * Converts the supplied day to a suitable month/year title // * // * @param day the day containing relevant month and year information // * @return a label to display for the given month/year // */ // CharSequence format(CalendarDay day); // } // // Path: library/src/main/java/com/prolificinteractive/materialcalendarview/format/WeekDayFormatter.java // public interface WeekDayFormatter { // /** // * Convert a given day of the week into a label. // * // * @param dayOfWeek the day of the week as returned by {@linkplain DayOfWeek#getValue()}. // * @return a label for the day of week. // */ // CharSequence format(DayOfWeek dayOfWeek); // // /** // * Default implementation used by {@linkplain com.prolificinteractive.materialcalendarview.MaterialCalendarView} // */ // WeekDayFormatter DEFAULT = new CalendarWeekDayFormatter(); // }
import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.view.PagerAdapter; import android.view.View; import android.view.ViewGroup; import com.prolificinteractive.materialcalendarview.MaterialCalendarView.ShowOtherDates; import com.prolificinteractive.materialcalendarview.format.DayFormatter; import com.prolificinteractive.materialcalendarview.format.TitleFormatter; import com.prolificinteractive.materialcalendarview.format.WeekDayFormatter; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.threeten.bp.LocalDate;
package com.prolificinteractive.materialcalendarview; /** * Pager adapter backing the calendar view */ abstract class CalendarPagerAdapter<V extends CalendarPagerView> extends PagerAdapter { private final ArrayDeque<V> currentViews; protected final MaterialCalendarView mcv; private final CalendarDay today;
// Path: library/src/main/java/com/prolificinteractive/materialcalendarview/format/DayFormatter.java // public interface DayFormatter { // // /** // * Default format for displaying the day. // */ // String DEFAULT_FORMAT = "d"; // // /** // * Default implementation used by {@linkplain com.prolificinteractive.materialcalendarview.MaterialCalendarView} // */ // DayFormatter DEFAULT = new DateFormatDayFormatter(); // // /** // * Format a given day into a string // * // * @param day the day // * @return a label for the day // */ // @NonNull String format(@NonNull CalendarDay day); // } // // Path: library/src/main/java/com/prolificinteractive/materialcalendarview/format/TitleFormatter.java // public interface TitleFormatter { // // String DEFAULT_FORMAT = "LLLL yyyy"; // // TitleFormatter DEFAULT = new DateFormatTitleFormatter(); // // /** // * Converts the supplied day to a suitable month/year title // * // * @param day the day containing relevant month and year information // * @return a label to display for the given month/year // */ // CharSequence format(CalendarDay day); // } // // Path: library/src/main/java/com/prolificinteractive/materialcalendarview/format/WeekDayFormatter.java // public interface WeekDayFormatter { // /** // * Convert a given day of the week into a label. // * // * @param dayOfWeek the day of the week as returned by {@linkplain DayOfWeek#getValue()}. // * @return a label for the day of week. // */ // CharSequence format(DayOfWeek dayOfWeek); // // /** // * Default implementation used by {@linkplain com.prolificinteractive.materialcalendarview.MaterialCalendarView} // */ // WeekDayFormatter DEFAULT = new CalendarWeekDayFormatter(); // } // Path: library/src/main/java/com/prolificinteractive/materialcalendarview/CalendarPagerAdapter.java import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.view.PagerAdapter; import android.view.View; import android.view.ViewGroup; import com.prolificinteractive.materialcalendarview.MaterialCalendarView.ShowOtherDates; import com.prolificinteractive.materialcalendarview.format.DayFormatter; import com.prolificinteractive.materialcalendarview.format.TitleFormatter; import com.prolificinteractive.materialcalendarview.format.WeekDayFormatter; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.threeten.bp.LocalDate; package com.prolificinteractive.materialcalendarview; /** * Pager adapter backing the calendar view */ abstract class CalendarPagerAdapter<V extends CalendarPagerView> extends PagerAdapter { private final ArrayDeque<V> currentViews; protected final MaterialCalendarView mcv; private final CalendarDay today;
@NonNull private TitleFormatter titleFormatter = TitleFormatter.DEFAULT;
prolificinteractive/material-calendarview
library/src/main/java/com/prolificinteractive/materialcalendarview/CalendarPagerAdapter.java
// Path: library/src/main/java/com/prolificinteractive/materialcalendarview/format/DayFormatter.java // public interface DayFormatter { // // /** // * Default format for displaying the day. // */ // String DEFAULT_FORMAT = "d"; // // /** // * Default implementation used by {@linkplain com.prolificinteractive.materialcalendarview.MaterialCalendarView} // */ // DayFormatter DEFAULT = new DateFormatDayFormatter(); // // /** // * Format a given day into a string // * // * @param day the day // * @return a label for the day // */ // @NonNull String format(@NonNull CalendarDay day); // } // // Path: library/src/main/java/com/prolificinteractive/materialcalendarview/format/TitleFormatter.java // public interface TitleFormatter { // // String DEFAULT_FORMAT = "LLLL yyyy"; // // TitleFormatter DEFAULT = new DateFormatTitleFormatter(); // // /** // * Converts the supplied day to a suitable month/year title // * // * @param day the day containing relevant month and year information // * @return a label to display for the given month/year // */ // CharSequence format(CalendarDay day); // } // // Path: library/src/main/java/com/prolificinteractive/materialcalendarview/format/WeekDayFormatter.java // public interface WeekDayFormatter { // /** // * Convert a given day of the week into a label. // * // * @param dayOfWeek the day of the week as returned by {@linkplain DayOfWeek#getValue()}. // * @return a label for the day of week. // */ // CharSequence format(DayOfWeek dayOfWeek); // // /** // * Default implementation used by {@linkplain com.prolificinteractive.materialcalendarview.MaterialCalendarView} // */ // WeekDayFormatter DEFAULT = new CalendarWeekDayFormatter(); // }
import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.view.PagerAdapter; import android.view.View; import android.view.ViewGroup; import com.prolificinteractive.materialcalendarview.MaterialCalendarView.ShowOtherDates; import com.prolificinteractive.materialcalendarview.format.DayFormatter; import com.prolificinteractive.materialcalendarview.format.TitleFormatter; import com.prolificinteractive.materialcalendarview.format.WeekDayFormatter; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.threeten.bp.LocalDate;
package com.prolificinteractive.materialcalendarview; /** * Pager adapter backing the calendar view */ abstract class CalendarPagerAdapter<V extends CalendarPagerView> extends PagerAdapter { private final ArrayDeque<V> currentViews; protected final MaterialCalendarView mcv; private final CalendarDay today; @NonNull private TitleFormatter titleFormatter = TitleFormatter.DEFAULT; private Integer color = null; private Integer dateTextAppearance = null; private Integer weekDayTextAppearance = null; @ShowOtherDates private int showOtherDates = MaterialCalendarView.SHOW_DEFAULTS; private CalendarDay minDate = null; private CalendarDay maxDate = null; private DateRangeIndex rangeIndex; private List<CalendarDay> selectedDates = new ArrayList<>();
// Path: library/src/main/java/com/prolificinteractive/materialcalendarview/format/DayFormatter.java // public interface DayFormatter { // // /** // * Default format for displaying the day. // */ // String DEFAULT_FORMAT = "d"; // // /** // * Default implementation used by {@linkplain com.prolificinteractive.materialcalendarview.MaterialCalendarView} // */ // DayFormatter DEFAULT = new DateFormatDayFormatter(); // // /** // * Format a given day into a string // * // * @param day the day // * @return a label for the day // */ // @NonNull String format(@NonNull CalendarDay day); // } // // Path: library/src/main/java/com/prolificinteractive/materialcalendarview/format/TitleFormatter.java // public interface TitleFormatter { // // String DEFAULT_FORMAT = "LLLL yyyy"; // // TitleFormatter DEFAULT = new DateFormatTitleFormatter(); // // /** // * Converts the supplied day to a suitable month/year title // * // * @param day the day containing relevant month and year information // * @return a label to display for the given month/year // */ // CharSequence format(CalendarDay day); // } // // Path: library/src/main/java/com/prolificinteractive/materialcalendarview/format/WeekDayFormatter.java // public interface WeekDayFormatter { // /** // * Convert a given day of the week into a label. // * // * @param dayOfWeek the day of the week as returned by {@linkplain DayOfWeek#getValue()}. // * @return a label for the day of week. // */ // CharSequence format(DayOfWeek dayOfWeek); // // /** // * Default implementation used by {@linkplain com.prolificinteractive.materialcalendarview.MaterialCalendarView} // */ // WeekDayFormatter DEFAULT = new CalendarWeekDayFormatter(); // } // Path: library/src/main/java/com/prolificinteractive/materialcalendarview/CalendarPagerAdapter.java import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.view.PagerAdapter; import android.view.View; import android.view.ViewGroup; import com.prolificinteractive.materialcalendarview.MaterialCalendarView.ShowOtherDates; import com.prolificinteractive.materialcalendarview.format.DayFormatter; import com.prolificinteractive.materialcalendarview.format.TitleFormatter; import com.prolificinteractive.materialcalendarview.format.WeekDayFormatter; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.threeten.bp.LocalDate; package com.prolificinteractive.materialcalendarview; /** * Pager adapter backing the calendar view */ abstract class CalendarPagerAdapter<V extends CalendarPagerView> extends PagerAdapter { private final ArrayDeque<V> currentViews; protected final MaterialCalendarView mcv; private final CalendarDay today; @NonNull private TitleFormatter titleFormatter = TitleFormatter.DEFAULT; private Integer color = null; private Integer dateTextAppearance = null; private Integer weekDayTextAppearance = null; @ShowOtherDates private int showOtherDates = MaterialCalendarView.SHOW_DEFAULTS; private CalendarDay minDate = null; private CalendarDay maxDate = null; private DateRangeIndex rangeIndex; private List<CalendarDay> selectedDates = new ArrayList<>();
private WeekDayFormatter weekDayFormatter = WeekDayFormatter.DEFAULT;
prolificinteractive/material-calendarview
library/src/main/java/com/prolificinteractive/materialcalendarview/CalendarPagerAdapter.java
// Path: library/src/main/java/com/prolificinteractive/materialcalendarview/format/DayFormatter.java // public interface DayFormatter { // // /** // * Default format for displaying the day. // */ // String DEFAULT_FORMAT = "d"; // // /** // * Default implementation used by {@linkplain com.prolificinteractive.materialcalendarview.MaterialCalendarView} // */ // DayFormatter DEFAULT = new DateFormatDayFormatter(); // // /** // * Format a given day into a string // * // * @param day the day // * @return a label for the day // */ // @NonNull String format(@NonNull CalendarDay day); // } // // Path: library/src/main/java/com/prolificinteractive/materialcalendarview/format/TitleFormatter.java // public interface TitleFormatter { // // String DEFAULT_FORMAT = "LLLL yyyy"; // // TitleFormatter DEFAULT = new DateFormatTitleFormatter(); // // /** // * Converts the supplied day to a suitable month/year title // * // * @param day the day containing relevant month and year information // * @return a label to display for the given month/year // */ // CharSequence format(CalendarDay day); // } // // Path: library/src/main/java/com/prolificinteractive/materialcalendarview/format/WeekDayFormatter.java // public interface WeekDayFormatter { // /** // * Convert a given day of the week into a label. // * // * @param dayOfWeek the day of the week as returned by {@linkplain DayOfWeek#getValue()}. // * @return a label for the day of week. // */ // CharSequence format(DayOfWeek dayOfWeek); // // /** // * Default implementation used by {@linkplain com.prolificinteractive.materialcalendarview.MaterialCalendarView} // */ // WeekDayFormatter DEFAULT = new CalendarWeekDayFormatter(); // }
import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.view.PagerAdapter; import android.view.View; import android.view.ViewGroup; import com.prolificinteractive.materialcalendarview.MaterialCalendarView.ShowOtherDates; import com.prolificinteractive.materialcalendarview.format.DayFormatter; import com.prolificinteractive.materialcalendarview.format.TitleFormatter; import com.prolificinteractive.materialcalendarview.format.WeekDayFormatter; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.threeten.bp.LocalDate;
package com.prolificinteractive.materialcalendarview; /** * Pager adapter backing the calendar view */ abstract class CalendarPagerAdapter<V extends CalendarPagerView> extends PagerAdapter { private final ArrayDeque<V> currentViews; protected final MaterialCalendarView mcv; private final CalendarDay today; @NonNull private TitleFormatter titleFormatter = TitleFormatter.DEFAULT; private Integer color = null; private Integer dateTextAppearance = null; private Integer weekDayTextAppearance = null; @ShowOtherDates private int showOtherDates = MaterialCalendarView.SHOW_DEFAULTS; private CalendarDay minDate = null; private CalendarDay maxDate = null; private DateRangeIndex rangeIndex; private List<CalendarDay> selectedDates = new ArrayList<>(); private WeekDayFormatter weekDayFormatter = WeekDayFormatter.DEFAULT;
// Path: library/src/main/java/com/prolificinteractive/materialcalendarview/format/DayFormatter.java // public interface DayFormatter { // // /** // * Default format for displaying the day. // */ // String DEFAULT_FORMAT = "d"; // // /** // * Default implementation used by {@linkplain com.prolificinteractive.materialcalendarview.MaterialCalendarView} // */ // DayFormatter DEFAULT = new DateFormatDayFormatter(); // // /** // * Format a given day into a string // * // * @param day the day // * @return a label for the day // */ // @NonNull String format(@NonNull CalendarDay day); // } // // Path: library/src/main/java/com/prolificinteractive/materialcalendarview/format/TitleFormatter.java // public interface TitleFormatter { // // String DEFAULT_FORMAT = "LLLL yyyy"; // // TitleFormatter DEFAULT = new DateFormatTitleFormatter(); // // /** // * Converts the supplied day to a suitable month/year title // * // * @param day the day containing relevant month and year information // * @return a label to display for the given month/year // */ // CharSequence format(CalendarDay day); // } // // Path: library/src/main/java/com/prolificinteractive/materialcalendarview/format/WeekDayFormatter.java // public interface WeekDayFormatter { // /** // * Convert a given day of the week into a label. // * // * @param dayOfWeek the day of the week as returned by {@linkplain DayOfWeek#getValue()}. // * @return a label for the day of week. // */ // CharSequence format(DayOfWeek dayOfWeek); // // /** // * Default implementation used by {@linkplain com.prolificinteractive.materialcalendarview.MaterialCalendarView} // */ // WeekDayFormatter DEFAULT = new CalendarWeekDayFormatter(); // } // Path: library/src/main/java/com/prolificinteractive/materialcalendarview/CalendarPagerAdapter.java import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.view.PagerAdapter; import android.view.View; import android.view.ViewGroup; import com.prolificinteractive.materialcalendarview.MaterialCalendarView.ShowOtherDates; import com.prolificinteractive.materialcalendarview.format.DayFormatter; import com.prolificinteractive.materialcalendarview.format.TitleFormatter; import com.prolificinteractive.materialcalendarview.format.WeekDayFormatter; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.threeten.bp.LocalDate; package com.prolificinteractive.materialcalendarview; /** * Pager adapter backing the calendar view */ abstract class CalendarPagerAdapter<V extends CalendarPagerView> extends PagerAdapter { private final ArrayDeque<V> currentViews; protected final MaterialCalendarView mcv; private final CalendarDay today; @NonNull private TitleFormatter titleFormatter = TitleFormatter.DEFAULT; private Integer color = null; private Integer dateTextAppearance = null; private Integer weekDayTextAppearance = null; @ShowOtherDates private int showOtherDates = MaterialCalendarView.SHOW_DEFAULTS; private CalendarDay minDate = null; private CalendarDay maxDate = null; private DateRangeIndex rangeIndex; private List<CalendarDay> selectedDates = new ArrayList<>(); private WeekDayFormatter weekDayFormatter = WeekDayFormatter.DEFAULT;
private DayFormatter dayFormatter = DayFormatter.DEFAULT;
prolificinteractive/material-calendarview
sample/src/main/java/com/prolificinteractive/materialcalendarview/sample/decorators/MySelectorDecorator.java
// Path: library/src/main/java/com/prolificinteractive/materialcalendarview/CalendarDay.java // public final class CalendarDay implements Parcelable { // // /** // * Everything is based on this variable for {@link CalendarDay}. // */ // @NonNull private final LocalDate date; // // /** // * @param year new instance's year // * @param month new instance's month as defined by {@linkplain java.util.Calendar} // * @param day new instance's day of month // */ // private CalendarDay(final int year, final int month, final int day) { // date = LocalDate.of(year, month, day); // } // // /** // * @param date {@link LocalDate} instance // */ // private CalendarDay(@NonNull final LocalDate date) { // this.date = date; // } // // /** // * Get a new instance set to today // * // * @return CalendarDay set to today's date // */ // @NonNull public static CalendarDay today() { // return from(LocalDate.now()); // } // // /** // * Get a new instance set to the specified day // * // * @param year new instance's year // * @param month new instance's month as defined by {@linkplain java.util.Calendar} // * @param day new instance's day of month // * @return CalendarDay set to the specified date // */ // @NonNull public static CalendarDay from(int year, int month, int day) { // return new CalendarDay(year, month, day); // } // // /** // * Get a new instance set to the specified day // * // * @param date {@linkplain LocalDate} to pull date information from. Passing null will return null // * @return CalendarDay set to the specified date // */ // public static CalendarDay from(@Nullable LocalDate date) { // if (date == null) { // return null; // } // return new CalendarDay(date); // } // // /** // * Get the year // * // * @return the year for this day // */ // public int getYear() { // return date.getYear(); // } // // /** // * Get the month, represented by values from {@linkplain LocalDate} // * // * @return the month of the year as defined by {@linkplain LocalDate} // */ // public int getMonth() { // return date.getMonthValue(); // } // // /** // * Get the day // * // * @return the day of the month for this day // */ // public int getDay() { // return date.getDayOfMonth(); // } // // /** // * Get this day as a {@linkplain LocalDate} // * // * @return a date with this days information // */ // @NonNull public LocalDate getDate() { // return date; // } // // /** // * Determine if this day is within a specified range // * // * @param minDate the earliest day, may be null // * @param maxDate the latest day, may be null // * @return true if the between (inclusive) the min and max dates. // */ // public boolean isInRange(@Nullable CalendarDay minDate, @Nullable CalendarDay maxDate) { // return !(minDate != null && minDate.isAfter(this)) && // !(maxDate != null && maxDate.isBefore(this)); // } // // /** // * Determine if this day is before the given instance // * // * @param other the other day to test // * @return true if this is before other, false if equal or after // */ // public boolean isBefore(@NonNull final CalendarDay other) { // return date.isBefore(other.getDate()); // } // // /** // * Determine if this day is after the given instance // * // * @param other the other day to test // * @return true if this is after other, false if equal or before // */ // public boolean isAfter(@NonNull final CalendarDay other) { // return date.isAfter(other.getDate()); // } // // @Override public boolean equals(Object o) { // return o instanceof CalendarDay && date.equals(((CalendarDay) o).getDate()); // } // // @Override // public int hashCode() { // return hashCode(date.getYear(), date.getMonthValue(), date.getDayOfMonth()); // } // // private static int hashCode(int year, int month, int day) { // //Should produce hashes like "20150401" // return (year * 10000) + (month * 100) + day; // } // // @Override // public String toString() { // return "CalendarDay{" + date.getYear() + "-" + date.getMonthValue() + "-" // + date.getDayOfMonth() + "}"; // } // // /* // * Parcelable Stuff // */ // // public CalendarDay(Parcel in) { // this(in.readInt(), in.readInt(), in.readInt()); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(date.getYear()); // dest.writeInt(date.getMonthValue()); // dest.writeInt(date.getDayOfMonth()); // } // // public static final Creator<CalendarDay> CREATOR = new Creator<CalendarDay>() { // public CalendarDay createFromParcel(Parcel in) { // return new CalendarDay(in); // } // // public CalendarDay[] newArray(int size) { // return new CalendarDay[size]; // } // }; // }
import android.app.Activity; import android.graphics.drawable.Drawable; import com.prolificinteractive.materialcalendarview.CalendarDay; import com.prolificinteractive.materialcalendarview.DayViewDecorator; import com.prolificinteractive.materialcalendarview.DayViewFacade; import com.prolificinteractive.materialcalendarview.sample.R;
package com.prolificinteractive.materialcalendarview.sample.decorators; /** * Use a custom selector */ public class MySelectorDecorator implements DayViewDecorator { private final Drawable drawable; public MySelectorDecorator(Activity context) { drawable = context.getResources().getDrawable(R.drawable.my_selector); } @Override
// Path: library/src/main/java/com/prolificinteractive/materialcalendarview/CalendarDay.java // public final class CalendarDay implements Parcelable { // // /** // * Everything is based on this variable for {@link CalendarDay}. // */ // @NonNull private final LocalDate date; // // /** // * @param year new instance's year // * @param month new instance's month as defined by {@linkplain java.util.Calendar} // * @param day new instance's day of month // */ // private CalendarDay(final int year, final int month, final int day) { // date = LocalDate.of(year, month, day); // } // // /** // * @param date {@link LocalDate} instance // */ // private CalendarDay(@NonNull final LocalDate date) { // this.date = date; // } // // /** // * Get a new instance set to today // * // * @return CalendarDay set to today's date // */ // @NonNull public static CalendarDay today() { // return from(LocalDate.now()); // } // // /** // * Get a new instance set to the specified day // * // * @param year new instance's year // * @param month new instance's month as defined by {@linkplain java.util.Calendar} // * @param day new instance's day of month // * @return CalendarDay set to the specified date // */ // @NonNull public static CalendarDay from(int year, int month, int day) { // return new CalendarDay(year, month, day); // } // // /** // * Get a new instance set to the specified day // * // * @param date {@linkplain LocalDate} to pull date information from. Passing null will return null // * @return CalendarDay set to the specified date // */ // public static CalendarDay from(@Nullable LocalDate date) { // if (date == null) { // return null; // } // return new CalendarDay(date); // } // // /** // * Get the year // * // * @return the year for this day // */ // public int getYear() { // return date.getYear(); // } // // /** // * Get the month, represented by values from {@linkplain LocalDate} // * // * @return the month of the year as defined by {@linkplain LocalDate} // */ // public int getMonth() { // return date.getMonthValue(); // } // // /** // * Get the day // * // * @return the day of the month for this day // */ // public int getDay() { // return date.getDayOfMonth(); // } // // /** // * Get this day as a {@linkplain LocalDate} // * // * @return a date with this days information // */ // @NonNull public LocalDate getDate() { // return date; // } // // /** // * Determine if this day is within a specified range // * // * @param minDate the earliest day, may be null // * @param maxDate the latest day, may be null // * @return true if the between (inclusive) the min and max dates. // */ // public boolean isInRange(@Nullable CalendarDay minDate, @Nullable CalendarDay maxDate) { // return !(minDate != null && minDate.isAfter(this)) && // !(maxDate != null && maxDate.isBefore(this)); // } // // /** // * Determine if this day is before the given instance // * // * @param other the other day to test // * @return true if this is before other, false if equal or after // */ // public boolean isBefore(@NonNull final CalendarDay other) { // return date.isBefore(other.getDate()); // } // // /** // * Determine if this day is after the given instance // * // * @param other the other day to test // * @return true if this is after other, false if equal or before // */ // public boolean isAfter(@NonNull final CalendarDay other) { // return date.isAfter(other.getDate()); // } // // @Override public boolean equals(Object o) { // return o instanceof CalendarDay && date.equals(((CalendarDay) o).getDate()); // } // // @Override // public int hashCode() { // return hashCode(date.getYear(), date.getMonthValue(), date.getDayOfMonth()); // } // // private static int hashCode(int year, int month, int day) { // //Should produce hashes like "20150401" // return (year * 10000) + (month * 100) + day; // } // // @Override // public String toString() { // return "CalendarDay{" + date.getYear() + "-" + date.getMonthValue() + "-" // + date.getDayOfMonth() + "}"; // } // // /* // * Parcelable Stuff // */ // // public CalendarDay(Parcel in) { // this(in.readInt(), in.readInt(), in.readInt()); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(date.getYear()); // dest.writeInt(date.getMonthValue()); // dest.writeInt(date.getDayOfMonth()); // } // // public static final Creator<CalendarDay> CREATOR = new Creator<CalendarDay>() { // public CalendarDay createFromParcel(Parcel in) { // return new CalendarDay(in); // } // // public CalendarDay[] newArray(int size) { // return new CalendarDay[size]; // } // }; // } // Path: sample/src/main/java/com/prolificinteractive/materialcalendarview/sample/decorators/MySelectorDecorator.java import android.app.Activity; import android.graphics.drawable.Drawable; import com.prolificinteractive.materialcalendarview.CalendarDay; import com.prolificinteractive.materialcalendarview.DayViewDecorator; import com.prolificinteractive.materialcalendarview.DayViewFacade; import com.prolificinteractive.materialcalendarview.sample.R; package com.prolificinteractive.materialcalendarview.sample.decorators; /** * Use a custom selector */ public class MySelectorDecorator implements DayViewDecorator { private final Drawable drawable; public MySelectorDecorator(Activity context) { drawable = context.getResources().getDrawable(R.drawable.my_selector); } @Override
public boolean shouldDecorate(CalendarDay day) {
prolificinteractive/material-calendarview
sample/src/main/java/com/prolificinteractive/materialcalendarview/sample/decorators/HighlightWeekendsDecorator.java
// Path: library/src/main/java/com/prolificinteractive/materialcalendarview/CalendarDay.java // public final class CalendarDay implements Parcelable { // // /** // * Everything is based on this variable for {@link CalendarDay}. // */ // @NonNull private final LocalDate date; // // /** // * @param year new instance's year // * @param month new instance's month as defined by {@linkplain java.util.Calendar} // * @param day new instance's day of month // */ // private CalendarDay(final int year, final int month, final int day) { // date = LocalDate.of(year, month, day); // } // // /** // * @param date {@link LocalDate} instance // */ // private CalendarDay(@NonNull final LocalDate date) { // this.date = date; // } // // /** // * Get a new instance set to today // * // * @return CalendarDay set to today's date // */ // @NonNull public static CalendarDay today() { // return from(LocalDate.now()); // } // // /** // * Get a new instance set to the specified day // * // * @param year new instance's year // * @param month new instance's month as defined by {@linkplain java.util.Calendar} // * @param day new instance's day of month // * @return CalendarDay set to the specified date // */ // @NonNull public static CalendarDay from(int year, int month, int day) { // return new CalendarDay(year, month, day); // } // // /** // * Get a new instance set to the specified day // * // * @param date {@linkplain LocalDate} to pull date information from. Passing null will return null // * @return CalendarDay set to the specified date // */ // public static CalendarDay from(@Nullable LocalDate date) { // if (date == null) { // return null; // } // return new CalendarDay(date); // } // // /** // * Get the year // * // * @return the year for this day // */ // public int getYear() { // return date.getYear(); // } // // /** // * Get the month, represented by values from {@linkplain LocalDate} // * // * @return the month of the year as defined by {@linkplain LocalDate} // */ // public int getMonth() { // return date.getMonthValue(); // } // // /** // * Get the day // * // * @return the day of the month for this day // */ // public int getDay() { // return date.getDayOfMonth(); // } // // /** // * Get this day as a {@linkplain LocalDate} // * // * @return a date with this days information // */ // @NonNull public LocalDate getDate() { // return date; // } // // /** // * Determine if this day is within a specified range // * // * @param minDate the earliest day, may be null // * @param maxDate the latest day, may be null // * @return true if the between (inclusive) the min and max dates. // */ // public boolean isInRange(@Nullable CalendarDay minDate, @Nullable CalendarDay maxDate) { // return !(minDate != null && minDate.isAfter(this)) && // !(maxDate != null && maxDate.isBefore(this)); // } // // /** // * Determine if this day is before the given instance // * // * @param other the other day to test // * @return true if this is before other, false if equal or after // */ // public boolean isBefore(@NonNull final CalendarDay other) { // return date.isBefore(other.getDate()); // } // // /** // * Determine if this day is after the given instance // * // * @param other the other day to test // * @return true if this is after other, false if equal or before // */ // public boolean isAfter(@NonNull final CalendarDay other) { // return date.isAfter(other.getDate()); // } // // @Override public boolean equals(Object o) { // return o instanceof CalendarDay && date.equals(((CalendarDay) o).getDate()); // } // // @Override // public int hashCode() { // return hashCode(date.getYear(), date.getMonthValue(), date.getDayOfMonth()); // } // // private static int hashCode(int year, int month, int day) { // //Should produce hashes like "20150401" // return (year * 10000) + (month * 100) + day; // } // // @Override // public String toString() { // return "CalendarDay{" + date.getYear() + "-" + date.getMonthValue() + "-" // + date.getDayOfMonth() + "}"; // } // // /* // * Parcelable Stuff // */ // // public CalendarDay(Parcel in) { // this(in.readInt(), in.readInt(), in.readInt()); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(date.getYear()); // dest.writeInt(date.getMonthValue()); // dest.writeInt(date.getDayOfMonth()); // } // // public static final Creator<CalendarDay> CREATOR = new Creator<CalendarDay>() { // public CalendarDay createFromParcel(Parcel in) { // return new CalendarDay(in); // } // // public CalendarDay[] newArray(int size) { // return new CalendarDay[size]; // } // }; // }
import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import com.prolificinteractive.materialcalendarview.CalendarDay; import com.prolificinteractive.materialcalendarview.DayViewDecorator; import com.prolificinteractive.materialcalendarview.DayViewFacade; import org.threeten.bp.DayOfWeek;
package com.prolificinteractive.materialcalendarview.sample.decorators; /** * Highlight Saturdays and Sundays with a background */ public class HighlightWeekendsDecorator implements DayViewDecorator { private final Drawable highlightDrawable; private static final int color = Color.parseColor("#228BC34A"); public HighlightWeekendsDecorator() { highlightDrawable = new ColorDrawable(color); }
// Path: library/src/main/java/com/prolificinteractive/materialcalendarview/CalendarDay.java // public final class CalendarDay implements Parcelable { // // /** // * Everything is based on this variable for {@link CalendarDay}. // */ // @NonNull private final LocalDate date; // // /** // * @param year new instance's year // * @param month new instance's month as defined by {@linkplain java.util.Calendar} // * @param day new instance's day of month // */ // private CalendarDay(final int year, final int month, final int day) { // date = LocalDate.of(year, month, day); // } // // /** // * @param date {@link LocalDate} instance // */ // private CalendarDay(@NonNull final LocalDate date) { // this.date = date; // } // // /** // * Get a new instance set to today // * // * @return CalendarDay set to today's date // */ // @NonNull public static CalendarDay today() { // return from(LocalDate.now()); // } // // /** // * Get a new instance set to the specified day // * // * @param year new instance's year // * @param month new instance's month as defined by {@linkplain java.util.Calendar} // * @param day new instance's day of month // * @return CalendarDay set to the specified date // */ // @NonNull public static CalendarDay from(int year, int month, int day) { // return new CalendarDay(year, month, day); // } // // /** // * Get a new instance set to the specified day // * // * @param date {@linkplain LocalDate} to pull date information from. Passing null will return null // * @return CalendarDay set to the specified date // */ // public static CalendarDay from(@Nullable LocalDate date) { // if (date == null) { // return null; // } // return new CalendarDay(date); // } // // /** // * Get the year // * // * @return the year for this day // */ // public int getYear() { // return date.getYear(); // } // // /** // * Get the month, represented by values from {@linkplain LocalDate} // * // * @return the month of the year as defined by {@linkplain LocalDate} // */ // public int getMonth() { // return date.getMonthValue(); // } // // /** // * Get the day // * // * @return the day of the month for this day // */ // public int getDay() { // return date.getDayOfMonth(); // } // // /** // * Get this day as a {@linkplain LocalDate} // * // * @return a date with this days information // */ // @NonNull public LocalDate getDate() { // return date; // } // // /** // * Determine if this day is within a specified range // * // * @param minDate the earliest day, may be null // * @param maxDate the latest day, may be null // * @return true if the between (inclusive) the min and max dates. // */ // public boolean isInRange(@Nullable CalendarDay minDate, @Nullable CalendarDay maxDate) { // return !(minDate != null && minDate.isAfter(this)) && // !(maxDate != null && maxDate.isBefore(this)); // } // // /** // * Determine if this day is before the given instance // * // * @param other the other day to test // * @return true if this is before other, false if equal or after // */ // public boolean isBefore(@NonNull final CalendarDay other) { // return date.isBefore(other.getDate()); // } // // /** // * Determine if this day is after the given instance // * // * @param other the other day to test // * @return true if this is after other, false if equal or before // */ // public boolean isAfter(@NonNull final CalendarDay other) { // return date.isAfter(other.getDate()); // } // // @Override public boolean equals(Object o) { // return o instanceof CalendarDay && date.equals(((CalendarDay) o).getDate()); // } // // @Override // public int hashCode() { // return hashCode(date.getYear(), date.getMonthValue(), date.getDayOfMonth()); // } // // private static int hashCode(int year, int month, int day) { // //Should produce hashes like "20150401" // return (year * 10000) + (month * 100) + day; // } // // @Override // public String toString() { // return "CalendarDay{" + date.getYear() + "-" + date.getMonthValue() + "-" // + date.getDayOfMonth() + "}"; // } // // /* // * Parcelable Stuff // */ // // public CalendarDay(Parcel in) { // this(in.readInt(), in.readInt(), in.readInt()); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(date.getYear()); // dest.writeInt(date.getMonthValue()); // dest.writeInt(date.getDayOfMonth()); // } // // public static final Creator<CalendarDay> CREATOR = new Creator<CalendarDay>() { // public CalendarDay createFromParcel(Parcel in) { // return new CalendarDay(in); // } // // public CalendarDay[] newArray(int size) { // return new CalendarDay[size]; // } // }; // } // Path: sample/src/main/java/com/prolificinteractive/materialcalendarview/sample/decorators/HighlightWeekendsDecorator.java import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import com.prolificinteractive.materialcalendarview.CalendarDay; import com.prolificinteractive.materialcalendarview.DayViewDecorator; import com.prolificinteractive.materialcalendarview.DayViewFacade; import org.threeten.bp.DayOfWeek; package com.prolificinteractive.materialcalendarview.sample.decorators; /** * Highlight Saturdays and Sundays with a background */ public class HighlightWeekendsDecorator implements DayViewDecorator { private final Drawable highlightDrawable; private static final int color = Color.parseColor("#228BC34A"); public HighlightWeekendsDecorator() { highlightDrawable = new ColorDrawable(color); }
@Override public boolean shouldDecorate(final CalendarDay day) {
prolificinteractive/material-calendarview
library/src/main/java/com/prolificinteractive/materialcalendarview/format/MonthArrayTitleFormatter.java
// Path: library/src/main/java/com/prolificinteractive/materialcalendarview/CalendarDay.java // public final class CalendarDay implements Parcelable { // // /** // * Everything is based on this variable for {@link CalendarDay}. // */ // @NonNull private final LocalDate date; // // /** // * @param year new instance's year // * @param month new instance's month as defined by {@linkplain java.util.Calendar} // * @param day new instance's day of month // */ // private CalendarDay(final int year, final int month, final int day) { // date = LocalDate.of(year, month, day); // } // // /** // * @param date {@link LocalDate} instance // */ // private CalendarDay(@NonNull final LocalDate date) { // this.date = date; // } // // /** // * Get a new instance set to today // * // * @return CalendarDay set to today's date // */ // @NonNull public static CalendarDay today() { // return from(LocalDate.now()); // } // // /** // * Get a new instance set to the specified day // * // * @param year new instance's year // * @param month new instance's month as defined by {@linkplain java.util.Calendar} // * @param day new instance's day of month // * @return CalendarDay set to the specified date // */ // @NonNull public static CalendarDay from(int year, int month, int day) { // return new CalendarDay(year, month, day); // } // // /** // * Get a new instance set to the specified day // * // * @param date {@linkplain LocalDate} to pull date information from. Passing null will return null // * @return CalendarDay set to the specified date // */ // public static CalendarDay from(@Nullable LocalDate date) { // if (date == null) { // return null; // } // return new CalendarDay(date); // } // // /** // * Get the year // * // * @return the year for this day // */ // public int getYear() { // return date.getYear(); // } // // /** // * Get the month, represented by values from {@linkplain LocalDate} // * // * @return the month of the year as defined by {@linkplain LocalDate} // */ // public int getMonth() { // return date.getMonthValue(); // } // // /** // * Get the day // * // * @return the day of the month for this day // */ // public int getDay() { // return date.getDayOfMonth(); // } // // /** // * Get this day as a {@linkplain LocalDate} // * // * @return a date with this days information // */ // @NonNull public LocalDate getDate() { // return date; // } // // /** // * Determine if this day is within a specified range // * // * @param minDate the earliest day, may be null // * @param maxDate the latest day, may be null // * @return true if the between (inclusive) the min and max dates. // */ // public boolean isInRange(@Nullable CalendarDay minDate, @Nullable CalendarDay maxDate) { // return !(minDate != null && minDate.isAfter(this)) && // !(maxDate != null && maxDate.isBefore(this)); // } // // /** // * Determine if this day is before the given instance // * // * @param other the other day to test // * @return true if this is before other, false if equal or after // */ // public boolean isBefore(@NonNull final CalendarDay other) { // return date.isBefore(other.getDate()); // } // // /** // * Determine if this day is after the given instance // * // * @param other the other day to test // * @return true if this is after other, false if equal or before // */ // public boolean isAfter(@NonNull final CalendarDay other) { // return date.isAfter(other.getDate()); // } // // @Override public boolean equals(Object o) { // return o instanceof CalendarDay && date.equals(((CalendarDay) o).getDate()); // } // // @Override // public int hashCode() { // return hashCode(date.getYear(), date.getMonthValue(), date.getDayOfMonth()); // } // // private static int hashCode(int year, int month, int day) { // //Should produce hashes like "20150401" // return (year * 10000) + (month * 100) + day; // } // // @Override // public String toString() { // return "CalendarDay{" + date.getYear() + "-" + date.getMonthValue() + "-" // + date.getDayOfMonth() + "}"; // } // // /* // * Parcelable Stuff // */ // // public CalendarDay(Parcel in) { // this(in.readInt(), in.readInt(), in.readInt()); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(date.getYear()); // dest.writeInt(date.getMonthValue()); // dest.writeInt(date.getDayOfMonth()); // } // // public static final Creator<CalendarDay> CREATOR = new Creator<CalendarDay>() { // public CalendarDay createFromParcel(Parcel in) { // return new CalendarDay(in); // } // // public CalendarDay[] newArray(int size) { // return new CalendarDay[size]; // } // }; // }
import android.text.SpannableStringBuilder; import com.prolificinteractive.materialcalendarview.CalendarDay;
package com.prolificinteractive.materialcalendarview.format; /** * Use an array to generate a month/year label */ public class MonthArrayTitleFormatter implements TitleFormatter { private final CharSequence[] monthLabels; /** * Format using an array of month labels * * @param monthLabels an array of 12 labels to use for months, starting with January */ public MonthArrayTitleFormatter(CharSequence[] monthLabels) { if (monthLabels == null) { throw new IllegalArgumentException("Label array cannot be null"); } if (monthLabels.length < 12) { throw new IllegalArgumentException("Label array is too short"); } this.monthLabels = monthLabels; } /** * {@inheritDoc} */ @Override
// Path: library/src/main/java/com/prolificinteractive/materialcalendarview/CalendarDay.java // public final class CalendarDay implements Parcelable { // // /** // * Everything is based on this variable for {@link CalendarDay}. // */ // @NonNull private final LocalDate date; // // /** // * @param year new instance's year // * @param month new instance's month as defined by {@linkplain java.util.Calendar} // * @param day new instance's day of month // */ // private CalendarDay(final int year, final int month, final int day) { // date = LocalDate.of(year, month, day); // } // // /** // * @param date {@link LocalDate} instance // */ // private CalendarDay(@NonNull final LocalDate date) { // this.date = date; // } // // /** // * Get a new instance set to today // * // * @return CalendarDay set to today's date // */ // @NonNull public static CalendarDay today() { // return from(LocalDate.now()); // } // // /** // * Get a new instance set to the specified day // * // * @param year new instance's year // * @param month new instance's month as defined by {@linkplain java.util.Calendar} // * @param day new instance's day of month // * @return CalendarDay set to the specified date // */ // @NonNull public static CalendarDay from(int year, int month, int day) { // return new CalendarDay(year, month, day); // } // // /** // * Get a new instance set to the specified day // * // * @param date {@linkplain LocalDate} to pull date information from. Passing null will return null // * @return CalendarDay set to the specified date // */ // public static CalendarDay from(@Nullable LocalDate date) { // if (date == null) { // return null; // } // return new CalendarDay(date); // } // // /** // * Get the year // * // * @return the year for this day // */ // public int getYear() { // return date.getYear(); // } // // /** // * Get the month, represented by values from {@linkplain LocalDate} // * // * @return the month of the year as defined by {@linkplain LocalDate} // */ // public int getMonth() { // return date.getMonthValue(); // } // // /** // * Get the day // * // * @return the day of the month for this day // */ // public int getDay() { // return date.getDayOfMonth(); // } // // /** // * Get this day as a {@linkplain LocalDate} // * // * @return a date with this days information // */ // @NonNull public LocalDate getDate() { // return date; // } // // /** // * Determine if this day is within a specified range // * // * @param minDate the earliest day, may be null // * @param maxDate the latest day, may be null // * @return true if the between (inclusive) the min and max dates. // */ // public boolean isInRange(@Nullable CalendarDay minDate, @Nullable CalendarDay maxDate) { // return !(minDate != null && minDate.isAfter(this)) && // !(maxDate != null && maxDate.isBefore(this)); // } // // /** // * Determine if this day is before the given instance // * // * @param other the other day to test // * @return true if this is before other, false if equal or after // */ // public boolean isBefore(@NonNull final CalendarDay other) { // return date.isBefore(other.getDate()); // } // // /** // * Determine if this day is after the given instance // * // * @param other the other day to test // * @return true if this is after other, false if equal or before // */ // public boolean isAfter(@NonNull final CalendarDay other) { // return date.isAfter(other.getDate()); // } // // @Override public boolean equals(Object o) { // return o instanceof CalendarDay && date.equals(((CalendarDay) o).getDate()); // } // // @Override // public int hashCode() { // return hashCode(date.getYear(), date.getMonthValue(), date.getDayOfMonth()); // } // // private static int hashCode(int year, int month, int day) { // //Should produce hashes like "20150401" // return (year * 10000) + (month * 100) + day; // } // // @Override // public String toString() { // return "CalendarDay{" + date.getYear() + "-" + date.getMonthValue() + "-" // + date.getDayOfMonth() + "}"; // } // // /* // * Parcelable Stuff // */ // // public CalendarDay(Parcel in) { // this(in.readInt(), in.readInt(), in.readInt()); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(date.getYear()); // dest.writeInt(date.getMonthValue()); // dest.writeInt(date.getDayOfMonth()); // } // // public static final Creator<CalendarDay> CREATOR = new Creator<CalendarDay>() { // public CalendarDay createFromParcel(Parcel in) { // return new CalendarDay(in); // } // // public CalendarDay[] newArray(int size) { // return new CalendarDay[size]; // } // }; // } // Path: library/src/main/java/com/prolificinteractive/materialcalendarview/format/MonthArrayTitleFormatter.java import android.text.SpannableStringBuilder; import com.prolificinteractive.materialcalendarview.CalendarDay; package com.prolificinteractive.materialcalendarview.format; /** * Use an array to generate a month/year label */ public class MonthArrayTitleFormatter implements TitleFormatter { private final CharSequence[] monthLabels; /** * Format using an array of month labels * * @param monthLabels an array of 12 labels to use for months, starting with January */ public MonthArrayTitleFormatter(CharSequence[] monthLabels) { if (monthLabels == null) { throw new IllegalArgumentException("Label array cannot be null"); } if (monthLabels.length < 12) { throw new IllegalArgumentException("Label array is too short"); } this.monthLabels = monthLabels; } /** * {@inheritDoc} */ @Override
public CharSequence format(CalendarDay day) {
prolificinteractive/material-calendarview
library/src/main/java/com/prolificinteractive/materialcalendarview/format/DateFormatTitleFormatter.java
// Path: library/src/main/java/com/prolificinteractive/materialcalendarview/CalendarDay.java // public final class CalendarDay implements Parcelable { // // /** // * Everything is based on this variable for {@link CalendarDay}. // */ // @NonNull private final LocalDate date; // // /** // * @param year new instance's year // * @param month new instance's month as defined by {@linkplain java.util.Calendar} // * @param day new instance's day of month // */ // private CalendarDay(final int year, final int month, final int day) { // date = LocalDate.of(year, month, day); // } // // /** // * @param date {@link LocalDate} instance // */ // private CalendarDay(@NonNull final LocalDate date) { // this.date = date; // } // // /** // * Get a new instance set to today // * // * @return CalendarDay set to today's date // */ // @NonNull public static CalendarDay today() { // return from(LocalDate.now()); // } // // /** // * Get a new instance set to the specified day // * // * @param year new instance's year // * @param month new instance's month as defined by {@linkplain java.util.Calendar} // * @param day new instance's day of month // * @return CalendarDay set to the specified date // */ // @NonNull public static CalendarDay from(int year, int month, int day) { // return new CalendarDay(year, month, day); // } // // /** // * Get a new instance set to the specified day // * // * @param date {@linkplain LocalDate} to pull date information from. Passing null will return null // * @return CalendarDay set to the specified date // */ // public static CalendarDay from(@Nullable LocalDate date) { // if (date == null) { // return null; // } // return new CalendarDay(date); // } // // /** // * Get the year // * // * @return the year for this day // */ // public int getYear() { // return date.getYear(); // } // // /** // * Get the month, represented by values from {@linkplain LocalDate} // * // * @return the month of the year as defined by {@linkplain LocalDate} // */ // public int getMonth() { // return date.getMonthValue(); // } // // /** // * Get the day // * // * @return the day of the month for this day // */ // public int getDay() { // return date.getDayOfMonth(); // } // // /** // * Get this day as a {@linkplain LocalDate} // * // * @return a date with this days information // */ // @NonNull public LocalDate getDate() { // return date; // } // // /** // * Determine if this day is within a specified range // * // * @param minDate the earliest day, may be null // * @param maxDate the latest day, may be null // * @return true if the between (inclusive) the min and max dates. // */ // public boolean isInRange(@Nullable CalendarDay minDate, @Nullable CalendarDay maxDate) { // return !(minDate != null && minDate.isAfter(this)) && // !(maxDate != null && maxDate.isBefore(this)); // } // // /** // * Determine if this day is before the given instance // * // * @param other the other day to test // * @return true if this is before other, false if equal or after // */ // public boolean isBefore(@NonNull final CalendarDay other) { // return date.isBefore(other.getDate()); // } // // /** // * Determine if this day is after the given instance // * // * @param other the other day to test // * @return true if this is after other, false if equal or before // */ // public boolean isAfter(@NonNull final CalendarDay other) { // return date.isAfter(other.getDate()); // } // // @Override public boolean equals(Object o) { // return o instanceof CalendarDay && date.equals(((CalendarDay) o).getDate()); // } // // @Override // public int hashCode() { // return hashCode(date.getYear(), date.getMonthValue(), date.getDayOfMonth()); // } // // private static int hashCode(int year, int month, int day) { // //Should produce hashes like "20150401" // return (year * 10000) + (month * 100) + day; // } // // @Override // public String toString() { // return "CalendarDay{" + date.getYear() + "-" + date.getMonthValue() + "-" // + date.getDayOfMonth() + "}"; // } // // /* // * Parcelable Stuff // */ // // public CalendarDay(Parcel in) { // this(in.readInt(), in.readInt(), in.readInt()); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(date.getYear()); // dest.writeInt(date.getMonthValue()); // dest.writeInt(date.getDayOfMonth()); // } // // public static final Creator<CalendarDay> CREATOR = new Creator<CalendarDay>() { // public CalendarDay createFromParcel(Parcel in) { // return new CalendarDay(in); // } // // public CalendarDay[] newArray(int size) { // return new CalendarDay[size]; // } // }; // }
import com.prolificinteractive.materialcalendarview.CalendarDay; import org.threeten.bp.format.DateTimeFormatter;
package com.prolificinteractive.materialcalendarview.format; /** * Format using a {@linkplain java.text.DateFormat} instance. */ public class DateFormatTitleFormatter implements TitleFormatter { private final DateTimeFormatter dateFormat; /** * Format using {@link TitleFormatter#DEFAULT_FORMAT} for formatting. */ public DateFormatTitleFormatter() { this(DateTimeFormatter.ofPattern(DEFAULT_FORMAT)); } /** * Format using a specified {@linkplain DateTimeFormatter} * * @param format the format to use */ public DateFormatTitleFormatter(final DateTimeFormatter format) { this.dateFormat = format; } /** * {@inheritDoc} */
// Path: library/src/main/java/com/prolificinteractive/materialcalendarview/CalendarDay.java // public final class CalendarDay implements Parcelable { // // /** // * Everything is based on this variable for {@link CalendarDay}. // */ // @NonNull private final LocalDate date; // // /** // * @param year new instance's year // * @param month new instance's month as defined by {@linkplain java.util.Calendar} // * @param day new instance's day of month // */ // private CalendarDay(final int year, final int month, final int day) { // date = LocalDate.of(year, month, day); // } // // /** // * @param date {@link LocalDate} instance // */ // private CalendarDay(@NonNull final LocalDate date) { // this.date = date; // } // // /** // * Get a new instance set to today // * // * @return CalendarDay set to today's date // */ // @NonNull public static CalendarDay today() { // return from(LocalDate.now()); // } // // /** // * Get a new instance set to the specified day // * // * @param year new instance's year // * @param month new instance's month as defined by {@linkplain java.util.Calendar} // * @param day new instance's day of month // * @return CalendarDay set to the specified date // */ // @NonNull public static CalendarDay from(int year, int month, int day) { // return new CalendarDay(year, month, day); // } // // /** // * Get a new instance set to the specified day // * // * @param date {@linkplain LocalDate} to pull date information from. Passing null will return null // * @return CalendarDay set to the specified date // */ // public static CalendarDay from(@Nullable LocalDate date) { // if (date == null) { // return null; // } // return new CalendarDay(date); // } // // /** // * Get the year // * // * @return the year for this day // */ // public int getYear() { // return date.getYear(); // } // // /** // * Get the month, represented by values from {@linkplain LocalDate} // * // * @return the month of the year as defined by {@linkplain LocalDate} // */ // public int getMonth() { // return date.getMonthValue(); // } // // /** // * Get the day // * // * @return the day of the month for this day // */ // public int getDay() { // return date.getDayOfMonth(); // } // // /** // * Get this day as a {@linkplain LocalDate} // * // * @return a date with this days information // */ // @NonNull public LocalDate getDate() { // return date; // } // // /** // * Determine if this day is within a specified range // * // * @param minDate the earliest day, may be null // * @param maxDate the latest day, may be null // * @return true if the between (inclusive) the min and max dates. // */ // public boolean isInRange(@Nullable CalendarDay minDate, @Nullable CalendarDay maxDate) { // return !(minDate != null && minDate.isAfter(this)) && // !(maxDate != null && maxDate.isBefore(this)); // } // // /** // * Determine if this day is before the given instance // * // * @param other the other day to test // * @return true if this is before other, false if equal or after // */ // public boolean isBefore(@NonNull final CalendarDay other) { // return date.isBefore(other.getDate()); // } // // /** // * Determine if this day is after the given instance // * // * @param other the other day to test // * @return true if this is after other, false if equal or before // */ // public boolean isAfter(@NonNull final CalendarDay other) { // return date.isAfter(other.getDate()); // } // // @Override public boolean equals(Object o) { // return o instanceof CalendarDay && date.equals(((CalendarDay) o).getDate()); // } // // @Override // public int hashCode() { // return hashCode(date.getYear(), date.getMonthValue(), date.getDayOfMonth()); // } // // private static int hashCode(int year, int month, int day) { // //Should produce hashes like "20150401" // return (year * 10000) + (month * 100) + day; // } // // @Override // public String toString() { // return "CalendarDay{" + date.getYear() + "-" + date.getMonthValue() + "-" // + date.getDayOfMonth() + "}"; // } // // /* // * Parcelable Stuff // */ // // public CalendarDay(Parcel in) { // this(in.readInt(), in.readInt(), in.readInt()); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(date.getYear()); // dest.writeInt(date.getMonthValue()); // dest.writeInt(date.getDayOfMonth()); // } // // public static final Creator<CalendarDay> CREATOR = new Creator<CalendarDay>() { // public CalendarDay createFromParcel(Parcel in) { // return new CalendarDay(in); // } // // public CalendarDay[] newArray(int size) { // return new CalendarDay[size]; // } // }; // } // Path: library/src/main/java/com/prolificinteractive/materialcalendarview/format/DateFormatTitleFormatter.java import com.prolificinteractive.materialcalendarview.CalendarDay; import org.threeten.bp.format.DateTimeFormatter; package com.prolificinteractive.materialcalendarview.format; /** * Format using a {@linkplain java.text.DateFormat} instance. */ public class DateFormatTitleFormatter implements TitleFormatter { private final DateTimeFormatter dateFormat; /** * Format using {@link TitleFormatter#DEFAULT_FORMAT} for formatting. */ public DateFormatTitleFormatter() { this(DateTimeFormatter.ofPattern(DEFAULT_FORMAT)); } /** * Format using a specified {@linkplain DateTimeFormatter} * * @param format the format to use */ public DateFormatTitleFormatter(final DateTimeFormatter format) { this.dateFormat = format; } /** * {@inheritDoc} */
@Override public CharSequence format(final CalendarDay day) {
prolificinteractive/material-calendarview
library/src/main/java/com/prolificinteractive/materialcalendarview/format/DateFormatDayFormatter.java
// Path: library/src/main/java/com/prolificinteractive/materialcalendarview/CalendarDay.java // public final class CalendarDay implements Parcelable { // // /** // * Everything is based on this variable for {@link CalendarDay}. // */ // @NonNull private final LocalDate date; // // /** // * @param year new instance's year // * @param month new instance's month as defined by {@linkplain java.util.Calendar} // * @param day new instance's day of month // */ // private CalendarDay(final int year, final int month, final int day) { // date = LocalDate.of(year, month, day); // } // // /** // * @param date {@link LocalDate} instance // */ // private CalendarDay(@NonNull final LocalDate date) { // this.date = date; // } // // /** // * Get a new instance set to today // * // * @return CalendarDay set to today's date // */ // @NonNull public static CalendarDay today() { // return from(LocalDate.now()); // } // // /** // * Get a new instance set to the specified day // * // * @param year new instance's year // * @param month new instance's month as defined by {@linkplain java.util.Calendar} // * @param day new instance's day of month // * @return CalendarDay set to the specified date // */ // @NonNull public static CalendarDay from(int year, int month, int day) { // return new CalendarDay(year, month, day); // } // // /** // * Get a new instance set to the specified day // * // * @param date {@linkplain LocalDate} to pull date information from. Passing null will return null // * @return CalendarDay set to the specified date // */ // public static CalendarDay from(@Nullable LocalDate date) { // if (date == null) { // return null; // } // return new CalendarDay(date); // } // // /** // * Get the year // * // * @return the year for this day // */ // public int getYear() { // return date.getYear(); // } // // /** // * Get the month, represented by values from {@linkplain LocalDate} // * // * @return the month of the year as defined by {@linkplain LocalDate} // */ // public int getMonth() { // return date.getMonthValue(); // } // // /** // * Get the day // * // * @return the day of the month for this day // */ // public int getDay() { // return date.getDayOfMonth(); // } // // /** // * Get this day as a {@linkplain LocalDate} // * // * @return a date with this days information // */ // @NonNull public LocalDate getDate() { // return date; // } // // /** // * Determine if this day is within a specified range // * // * @param minDate the earliest day, may be null // * @param maxDate the latest day, may be null // * @return true if the between (inclusive) the min and max dates. // */ // public boolean isInRange(@Nullable CalendarDay minDate, @Nullable CalendarDay maxDate) { // return !(minDate != null && minDate.isAfter(this)) && // !(maxDate != null && maxDate.isBefore(this)); // } // // /** // * Determine if this day is before the given instance // * // * @param other the other day to test // * @return true if this is before other, false if equal or after // */ // public boolean isBefore(@NonNull final CalendarDay other) { // return date.isBefore(other.getDate()); // } // // /** // * Determine if this day is after the given instance // * // * @param other the other day to test // * @return true if this is after other, false if equal or before // */ // public boolean isAfter(@NonNull final CalendarDay other) { // return date.isAfter(other.getDate()); // } // // @Override public boolean equals(Object o) { // return o instanceof CalendarDay && date.equals(((CalendarDay) o).getDate()); // } // // @Override // public int hashCode() { // return hashCode(date.getYear(), date.getMonthValue(), date.getDayOfMonth()); // } // // private static int hashCode(int year, int month, int day) { // //Should produce hashes like "20150401" // return (year * 10000) + (month * 100) + day; // } // // @Override // public String toString() { // return "CalendarDay{" + date.getYear() + "-" + date.getMonthValue() + "-" // + date.getDayOfMonth() + "}"; // } // // /* // * Parcelable Stuff // */ // // public CalendarDay(Parcel in) { // this(in.readInt(), in.readInt(), in.readInt()); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(date.getYear()); // dest.writeInt(date.getMonthValue()); // dest.writeInt(date.getDayOfMonth()); // } // // public static final Creator<CalendarDay> CREATOR = new Creator<CalendarDay>() { // public CalendarDay createFromParcel(Parcel in) { // return new CalendarDay(in); // } // // public CalendarDay[] newArray(int size) { // return new CalendarDay[size]; // } // }; // }
import android.support.annotation.NonNull; import com.prolificinteractive.materialcalendarview.CalendarDay; import java.text.DateFormat; import java.util.Locale; import org.threeten.bp.format.DateTimeFormatter;
package com.prolificinteractive.materialcalendarview.format; /** * Format using a {@linkplain DateFormat} instance. */ public class DateFormatDayFormatter implements DayFormatter { private final DateTimeFormatter dateFormat; /** * Format using a default format */ public DateFormatDayFormatter() { this(DateTimeFormatter.ofPattern(DEFAULT_FORMAT, Locale.getDefault())); } /** * Format using a specific {@linkplain DateFormat} * * @param format the format to use */ public DateFormatDayFormatter(@NonNull final DateTimeFormatter format) { this.dateFormat = format; } /** * {@inheritDoc} */
// Path: library/src/main/java/com/prolificinteractive/materialcalendarview/CalendarDay.java // public final class CalendarDay implements Parcelable { // // /** // * Everything is based on this variable for {@link CalendarDay}. // */ // @NonNull private final LocalDate date; // // /** // * @param year new instance's year // * @param month new instance's month as defined by {@linkplain java.util.Calendar} // * @param day new instance's day of month // */ // private CalendarDay(final int year, final int month, final int day) { // date = LocalDate.of(year, month, day); // } // // /** // * @param date {@link LocalDate} instance // */ // private CalendarDay(@NonNull final LocalDate date) { // this.date = date; // } // // /** // * Get a new instance set to today // * // * @return CalendarDay set to today's date // */ // @NonNull public static CalendarDay today() { // return from(LocalDate.now()); // } // // /** // * Get a new instance set to the specified day // * // * @param year new instance's year // * @param month new instance's month as defined by {@linkplain java.util.Calendar} // * @param day new instance's day of month // * @return CalendarDay set to the specified date // */ // @NonNull public static CalendarDay from(int year, int month, int day) { // return new CalendarDay(year, month, day); // } // // /** // * Get a new instance set to the specified day // * // * @param date {@linkplain LocalDate} to pull date information from. Passing null will return null // * @return CalendarDay set to the specified date // */ // public static CalendarDay from(@Nullable LocalDate date) { // if (date == null) { // return null; // } // return new CalendarDay(date); // } // // /** // * Get the year // * // * @return the year for this day // */ // public int getYear() { // return date.getYear(); // } // // /** // * Get the month, represented by values from {@linkplain LocalDate} // * // * @return the month of the year as defined by {@linkplain LocalDate} // */ // public int getMonth() { // return date.getMonthValue(); // } // // /** // * Get the day // * // * @return the day of the month for this day // */ // public int getDay() { // return date.getDayOfMonth(); // } // // /** // * Get this day as a {@linkplain LocalDate} // * // * @return a date with this days information // */ // @NonNull public LocalDate getDate() { // return date; // } // // /** // * Determine if this day is within a specified range // * // * @param minDate the earliest day, may be null // * @param maxDate the latest day, may be null // * @return true if the between (inclusive) the min and max dates. // */ // public boolean isInRange(@Nullable CalendarDay minDate, @Nullable CalendarDay maxDate) { // return !(minDate != null && minDate.isAfter(this)) && // !(maxDate != null && maxDate.isBefore(this)); // } // // /** // * Determine if this day is before the given instance // * // * @param other the other day to test // * @return true if this is before other, false if equal or after // */ // public boolean isBefore(@NonNull final CalendarDay other) { // return date.isBefore(other.getDate()); // } // // /** // * Determine if this day is after the given instance // * // * @param other the other day to test // * @return true if this is after other, false if equal or before // */ // public boolean isAfter(@NonNull final CalendarDay other) { // return date.isAfter(other.getDate()); // } // // @Override public boolean equals(Object o) { // return o instanceof CalendarDay && date.equals(((CalendarDay) o).getDate()); // } // // @Override // public int hashCode() { // return hashCode(date.getYear(), date.getMonthValue(), date.getDayOfMonth()); // } // // private static int hashCode(int year, int month, int day) { // //Should produce hashes like "20150401" // return (year * 10000) + (month * 100) + day; // } // // @Override // public String toString() { // return "CalendarDay{" + date.getYear() + "-" + date.getMonthValue() + "-" // + date.getDayOfMonth() + "}"; // } // // /* // * Parcelable Stuff // */ // // public CalendarDay(Parcel in) { // this(in.readInt(), in.readInt(), in.readInt()); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(date.getYear()); // dest.writeInt(date.getMonthValue()); // dest.writeInt(date.getDayOfMonth()); // } // // public static final Creator<CalendarDay> CREATOR = new Creator<CalendarDay>() { // public CalendarDay createFromParcel(Parcel in) { // return new CalendarDay(in); // } // // public CalendarDay[] newArray(int size) { // return new CalendarDay[size]; // } // }; // } // Path: library/src/main/java/com/prolificinteractive/materialcalendarview/format/DateFormatDayFormatter.java import android.support.annotation.NonNull; import com.prolificinteractive.materialcalendarview.CalendarDay; import java.text.DateFormat; import java.util.Locale; import org.threeten.bp.format.DateTimeFormatter; package com.prolificinteractive.materialcalendarview.format; /** * Format using a {@linkplain DateFormat} instance. */ public class DateFormatDayFormatter implements DayFormatter { private final DateTimeFormatter dateFormat; /** * Format using a default format */ public DateFormatDayFormatter() { this(DateTimeFormatter.ofPattern(DEFAULT_FORMAT, Locale.getDefault())); } /** * Format using a specific {@linkplain DateFormat} * * @param format the format to use */ public DateFormatDayFormatter(@NonNull final DateTimeFormatter format) { this.dateFormat = format; } /** * {@inheritDoc} */
@Override @NonNull public String format(@NonNull final CalendarDay day) {
prolificinteractive/material-calendarview
library/src/main/java/com/prolificinteractive/materialcalendarview/format/DayFormatter.java
// Path: library/src/main/java/com/prolificinteractive/materialcalendarview/CalendarDay.java // public final class CalendarDay implements Parcelable { // // /** // * Everything is based on this variable for {@link CalendarDay}. // */ // @NonNull private final LocalDate date; // // /** // * @param year new instance's year // * @param month new instance's month as defined by {@linkplain java.util.Calendar} // * @param day new instance's day of month // */ // private CalendarDay(final int year, final int month, final int day) { // date = LocalDate.of(year, month, day); // } // // /** // * @param date {@link LocalDate} instance // */ // private CalendarDay(@NonNull final LocalDate date) { // this.date = date; // } // // /** // * Get a new instance set to today // * // * @return CalendarDay set to today's date // */ // @NonNull public static CalendarDay today() { // return from(LocalDate.now()); // } // // /** // * Get a new instance set to the specified day // * // * @param year new instance's year // * @param month new instance's month as defined by {@linkplain java.util.Calendar} // * @param day new instance's day of month // * @return CalendarDay set to the specified date // */ // @NonNull public static CalendarDay from(int year, int month, int day) { // return new CalendarDay(year, month, day); // } // // /** // * Get a new instance set to the specified day // * // * @param date {@linkplain LocalDate} to pull date information from. Passing null will return null // * @return CalendarDay set to the specified date // */ // public static CalendarDay from(@Nullable LocalDate date) { // if (date == null) { // return null; // } // return new CalendarDay(date); // } // // /** // * Get the year // * // * @return the year for this day // */ // public int getYear() { // return date.getYear(); // } // // /** // * Get the month, represented by values from {@linkplain LocalDate} // * // * @return the month of the year as defined by {@linkplain LocalDate} // */ // public int getMonth() { // return date.getMonthValue(); // } // // /** // * Get the day // * // * @return the day of the month for this day // */ // public int getDay() { // return date.getDayOfMonth(); // } // // /** // * Get this day as a {@linkplain LocalDate} // * // * @return a date with this days information // */ // @NonNull public LocalDate getDate() { // return date; // } // // /** // * Determine if this day is within a specified range // * // * @param minDate the earliest day, may be null // * @param maxDate the latest day, may be null // * @return true if the between (inclusive) the min and max dates. // */ // public boolean isInRange(@Nullable CalendarDay minDate, @Nullable CalendarDay maxDate) { // return !(minDate != null && minDate.isAfter(this)) && // !(maxDate != null && maxDate.isBefore(this)); // } // // /** // * Determine if this day is before the given instance // * // * @param other the other day to test // * @return true if this is before other, false if equal or after // */ // public boolean isBefore(@NonNull final CalendarDay other) { // return date.isBefore(other.getDate()); // } // // /** // * Determine if this day is after the given instance // * // * @param other the other day to test // * @return true if this is after other, false if equal or before // */ // public boolean isAfter(@NonNull final CalendarDay other) { // return date.isAfter(other.getDate()); // } // // @Override public boolean equals(Object o) { // return o instanceof CalendarDay && date.equals(((CalendarDay) o).getDate()); // } // // @Override // public int hashCode() { // return hashCode(date.getYear(), date.getMonthValue(), date.getDayOfMonth()); // } // // private static int hashCode(int year, int month, int day) { // //Should produce hashes like "20150401" // return (year * 10000) + (month * 100) + day; // } // // @Override // public String toString() { // return "CalendarDay{" + date.getYear() + "-" + date.getMonthValue() + "-" // + date.getDayOfMonth() + "}"; // } // // /* // * Parcelable Stuff // */ // // public CalendarDay(Parcel in) { // this(in.readInt(), in.readInt(), in.readInt()); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(date.getYear()); // dest.writeInt(date.getMonthValue()); // dest.writeInt(date.getDayOfMonth()); // } // // public static final Creator<CalendarDay> CREATOR = new Creator<CalendarDay>() { // public CalendarDay createFromParcel(Parcel in) { // return new CalendarDay(in); // } // // public CalendarDay[] newArray(int size) { // return new CalendarDay[size]; // } // }; // }
import android.support.annotation.NonNull; import com.prolificinteractive.materialcalendarview.CalendarDay; import java.text.SimpleDateFormat;
package com.prolificinteractive.materialcalendarview.format; /** * Supply labels for a given day. Default implementation is to format using a {@linkplain SimpleDateFormat} */ public interface DayFormatter { /** * Default format for displaying the day. */ String DEFAULT_FORMAT = "d"; /** * Default implementation used by {@linkplain com.prolificinteractive.materialcalendarview.MaterialCalendarView} */ DayFormatter DEFAULT = new DateFormatDayFormatter(); /** * Format a given day into a string * * @param day the day * @return a label for the day */
// Path: library/src/main/java/com/prolificinteractive/materialcalendarview/CalendarDay.java // public final class CalendarDay implements Parcelable { // // /** // * Everything is based on this variable for {@link CalendarDay}. // */ // @NonNull private final LocalDate date; // // /** // * @param year new instance's year // * @param month new instance's month as defined by {@linkplain java.util.Calendar} // * @param day new instance's day of month // */ // private CalendarDay(final int year, final int month, final int day) { // date = LocalDate.of(year, month, day); // } // // /** // * @param date {@link LocalDate} instance // */ // private CalendarDay(@NonNull final LocalDate date) { // this.date = date; // } // // /** // * Get a new instance set to today // * // * @return CalendarDay set to today's date // */ // @NonNull public static CalendarDay today() { // return from(LocalDate.now()); // } // // /** // * Get a new instance set to the specified day // * // * @param year new instance's year // * @param month new instance's month as defined by {@linkplain java.util.Calendar} // * @param day new instance's day of month // * @return CalendarDay set to the specified date // */ // @NonNull public static CalendarDay from(int year, int month, int day) { // return new CalendarDay(year, month, day); // } // // /** // * Get a new instance set to the specified day // * // * @param date {@linkplain LocalDate} to pull date information from. Passing null will return null // * @return CalendarDay set to the specified date // */ // public static CalendarDay from(@Nullable LocalDate date) { // if (date == null) { // return null; // } // return new CalendarDay(date); // } // // /** // * Get the year // * // * @return the year for this day // */ // public int getYear() { // return date.getYear(); // } // // /** // * Get the month, represented by values from {@linkplain LocalDate} // * // * @return the month of the year as defined by {@linkplain LocalDate} // */ // public int getMonth() { // return date.getMonthValue(); // } // // /** // * Get the day // * // * @return the day of the month for this day // */ // public int getDay() { // return date.getDayOfMonth(); // } // // /** // * Get this day as a {@linkplain LocalDate} // * // * @return a date with this days information // */ // @NonNull public LocalDate getDate() { // return date; // } // // /** // * Determine if this day is within a specified range // * // * @param minDate the earliest day, may be null // * @param maxDate the latest day, may be null // * @return true if the between (inclusive) the min and max dates. // */ // public boolean isInRange(@Nullable CalendarDay minDate, @Nullable CalendarDay maxDate) { // return !(minDate != null && minDate.isAfter(this)) && // !(maxDate != null && maxDate.isBefore(this)); // } // // /** // * Determine if this day is before the given instance // * // * @param other the other day to test // * @return true if this is before other, false if equal or after // */ // public boolean isBefore(@NonNull final CalendarDay other) { // return date.isBefore(other.getDate()); // } // // /** // * Determine if this day is after the given instance // * // * @param other the other day to test // * @return true if this is after other, false if equal or before // */ // public boolean isAfter(@NonNull final CalendarDay other) { // return date.isAfter(other.getDate()); // } // // @Override public boolean equals(Object o) { // return o instanceof CalendarDay && date.equals(((CalendarDay) o).getDate()); // } // // @Override // public int hashCode() { // return hashCode(date.getYear(), date.getMonthValue(), date.getDayOfMonth()); // } // // private static int hashCode(int year, int month, int day) { // //Should produce hashes like "20150401" // return (year * 10000) + (month * 100) + day; // } // // @Override // public String toString() { // return "CalendarDay{" + date.getYear() + "-" + date.getMonthValue() + "-" // + date.getDayOfMonth() + "}"; // } // // /* // * Parcelable Stuff // */ // // public CalendarDay(Parcel in) { // this(in.readInt(), in.readInt(), in.readInt()); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(date.getYear()); // dest.writeInt(date.getMonthValue()); // dest.writeInt(date.getDayOfMonth()); // } // // public static final Creator<CalendarDay> CREATOR = new Creator<CalendarDay>() { // public CalendarDay createFromParcel(Parcel in) { // return new CalendarDay(in); // } // // public CalendarDay[] newArray(int size) { // return new CalendarDay[size]; // } // }; // } // Path: library/src/main/java/com/prolificinteractive/materialcalendarview/format/DayFormatter.java import android.support.annotation.NonNull; import com.prolificinteractive.materialcalendarview.CalendarDay; import java.text.SimpleDateFormat; package com.prolificinteractive.materialcalendarview.format; /** * Supply labels for a given day. Default implementation is to format using a {@linkplain SimpleDateFormat} */ public interface DayFormatter { /** * Default format for displaying the day. */ String DEFAULT_FORMAT = "d"; /** * Default implementation used by {@linkplain com.prolificinteractive.materialcalendarview.MaterialCalendarView} */ DayFormatter DEFAULT = new DateFormatDayFormatter(); /** * Format a given day into a string * * @param day the day * @return a label for the day */
@NonNull String format(@NonNull CalendarDay day);
prolificinteractive/material-calendarview
library/src/main/java/com/prolificinteractive/materialcalendarview/TitleChanger.java
// Path: library/src/main/java/com/prolificinteractive/materialcalendarview/format/TitleFormatter.java // public interface TitleFormatter { // // String DEFAULT_FORMAT = "LLLL yyyy"; // // TitleFormatter DEFAULT = new DateFormatTitleFormatter(); // // /** // * Converts the supplied day to a suitable month/year title // * // * @param day the day containing relevant month and year information // * @return a label to display for the given month/year // */ // CharSequence format(CalendarDay day); // }
import android.animation.Animator; import android.content.res.Resources; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.text.TextUtils; import android.util.TypedValue; import android.view.ViewPropertyAnimator; import android.view.animation.DecelerateInterpolator; import android.view.animation.Interpolator; import android.widget.TextView; import com.prolificinteractive.materialcalendarview.format.TitleFormatter;
package com.prolificinteractive.materialcalendarview; class TitleChanger { public static final int DEFAULT_ANIMATION_DELAY = 400; public static final int DEFAULT_Y_TRANSLATION_DP = 20; private final TextView title;
// Path: library/src/main/java/com/prolificinteractive/materialcalendarview/format/TitleFormatter.java // public interface TitleFormatter { // // String DEFAULT_FORMAT = "LLLL yyyy"; // // TitleFormatter DEFAULT = new DateFormatTitleFormatter(); // // /** // * Converts the supplied day to a suitable month/year title // * // * @param day the day containing relevant month and year information // * @return a label to display for the given month/year // */ // CharSequence format(CalendarDay day); // } // Path: library/src/main/java/com/prolificinteractive/materialcalendarview/TitleChanger.java import android.animation.Animator; import android.content.res.Resources; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.text.TextUtils; import android.util.TypedValue; import android.view.ViewPropertyAnimator; import android.view.animation.DecelerateInterpolator; import android.view.animation.Interpolator; import android.widget.TextView; import com.prolificinteractive.materialcalendarview.format.TitleFormatter; package com.prolificinteractive.materialcalendarview; class TitleChanger { public static final int DEFAULT_ANIMATION_DELAY = 400; public static final int DEFAULT_Y_TRANSLATION_DP = 20; private final TextView title;
@NonNull private TitleFormatter titleFormatter = TitleFormatter.DEFAULT;
mikelduke/LedTable
RPi-Java-LedTable/src/net/mdp3/java/rpi/ledtable/webservice/WebserviceCommands.java
// Path: RPi-Java-LedTable/src/net/mdp3/java/util/xml/DomXml.java // public interface DomXml { // public Element toXml(Document doc); // public void fromXml(Element e) throws Exception; // } // // Path: RPi-Java-LedTable/src/net/mdp3/java/util/xml/XmlHelper.java // public class XmlHelper { // // /** // * Method to make adding repetitive text nodes to an element easier. // * // * @param doc Java DOM Doc which is the items get added to // * @param name Name of the new element // * @param val Text Value of the new element // * @return Element containing a value ready to append to another Element // */ // public static Element newTextElement(Document doc, String name, Object val) { // Element e = doc.createElement(name); // e.appendChild(doc.createTextNode(val.toString())); // return e; // } // // /** // * Converts a Java DOM Xml Element to a String for simple output to // * console, logs, or files. // * // * @param e Element to convert // * @return String representation of element // * @throws TransformerFactoryConfigurationError // * @throws TransformerException // */ // public static String elementToString(Element e) throws TransformerFactoryConfigurationError, TransformerException { // String ret = ""; // Transformer transformer; // // transformer = TransformerFactory.newInstance().newTransformer(); // transformer.setOutputProperty(OutputKeys.INDENT, "yes"); // // StreamResult result = new StreamResult(new StringWriter()); // DOMSource source = new DOMSource(e); // transformer.transform(source, result); // // ret = result.getWriter().toString(); // // return ret; // } // // /** // * Returns a new Java DOM Doc object for use with elements. This doc should // * not be used for saving it is just used for internal copy/move/load type // * functions. // * // * @return // */ // public static Document getNewDoc() { // DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); // DocumentBuilder docBuilder; // // try { // docBuilder = docFactory.newDocumentBuilder(); // // // root elements // Document doc = docBuilder.newDocument(); // //Element rootElement = doc.createElement(rootElementName); // //doc.appendChild(rootElement); // // return doc; // } catch (ParserConfigurationException e) { // e.printStackTrace(); // } // // return null; // } // // public static void saveDocument(Document doc, File file) throws TransformerException { // TransformerFactory transformerFactory = TransformerFactory.newInstance(); // Transformer transformer = transformerFactory.newTransformer(); // DOMSource source = new DOMSource(doc); // StreamResult result = new StreamResult(file); // // transformer.transform(source, result); // } // // /** // * Reads in an xml file and returns the root element // * // * @param fileLocation // * @return // * @throws ParserConfigurationException // * @throws SAXException // * @throws IOException // */ // public static Element readXmlFile(String fileLocation) throws ParserConfigurationException, SAXException, IOException { // File f = new File(fileLocation); // return XmlHelper.readXmlFile(f); // } // // /** // * Reads in an xml file and returns the root Element // * // * @param f // * @return // * @throws ParserConfigurationException // * @throws SAXException // * @throws IOException // */ // public static Element readXmlFile(File f) throws ParserConfigurationException, SAXException, IOException { // Element retE = null; // // DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); // DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); // Document doc = dBuilder.parse(f); // // doc.getDocumentElement().normalize(); // // retE = doc.getDocumentElement(); // // return retE; // } // }
import org.w3c.dom.Document; import org.w3c.dom.Element; import net.mdp3.java.util.xml.DomXml; import net.mdp3.java.util.xml.XmlHelper;
/** * */ package net.mdp3.java.rpi.ledtable.webservice; /** * @author Mikel * */ public class WebserviceCommands { public static final String WS_CMD = "cmd";
// Path: RPi-Java-LedTable/src/net/mdp3/java/util/xml/DomXml.java // public interface DomXml { // public Element toXml(Document doc); // public void fromXml(Element e) throws Exception; // } // // Path: RPi-Java-LedTable/src/net/mdp3/java/util/xml/XmlHelper.java // public class XmlHelper { // // /** // * Method to make adding repetitive text nodes to an element easier. // * // * @param doc Java DOM Doc which is the items get added to // * @param name Name of the new element // * @param val Text Value of the new element // * @return Element containing a value ready to append to another Element // */ // public static Element newTextElement(Document doc, String name, Object val) { // Element e = doc.createElement(name); // e.appendChild(doc.createTextNode(val.toString())); // return e; // } // // /** // * Converts a Java DOM Xml Element to a String for simple output to // * console, logs, or files. // * // * @param e Element to convert // * @return String representation of element // * @throws TransformerFactoryConfigurationError // * @throws TransformerException // */ // public static String elementToString(Element e) throws TransformerFactoryConfigurationError, TransformerException { // String ret = ""; // Transformer transformer; // // transformer = TransformerFactory.newInstance().newTransformer(); // transformer.setOutputProperty(OutputKeys.INDENT, "yes"); // // StreamResult result = new StreamResult(new StringWriter()); // DOMSource source = new DOMSource(e); // transformer.transform(source, result); // // ret = result.getWriter().toString(); // // return ret; // } // // /** // * Returns a new Java DOM Doc object for use with elements. This doc should // * not be used for saving it is just used for internal copy/move/load type // * functions. // * // * @return // */ // public static Document getNewDoc() { // DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); // DocumentBuilder docBuilder; // // try { // docBuilder = docFactory.newDocumentBuilder(); // // // root elements // Document doc = docBuilder.newDocument(); // //Element rootElement = doc.createElement(rootElementName); // //doc.appendChild(rootElement); // // return doc; // } catch (ParserConfigurationException e) { // e.printStackTrace(); // } // // return null; // } // // public static void saveDocument(Document doc, File file) throws TransformerException { // TransformerFactory transformerFactory = TransformerFactory.newInstance(); // Transformer transformer = transformerFactory.newTransformer(); // DOMSource source = new DOMSource(doc); // StreamResult result = new StreamResult(file); // // transformer.transform(source, result); // } // // /** // * Reads in an xml file and returns the root element // * // * @param fileLocation // * @return // * @throws ParserConfigurationException // * @throws SAXException // * @throws IOException // */ // public static Element readXmlFile(String fileLocation) throws ParserConfigurationException, SAXException, IOException { // File f = new File(fileLocation); // return XmlHelper.readXmlFile(f); // } // // /** // * Reads in an xml file and returns the root Element // * // * @param f // * @return // * @throws ParserConfigurationException // * @throws SAXException // * @throws IOException // */ // public static Element readXmlFile(File f) throws ParserConfigurationException, SAXException, IOException { // Element retE = null; // // DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); // DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); // Document doc = dBuilder.parse(f); // // doc.getDocumentElement().normalize(); // // retE = doc.getDocumentElement(); // // return retE; // } // } // Path: RPi-Java-LedTable/src/net/mdp3/java/rpi/ledtable/webservice/WebserviceCommands.java import org.w3c.dom.Document; import org.w3c.dom.Element; import net.mdp3.java.util.xml.DomXml; import net.mdp3.java.util.xml.XmlHelper; /** * */ package net.mdp3.java.rpi.ledtable.webservice; /** * @author Mikel * */ public class WebserviceCommands { public static final String WS_CMD = "cmd";
public static enum WebserviceCommand implements DomXml {
mikelduke/LedTable
RPi-Java-LedTable/src/net/mdp3/java/rpi/ledtable/webservice/WebserviceCommands.java
// Path: RPi-Java-LedTable/src/net/mdp3/java/util/xml/DomXml.java // public interface DomXml { // public Element toXml(Document doc); // public void fromXml(Element e) throws Exception; // } // // Path: RPi-Java-LedTable/src/net/mdp3/java/util/xml/XmlHelper.java // public class XmlHelper { // // /** // * Method to make adding repetitive text nodes to an element easier. // * // * @param doc Java DOM Doc which is the items get added to // * @param name Name of the new element // * @param val Text Value of the new element // * @return Element containing a value ready to append to another Element // */ // public static Element newTextElement(Document doc, String name, Object val) { // Element e = doc.createElement(name); // e.appendChild(doc.createTextNode(val.toString())); // return e; // } // // /** // * Converts a Java DOM Xml Element to a String for simple output to // * console, logs, or files. // * // * @param e Element to convert // * @return String representation of element // * @throws TransformerFactoryConfigurationError // * @throws TransformerException // */ // public static String elementToString(Element e) throws TransformerFactoryConfigurationError, TransformerException { // String ret = ""; // Transformer transformer; // // transformer = TransformerFactory.newInstance().newTransformer(); // transformer.setOutputProperty(OutputKeys.INDENT, "yes"); // // StreamResult result = new StreamResult(new StringWriter()); // DOMSource source = new DOMSource(e); // transformer.transform(source, result); // // ret = result.getWriter().toString(); // // return ret; // } // // /** // * Returns a new Java DOM Doc object for use with elements. This doc should // * not be used for saving it is just used for internal copy/move/load type // * functions. // * // * @return // */ // public static Document getNewDoc() { // DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); // DocumentBuilder docBuilder; // // try { // docBuilder = docFactory.newDocumentBuilder(); // // // root elements // Document doc = docBuilder.newDocument(); // //Element rootElement = doc.createElement(rootElementName); // //doc.appendChild(rootElement); // // return doc; // } catch (ParserConfigurationException e) { // e.printStackTrace(); // } // // return null; // } // // public static void saveDocument(Document doc, File file) throws TransformerException { // TransformerFactory transformerFactory = TransformerFactory.newInstance(); // Transformer transformer = transformerFactory.newTransformer(); // DOMSource source = new DOMSource(doc); // StreamResult result = new StreamResult(file); // // transformer.transform(source, result); // } // // /** // * Reads in an xml file and returns the root element // * // * @param fileLocation // * @return // * @throws ParserConfigurationException // * @throws SAXException // * @throws IOException // */ // public static Element readXmlFile(String fileLocation) throws ParserConfigurationException, SAXException, IOException { // File f = new File(fileLocation); // return XmlHelper.readXmlFile(f); // } // // /** // * Reads in an xml file and returns the root Element // * // * @param f // * @return // * @throws ParserConfigurationException // * @throws SAXException // * @throws IOException // */ // public static Element readXmlFile(File f) throws ParserConfigurationException, SAXException, IOException { // Element retE = null; // // DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); // DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); // Document doc = dBuilder.parse(f); // // doc.getDocumentElement().normalize(); // // retE = doc.getDocumentElement(); // // return retE; // } // }
import org.w3c.dom.Document; import org.w3c.dom.Element; import net.mdp3.java.util.xml.DomXml; import net.mdp3.java.util.xml.XmlHelper;
/** * */ package net.mdp3.java.rpi.ledtable.webservice; /** * @author Mikel * */ public class WebserviceCommands { public static final String WS_CMD = "cmd"; public static enum WebserviceCommand implements DomXml { COMMAND_LIST, MODE, SAVE, CURRENT_SELECTION_INFO, EFFECT_INFO, EFFECT_LIST, PLAYLIST, PLAYLIST_INFO, FILE; public static final String NODE_NAME = "Command"; public static final String NODE_CMD_NAME = "Name"; @Override public Element toXml(Document doc) { Element wsCmdE = doc.createElement(WebserviceCommand.NODE_NAME);
// Path: RPi-Java-LedTable/src/net/mdp3/java/util/xml/DomXml.java // public interface DomXml { // public Element toXml(Document doc); // public void fromXml(Element e) throws Exception; // } // // Path: RPi-Java-LedTable/src/net/mdp3/java/util/xml/XmlHelper.java // public class XmlHelper { // // /** // * Method to make adding repetitive text nodes to an element easier. // * // * @param doc Java DOM Doc which is the items get added to // * @param name Name of the new element // * @param val Text Value of the new element // * @return Element containing a value ready to append to another Element // */ // public static Element newTextElement(Document doc, String name, Object val) { // Element e = doc.createElement(name); // e.appendChild(doc.createTextNode(val.toString())); // return e; // } // // /** // * Converts a Java DOM Xml Element to a String for simple output to // * console, logs, or files. // * // * @param e Element to convert // * @return String representation of element // * @throws TransformerFactoryConfigurationError // * @throws TransformerException // */ // public static String elementToString(Element e) throws TransformerFactoryConfigurationError, TransformerException { // String ret = ""; // Transformer transformer; // // transformer = TransformerFactory.newInstance().newTransformer(); // transformer.setOutputProperty(OutputKeys.INDENT, "yes"); // // StreamResult result = new StreamResult(new StringWriter()); // DOMSource source = new DOMSource(e); // transformer.transform(source, result); // // ret = result.getWriter().toString(); // // return ret; // } // // /** // * Returns a new Java DOM Doc object for use with elements. This doc should // * not be used for saving it is just used for internal copy/move/load type // * functions. // * // * @return // */ // public static Document getNewDoc() { // DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); // DocumentBuilder docBuilder; // // try { // docBuilder = docFactory.newDocumentBuilder(); // // // root elements // Document doc = docBuilder.newDocument(); // //Element rootElement = doc.createElement(rootElementName); // //doc.appendChild(rootElement); // // return doc; // } catch (ParserConfigurationException e) { // e.printStackTrace(); // } // // return null; // } // // public static void saveDocument(Document doc, File file) throws TransformerException { // TransformerFactory transformerFactory = TransformerFactory.newInstance(); // Transformer transformer = transformerFactory.newTransformer(); // DOMSource source = new DOMSource(doc); // StreamResult result = new StreamResult(file); // // transformer.transform(source, result); // } // // /** // * Reads in an xml file and returns the root element // * // * @param fileLocation // * @return // * @throws ParserConfigurationException // * @throws SAXException // * @throws IOException // */ // public static Element readXmlFile(String fileLocation) throws ParserConfigurationException, SAXException, IOException { // File f = new File(fileLocation); // return XmlHelper.readXmlFile(f); // } // // /** // * Reads in an xml file and returns the root Element // * // * @param f // * @return // * @throws ParserConfigurationException // * @throws SAXException // * @throws IOException // */ // public static Element readXmlFile(File f) throws ParserConfigurationException, SAXException, IOException { // Element retE = null; // // DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); // DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); // Document doc = dBuilder.parse(f); // // doc.getDocumentElement().normalize(); // // retE = doc.getDocumentElement(); // // return retE; // } // } // Path: RPi-Java-LedTable/src/net/mdp3/java/rpi/ledtable/webservice/WebserviceCommands.java import org.w3c.dom.Document; import org.w3c.dom.Element; import net.mdp3.java.util.xml.DomXml; import net.mdp3.java.util.xml.XmlHelper; /** * */ package net.mdp3.java.rpi.ledtable.webservice; /** * @author Mikel * */ public class WebserviceCommands { public static final String WS_CMD = "cmd"; public static enum WebserviceCommand implements DomXml { COMMAND_LIST, MODE, SAVE, CURRENT_SELECTION_INFO, EFFECT_INFO, EFFECT_LIST, PLAYLIST, PLAYLIST_INFO, FILE; public static final String NODE_NAME = "Command"; public static final String NODE_CMD_NAME = "Name"; @Override public Element toXml(Document doc) { Element wsCmdE = doc.createElement(WebserviceCommand.NODE_NAME);
wsCmdE.appendChild(XmlHelper.newTextElement(doc, WebserviceCommand.NODE_CMD_NAME, this.name()));
mikelduke/LedTable
RPi-Java-LedTable/src/net/mdp3/java/rpi/ledtable/table/TableFile.java
// Path: RPi-Java-LedTable/src/net/mdp3/java/rpi/ledtable/LedTable_Settings.java // public class LedTable_Settings { // private final static Logger LOG = Logger.getLogger(LedTable_Settings.class.getName()); // private final static String name = "LedTable_Settings"; // // //Default settings if not overwritten in settings.txt // public static boolean enableGUI = true; // public static int guiW = 504; // public static int guiH = 336; // public static boolean flipY = true; // // public static String wsName = "/ledtable"; // public static int wsPort = 85; // // public static boolean enableTableOutput = false; // public static String tableMode = "SPI"; // public static String serialPort = "/dev/ttyACM0"; // public static int serialBaud = 57600; // // public static int spiSpeed = 1953000; // // public static String outputFile = "/dev/spidev0.0"; // // public static int ledY = 8; // public static int ledX = 12; // public static boolean snakedLeds = true; // // public static boolean debug = true; // // public static long midiUpdateDelay = 100; // // public static String defaultSaveFolder = ""; // public static String defaultFilePrefix = "LedTable"; // // public static boolean remoteWS = false; // public static String remoteWSURL = ""; // // public static boolean autoplaySelection = false; // public static String defaultSelectionFile = ""; // // public static boolean autoplayPlaylist = false; // public static String defaultPlaylistFile = ""; // // /** // * Loads the settings to the static variables using the mdp3_Util // * Settings methods // * // * Currently hardcoded to use filename of settings.txt // */ // public static void loadSettings() { // loadSettings("settings.txt"); // } // // /** // * Loads the settings to the static variables using the mdp3_Util // * Settings methods // * // * @param fileName // */ // public static void loadSettings(String fileName) { // LOG.entering(name, "loadSettings", "Filename: " + fileName); // // SettingsLoader set = new SettingsLoader(LedTable_Settings.class, false); // // //URL url = SettingsTest.class.getResource("SettingsTest.txt"); // //File file = new File(url.getPath()); // set.loadSettings(fileName); // // checkSettings(); // // LOG.exiting(name, "loadSettings"); // } // // /** // * Method to run to bounds check variables after being loaded from file // */ // public static void checkSettings() { // //Check bounds, must have atleast 1 row of each // if (ledX < 1) { // LOG.warning("Error in settings: ledX < 1; changing value to ledX = 1"); // ledX = 1; // } // // if (ledY < 1) { // LOG.warning("Error in settings: ledY < 1; changing value to ledY = 1"); // ledY = 1; // } // } // }
import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import net.mdp3.java.rpi.ledtable.LedTable_Settings;
package net.mdp3.java.rpi.ledtable.table; public class TableFile extends Table { private final static String name = "LedTable_CMD"; private File file = null; private FileOutputStream fos = null; public TableFile() { super();
// Path: RPi-Java-LedTable/src/net/mdp3/java/rpi/ledtable/LedTable_Settings.java // public class LedTable_Settings { // private final static Logger LOG = Logger.getLogger(LedTable_Settings.class.getName()); // private final static String name = "LedTable_Settings"; // // //Default settings if not overwritten in settings.txt // public static boolean enableGUI = true; // public static int guiW = 504; // public static int guiH = 336; // public static boolean flipY = true; // // public static String wsName = "/ledtable"; // public static int wsPort = 85; // // public static boolean enableTableOutput = false; // public static String tableMode = "SPI"; // public static String serialPort = "/dev/ttyACM0"; // public static int serialBaud = 57600; // // public static int spiSpeed = 1953000; // // public static String outputFile = "/dev/spidev0.0"; // // public static int ledY = 8; // public static int ledX = 12; // public static boolean snakedLeds = true; // // public static boolean debug = true; // // public static long midiUpdateDelay = 100; // // public static String defaultSaveFolder = ""; // public static String defaultFilePrefix = "LedTable"; // // public static boolean remoteWS = false; // public static String remoteWSURL = ""; // // public static boolean autoplaySelection = false; // public static String defaultSelectionFile = ""; // // public static boolean autoplayPlaylist = false; // public static String defaultPlaylistFile = ""; // // /** // * Loads the settings to the static variables using the mdp3_Util // * Settings methods // * // * Currently hardcoded to use filename of settings.txt // */ // public static void loadSettings() { // loadSettings("settings.txt"); // } // // /** // * Loads the settings to the static variables using the mdp3_Util // * Settings methods // * // * @param fileName // */ // public static void loadSettings(String fileName) { // LOG.entering(name, "loadSettings", "Filename: " + fileName); // // SettingsLoader set = new SettingsLoader(LedTable_Settings.class, false); // // //URL url = SettingsTest.class.getResource("SettingsTest.txt"); // //File file = new File(url.getPath()); // set.loadSettings(fileName); // // checkSettings(); // // LOG.exiting(name, "loadSettings"); // } // // /** // * Method to run to bounds check variables after being loaded from file // */ // public static void checkSettings() { // //Check bounds, must have atleast 1 row of each // if (ledX < 1) { // LOG.warning("Error in settings: ledX < 1; changing value to ledX = 1"); // ledX = 1; // } // // if (ledY < 1) { // LOG.warning("Error in settings: ledY < 1; changing value to ledY = 1"); // ledY = 1; // } // } // } // Path: RPi-Java-LedTable/src/net/mdp3/java/rpi/ledtable/table/TableFile.java import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import net.mdp3.java.rpi.ledtable.LedTable_Settings; package net.mdp3.java.rpi.ledtable.table; public class TableFile extends Table { private final static String name = "LedTable_CMD"; private File file = null; private FileOutputStream fos = null; public TableFile() { super();
file = new File(LedTable_Settings.outputFile);
mikelduke/LedTable
RPi-Java-LedTable/src/net/mdp3/java/rpi/ledtable/gui/TablePanel.java
// Path: RPi-Java-LedTable/src/net/mdp3/java/rpi/ledtable/LedTable_Settings.java // public class LedTable_Settings { // private final static Logger LOG = Logger.getLogger(LedTable_Settings.class.getName()); // private final static String name = "LedTable_Settings"; // // //Default settings if not overwritten in settings.txt // public static boolean enableGUI = true; // public static int guiW = 504; // public static int guiH = 336; // public static boolean flipY = true; // // public static String wsName = "/ledtable"; // public static int wsPort = 85; // // public static boolean enableTableOutput = false; // public static String tableMode = "SPI"; // public static String serialPort = "/dev/ttyACM0"; // public static int serialBaud = 57600; // // public static int spiSpeed = 1953000; // // public static String outputFile = "/dev/spidev0.0"; // // public static int ledY = 8; // public static int ledX = 12; // public static boolean snakedLeds = true; // // public static boolean debug = true; // // public static long midiUpdateDelay = 100; // // public static String defaultSaveFolder = ""; // public static String defaultFilePrefix = "LedTable"; // // public static boolean remoteWS = false; // public static String remoteWSURL = ""; // // public static boolean autoplaySelection = false; // public static String defaultSelectionFile = ""; // // public static boolean autoplayPlaylist = false; // public static String defaultPlaylistFile = ""; // // /** // * Loads the settings to the static variables using the mdp3_Util // * Settings methods // * // * Currently hardcoded to use filename of settings.txt // */ // public static void loadSettings() { // loadSettings("settings.txt"); // } // // /** // * Loads the settings to the static variables using the mdp3_Util // * Settings methods // * // * @param fileName // */ // public static void loadSettings(String fileName) { // LOG.entering(name, "loadSettings", "Filename: " + fileName); // // SettingsLoader set = new SettingsLoader(LedTable_Settings.class, false); // // //URL url = SettingsTest.class.getResource("SettingsTest.txt"); // //File file = new File(url.getPath()); // set.loadSettings(fileName); // // checkSettings(); // // LOG.exiting(name, "loadSettings"); // } // // /** // * Method to run to bounds check variables after being loaded from file // */ // public static void checkSettings() { // //Check bounds, must have atleast 1 row of each // if (ledX < 1) { // LOG.warning("Error in settings: ledX < 1; changing value to ledX = 1"); // ledX = 1; // } // // if (ledY < 1) { // LOG.warning("Error in settings: ledY < 1; changing value to ledY = 1"); // ledY = 1; // } // } // } // // Path: RPi-Java-LedTable/src/net/mdp3/java/rpi/ledtable/table/WriteListener.java // public interface WriteListener { // public void writeEvent(byte[] bAr); // }
import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.logging.Logger; import javax.imageio.ImageIO; import javax.swing.JPanel; import net.mdp3.java.rpi.ledtable.LedTable_Settings; import net.mdp3.java.rpi.ledtable.table.WriteListener;
/** * */ package net.mdp3.java.rpi.ledtable.gui; /** * @author Mikel * */ public class TablePanel extends JPanel implements WriteListener { private final static Logger LOG = Logger.getLogger(TablePanel.class.getName()); private final static String name = "TablePanel"; /** * */ private static final long serialVersionUID = 4720593039682897655L;
// Path: RPi-Java-LedTable/src/net/mdp3/java/rpi/ledtable/LedTable_Settings.java // public class LedTable_Settings { // private final static Logger LOG = Logger.getLogger(LedTable_Settings.class.getName()); // private final static String name = "LedTable_Settings"; // // //Default settings if not overwritten in settings.txt // public static boolean enableGUI = true; // public static int guiW = 504; // public static int guiH = 336; // public static boolean flipY = true; // // public static String wsName = "/ledtable"; // public static int wsPort = 85; // // public static boolean enableTableOutput = false; // public static String tableMode = "SPI"; // public static String serialPort = "/dev/ttyACM0"; // public static int serialBaud = 57600; // // public static int spiSpeed = 1953000; // // public static String outputFile = "/dev/spidev0.0"; // // public static int ledY = 8; // public static int ledX = 12; // public static boolean snakedLeds = true; // // public static boolean debug = true; // // public static long midiUpdateDelay = 100; // // public static String defaultSaveFolder = ""; // public static String defaultFilePrefix = "LedTable"; // // public static boolean remoteWS = false; // public static String remoteWSURL = ""; // // public static boolean autoplaySelection = false; // public static String defaultSelectionFile = ""; // // public static boolean autoplayPlaylist = false; // public static String defaultPlaylistFile = ""; // // /** // * Loads the settings to the static variables using the mdp3_Util // * Settings methods // * // * Currently hardcoded to use filename of settings.txt // */ // public static void loadSettings() { // loadSettings("settings.txt"); // } // // /** // * Loads the settings to the static variables using the mdp3_Util // * Settings methods // * // * @param fileName // */ // public static void loadSettings(String fileName) { // LOG.entering(name, "loadSettings", "Filename: " + fileName); // // SettingsLoader set = new SettingsLoader(LedTable_Settings.class, false); // // //URL url = SettingsTest.class.getResource("SettingsTest.txt"); // //File file = new File(url.getPath()); // set.loadSettings(fileName); // // checkSettings(); // // LOG.exiting(name, "loadSettings"); // } // // /** // * Method to run to bounds check variables after being loaded from file // */ // public static void checkSettings() { // //Check bounds, must have atleast 1 row of each // if (ledX < 1) { // LOG.warning("Error in settings: ledX < 1; changing value to ledX = 1"); // ledX = 1; // } // // if (ledY < 1) { // LOG.warning("Error in settings: ledY < 1; changing value to ledY = 1"); // ledY = 1; // } // } // } // // Path: RPi-Java-LedTable/src/net/mdp3/java/rpi/ledtable/table/WriteListener.java // public interface WriteListener { // public void writeEvent(byte[] bAr); // } // Path: RPi-Java-LedTable/src/net/mdp3/java/rpi/ledtable/gui/TablePanel.java import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.logging.Logger; import javax.imageio.ImageIO; import javax.swing.JPanel; import net.mdp3.java.rpi.ledtable.LedTable_Settings; import net.mdp3.java.rpi.ledtable.table.WriteListener; /** * */ package net.mdp3.java.rpi.ledtable.gui; /** * @author Mikel * */ public class TablePanel extends JPanel implements WriteListener { private final static Logger LOG = Logger.getLogger(TablePanel.class.getName()); private final static String name = "TablePanel"; /** * */ private static final long serialVersionUID = 4720593039682897655L;
private int pixelW = (LedTable_Settings.guiW - 10) / LedTable_Settings.ledX;
mikelduke/LedTable
RPi-Java-LedTable/src/net/mdp3/java/rpi/ledtable/table/TableCMD.java
// Path: RPi-Java-LedTable/src/net/mdp3/java/rpi/ledtable/LedTable_Settings.java // public class LedTable_Settings { // private final static Logger LOG = Logger.getLogger(LedTable_Settings.class.getName()); // private final static String name = "LedTable_Settings"; // // //Default settings if not overwritten in settings.txt // public static boolean enableGUI = true; // public static int guiW = 504; // public static int guiH = 336; // public static boolean flipY = true; // // public static String wsName = "/ledtable"; // public static int wsPort = 85; // // public static boolean enableTableOutput = false; // public static String tableMode = "SPI"; // public static String serialPort = "/dev/ttyACM0"; // public static int serialBaud = 57600; // // public static int spiSpeed = 1953000; // // public static String outputFile = "/dev/spidev0.0"; // // public static int ledY = 8; // public static int ledX = 12; // public static boolean snakedLeds = true; // // public static boolean debug = true; // // public static long midiUpdateDelay = 100; // // public static String defaultSaveFolder = ""; // public static String defaultFilePrefix = "LedTable"; // // public static boolean remoteWS = false; // public static String remoteWSURL = ""; // // public static boolean autoplaySelection = false; // public static String defaultSelectionFile = ""; // // public static boolean autoplayPlaylist = false; // public static String defaultPlaylistFile = ""; // // /** // * Loads the settings to the static variables using the mdp3_Util // * Settings methods // * // * Currently hardcoded to use filename of settings.txt // */ // public static void loadSettings() { // loadSettings("settings.txt"); // } // // /** // * Loads the settings to the static variables using the mdp3_Util // * Settings methods // * // * @param fileName // */ // public static void loadSettings(String fileName) { // LOG.entering(name, "loadSettings", "Filename: " + fileName); // // SettingsLoader set = new SettingsLoader(LedTable_Settings.class, false); // // //URL url = SettingsTest.class.getResource("SettingsTest.txt"); // //File file = new File(url.getPath()); // set.loadSettings(fileName); // // checkSettings(); // // LOG.exiting(name, "loadSettings"); // } // // /** // * Method to run to bounds check variables after being loaded from file // */ // public static void checkSettings() { // //Check bounds, must have atleast 1 row of each // if (ledX < 1) { // LOG.warning("Error in settings: ledX < 1; changing value to ledX = 1"); // ledX = 1; // } // // if (ledY < 1) { // LOG.warning("Error in settings: ledY < 1; changing value to ledY = 1"); // ledY = 1; // } // } // }
import java.io.IOException; import net.mdp3.java.rpi.ledtable.LedTable_Settings;
package net.mdp3.java.rpi.ledtable.table; public class TableCMD extends Table { private final static String name = "LedTable_CMD"; public synchronized void write(byte[] bAr) { LOG.entering(TableCMD.name, "write", bAr); //LOG.finest(LedTable_Util.bArToString(bAr)); //long t = System.currentTimeMillis();
// Path: RPi-Java-LedTable/src/net/mdp3/java/rpi/ledtable/LedTable_Settings.java // public class LedTable_Settings { // private final static Logger LOG = Logger.getLogger(LedTable_Settings.class.getName()); // private final static String name = "LedTable_Settings"; // // //Default settings if not overwritten in settings.txt // public static boolean enableGUI = true; // public static int guiW = 504; // public static int guiH = 336; // public static boolean flipY = true; // // public static String wsName = "/ledtable"; // public static int wsPort = 85; // // public static boolean enableTableOutput = false; // public static String tableMode = "SPI"; // public static String serialPort = "/dev/ttyACM0"; // public static int serialBaud = 57600; // // public static int spiSpeed = 1953000; // // public static String outputFile = "/dev/spidev0.0"; // // public static int ledY = 8; // public static int ledX = 12; // public static boolean snakedLeds = true; // // public static boolean debug = true; // // public static long midiUpdateDelay = 100; // // public static String defaultSaveFolder = ""; // public static String defaultFilePrefix = "LedTable"; // // public static boolean remoteWS = false; // public static String remoteWSURL = ""; // // public static boolean autoplaySelection = false; // public static String defaultSelectionFile = ""; // // public static boolean autoplayPlaylist = false; // public static String defaultPlaylistFile = ""; // // /** // * Loads the settings to the static variables using the mdp3_Util // * Settings methods // * // * Currently hardcoded to use filename of settings.txt // */ // public static void loadSettings() { // loadSettings("settings.txt"); // } // // /** // * Loads the settings to the static variables using the mdp3_Util // * Settings methods // * // * @param fileName // */ // public static void loadSettings(String fileName) { // LOG.entering(name, "loadSettings", "Filename: " + fileName); // // SettingsLoader set = new SettingsLoader(LedTable_Settings.class, false); // // //URL url = SettingsTest.class.getResource("SettingsTest.txt"); // //File file = new File(url.getPath()); // set.loadSettings(fileName); // // checkSettings(); // // LOG.exiting(name, "loadSettings"); // } // // /** // * Method to run to bounds check variables after being loaded from file // */ // public static void checkSettings() { // //Check bounds, must have atleast 1 row of each // if (ledX < 1) { // LOG.warning("Error in settings: ledX < 1; changing value to ledX = 1"); // ledX = 1; // } // // if (ledY < 1) { // LOG.warning("Error in settings: ledY < 1; changing value to ledY = 1"); // ledY = 1; // } // } // } // Path: RPi-Java-LedTable/src/net/mdp3/java/rpi/ledtable/table/TableCMD.java import java.io.IOException; import net.mdp3.java.rpi.ledtable.LedTable_Settings; package net.mdp3.java.rpi.ledtable.table; public class TableCMD extends Table { private final static String name = "LedTable_CMD"; public synchronized void write(byte[] bAr) { LOG.entering(TableCMD.name, "write", bAr); //LOG.finest(LedTable_Util.bArToString(bAr)); //long t = System.currentTimeMillis();
if (LedTable_Settings.enableTableOutput) {
mikelduke/LedTable
RPi-Java-LedTable/src/net/mdp3/java/rpi/ledtable/table/TableSerial.java
// Path: RPi-Java-LedTable/src/net/mdp3/java/rpi/ledtable/LedTable_Settings.java // public class LedTable_Settings { // private final static Logger LOG = Logger.getLogger(LedTable_Settings.class.getName()); // private final static String name = "LedTable_Settings"; // // //Default settings if not overwritten in settings.txt // public static boolean enableGUI = true; // public static int guiW = 504; // public static int guiH = 336; // public static boolean flipY = true; // // public static String wsName = "/ledtable"; // public static int wsPort = 85; // // public static boolean enableTableOutput = false; // public static String tableMode = "SPI"; // public static String serialPort = "/dev/ttyACM0"; // public static int serialBaud = 57600; // // public static int spiSpeed = 1953000; // // public static String outputFile = "/dev/spidev0.0"; // // public static int ledY = 8; // public static int ledX = 12; // public static boolean snakedLeds = true; // // public static boolean debug = true; // // public static long midiUpdateDelay = 100; // // public static String defaultSaveFolder = ""; // public static String defaultFilePrefix = "LedTable"; // // public static boolean remoteWS = false; // public static String remoteWSURL = ""; // // public static boolean autoplaySelection = false; // public static String defaultSelectionFile = ""; // // public static boolean autoplayPlaylist = false; // public static String defaultPlaylistFile = ""; // // /** // * Loads the settings to the static variables using the mdp3_Util // * Settings methods // * // * Currently hardcoded to use filename of settings.txt // */ // public static void loadSettings() { // loadSettings("settings.txt"); // } // // /** // * Loads the settings to the static variables using the mdp3_Util // * Settings methods // * // * @param fileName // */ // public static void loadSettings(String fileName) { // LOG.entering(name, "loadSettings", "Filename: " + fileName); // // SettingsLoader set = new SettingsLoader(LedTable_Settings.class, false); // // //URL url = SettingsTest.class.getResource("SettingsTest.txt"); // //File file = new File(url.getPath()); // set.loadSettings(fileName); // // checkSettings(); // // LOG.exiting(name, "loadSettings"); // } // // /** // * Method to run to bounds check variables after being loaded from file // */ // public static void checkSettings() { // //Check bounds, must have atleast 1 row of each // if (ledX < 1) { // LOG.warning("Error in settings: ledX < 1; changing value to ledX = 1"); // ledX = 1; // } // // if (ledY < 1) { // LOG.warning("Error in settings: ledY < 1; changing value to ledY = 1"); // ledY = 1; // } // } // }
import net.mdp3.java.rpi.ledtable.LedTable_Settings; import com.pi4j.io.serial.Serial; import com.pi4j.io.serial.SerialDataEvent; import com.pi4j.io.serial.SerialDataListener; import com.pi4j.io.serial.SerialFactory; import com.pi4j.io.serial.SerialPortException;
/** * */ package net.mdp3.java.rpi.ledtable.table; /** * @author Mikel * */ public class TableSerial extends Table { private final static String name = "TableSerial"; private SerialDataListener sdl = null; public final Serial serial; private boolean connected = false; private String comPort = ""; private int baud = 57600; public TableSerial() { super(); serial = SerialFactory.createInstance();
// Path: RPi-Java-LedTable/src/net/mdp3/java/rpi/ledtable/LedTable_Settings.java // public class LedTable_Settings { // private final static Logger LOG = Logger.getLogger(LedTable_Settings.class.getName()); // private final static String name = "LedTable_Settings"; // // //Default settings if not overwritten in settings.txt // public static boolean enableGUI = true; // public static int guiW = 504; // public static int guiH = 336; // public static boolean flipY = true; // // public static String wsName = "/ledtable"; // public static int wsPort = 85; // // public static boolean enableTableOutput = false; // public static String tableMode = "SPI"; // public static String serialPort = "/dev/ttyACM0"; // public static int serialBaud = 57600; // // public static int spiSpeed = 1953000; // // public static String outputFile = "/dev/spidev0.0"; // // public static int ledY = 8; // public static int ledX = 12; // public static boolean snakedLeds = true; // // public static boolean debug = true; // // public static long midiUpdateDelay = 100; // // public static String defaultSaveFolder = ""; // public static String defaultFilePrefix = "LedTable"; // // public static boolean remoteWS = false; // public static String remoteWSURL = ""; // // public static boolean autoplaySelection = false; // public static String defaultSelectionFile = ""; // // public static boolean autoplayPlaylist = false; // public static String defaultPlaylistFile = ""; // // /** // * Loads the settings to the static variables using the mdp3_Util // * Settings methods // * // * Currently hardcoded to use filename of settings.txt // */ // public static void loadSettings() { // loadSettings("settings.txt"); // } // // /** // * Loads the settings to the static variables using the mdp3_Util // * Settings methods // * // * @param fileName // */ // public static void loadSettings(String fileName) { // LOG.entering(name, "loadSettings", "Filename: " + fileName); // // SettingsLoader set = new SettingsLoader(LedTable_Settings.class, false); // // //URL url = SettingsTest.class.getResource("SettingsTest.txt"); // //File file = new File(url.getPath()); // set.loadSettings(fileName); // // checkSettings(); // // LOG.exiting(name, "loadSettings"); // } // // /** // * Method to run to bounds check variables after being loaded from file // */ // public static void checkSettings() { // //Check bounds, must have atleast 1 row of each // if (ledX < 1) { // LOG.warning("Error in settings: ledX < 1; changing value to ledX = 1"); // ledX = 1; // } // // if (ledY < 1) { // LOG.warning("Error in settings: ledY < 1; changing value to ledY = 1"); // ledY = 1; // } // } // } // Path: RPi-Java-LedTable/src/net/mdp3/java/rpi/ledtable/table/TableSerial.java import net.mdp3.java.rpi.ledtable.LedTable_Settings; import com.pi4j.io.serial.Serial; import com.pi4j.io.serial.SerialDataEvent; import com.pi4j.io.serial.SerialDataListener; import com.pi4j.io.serial.SerialFactory; import com.pi4j.io.serial.SerialPortException; /** * */ package net.mdp3.java.rpi.ledtable.table; /** * @author Mikel * */ public class TableSerial extends Table { private final static String name = "TableSerial"; private SerialDataListener sdl = null; public final Serial serial; private boolean connected = false; private String comPort = ""; private int baud = 57600; public TableSerial() { super(); serial = SerialFactory.createInstance();
this.comPort = LedTable_Settings.serialPort;
mikelduke/LedTable
RPi-Java-LedTable/src/net/mdp3/java/rpi/ledtable/effects/EffectInfoParameter.java
// Path: RPi-Java-LedTable/src/net/mdp3/java/util/xml/DomXml.java // public interface DomXml { // public Element toXml(Document doc); // public void fromXml(Element e) throws Exception; // } // // Path: RPi-Java-LedTable/src/net/mdp3/java/util/xml/XmlHelper.java // public class XmlHelper { // // /** // * Method to make adding repetitive text nodes to an element easier. // * // * @param doc Java DOM Doc which is the items get added to // * @param name Name of the new element // * @param val Text Value of the new element // * @return Element containing a value ready to append to another Element // */ // public static Element newTextElement(Document doc, String name, Object val) { // Element e = doc.createElement(name); // e.appendChild(doc.createTextNode(val.toString())); // return e; // } // // /** // * Converts a Java DOM Xml Element to a String for simple output to // * console, logs, or files. // * // * @param e Element to convert // * @return String representation of element // * @throws TransformerFactoryConfigurationError // * @throws TransformerException // */ // public static String elementToString(Element e) throws TransformerFactoryConfigurationError, TransformerException { // String ret = ""; // Transformer transformer; // // transformer = TransformerFactory.newInstance().newTransformer(); // transformer.setOutputProperty(OutputKeys.INDENT, "yes"); // // StreamResult result = new StreamResult(new StringWriter()); // DOMSource source = new DOMSource(e); // transformer.transform(source, result); // // ret = result.getWriter().toString(); // // return ret; // } // // /** // * Returns a new Java DOM Doc object for use with elements. This doc should // * not be used for saving it is just used for internal copy/move/load type // * functions. // * // * @return // */ // public static Document getNewDoc() { // DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); // DocumentBuilder docBuilder; // // try { // docBuilder = docFactory.newDocumentBuilder(); // // // root elements // Document doc = docBuilder.newDocument(); // //Element rootElement = doc.createElement(rootElementName); // //doc.appendChild(rootElement); // // return doc; // } catch (ParserConfigurationException e) { // e.printStackTrace(); // } // // return null; // } // // public static void saveDocument(Document doc, File file) throws TransformerException { // TransformerFactory transformerFactory = TransformerFactory.newInstance(); // Transformer transformer = transformerFactory.newTransformer(); // DOMSource source = new DOMSource(doc); // StreamResult result = new StreamResult(file); // // transformer.transform(source, result); // } // // /** // * Reads in an xml file and returns the root element // * // * @param fileLocation // * @return // * @throws ParserConfigurationException // * @throws SAXException // * @throws IOException // */ // public static Element readXmlFile(String fileLocation) throws ParserConfigurationException, SAXException, IOException { // File f = new File(fileLocation); // return XmlHelper.readXmlFile(f); // } // // /** // * Reads in an xml file and returns the root Element // * // * @param f // * @return // * @throws ParserConfigurationException // * @throws SAXException // * @throws IOException // */ // public static Element readXmlFile(File f) throws ParserConfigurationException, SAXException, IOException { // Element retE = null; // // DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); // DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); // Document doc = dBuilder.parse(f); // // doc.getDocumentElement().normalize(); // // retE = doc.getDocumentElement(); // // return retE; // } // }
import net.mdp3.java.util.xml.DomXml; import net.mdp3.java.util.xml.XmlHelper; import org.w3c.dom.Document; import org.w3c.dom.Element;
this.paramDesc = paramDesc; } public String getParamName() { return paramName; } public void setParamName(String paramName) { this.paramName = paramName; } public String toString() { String ret = ""; ret += "Name: " + this.getParamName(); ret += "\nDesc: " + this.getParamDesc(); ret += "\nData Type: " + this.getParamDataType(); if (this.getMinValue() != 0 || this.getMaxValue() != 0) { ret += "\nMin Value: " + this.getMinValue(); ret += "\nMax Value: " + this.getMaxValue(); } return ret; } @Override public Element toXml(Document doc) { Element eipE = doc.createElement(EffectInfoParameter.NODE_NAME);
// Path: RPi-Java-LedTable/src/net/mdp3/java/util/xml/DomXml.java // public interface DomXml { // public Element toXml(Document doc); // public void fromXml(Element e) throws Exception; // } // // Path: RPi-Java-LedTable/src/net/mdp3/java/util/xml/XmlHelper.java // public class XmlHelper { // // /** // * Method to make adding repetitive text nodes to an element easier. // * // * @param doc Java DOM Doc which is the items get added to // * @param name Name of the new element // * @param val Text Value of the new element // * @return Element containing a value ready to append to another Element // */ // public static Element newTextElement(Document doc, String name, Object val) { // Element e = doc.createElement(name); // e.appendChild(doc.createTextNode(val.toString())); // return e; // } // // /** // * Converts a Java DOM Xml Element to a String for simple output to // * console, logs, or files. // * // * @param e Element to convert // * @return String representation of element // * @throws TransformerFactoryConfigurationError // * @throws TransformerException // */ // public static String elementToString(Element e) throws TransformerFactoryConfigurationError, TransformerException { // String ret = ""; // Transformer transformer; // // transformer = TransformerFactory.newInstance().newTransformer(); // transformer.setOutputProperty(OutputKeys.INDENT, "yes"); // // StreamResult result = new StreamResult(new StringWriter()); // DOMSource source = new DOMSource(e); // transformer.transform(source, result); // // ret = result.getWriter().toString(); // // return ret; // } // // /** // * Returns a new Java DOM Doc object for use with elements. This doc should // * not be used for saving it is just used for internal copy/move/load type // * functions. // * // * @return // */ // public static Document getNewDoc() { // DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); // DocumentBuilder docBuilder; // // try { // docBuilder = docFactory.newDocumentBuilder(); // // // root elements // Document doc = docBuilder.newDocument(); // //Element rootElement = doc.createElement(rootElementName); // //doc.appendChild(rootElement); // // return doc; // } catch (ParserConfigurationException e) { // e.printStackTrace(); // } // // return null; // } // // public static void saveDocument(Document doc, File file) throws TransformerException { // TransformerFactory transformerFactory = TransformerFactory.newInstance(); // Transformer transformer = transformerFactory.newTransformer(); // DOMSource source = new DOMSource(doc); // StreamResult result = new StreamResult(file); // // transformer.transform(source, result); // } // // /** // * Reads in an xml file and returns the root element // * // * @param fileLocation // * @return // * @throws ParserConfigurationException // * @throws SAXException // * @throws IOException // */ // public static Element readXmlFile(String fileLocation) throws ParserConfigurationException, SAXException, IOException { // File f = new File(fileLocation); // return XmlHelper.readXmlFile(f); // } // // /** // * Reads in an xml file and returns the root Element // * // * @param f // * @return // * @throws ParserConfigurationException // * @throws SAXException // * @throws IOException // */ // public static Element readXmlFile(File f) throws ParserConfigurationException, SAXException, IOException { // Element retE = null; // // DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); // DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); // Document doc = dBuilder.parse(f); // // doc.getDocumentElement().normalize(); // // retE = doc.getDocumentElement(); // // return retE; // } // } // Path: RPi-Java-LedTable/src/net/mdp3/java/rpi/ledtable/effects/EffectInfoParameter.java import net.mdp3.java.util.xml.DomXml; import net.mdp3.java.util.xml.XmlHelper; import org.w3c.dom.Document; import org.w3c.dom.Element; this.paramDesc = paramDesc; } public String getParamName() { return paramName; } public void setParamName(String paramName) { this.paramName = paramName; } public String toString() { String ret = ""; ret += "Name: " + this.getParamName(); ret += "\nDesc: " + this.getParamDesc(); ret += "\nData Type: " + this.getParamDataType(); if (this.getMinValue() != 0 || this.getMaxValue() != 0) { ret += "\nMin Value: " + this.getMinValue(); ret += "\nMax Value: " + this.getMaxValue(); } return ret; } @Override public Element toXml(Document doc) { Element eipE = doc.createElement(EffectInfoParameter.NODE_NAME);
eipE.appendChild(XmlHelper.newTextElement(doc, EffectInfoParameter.NODE_EIP_NAME, this.paramName));
mikelduke/LedTable
RPi-Java-LedTable/src/net/mdp3/java/util/test/SimpleFileIOTest.java
// Path: RPi-Java-LedTable/src/net/mdp3/java/util/file/SimpleFileIO.java // public class SimpleFileIO { // // public static void writeStringToFile(String fileName, String s) throws IOException { // writeStringToFile(new File(fileName), s); // } // // public static void writeStringToFile(File file, String s) throws IOException { // BufferedWriter bw = null; // // bw = new BufferedWriter(new FileWriter(file)); // bw.write(s); // bw.close(); // } // // public static String loadFileToString(String fileName) throws FileNotFoundException { // return loadFileToString(new File(fileName)); // } // // public static String loadFileToString(File file) throws FileNotFoundException { // StringBuilder sb = new StringBuilder(); // Scanner sc = new Scanner(file); // // while (sc.hasNext()) { // sb.append(sc.nextLine()).append("\n"); // } // sc.close(); // // return sb.toString(); // } // // public static void appendStringToFile(String fileName, String s) throws IOException, FileNotFoundException { // appendStringToFile(new File(fileName), s); // } // // public static void appendStringToFile(File file, String s) throws IOException, FileNotFoundException { // String fileContents = loadFileToString(file); // // if (!fileContents.endsWith("\n")) fileContents += "\n"; // fileContents += s; // // writeStringToFile(file, fileContents); // } // }
import net.mdp3.java.util.file.SimpleFileIO; import java.io.FileNotFoundException; import java.io.IOException;
/** * */ package net.mdp3.java.util.test; /** * Test script for the SimpleFileIO class. * * Writes a string to a file, loads the file, then appends a string to file * and reloads the contents. * * @author Mikel * */ public class SimpleFileIOTest { /** * @param args */ public static void main(String[] args) { String text = "Test String!!@RWSF"; try {
// Path: RPi-Java-LedTable/src/net/mdp3/java/util/file/SimpleFileIO.java // public class SimpleFileIO { // // public static void writeStringToFile(String fileName, String s) throws IOException { // writeStringToFile(new File(fileName), s); // } // // public static void writeStringToFile(File file, String s) throws IOException { // BufferedWriter bw = null; // // bw = new BufferedWriter(new FileWriter(file)); // bw.write(s); // bw.close(); // } // // public static String loadFileToString(String fileName) throws FileNotFoundException { // return loadFileToString(new File(fileName)); // } // // public static String loadFileToString(File file) throws FileNotFoundException { // StringBuilder sb = new StringBuilder(); // Scanner sc = new Scanner(file); // // while (sc.hasNext()) { // sb.append(sc.nextLine()).append("\n"); // } // sc.close(); // // return sb.toString(); // } // // public static void appendStringToFile(String fileName, String s) throws IOException, FileNotFoundException { // appendStringToFile(new File(fileName), s); // } // // public static void appendStringToFile(File file, String s) throws IOException, FileNotFoundException { // String fileContents = loadFileToString(file); // // if (!fileContents.endsWith("\n")) fileContents += "\n"; // fileContents += s; // // writeStringToFile(file, fileContents); // } // } // Path: RPi-Java-LedTable/src/net/mdp3/java/util/test/SimpleFileIOTest.java import net.mdp3.java.util.file.SimpleFileIO; import java.io.FileNotFoundException; import java.io.IOException; /** * */ package net.mdp3.java.util.test; /** * Test script for the SimpleFileIO class. * * Writes a string to a file, loads the file, then appends a string to file * and reloads the contents. * * @author Mikel * */ public class SimpleFileIOTest { /** * @param args */ public static void main(String[] args) { String text = "Test String!!@RWSF"; try {
SimpleFileIO.writeStringToFile("test.txt", text);
mikelduke/LedTable
RPi-Java-LedTable/src/net/mdp3/java/rpi/ledtable/effects/EffectMode.java
// Path: RPi-Java-LedTable/src/net/mdp3/java/util/xml/DomXml.java // public interface DomXml { // public Element toXml(Document doc); // public void fromXml(Element e) throws Exception; // } // // Path: RPi-Java-LedTable/src/net/mdp3/java/util/xml/XmlHelper.java // public class XmlHelper { // // /** // * Method to make adding repetitive text nodes to an element easier. // * // * @param doc Java DOM Doc which is the items get added to // * @param name Name of the new element // * @param val Text Value of the new element // * @return Element containing a value ready to append to another Element // */ // public static Element newTextElement(Document doc, String name, Object val) { // Element e = doc.createElement(name); // e.appendChild(doc.createTextNode(val.toString())); // return e; // } // // /** // * Converts a Java DOM Xml Element to a String for simple output to // * console, logs, or files. // * // * @param e Element to convert // * @return String representation of element // * @throws TransformerFactoryConfigurationError // * @throws TransformerException // */ // public static String elementToString(Element e) throws TransformerFactoryConfigurationError, TransformerException { // String ret = ""; // Transformer transformer; // // transformer = TransformerFactory.newInstance().newTransformer(); // transformer.setOutputProperty(OutputKeys.INDENT, "yes"); // // StreamResult result = new StreamResult(new StringWriter()); // DOMSource source = new DOMSource(e); // transformer.transform(source, result); // // ret = result.getWriter().toString(); // // return ret; // } // // /** // * Returns a new Java DOM Doc object for use with elements. This doc should // * not be used for saving it is just used for internal copy/move/load type // * functions. // * // * @return // */ // public static Document getNewDoc() { // DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); // DocumentBuilder docBuilder; // // try { // docBuilder = docFactory.newDocumentBuilder(); // // // root elements // Document doc = docBuilder.newDocument(); // //Element rootElement = doc.createElement(rootElementName); // //doc.appendChild(rootElement); // // return doc; // } catch (ParserConfigurationException e) { // e.printStackTrace(); // } // // return null; // } // // public static void saveDocument(Document doc, File file) throws TransformerException { // TransformerFactory transformerFactory = TransformerFactory.newInstance(); // Transformer transformer = transformerFactory.newTransformer(); // DOMSource source = new DOMSource(doc); // StreamResult result = new StreamResult(file); // // transformer.transform(source, result); // } // // /** // * Reads in an xml file and returns the root element // * // * @param fileLocation // * @return // * @throws ParserConfigurationException // * @throws SAXException // * @throws IOException // */ // public static Element readXmlFile(String fileLocation) throws ParserConfigurationException, SAXException, IOException { // File f = new File(fileLocation); // return XmlHelper.readXmlFile(f); // } // // /** // * Reads in an xml file and returns the root Element // * // * @param f // * @return // * @throws ParserConfigurationException // * @throws SAXException // * @throws IOException // */ // public static Element readXmlFile(File f) throws ParserConfigurationException, SAXException, IOException { // Element retE = null; // // DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); // DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); // Document doc = dBuilder.parse(f); // // doc.getDocumentElement().normalize(); // // retE = doc.getDocumentElement(); // // return retE; // } // }
import org.w3c.dom.Document; import org.w3c.dom.Element; import net.mdp3.java.util.xml.DomXml; import net.mdp3.java.util.xml.XmlHelper;
this(null, ""); } private EffectMode(String name) { this(null, name); } private EffectMode(Class<? extends Effect> effectClass) { this(effectClass, ""); } private EffectMode(Class<? extends Effect> effectClass, String name) { this.effectClass = effectClass; this.name = name; } public Class<? extends Effect> getEffectClass() { return this.effectClass; } public String getDescName() { //if (this.name != null && this.name.length() > 0) return this.name; //else return this.name(); } @Override public Element toXml(Document doc) { Element effectModeE = doc.createElement(EffectMode.NODE_NAME);
// Path: RPi-Java-LedTable/src/net/mdp3/java/util/xml/DomXml.java // public interface DomXml { // public Element toXml(Document doc); // public void fromXml(Element e) throws Exception; // } // // Path: RPi-Java-LedTable/src/net/mdp3/java/util/xml/XmlHelper.java // public class XmlHelper { // // /** // * Method to make adding repetitive text nodes to an element easier. // * // * @param doc Java DOM Doc which is the items get added to // * @param name Name of the new element // * @param val Text Value of the new element // * @return Element containing a value ready to append to another Element // */ // public static Element newTextElement(Document doc, String name, Object val) { // Element e = doc.createElement(name); // e.appendChild(doc.createTextNode(val.toString())); // return e; // } // // /** // * Converts a Java DOM Xml Element to a String for simple output to // * console, logs, or files. // * // * @param e Element to convert // * @return String representation of element // * @throws TransformerFactoryConfigurationError // * @throws TransformerException // */ // public static String elementToString(Element e) throws TransformerFactoryConfigurationError, TransformerException { // String ret = ""; // Transformer transformer; // // transformer = TransformerFactory.newInstance().newTransformer(); // transformer.setOutputProperty(OutputKeys.INDENT, "yes"); // // StreamResult result = new StreamResult(new StringWriter()); // DOMSource source = new DOMSource(e); // transformer.transform(source, result); // // ret = result.getWriter().toString(); // // return ret; // } // // /** // * Returns a new Java DOM Doc object for use with elements. This doc should // * not be used for saving it is just used for internal copy/move/load type // * functions. // * // * @return // */ // public static Document getNewDoc() { // DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); // DocumentBuilder docBuilder; // // try { // docBuilder = docFactory.newDocumentBuilder(); // // // root elements // Document doc = docBuilder.newDocument(); // //Element rootElement = doc.createElement(rootElementName); // //doc.appendChild(rootElement); // // return doc; // } catch (ParserConfigurationException e) { // e.printStackTrace(); // } // // return null; // } // // public static void saveDocument(Document doc, File file) throws TransformerException { // TransformerFactory transformerFactory = TransformerFactory.newInstance(); // Transformer transformer = transformerFactory.newTransformer(); // DOMSource source = new DOMSource(doc); // StreamResult result = new StreamResult(file); // // transformer.transform(source, result); // } // // /** // * Reads in an xml file and returns the root element // * // * @param fileLocation // * @return // * @throws ParserConfigurationException // * @throws SAXException // * @throws IOException // */ // public static Element readXmlFile(String fileLocation) throws ParserConfigurationException, SAXException, IOException { // File f = new File(fileLocation); // return XmlHelper.readXmlFile(f); // } // // /** // * Reads in an xml file and returns the root Element // * // * @param f // * @return // * @throws ParserConfigurationException // * @throws SAXException // * @throws IOException // */ // public static Element readXmlFile(File f) throws ParserConfigurationException, SAXException, IOException { // Element retE = null; // // DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); // DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); // Document doc = dBuilder.parse(f); // // doc.getDocumentElement().normalize(); // // retE = doc.getDocumentElement(); // // return retE; // } // } // Path: RPi-Java-LedTable/src/net/mdp3/java/rpi/ledtable/effects/EffectMode.java import org.w3c.dom.Document; import org.w3c.dom.Element; import net.mdp3.java.util.xml.DomXml; import net.mdp3.java.util.xml.XmlHelper; this(null, ""); } private EffectMode(String name) { this(null, name); } private EffectMode(Class<? extends Effect> effectClass) { this(effectClass, ""); } private EffectMode(Class<? extends Effect> effectClass, String name) { this.effectClass = effectClass; this.name = name; } public Class<? extends Effect> getEffectClass() { return this.effectClass; } public String getDescName() { //if (this.name != null && this.name.length() > 0) return this.name; //else return this.name(); } @Override public Element toXml(Document doc) { Element effectModeE = doc.createElement(EffectMode.NODE_NAME);
effectModeE.appendChild(XmlHelper.newTextElement(doc, EffectMode.NODE_MODE_NAME, this.name()));
mikelduke/LedTable
RPi-Java-LedTable/src/net/mdp3/java/util/console/ConsoleArgumentHandler.java
// Path: RPi-Java-LedTable/src/net/mdp3/java/util/misc/ObjectNotInitializedException.java // public class ObjectNotInitializedException extends Exception { // // private static final long serialVersionUID = 2993512881656200086L; // // public ObjectNotInitializedException() { // super(); // } // // /** // * @param message // */ // public ObjectNotInitializedException(String message) { // super(message); // } // // /** // * @param cause // */ // public ObjectNotInitializedException(Throwable cause) { // super(cause); // } // // /** // * @param message // * @param cause // */ // public ObjectNotInitializedException(String message, Throwable cause) { // super(message, cause); // } // // /** // * @param message // * @param cause // * @param enableSuppression // * @param writableStackTrace // */ // public ObjectNotInitializedException(String message, Throwable cause, // boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // // }
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Logger; import net.mdp3.java.util.misc.ObjectNotInitializedException;
* * @param prefixAr */ public void setPrefixList(String[] prefixAr) { if (prefixAr != null && prefixAr.length > 0) this.cmdPrefixList = Arrays.asList(prefixAr); else this.cmdPrefixList = Arrays.asList(DEFAULT_PREFIX_LIST); } /** * Adds another prefix to the list, helpful if you want to use the default * list and an extra item or two * * @param prefix */ public void addPrefix(String prefix) { this.cmdPrefixList.add(prefix); } /** * Runs the argument runner against the object, returns a list of failed * arguments from the argList. A failure is when the command cannot be * found in the arg, not when the command doesnt exist on the object. * * @return List<String> of failed arguments * @throws InvocationTargetException * @throws IllegalArgumentException * @throws IllegalAccessException * @throws ObjectNotInitializedException */
// Path: RPi-Java-LedTable/src/net/mdp3/java/util/misc/ObjectNotInitializedException.java // public class ObjectNotInitializedException extends Exception { // // private static final long serialVersionUID = 2993512881656200086L; // // public ObjectNotInitializedException() { // super(); // } // // /** // * @param message // */ // public ObjectNotInitializedException(String message) { // super(message); // } // // /** // * @param cause // */ // public ObjectNotInitializedException(Throwable cause) { // super(cause); // } // // /** // * @param message // * @param cause // */ // public ObjectNotInitializedException(String message, Throwable cause) { // super(message, cause); // } // // /** // * @param message // * @param cause // * @param enableSuppression // * @param writableStackTrace // */ // public ObjectNotInitializedException(String message, Throwable cause, // boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // // } // Path: RPi-Java-LedTable/src/net/mdp3/java/util/console/ConsoleArgumentHandler.java import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Logger; import net.mdp3.java.util.misc.ObjectNotInitializedException; * * @param prefixAr */ public void setPrefixList(String[] prefixAr) { if (prefixAr != null && prefixAr.length > 0) this.cmdPrefixList = Arrays.asList(prefixAr); else this.cmdPrefixList = Arrays.asList(DEFAULT_PREFIX_LIST); } /** * Adds another prefix to the list, helpful if you want to use the default * list and an extra item or two * * @param prefix */ public void addPrefix(String prefix) { this.cmdPrefixList.add(prefix); } /** * Runs the argument runner against the object, returns a list of failed * arguments from the argList. A failure is when the command cannot be * found in the arg, not when the command doesnt exist on the object. * * @return List<String> of failed arguments * @throws InvocationTargetException * @throws IllegalArgumentException * @throws IllegalAccessException * @throws ObjectNotInitializedException */
public List<String> runArgs() throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, ObjectNotInitializedException {
mikelduke/LedTable
RPi-Java-LedTable/src/net/mdp3/java/rpi/ledtable/effects/EffectInfo.java
// Path: RPi-Java-LedTable/src/net/mdp3/java/util/xml/DomXml.java // public interface DomXml { // public Element toXml(Document doc); // public void fromXml(Element e) throws Exception; // } // // Path: RPi-Java-LedTable/src/net/mdp3/java/util/xml/XmlHelper.java // public class XmlHelper { // // /** // * Method to make adding repetitive text nodes to an element easier. // * // * @param doc Java DOM Doc which is the items get added to // * @param name Name of the new element // * @param val Text Value of the new element // * @return Element containing a value ready to append to another Element // */ // public static Element newTextElement(Document doc, String name, Object val) { // Element e = doc.createElement(name); // e.appendChild(doc.createTextNode(val.toString())); // return e; // } // // /** // * Converts a Java DOM Xml Element to a String for simple output to // * console, logs, or files. // * // * @param e Element to convert // * @return String representation of element // * @throws TransformerFactoryConfigurationError // * @throws TransformerException // */ // public static String elementToString(Element e) throws TransformerFactoryConfigurationError, TransformerException { // String ret = ""; // Transformer transformer; // // transformer = TransformerFactory.newInstance().newTransformer(); // transformer.setOutputProperty(OutputKeys.INDENT, "yes"); // // StreamResult result = new StreamResult(new StringWriter()); // DOMSource source = new DOMSource(e); // transformer.transform(source, result); // // ret = result.getWriter().toString(); // // return ret; // } // // /** // * Returns a new Java DOM Doc object for use with elements. This doc should // * not be used for saving it is just used for internal copy/move/load type // * functions. // * // * @return // */ // public static Document getNewDoc() { // DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); // DocumentBuilder docBuilder; // // try { // docBuilder = docFactory.newDocumentBuilder(); // // // root elements // Document doc = docBuilder.newDocument(); // //Element rootElement = doc.createElement(rootElementName); // //doc.appendChild(rootElement); // // return doc; // } catch (ParserConfigurationException e) { // e.printStackTrace(); // } // // return null; // } // // public static void saveDocument(Document doc, File file) throws TransformerException { // TransformerFactory transformerFactory = TransformerFactory.newInstance(); // Transformer transformer = transformerFactory.newTransformer(); // DOMSource source = new DOMSource(doc); // StreamResult result = new StreamResult(file); // // transformer.transform(source, result); // } // // /** // * Reads in an xml file and returns the root element // * // * @param fileLocation // * @return // * @throws ParserConfigurationException // * @throws SAXException // * @throws IOException // */ // public static Element readXmlFile(String fileLocation) throws ParserConfigurationException, SAXException, IOException { // File f = new File(fileLocation); // return XmlHelper.readXmlFile(f); // } // // /** // * Reads in an xml file and returns the root Element // * // * @param f // * @return // * @throws ParserConfigurationException // * @throws SAXException // * @throws IOException // */ // public static Element readXmlFile(File f) throws ParserConfigurationException, SAXException, IOException { // Element retE = null; // // DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); // DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); // Document doc = dBuilder.parse(f); // // doc.getDocumentElement().normalize(); // // retE = doc.getDocumentElement(); // // return retE; // } // }
import java.util.ArrayList; import java.util.Arrays; import net.mdp3.java.util.xml.DomXml; import net.mdp3.java.util.xml.XmlHelper; import org.w3c.dom.Document; import org.w3c.dom.Element;
public String getEffectName() { return effectName; } public void setEffectName(String effectName) { this.effectName = effectName; } public String toString() { String ret = ""; ret += "Name: " + this.getEffectName(); ret += "\nDesc: " + this.getEffectDesc(); if (this.paramInfo.size() > 0) { ret += "\n\nParameter Info: \n"; for (EffectInfoParameter eip : this.paramInfo) { ret += "\n" + eip.toString(); } } return ret; } @Override public Element toXml(Document doc) { Element effectInfoE = doc.createElement(EffectInfo.NODE_NAME);
// Path: RPi-Java-LedTable/src/net/mdp3/java/util/xml/DomXml.java // public interface DomXml { // public Element toXml(Document doc); // public void fromXml(Element e) throws Exception; // } // // Path: RPi-Java-LedTable/src/net/mdp3/java/util/xml/XmlHelper.java // public class XmlHelper { // // /** // * Method to make adding repetitive text nodes to an element easier. // * // * @param doc Java DOM Doc which is the items get added to // * @param name Name of the new element // * @param val Text Value of the new element // * @return Element containing a value ready to append to another Element // */ // public static Element newTextElement(Document doc, String name, Object val) { // Element e = doc.createElement(name); // e.appendChild(doc.createTextNode(val.toString())); // return e; // } // // /** // * Converts a Java DOM Xml Element to a String for simple output to // * console, logs, or files. // * // * @param e Element to convert // * @return String representation of element // * @throws TransformerFactoryConfigurationError // * @throws TransformerException // */ // public static String elementToString(Element e) throws TransformerFactoryConfigurationError, TransformerException { // String ret = ""; // Transformer transformer; // // transformer = TransformerFactory.newInstance().newTransformer(); // transformer.setOutputProperty(OutputKeys.INDENT, "yes"); // // StreamResult result = new StreamResult(new StringWriter()); // DOMSource source = new DOMSource(e); // transformer.transform(source, result); // // ret = result.getWriter().toString(); // // return ret; // } // // /** // * Returns a new Java DOM Doc object for use with elements. This doc should // * not be used for saving it is just used for internal copy/move/load type // * functions. // * // * @return // */ // public static Document getNewDoc() { // DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); // DocumentBuilder docBuilder; // // try { // docBuilder = docFactory.newDocumentBuilder(); // // // root elements // Document doc = docBuilder.newDocument(); // //Element rootElement = doc.createElement(rootElementName); // //doc.appendChild(rootElement); // // return doc; // } catch (ParserConfigurationException e) { // e.printStackTrace(); // } // // return null; // } // // public static void saveDocument(Document doc, File file) throws TransformerException { // TransformerFactory transformerFactory = TransformerFactory.newInstance(); // Transformer transformer = transformerFactory.newTransformer(); // DOMSource source = new DOMSource(doc); // StreamResult result = new StreamResult(file); // // transformer.transform(source, result); // } // // /** // * Reads in an xml file and returns the root element // * // * @param fileLocation // * @return // * @throws ParserConfigurationException // * @throws SAXException // * @throws IOException // */ // public static Element readXmlFile(String fileLocation) throws ParserConfigurationException, SAXException, IOException { // File f = new File(fileLocation); // return XmlHelper.readXmlFile(f); // } // // /** // * Reads in an xml file and returns the root Element // * // * @param f // * @return // * @throws ParserConfigurationException // * @throws SAXException // * @throws IOException // */ // public static Element readXmlFile(File f) throws ParserConfigurationException, SAXException, IOException { // Element retE = null; // // DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); // DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); // Document doc = dBuilder.parse(f); // // doc.getDocumentElement().normalize(); // // retE = doc.getDocumentElement(); // // return retE; // } // } // Path: RPi-Java-LedTable/src/net/mdp3/java/rpi/ledtable/effects/EffectInfo.java import java.util.ArrayList; import java.util.Arrays; import net.mdp3.java.util.xml.DomXml; import net.mdp3.java.util.xml.XmlHelper; import org.w3c.dom.Document; import org.w3c.dom.Element; public String getEffectName() { return effectName; } public void setEffectName(String effectName) { this.effectName = effectName; } public String toString() { String ret = ""; ret += "Name: " + this.getEffectName(); ret += "\nDesc: " + this.getEffectDesc(); if (this.paramInfo.size() > 0) { ret += "\n\nParameter Info: \n"; for (EffectInfoParameter eip : this.paramInfo) { ret += "\n" + eip.toString(); } } return ret; } @Override public Element toXml(Document doc) { Element effectInfoE = doc.createElement(EffectInfo.NODE_NAME);
effectInfoE.appendChild(XmlHelper.newTextElement(doc, EffectInfo.NODE_EFFECT_NAME, this.effectName));
mikelduke/LedTable
RPi-Java-LedTable/src/net/mdp3/java/rpi/ledtable/table/TableSPI.java
// Path: RPi-Java-LedTable/src/net/mdp3/java/rpi/ledtable/LedTable_Settings.java // public class LedTable_Settings { // private final static Logger LOG = Logger.getLogger(LedTable_Settings.class.getName()); // private final static String name = "LedTable_Settings"; // // //Default settings if not overwritten in settings.txt // public static boolean enableGUI = true; // public static int guiW = 504; // public static int guiH = 336; // public static boolean flipY = true; // // public static String wsName = "/ledtable"; // public static int wsPort = 85; // // public static boolean enableTableOutput = false; // public static String tableMode = "SPI"; // public static String serialPort = "/dev/ttyACM0"; // public static int serialBaud = 57600; // // public static int spiSpeed = 1953000; // // public static String outputFile = "/dev/spidev0.0"; // // public static int ledY = 8; // public static int ledX = 12; // public static boolean snakedLeds = true; // // public static boolean debug = true; // // public static long midiUpdateDelay = 100; // // public static String defaultSaveFolder = ""; // public static String defaultFilePrefix = "LedTable"; // // public static boolean remoteWS = false; // public static String remoteWSURL = ""; // // public static boolean autoplaySelection = false; // public static String defaultSelectionFile = ""; // // public static boolean autoplayPlaylist = false; // public static String defaultPlaylistFile = ""; // // /** // * Loads the settings to the static variables using the mdp3_Util // * Settings methods // * // * Currently hardcoded to use filename of settings.txt // */ // public static void loadSettings() { // loadSettings("settings.txt"); // } // // /** // * Loads the settings to the static variables using the mdp3_Util // * Settings methods // * // * @param fileName // */ // public static void loadSettings(String fileName) { // LOG.entering(name, "loadSettings", "Filename: " + fileName); // // SettingsLoader set = new SettingsLoader(LedTable_Settings.class, false); // // //URL url = SettingsTest.class.getResource("SettingsTest.txt"); // //File file = new File(url.getPath()); // set.loadSettings(fileName); // // checkSettings(); // // LOG.exiting(name, "loadSettings"); // } // // /** // * Method to run to bounds check variables after being loaded from file // */ // public static void checkSettings() { // //Check bounds, must have atleast 1 row of each // if (ledX < 1) { // LOG.warning("Error in settings: ledX < 1; changing value to ledX = 1"); // ledX = 1; // } // // if (ledY < 1) { // LOG.warning("Error in settings: ledY < 1; changing value to ledY = 1"); // ledY = 1; // } // } // }
import java.io.IOException; import net.mdp3.java.rpi.ledtable.LedTable_Settings; import com.pi4j.io.spi.SpiChannel; import com.pi4j.io.spi.SpiDevice; import com.pi4j.io.spi.SpiFactory; import com.pi4j.io.spi.SpiMode;
package net.mdp3.java.rpi.ledtable.table; public class TableSPI extends Table { private final static String name = "LedTable_SPI"; private SpiDevice spi = null; public TableSPI() throws IOException { LOG.entering(TableSPI.name, "new");
// Path: RPi-Java-LedTable/src/net/mdp3/java/rpi/ledtable/LedTable_Settings.java // public class LedTable_Settings { // private final static Logger LOG = Logger.getLogger(LedTable_Settings.class.getName()); // private final static String name = "LedTable_Settings"; // // //Default settings if not overwritten in settings.txt // public static boolean enableGUI = true; // public static int guiW = 504; // public static int guiH = 336; // public static boolean flipY = true; // // public static String wsName = "/ledtable"; // public static int wsPort = 85; // // public static boolean enableTableOutput = false; // public static String tableMode = "SPI"; // public static String serialPort = "/dev/ttyACM0"; // public static int serialBaud = 57600; // // public static int spiSpeed = 1953000; // // public static String outputFile = "/dev/spidev0.0"; // // public static int ledY = 8; // public static int ledX = 12; // public static boolean snakedLeds = true; // // public static boolean debug = true; // // public static long midiUpdateDelay = 100; // // public static String defaultSaveFolder = ""; // public static String defaultFilePrefix = "LedTable"; // // public static boolean remoteWS = false; // public static String remoteWSURL = ""; // // public static boolean autoplaySelection = false; // public static String defaultSelectionFile = ""; // // public static boolean autoplayPlaylist = false; // public static String defaultPlaylistFile = ""; // // /** // * Loads the settings to the static variables using the mdp3_Util // * Settings methods // * // * Currently hardcoded to use filename of settings.txt // */ // public static void loadSettings() { // loadSettings("settings.txt"); // } // // /** // * Loads the settings to the static variables using the mdp3_Util // * Settings methods // * // * @param fileName // */ // public static void loadSettings(String fileName) { // LOG.entering(name, "loadSettings", "Filename: " + fileName); // // SettingsLoader set = new SettingsLoader(LedTable_Settings.class, false); // // //URL url = SettingsTest.class.getResource("SettingsTest.txt"); // //File file = new File(url.getPath()); // set.loadSettings(fileName); // // checkSettings(); // // LOG.exiting(name, "loadSettings"); // } // // /** // * Method to run to bounds check variables after being loaded from file // */ // public static void checkSettings() { // //Check bounds, must have atleast 1 row of each // if (ledX < 1) { // LOG.warning("Error in settings: ledX < 1; changing value to ledX = 1"); // ledX = 1; // } // // if (ledY < 1) { // LOG.warning("Error in settings: ledY < 1; changing value to ledY = 1"); // ledY = 1; // } // } // } // Path: RPi-Java-LedTable/src/net/mdp3/java/rpi/ledtable/table/TableSPI.java import java.io.IOException; import net.mdp3.java.rpi.ledtable.LedTable_Settings; import com.pi4j.io.spi.SpiChannel; import com.pi4j.io.spi.SpiDevice; import com.pi4j.io.spi.SpiFactory; import com.pi4j.io.spi.SpiMode; package net.mdp3.java.rpi.ledtable.table; public class TableSPI extends Table { private final static String name = "LedTable_SPI"; private SpiDevice spi = null; public TableSPI() throws IOException { LOG.entering(TableSPI.name, "new");
if (LedTable_Settings.enableTableOutput)
cvtienhoven/graylog-plugin-aggregates
src/main/java/org/graylog/plugins/aggregates/report/ReportFactory.java
// Path: src/main/java/org/graylog/plugins/aggregates/history/HistoryAggregateItem.java // public interface HistoryAggregateItem { // public String getMoment(); // // public long getNumberOfHits(); // // } // // Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/ReportSchedule.java // public interface ReportSchedule { // // public String getId(); // // public String getName(); // // public String getExpression(); // // public String getTimespan(); // // public boolean isDefaultSchedule(); // // public Long getNextFireTime(); // // public List<String> getReportReceivers(); // } // // Path: src/main/java/org/graylog/plugins/aggregates/rule/Rule.java // public interface Rule { // // public String getQuery(); // // public String getField(); // // public long getNumberOfMatches(); // // public boolean isMatchMoreOrEqual(); // // public int getInterval(); // // public String getName(); // // public boolean isEnabled(); // // public String getStreamId(); // // public boolean isInReport(); // // public List<String> getReportSchedules(); // // public String getAlertConditionId(); // // public boolean shouldRepeatNotifications(); // // public long getBacklog(); // }
import java.awt.Graphics2D; import java.awt.geom.Rectangle2D; import java.io.OutputStream; import java.text.ParseException; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Map; import org.graylog.plugins.aggregates.history.HistoryAggregateItem; import org.graylog.plugins.aggregates.report.schedule.ReportSchedule; import org.graylog.plugins.aggregates.rule.Rule; import org.jfree.chart.JFreeChart; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.itextpdf.awt.DefaultFontMapper; import com.itextpdf.text.Document; import com.itextpdf.text.PageSize; import com.itextpdf.text.Paragraph; import com.itextpdf.text.pdf.PdfContentByte; import com.itextpdf.text.pdf.PdfTemplate; import com.itextpdf.text.pdf.PdfWriter;
package org.graylog.plugins.aggregates.report; public class ReportFactory { private static final Logger LOG = LoggerFactory.getLogger(ReportFactory.class);
// Path: src/main/java/org/graylog/plugins/aggregates/history/HistoryAggregateItem.java // public interface HistoryAggregateItem { // public String getMoment(); // // public long getNumberOfHits(); // // } // // Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/ReportSchedule.java // public interface ReportSchedule { // // public String getId(); // // public String getName(); // // public String getExpression(); // // public String getTimespan(); // // public boolean isDefaultSchedule(); // // public Long getNextFireTime(); // // public List<String> getReportReceivers(); // } // // Path: src/main/java/org/graylog/plugins/aggregates/rule/Rule.java // public interface Rule { // // public String getQuery(); // // public String getField(); // // public long getNumberOfMatches(); // // public boolean isMatchMoreOrEqual(); // // public int getInterval(); // // public String getName(); // // public boolean isEnabled(); // // public String getStreamId(); // // public boolean isInReport(); // // public List<String> getReportSchedules(); // // public String getAlertConditionId(); // // public boolean shouldRepeatNotifications(); // // public long getBacklog(); // } // Path: src/main/java/org/graylog/plugins/aggregates/report/ReportFactory.java import java.awt.Graphics2D; import java.awt.geom.Rectangle2D; import java.io.OutputStream; import java.text.ParseException; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Map; import org.graylog.plugins.aggregates.history.HistoryAggregateItem; import org.graylog.plugins.aggregates.report.schedule.ReportSchedule; import org.graylog.plugins.aggregates.rule.Rule; import org.jfree.chart.JFreeChart; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.itextpdf.awt.DefaultFontMapper; import com.itextpdf.text.Document; import com.itextpdf.text.PageSize; import com.itextpdf.text.Paragraph; import com.itextpdf.text.pdf.PdfContentByte; import com.itextpdf.text.pdf.PdfTemplate; import com.itextpdf.text.pdf.PdfWriter; package org.graylog.plugins.aggregates.report; public class ReportFactory { private static final Logger LOG = LoggerFactory.getLogger(ReportFactory.class);
public static void createReport(Map<Rule, List<HistoryAggregateItem>> series, Map<Rule, ReportSchedule> ruleScheduleMapping, Calendar cal, OutputStream outputStream, String hostname) throws ParseException {
cvtienhoven/graylog-plugin-aggregates
src/main/java/org/graylog/plugins/aggregates/report/ReportFactory.java
// Path: src/main/java/org/graylog/plugins/aggregates/history/HistoryAggregateItem.java // public interface HistoryAggregateItem { // public String getMoment(); // // public long getNumberOfHits(); // // } // // Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/ReportSchedule.java // public interface ReportSchedule { // // public String getId(); // // public String getName(); // // public String getExpression(); // // public String getTimespan(); // // public boolean isDefaultSchedule(); // // public Long getNextFireTime(); // // public List<String> getReportReceivers(); // } // // Path: src/main/java/org/graylog/plugins/aggregates/rule/Rule.java // public interface Rule { // // public String getQuery(); // // public String getField(); // // public long getNumberOfMatches(); // // public boolean isMatchMoreOrEqual(); // // public int getInterval(); // // public String getName(); // // public boolean isEnabled(); // // public String getStreamId(); // // public boolean isInReport(); // // public List<String> getReportSchedules(); // // public String getAlertConditionId(); // // public boolean shouldRepeatNotifications(); // // public long getBacklog(); // }
import java.awt.Graphics2D; import java.awt.geom.Rectangle2D; import java.io.OutputStream; import java.text.ParseException; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Map; import org.graylog.plugins.aggregates.history.HistoryAggregateItem; import org.graylog.plugins.aggregates.report.schedule.ReportSchedule; import org.graylog.plugins.aggregates.rule.Rule; import org.jfree.chart.JFreeChart; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.itextpdf.awt.DefaultFontMapper; import com.itextpdf.text.Document; import com.itextpdf.text.PageSize; import com.itextpdf.text.Paragraph; import com.itextpdf.text.pdf.PdfContentByte; import com.itextpdf.text.pdf.PdfTemplate; import com.itextpdf.text.pdf.PdfWriter;
package org.graylog.plugins.aggregates.report; public class ReportFactory { private static final Logger LOG = LoggerFactory.getLogger(ReportFactory.class);
// Path: src/main/java/org/graylog/plugins/aggregates/history/HistoryAggregateItem.java // public interface HistoryAggregateItem { // public String getMoment(); // // public long getNumberOfHits(); // // } // // Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/ReportSchedule.java // public interface ReportSchedule { // // public String getId(); // // public String getName(); // // public String getExpression(); // // public String getTimespan(); // // public boolean isDefaultSchedule(); // // public Long getNextFireTime(); // // public List<String> getReportReceivers(); // } // // Path: src/main/java/org/graylog/plugins/aggregates/rule/Rule.java // public interface Rule { // // public String getQuery(); // // public String getField(); // // public long getNumberOfMatches(); // // public boolean isMatchMoreOrEqual(); // // public int getInterval(); // // public String getName(); // // public boolean isEnabled(); // // public String getStreamId(); // // public boolean isInReport(); // // public List<String> getReportSchedules(); // // public String getAlertConditionId(); // // public boolean shouldRepeatNotifications(); // // public long getBacklog(); // } // Path: src/main/java/org/graylog/plugins/aggregates/report/ReportFactory.java import java.awt.Graphics2D; import java.awt.geom.Rectangle2D; import java.io.OutputStream; import java.text.ParseException; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Map; import org.graylog.plugins.aggregates.history.HistoryAggregateItem; import org.graylog.plugins.aggregates.report.schedule.ReportSchedule; import org.graylog.plugins.aggregates.rule.Rule; import org.jfree.chart.JFreeChart; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.itextpdf.awt.DefaultFontMapper; import com.itextpdf.text.Document; import com.itextpdf.text.PageSize; import com.itextpdf.text.Paragraph; import com.itextpdf.text.pdf.PdfContentByte; import com.itextpdf.text.pdf.PdfTemplate; import com.itextpdf.text.pdf.PdfWriter; package org.graylog.plugins.aggregates.report; public class ReportFactory { private static final Logger LOG = LoggerFactory.getLogger(ReportFactory.class);
public static void createReport(Map<Rule, List<HistoryAggregateItem>> series, Map<Rule, ReportSchedule> ruleScheduleMapping, Calendar cal, OutputStream outputStream, String hostname) throws ParseException {
cvtienhoven/graylog-plugin-aggregates
src/main/java/org/graylog/plugins/aggregates/report/ReportFactory.java
// Path: src/main/java/org/graylog/plugins/aggregates/history/HistoryAggregateItem.java // public interface HistoryAggregateItem { // public String getMoment(); // // public long getNumberOfHits(); // // } // // Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/ReportSchedule.java // public interface ReportSchedule { // // public String getId(); // // public String getName(); // // public String getExpression(); // // public String getTimespan(); // // public boolean isDefaultSchedule(); // // public Long getNextFireTime(); // // public List<String> getReportReceivers(); // } // // Path: src/main/java/org/graylog/plugins/aggregates/rule/Rule.java // public interface Rule { // // public String getQuery(); // // public String getField(); // // public long getNumberOfMatches(); // // public boolean isMatchMoreOrEqual(); // // public int getInterval(); // // public String getName(); // // public boolean isEnabled(); // // public String getStreamId(); // // public boolean isInReport(); // // public List<String> getReportSchedules(); // // public String getAlertConditionId(); // // public boolean shouldRepeatNotifications(); // // public long getBacklog(); // }
import java.awt.Graphics2D; import java.awt.geom.Rectangle2D; import java.io.OutputStream; import java.text.ParseException; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Map; import org.graylog.plugins.aggregates.history.HistoryAggregateItem; import org.graylog.plugins.aggregates.report.schedule.ReportSchedule; import org.graylog.plugins.aggregates.rule.Rule; import org.jfree.chart.JFreeChart; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.itextpdf.awt.DefaultFontMapper; import com.itextpdf.text.Document; import com.itextpdf.text.PageSize; import com.itextpdf.text.Paragraph; import com.itextpdf.text.pdf.PdfContentByte; import com.itextpdf.text.pdf.PdfTemplate; import com.itextpdf.text.pdf.PdfWriter;
package org.graylog.plugins.aggregates.report; public class ReportFactory { private static final Logger LOG = LoggerFactory.getLogger(ReportFactory.class);
// Path: src/main/java/org/graylog/plugins/aggregates/history/HistoryAggregateItem.java // public interface HistoryAggregateItem { // public String getMoment(); // // public long getNumberOfHits(); // // } // // Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/ReportSchedule.java // public interface ReportSchedule { // // public String getId(); // // public String getName(); // // public String getExpression(); // // public String getTimespan(); // // public boolean isDefaultSchedule(); // // public Long getNextFireTime(); // // public List<String> getReportReceivers(); // } // // Path: src/main/java/org/graylog/plugins/aggregates/rule/Rule.java // public interface Rule { // // public String getQuery(); // // public String getField(); // // public long getNumberOfMatches(); // // public boolean isMatchMoreOrEqual(); // // public int getInterval(); // // public String getName(); // // public boolean isEnabled(); // // public String getStreamId(); // // public boolean isInReport(); // // public List<String> getReportSchedules(); // // public String getAlertConditionId(); // // public boolean shouldRepeatNotifications(); // // public long getBacklog(); // } // Path: src/main/java/org/graylog/plugins/aggregates/report/ReportFactory.java import java.awt.Graphics2D; import java.awt.geom.Rectangle2D; import java.io.OutputStream; import java.text.ParseException; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Map; import org.graylog.plugins.aggregates.history.HistoryAggregateItem; import org.graylog.plugins.aggregates.report.schedule.ReportSchedule; import org.graylog.plugins.aggregates.rule.Rule; import org.jfree.chart.JFreeChart; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.itextpdf.awt.DefaultFontMapper; import com.itextpdf.text.Document; import com.itextpdf.text.PageSize; import com.itextpdf.text.Paragraph; import com.itextpdf.text.pdf.PdfContentByte; import com.itextpdf.text.pdf.PdfTemplate; import com.itextpdf.text.pdf.PdfWriter; package org.graylog.plugins.aggregates.report; public class ReportFactory { private static final Logger LOG = LoggerFactory.getLogger(ReportFactory.class);
public static void createReport(Map<Rule, List<HistoryAggregateItem>> series, Map<Rule, ReportSchedule> ruleScheduleMapping, Calendar cal, OutputStream outputStream, String hostname) throws ParseException {
cvtienhoven/graylog-plugin-aggregates
src/main/java/org/graylog/plugins/aggregates/report/schedule/ReportScheduleServiceImpl.java
// Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/rest/models/requests/AddReportScheduleRequest.java // @AutoValue // @JsonAutoDetect // public abstract class AddReportScheduleRequest { // // @JsonProperty("reportSchedule") // @NotNull // public abstract ReportScheduleImpl getReportSchedule(); // // @JsonCreator // public static AddReportScheduleRequest create(//@JsonProperty("name") @Valid String name, // @JsonProperty("reportSchedule") @Valid ReportScheduleImpl reportSchedule // // ) { // return new AutoValue_AddReportScheduleRequest(reportSchedule); // } // } // // Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/rest/models/requests/UpdateReportScheduleRequest.java // @AutoValue // @JsonAutoDetect // public abstract class UpdateReportScheduleRequest { // // // @JsonProperty("reportSchedule") // @NotNull // public abstract ReportScheduleImpl getReportSchedule(); // // @JsonCreator // public static UpdateReportScheduleRequest create( // @JsonProperty("reportSchedule") @Valid ReportScheduleImpl reportSchedule // ) { // return new AutoValue_UpdateReportScheduleRequest(reportSchedule); // } // } // // Path: src/main/java/org/graylog/plugins/aggregates/rule/RuleImpl.java // @AutoValue // @JsonAutoDetect // @JsonIgnoreProperties(ignoreUnknown = true) // @CollectionName("aggregate_rules") // public abstract class RuleImpl implements Rule{ // // // @JsonProperty("query") // @Override // @NotNull // public abstract String getQuery(); // // @JsonProperty("field") // @Override // @NotNull // public abstract String getField(); // // @JsonProperty("numberOfMatches") // @Override // @Min(1) // public abstract long getNumberOfMatches(); // // @JsonProperty("matchMoreOrEqual") // @Override // public abstract boolean isMatchMoreOrEqual(); // // @JsonProperty("interval") // @Override // @Min(1) // public abstract int getInterval(); // // @JsonProperty("name") // @Override // @NotNull // public abstract String getName(); // // @JsonProperty("enabled") // @Override // public abstract boolean isEnabled(); // // @JsonProperty("streamId") // @Override // public abstract String getStreamId(); // // @JsonProperty("inReport") // @Override // public abstract boolean isInReport(); // // @JsonProperty("reportSchedules") // @Override // @Nullable // public abstract List<String> getReportSchedules(); // // @JsonProperty("alertConditionId") // @Override // @Nullable // public abstract String getAlertConditionId(); // // @JsonProperty("repeatNotifications") // @Override // @Nullable // public abstract boolean shouldRepeatNotifications(); // // @JsonProperty("backlog") // @Override // @Nullable // @Min(0) // public abstract long getBacklog(); // // @JsonCreator // public static RuleImpl create(@JsonProperty("_id") String objectId, // @JsonProperty("query") String query, // @JsonProperty("field") String field, // @JsonProperty("numberOfMatches") long numberOfMatches, // @JsonProperty("matchMoreOrEqual") boolean matchMoreOrEqual, // @JsonProperty("interval") int interval, // @JsonProperty("name") String name, // @JsonProperty("enabled") boolean enabled, // @JsonProperty("streamId") String streamId, // @JsonProperty("inReport") boolean inReport, // @JsonProperty("reportSchedules") List<String> reportSchedules, // @JsonProperty("alertConditionId") String alertConditionId, // @JsonProperty("repeatNotifications") boolean repeatNotifications, // @JsonProperty("backlog") long backlog) { // return new AutoValue_RuleImpl(query, field, numberOfMatches, matchMoreOrEqual, interval, name, enabled, streamId, inReport, reportSchedules, alertConditionId, repeatNotifications, backlog); // } // // public static RuleImpl create( // String query, // String field, // long numberOfMatches, // boolean matchMoreOrEqual, // int interval, // String name, // boolean enabled, // String streamId, // boolean inReport, // List<String> reportSchedules, // String alertConditionId, // boolean repeatNotifications, // long backlog) { // return new AutoValue_RuleImpl(query, field, numberOfMatches, matchMoreOrEqual, interval, name, enabled, streamId, inReport, reportSchedules, alertConditionId, repeatNotifications, backlog); // // } // }
import com.google.common.collect.Lists; import com.mongodb.BasicDBObject; import com.mongodb.DBCollection; import org.bson.types.ObjectId; import org.drools.core.time.impl.CronExpression; import org.graylog.plugins.aggregates.report.schedule.rest.models.requests.AddReportScheduleRequest; import org.graylog.plugins.aggregates.report.schedule.rest.models.requests.UpdateReportScheduleRequest; import org.graylog.plugins.aggregates.rule.RuleImpl; import org.graylog2.bindings.providers.MongoJackObjectMapperProvider; import org.graylog2.database.CollectionName; import org.graylog2.database.MongoConnection; import org.mongojack.DBCursor; import org.mongojack.DBQuery; import org.mongojack.DBUpdate; import org.mongojack.JacksonDBCollection; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.inject.Inject; import javax.validation.ConstraintViolation; import javax.validation.Validator; import java.text.ParseException; import java.util.Date; import java.util.List; import java.util.Set;
package org.graylog.plugins.aggregates.report.schedule; public class ReportScheduleServiceImpl implements ReportScheduleService { private final JacksonDBCollection<ReportScheduleImpl, String> coll;
// Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/rest/models/requests/AddReportScheduleRequest.java // @AutoValue // @JsonAutoDetect // public abstract class AddReportScheduleRequest { // // @JsonProperty("reportSchedule") // @NotNull // public abstract ReportScheduleImpl getReportSchedule(); // // @JsonCreator // public static AddReportScheduleRequest create(//@JsonProperty("name") @Valid String name, // @JsonProperty("reportSchedule") @Valid ReportScheduleImpl reportSchedule // // ) { // return new AutoValue_AddReportScheduleRequest(reportSchedule); // } // } // // Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/rest/models/requests/UpdateReportScheduleRequest.java // @AutoValue // @JsonAutoDetect // public abstract class UpdateReportScheduleRequest { // // // @JsonProperty("reportSchedule") // @NotNull // public abstract ReportScheduleImpl getReportSchedule(); // // @JsonCreator // public static UpdateReportScheduleRequest create( // @JsonProperty("reportSchedule") @Valid ReportScheduleImpl reportSchedule // ) { // return new AutoValue_UpdateReportScheduleRequest(reportSchedule); // } // } // // Path: src/main/java/org/graylog/plugins/aggregates/rule/RuleImpl.java // @AutoValue // @JsonAutoDetect // @JsonIgnoreProperties(ignoreUnknown = true) // @CollectionName("aggregate_rules") // public abstract class RuleImpl implements Rule{ // // // @JsonProperty("query") // @Override // @NotNull // public abstract String getQuery(); // // @JsonProperty("field") // @Override // @NotNull // public abstract String getField(); // // @JsonProperty("numberOfMatches") // @Override // @Min(1) // public abstract long getNumberOfMatches(); // // @JsonProperty("matchMoreOrEqual") // @Override // public abstract boolean isMatchMoreOrEqual(); // // @JsonProperty("interval") // @Override // @Min(1) // public abstract int getInterval(); // // @JsonProperty("name") // @Override // @NotNull // public abstract String getName(); // // @JsonProperty("enabled") // @Override // public abstract boolean isEnabled(); // // @JsonProperty("streamId") // @Override // public abstract String getStreamId(); // // @JsonProperty("inReport") // @Override // public abstract boolean isInReport(); // // @JsonProperty("reportSchedules") // @Override // @Nullable // public abstract List<String> getReportSchedules(); // // @JsonProperty("alertConditionId") // @Override // @Nullable // public abstract String getAlertConditionId(); // // @JsonProperty("repeatNotifications") // @Override // @Nullable // public abstract boolean shouldRepeatNotifications(); // // @JsonProperty("backlog") // @Override // @Nullable // @Min(0) // public abstract long getBacklog(); // // @JsonCreator // public static RuleImpl create(@JsonProperty("_id") String objectId, // @JsonProperty("query") String query, // @JsonProperty("field") String field, // @JsonProperty("numberOfMatches") long numberOfMatches, // @JsonProperty("matchMoreOrEqual") boolean matchMoreOrEqual, // @JsonProperty("interval") int interval, // @JsonProperty("name") String name, // @JsonProperty("enabled") boolean enabled, // @JsonProperty("streamId") String streamId, // @JsonProperty("inReport") boolean inReport, // @JsonProperty("reportSchedules") List<String> reportSchedules, // @JsonProperty("alertConditionId") String alertConditionId, // @JsonProperty("repeatNotifications") boolean repeatNotifications, // @JsonProperty("backlog") long backlog) { // return new AutoValue_RuleImpl(query, field, numberOfMatches, matchMoreOrEqual, interval, name, enabled, streamId, inReport, reportSchedules, alertConditionId, repeatNotifications, backlog); // } // // public static RuleImpl create( // String query, // String field, // long numberOfMatches, // boolean matchMoreOrEqual, // int interval, // String name, // boolean enabled, // String streamId, // boolean inReport, // List<String> reportSchedules, // String alertConditionId, // boolean repeatNotifications, // long backlog) { // return new AutoValue_RuleImpl(query, field, numberOfMatches, matchMoreOrEqual, interval, name, enabled, streamId, inReport, reportSchedules, alertConditionId, repeatNotifications, backlog); // // } // } // Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/ReportScheduleServiceImpl.java import com.google.common.collect.Lists; import com.mongodb.BasicDBObject; import com.mongodb.DBCollection; import org.bson.types.ObjectId; import org.drools.core.time.impl.CronExpression; import org.graylog.plugins.aggregates.report.schedule.rest.models.requests.AddReportScheduleRequest; import org.graylog.plugins.aggregates.report.schedule.rest.models.requests.UpdateReportScheduleRequest; import org.graylog.plugins.aggregates.rule.RuleImpl; import org.graylog2.bindings.providers.MongoJackObjectMapperProvider; import org.graylog2.database.CollectionName; import org.graylog2.database.MongoConnection; import org.mongojack.DBCursor; import org.mongojack.DBQuery; import org.mongojack.DBUpdate; import org.mongojack.JacksonDBCollection; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.inject.Inject; import javax.validation.ConstraintViolation; import javax.validation.Validator; import java.text.ParseException; import java.util.Date; import java.util.List; import java.util.Set; package org.graylog.plugins.aggregates.report.schedule; public class ReportScheduleServiceImpl implements ReportScheduleService { private final JacksonDBCollection<ReportScheduleImpl, String> coll;
private final JacksonDBCollection<RuleImpl, String> ruleColl;
cvtienhoven/graylog-plugin-aggregates
src/main/java/org/graylog/plugins/aggregates/report/schedule/rest/models/responses/ReportSchedulesList.java
// Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/ReportSchedule.java // public interface ReportSchedule { // // public String getId(); // // public String getName(); // // public String getExpression(); // // public String getTimespan(); // // public boolean isDefaultSchedule(); // // public Long getNextFireTime(); // // public List<String> getReportReceivers(); // }
import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.auto.value.AutoValue; import java.util.List; import org.graylog.plugins.aggregates.report.schedule.ReportSchedule;
package org.graylog.plugins.aggregates.report.schedule.rest.models.responses; @AutoValue @JsonAutoDetect public abstract class ReportSchedulesList { @JsonProperty
// Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/ReportSchedule.java // public interface ReportSchedule { // // public String getId(); // // public String getName(); // // public String getExpression(); // // public String getTimespan(); // // public boolean isDefaultSchedule(); // // public Long getNextFireTime(); // // public List<String> getReportReceivers(); // } // Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/rest/models/responses/ReportSchedulesList.java import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.auto.value.AutoValue; import java.util.List; import org.graylog.plugins.aggregates.report.schedule.ReportSchedule; package org.graylog.plugins.aggregates.report.schedule.rest.models.responses; @AutoValue @JsonAutoDetect public abstract class ReportSchedulesList { @JsonProperty
public abstract List<ReportSchedule> getReportSchedules();
cvtienhoven/graylog-plugin-aggregates
src/main/java/org/graylog/plugins/aggregates/report/ChartFactory.java
// Path: src/main/java/org/graylog/plugins/aggregates/history/HistoryAggregateItem.java // public interface HistoryAggregateItem { // public String getMoment(); // // public long getNumberOfHits(); // // } // // Path: src/main/java/org/graylog/plugins/aggregates/util/AggregatesUtil.java // public class AggregatesUtil { // public final static String ALERT_CONDITION_TYPE = "Aggregates Alert"; // // public static int timespanToSeconds(String timespan, Calendar cal){ // Period period = Period.parse(timespan); // Duration duration = period.toDurationFrom(new DateTime(cal.getTime())); // return duration.toStandardSeconds().getSeconds(); // } // // public static String getAlertConditionDescription(Rule rule){ // String matchDescriptor = rule.getNumberOfMatches() + " or more"; // if (!rule.isMatchMoreOrEqual()){ // matchDescriptor = "less than " + rule.getNumberOfMatches(); // } // return "The same value of field '" + rule.getField() + "' occurs " + matchDescriptor + " times in a " + rule.getInterval() + " minute interval"; // } // // public String buildSummary(Rule rule, EmailConfiguration emailConfiguration, Map<String, Long> matchedTerms, TimeRange timeRange) throws UnsupportedEncodingException { // // final StringBuilder sb = new StringBuilder(); // // sb.append("Matched values for field [ " + rule.getField() + " ]\n"); // // for (Map.Entry<String, Long> entry : matchedTerms.entrySet()) { // // sb.append("\nValue: " + entry.getKey() + "\n"); // sb.append("Occurrences: " + entry.getValue() + "\n"); // // if (!emailConfiguration.isEnabled()) { // sb.append("\n"); // } else { // String streamId = rule.getStreamId(); // String search_uri = ""; // // if (streamId != null && streamId != "") { // search_uri += "/streams/" + streamId; // } // search_uri += "/search?rangetype=absolute&fields=message%2Csource%2C" + rule.getField() + "&from=" + timeRange.getFrom() + "&to=" + timeRange.getTo() + "&q=" + URLEncoder.encode(rule.getQuery() + " AND " + rule.getField() + ":\"" + entry.getKey() + "\"", "UTF-8"); // sb.append("Search: " + emailConfiguration.getWebInterfaceUri() + search_uri + "\n"); // // } // } // return sb.toString(); // // } // // public static Map<String, Object> parametersFromRule(Rule rule){ // String query = rule.getQuery(); // String streamId = rule.getStreamId(); // // Map<String, Object> parameters = new HashMap<String, Object>(); // parameters.put("time", rule.getInterval()); // parameters.put("description", AggregatesUtil.getAlertConditionDescription(rule)); // // if (rule.isMatchMoreOrEqual()){ // parameters.put("threshold_type", AggregatesAlertCondition.ThresholdType.MORE_OR_EQUAL.toString()); // } else { // parameters.put("threshold_type", AggregatesAlertCondition.ThresholdType.LESS.toString()); // } // // parameters.put("threshold", rule.getNumberOfMatches()); // parameters.put("grace", 0); // parameters.put("type", AggregatesUtil.ALERT_CONDITION_TYPE); // parameters.put("field", rule.getField()); // parameters.put("number_of_matches", rule.getNumberOfMatches()); // parameters.put("match_more_or_equal", rule.isMatchMoreOrEqual()); // parameters.put("backlog", rule.getBacklog()); // parameters.put("repeat_notifications", rule.shouldRepeatNotifications()); // parameters.put("interval", rule.getInterval()); // parameters.put("query", query); // parameters.put("rule_name", rule.getName()); // // return parameters; // } // // public static String alertConditionTitleFromRule(Rule rule){ // return "Aggregate rule [" + rule.getName() + "] triggered an alert."; // } // }
import java.awt.Color; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.List; import java.util.TimeZone; import org.graylog.plugins.aggregates.history.HistoryAggregateItem; import org.graylog.plugins.aggregates.util.AggregatesUtil; import org.jfree.chart.JFreeChart; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.XYPlot; import org.jfree.data.time.Day; import org.jfree.data.time.Hour; import org.jfree.data.time.Month; import org.jfree.data.time.TimeSeries; import org.jfree.data.time.TimeSeriesCollection; import org.jfree.data.time.Year; import org.jfree.data.xy.IntervalXYDataset; import org.jfree.data.xy.XYBarDataset; import autovalue.shaded.com.google.common.common.annotations.VisibleForTesting;
package org.graylog.plugins.aggregates.report; public class ChartFactory { private final static int SECONDS_IN_YEAR = 3600*24*366; private final static int SECONDS_IN_MONTH = 3600*24*31; private final static int SECONDS_IN_DAY = 3600*24; private final static int SECONDS_IN_HOUR = 3600; @SuppressWarnings("deprecation") @VisibleForTesting
// Path: src/main/java/org/graylog/plugins/aggregates/history/HistoryAggregateItem.java // public interface HistoryAggregateItem { // public String getMoment(); // // public long getNumberOfHits(); // // } // // Path: src/main/java/org/graylog/plugins/aggregates/util/AggregatesUtil.java // public class AggregatesUtil { // public final static String ALERT_CONDITION_TYPE = "Aggregates Alert"; // // public static int timespanToSeconds(String timespan, Calendar cal){ // Period period = Period.parse(timespan); // Duration duration = period.toDurationFrom(new DateTime(cal.getTime())); // return duration.toStandardSeconds().getSeconds(); // } // // public static String getAlertConditionDescription(Rule rule){ // String matchDescriptor = rule.getNumberOfMatches() + " or more"; // if (!rule.isMatchMoreOrEqual()){ // matchDescriptor = "less than " + rule.getNumberOfMatches(); // } // return "The same value of field '" + rule.getField() + "' occurs " + matchDescriptor + " times in a " + rule.getInterval() + " minute interval"; // } // // public String buildSummary(Rule rule, EmailConfiguration emailConfiguration, Map<String, Long> matchedTerms, TimeRange timeRange) throws UnsupportedEncodingException { // // final StringBuilder sb = new StringBuilder(); // // sb.append("Matched values for field [ " + rule.getField() + " ]\n"); // // for (Map.Entry<String, Long> entry : matchedTerms.entrySet()) { // // sb.append("\nValue: " + entry.getKey() + "\n"); // sb.append("Occurrences: " + entry.getValue() + "\n"); // // if (!emailConfiguration.isEnabled()) { // sb.append("\n"); // } else { // String streamId = rule.getStreamId(); // String search_uri = ""; // // if (streamId != null && streamId != "") { // search_uri += "/streams/" + streamId; // } // search_uri += "/search?rangetype=absolute&fields=message%2Csource%2C" + rule.getField() + "&from=" + timeRange.getFrom() + "&to=" + timeRange.getTo() + "&q=" + URLEncoder.encode(rule.getQuery() + " AND " + rule.getField() + ":\"" + entry.getKey() + "\"", "UTF-8"); // sb.append("Search: " + emailConfiguration.getWebInterfaceUri() + search_uri + "\n"); // // } // } // return sb.toString(); // // } // // public static Map<String, Object> parametersFromRule(Rule rule){ // String query = rule.getQuery(); // String streamId = rule.getStreamId(); // // Map<String, Object> parameters = new HashMap<String, Object>(); // parameters.put("time", rule.getInterval()); // parameters.put("description", AggregatesUtil.getAlertConditionDescription(rule)); // // if (rule.isMatchMoreOrEqual()){ // parameters.put("threshold_type", AggregatesAlertCondition.ThresholdType.MORE_OR_EQUAL.toString()); // } else { // parameters.put("threshold_type", AggregatesAlertCondition.ThresholdType.LESS.toString()); // } // // parameters.put("threshold", rule.getNumberOfMatches()); // parameters.put("grace", 0); // parameters.put("type", AggregatesUtil.ALERT_CONDITION_TYPE); // parameters.put("field", rule.getField()); // parameters.put("number_of_matches", rule.getNumberOfMatches()); // parameters.put("match_more_or_equal", rule.isMatchMoreOrEqual()); // parameters.put("backlog", rule.getBacklog()); // parameters.put("repeat_notifications", rule.shouldRepeatNotifications()); // parameters.put("interval", rule.getInterval()); // parameters.put("query", query); // parameters.put("rule_name", rule.getName()); // // return parameters; // } // // public static String alertConditionTitleFromRule(Rule rule){ // return "Aggregate rule [" + rule.getName() + "] triggered an alert."; // } // } // Path: src/main/java/org/graylog/plugins/aggregates/report/ChartFactory.java import java.awt.Color; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.List; import java.util.TimeZone; import org.graylog.plugins.aggregates.history.HistoryAggregateItem; import org.graylog.plugins.aggregates.util.AggregatesUtil; import org.jfree.chart.JFreeChart; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.XYPlot; import org.jfree.data.time.Day; import org.jfree.data.time.Hour; import org.jfree.data.time.Month; import org.jfree.data.time.TimeSeries; import org.jfree.data.time.TimeSeriesCollection; import org.jfree.data.time.Year; import org.jfree.data.xy.IntervalXYDataset; import org.jfree.data.xy.XYBarDataset; import autovalue.shaded.com.google.common.common.annotations.VisibleForTesting; package org.graylog.plugins.aggregates.report; public class ChartFactory { private final static int SECONDS_IN_YEAR = 3600*24*366; private final static int SECONDS_IN_MONTH = 3600*24*31; private final static int SECONDS_IN_DAY = 3600*24; private final static int SECONDS_IN_HOUR = 3600; @SuppressWarnings("deprecation") @VisibleForTesting
private static TimeSeries initializeSeries(String timespan, Calendar calParam, List<HistoryAggregateItem> history) throws ParseException{
cvtienhoven/graylog-plugin-aggregates
src/main/java/org/graylog/plugins/aggregates/report/ChartFactory.java
// Path: src/main/java/org/graylog/plugins/aggregates/history/HistoryAggregateItem.java // public interface HistoryAggregateItem { // public String getMoment(); // // public long getNumberOfHits(); // // } // // Path: src/main/java/org/graylog/plugins/aggregates/util/AggregatesUtil.java // public class AggregatesUtil { // public final static String ALERT_CONDITION_TYPE = "Aggregates Alert"; // // public static int timespanToSeconds(String timespan, Calendar cal){ // Period period = Period.parse(timespan); // Duration duration = period.toDurationFrom(new DateTime(cal.getTime())); // return duration.toStandardSeconds().getSeconds(); // } // // public static String getAlertConditionDescription(Rule rule){ // String matchDescriptor = rule.getNumberOfMatches() + " or more"; // if (!rule.isMatchMoreOrEqual()){ // matchDescriptor = "less than " + rule.getNumberOfMatches(); // } // return "The same value of field '" + rule.getField() + "' occurs " + matchDescriptor + " times in a " + rule.getInterval() + " minute interval"; // } // // public String buildSummary(Rule rule, EmailConfiguration emailConfiguration, Map<String, Long> matchedTerms, TimeRange timeRange) throws UnsupportedEncodingException { // // final StringBuilder sb = new StringBuilder(); // // sb.append("Matched values for field [ " + rule.getField() + " ]\n"); // // for (Map.Entry<String, Long> entry : matchedTerms.entrySet()) { // // sb.append("\nValue: " + entry.getKey() + "\n"); // sb.append("Occurrences: " + entry.getValue() + "\n"); // // if (!emailConfiguration.isEnabled()) { // sb.append("\n"); // } else { // String streamId = rule.getStreamId(); // String search_uri = ""; // // if (streamId != null && streamId != "") { // search_uri += "/streams/" + streamId; // } // search_uri += "/search?rangetype=absolute&fields=message%2Csource%2C" + rule.getField() + "&from=" + timeRange.getFrom() + "&to=" + timeRange.getTo() + "&q=" + URLEncoder.encode(rule.getQuery() + " AND " + rule.getField() + ":\"" + entry.getKey() + "\"", "UTF-8"); // sb.append("Search: " + emailConfiguration.getWebInterfaceUri() + search_uri + "\n"); // // } // } // return sb.toString(); // // } // // public static Map<String, Object> parametersFromRule(Rule rule){ // String query = rule.getQuery(); // String streamId = rule.getStreamId(); // // Map<String, Object> parameters = new HashMap<String, Object>(); // parameters.put("time", rule.getInterval()); // parameters.put("description", AggregatesUtil.getAlertConditionDescription(rule)); // // if (rule.isMatchMoreOrEqual()){ // parameters.put("threshold_type", AggregatesAlertCondition.ThresholdType.MORE_OR_EQUAL.toString()); // } else { // parameters.put("threshold_type", AggregatesAlertCondition.ThresholdType.LESS.toString()); // } // // parameters.put("threshold", rule.getNumberOfMatches()); // parameters.put("grace", 0); // parameters.put("type", AggregatesUtil.ALERT_CONDITION_TYPE); // parameters.put("field", rule.getField()); // parameters.put("number_of_matches", rule.getNumberOfMatches()); // parameters.put("match_more_or_equal", rule.isMatchMoreOrEqual()); // parameters.put("backlog", rule.getBacklog()); // parameters.put("repeat_notifications", rule.shouldRepeatNotifications()); // parameters.put("interval", rule.getInterval()); // parameters.put("query", query); // parameters.put("rule_name", rule.getName()); // // return parameters; // } // // public static String alertConditionTitleFromRule(Rule rule){ // return "Aggregate rule [" + rule.getName() + "] triggered an alert."; // } // }
import java.awt.Color; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.List; import java.util.TimeZone; import org.graylog.plugins.aggregates.history.HistoryAggregateItem; import org.graylog.plugins.aggregates.util.AggregatesUtil; import org.jfree.chart.JFreeChart; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.XYPlot; import org.jfree.data.time.Day; import org.jfree.data.time.Hour; import org.jfree.data.time.Month; import org.jfree.data.time.TimeSeries; import org.jfree.data.time.TimeSeriesCollection; import org.jfree.data.time.Year; import org.jfree.data.xy.IntervalXYDataset; import org.jfree.data.xy.XYBarDataset; import autovalue.shaded.com.google.common.common.annotations.VisibleForTesting;
package org.graylog.plugins.aggregates.report; public class ChartFactory { private final static int SECONDS_IN_YEAR = 3600*24*366; private final static int SECONDS_IN_MONTH = 3600*24*31; private final static int SECONDS_IN_DAY = 3600*24; private final static int SECONDS_IN_HOUR = 3600; @SuppressWarnings("deprecation") @VisibleForTesting private static TimeSeries initializeSeries(String timespan, Calendar calParam, List<HistoryAggregateItem> history) throws ParseException{ Calendar cal = (Calendar) calParam.clone();
// Path: src/main/java/org/graylog/plugins/aggregates/history/HistoryAggregateItem.java // public interface HistoryAggregateItem { // public String getMoment(); // // public long getNumberOfHits(); // // } // // Path: src/main/java/org/graylog/plugins/aggregates/util/AggregatesUtil.java // public class AggregatesUtil { // public final static String ALERT_CONDITION_TYPE = "Aggregates Alert"; // // public static int timespanToSeconds(String timespan, Calendar cal){ // Period period = Period.parse(timespan); // Duration duration = period.toDurationFrom(new DateTime(cal.getTime())); // return duration.toStandardSeconds().getSeconds(); // } // // public static String getAlertConditionDescription(Rule rule){ // String matchDescriptor = rule.getNumberOfMatches() + " or more"; // if (!rule.isMatchMoreOrEqual()){ // matchDescriptor = "less than " + rule.getNumberOfMatches(); // } // return "The same value of field '" + rule.getField() + "' occurs " + matchDescriptor + " times in a " + rule.getInterval() + " minute interval"; // } // // public String buildSummary(Rule rule, EmailConfiguration emailConfiguration, Map<String, Long> matchedTerms, TimeRange timeRange) throws UnsupportedEncodingException { // // final StringBuilder sb = new StringBuilder(); // // sb.append("Matched values for field [ " + rule.getField() + " ]\n"); // // for (Map.Entry<String, Long> entry : matchedTerms.entrySet()) { // // sb.append("\nValue: " + entry.getKey() + "\n"); // sb.append("Occurrences: " + entry.getValue() + "\n"); // // if (!emailConfiguration.isEnabled()) { // sb.append("\n"); // } else { // String streamId = rule.getStreamId(); // String search_uri = ""; // // if (streamId != null && streamId != "") { // search_uri += "/streams/" + streamId; // } // search_uri += "/search?rangetype=absolute&fields=message%2Csource%2C" + rule.getField() + "&from=" + timeRange.getFrom() + "&to=" + timeRange.getTo() + "&q=" + URLEncoder.encode(rule.getQuery() + " AND " + rule.getField() + ":\"" + entry.getKey() + "\"", "UTF-8"); // sb.append("Search: " + emailConfiguration.getWebInterfaceUri() + search_uri + "\n"); // // } // } // return sb.toString(); // // } // // public static Map<String, Object> parametersFromRule(Rule rule){ // String query = rule.getQuery(); // String streamId = rule.getStreamId(); // // Map<String, Object> parameters = new HashMap<String, Object>(); // parameters.put("time", rule.getInterval()); // parameters.put("description", AggregatesUtil.getAlertConditionDescription(rule)); // // if (rule.isMatchMoreOrEqual()){ // parameters.put("threshold_type", AggregatesAlertCondition.ThresholdType.MORE_OR_EQUAL.toString()); // } else { // parameters.put("threshold_type", AggregatesAlertCondition.ThresholdType.LESS.toString()); // } // // parameters.put("threshold", rule.getNumberOfMatches()); // parameters.put("grace", 0); // parameters.put("type", AggregatesUtil.ALERT_CONDITION_TYPE); // parameters.put("field", rule.getField()); // parameters.put("number_of_matches", rule.getNumberOfMatches()); // parameters.put("match_more_or_equal", rule.isMatchMoreOrEqual()); // parameters.put("backlog", rule.getBacklog()); // parameters.put("repeat_notifications", rule.shouldRepeatNotifications()); // parameters.put("interval", rule.getInterval()); // parameters.put("query", query); // parameters.put("rule_name", rule.getName()); // // return parameters; // } // // public static String alertConditionTitleFromRule(Rule rule){ // return "Aggregate rule [" + rule.getName() + "] triggered an alert."; // } // } // Path: src/main/java/org/graylog/plugins/aggregates/report/ChartFactory.java import java.awt.Color; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.List; import java.util.TimeZone; import org.graylog.plugins.aggregates.history.HistoryAggregateItem; import org.graylog.plugins.aggregates.util.AggregatesUtil; import org.jfree.chart.JFreeChart; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.XYPlot; import org.jfree.data.time.Day; import org.jfree.data.time.Hour; import org.jfree.data.time.Month; import org.jfree.data.time.TimeSeries; import org.jfree.data.time.TimeSeriesCollection; import org.jfree.data.time.Year; import org.jfree.data.xy.IntervalXYDataset; import org.jfree.data.xy.XYBarDataset; import autovalue.shaded.com.google.common.common.annotations.VisibleForTesting; package org.graylog.plugins.aggregates.report; public class ChartFactory { private final static int SECONDS_IN_YEAR = 3600*24*366; private final static int SECONDS_IN_MONTH = 3600*24*31; private final static int SECONDS_IN_DAY = 3600*24; private final static int SECONDS_IN_HOUR = 3600; @SuppressWarnings("deprecation") @VisibleForTesting private static TimeSeries initializeSeries(String timespan, Calendar calParam, List<HistoryAggregateItem> history) throws ParseException{ Calendar cal = (Calendar) calParam.clone();
int seconds = AggregatesUtil.timespanToSeconds(timespan, cal);
cvtienhoven/graylog-plugin-aggregates
src/main/java/org/graylog/plugins/aggregates/report/schedule/ReportScheduleService.java
// Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/rest/models/requests/AddReportScheduleRequest.java // @AutoValue // @JsonAutoDetect // public abstract class AddReportScheduleRequest { // // @JsonProperty("reportSchedule") // @NotNull // public abstract ReportScheduleImpl getReportSchedule(); // // @JsonCreator // public static AddReportScheduleRequest create(//@JsonProperty("name") @Valid String name, // @JsonProperty("reportSchedule") @Valid ReportScheduleImpl reportSchedule // // ) { // return new AutoValue_AddReportScheduleRequest(reportSchedule); // } // } // // Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/rest/models/requests/UpdateReportScheduleRequest.java // @AutoValue // @JsonAutoDetect // public abstract class UpdateReportScheduleRequest { // // // @JsonProperty("reportSchedule") // @NotNull // public abstract ReportScheduleImpl getReportSchedule(); // // @JsonCreator // public static UpdateReportScheduleRequest create( // @JsonProperty("reportSchedule") @Valid ReportScheduleImpl reportSchedule // ) { // return new AutoValue_UpdateReportScheduleRequest(reportSchedule); // } // }
import java.io.UnsupportedEncodingException; import java.util.Date; import java.util.List; import org.graylog.plugins.aggregates.report.schedule.rest.models.requests.AddReportScheduleRequest; import org.graylog.plugins.aggregates.report.schedule.rest.models.requests.UpdateReportScheduleRequest; import com.mongodb.MongoException;
package org.graylog.plugins.aggregates.report.schedule; public interface ReportScheduleService { long count(); ReportSchedule update(String name, ReportSchedule schedule); ReportSchedule create(ReportSchedule schedule); List<ReportSchedule> all(); int destroy(String scheduleName) throws MongoException, UnsupportedEncodingException;
// Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/rest/models/requests/AddReportScheduleRequest.java // @AutoValue // @JsonAutoDetect // public abstract class AddReportScheduleRequest { // // @JsonProperty("reportSchedule") // @NotNull // public abstract ReportScheduleImpl getReportSchedule(); // // @JsonCreator // public static AddReportScheduleRequest create(//@JsonProperty("name") @Valid String name, // @JsonProperty("reportSchedule") @Valid ReportScheduleImpl reportSchedule // // ) { // return new AutoValue_AddReportScheduleRequest(reportSchedule); // } // } // // Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/rest/models/requests/UpdateReportScheduleRequest.java // @AutoValue // @JsonAutoDetect // public abstract class UpdateReportScheduleRequest { // // // @JsonProperty("reportSchedule") // @NotNull // public abstract ReportScheduleImpl getReportSchedule(); // // @JsonCreator // public static UpdateReportScheduleRequest create( // @JsonProperty("reportSchedule") @Valid ReportScheduleImpl reportSchedule // ) { // return new AutoValue_UpdateReportScheduleRequest(reportSchedule); // } // } // Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/ReportScheduleService.java import java.io.UnsupportedEncodingException; import java.util.Date; import java.util.List; import org.graylog.plugins.aggregates.report.schedule.rest.models.requests.AddReportScheduleRequest; import org.graylog.plugins.aggregates.report.schedule.rest.models.requests.UpdateReportScheduleRequest; import com.mongodb.MongoException; package org.graylog.plugins.aggregates.report.schedule; public interface ReportScheduleService { long count(); ReportSchedule update(String name, ReportSchedule schedule); ReportSchedule create(ReportSchedule schedule); List<ReportSchedule> all(); int destroy(String scheduleName) throws MongoException, UnsupportedEncodingException;
ReportSchedule fromRequest(AddReportScheduleRequest request);
cvtienhoven/graylog-plugin-aggregates
src/main/java/org/graylog/plugins/aggregates/report/schedule/ReportScheduleService.java
// Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/rest/models/requests/AddReportScheduleRequest.java // @AutoValue // @JsonAutoDetect // public abstract class AddReportScheduleRequest { // // @JsonProperty("reportSchedule") // @NotNull // public abstract ReportScheduleImpl getReportSchedule(); // // @JsonCreator // public static AddReportScheduleRequest create(//@JsonProperty("name") @Valid String name, // @JsonProperty("reportSchedule") @Valid ReportScheduleImpl reportSchedule // // ) { // return new AutoValue_AddReportScheduleRequest(reportSchedule); // } // } // // Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/rest/models/requests/UpdateReportScheduleRequest.java // @AutoValue // @JsonAutoDetect // public abstract class UpdateReportScheduleRequest { // // // @JsonProperty("reportSchedule") // @NotNull // public abstract ReportScheduleImpl getReportSchedule(); // // @JsonCreator // public static UpdateReportScheduleRequest create( // @JsonProperty("reportSchedule") @Valid ReportScheduleImpl reportSchedule // ) { // return new AutoValue_UpdateReportScheduleRequest(reportSchedule); // } // }
import java.io.UnsupportedEncodingException; import java.util.Date; import java.util.List; import org.graylog.plugins.aggregates.report.schedule.rest.models.requests.AddReportScheduleRequest; import org.graylog.plugins.aggregates.report.schedule.rest.models.requests.UpdateReportScheduleRequest; import com.mongodb.MongoException;
package org.graylog.plugins.aggregates.report.schedule; public interface ReportScheduleService { long count(); ReportSchedule update(String name, ReportSchedule schedule); ReportSchedule create(ReportSchedule schedule); List<ReportSchedule> all(); int destroy(String scheduleName) throws MongoException, UnsupportedEncodingException; ReportSchedule fromRequest(AddReportScheduleRequest request);
// Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/rest/models/requests/AddReportScheduleRequest.java // @AutoValue // @JsonAutoDetect // public abstract class AddReportScheduleRequest { // // @JsonProperty("reportSchedule") // @NotNull // public abstract ReportScheduleImpl getReportSchedule(); // // @JsonCreator // public static AddReportScheduleRequest create(//@JsonProperty("name") @Valid String name, // @JsonProperty("reportSchedule") @Valid ReportScheduleImpl reportSchedule // // ) { // return new AutoValue_AddReportScheduleRequest(reportSchedule); // } // } // // Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/rest/models/requests/UpdateReportScheduleRequest.java // @AutoValue // @JsonAutoDetect // public abstract class UpdateReportScheduleRequest { // // // @JsonProperty("reportSchedule") // @NotNull // public abstract ReportScheduleImpl getReportSchedule(); // // @JsonCreator // public static UpdateReportScheduleRequest create( // @JsonProperty("reportSchedule") @Valid ReportScheduleImpl reportSchedule // ) { // return new AutoValue_UpdateReportScheduleRequest(reportSchedule); // } // } // Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/ReportScheduleService.java import java.io.UnsupportedEncodingException; import java.util.Date; import java.util.List; import org.graylog.plugins.aggregates.report.schedule.rest.models.requests.AddReportScheduleRequest; import org.graylog.plugins.aggregates.report.schedule.rest.models.requests.UpdateReportScheduleRequest; import com.mongodb.MongoException; package org.graylog.plugins.aggregates.report.schedule; public interface ReportScheduleService { long count(); ReportSchedule update(String name, ReportSchedule schedule); ReportSchedule create(ReportSchedule schedule); List<ReportSchedule> all(); int destroy(String scheduleName) throws MongoException, UnsupportedEncodingException; ReportSchedule fromRequest(AddReportScheduleRequest request);
ReportSchedule fromRequest(UpdateReportScheduleRequest request);
cvtienhoven/graylog-plugin-aggregates
src/main/java/org/graylog/plugins/aggregates/rule/RuleService.java
// Path: src/main/java/org/graylog/plugins/aggregates/rule/rest/models/requests/AddRuleRequest.java // @AutoValue // @JsonAutoDetect // public abstract class AddRuleRequest { // // @JsonProperty("rule") // @NotNull // public abstract RuleImpl getRule(); // // @JsonCreator // public static AddRuleRequest create(//@JsonProperty("name") @Valid String name, // @JsonProperty("rule") @Valid RuleImpl rule // // ) { // return new AutoValue_AddRuleRequest(rule); // } // } // // Path: src/main/java/org/graylog/plugins/aggregates/rule/rest/models/requests/UpdateRuleRequest.java // @AutoValue // @JsonAutoDetect // public abstract class UpdateRuleRequest { // // // @JsonProperty("rule") // @NotNull // public abstract RuleImpl getRule(); // // @JsonCreator // public static UpdateRuleRequest create( // @JsonProperty("rule") @Valid RuleImpl rule // ) { // return new AutoValue_UpdateRuleRequest(rule); // } // }
import java.io.UnsupportedEncodingException; import java.util.List; import org.graylog.plugins.aggregates.rule.rest.models.requests.AddRuleRequest; import org.graylog.plugins.aggregates.rule.rest.models.requests.UpdateRuleRequest; import com.mongodb.MongoException;
package org.graylog.plugins.aggregates.rule; public interface RuleService { long count(); Rule update(String name, Rule rule); Rule create(Rule rule); List<Rule> all(); int destroy(String ruleName) throws MongoException, UnsupportedEncodingException;
// Path: src/main/java/org/graylog/plugins/aggregates/rule/rest/models/requests/AddRuleRequest.java // @AutoValue // @JsonAutoDetect // public abstract class AddRuleRequest { // // @JsonProperty("rule") // @NotNull // public abstract RuleImpl getRule(); // // @JsonCreator // public static AddRuleRequest create(//@JsonProperty("name") @Valid String name, // @JsonProperty("rule") @Valid RuleImpl rule // // ) { // return new AutoValue_AddRuleRequest(rule); // } // } // // Path: src/main/java/org/graylog/plugins/aggregates/rule/rest/models/requests/UpdateRuleRequest.java // @AutoValue // @JsonAutoDetect // public abstract class UpdateRuleRequest { // // // @JsonProperty("rule") // @NotNull // public abstract RuleImpl getRule(); // // @JsonCreator // public static UpdateRuleRequest create( // @JsonProperty("rule") @Valid RuleImpl rule // ) { // return new AutoValue_UpdateRuleRequest(rule); // } // } // Path: src/main/java/org/graylog/plugins/aggregates/rule/RuleService.java import java.io.UnsupportedEncodingException; import java.util.List; import org.graylog.plugins.aggregates.rule.rest.models.requests.AddRuleRequest; import org.graylog.plugins.aggregates.rule.rest.models.requests.UpdateRuleRequest; import com.mongodb.MongoException; package org.graylog.plugins.aggregates.rule; public interface RuleService { long count(); Rule update(String name, Rule rule); Rule create(Rule rule); List<Rule> all(); int destroy(String ruleName) throws MongoException, UnsupportedEncodingException;
Rule fromRequest(AddRuleRequest request);
cvtienhoven/graylog-plugin-aggregates
src/main/java/org/graylog/plugins/aggregates/rule/RuleService.java
// Path: src/main/java/org/graylog/plugins/aggregates/rule/rest/models/requests/AddRuleRequest.java // @AutoValue // @JsonAutoDetect // public abstract class AddRuleRequest { // // @JsonProperty("rule") // @NotNull // public abstract RuleImpl getRule(); // // @JsonCreator // public static AddRuleRequest create(//@JsonProperty("name") @Valid String name, // @JsonProperty("rule") @Valid RuleImpl rule // // ) { // return new AutoValue_AddRuleRequest(rule); // } // } // // Path: src/main/java/org/graylog/plugins/aggregates/rule/rest/models/requests/UpdateRuleRequest.java // @AutoValue // @JsonAutoDetect // public abstract class UpdateRuleRequest { // // // @JsonProperty("rule") // @NotNull // public abstract RuleImpl getRule(); // // @JsonCreator // public static UpdateRuleRequest create( // @JsonProperty("rule") @Valid RuleImpl rule // ) { // return new AutoValue_UpdateRuleRequest(rule); // } // }
import java.io.UnsupportedEncodingException; import java.util.List; import org.graylog.plugins.aggregates.rule.rest.models.requests.AddRuleRequest; import org.graylog.plugins.aggregates.rule.rest.models.requests.UpdateRuleRequest; import com.mongodb.MongoException;
package org.graylog.plugins.aggregates.rule; public interface RuleService { long count(); Rule update(String name, Rule rule); Rule create(Rule rule); List<Rule> all(); int destroy(String ruleName) throws MongoException, UnsupportedEncodingException; Rule fromRequest(AddRuleRequest request);
// Path: src/main/java/org/graylog/plugins/aggregates/rule/rest/models/requests/AddRuleRequest.java // @AutoValue // @JsonAutoDetect // public abstract class AddRuleRequest { // // @JsonProperty("rule") // @NotNull // public abstract RuleImpl getRule(); // // @JsonCreator // public static AddRuleRequest create(//@JsonProperty("name") @Valid String name, // @JsonProperty("rule") @Valid RuleImpl rule // // ) { // return new AutoValue_AddRuleRequest(rule); // } // } // // Path: src/main/java/org/graylog/plugins/aggregates/rule/rest/models/requests/UpdateRuleRequest.java // @AutoValue // @JsonAutoDetect // public abstract class UpdateRuleRequest { // // // @JsonProperty("rule") // @NotNull // public abstract RuleImpl getRule(); // // @JsonCreator // public static UpdateRuleRequest create( // @JsonProperty("rule") @Valid RuleImpl rule // ) { // return new AutoValue_UpdateRuleRequest(rule); // } // } // Path: src/main/java/org/graylog/plugins/aggregates/rule/RuleService.java import java.io.UnsupportedEncodingException; import java.util.List; import org.graylog.plugins.aggregates.rule.rest.models.requests.AddRuleRequest; import org.graylog.plugins.aggregates.rule.rest.models.requests.UpdateRuleRequest; import com.mongodb.MongoException; package org.graylog.plugins.aggregates.rule; public interface RuleService { long count(); Rule update(String name, Rule rule); Rule create(Rule rule); List<Rule> all(); int destroy(String ruleName) throws MongoException, UnsupportedEncodingException; Rule fromRequest(AddRuleRequest request);
Rule fromRequest(UpdateRuleRequest request);
cvtienhoven/graylog-plugin-aggregates
src/main/java/org/graylog/plugins/aggregates/rule/rest/models/requests/UpdateRuleRequest.java
// Path: src/main/java/org/graylog/plugins/aggregates/rule/Rule.java // public interface Rule { // // public String getQuery(); // // public String getField(); // // public long getNumberOfMatches(); // // public boolean isMatchMoreOrEqual(); // // public int getInterval(); // // public String getName(); // // public boolean isEnabled(); // // public String getStreamId(); // // public boolean isInReport(); // // public List<String> getReportSchedules(); // // public String getAlertConditionId(); // // public boolean shouldRepeatNotifications(); // // public long getBacklog(); // } // // Path: src/main/java/org/graylog/plugins/aggregates/rule/RuleImpl.java // @AutoValue // @JsonAutoDetect // @JsonIgnoreProperties(ignoreUnknown = true) // @CollectionName("aggregate_rules") // public abstract class RuleImpl implements Rule{ // // // @JsonProperty("query") // @Override // @NotNull // public abstract String getQuery(); // // @JsonProperty("field") // @Override // @NotNull // public abstract String getField(); // // @JsonProperty("numberOfMatches") // @Override // @Min(1) // public abstract long getNumberOfMatches(); // // @JsonProperty("matchMoreOrEqual") // @Override // public abstract boolean isMatchMoreOrEqual(); // // @JsonProperty("interval") // @Override // @Min(1) // public abstract int getInterval(); // // @JsonProperty("name") // @Override // @NotNull // public abstract String getName(); // // @JsonProperty("enabled") // @Override // public abstract boolean isEnabled(); // // @JsonProperty("streamId") // @Override // public abstract String getStreamId(); // // @JsonProperty("inReport") // @Override // public abstract boolean isInReport(); // // @JsonProperty("reportSchedules") // @Override // @Nullable // public abstract List<String> getReportSchedules(); // // @JsonProperty("alertConditionId") // @Override // @Nullable // public abstract String getAlertConditionId(); // // @JsonProperty("repeatNotifications") // @Override // @Nullable // public abstract boolean shouldRepeatNotifications(); // // @JsonProperty("backlog") // @Override // @Nullable // @Min(0) // public abstract long getBacklog(); // // @JsonCreator // public static RuleImpl create(@JsonProperty("_id") String objectId, // @JsonProperty("query") String query, // @JsonProperty("field") String field, // @JsonProperty("numberOfMatches") long numberOfMatches, // @JsonProperty("matchMoreOrEqual") boolean matchMoreOrEqual, // @JsonProperty("interval") int interval, // @JsonProperty("name") String name, // @JsonProperty("enabled") boolean enabled, // @JsonProperty("streamId") String streamId, // @JsonProperty("inReport") boolean inReport, // @JsonProperty("reportSchedules") List<String> reportSchedules, // @JsonProperty("alertConditionId") String alertConditionId, // @JsonProperty("repeatNotifications") boolean repeatNotifications, // @JsonProperty("backlog") long backlog) { // return new AutoValue_RuleImpl(query, field, numberOfMatches, matchMoreOrEqual, interval, name, enabled, streamId, inReport, reportSchedules, alertConditionId, repeatNotifications, backlog); // } // // public static RuleImpl create( // String query, // String field, // long numberOfMatches, // boolean matchMoreOrEqual, // int interval, // String name, // boolean enabled, // String streamId, // boolean inReport, // List<String> reportSchedules, // String alertConditionId, // boolean repeatNotifications, // long backlog) { // return new AutoValue_RuleImpl(query, field, numberOfMatches, matchMoreOrEqual, interval, name, enabled, streamId, inReport, reportSchedules, alertConditionId, repeatNotifications, backlog); // // } // }
import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.auto.value.AutoValue; import org.graylog.plugins.aggregates.rule.Rule; import org.graylog.plugins.aggregates.rule.RuleImpl; import javax.validation.Valid; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size;
package org.graylog.plugins.aggregates.rule.rest.models.requests; @AutoValue @JsonAutoDetect public abstract class UpdateRuleRequest { @JsonProperty("rule") @NotNull
// Path: src/main/java/org/graylog/plugins/aggregates/rule/Rule.java // public interface Rule { // // public String getQuery(); // // public String getField(); // // public long getNumberOfMatches(); // // public boolean isMatchMoreOrEqual(); // // public int getInterval(); // // public String getName(); // // public boolean isEnabled(); // // public String getStreamId(); // // public boolean isInReport(); // // public List<String> getReportSchedules(); // // public String getAlertConditionId(); // // public boolean shouldRepeatNotifications(); // // public long getBacklog(); // } // // Path: src/main/java/org/graylog/plugins/aggregates/rule/RuleImpl.java // @AutoValue // @JsonAutoDetect // @JsonIgnoreProperties(ignoreUnknown = true) // @CollectionName("aggregate_rules") // public abstract class RuleImpl implements Rule{ // // // @JsonProperty("query") // @Override // @NotNull // public abstract String getQuery(); // // @JsonProperty("field") // @Override // @NotNull // public abstract String getField(); // // @JsonProperty("numberOfMatches") // @Override // @Min(1) // public abstract long getNumberOfMatches(); // // @JsonProperty("matchMoreOrEqual") // @Override // public abstract boolean isMatchMoreOrEqual(); // // @JsonProperty("interval") // @Override // @Min(1) // public abstract int getInterval(); // // @JsonProperty("name") // @Override // @NotNull // public abstract String getName(); // // @JsonProperty("enabled") // @Override // public abstract boolean isEnabled(); // // @JsonProperty("streamId") // @Override // public abstract String getStreamId(); // // @JsonProperty("inReport") // @Override // public abstract boolean isInReport(); // // @JsonProperty("reportSchedules") // @Override // @Nullable // public abstract List<String> getReportSchedules(); // // @JsonProperty("alertConditionId") // @Override // @Nullable // public abstract String getAlertConditionId(); // // @JsonProperty("repeatNotifications") // @Override // @Nullable // public abstract boolean shouldRepeatNotifications(); // // @JsonProperty("backlog") // @Override // @Nullable // @Min(0) // public abstract long getBacklog(); // // @JsonCreator // public static RuleImpl create(@JsonProperty("_id") String objectId, // @JsonProperty("query") String query, // @JsonProperty("field") String field, // @JsonProperty("numberOfMatches") long numberOfMatches, // @JsonProperty("matchMoreOrEqual") boolean matchMoreOrEqual, // @JsonProperty("interval") int interval, // @JsonProperty("name") String name, // @JsonProperty("enabled") boolean enabled, // @JsonProperty("streamId") String streamId, // @JsonProperty("inReport") boolean inReport, // @JsonProperty("reportSchedules") List<String> reportSchedules, // @JsonProperty("alertConditionId") String alertConditionId, // @JsonProperty("repeatNotifications") boolean repeatNotifications, // @JsonProperty("backlog") long backlog) { // return new AutoValue_RuleImpl(query, field, numberOfMatches, matchMoreOrEqual, interval, name, enabled, streamId, inReport, reportSchedules, alertConditionId, repeatNotifications, backlog); // } // // public static RuleImpl create( // String query, // String field, // long numberOfMatches, // boolean matchMoreOrEqual, // int interval, // String name, // boolean enabled, // String streamId, // boolean inReport, // List<String> reportSchedules, // String alertConditionId, // boolean repeatNotifications, // long backlog) { // return new AutoValue_RuleImpl(query, field, numberOfMatches, matchMoreOrEqual, interval, name, enabled, streamId, inReport, reportSchedules, alertConditionId, repeatNotifications, backlog); // // } // } // Path: src/main/java/org/graylog/plugins/aggregates/rule/rest/models/requests/UpdateRuleRequest.java import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.auto.value.AutoValue; import org.graylog.plugins.aggregates.rule.Rule; import org.graylog.plugins.aggregates.rule.RuleImpl; import javax.validation.Valid; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; package org.graylog.plugins.aggregates.rule.rest.models.requests; @AutoValue @JsonAutoDetect public abstract class UpdateRuleRequest { @JsonProperty("rule") @NotNull
public abstract RuleImpl getRule();
cvtienhoven/graylog-plugin-aggregates
src/main/java/org/graylog/plugins/aggregates/report/AggregatesReport.java
// Path: src/main/java/org/graylog/plugins/aggregates/history/HistoryAggregateItem.java // public interface HistoryAggregateItem { // public String getMoment(); // // public long getNumberOfHits(); // // } // // Path: src/main/java/org/graylog/plugins/aggregates/history/HistoryItemService.java // public interface HistoryItemService { // long count(); // // HistoryItem create(HistoryItem historyItem); // // List<HistoryItem> all(); // // List<HistoryAggregateItem> getForRuleName(String ruleName, int days); // // void removeBefore(Date date); // // List<HistoryAggregateItem> getForRuleName(String ruleName, String timespan); // // void updateHistoryRuleName(String oldName, String newName); // } // // Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/ReportSchedule.java // public interface ReportSchedule { // // public String getId(); // // public String getName(); // // public String getExpression(); // // public String getTimespan(); // // public boolean isDefaultSchedule(); // // public Long getNextFireTime(); // // public List<String> getReportReceivers(); // } // // Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/ReportScheduleService.java // public interface ReportScheduleService { // long count(); // // ReportSchedule update(String name, ReportSchedule schedule); // // ReportSchedule create(ReportSchedule schedule); // // List<ReportSchedule> all(); // // int destroy(String scheduleName) throws MongoException, UnsupportedEncodingException; // // ReportSchedule fromRequest(AddReportScheduleRequest request); // // ReportSchedule fromRequest(UpdateReportScheduleRequest request); // // ReportSchedule get(String id); // // ReportSchedule updateNextFireTime(String id, Date nextFireTime); // // } // // Path: src/main/java/org/graylog/plugins/aggregates/rule/Rule.java // public interface Rule { // // public String getQuery(); // // public String getField(); // // public long getNumberOfMatches(); // // public boolean isMatchMoreOrEqual(); // // public int getInterval(); // // public String getName(); // // public boolean isEnabled(); // // public String getStreamId(); // // public boolean isInReport(); // // public List<String> getReportSchedules(); // // public String getAlertConditionId(); // // public boolean shouldRepeatNotifications(); // // public long getBacklog(); // } // // Path: src/main/java/org/graylog/plugins/aggregates/rule/RuleService.java // public interface RuleService { // long count(); // // Rule update(String name, Rule rule); // // Rule create(Rule rule); // // List<Rule> all(); // // int destroy(String ruleName) throws MongoException, UnsupportedEncodingException; // // Rule fromRequest(AddRuleRequest request); // // Rule fromRequest(UpdateRuleRequest request); // // //Rule setAlertConditionId(Rule rule, String currentAlertId); // // String createOrUpdateAlertCondition(Rule rule); // }
import java.io.ByteArrayOutputStream; import java.net.InetAddress; import java.net.UnknownHostException; import java.text.ParseException; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.inject.Inject; import javax.mail.MessagingException; import org.apache.commons.mail.EmailException; import org.drools.core.time.impl.CronExpression; import org.graylog.plugins.aggregates.history.HistoryAggregateItem; import org.graylog.plugins.aggregates.history.HistoryItemService; import org.graylog.plugins.aggregates.report.schedule.ReportSchedule; import org.graylog.plugins.aggregates.report.schedule.ReportScheduleService; import org.graylog.plugins.aggregates.rule.Rule; import org.graylog.plugins.aggregates.rule.RuleService; import org.graylog2.plugin.alarms.transports.TransportConfigurationException; import org.graylog2.plugin.periodical.Periodical; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
package org.graylog.plugins.aggregates.report; public class AggregatesReport extends Periodical { private static final Logger LOG = LoggerFactory.getLogger(AggregatesReport.class); private final ReportSender reportSender;
// Path: src/main/java/org/graylog/plugins/aggregates/history/HistoryAggregateItem.java // public interface HistoryAggregateItem { // public String getMoment(); // // public long getNumberOfHits(); // // } // // Path: src/main/java/org/graylog/plugins/aggregates/history/HistoryItemService.java // public interface HistoryItemService { // long count(); // // HistoryItem create(HistoryItem historyItem); // // List<HistoryItem> all(); // // List<HistoryAggregateItem> getForRuleName(String ruleName, int days); // // void removeBefore(Date date); // // List<HistoryAggregateItem> getForRuleName(String ruleName, String timespan); // // void updateHistoryRuleName(String oldName, String newName); // } // // Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/ReportSchedule.java // public interface ReportSchedule { // // public String getId(); // // public String getName(); // // public String getExpression(); // // public String getTimespan(); // // public boolean isDefaultSchedule(); // // public Long getNextFireTime(); // // public List<String> getReportReceivers(); // } // // Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/ReportScheduleService.java // public interface ReportScheduleService { // long count(); // // ReportSchedule update(String name, ReportSchedule schedule); // // ReportSchedule create(ReportSchedule schedule); // // List<ReportSchedule> all(); // // int destroy(String scheduleName) throws MongoException, UnsupportedEncodingException; // // ReportSchedule fromRequest(AddReportScheduleRequest request); // // ReportSchedule fromRequest(UpdateReportScheduleRequest request); // // ReportSchedule get(String id); // // ReportSchedule updateNextFireTime(String id, Date nextFireTime); // // } // // Path: src/main/java/org/graylog/plugins/aggregates/rule/Rule.java // public interface Rule { // // public String getQuery(); // // public String getField(); // // public long getNumberOfMatches(); // // public boolean isMatchMoreOrEqual(); // // public int getInterval(); // // public String getName(); // // public boolean isEnabled(); // // public String getStreamId(); // // public boolean isInReport(); // // public List<String> getReportSchedules(); // // public String getAlertConditionId(); // // public boolean shouldRepeatNotifications(); // // public long getBacklog(); // } // // Path: src/main/java/org/graylog/plugins/aggregates/rule/RuleService.java // public interface RuleService { // long count(); // // Rule update(String name, Rule rule); // // Rule create(Rule rule); // // List<Rule> all(); // // int destroy(String ruleName) throws MongoException, UnsupportedEncodingException; // // Rule fromRequest(AddRuleRequest request); // // Rule fromRequest(UpdateRuleRequest request); // // //Rule setAlertConditionId(Rule rule, String currentAlertId); // // String createOrUpdateAlertCondition(Rule rule); // } // Path: src/main/java/org/graylog/plugins/aggregates/report/AggregatesReport.java import java.io.ByteArrayOutputStream; import java.net.InetAddress; import java.net.UnknownHostException; import java.text.ParseException; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.inject.Inject; import javax.mail.MessagingException; import org.apache.commons.mail.EmailException; import org.drools.core.time.impl.CronExpression; import org.graylog.plugins.aggregates.history.HistoryAggregateItem; import org.graylog.plugins.aggregates.history.HistoryItemService; import org.graylog.plugins.aggregates.report.schedule.ReportSchedule; import org.graylog.plugins.aggregates.report.schedule.ReportScheduleService; import org.graylog.plugins.aggregates.rule.Rule; import org.graylog.plugins.aggregates.rule.RuleService; import org.graylog2.plugin.alarms.transports.TransportConfigurationException; import org.graylog2.plugin.periodical.Periodical; import org.slf4j.Logger; import org.slf4j.LoggerFactory; package org.graylog.plugins.aggregates.report; public class AggregatesReport extends Periodical { private static final Logger LOG = LoggerFactory.getLogger(AggregatesReport.class); private final ReportSender reportSender;
private final HistoryItemService historyItemService;
cvtienhoven/graylog-plugin-aggregates
src/main/java/org/graylog/plugins/aggregates/report/AggregatesReport.java
// Path: src/main/java/org/graylog/plugins/aggregates/history/HistoryAggregateItem.java // public interface HistoryAggregateItem { // public String getMoment(); // // public long getNumberOfHits(); // // } // // Path: src/main/java/org/graylog/plugins/aggregates/history/HistoryItemService.java // public interface HistoryItemService { // long count(); // // HistoryItem create(HistoryItem historyItem); // // List<HistoryItem> all(); // // List<HistoryAggregateItem> getForRuleName(String ruleName, int days); // // void removeBefore(Date date); // // List<HistoryAggregateItem> getForRuleName(String ruleName, String timespan); // // void updateHistoryRuleName(String oldName, String newName); // } // // Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/ReportSchedule.java // public interface ReportSchedule { // // public String getId(); // // public String getName(); // // public String getExpression(); // // public String getTimespan(); // // public boolean isDefaultSchedule(); // // public Long getNextFireTime(); // // public List<String> getReportReceivers(); // } // // Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/ReportScheduleService.java // public interface ReportScheduleService { // long count(); // // ReportSchedule update(String name, ReportSchedule schedule); // // ReportSchedule create(ReportSchedule schedule); // // List<ReportSchedule> all(); // // int destroy(String scheduleName) throws MongoException, UnsupportedEncodingException; // // ReportSchedule fromRequest(AddReportScheduleRequest request); // // ReportSchedule fromRequest(UpdateReportScheduleRequest request); // // ReportSchedule get(String id); // // ReportSchedule updateNextFireTime(String id, Date nextFireTime); // // } // // Path: src/main/java/org/graylog/plugins/aggregates/rule/Rule.java // public interface Rule { // // public String getQuery(); // // public String getField(); // // public long getNumberOfMatches(); // // public boolean isMatchMoreOrEqual(); // // public int getInterval(); // // public String getName(); // // public boolean isEnabled(); // // public String getStreamId(); // // public boolean isInReport(); // // public List<String> getReportSchedules(); // // public String getAlertConditionId(); // // public boolean shouldRepeatNotifications(); // // public long getBacklog(); // } // // Path: src/main/java/org/graylog/plugins/aggregates/rule/RuleService.java // public interface RuleService { // long count(); // // Rule update(String name, Rule rule); // // Rule create(Rule rule); // // List<Rule> all(); // // int destroy(String ruleName) throws MongoException, UnsupportedEncodingException; // // Rule fromRequest(AddRuleRequest request); // // Rule fromRequest(UpdateRuleRequest request); // // //Rule setAlertConditionId(Rule rule, String currentAlertId); // // String createOrUpdateAlertCondition(Rule rule); // }
import java.io.ByteArrayOutputStream; import java.net.InetAddress; import java.net.UnknownHostException; import java.text.ParseException; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.inject.Inject; import javax.mail.MessagingException; import org.apache.commons.mail.EmailException; import org.drools.core.time.impl.CronExpression; import org.graylog.plugins.aggregates.history.HistoryAggregateItem; import org.graylog.plugins.aggregates.history.HistoryItemService; import org.graylog.plugins.aggregates.report.schedule.ReportSchedule; import org.graylog.plugins.aggregates.report.schedule.ReportScheduleService; import org.graylog.plugins.aggregates.rule.Rule; import org.graylog.plugins.aggregates.rule.RuleService; import org.graylog2.plugin.alarms.transports.TransportConfigurationException; import org.graylog2.plugin.periodical.Periodical; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
package org.graylog.plugins.aggregates.report; public class AggregatesReport extends Periodical { private static final Logger LOG = LoggerFactory.getLogger(AggregatesReport.class); private final ReportSender reportSender; private final HistoryItemService historyItemService;
// Path: src/main/java/org/graylog/plugins/aggregates/history/HistoryAggregateItem.java // public interface HistoryAggregateItem { // public String getMoment(); // // public long getNumberOfHits(); // // } // // Path: src/main/java/org/graylog/plugins/aggregates/history/HistoryItemService.java // public interface HistoryItemService { // long count(); // // HistoryItem create(HistoryItem historyItem); // // List<HistoryItem> all(); // // List<HistoryAggregateItem> getForRuleName(String ruleName, int days); // // void removeBefore(Date date); // // List<HistoryAggregateItem> getForRuleName(String ruleName, String timespan); // // void updateHistoryRuleName(String oldName, String newName); // } // // Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/ReportSchedule.java // public interface ReportSchedule { // // public String getId(); // // public String getName(); // // public String getExpression(); // // public String getTimespan(); // // public boolean isDefaultSchedule(); // // public Long getNextFireTime(); // // public List<String> getReportReceivers(); // } // // Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/ReportScheduleService.java // public interface ReportScheduleService { // long count(); // // ReportSchedule update(String name, ReportSchedule schedule); // // ReportSchedule create(ReportSchedule schedule); // // List<ReportSchedule> all(); // // int destroy(String scheduleName) throws MongoException, UnsupportedEncodingException; // // ReportSchedule fromRequest(AddReportScheduleRequest request); // // ReportSchedule fromRequest(UpdateReportScheduleRequest request); // // ReportSchedule get(String id); // // ReportSchedule updateNextFireTime(String id, Date nextFireTime); // // } // // Path: src/main/java/org/graylog/plugins/aggregates/rule/Rule.java // public interface Rule { // // public String getQuery(); // // public String getField(); // // public long getNumberOfMatches(); // // public boolean isMatchMoreOrEqual(); // // public int getInterval(); // // public String getName(); // // public boolean isEnabled(); // // public String getStreamId(); // // public boolean isInReport(); // // public List<String> getReportSchedules(); // // public String getAlertConditionId(); // // public boolean shouldRepeatNotifications(); // // public long getBacklog(); // } // // Path: src/main/java/org/graylog/plugins/aggregates/rule/RuleService.java // public interface RuleService { // long count(); // // Rule update(String name, Rule rule); // // Rule create(Rule rule); // // List<Rule> all(); // // int destroy(String ruleName) throws MongoException, UnsupportedEncodingException; // // Rule fromRequest(AddRuleRequest request); // // Rule fromRequest(UpdateRuleRequest request); // // //Rule setAlertConditionId(Rule rule, String currentAlertId); // // String createOrUpdateAlertCondition(Rule rule); // } // Path: src/main/java/org/graylog/plugins/aggregates/report/AggregatesReport.java import java.io.ByteArrayOutputStream; import java.net.InetAddress; import java.net.UnknownHostException; import java.text.ParseException; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.inject.Inject; import javax.mail.MessagingException; import org.apache.commons.mail.EmailException; import org.drools.core.time.impl.CronExpression; import org.graylog.plugins.aggregates.history.HistoryAggregateItem; import org.graylog.plugins.aggregates.history.HistoryItemService; import org.graylog.plugins.aggregates.report.schedule.ReportSchedule; import org.graylog.plugins.aggregates.report.schedule.ReportScheduleService; import org.graylog.plugins.aggregates.rule.Rule; import org.graylog.plugins.aggregates.rule.RuleService; import org.graylog2.plugin.alarms.transports.TransportConfigurationException; import org.graylog2.plugin.periodical.Periodical; import org.slf4j.Logger; import org.slf4j.LoggerFactory; package org.graylog.plugins.aggregates.report; public class AggregatesReport extends Periodical { private static final Logger LOG = LoggerFactory.getLogger(AggregatesReport.class); private final ReportSender reportSender; private final HistoryItemService historyItemService;
private final RuleService ruleService;
cvtienhoven/graylog-plugin-aggregates
src/main/java/org/graylog/plugins/aggregates/report/AggregatesReport.java
// Path: src/main/java/org/graylog/plugins/aggregates/history/HistoryAggregateItem.java // public interface HistoryAggregateItem { // public String getMoment(); // // public long getNumberOfHits(); // // } // // Path: src/main/java/org/graylog/plugins/aggregates/history/HistoryItemService.java // public interface HistoryItemService { // long count(); // // HistoryItem create(HistoryItem historyItem); // // List<HistoryItem> all(); // // List<HistoryAggregateItem> getForRuleName(String ruleName, int days); // // void removeBefore(Date date); // // List<HistoryAggregateItem> getForRuleName(String ruleName, String timespan); // // void updateHistoryRuleName(String oldName, String newName); // } // // Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/ReportSchedule.java // public interface ReportSchedule { // // public String getId(); // // public String getName(); // // public String getExpression(); // // public String getTimespan(); // // public boolean isDefaultSchedule(); // // public Long getNextFireTime(); // // public List<String> getReportReceivers(); // } // // Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/ReportScheduleService.java // public interface ReportScheduleService { // long count(); // // ReportSchedule update(String name, ReportSchedule schedule); // // ReportSchedule create(ReportSchedule schedule); // // List<ReportSchedule> all(); // // int destroy(String scheduleName) throws MongoException, UnsupportedEncodingException; // // ReportSchedule fromRequest(AddReportScheduleRequest request); // // ReportSchedule fromRequest(UpdateReportScheduleRequest request); // // ReportSchedule get(String id); // // ReportSchedule updateNextFireTime(String id, Date nextFireTime); // // } // // Path: src/main/java/org/graylog/plugins/aggregates/rule/Rule.java // public interface Rule { // // public String getQuery(); // // public String getField(); // // public long getNumberOfMatches(); // // public boolean isMatchMoreOrEqual(); // // public int getInterval(); // // public String getName(); // // public boolean isEnabled(); // // public String getStreamId(); // // public boolean isInReport(); // // public List<String> getReportSchedules(); // // public String getAlertConditionId(); // // public boolean shouldRepeatNotifications(); // // public long getBacklog(); // } // // Path: src/main/java/org/graylog/plugins/aggregates/rule/RuleService.java // public interface RuleService { // long count(); // // Rule update(String name, Rule rule); // // Rule create(Rule rule); // // List<Rule> all(); // // int destroy(String ruleName) throws MongoException, UnsupportedEncodingException; // // Rule fromRequest(AddRuleRequest request); // // Rule fromRequest(UpdateRuleRequest request); // // //Rule setAlertConditionId(Rule rule, String currentAlertId); // // String createOrUpdateAlertCondition(Rule rule); // }
import java.io.ByteArrayOutputStream; import java.net.InetAddress; import java.net.UnknownHostException; import java.text.ParseException; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.inject.Inject; import javax.mail.MessagingException; import org.apache.commons.mail.EmailException; import org.drools.core.time.impl.CronExpression; import org.graylog.plugins.aggregates.history.HistoryAggregateItem; import org.graylog.plugins.aggregates.history.HistoryItemService; import org.graylog.plugins.aggregates.report.schedule.ReportSchedule; import org.graylog.plugins.aggregates.report.schedule.ReportScheduleService; import org.graylog.plugins.aggregates.rule.Rule; import org.graylog.plugins.aggregates.rule.RuleService; import org.graylog2.plugin.alarms.transports.TransportConfigurationException; import org.graylog2.plugin.periodical.Periodical; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
package org.graylog.plugins.aggregates.report; public class AggregatesReport extends Periodical { private static final Logger LOG = LoggerFactory.getLogger(AggregatesReport.class); private final ReportSender reportSender; private final HistoryItemService historyItemService; private final RuleService ruleService;
// Path: src/main/java/org/graylog/plugins/aggregates/history/HistoryAggregateItem.java // public interface HistoryAggregateItem { // public String getMoment(); // // public long getNumberOfHits(); // // } // // Path: src/main/java/org/graylog/plugins/aggregates/history/HistoryItemService.java // public interface HistoryItemService { // long count(); // // HistoryItem create(HistoryItem historyItem); // // List<HistoryItem> all(); // // List<HistoryAggregateItem> getForRuleName(String ruleName, int days); // // void removeBefore(Date date); // // List<HistoryAggregateItem> getForRuleName(String ruleName, String timespan); // // void updateHistoryRuleName(String oldName, String newName); // } // // Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/ReportSchedule.java // public interface ReportSchedule { // // public String getId(); // // public String getName(); // // public String getExpression(); // // public String getTimespan(); // // public boolean isDefaultSchedule(); // // public Long getNextFireTime(); // // public List<String> getReportReceivers(); // } // // Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/ReportScheduleService.java // public interface ReportScheduleService { // long count(); // // ReportSchedule update(String name, ReportSchedule schedule); // // ReportSchedule create(ReportSchedule schedule); // // List<ReportSchedule> all(); // // int destroy(String scheduleName) throws MongoException, UnsupportedEncodingException; // // ReportSchedule fromRequest(AddReportScheduleRequest request); // // ReportSchedule fromRequest(UpdateReportScheduleRequest request); // // ReportSchedule get(String id); // // ReportSchedule updateNextFireTime(String id, Date nextFireTime); // // } // // Path: src/main/java/org/graylog/plugins/aggregates/rule/Rule.java // public interface Rule { // // public String getQuery(); // // public String getField(); // // public long getNumberOfMatches(); // // public boolean isMatchMoreOrEqual(); // // public int getInterval(); // // public String getName(); // // public boolean isEnabled(); // // public String getStreamId(); // // public boolean isInReport(); // // public List<String> getReportSchedules(); // // public String getAlertConditionId(); // // public boolean shouldRepeatNotifications(); // // public long getBacklog(); // } // // Path: src/main/java/org/graylog/plugins/aggregates/rule/RuleService.java // public interface RuleService { // long count(); // // Rule update(String name, Rule rule); // // Rule create(Rule rule); // // List<Rule> all(); // // int destroy(String ruleName) throws MongoException, UnsupportedEncodingException; // // Rule fromRequest(AddRuleRequest request); // // Rule fromRequest(UpdateRuleRequest request); // // //Rule setAlertConditionId(Rule rule, String currentAlertId); // // String createOrUpdateAlertCondition(Rule rule); // } // Path: src/main/java/org/graylog/plugins/aggregates/report/AggregatesReport.java import java.io.ByteArrayOutputStream; import java.net.InetAddress; import java.net.UnknownHostException; import java.text.ParseException; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.inject.Inject; import javax.mail.MessagingException; import org.apache.commons.mail.EmailException; import org.drools.core.time.impl.CronExpression; import org.graylog.plugins.aggregates.history.HistoryAggregateItem; import org.graylog.plugins.aggregates.history.HistoryItemService; import org.graylog.plugins.aggregates.report.schedule.ReportSchedule; import org.graylog.plugins.aggregates.report.schedule.ReportScheduleService; import org.graylog.plugins.aggregates.rule.Rule; import org.graylog.plugins.aggregates.rule.RuleService; import org.graylog2.plugin.alarms.transports.TransportConfigurationException; import org.graylog2.plugin.periodical.Periodical; import org.slf4j.Logger; import org.slf4j.LoggerFactory; package org.graylog.plugins.aggregates.report; public class AggregatesReport extends Periodical { private static final Logger LOG = LoggerFactory.getLogger(AggregatesReport.class); private final ReportSender reportSender; private final HistoryItemService historyItemService; private final RuleService ruleService;
private final ReportScheduleService reportScheduleService;
cvtienhoven/graylog-plugin-aggregates
src/main/java/org/graylog/plugins/aggregates/report/AggregatesReport.java
// Path: src/main/java/org/graylog/plugins/aggregates/history/HistoryAggregateItem.java // public interface HistoryAggregateItem { // public String getMoment(); // // public long getNumberOfHits(); // // } // // Path: src/main/java/org/graylog/plugins/aggregates/history/HistoryItemService.java // public interface HistoryItemService { // long count(); // // HistoryItem create(HistoryItem historyItem); // // List<HistoryItem> all(); // // List<HistoryAggregateItem> getForRuleName(String ruleName, int days); // // void removeBefore(Date date); // // List<HistoryAggregateItem> getForRuleName(String ruleName, String timespan); // // void updateHistoryRuleName(String oldName, String newName); // } // // Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/ReportSchedule.java // public interface ReportSchedule { // // public String getId(); // // public String getName(); // // public String getExpression(); // // public String getTimespan(); // // public boolean isDefaultSchedule(); // // public Long getNextFireTime(); // // public List<String> getReportReceivers(); // } // // Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/ReportScheduleService.java // public interface ReportScheduleService { // long count(); // // ReportSchedule update(String name, ReportSchedule schedule); // // ReportSchedule create(ReportSchedule schedule); // // List<ReportSchedule> all(); // // int destroy(String scheduleName) throws MongoException, UnsupportedEncodingException; // // ReportSchedule fromRequest(AddReportScheduleRequest request); // // ReportSchedule fromRequest(UpdateReportScheduleRequest request); // // ReportSchedule get(String id); // // ReportSchedule updateNextFireTime(String id, Date nextFireTime); // // } // // Path: src/main/java/org/graylog/plugins/aggregates/rule/Rule.java // public interface Rule { // // public String getQuery(); // // public String getField(); // // public long getNumberOfMatches(); // // public boolean isMatchMoreOrEqual(); // // public int getInterval(); // // public String getName(); // // public boolean isEnabled(); // // public String getStreamId(); // // public boolean isInReport(); // // public List<String> getReportSchedules(); // // public String getAlertConditionId(); // // public boolean shouldRepeatNotifications(); // // public long getBacklog(); // } // // Path: src/main/java/org/graylog/plugins/aggregates/rule/RuleService.java // public interface RuleService { // long count(); // // Rule update(String name, Rule rule); // // Rule create(Rule rule); // // List<Rule> all(); // // int destroy(String ruleName) throws MongoException, UnsupportedEncodingException; // // Rule fromRequest(AddRuleRequest request); // // Rule fromRequest(UpdateRuleRequest request); // // //Rule setAlertConditionId(Rule rule, String currentAlertId); // // String createOrUpdateAlertCondition(Rule rule); // }
import java.io.ByteArrayOutputStream; import java.net.InetAddress; import java.net.UnknownHostException; import java.text.ParseException; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.inject.Inject; import javax.mail.MessagingException; import org.apache.commons.mail.EmailException; import org.drools.core.time.impl.CronExpression; import org.graylog.plugins.aggregates.history.HistoryAggregateItem; import org.graylog.plugins.aggregates.history.HistoryItemService; import org.graylog.plugins.aggregates.report.schedule.ReportSchedule; import org.graylog.plugins.aggregates.report.schedule.ReportScheduleService; import org.graylog.plugins.aggregates.rule.Rule; import org.graylog.plugins.aggregates.rule.RuleService; import org.graylog2.plugin.alarms.transports.TransportConfigurationException; import org.graylog2.plugin.periodical.Periodical; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
package org.graylog.plugins.aggregates.report; public class AggregatesReport extends Periodical { private static final Logger LOG = LoggerFactory.getLogger(AggregatesReport.class); private final ReportSender reportSender; private final HistoryItemService historyItemService; private final RuleService ruleService; private final ReportScheduleService reportScheduleService; private String hostname = "localhost"; @Inject public AggregatesReport(ReportSender reportSender, HistoryItemService historyItemService, RuleService ruleService, ReportScheduleService reportScheduleService) { this.reportSender = reportSender; this.historyItemService = historyItemService; this.ruleService = ruleService; this.reportScheduleService = reportScheduleService; InetAddress addr; try { addr = InetAddress.getLocalHost(); this.hostname = addr.getCanonicalHostName(); } catch (UnknownHostException e) { e.printStackTrace(); } }
// Path: src/main/java/org/graylog/plugins/aggregates/history/HistoryAggregateItem.java // public interface HistoryAggregateItem { // public String getMoment(); // // public long getNumberOfHits(); // // } // // Path: src/main/java/org/graylog/plugins/aggregates/history/HistoryItemService.java // public interface HistoryItemService { // long count(); // // HistoryItem create(HistoryItem historyItem); // // List<HistoryItem> all(); // // List<HistoryAggregateItem> getForRuleName(String ruleName, int days); // // void removeBefore(Date date); // // List<HistoryAggregateItem> getForRuleName(String ruleName, String timespan); // // void updateHistoryRuleName(String oldName, String newName); // } // // Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/ReportSchedule.java // public interface ReportSchedule { // // public String getId(); // // public String getName(); // // public String getExpression(); // // public String getTimespan(); // // public boolean isDefaultSchedule(); // // public Long getNextFireTime(); // // public List<String> getReportReceivers(); // } // // Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/ReportScheduleService.java // public interface ReportScheduleService { // long count(); // // ReportSchedule update(String name, ReportSchedule schedule); // // ReportSchedule create(ReportSchedule schedule); // // List<ReportSchedule> all(); // // int destroy(String scheduleName) throws MongoException, UnsupportedEncodingException; // // ReportSchedule fromRequest(AddReportScheduleRequest request); // // ReportSchedule fromRequest(UpdateReportScheduleRequest request); // // ReportSchedule get(String id); // // ReportSchedule updateNextFireTime(String id, Date nextFireTime); // // } // // Path: src/main/java/org/graylog/plugins/aggregates/rule/Rule.java // public interface Rule { // // public String getQuery(); // // public String getField(); // // public long getNumberOfMatches(); // // public boolean isMatchMoreOrEqual(); // // public int getInterval(); // // public String getName(); // // public boolean isEnabled(); // // public String getStreamId(); // // public boolean isInReport(); // // public List<String> getReportSchedules(); // // public String getAlertConditionId(); // // public boolean shouldRepeatNotifications(); // // public long getBacklog(); // } // // Path: src/main/java/org/graylog/plugins/aggregates/rule/RuleService.java // public interface RuleService { // long count(); // // Rule update(String name, Rule rule); // // Rule create(Rule rule); // // List<Rule> all(); // // int destroy(String ruleName) throws MongoException, UnsupportedEncodingException; // // Rule fromRequest(AddRuleRequest request); // // Rule fromRequest(UpdateRuleRequest request); // // //Rule setAlertConditionId(Rule rule, String currentAlertId); // // String createOrUpdateAlertCondition(Rule rule); // } // Path: src/main/java/org/graylog/plugins/aggregates/report/AggregatesReport.java import java.io.ByteArrayOutputStream; import java.net.InetAddress; import java.net.UnknownHostException; import java.text.ParseException; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.inject.Inject; import javax.mail.MessagingException; import org.apache.commons.mail.EmailException; import org.drools.core.time.impl.CronExpression; import org.graylog.plugins.aggregates.history.HistoryAggregateItem; import org.graylog.plugins.aggregates.history.HistoryItemService; import org.graylog.plugins.aggregates.report.schedule.ReportSchedule; import org.graylog.plugins.aggregates.report.schedule.ReportScheduleService; import org.graylog.plugins.aggregates.rule.Rule; import org.graylog.plugins.aggregates.rule.RuleService; import org.graylog2.plugin.alarms.transports.TransportConfigurationException; import org.graylog2.plugin.periodical.Periodical; import org.slf4j.Logger; import org.slf4j.LoggerFactory; package org.graylog.plugins.aggregates.report; public class AggregatesReport extends Periodical { private static final Logger LOG = LoggerFactory.getLogger(AggregatesReport.class); private final ReportSender reportSender; private final HistoryItemService historyItemService; private final RuleService ruleService; private final ReportScheduleService reportScheduleService; private String hostname = "localhost"; @Inject public AggregatesReport(ReportSender reportSender, HistoryItemService historyItemService, RuleService ruleService, ReportScheduleService reportScheduleService) { this.reportSender = reportSender; this.historyItemService = historyItemService; this.ruleService = ruleService; this.reportScheduleService = reportScheduleService; InetAddress addr; try { addr = InetAddress.getLocalHost(); this.hostname = addr.getCanonicalHostName(); } catch (UnknownHostException e) { e.printStackTrace(); } }
private void setNewFireTime(ReportSchedule reportSchedule, Calendar cal) {
cvtienhoven/graylog-plugin-aggregates
src/main/java/org/graylog/plugins/aggregates/report/AggregatesReport.java
// Path: src/main/java/org/graylog/plugins/aggregates/history/HistoryAggregateItem.java // public interface HistoryAggregateItem { // public String getMoment(); // // public long getNumberOfHits(); // // } // // Path: src/main/java/org/graylog/plugins/aggregates/history/HistoryItemService.java // public interface HistoryItemService { // long count(); // // HistoryItem create(HistoryItem historyItem); // // List<HistoryItem> all(); // // List<HistoryAggregateItem> getForRuleName(String ruleName, int days); // // void removeBefore(Date date); // // List<HistoryAggregateItem> getForRuleName(String ruleName, String timespan); // // void updateHistoryRuleName(String oldName, String newName); // } // // Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/ReportSchedule.java // public interface ReportSchedule { // // public String getId(); // // public String getName(); // // public String getExpression(); // // public String getTimespan(); // // public boolean isDefaultSchedule(); // // public Long getNextFireTime(); // // public List<String> getReportReceivers(); // } // // Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/ReportScheduleService.java // public interface ReportScheduleService { // long count(); // // ReportSchedule update(String name, ReportSchedule schedule); // // ReportSchedule create(ReportSchedule schedule); // // List<ReportSchedule> all(); // // int destroy(String scheduleName) throws MongoException, UnsupportedEncodingException; // // ReportSchedule fromRequest(AddReportScheduleRequest request); // // ReportSchedule fromRequest(UpdateReportScheduleRequest request); // // ReportSchedule get(String id); // // ReportSchedule updateNextFireTime(String id, Date nextFireTime); // // } // // Path: src/main/java/org/graylog/plugins/aggregates/rule/Rule.java // public interface Rule { // // public String getQuery(); // // public String getField(); // // public long getNumberOfMatches(); // // public boolean isMatchMoreOrEqual(); // // public int getInterval(); // // public String getName(); // // public boolean isEnabled(); // // public String getStreamId(); // // public boolean isInReport(); // // public List<String> getReportSchedules(); // // public String getAlertConditionId(); // // public boolean shouldRepeatNotifications(); // // public long getBacklog(); // } // // Path: src/main/java/org/graylog/plugins/aggregates/rule/RuleService.java // public interface RuleService { // long count(); // // Rule update(String name, Rule rule); // // Rule create(Rule rule); // // List<Rule> all(); // // int destroy(String ruleName) throws MongoException, UnsupportedEncodingException; // // Rule fromRequest(AddRuleRequest request); // // Rule fromRequest(UpdateRuleRequest request); // // //Rule setAlertConditionId(Rule rule, String currentAlertId); // // String createOrUpdateAlertCondition(Rule rule); // }
import java.io.ByteArrayOutputStream; import java.net.InetAddress; import java.net.UnknownHostException; import java.text.ParseException; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.inject.Inject; import javax.mail.MessagingException; import org.apache.commons.mail.EmailException; import org.drools.core.time.impl.CronExpression; import org.graylog.plugins.aggregates.history.HistoryAggregateItem; import org.graylog.plugins.aggregates.history.HistoryItemService; import org.graylog.plugins.aggregates.report.schedule.ReportSchedule; import org.graylog.plugins.aggregates.report.schedule.ReportScheduleService; import org.graylog.plugins.aggregates.rule.Rule; import org.graylog.plugins.aggregates.rule.RuleService; import org.graylog2.plugin.alarms.transports.TransportConfigurationException; import org.graylog2.plugin.periodical.Periodical; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
@Inject public AggregatesReport(ReportSender reportSender, HistoryItemService historyItemService, RuleService ruleService, ReportScheduleService reportScheduleService) { this.reportSender = reportSender; this.historyItemService = historyItemService; this.ruleService = ruleService; this.reportScheduleService = reportScheduleService; InetAddress addr; try { addr = InetAddress.getLocalHost(); this.hostname = addr.getCanonicalHostName(); } catch (UnknownHostException e) { e.printStackTrace(); } } private void setNewFireTime(ReportSchedule reportSchedule, Calendar cal) { CronExpression c; try { c = new CronExpression(reportSchedule.getExpression()); reportScheduleService.updateNextFireTime(reportSchedule.getId(), c.getNextValidTimeAfter(cal.getTime())); } catch (ParseException e) { LOG.error("Schedule " + reportSchedule.getName() + " has invalid Cron Expression " + reportSchedule.getExpression()); } }
// Path: src/main/java/org/graylog/plugins/aggregates/history/HistoryAggregateItem.java // public interface HistoryAggregateItem { // public String getMoment(); // // public long getNumberOfHits(); // // } // // Path: src/main/java/org/graylog/plugins/aggregates/history/HistoryItemService.java // public interface HistoryItemService { // long count(); // // HistoryItem create(HistoryItem historyItem); // // List<HistoryItem> all(); // // List<HistoryAggregateItem> getForRuleName(String ruleName, int days); // // void removeBefore(Date date); // // List<HistoryAggregateItem> getForRuleName(String ruleName, String timespan); // // void updateHistoryRuleName(String oldName, String newName); // } // // Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/ReportSchedule.java // public interface ReportSchedule { // // public String getId(); // // public String getName(); // // public String getExpression(); // // public String getTimespan(); // // public boolean isDefaultSchedule(); // // public Long getNextFireTime(); // // public List<String> getReportReceivers(); // } // // Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/ReportScheduleService.java // public interface ReportScheduleService { // long count(); // // ReportSchedule update(String name, ReportSchedule schedule); // // ReportSchedule create(ReportSchedule schedule); // // List<ReportSchedule> all(); // // int destroy(String scheduleName) throws MongoException, UnsupportedEncodingException; // // ReportSchedule fromRequest(AddReportScheduleRequest request); // // ReportSchedule fromRequest(UpdateReportScheduleRequest request); // // ReportSchedule get(String id); // // ReportSchedule updateNextFireTime(String id, Date nextFireTime); // // } // // Path: src/main/java/org/graylog/plugins/aggregates/rule/Rule.java // public interface Rule { // // public String getQuery(); // // public String getField(); // // public long getNumberOfMatches(); // // public boolean isMatchMoreOrEqual(); // // public int getInterval(); // // public String getName(); // // public boolean isEnabled(); // // public String getStreamId(); // // public boolean isInReport(); // // public List<String> getReportSchedules(); // // public String getAlertConditionId(); // // public boolean shouldRepeatNotifications(); // // public long getBacklog(); // } // // Path: src/main/java/org/graylog/plugins/aggregates/rule/RuleService.java // public interface RuleService { // long count(); // // Rule update(String name, Rule rule); // // Rule create(Rule rule); // // List<Rule> all(); // // int destroy(String ruleName) throws MongoException, UnsupportedEncodingException; // // Rule fromRequest(AddRuleRequest request); // // Rule fromRequest(UpdateRuleRequest request); // // //Rule setAlertConditionId(Rule rule, String currentAlertId); // // String createOrUpdateAlertCondition(Rule rule); // } // Path: src/main/java/org/graylog/plugins/aggregates/report/AggregatesReport.java import java.io.ByteArrayOutputStream; import java.net.InetAddress; import java.net.UnknownHostException; import java.text.ParseException; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.inject.Inject; import javax.mail.MessagingException; import org.apache.commons.mail.EmailException; import org.drools.core.time.impl.CronExpression; import org.graylog.plugins.aggregates.history.HistoryAggregateItem; import org.graylog.plugins.aggregates.history.HistoryItemService; import org.graylog.plugins.aggregates.report.schedule.ReportSchedule; import org.graylog.plugins.aggregates.report.schedule.ReportScheduleService; import org.graylog.plugins.aggregates.rule.Rule; import org.graylog.plugins.aggregates.rule.RuleService; import org.graylog2.plugin.alarms.transports.TransportConfigurationException; import org.graylog2.plugin.periodical.Periodical; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @Inject public AggregatesReport(ReportSender reportSender, HistoryItemService historyItemService, RuleService ruleService, ReportScheduleService reportScheduleService) { this.reportSender = reportSender; this.historyItemService = historyItemService; this.ruleService = ruleService; this.reportScheduleService = reportScheduleService; InetAddress addr; try { addr = InetAddress.getLocalHost(); this.hostname = addr.getCanonicalHostName(); } catch (UnknownHostException e) { e.printStackTrace(); } } private void setNewFireTime(ReportSchedule reportSchedule, Calendar cal) { CronExpression c; try { c = new CronExpression(reportSchedule.getExpression()); reportScheduleService.updateNextFireTime(reportSchedule.getId(), c.getNextValidTimeAfter(cal.getTime())); } catch (ParseException e) { LOG.error("Schedule " + reportSchedule.getName() + " has invalid Cron Expression " + reportSchedule.getExpression()); } }
private ReportSchedule getMatchingSchedule(Rule rule, List<ReportSchedule> reportSchedules) {
cvtienhoven/graylog-plugin-aggregates
src/main/java/org/graylog/plugins/aggregates/report/AggregatesReport.java
// Path: src/main/java/org/graylog/plugins/aggregates/history/HistoryAggregateItem.java // public interface HistoryAggregateItem { // public String getMoment(); // // public long getNumberOfHits(); // // } // // Path: src/main/java/org/graylog/plugins/aggregates/history/HistoryItemService.java // public interface HistoryItemService { // long count(); // // HistoryItem create(HistoryItem historyItem); // // List<HistoryItem> all(); // // List<HistoryAggregateItem> getForRuleName(String ruleName, int days); // // void removeBefore(Date date); // // List<HistoryAggregateItem> getForRuleName(String ruleName, String timespan); // // void updateHistoryRuleName(String oldName, String newName); // } // // Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/ReportSchedule.java // public interface ReportSchedule { // // public String getId(); // // public String getName(); // // public String getExpression(); // // public String getTimespan(); // // public boolean isDefaultSchedule(); // // public Long getNextFireTime(); // // public List<String> getReportReceivers(); // } // // Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/ReportScheduleService.java // public interface ReportScheduleService { // long count(); // // ReportSchedule update(String name, ReportSchedule schedule); // // ReportSchedule create(ReportSchedule schedule); // // List<ReportSchedule> all(); // // int destroy(String scheduleName) throws MongoException, UnsupportedEncodingException; // // ReportSchedule fromRequest(AddReportScheduleRequest request); // // ReportSchedule fromRequest(UpdateReportScheduleRequest request); // // ReportSchedule get(String id); // // ReportSchedule updateNextFireTime(String id, Date nextFireTime); // // } // // Path: src/main/java/org/graylog/plugins/aggregates/rule/Rule.java // public interface Rule { // // public String getQuery(); // // public String getField(); // // public long getNumberOfMatches(); // // public boolean isMatchMoreOrEqual(); // // public int getInterval(); // // public String getName(); // // public boolean isEnabled(); // // public String getStreamId(); // // public boolean isInReport(); // // public List<String> getReportSchedules(); // // public String getAlertConditionId(); // // public boolean shouldRepeatNotifications(); // // public long getBacklog(); // } // // Path: src/main/java/org/graylog/plugins/aggregates/rule/RuleService.java // public interface RuleService { // long count(); // // Rule update(String name, Rule rule); // // Rule create(Rule rule); // // List<Rule> all(); // // int destroy(String ruleName) throws MongoException, UnsupportedEncodingException; // // Rule fromRequest(AddRuleRequest request); // // Rule fromRequest(UpdateRuleRequest request); // // //Rule setAlertConditionId(Rule rule, String currentAlertId); // // String createOrUpdateAlertCondition(Rule rule); // }
import java.io.ByteArrayOutputStream; import java.net.InetAddress; import java.net.UnknownHostException; import java.text.ParseException; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.inject.Inject; import javax.mail.MessagingException; import org.apache.commons.mail.EmailException; import org.drools.core.time.impl.CronExpression; import org.graylog.plugins.aggregates.history.HistoryAggregateItem; import org.graylog.plugins.aggregates.history.HistoryItemService; import org.graylog.plugins.aggregates.report.schedule.ReportSchedule; import org.graylog.plugins.aggregates.report.schedule.ReportScheduleService; import org.graylog.plugins.aggregates.rule.Rule; import org.graylog.plugins.aggregates.rule.RuleService; import org.graylog2.plugin.alarms.transports.TransportConfigurationException; import org.graylog2.plugin.periodical.Periodical; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
for (ReportSchedule reportSchedule : reportSchedules) { if (rule.getReportSchedules().contains(reportSchedule.getId())) { return reportSchedule; } } return null; } @Override public void doRun() { Calendar cal = Calendar.getInstance(); List<ReportSchedule> reportSchedules = reportScheduleService.all(); List<ReportSchedule> applicableReportSchedules = new ArrayList<ReportSchedule>(); // get the schedules that apply to the current dateTime for (ReportSchedule reportSchedule : reportSchedules) { if (reportSchedule.getNextFireTime() == null) { setNewFireTime(reportSchedule, cal); } if (reportSchedule.getNextFireTime() != null && new Date(reportSchedule.getNextFireTime()).before(cal.getTime())) { applicableReportSchedules.add(reportSchedule); setNewFireTime(reportSchedule, cal); } } // select the rules that match the applicable schedules List<Rule> rulesList = ruleService.all();
// Path: src/main/java/org/graylog/plugins/aggregates/history/HistoryAggregateItem.java // public interface HistoryAggregateItem { // public String getMoment(); // // public long getNumberOfHits(); // // } // // Path: src/main/java/org/graylog/plugins/aggregates/history/HistoryItemService.java // public interface HistoryItemService { // long count(); // // HistoryItem create(HistoryItem historyItem); // // List<HistoryItem> all(); // // List<HistoryAggregateItem> getForRuleName(String ruleName, int days); // // void removeBefore(Date date); // // List<HistoryAggregateItem> getForRuleName(String ruleName, String timespan); // // void updateHistoryRuleName(String oldName, String newName); // } // // Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/ReportSchedule.java // public interface ReportSchedule { // // public String getId(); // // public String getName(); // // public String getExpression(); // // public String getTimespan(); // // public boolean isDefaultSchedule(); // // public Long getNextFireTime(); // // public List<String> getReportReceivers(); // } // // Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/ReportScheduleService.java // public interface ReportScheduleService { // long count(); // // ReportSchedule update(String name, ReportSchedule schedule); // // ReportSchedule create(ReportSchedule schedule); // // List<ReportSchedule> all(); // // int destroy(String scheduleName) throws MongoException, UnsupportedEncodingException; // // ReportSchedule fromRequest(AddReportScheduleRequest request); // // ReportSchedule fromRequest(UpdateReportScheduleRequest request); // // ReportSchedule get(String id); // // ReportSchedule updateNextFireTime(String id, Date nextFireTime); // // } // // Path: src/main/java/org/graylog/plugins/aggregates/rule/Rule.java // public interface Rule { // // public String getQuery(); // // public String getField(); // // public long getNumberOfMatches(); // // public boolean isMatchMoreOrEqual(); // // public int getInterval(); // // public String getName(); // // public boolean isEnabled(); // // public String getStreamId(); // // public boolean isInReport(); // // public List<String> getReportSchedules(); // // public String getAlertConditionId(); // // public boolean shouldRepeatNotifications(); // // public long getBacklog(); // } // // Path: src/main/java/org/graylog/plugins/aggregates/rule/RuleService.java // public interface RuleService { // long count(); // // Rule update(String name, Rule rule); // // Rule create(Rule rule); // // List<Rule> all(); // // int destroy(String ruleName) throws MongoException, UnsupportedEncodingException; // // Rule fromRequest(AddRuleRequest request); // // Rule fromRequest(UpdateRuleRequest request); // // //Rule setAlertConditionId(Rule rule, String currentAlertId); // // String createOrUpdateAlertCondition(Rule rule); // } // Path: src/main/java/org/graylog/plugins/aggregates/report/AggregatesReport.java import java.io.ByteArrayOutputStream; import java.net.InetAddress; import java.net.UnknownHostException; import java.text.ParseException; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.inject.Inject; import javax.mail.MessagingException; import org.apache.commons.mail.EmailException; import org.drools.core.time.impl.CronExpression; import org.graylog.plugins.aggregates.history.HistoryAggregateItem; import org.graylog.plugins.aggregates.history.HistoryItemService; import org.graylog.plugins.aggregates.report.schedule.ReportSchedule; import org.graylog.plugins.aggregates.report.schedule.ReportScheduleService; import org.graylog.plugins.aggregates.rule.Rule; import org.graylog.plugins.aggregates.rule.RuleService; import org.graylog2.plugin.alarms.transports.TransportConfigurationException; import org.graylog2.plugin.periodical.Periodical; import org.slf4j.Logger; import org.slf4j.LoggerFactory; for (ReportSchedule reportSchedule : reportSchedules) { if (rule.getReportSchedules().contains(reportSchedule.getId())) { return reportSchedule; } } return null; } @Override public void doRun() { Calendar cal = Calendar.getInstance(); List<ReportSchedule> reportSchedules = reportScheduleService.all(); List<ReportSchedule> applicableReportSchedules = new ArrayList<ReportSchedule>(); // get the schedules that apply to the current dateTime for (ReportSchedule reportSchedule : reportSchedules) { if (reportSchedule.getNextFireTime() == null) { setNewFireTime(reportSchedule, cal); } if (reportSchedule.getNextFireTime() != null && new Date(reportSchedule.getNextFireTime()).before(cal.getTime())) { applicableReportSchedules.add(reportSchedule); setNewFireTime(reportSchedule, cal); } } // select the rules that match the applicable schedules List<Rule> rulesList = ruleService.all();
Map<String, Map<Rule, List<HistoryAggregateItem>>> receipientsSeries = new HashMap<String, Map<Rule, List<HistoryAggregateItem>>>();
cvtienhoven/graylog-plugin-aggregates
src/main/java/org/graylog/plugins/aggregates/rule/rest/models/responses/RulesList.java
// Path: src/main/java/org/graylog/plugins/aggregates/rule/Rule.java // public interface Rule { // // public String getQuery(); // // public String getField(); // // public long getNumberOfMatches(); // // public boolean isMatchMoreOrEqual(); // // public int getInterval(); // // public String getName(); // // public boolean isEnabled(); // // public String getStreamId(); // // public boolean isInReport(); // // public List<String> getReportSchedules(); // // public String getAlertConditionId(); // // public boolean shouldRepeatNotifications(); // // public long getBacklog(); // }
import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.auto.value.AutoValue; import java.util.List; import org.graylog.plugins.aggregates.rule.Rule;
package org.graylog.plugins.aggregates.rule.rest.models.responses; @AutoValue @JsonAutoDetect public abstract class RulesList { @JsonProperty
// Path: src/main/java/org/graylog/plugins/aggregates/rule/Rule.java // public interface Rule { // // public String getQuery(); // // public String getField(); // // public long getNumberOfMatches(); // // public boolean isMatchMoreOrEqual(); // // public int getInterval(); // // public String getName(); // // public boolean isEnabled(); // // public String getStreamId(); // // public boolean isInReport(); // // public List<String> getReportSchedules(); // // public String getAlertConditionId(); // // public boolean shouldRepeatNotifications(); // // public long getBacklog(); // } // Path: src/main/java/org/graylog/plugins/aggregates/rule/rest/models/responses/RulesList.java import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.auto.value.AutoValue; import java.util.List; import org.graylog.plugins.aggregates.rule.Rule; package org.graylog.plugins.aggregates.rule.rest.models.responses; @AutoValue @JsonAutoDetect public abstract class RulesList { @JsonProperty
public abstract List<Rule> getRules();
cvtienhoven/graylog-plugin-aggregates
src/main/java/org/graylog/plugins/aggregates/rule/rest/models/requests/AddRuleRequest.java
// Path: src/main/java/org/graylog/plugins/aggregates/rule/Rule.java // public interface Rule { // // public String getQuery(); // // public String getField(); // // public long getNumberOfMatches(); // // public boolean isMatchMoreOrEqual(); // // public int getInterval(); // // public String getName(); // // public boolean isEnabled(); // // public String getStreamId(); // // public boolean isInReport(); // // public List<String> getReportSchedules(); // // public String getAlertConditionId(); // // public boolean shouldRepeatNotifications(); // // public long getBacklog(); // } // // Path: src/main/java/org/graylog/plugins/aggregates/rule/RuleImpl.java // @AutoValue // @JsonAutoDetect // @JsonIgnoreProperties(ignoreUnknown = true) // @CollectionName("aggregate_rules") // public abstract class RuleImpl implements Rule{ // // // @JsonProperty("query") // @Override // @NotNull // public abstract String getQuery(); // // @JsonProperty("field") // @Override // @NotNull // public abstract String getField(); // // @JsonProperty("numberOfMatches") // @Override // @Min(1) // public abstract long getNumberOfMatches(); // // @JsonProperty("matchMoreOrEqual") // @Override // public abstract boolean isMatchMoreOrEqual(); // // @JsonProperty("interval") // @Override // @Min(1) // public abstract int getInterval(); // // @JsonProperty("name") // @Override // @NotNull // public abstract String getName(); // // @JsonProperty("enabled") // @Override // public abstract boolean isEnabled(); // // @JsonProperty("streamId") // @Override // public abstract String getStreamId(); // // @JsonProperty("inReport") // @Override // public abstract boolean isInReport(); // // @JsonProperty("reportSchedules") // @Override // @Nullable // public abstract List<String> getReportSchedules(); // // @JsonProperty("alertConditionId") // @Override // @Nullable // public abstract String getAlertConditionId(); // // @JsonProperty("repeatNotifications") // @Override // @Nullable // public abstract boolean shouldRepeatNotifications(); // // @JsonProperty("backlog") // @Override // @Nullable // @Min(0) // public abstract long getBacklog(); // // @JsonCreator // public static RuleImpl create(@JsonProperty("_id") String objectId, // @JsonProperty("query") String query, // @JsonProperty("field") String field, // @JsonProperty("numberOfMatches") long numberOfMatches, // @JsonProperty("matchMoreOrEqual") boolean matchMoreOrEqual, // @JsonProperty("interval") int interval, // @JsonProperty("name") String name, // @JsonProperty("enabled") boolean enabled, // @JsonProperty("streamId") String streamId, // @JsonProperty("inReport") boolean inReport, // @JsonProperty("reportSchedules") List<String> reportSchedules, // @JsonProperty("alertConditionId") String alertConditionId, // @JsonProperty("repeatNotifications") boolean repeatNotifications, // @JsonProperty("backlog") long backlog) { // return new AutoValue_RuleImpl(query, field, numberOfMatches, matchMoreOrEqual, interval, name, enabled, streamId, inReport, reportSchedules, alertConditionId, repeatNotifications, backlog); // } // // public static RuleImpl create( // String query, // String field, // long numberOfMatches, // boolean matchMoreOrEqual, // int interval, // String name, // boolean enabled, // String streamId, // boolean inReport, // List<String> reportSchedules, // String alertConditionId, // boolean repeatNotifications, // long backlog) { // return new AutoValue_RuleImpl(query, field, numberOfMatches, matchMoreOrEqual, interval, name, enabled, streamId, inReport, reportSchedules, alertConditionId, repeatNotifications, backlog); // // } // }
import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.auto.value.AutoValue; import org.graylog.plugins.aggregates.rule.Rule; import org.graylog.plugins.aggregates.rule.RuleImpl; import javax.validation.Valid; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size;
package org.graylog.plugins.aggregates.rule.rest.models.requests; @AutoValue @JsonAutoDetect public abstract class AddRuleRequest { @JsonProperty("rule") @NotNull
// Path: src/main/java/org/graylog/plugins/aggregates/rule/Rule.java // public interface Rule { // // public String getQuery(); // // public String getField(); // // public long getNumberOfMatches(); // // public boolean isMatchMoreOrEqual(); // // public int getInterval(); // // public String getName(); // // public boolean isEnabled(); // // public String getStreamId(); // // public boolean isInReport(); // // public List<String> getReportSchedules(); // // public String getAlertConditionId(); // // public boolean shouldRepeatNotifications(); // // public long getBacklog(); // } // // Path: src/main/java/org/graylog/plugins/aggregates/rule/RuleImpl.java // @AutoValue // @JsonAutoDetect // @JsonIgnoreProperties(ignoreUnknown = true) // @CollectionName("aggregate_rules") // public abstract class RuleImpl implements Rule{ // // // @JsonProperty("query") // @Override // @NotNull // public abstract String getQuery(); // // @JsonProperty("field") // @Override // @NotNull // public abstract String getField(); // // @JsonProperty("numberOfMatches") // @Override // @Min(1) // public abstract long getNumberOfMatches(); // // @JsonProperty("matchMoreOrEqual") // @Override // public abstract boolean isMatchMoreOrEqual(); // // @JsonProperty("interval") // @Override // @Min(1) // public abstract int getInterval(); // // @JsonProperty("name") // @Override // @NotNull // public abstract String getName(); // // @JsonProperty("enabled") // @Override // public abstract boolean isEnabled(); // // @JsonProperty("streamId") // @Override // public abstract String getStreamId(); // // @JsonProperty("inReport") // @Override // public abstract boolean isInReport(); // // @JsonProperty("reportSchedules") // @Override // @Nullable // public abstract List<String> getReportSchedules(); // // @JsonProperty("alertConditionId") // @Override // @Nullable // public abstract String getAlertConditionId(); // // @JsonProperty("repeatNotifications") // @Override // @Nullable // public abstract boolean shouldRepeatNotifications(); // // @JsonProperty("backlog") // @Override // @Nullable // @Min(0) // public abstract long getBacklog(); // // @JsonCreator // public static RuleImpl create(@JsonProperty("_id") String objectId, // @JsonProperty("query") String query, // @JsonProperty("field") String field, // @JsonProperty("numberOfMatches") long numberOfMatches, // @JsonProperty("matchMoreOrEqual") boolean matchMoreOrEqual, // @JsonProperty("interval") int interval, // @JsonProperty("name") String name, // @JsonProperty("enabled") boolean enabled, // @JsonProperty("streamId") String streamId, // @JsonProperty("inReport") boolean inReport, // @JsonProperty("reportSchedules") List<String> reportSchedules, // @JsonProperty("alertConditionId") String alertConditionId, // @JsonProperty("repeatNotifications") boolean repeatNotifications, // @JsonProperty("backlog") long backlog) { // return new AutoValue_RuleImpl(query, field, numberOfMatches, matchMoreOrEqual, interval, name, enabled, streamId, inReport, reportSchedules, alertConditionId, repeatNotifications, backlog); // } // // public static RuleImpl create( // String query, // String field, // long numberOfMatches, // boolean matchMoreOrEqual, // int interval, // String name, // boolean enabled, // String streamId, // boolean inReport, // List<String> reportSchedules, // String alertConditionId, // boolean repeatNotifications, // long backlog) { // return new AutoValue_RuleImpl(query, field, numberOfMatches, matchMoreOrEqual, interval, name, enabled, streamId, inReport, reportSchedules, alertConditionId, repeatNotifications, backlog); // // } // } // Path: src/main/java/org/graylog/plugins/aggregates/rule/rest/models/requests/AddRuleRequest.java import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.auto.value.AutoValue; import org.graylog.plugins.aggregates.rule.Rule; import org.graylog.plugins.aggregates.rule.RuleImpl; import javax.validation.Valid; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; package org.graylog.plugins.aggregates.rule.rest.models.requests; @AutoValue @JsonAutoDetect public abstract class AddRuleRequest { @JsonProperty("rule") @NotNull
public abstract RuleImpl getRule();
cvtienhoven/graylog-plugin-aggregates
src/test/java/org/graylog/plugins/aggregates/report/ChartFactoryTest.java
// Path: src/main/java/org/graylog/plugins/aggregates/history/HistoryAggregateItem.java // public interface HistoryAggregateItem { // public String getMoment(); // // public long getNumberOfHits(); // // } // // Path: src/main/java/org/graylog/plugins/aggregates/history/HistoryAggregateItemImpl.java // @AutoValue // @JsonAutoDetect // public abstract class HistoryAggregateItemImpl implements HistoryAggregateItem{ // // @JsonProperty("moment") // @Override // public abstract String getMoment(); // // @JsonProperty("numberOfHits") // @Override // public abstract long getNumberOfHits(); // // // @JsonCreator // public static HistoryAggregateItemImpl create(@JsonProperty("_id") String objectId, // @JsonProperty("moment") String moment, // @JsonProperty("numberOfHits") long numberOfHits) { // return new AutoValue_HistoryAggregateItemImpl(moment, numberOfHits); // } // // public static HistoryAggregateItemImpl create( // String moment, // long numberOfHits) { // return new AutoValue_HistoryAggregateItemImpl(moment, numberOfHits); // // } // }
import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import org.graylog.plugins.aggregates.history.HistoryAggregateItem; import org.graylog.plugins.aggregates.history.HistoryAggregateItemImpl; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.runners.MockitoJUnitRunner;
package org.graylog.plugins.aggregates.report; @RunWith(MockitoJUnitRunner.class) public class ChartFactoryTest { @Test public void testGenerateTimeSeriesChart() throws ParseException{ Calendar cal = Calendar.getInstance(); SimpleDateFormat format = new SimpleDateFormat ("yyyy-MM-dd'T'HH");
// Path: src/main/java/org/graylog/plugins/aggregates/history/HistoryAggregateItem.java // public interface HistoryAggregateItem { // public String getMoment(); // // public long getNumberOfHits(); // // } // // Path: src/main/java/org/graylog/plugins/aggregates/history/HistoryAggregateItemImpl.java // @AutoValue // @JsonAutoDetect // public abstract class HistoryAggregateItemImpl implements HistoryAggregateItem{ // // @JsonProperty("moment") // @Override // public abstract String getMoment(); // // @JsonProperty("numberOfHits") // @Override // public abstract long getNumberOfHits(); // // // @JsonCreator // public static HistoryAggregateItemImpl create(@JsonProperty("_id") String objectId, // @JsonProperty("moment") String moment, // @JsonProperty("numberOfHits") long numberOfHits) { // return new AutoValue_HistoryAggregateItemImpl(moment, numberOfHits); // } // // public static HistoryAggregateItemImpl create( // String moment, // long numberOfHits) { // return new AutoValue_HistoryAggregateItemImpl(moment, numberOfHits); // // } // } // Path: src/test/java/org/graylog/plugins/aggregates/report/ChartFactoryTest.java import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import org.graylog.plugins.aggregates.history.HistoryAggregateItem; import org.graylog.plugins.aggregates.history.HistoryAggregateItemImpl; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.runners.MockitoJUnitRunner; package org.graylog.plugins.aggregates.report; @RunWith(MockitoJUnitRunner.class) public class ChartFactoryTest { @Test public void testGenerateTimeSeriesChart() throws ParseException{ Calendar cal = Calendar.getInstance(); SimpleDateFormat format = new SimpleDateFormat ("yyyy-MM-dd'T'HH");
List<HistoryAggregateItem> history = new ArrayList<HistoryAggregateItem>();
cvtienhoven/graylog-plugin-aggregates
src/test/java/org/graylog/plugins/aggregates/report/ChartFactoryTest.java
// Path: src/main/java/org/graylog/plugins/aggregates/history/HistoryAggregateItem.java // public interface HistoryAggregateItem { // public String getMoment(); // // public long getNumberOfHits(); // // } // // Path: src/main/java/org/graylog/plugins/aggregates/history/HistoryAggregateItemImpl.java // @AutoValue // @JsonAutoDetect // public abstract class HistoryAggregateItemImpl implements HistoryAggregateItem{ // // @JsonProperty("moment") // @Override // public abstract String getMoment(); // // @JsonProperty("numberOfHits") // @Override // public abstract long getNumberOfHits(); // // // @JsonCreator // public static HistoryAggregateItemImpl create(@JsonProperty("_id") String objectId, // @JsonProperty("moment") String moment, // @JsonProperty("numberOfHits") long numberOfHits) { // return new AutoValue_HistoryAggregateItemImpl(moment, numberOfHits); // } // // public static HistoryAggregateItemImpl create( // String moment, // long numberOfHits) { // return new AutoValue_HistoryAggregateItemImpl(moment, numberOfHits); // // } // }
import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import org.graylog.plugins.aggregates.history.HistoryAggregateItem; import org.graylog.plugins.aggregates.history.HistoryAggregateItemImpl; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.runners.MockitoJUnitRunner;
package org.graylog.plugins.aggregates.report; @RunWith(MockitoJUnitRunner.class) public class ChartFactoryTest { @Test public void testGenerateTimeSeriesChart() throws ParseException{ Calendar cal = Calendar.getInstance(); SimpleDateFormat format = new SimpleDateFormat ("yyyy-MM-dd'T'HH"); List<HistoryAggregateItem> history = new ArrayList<HistoryAggregateItem>(); for (int i=0; i<70; i++){ cal.add(Calendar.DATE, -1); String day = format.format(cal.getTime());
// Path: src/main/java/org/graylog/plugins/aggregates/history/HistoryAggregateItem.java // public interface HistoryAggregateItem { // public String getMoment(); // // public long getNumberOfHits(); // // } // // Path: src/main/java/org/graylog/plugins/aggregates/history/HistoryAggregateItemImpl.java // @AutoValue // @JsonAutoDetect // public abstract class HistoryAggregateItemImpl implements HistoryAggregateItem{ // // @JsonProperty("moment") // @Override // public abstract String getMoment(); // // @JsonProperty("numberOfHits") // @Override // public abstract long getNumberOfHits(); // // // @JsonCreator // public static HistoryAggregateItemImpl create(@JsonProperty("_id") String objectId, // @JsonProperty("moment") String moment, // @JsonProperty("numberOfHits") long numberOfHits) { // return new AutoValue_HistoryAggregateItemImpl(moment, numberOfHits); // } // // public static HistoryAggregateItemImpl create( // String moment, // long numberOfHits) { // return new AutoValue_HistoryAggregateItemImpl(moment, numberOfHits); // // } // } // Path: src/test/java/org/graylog/plugins/aggregates/report/ChartFactoryTest.java import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import org.graylog.plugins.aggregates.history.HistoryAggregateItem; import org.graylog.plugins.aggregates.history.HistoryAggregateItemImpl; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.runners.MockitoJUnitRunner; package org.graylog.plugins.aggregates.report; @RunWith(MockitoJUnitRunner.class) public class ChartFactoryTest { @Test public void testGenerateTimeSeriesChart() throws ParseException{ Calendar cal = Calendar.getInstance(); SimpleDateFormat format = new SimpleDateFormat ("yyyy-MM-dd'T'HH"); List<HistoryAggregateItem> history = new ArrayList<HistoryAggregateItem>(); for (int i=0; i<70; i++){ cal.add(Calendar.DATE, -1); String day = format.format(cal.getTime());
history.add(HistoryAggregateItemImpl.create(day, 54+i));
fstab/promagent
promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/hooks/TwoHooks.java
// Path: promagent-framework/promagent-api/src/main/java/io/promagent/hookcontext/MetricsStore.java // public class MetricsStore { // // private final CollectorRegistry registry; // private final ConcurrentMap<String, Collector> metrics = new ConcurrentHashMap<>(); // // public MetricsStore(CollectorRegistry registry) { // this.registry = registry; // } // // /** // * See {@link MetricsStore} and {@link MetricDef#MetricDef(String, BiFunction)}. // */ // @SuppressWarnings("unchecked") // public <T extends Collector> T createOrGet(MetricDef<T> metricDef) { // return (T) metrics.computeIfAbsent(metricDef.getMetricName(), s -> metricDef.getProducer().apply(metricDef.getMetricName(), registry)); // } // } // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/MethodCallCounter.java // public class MethodCallCounter { // // public static void reset() { // captures.clear(); // } // // public static void observe(Object hook, String methodName, Object... args) { // captures.add(new Capture(hook, methodName, args)); // } // // public static void assertNumCalls(int expectedNumberOfCalls, Class<?> hookClass, String hookMethod, Object... expectedArgs) { // List<Capture> matching = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .filter(c -> c.hookMethod.equals(hookMethod)) // .filter(c -> Arrays.equals(expectedArgs, c.args)) // .collect(Collectors.toList()); // Assertions.assertEquals(expectedNumberOfCalls, matching.size()); // } // // // special case for the varargsMixed test // public static void assertNumCalls(int expectedNumberOfCalls, Class<?> hookClass, String hookMethod, String firstString, String... moreStrings) { // List<Capture> matching = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .filter(c -> c.hookMethod.equals(hookMethod)) // .filter(c -> c.args.length == 2) // .filter(c -> Objects.equals(firstString, c.args[0])) // .filter(c -> Arrays.equals(moreStrings, (String[]) c.args[1])) // .collect(Collectors.toList()); // Assertions.assertEquals(expectedNumberOfCalls, matching.size()); // } // // public static void assertNumHookInstances(int expectedNumberOfInstances, Class<?> hookClass) { // long actualNumberOfInstances = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .map(c -> c.hook) // .distinct() // .count(); // Assertions.assertEquals(expectedNumberOfInstances, (int) actualNumberOfInstances); // } // // private static class Capture { // final Object hook; // final String hookMethod; // final Object[] args; // // Capture(Object hook, String hookMethod, Object[] args) { // this.hook = hook; // this.hookMethod = hookMethod; // this.args = args; // } // } // // private static final List<Capture> captures = Collections.synchronizedList(new ArrayList<>()); // // private MethodCallCounter() {} // } // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/classes/Fruit.java // public class Fruit { // public static class Orange extends Fruit{} // }
import io.promagent.annotations.Before; import io.promagent.annotations.Hook; import io.promagent.hookcontext.MetricsStore; import io.promagent.internal.instrumentationtests.MethodCallCounter; import io.promagent.internal.instrumentationtests.classes.Fruit;
package io.promagent.internal.instrumentationtests.hooks; /** * Two hooks instrumenting the same class. */ public class TwoHooks { @Hook(instruments = "io.promagent.internal.instrumentationtests.classes.ParameterTypesExample") public static class HookOne {
// Path: promagent-framework/promagent-api/src/main/java/io/promagent/hookcontext/MetricsStore.java // public class MetricsStore { // // private final CollectorRegistry registry; // private final ConcurrentMap<String, Collector> metrics = new ConcurrentHashMap<>(); // // public MetricsStore(CollectorRegistry registry) { // this.registry = registry; // } // // /** // * See {@link MetricsStore} and {@link MetricDef#MetricDef(String, BiFunction)}. // */ // @SuppressWarnings("unchecked") // public <T extends Collector> T createOrGet(MetricDef<T> metricDef) { // return (T) metrics.computeIfAbsent(metricDef.getMetricName(), s -> metricDef.getProducer().apply(metricDef.getMetricName(), registry)); // } // } // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/MethodCallCounter.java // public class MethodCallCounter { // // public static void reset() { // captures.clear(); // } // // public static void observe(Object hook, String methodName, Object... args) { // captures.add(new Capture(hook, methodName, args)); // } // // public static void assertNumCalls(int expectedNumberOfCalls, Class<?> hookClass, String hookMethod, Object... expectedArgs) { // List<Capture> matching = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .filter(c -> c.hookMethod.equals(hookMethod)) // .filter(c -> Arrays.equals(expectedArgs, c.args)) // .collect(Collectors.toList()); // Assertions.assertEquals(expectedNumberOfCalls, matching.size()); // } // // // special case for the varargsMixed test // public static void assertNumCalls(int expectedNumberOfCalls, Class<?> hookClass, String hookMethod, String firstString, String... moreStrings) { // List<Capture> matching = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .filter(c -> c.hookMethod.equals(hookMethod)) // .filter(c -> c.args.length == 2) // .filter(c -> Objects.equals(firstString, c.args[0])) // .filter(c -> Arrays.equals(moreStrings, (String[]) c.args[1])) // .collect(Collectors.toList()); // Assertions.assertEquals(expectedNumberOfCalls, matching.size()); // } // // public static void assertNumHookInstances(int expectedNumberOfInstances, Class<?> hookClass) { // long actualNumberOfInstances = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .map(c -> c.hook) // .distinct() // .count(); // Assertions.assertEquals(expectedNumberOfInstances, (int) actualNumberOfInstances); // } // // private static class Capture { // final Object hook; // final String hookMethod; // final Object[] args; // // Capture(Object hook, String hookMethod, Object[] args) { // this.hook = hook; // this.hookMethod = hookMethod; // this.args = args; // } // } // // private static final List<Capture> captures = Collections.synchronizedList(new ArrayList<>()); // // private MethodCallCounter() {} // } // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/classes/Fruit.java // public class Fruit { // public static class Orange extends Fruit{} // } // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/hooks/TwoHooks.java import io.promagent.annotations.Before; import io.promagent.annotations.Hook; import io.promagent.hookcontext.MetricsStore; import io.promagent.internal.instrumentationtests.MethodCallCounter; import io.promagent.internal.instrumentationtests.classes.Fruit; package io.promagent.internal.instrumentationtests.hooks; /** * Two hooks instrumenting the same class. */ public class TwoHooks { @Hook(instruments = "io.promagent.internal.instrumentationtests.classes.ParameterTypesExample") public static class HookOne {
public HookOne(MetricsStore m) {}
fstab/promagent
promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/hooks/TwoHooks.java
// Path: promagent-framework/promagent-api/src/main/java/io/promagent/hookcontext/MetricsStore.java // public class MetricsStore { // // private final CollectorRegistry registry; // private final ConcurrentMap<String, Collector> metrics = new ConcurrentHashMap<>(); // // public MetricsStore(CollectorRegistry registry) { // this.registry = registry; // } // // /** // * See {@link MetricsStore} and {@link MetricDef#MetricDef(String, BiFunction)}. // */ // @SuppressWarnings("unchecked") // public <T extends Collector> T createOrGet(MetricDef<T> metricDef) { // return (T) metrics.computeIfAbsent(metricDef.getMetricName(), s -> metricDef.getProducer().apply(metricDef.getMetricName(), registry)); // } // } // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/MethodCallCounter.java // public class MethodCallCounter { // // public static void reset() { // captures.clear(); // } // // public static void observe(Object hook, String methodName, Object... args) { // captures.add(new Capture(hook, methodName, args)); // } // // public static void assertNumCalls(int expectedNumberOfCalls, Class<?> hookClass, String hookMethod, Object... expectedArgs) { // List<Capture> matching = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .filter(c -> c.hookMethod.equals(hookMethod)) // .filter(c -> Arrays.equals(expectedArgs, c.args)) // .collect(Collectors.toList()); // Assertions.assertEquals(expectedNumberOfCalls, matching.size()); // } // // // special case for the varargsMixed test // public static void assertNumCalls(int expectedNumberOfCalls, Class<?> hookClass, String hookMethod, String firstString, String... moreStrings) { // List<Capture> matching = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .filter(c -> c.hookMethod.equals(hookMethod)) // .filter(c -> c.args.length == 2) // .filter(c -> Objects.equals(firstString, c.args[0])) // .filter(c -> Arrays.equals(moreStrings, (String[]) c.args[1])) // .collect(Collectors.toList()); // Assertions.assertEquals(expectedNumberOfCalls, matching.size()); // } // // public static void assertNumHookInstances(int expectedNumberOfInstances, Class<?> hookClass) { // long actualNumberOfInstances = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .map(c -> c.hook) // .distinct() // .count(); // Assertions.assertEquals(expectedNumberOfInstances, (int) actualNumberOfInstances); // } // // private static class Capture { // final Object hook; // final String hookMethod; // final Object[] args; // // Capture(Object hook, String hookMethod, Object[] args) { // this.hook = hook; // this.hookMethod = hookMethod; // this.args = args; // } // } // // private static final List<Capture> captures = Collections.synchronizedList(new ArrayList<>()); // // private MethodCallCounter() {} // } // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/classes/Fruit.java // public class Fruit { // public static class Orange extends Fruit{} // }
import io.promagent.annotations.Before; import io.promagent.annotations.Hook; import io.promagent.hookcontext.MetricsStore; import io.promagent.internal.instrumentationtests.MethodCallCounter; import io.promagent.internal.instrumentationtests.classes.Fruit;
package io.promagent.internal.instrumentationtests.hooks; /** * Two hooks instrumenting the same class. */ public class TwoHooks { @Hook(instruments = "io.promagent.internal.instrumentationtests.classes.ParameterTypesExample") public static class HookOne { public HookOne(MetricsStore m) {} @Before(method = "objects")
// Path: promagent-framework/promagent-api/src/main/java/io/promagent/hookcontext/MetricsStore.java // public class MetricsStore { // // private final CollectorRegistry registry; // private final ConcurrentMap<String, Collector> metrics = new ConcurrentHashMap<>(); // // public MetricsStore(CollectorRegistry registry) { // this.registry = registry; // } // // /** // * See {@link MetricsStore} and {@link MetricDef#MetricDef(String, BiFunction)}. // */ // @SuppressWarnings("unchecked") // public <T extends Collector> T createOrGet(MetricDef<T> metricDef) { // return (T) metrics.computeIfAbsent(metricDef.getMetricName(), s -> metricDef.getProducer().apply(metricDef.getMetricName(), registry)); // } // } // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/MethodCallCounter.java // public class MethodCallCounter { // // public static void reset() { // captures.clear(); // } // // public static void observe(Object hook, String methodName, Object... args) { // captures.add(new Capture(hook, methodName, args)); // } // // public static void assertNumCalls(int expectedNumberOfCalls, Class<?> hookClass, String hookMethod, Object... expectedArgs) { // List<Capture> matching = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .filter(c -> c.hookMethod.equals(hookMethod)) // .filter(c -> Arrays.equals(expectedArgs, c.args)) // .collect(Collectors.toList()); // Assertions.assertEquals(expectedNumberOfCalls, matching.size()); // } // // // special case for the varargsMixed test // public static void assertNumCalls(int expectedNumberOfCalls, Class<?> hookClass, String hookMethod, String firstString, String... moreStrings) { // List<Capture> matching = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .filter(c -> c.hookMethod.equals(hookMethod)) // .filter(c -> c.args.length == 2) // .filter(c -> Objects.equals(firstString, c.args[0])) // .filter(c -> Arrays.equals(moreStrings, (String[]) c.args[1])) // .collect(Collectors.toList()); // Assertions.assertEquals(expectedNumberOfCalls, matching.size()); // } // // public static void assertNumHookInstances(int expectedNumberOfInstances, Class<?> hookClass) { // long actualNumberOfInstances = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .map(c -> c.hook) // .distinct() // .count(); // Assertions.assertEquals(expectedNumberOfInstances, (int) actualNumberOfInstances); // } // // private static class Capture { // final Object hook; // final String hookMethod; // final Object[] args; // // Capture(Object hook, String hookMethod, Object[] args) { // this.hook = hook; // this.hookMethod = hookMethod; // this.args = args; // } // } // // private static final List<Capture> captures = Collections.synchronizedList(new ArrayList<>()); // // private MethodCallCounter() {} // } // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/classes/Fruit.java // public class Fruit { // public static class Orange extends Fruit{} // } // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/hooks/TwoHooks.java import io.promagent.annotations.Before; import io.promagent.annotations.Hook; import io.promagent.hookcontext.MetricsStore; import io.promagent.internal.instrumentationtests.MethodCallCounter; import io.promagent.internal.instrumentationtests.classes.Fruit; package io.promagent.internal.instrumentationtests.hooks; /** * Two hooks instrumenting the same class. */ public class TwoHooks { @Hook(instruments = "io.promagent.internal.instrumentationtests.classes.ParameterTypesExample") public static class HookOne { public HookOne(MetricsStore m) {} @Before(method = "objects")
public void before(Object o, Fruit f, Fruit.Orange x) {
fstab/promagent
promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/hooks/TwoHooks.java
// Path: promagent-framework/promagent-api/src/main/java/io/promagent/hookcontext/MetricsStore.java // public class MetricsStore { // // private final CollectorRegistry registry; // private final ConcurrentMap<String, Collector> metrics = new ConcurrentHashMap<>(); // // public MetricsStore(CollectorRegistry registry) { // this.registry = registry; // } // // /** // * See {@link MetricsStore} and {@link MetricDef#MetricDef(String, BiFunction)}. // */ // @SuppressWarnings("unchecked") // public <T extends Collector> T createOrGet(MetricDef<T> metricDef) { // return (T) metrics.computeIfAbsent(metricDef.getMetricName(), s -> metricDef.getProducer().apply(metricDef.getMetricName(), registry)); // } // } // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/MethodCallCounter.java // public class MethodCallCounter { // // public static void reset() { // captures.clear(); // } // // public static void observe(Object hook, String methodName, Object... args) { // captures.add(new Capture(hook, methodName, args)); // } // // public static void assertNumCalls(int expectedNumberOfCalls, Class<?> hookClass, String hookMethod, Object... expectedArgs) { // List<Capture> matching = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .filter(c -> c.hookMethod.equals(hookMethod)) // .filter(c -> Arrays.equals(expectedArgs, c.args)) // .collect(Collectors.toList()); // Assertions.assertEquals(expectedNumberOfCalls, matching.size()); // } // // // special case for the varargsMixed test // public static void assertNumCalls(int expectedNumberOfCalls, Class<?> hookClass, String hookMethod, String firstString, String... moreStrings) { // List<Capture> matching = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .filter(c -> c.hookMethod.equals(hookMethod)) // .filter(c -> c.args.length == 2) // .filter(c -> Objects.equals(firstString, c.args[0])) // .filter(c -> Arrays.equals(moreStrings, (String[]) c.args[1])) // .collect(Collectors.toList()); // Assertions.assertEquals(expectedNumberOfCalls, matching.size()); // } // // public static void assertNumHookInstances(int expectedNumberOfInstances, Class<?> hookClass) { // long actualNumberOfInstances = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .map(c -> c.hook) // .distinct() // .count(); // Assertions.assertEquals(expectedNumberOfInstances, (int) actualNumberOfInstances); // } // // private static class Capture { // final Object hook; // final String hookMethod; // final Object[] args; // // Capture(Object hook, String hookMethod, Object[] args) { // this.hook = hook; // this.hookMethod = hookMethod; // this.args = args; // } // } // // private static final List<Capture> captures = Collections.synchronizedList(new ArrayList<>()); // // private MethodCallCounter() {} // } // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/classes/Fruit.java // public class Fruit { // public static class Orange extends Fruit{} // }
import io.promagent.annotations.Before; import io.promagent.annotations.Hook; import io.promagent.hookcontext.MetricsStore; import io.promagent.internal.instrumentationtests.MethodCallCounter; import io.promagent.internal.instrumentationtests.classes.Fruit;
package io.promagent.internal.instrumentationtests.hooks; /** * Two hooks instrumenting the same class. */ public class TwoHooks { @Hook(instruments = "io.promagent.internal.instrumentationtests.classes.ParameterTypesExample") public static class HookOne { public HookOne(MetricsStore m) {} @Before(method = "objects") public void before(Object o, Fruit f, Fruit.Orange x) {
// Path: promagent-framework/promagent-api/src/main/java/io/promagent/hookcontext/MetricsStore.java // public class MetricsStore { // // private final CollectorRegistry registry; // private final ConcurrentMap<String, Collector> metrics = new ConcurrentHashMap<>(); // // public MetricsStore(CollectorRegistry registry) { // this.registry = registry; // } // // /** // * See {@link MetricsStore} and {@link MetricDef#MetricDef(String, BiFunction)}. // */ // @SuppressWarnings("unchecked") // public <T extends Collector> T createOrGet(MetricDef<T> metricDef) { // return (T) metrics.computeIfAbsent(metricDef.getMetricName(), s -> metricDef.getProducer().apply(metricDef.getMetricName(), registry)); // } // } // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/MethodCallCounter.java // public class MethodCallCounter { // // public static void reset() { // captures.clear(); // } // // public static void observe(Object hook, String methodName, Object... args) { // captures.add(new Capture(hook, methodName, args)); // } // // public static void assertNumCalls(int expectedNumberOfCalls, Class<?> hookClass, String hookMethod, Object... expectedArgs) { // List<Capture> matching = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .filter(c -> c.hookMethod.equals(hookMethod)) // .filter(c -> Arrays.equals(expectedArgs, c.args)) // .collect(Collectors.toList()); // Assertions.assertEquals(expectedNumberOfCalls, matching.size()); // } // // // special case for the varargsMixed test // public static void assertNumCalls(int expectedNumberOfCalls, Class<?> hookClass, String hookMethod, String firstString, String... moreStrings) { // List<Capture> matching = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .filter(c -> c.hookMethod.equals(hookMethod)) // .filter(c -> c.args.length == 2) // .filter(c -> Objects.equals(firstString, c.args[0])) // .filter(c -> Arrays.equals(moreStrings, (String[]) c.args[1])) // .collect(Collectors.toList()); // Assertions.assertEquals(expectedNumberOfCalls, matching.size()); // } // // public static void assertNumHookInstances(int expectedNumberOfInstances, Class<?> hookClass) { // long actualNumberOfInstances = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .map(c -> c.hook) // .distinct() // .count(); // Assertions.assertEquals(expectedNumberOfInstances, (int) actualNumberOfInstances); // } // // private static class Capture { // final Object hook; // final String hookMethod; // final Object[] args; // // Capture(Object hook, String hookMethod, Object[] args) { // this.hook = hook; // this.hookMethod = hookMethod; // this.args = args; // } // } // // private static final List<Capture> captures = Collections.synchronizedList(new ArrayList<>()); // // private MethodCallCounter() {} // } // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/classes/Fruit.java // public class Fruit { // public static class Orange extends Fruit{} // } // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/hooks/TwoHooks.java import io.promagent.annotations.Before; import io.promagent.annotations.Hook; import io.promagent.hookcontext.MetricsStore; import io.promagent.internal.instrumentationtests.MethodCallCounter; import io.promagent.internal.instrumentationtests.classes.Fruit; package io.promagent.internal.instrumentationtests.hooks; /** * Two hooks instrumenting the same class. */ public class TwoHooks { @Hook(instruments = "io.promagent.internal.instrumentationtests.classes.ParameterTypesExample") public static class HookOne { public HookOne(MetricsStore m) {} @Before(method = "objects") public void before(Object o, Fruit f, Fruit.Orange x) {
MethodCallCounter.observe(this, "before", o, f, x);
fstab/promagent
promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/hooks/ReturnedAndThrownHook.java
// Path: promagent-framework/promagent-api/src/main/java/io/promagent/hookcontext/MetricsStore.java // public class MetricsStore { // // private final CollectorRegistry registry; // private final ConcurrentMap<String, Collector> metrics = new ConcurrentHashMap<>(); // // public MetricsStore(CollectorRegistry registry) { // this.registry = registry; // } // // /** // * See {@link MetricsStore} and {@link MetricDef#MetricDef(String, BiFunction)}. // */ // @SuppressWarnings("unchecked") // public <T extends Collector> T createOrGet(MetricDef<T> metricDef) { // return (T) metrics.computeIfAbsent(metricDef.getMetricName(), s -> metricDef.getProducer().apply(metricDef.getMetricName(), registry)); // } // } // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/MethodCallCounter.java // public class MethodCallCounter { // // public static void reset() { // captures.clear(); // } // // public static void observe(Object hook, String methodName, Object... args) { // captures.add(new Capture(hook, methodName, args)); // } // // public static void assertNumCalls(int expectedNumberOfCalls, Class<?> hookClass, String hookMethod, Object... expectedArgs) { // List<Capture> matching = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .filter(c -> c.hookMethod.equals(hookMethod)) // .filter(c -> Arrays.equals(expectedArgs, c.args)) // .collect(Collectors.toList()); // Assertions.assertEquals(expectedNumberOfCalls, matching.size()); // } // // // special case for the varargsMixed test // public static void assertNumCalls(int expectedNumberOfCalls, Class<?> hookClass, String hookMethod, String firstString, String... moreStrings) { // List<Capture> matching = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .filter(c -> c.hookMethod.equals(hookMethod)) // .filter(c -> c.args.length == 2) // .filter(c -> Objects.equals(firstString, c.args[0])) // .filter(c -> Arrays.equals(moreStrings, (String[]) c.args[1])) // .collect(Collectors.toList()); // Assertions.assertEquals(expectedNumberOfCalls, matching.size()); // } // // public static void assertNumHookInstances(int expectedNumberOfInstances, Class<?> hookClass) { // long actualNumberOfInstances = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .map(c -> c.hook) // .distinct() // .count(); // Assertions.assertEquals(expectedNumberOfInstances, (int) actualNumberOfInstances); // } // // private static class Capture { // final Object hook; // final String hookMethod; // final Object[] args; // // Capture(Object hook, String hookMethod, Object[] args) { // this.hook = hook; // this.hookMethod = hookMethod; // this.args = args; // } // } // // private static final List<Capture> captures = Collections.synchronizedList(new ArrayList<>()); // // private MethodCallCounter() {} // } // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/classes/Fruit.java // public class Fruit { // public static class Orange extends Fruit{} // }
import io.promagent.annotations.*; import io.promagent.hookcontext.MetricsStore; import io.promagent.internal.instrumentationtests.MethodCallCounter; import io.promagent.internal.instrumentationtests.classes.Fruit; import java.util.List;
package io.promagent.internal.instrumentationtests.hooks; @Hook(instruments = "io.promagent.internal.instrumentationtests.classes.ReturnedAndThrownExample") public class ReturnedAndThrownHook {
// Path: promagent-framework/promagent-api/src/main/java/io/promagent/hookcontext/MetricsStore.java // public class MetricsStore { // // private final CollectorRegistry registry; // private final ConcurrentMap<String, Collector> metrics = new ConcurrentHashMap<>(); // // public MetricsStore(CollectorRegistry registry) { // this.registry = registry; // } // // /** // * See {@link MetricsStore} and {@link MetricDef#MetricDef(String, BiFunction)}. // */ // @SuppressWarnings("unchecked") // public <T extends Collector> T createOrGet(MetricDef<T> metricDef) { // return (T) metrics.computeIfAbsent(metricDef.getMetricName(), s -> metricDef.getProducer().apply(metricDef.getMetricName(), registry)); // } // } // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/MethodCallCounter.java // public class MethodCallCounter { // // public static void reset() { // captures.clear(); // } // // public static void observe(Object hook, String methodName, Object... args) { // captures.add(new Capture(hook, methodName, args)); // } // // public static void assertNumCalls(int expectedNumberOfCalls, Class<?> hookClass, String hookMethod, Object... expectedArgs) { // List<Capture> matching = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .filter(c -> c.hookMethod.equals(hookMethod)) // .filter(c -> Arrays.equals(expectedArgs, c.args)) // .collect(Collectors.toList()); // Assertions.assertEquals(expectedNumberOfCalls, matching.size()); // } // // // special case for the varargsMixed test // public static void assertNumCalls(int expectedNumberOfCalls, Class<?> hookClass, String hookMethod, String firstString, String... moreStrings) { // List<Capture> matching = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .filter(c -> c.hookMethod.equals(hookMethod)) // .filter(c -> c.args.length == 2) // .filter(c -> Objects.equals(firstString, c.args[0])) // .filter(c -> Arrays.equals(moreStrings, (String[]) c.args[1])) // .collect(Collectors.toList()); // Assertions.assertEquals(expectedNumberOfCalls, matching.size()); // } // // public static void assertNumHookInstances(int expectedNumberOfInstances, Class<?> hookClass) { // long actualNumberOfInstances = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .map(c -> c.hook) // .distinct() // .count(); // Assertions.assertEquals(expectedNumberOfInstances, (int) actualNumberOfInstances); // } // // private static class Capture { // final Object hook; // final String hookMethod; // final Object[] args; // // Capture(Object hook, String hookMethod, Object[] args) { // this.hook = hook; // this.hookMethod = hookMethod; // this.args = args; // } // } // // private static final List<Capture> captures = Collections.synchronizedList(new ArrayList<>()); // // private MethodCallCounter() {} // } // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/classes/Fruit.java // public class Fruit { // public static class Orange extends Fruit{} // } // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/hooks/ReturnedAndThrownHook.java import io.promagent.annotations.*; import io.promagent.hookcontext.MetricsStore; import io.promagent.internal.instrumentationtests.MethodCallCounter; import io.promagent.internal.instrumentationtests.classes.Fruit; import java.util.List; package io.promagent.internal.instrumentationtests.hooks; @Hook(instruments = "io.promagent.internal.instrumentationtests.classes.ReturnedAndThrownExample") public class ReturnedAndThrownHook {
public ReturnedAndThrownHook(MetricsStore m) {}
fstab/promagent
promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/hooks/ReturnedAndThrownHook.java
// Path: promagent-framework/promagent-api/src/main/java/io/promagent/hookcontext/MetricsStore.java // public class MetricsStore { // // private final CollectorRegistry registry; // private final ConcurrentMap<String, Collector> metrics = new ConcurrentHashMap<>(); // // public MetricsStore(CollectorRegistry registry) { // this.registry = registry; // } // // /** // * See {@link MetricsStore} and {@link MetricDef#MetricDef(String, BiFunction)}. // */ // @SuppressWarnings("unchecked") // public <T extends Collector> T createOrGet(MetricDef<T> metricDef) { // return (T) metrics.computeIfAbsent(metricDef.getMetricName(), s -> metricDef.getProducer().apply(metricDef.getMetricName(), registry)); // } // } // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/MethodCallCounter.java // public class MethodCallCounter { // // public static void reset() { // captures.clear(); // } // // public static void observe(Object hook, String methodName, Object... args) { // captures.add(new Capture(hook, methodName, args)); // } // // public static void assertNumCalls(int expectedNumberOfCalls, Class<?> hookClass, String hookMethod, Object... expectedArgs) { // List<Capture> matching = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .filter(c -> c.hookMethod.equals(hookMethod)) // .filter(c -> Arrays.equals(expectedArgs, c.args)) // .collect(Collectors.toList()); // Assertions.assertEquals(expectedNumberOfCalls, matching.size()); // } // // // special case for the varargsMixed test // public static void assertNumCalls(int expectedNumberOfCalls, Class<?> hookClass, String hookMethod, String firstString, String... moreStrings) { // List<Capture> matching = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .filter(c -> c.hookMethod.equals(hookMethod)) // .filter(c -> c.args.length == 2) // .filter(c -> Objects.equals(firstString, c.args[0])) // .filter(c -> Arrays.equals(moreStrings, (String[]) c.args[1])) // .collect(Collectors.toList()); // Assertions.assertEquals(expectedNumberOfCalls, matching.size()); // } // // public static void assertNumHookInstances(int expectedNumberOfInstances, Class<?> hookClass) { // long actualNumberOfInstances = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .map(c -> c.hook) // .distinct() // .count(); // Assertions.assertEquals(expectedNumberOfInstances, (int) actualNumberOfInstances); // } // // private static class Capture { // final Object hook; // final String hookMethod; // final Object[] args; // // Capture(Object hook, String hookMethod, Object[] args) { // this.hook = hook; // this.hookMethod = hookMethod; // this.args = args; // } // } // // private static final List<Capture> captures = Collections.synchronizedList(new ArrayList<>()); // // private MethodCallCounter() {} // } // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/classes/Fruit.java // public class Fruit { // public static class Orange extends Fruit{} // }
import io.promagent.annotations.*; import io.promagent.hookcontext.MetricsStore; import io.promagent.internal.instrumentationtests.MethodCallCounter; import io.promagent.internal.instrumentationtests.classes.Fruit; import java.util.List;
package io.promagent.internal.instrumentationtests.hooks; @Hook(instruments = "io.promagent.internal.instrumentationtests.classes.ReturnedAndThrownExample") public class ReturnedAndThrownHook { public ReturnedAndThrownHook(MetricsStore m) {} @Before(method = "returnVoid")
// Path: promagent-framework/promagent-api/src/main/java/io/promagent/hookcontext/MetricsStore.java // public class MetricsStore { // // private final CollectorRegistry registry; // private final ConcurrentMap<String, Collector> metrics = new ConcurrentHashMap<>(); // // public MetricsStore(CollectorRegistry registry) { // this.registry = registry; // } // // /** // * See {@link MetricsStore} and {@link MetricDef#MetricDef(String, BiFunction)}. // */ // @SuppressWarnings("unchecked") // public <T extends Collector> T createOrGet(MetricDef<T> metricDef) { // return (T) metrics.computeIfAbsent(metricDef.getMetricName(), s -> metricDef.getProducer().apply(metricDef.getMetricName(), registry)); // } // } // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/MethodCallCounter.java // public class MethodCallCounter { // // public static void reset() { // captures.clear(); // } // // public static void observe(Object hook, String methodName, Object... args) { // captures.add(new Capture(hook, methodName, args)); // } // // public static void assertNumCalls(int expectedNumberOfCalls, Class<?> hookClass, String hookMethod, Object... expectedArgs) { // List<Capture> matching = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .filter(c -> c.hookMethod.equals(hookMethod)) // .filter(c -> Arrays.equals(expectedArgs, c.args)) // .collect(Collectors.toList()); // Assertions.assertEquals(expectedNumberOfCalls, matching.size()); // } // // // special case for the varargsMixed test // public static void assertNumCalls(int expectedNumberOfCalls, Class<?> hookClass, String hookMethod, String firstString, String... moreStrings) { // List<Capture> matching = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .filter(c -> c.hookMethod.equals(hookMethod)) // .filter(c -> c.args.length == 2) // .filter(c -> Objects.equals(firstString, c.args[0])) // .filter(c -> Arrays.equals(moreStrings, (String[]) c.args[1])) // .collect(Collectors.toList()); // Assertions.assertEquals(expectedNumberOfCalls, matching.size()); // } // // public static void assertNumHookInstances(int expectedNumberOfInstances, Class<?> hookClass) { // long actualNumberOfInstances = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .map(c -> c.hook) // .distinct() // .count(); // Assertions.assertEquals(expectedNumberOfInstances, (int) actualNumberOfInstances); // } // // private static class Capture { // final Object hook; // final String hookMethod; // final Object[] args; // // Capture(Object hook, String hookMethod, Object[] args) { // this.hook = hook; // this.hookMethod = hookMethod; // this.args = args; // } // } // // private static final List<Capture> captures = Collections.synchronizedList(new ArrayList<>()); // // private MethodCallCounter() {} // } // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/classes/Fruit.java // public class Fruit { // public static class Orange extends Fruit{} // } // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/hooks/ReturnedAndThrownHook.java import io.promagent.annotations.*; import io.promagent.hookcontext.MetricsStore; import io.promagent.internal.instrumentationtests.MethodCallCounter; import io.promagent.internal.instrumentationtests.classes.Fruit; import java.util.List; package io.promagent.internal.instrumentationtests.hooks; @Hook(instruments = "io.promagent.internal.instrumentationtests.classes.ReturnedAndThrownExample") public class ReturnedAndThrownHook { public ReturnedAndThrownHook(MetricsStore m) {} @Before(method = "returnVoid")
public void beforeVoid(Fruit f) {
fstab/promagent
promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/hooks/ReturnedAndThrownHook.java
// Path: promagent-framework/promagent-api/src/main/java/io/promagent/hookcontext/MetricsStore.java // public class MetricsStore { // // private final CollectorRegistry registry; // private final ConcurrentMap<String, Collector> metrics = new ConcurrentHashMap<>(); // // public MetricsStore(CollectorRegistry registry) { // this.registry = registry; // } // // /** // * See {@link MetricsStore} and {@link MetricDef#MetricDef(String, BiFunction)}. // */ // @SuppressWarnings("unchecked") // public <T extends Collector> T createOrGet(MetricDef<T> metricDef) { // return (T) metrics.computeIfAbsent(metricDef.getMetricName(), s -> metricDef.getProducer().apply(metricDef.getMetricName(), registry)); // } // } // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/MethodCallCounter.java // public class MethodCallCounter { // // public static void reset() { // captures.clear(); // } // // public static void observe(Object hook, String methodName, Object... args) { // captures.add(new Capture(hook, methodName, args)); // } // // public static void assertNumCalls(int expectedNumberOfCalls, Class<?> hookClass, String hookMethod, Object... expectedArgs) { // List<Capture> matching = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .filter(c -> c.hookMethod.equals(hookMethod)) // .filter(c -> Arrays.equals(expectedArgs, c.args)) // .collect(Collectors.toList()); // Assertions.assertEquals(expectedNumberOfCalls, matching.size()); // } // // // special case for the varargsMixed test // public static void assertNumCalls(int expectedNumberOfCalls, Class<?> hookClass, String hookMethod, String firstString, String... moreStrings) { // List<Capture> matching = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .filter(c -> c.hookMethod.equals(hookMethod)) // .filter(c -> c.args.length == 2) // .filter(c -> Objects.equals(firstString, c.args[0])) // .filter(c -> Arrays.equals(moreStrings, (String[]) c.args[1])) // .collect(Collectors.toList()); // Assertions.assertEquals(expectedNumberOfCalls, matching.size()); // } // // public static void assertNumHookInstances(int expectedNumberOfInstances, Class<?> hookClass) { // long actualNumberOfInstances = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .map(c -> c.hook) // .distinct() // .count(); // Assertions.assertEquals(expectedNumberOfInstances, (int) actualNumberOfInstances); // } // // private static class Capture { // final Object hook; // final String hookMethod; // final Object[] args; // // Capture(Object hook, String hookMethod, Object[] args) { // this.hook = hook; // this.hookMethod = hookMethod; // this.args = args; // } // } // // private static final List<Capture> captures = Collections.synchronizedList(new ArrayList<>()); // // private MethodCallCounter() {} // } // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/classes/Fruit.java // public class Fruit { // public static class Orange extends Fruit{} // }
import io.promagent.annotations.*; import io.promagent.hookcontext.MetricsStore; import io.promagent.internal.instrumentationtests.MethodCallCounter; import io.promagent.internal.instrumentationtests.classes.Fruit; import java.util.List;
package io.promagent.internal.instrumentationtests.hooks; @Hook(instruments = "io.promagent.internal.instrumentationtests.classes.ReturnedAndThrownExample") public class ReturnedAndThrownHook { public ReturnedAndThrownHook(MetricsStore m) {} @Before(method = "returnVoid") public void beforeVoid(Fruit f) {
// Path: promagent-framework/promagent-api/src/main/java/io/promagent/hookcontext/MetricsStore.java // public class MetricsStore { // // private final CollectorRegistry registry; // private final ConcurrentMap<String, Collector> metrics = new ConcurrentHashMap<>(); // // public MetricsStore(CollectorRegistry registry) { // this.registry = registry; // } // // /** // * See {@link MetricsStore} and {@link MetricDef#MetricDef(String, BiFunction)}. // */ // @SuppressWarnings("unchecked") // public <T extends Collector> T createOrGet(MetricDef<T> metricDef) { // return (T) metrics.computeIfAbsent(metricDef.getMetricName(), s -> metricDef.getProducer().apply(metricDef.getMetricName(), registry)); // } // } // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/MethodCallCounter.java // public class MethodCallCounter { // // public static void reset() { // captures.clear(); // } // // public static void observe(Object hook, String methodName, Object... args) { // captures.add(new Capture(hook, methodName, args)); // } // // public static void assertNumCalls(int expectedNumberOfCalls, Class<?> hookClass, String hookMethod, Object... expectedArgs) { // List<Capture> matching = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .filter(c -> c.hookMethod.equals(hookMethod)) // .filter(c -> Arrays.equals(expectedArgs, c.args)) // .collect(Collectors.toList()); // Assertions.assertEquals(expectedNumberOfCalls, matching.size()); // } // // // special case for the varargsMixed test // public static void assertNumCalls(int expectedNumberOfCalls, Class<?> hookClass, String hookMethod, String firstString, String... moreStrings) { // List<Capture> matching = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .filter(c -> c.hookMethod.equals(hookMethod)) // .filter(c -> c.args.length == 2) // .filter(c -> Objects.equals(firstString, c.args[0])) // .filter(c -> Arrays.equals(moreStrings, (String[]) c.args[1])) // .collect(Collectors.toList()); // Assertions.assertEquals(expectedNumberOfCalls, matching.size()); // } // // public static void assertNumHookInstances(int expectedNumberOfInstances, Class<?> hookClass) { // long actualNumberOfInstances = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .map(c -> c.hook) // .distinct() // .count(); // Assertions.assertEquals(expectedNumberOfInstances, (int) actualNumberOfInstances); // } // // private static class Capture { // final Object hook; // final String hookMethod; // final Object[] args; // // Capture(Object hook, String hookMethod, Object[] args) { // this.hook = hook; // this.hookMethod = hookMethod; // this.args = args; // } // } // // private static final List<Capture> captures = Collections.synchronizedList(new ArrayList<>()); // // private MethodCallCounter() {} // } // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/classes/Fruit.java // public class Fruit { // public static class Orange extends Fruit{} // } // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/hooks/ReturnedAndThrownHook.java import io.promagent.annotations.*; import io.promagent.hookcontext.MetricsStore; import io.promagent.internal.instrumentationtests.MethodCallCounter; import io.promagent.internal.instrumentationtests.classes.Fruit; import java.util.List; package io.promagent.internal.instrumentationtests.hooks; @Hook(instruments = "io.promagent.internal.instrumentationtests.classes.ReturnedAndThrownExample") public class ReturnedAndThrownHook { public ReturnedAndThrownHook(MetricsStore m) {} @Before(method = "returnVoid") public void beforeVoid(Fruit f) {
MethodCallCounter.observe(this, "beforeVoid", f);
fstab/promagent
promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/hooks/OnlyBeforeHook.java
// Path: promagent-framework/promagent-api/src/main/java/io/promagent/hookcontext/MetricsStore.java // public class MetricsStore { // // private final CollectorRegistry registry; // private final ConcurrentMap<String, Collector> metrics = new ConcurrentHashMap<>(); // // public MetricsStore(CollectorRegistry registry) { // this.registry = registry; // } // // /** // * See {@link MetricsStore} and {@link MetricDef#MetricDef(String, BiFunction)}. // */ // @SuppressWarnings("unchecked") // public <T extends Collector> T createOrGet(MetricDef<T> metricDef) { // return (T) metrics.computeIfAbsent(metricDef.getMetricName(), s -> metricDef.getProducer().apply(metricDef.getMetricName(), registry)); // } // } // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/MethodCallCounter.java // public class MethodCallCounter { // // public static void reset() { // captures.clear(); // } // // public static void observe(Object hook, String methodName, Object... args) { // captures.add(new Capture(hook, methodName, args)); // } // // public static void assertNumCalls(int expectedNumberOfCalls, Class<?> hookClass, String hookMethod, Object... expectedArgs) { // List<Capture> matching = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .filter(c -> c.hookMethod.equals(hookMethod)) // .filter(c -> Arrays.equals(expectedArgs, c.args)) // .collect(Collectors.toList()); // Assertions.assertEquals(expectedNumberOfCalls, matching.size()); // } // // // special case for the varargsMixed test // public static void assertNumCalls(int expectedNumberOfCalls, Class<?> hookClass, String hookMethod, String firstString, String... moreStrings) { // List<Capture> matching = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .filter(c -> c.hookMethod.equals(hookMethod)) // .filter(c -> c.args.length == 2) // .filter(c -> Objects.equals(firstString, c.args[0])) // .filter(c -> Arrays.equals(moreStrings, (String[]) c.args[1])) // .collect(Collectors.toList()); // Assertions.assertEquals(expectedNumberOfCalls, matching.size()); // } // // public static void assertNumHookInstances(int expectedNumberOfInstances, Class<?> hookClass) { // long actualNumberOfInstances = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .map(c -> c.hook) // .distinct() // .count(); // Assertions.assertEquals(expectedNumberOfInstances, (int) actualNumberOfInstances); // } // // private static class Capture { // final Object hook; // final String hookMethod; // final Object[] args; // // Capture(Object hook, String hookMethod, Object[] args) { // this.hook = hook; // this.hookMethod = hookMethod; // this.args = args; // } // } // // private static final List<Capture> captures = Collections.synchronizedList(new ArrayList<>()); // // private MethodCallCounter() {} // } // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/classes/Fruit.java // public class Fruit { // public static class Orange extends Fruit{} // }
import io.promagent.annotations.Before; import io.promagent.annotations.Hook; import io.promagent.hookcontext.MetricsStore; import io.promagent.internal.instrumentationtests.MethodCallCounter; import io.promagent.internal.instrumentationtests.classes.Fruit;
package io.promagent.internal.instrumentationtests.hooks; /** * Test hook with no @After method */ @Hook(instruments = "io.promagent.internal.instrumentationtests.classes.ParameterTypesExample") public class OnlyBeforeHook {
// Path: promagent-framework/promagent-api/src/main/java/io/promagent/hookcontext/MetricsStore.java // public class MetricsStore { // // private final CollectorRegistry registry; // private final ConcurrentMap<String, Collector> metrics = new ConcurrentHashMap<>(); // // public MetricsStore(CollectorRegistry registry) { // this.registry = registry; // } // // /** // * See {@link MetricsStore} and {@link MetricDef#MetricDef(String, BiFunction)}. // */ // @SuppressWarnings("unchecked") // public <T extends Collector> T createOrGet(MetricDef<T> metricDef) { // return (T) metrics.computeIfAbsent(metricDef.getMetricName(), s -> metricDef.getProducer().apply(metricDef.getMetricName(), registry)); // } // } // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/MethodCallCounter.java // public class MethodCallCounter { // // public static void reset() { // captures.clear(); // } // // public static void observe(Object hook, String methodName, Object... args) { // captures.add(new Capture(hook, methodName, args)); // } // // public static void assertNumCalls(int expectedNumberOfCalls, Class<?> hookClass, String hookMethod, Object... expectedArgs) { // List<Capture> matching = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .filter(c -> c.hookMethod.equals(hookMethod)) // .filter(c -> Arrays.equals(expectedArgs, c.args)) // .collect(Collectors.toList()); // Assertions.assertEquals(expectedNumberOfCalls, matching.size()); // } // // // special case for the varargsMixed test // public static void assertNumCalls(int expectedNumberOfCalls, Class<?> hookClass, String hookMethod, String firstString, String... moreStrings) { // List<Capture> matching = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .filter(c -> c.hookMethod.equals(hookMethod)) // .filter(c -> c.args.length == 2) // .filter(c -> Objects.equals(firstString, c.args[0])) // .filter(c -> Arrays.equals(moreStrings, (String[]) c.args[1])) // .collect(Collectors.toList()); // Assertions.assertEquals(expectedNumberOfCalls, matching.size()); // } // // public static void assertNumHookInstances(int expectedNumberOfInstances, Class<?> hookClass) { // long actualNumberOfInstances = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .map(c -> c.hook) // .distinct() // .count(); // Assertions.assertEquals(expectedNumberOfInstances, (int) actualNumberOfInstances); // } // // private static class Capture { // final Object hook; // final String hookMethod; // final Object[] args; // // Capture(Object hook, String hookMethod, Object[] args) { // this.hook = hook; // this.hookMethod = hookMethod; // this.args = args; // } // } // // private static final List<Capture> captures = Collections.synchronizedList(new ArrayList<>()); // // private MethodCallCounter() {} // } // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/classes/Fruit.java // public class Fruit { // public static class Orange extends Fruit{} // } // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/hooks/OnlyBeforeHook.java import io.promagent.annotations.Before; import io.promagent.annotations.Hook; import io.promagent.hookcontext.MetricsStore; import io.promagent.internal.instrumentationtests.MethodCallCounter; import io.promagent.internal.instrumentationtests.classes.Fruit; package io.promagent.internal.instrumentationtests.hooks; /** * Test hook with no @After method */ @Hook(instruments = "io.promagent.internal.instrumentationtests.classes.ParameterTypesExample") public class OnlyBeforeHook {
public OnlyBeforeHook(MetricsStore m) {}
fstab/promagent
promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/hooks/OnlyBeforeHook.java
// Path: promagent-framework/promagent-api/src/main/java/io/promagent/hookcontext/MetricsStore.java // public class MetricsStore { // // private final CollectorRegistry registry; // private final ConcurrentMap<String, Collector> metrics = new ConcurrentHashMap<>(); // // public MetricsStore(CollectorRegistry registry) { // this.registry = registry; // } // // /** // * See {@link MetricsStore} and {@link MetricDef#MetricDef(String, BiFunction)}. // */ // @SuppressWarnings("unchecked") // public <T extends Collector> T createOrGet(MetricDef<T> metricDef) { // return (T) metrics.computeIfAbsent(metricDef.getMetricName(), s -> metricDef.getProducer().apply(metricDef.getMetricName(), registry)); // } // } // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/MethodCallCounter.java // public class MethodCallCounter { // // public static void reset() { // captures.clear(); // } // // public static void observe(Object hook, String methodName, Object... args) { // captures.add(new Capture(hook, methodName, args)); // } // // public static void assertNumCalls(int expectedNumberOfCalls, Class<?> hookClass, String hookMethod, Object... expectedArgs) { // List<Capture> matching = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .filter(c -> c.hookMethod.equals(hookMethod)) // .filter(c -> Arrays.equals(expectedArgs, c.args)) // .collect(Collectors.toList()); // Assertions.assertEquals(expectedNumberOfCalls, matching.size()); // } // // // special case for the varargsMixed test // public static void assertNumCalls(int expectedNumberOfCalls, Class<?> hookClass, String hookMethod, String firstString, String... moreStrings) { // List<Capture> matching = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .filter(c -> c.hookMethod.equals(hookMethod)) // .filter(c -> c.args.length == 2) // .filter(c -> Objects.equals(firstString, c.args[0])) // .filter(c -> Arrays.equals(moreStrings, (String[]) c.args[1])) // .collect(Collectors.toList()); // Assertions.assertEquals(expectedNumberOfCalls, matching.size()); // } // // public static void assertNumHookInstances(int expectedNumberOfInstances, Class<?> hookClass) { // long actualNumberOfInstances = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .map(c -> c.hook) // .distinct() // .count(); // Assertions.assertEquals(expectedNumberOfInstances, (int) actualNumberOfInstances); // } // // private static class Capture { // final Object hook; // final String hookMethod; // final Object[] args; // // Capture(Object hook, String hookMethod, Object[] args) { // this.hook = hook; // this.hookMethod = hookMethod; // this.args = args; // } // } // // private static final List<Capture> captures = Collections.synchronizedList(new ArrayList<>()); // // private MethodCallCounter() {} // } // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/classes/Fruit.java // public class Fruit { // public static class Orange extends Fruit{} // }
import io.promagent.annotations.Before; import io.promagent.annotations.Hook; import io.promagent.hookcontext.MetricsStore; import io.promagent.internal.instrumentationtests.MethodCallCounter; import io.promagent.internal.instrumentationtests.classes.Fruit;
package io.promagent.internal.instrumentationtests.hooks; /** * Test hook with no @After method */ @Hook(instruments = "io.promagent.internal.instrumentationtests.classes.ParameterTypesExample") public class OnlyBeforeHook { public OnlyBeforeHook(MetricsStore m) {} @Before(method = "objects")
// Path: promagent-framework/promagent-api/src/main/java/io/promagent/hookcontext/MetricsStore.java // public class MetricsStore { // // private final CollectorRegistry registry; // private final ConcurrentMap<String, Collector> metrics = new ConcurrentHashMap<>(); // // public MetricsStore(CollectorRegistry registry) { // this.registry = registry; // } // // /** // * See {@link MetricsStore} and {@link MetricDef#MetricDef(String, BiFunction)}. // */ // @SuppressWarnings("unchecked") // public <T extends Collector> T createOrGet(MetricDef<T> metricDef) { // return (T) metrics.computeIfAbsent(metricDef.getMetricName(), s -> metricDef.getProducer().apply(metricDef.getMetricName(), registry)); // } // } // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/MethodCallCounter.java // public class MethodCallCounter { // // public static void reset() { // captures.clear(); // } // // public static void observe(Object hook, String methodName, Object... args) { // captures.add(new Capture(hook, methodName, args)); // } // // public static void assertNumCalls(int expectedNumberOfCalls, Class<?> hookClass, String hookMethod, Object... expectedArgs) { // List<Capture> matching = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .filter(c -> c.hookMethod.equals(hookMethod)) // .filter(c -> Arrays.equals(expectedArgs, c.args)) // .collect(Collectors.toList()); // Assertions.assertEquals(expectedNumberOfCalls, matching.size()); // } // // // special case for the varargsMixed test // public static void assertNumCalls(int expectedNumberOfCalls, Class<?> hookClass, String hookMethod, String firstString, String... moreStrings) { // List<Capture> matching = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .filter(c -> c.hookMethod.equals(hookMethod)) // .filter(c -> c.args.length == 2) // .filter(c -> Objects.equals(firstString, c.args[0])) // .filter(c -> Arrays.equals(moreStrings, (String[]) c.args[1])) // .collect(Collectors.toList()); // Assertions.assertEquals(expectedNumberOfCalls, matching.size()); // } // // public static void assertNumHookInstances(int expectedNumberOfInstances, Class<?> hookClass) { // long actualNumberOfInstances = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .map(c -> c.hook) // .distinct() // .count(); // Assertions.assertEquals(expectedNumberOfInstances, (int) actualNumberOfInstances); // } // // private static class Capture { // final Object hook; // final String hookMethod; // final Object[] args; // // Capture(Object hook, String hookMethod, Object[] args) { // this.hook = hook; // this.hookMethod = hookMethod; // this.args = args; // } // } // // private static final List<Capture> captures = Collections.synchronizedList(new ArrayList<>()); // // private MethodCallCounter() {} // } // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/classes/Fruit.java // public class Fruit { // public static class Orange extends Fruit{} // } // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/hooks/OnlyBeforeHook.java import io.promagent.annotations.Before; import io.promagent.annotations.Hook; import io.promagent.hookcontext.MetricsStore; import io.promagent.internal.instrumentationtests.MethodCallCounter; import io.promagent.internal.instrumentationtests.classes.Fruit; package io.promagent.internal.instrumentationtests.hooks; /** * Test hook with no @After method */ @Hook(instruments = "io.promagent.internal.instrumentationtests.classes.ParameterTypesExample") public class OnlyBeforeHook { public OnlyBeforeHook(MetricsStore m) {} @Before(method = "objects")
public void before(Object o, Fruit f, Fruit.Orange x) {
fstab/promagent
promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/hooks/OnlyBeforeHook.java
// Path: promagent-framework/promagent-api/src/main/java/io/promagent/hookcontext/MetricsStore.java // public class MetricsStore { // // private final CollectorRegistry registry; // private final ConcurrentMap<String, Collector> metrics = new ConcurrentHashMap<>(); // // public MetricsStore(CollectorRegistry registry) { // this.registry = registry; // } // // /** // * See {@link MetricsStore} and {@link MetricDef#MetricDef(String, BiFunction)}. // */ // @SuppressWarnings("unchecked") // public <T extends Collector> T createOrGet(MetricDef<T> metricDef) { // return (T) metrics.computeIfAbsent(metricDef.getMetricName(), s -> metricDef.getProducer().apply(metricDef.getMetricName(), registry)); // } // } // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/MethodCallCounter.java // public class MethodCallCounter { // // public static void reset() { // captures.clear(); // } // // public static void observe(Object hook, String methodName, Object... args) { // captures.add(new Capture(hook, methodName, args)); // } // // public static void assertNumCalls(int expectedNumberOfCalls, Class<?> hookClass, String hookMethod, Object... expectedArgs) { // List<Capture> matching = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .filter(c -> c.hookMethod.equals(hookMethod)) // .filter(c -> Arrays.equals(expectedArgs, c.args)) // .collect(Collectors.toList()); // Assertions.assertEquals(expectedNumberOfCalls, matching.size()); // } // // // special case for the varargsMixed test // public static void assertNumCalls(int expectedNumberOfCalls, Class<?> hookClass, String hookMethod, String firstString, String... moreStrings) { // List<Capture> matching = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .filter(c -> c.hookMethod.equals(hookMethod)) // .filter(c -> c.args.length == 2) // .filter(c -> Objects.equals(firstString, c.args[0])) // .filter(c -> Arrays.equals(moreStrings, (String[]) c.args[1])) // .collect(Collectors.toList()); // Assertions.assertEquals(expectedNumberOfCalls, matching.size()); // } // // public static void assertNumHookInstances(int expectedNumberOfInstances, Class<?> hookClass) { // long actualNumberOfInstances = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .map(c -> c.hook) // .distinct() // .count(); // Assertions.assertEquals(expectedNumberOfInstances, (int) actualNumberOfInstances); // } // // private static class Capture { // final Object hook; // final String hookMethod; // final Object[] args; // // Capture(Object hook, String hookMethod, Object[] args) { // this.hook = hook; // this.hookMethod = hookMethod; // this.args = args; // } // } // // private static final List<Capture> captures = Collections.synchronizedList(new ArrayList<>()); // // private MethodCallCounter() {} // } // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/classes/Fruit.java // public class Fruit { // public static class Orange extends Fruit{} // }
import io.promagent.annotations.Before; import io.promagent.annotations.Hook; import io.promagent.hookcontext.MetricsStore; import io.promagent.internal.instrumentationtests.MethodCallCounter; import io.promagent.internal.instrumentationtests.classes.Fruit;
package io.promagent.internal.instrumentationtests.hooks; /** * Test hook with no @After method */ @Hook(instruments = "io.promagent.internal.instrumentationtests.classes.ParameterTypesExample") public class OnlyBeforeHook { public OnlyBeforeHook(MetricsStore m) {} @Before(method = "objects") public void before(Object o, Fruit f, Fruit.Orange x) {
// Path: promagent-framework/promagent-api/src/main/java/io/promagent/hookcontext/MetricsStore.java // public class MetricsStore { // // private final CollectorRegistry registry; // private final ConcurrentMap<String, Collector> metrics = new ConcurrentHashMap<>(); // // public MetricsStore(CollectorRegistry registry) { // this.registry = registry; // } // // /** // * See {@link MetricsStore} and {@link MetricDef#MetricDef(String, BiFunction)}. // */ // @SuppressWarnings("unchecked") // public <T extends Collector> T createOrGet(MetricDef<T> metricDef) { // return (T) metrics.computeIfAbsent(metricDef.getMetricName(), s -> metricDef.getProducer().apply(metricDef.getMetricName(), registry)); // } // } // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/MethodCallCounter.java // public class MethodCallCounter { // // public static void reset() { // captures.clear(); // } // // public static void observe(Object hook, String methodName, Object... args) { // captures.add(new Capture(hook, methodName, args)); // } // // public static void assertNumCalls(int expectedNumberOfCalls, Class<?> hookClass, String hookMethod, Object... expectedArgs) { // List<Capture> matching = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .filter(c -> c.hookMethod.equals(hookMethod)) // .filter(c -> Arrays.equals(expectedArgs, c.args)) // .collect(Collectors.toList()); // Assertions.assertEquals(expectedNumberOfCalls, matching.size()); // } // // // special case for the varargsMixed test // public static void assertNumCalls(int expectedNumberOfCalls, Class<?> hookClass, String hookMethod, String firstString, String... moreStrings) { // List<Capture> matching = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .filter(c -> c.hookMethod.equals(hookMethod)) // .filter(c -> c.args.length == 2) // .filter(c -> Objects.equals(firstString, c.args[0])) // .filter(c -> Arrays.equals(moreStrings, (String[]) c.args[1])) // .collect(Collectors.toList()); // Assertions.assertEquals(expectedNumberOfCalls, matching.size()); // } // // public static void assertNumHookInstances(int expectedNumberOfInstances, Class<?> hookClass) { // long actualNumberOfInstances = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .map(c -> c.hook) // .distinct() // .count(); // Assertions.assertEquals(expectedNumberOfInstances, (int) actualNumberOfInstances); // } // // private static class Capture { // final Object hook; // final String hookMethod; // final Object[] args; // // Capture(Object hook, String hookMethod, Object[] args) { // this.hook = hook; // this.hookMethod = hookMethod; // this.args = args; // } // } // // private static final List<Capture> captures = Collections.synchronizedList(new ArrayList<>()); // // private MethodCallCounter() {} // } // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/classes/Fruit.java // public class Fruit { // public static class Orange extends Fruit{} // } // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/hooks/OnlyBeforeHook.java import io.promagent.annotations.Before; import io.promagent.annotations.Hook; import io.promagent.hookcontext.MetricsStore; import io.promagent.internal.instrumentationtests.MethodCallCounter; import io.promagent.internal.instrumentationtests.classes.Fruit; package io.promagent.internal.instrumentationtests.hooks; /** * Test hook with no @After method */ @Hook(instruments = "io.promagent.internal.instrumentationtests.classes.ParameterTypesExample") public class OnlyBeforeHook { public OnlyBeforeHook(MetricsStore m) {} @Before(method = "objects") public void before(Object o, Fruit f, Fruit.Orange x) {
MethodCallCounter.observe(this, "before", o, f, x);
fstab/promagent
promagent-framework/promagent-internal/src/main/java/io/promagent/internal/Delegator.java
// Path: promagent-framework/promagent-agent/src/main/java/io/promagent/agent/ClassLoaderCache.java // public class ClassLoaderCache { // // private static ClassLoaderCache instance; // // // TODO: The cache does not free class loaders when applications are undeployed. Maybe use WeakHashMap? // private final Map<ClassLoader, PerDeploymentClassLoader> cache = new HashMap<>(); // private final URLClassLoader sharedClassLoader; // shared across multiple deployments // private final List<Path> perDeploymentJars; // one class loader for each deployment for these JARs // // private ClassLoaderCache(JarFiles jarFiles) { // sharedClassLoader = new URLClassLoader(pathsToURLs(jarFiles.getSharedJars())); // perDeploymentJars = jarFiles.getPerDeploymentJars(); // } // // public static synchronized ClassLoaderCache getInstance() { // if (instance == null) { // instance = new ClassLoaderCache(JarFiles.extract()); // } // return instance; // } // // public List<Path> getPerDeploymentJars() { // return perDeploymentJars; // } // // public synchronized ClassLoader currentClassLoader() { // ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); // if (! cache.containsKey(contextClassLoader)) { // cache.put(contextClassLoader, new PerDeploymentClassLoader(pathsToURLs(perDeploymentJars), sharedClassLoader, contextClassLoader)); // } // return cache.get(contextClassLoader); // } // // private static URL[] pathsToURLs(List<Path> paths) { // try { // URL[] result = new URL[paths.size()]; // for (int i=0; i<paths.size(); i++) { // result[i] = paths.get(i).toUri().toURL(); // } // return result; // } catch (MalformedURLException e) { // throw new RuntimeException(e); // } // } // } // // Path: promagent-framework/promagent-api/src/main/java/io/promagent/hookcontext/MetricsStore.java // public class MetricsStore { // // private final CollectorRegistry registry; // private final ConcurrentMap<String, Collector> metrics = new ConcurrentHashMap<>(); // // public MetricsStore(CollectorRegistry registry) { // this.registry = registry; // } // // /** // * See {@link MetricsStore} and {@link MetricDef#MetricDef(String, BiFunction)}. // */ // @SuppressWarnings("unchecked") // public <T extends Collector> T createOrGet(MetricDef<T> metricDef) { // return (T) metrics.computeIfAbsent(metricDef.getMetricName(), s -> metricDef.getProducer().apply(metricDef.getMetricName(), registry)); // } // }
import io.promagent.agent.ClassLoaderCache; import io.promagent.annotations.After; import io.promagent.annotations.Before; import io.promagent.annotations.Returned; import io.promagent.annotations.Thrown; import io.promagent.hookcontext.MetricsStore; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream;
// Copyright 2017 The Promagent Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package io.promagent.internal; /** * Delegator is called from the Byte Buddy Advice, and calls the Hook's @Before and @After methods. * <p> * TODO: This is called often, should be performance optimized, e.g. caching hook method handles, etc. */ public class Delegator { private static Delegator instance; // not thread-safe, but it is set only once in the agent's premain method. private final SortedSet<HookMetadata> hookMetadata;
// Path: promagent-framework/promagent-agent/src/main/java/io/promagent/agent/ClassLoaderCache.java // public class ClassLoaderCache { // // private static ClassLoaderCache instance; // // // TODO: The cache does not free class loaders when applications are undeployed. Maybe use WeakHashMap? // private final Map<ClassLoader, PerDeploymentClassLoader> cache = new HashMap<>(); // private final URLClassLoader sharedClassLoader; // shared across multiple deployments // private final List<Path> perDeploymentJars; // one class loader for each deployment for these JARs // // private ClassLoaderCache(JarFiles jarFiles) { // sharedClassLoader = new URLClassLoader(pathsToURLs(jarFiles.getSharedJars())); // perDeploymentJars = jarFiles.getPerDeploymentJars(); // } // // public static synchronized ClassLoaderCache getInstance() { // if (instance == null) { // instance = new ClassLoaderCache(JarFiles.extract()); // } // return instance; // } // // public List<Path> getPerDeploymentJars() { // return perDeploymentJars; // } // // public synchronized ClassLoader currentClassLoader() { // ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); // if (! cache.containsKey(contextClassLoader)) { // cache.put(contextClassLoader, new PerDeploymentClassLoader(pathsToURLs(perDeploymentJars), sharedClassLoader, contextClassLoader)); // } // return cache.get(contextClassLoader); // } // // private static URL[] pathsToURLs(List<Path> paths) { // try { // URL[] result = new URL[paths.size()]; // for (int i=0; i<paths.size(); i++) { // result[i] = paths.get(i).toUri().toURL(); // } // return result; // } catch (MalformedURLException e) { // throw new RuntimeException(e); // } // } // } // // Path: promagent-framework/promagent-api/src/main/java/io/promagent/hookcontext/MetricsStore.java // public class MetricsStore { // // private final CollectorRegistry registry; // private final ConcurrentMap<String, Collector> metrics = new ConcurrentHashMap<>(); // // public MetricsStore(CollectorRegistry registry) { // this.registry = registry; // } // // /** // * See {@link MetricsStore} and {@link MetricDef#MetricDef(String, BiFunction)}. // */ // @SuppressWarnings("unchecked") // public <T extends Collector> T createOrGet(MetricDef<T> metricDef) { // return (T) metrics.computeIfAbsent(metricDef.getMetricName(), s -> metricDef.getProducer().apply(metricDef.getMetricName(), registry)); // } // } // Path: promagent-framework/promagent-internal/src/main/java/io/promagent/internal/Delegator.java import io.promagent.agent.ClassLoaderCache; import io.promagent.annotations.After; import io.promagent.annotations.Before; import io.promagent.annotations.Returned; import io.promagent.annotations.Thrown; import io.promagent.hookcontext.MetricsStore; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; // Copyright 2017 The Promagent Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package io.promagent.internal; /** * Delegator is called from the Byte Buddy Advice, and calls the Hook's @Before and @After methods. * <p> * TODO: This is called often, should be performance optimized, e.g. caching hook method handles, etc. */ public class Delegator { private static Delegator instance; // not thread-safe, but it is set only once in the agent's premain method. private final SortedSet<HookMetadata> hookMetadata;
private final MetricsStore metricsStore;
fstab/promagent
promagent-framework/promagent-internal/src/main/java/io/promagent/internal/Delegator.java
// Path: promagent-framework/promagent-agent/src/main/java/io/promagent/agent/ClassLoaderCache.java // public class ClassLoaderCache { // // private static ClassLoaderCache instance; // // // TODO: The cache does not free class loaders when applications are undeployed. Maybe use WeakHashMap? // private final Map<ClassLoader, PerDeploymentClassLoader> cache = new HashMap<>(); // private final URLClassLoader sharedClassLoader; // shared across multiple deployments // private final List<Path> perDeploymentJars; // one class loader for each deployment for these JARs // // private ClassLoaderCache(JarFiles jarFiles) { // sharedClassLoader = new URLClassLoader(pathsToURLs(jarFiles.getSharedJars())); // perDeploymentJars = jarFiles.getPerDeploymentJars(); // } // // public static synchronized ClassLoaderCache getInstance() { // if (instance == null) { // instance = new ClassLoaderCache(JarFiles.extract()); // } // return instance; // } // // public List<Path> getPerDeploymentJars() { // return perDeploymentJars; // } // // public synchronized ClassLoader currentClassLoader() { // ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); // if (! cache.containsKey(contextClassLoader)) { // cache.put(contextClassLoader, new PerDeploymentClassLoader(pathsToURLs(perDeploymentJars), sharedClassLoader, contextClassLoader)); // } // return cache.get(contextClassLoader); // } // // private static URL[] pathsToURLs(List<Path> paths) { // try { // URL[] result = new URL[paths.size()]; // for (int i=0; i<paths.size(); i++) { // result[i] = paths.get(i).toUri().toURL(); // } // return result; // } catch (MalformedURLException e) { // throw new RuntimeException(e); // } // } // } // // Path: promagent-framework/promagent-api/src/main/java/io/promagent/hookcontext/MetricsStore.java // public class MetricsStore { // // private final CollectorRegistry registry; // private final ConcurrentMap<String, Collector> metrics = new ConcurrentHashMap<>(); // // public MetricsStore(CollectorRegistry registry) { // this.registry = registry; // } // // /** // * See {@link MetricsStore} and {@link MetricDef#MetricDef(String, BiFunction)}. // */ // @SuppressWarnings("unchecked") // public <T extends Collector> T createOrGet(MetricDef<T> metricDef) { // return (T) metrics.computeIfAbsent(metricDef.getMetricName(), s -> metricDef.getProducer().apply(metricDef.getMetricName(), registry)); // } // }
import io.promagent.agent.ClassLoaderCache; import io.promagent.annotations.After; import io.promagent.annotations.Before; import io.promagent.annotations.Returned; import io.promagent.annotations.Thrown; import io.promagent.hookcontext.MetricsStore; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream;
// Copyright 2017 The Promagent Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package io.promagent.internal; /** * Delegator is called from the Byte Buddy Advice, and calls the Hook's @Before and @After methods. * <p> * TODO: This is called often, should be performance optimized, e.g. caching hook method handles, etc. */ public class Delegator { private static Delegator instance; // not thread-safe, but it is set only once in the agent's premain method. private final SortedSet<HookMetadata> hookMetadata; private final MetricsStore metricsStore;
// Path: promagent-framework/promagent-agent/src/main/java/io/promagent/agent/ClassLoaderCache.java // public class ClassLoaderCache { // // private static ClassLoaderCache instance; // // // TODO: The cache does not free class loaders when applications are undeployed. Maybe use WeakHashMap? // private final Map<ClassLoader, PerDeploymentClassLoader> cache = new HashMap<>(); // private final URLClassLoader sharedClassLoader; // shared across multiple deployments // private final List<Path> perDeploymentJars; // one class loader for each deployment for these JARs // // private ClassLoaderCache(JarFiles jarFiles) { // sharedClassLoader = new URLClassLoader(pathsToURLs(jarFiles.getSharedJars())); // perDeploymentJars = jarFiles.getPerDeploymentJars(); // } // // public static synchronized ClassLoaderCache getInstance() { // if (instance == null) { // instance = new ClassLoaderCache(JarFiles.extract()); // } // return instance; // } // // public List<Path> getPerDeploymentJars() { // return perDeploymentJars; // } // // public synchronized ClassLoader currentClassLoader() { // ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); // if (! cache.containsKey(contextClassLoader)) { // cache.put(contextClassLoader, new PerDeploymentClassLoader(pathsToURLs(perDeploymentJars), sharedClassLoader, contextClassLoader)); // } // return cache.get(contextClassLoader); // } // // private static URL[] pathsToURLs(List<Path> paths) { // try { // URL[] result = new URL[paths.size()]; // for (int i=0; i<paths.size(); i++) { // result[i] = paths.get(i).toUri().toURL(); // } // return result; // } catch (MalformedURLException e) { // throw new RuntimeException(e); // } // } // } // // Path: promagent-framework/promagent-api/src/main/java/io/promagent/hookcontext/MetricsStore.java // public class MetricsStore { // // private final CollectorRegistry registry; // private final ConcurrentMap<String, Collector> metrics = new ConcurrentHashMap<>(); // // public MetricsStore(CollectorRegistry registry) { // this.registry = registry; // } // // /** // * See {@link MetricsStore} and {@link MetricDef#MetricDef(String, BiFunction)}. // */ // @SuppressWarnings("unchecked") // public <T extends Collector> T createOrGet(MetricDef<T> metricDef) { // return (T) metrics.computeIfAbsent(metricDef.getMetricName(), s -> metricDef.getProducer().apply(metricDef.getMetricName(), registry)); // } // } // Path: promagent-framework/promagent-internal/src/main/java/io/promagent/internal/Delegator.java import io.promagent.agent.ClassLoaderCache; import io.promagent.annotations.After; import io.promagent.annotations.Before; import io.promagent.annotations.Returned; import io.promagent.annotations.Thrown; import io.promagent.hookcontext.MetricsStore; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; // Copyright 2017 The Promagent Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package io.promagent.internal; /** * Delegator is called from the Byte Buddy Advice, and calls the Hook's @Before and @After methods. * <p> * TODO: This is called often, should be performance optimized, e.g. caching hook method handles, etc. */ public class Delegator { private static Delegator instance; // not thread-safe, but it is set only once in the agent's premain method. private final SortedSet<HookMetadata> hookMetadata; private final MetricsStore metricsStore;
private final ClassLoaderCache classLoaderCache;
fstab/promagent
promagent-example/src/main/java/io/promagent/hooks/JdbcHook.java
// Path: promagent-framework/promagent-api/src/main/java/io/promagent/hookcontext/MetricDef.java // public class MetricDef<T extends Collector> { // // private final String metricName; // private final BiFunction<String, CollectorRegistry, T> producer; // // /** // * See {@link MetricsStore}. // * @param metricName Name of the Prometheus metric, like <tt>"http_requests_total"</tt>. // * @param producer Function to create a new metric and register it with the registry. // * This function will only be called once, subsequent calls to {@link MetricsStore#createOrGet(MetricDef)} // * will return the previously created metric with the specified name. // * The two parameters are the <i>metricName</i> as specified above, // * and the Prometheus registry where the new metric should be registered. // * For an example see JavaDoc for {@link MetricsStore}. // */ // public MetricDef(String metricName, BiFunction<String, CollectorRegistry, T> producer) { // this.metricName = metricName; // this.producer = producer; // } // // String getMetricName() { // return metricName; // } // // BiFunction<String, CollectorRegistry, T> getProducer() { // return producer; // } // } // // Path: promagent-framework/promagent-api/src/main/java/io/promagent/hookcontext/MetricsStore.java // public class MetricsStore { // // private final CollectorRegistry registry; // private final ConcurrentMap<String, Collector> metrics = new ConcurrentHashMap<>(); // // public MetricsStore(CollectorRegistry registry) { // this.registry = registry; // } // // /** // * See {@link MetricsStore} and {@link MetricDef#MetricDef(String, BiFunction)}. // */ // @SuppressWarnings("unchecked") // public <T extends Collector> T createOrGet(MetricDef<T> metricDef) { // return (T) metrics.computeIfAbsent(metricDef.getMetricName(), s -> metricDef.getProducer().apply(metricDef.getMetricName(), registry)); // } // } // // Path: promagent-example/src/main/java/io/promagent/hooks/HttpContext.java // static final Key<String> HTTP_METHOD = new Key<>(); // // Path: promagent-example/src/main/java/io/promagent/hooks/HttpContext.java // static final Key<String> HTTP_PATH = new Key<>();
import io.promagent.annotations.After; import io.promagent.annotations.Before; import io.promagent.annotations.Hook; import io.promagent.hookcontext.MetricDef; import io.promagent.hookcontext.MetricsStore; import io.prometheus.client.Counter; import io.prometheus.client.Summary; import java.util.concurrent.TimeUnit; import static io.promagent.hooks.HttpContext.HTTP_METHOD; import static io.promagent.hooks.HttpContext.HTTP_PATH;
// Copyright 2017 The Promagent Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package io.promagent.hooks; @Hook(instruments = { "java.sql.Statement", "java.sql.Connection" }) public class JdbcHook { private final Counter sqlQueriesTotal; private final Summary sqlQueriesDuration; private long startTime = 0;
// Path: promagent-framework/promagent-api/src/main/java/io/promagent/hookcontext/MetricDef.java // public class MetricDef<T extends Collector> { // // private final String metricName; // private final BiFunction<String, CollectorRegistry, T> producer; // // /** // * See {@link MetricsStore}. // * @param metricName Name of the Prometheus metric, like <tt>"http_requests_total"</tt>. // * @param producer Function to create a new metric and register it with the registry. // * This function will only be called once, subsequent calls to {@link MetricsStore#createOrGet(MetricDef)} // * will return the previously created metric with the specified name. // * The two parameters are the <i>metricName</i> as specified above, // * and the Prometheus registry where the new metric should be registered. // * For an example see JavaDoc for {@link MetricsStore}. // */ // public MetricDef(String metricName, BiFunction<String, CollectorRegistry, T> producer) { // this.metricName = metricName; // this.producer = producer; // } // // String getMetricName() { // return metricName; // } // // BiFunction<String, CollectorRegistry, T> getProducer() { // return producer; // } // } // // Path: promagent-framework/promagent-api/src/main/java/io/promagent/hookcontext/MetricsStore.java // public class MetricsStore { // // private final CollectorRegistry registry; // private final ConcurrentMap<String, Collector> metrics = new ConcurrentHashMap<>(); // // public MetricsStore(CollectorRegistry registry) { // this.registry = registry; // } // // /** // * See {@link MetricsStore} and {@link MetricDef#MetricDef(String, BiFunction)}. // */ // @SuppressWarnings("unchecked") // public <T extends Collector> T createOrGet(MetricDef<T> metricDef) { // return (T) metrics.computeIfAbsent(metricDef.getMetricName(), s -> metricDef.getProducer().apply(metricDef.getMetricName(), registry)); // } // } // // Path: promagent-example/src/main/java/io/promagent/hooks/HttpContext.java // static final Key<String> HTTP_METHOD = new Key<>(); // // Path: promagent-example/src/main/java/io/promagent/hooks/HttpContext.java // static final Key<String> HTTP_PATH = new Key<>(); // Path: promagent-example/src/main/java/io/promagent/hooks/JdbcHook.java import io.promagent.annotations.After; import io.promagent.annotations.Before; import io.promagent.annotations.Hook; import io.promagent.hookcontext.MetricDef; import io.promagent.hookcontext.MetricsStore; import io.prometheus.client.Counter; import io.prometheus.client.Summary; import java.util.concurrent.TimeUnit; import static io.promagent.hooks.HttpContext.HTTP_METHOD; import static io.promagent.hooks.HttpContext.HTTP_PATH; // Copyright 2017 The Promagent Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package io.promagent.hooks; @Hook(instruments = { "java.sql.Statement", "java.sql.Connection" }) public class JdbcHook { private final Counter sqlQueriesTotal; private final Summary sqlQueriesDuration; private long startTime = 0;
public JdbcHook(MetricsStore metricsStore) {
fstab/promagent
promagent-example/src/main/java/io/promagent/hooks/JdbcHook.java
// Path: promagent-framework/promagent-api/src/main/java/io/promagent/hookcontext/MetricDef.java // public class MetricDef<T extends Collector> { // // private final String metricName; // private final BiFunction<String, CollectorRegistry, T> producer; // // /** // * See {@link MetricsStore}. // * @param metricName Name of the Prometheus metric, like <tt>"http_requests_total"</tt>. // * @param producer Function to create a new metric and register it with the registry. // * This function will only be called once, subsequent calls to {@link MetricsStore#createOrGet(MetricDef)} // * will return the previously created metric with the specified name. // * The two parameters are the <i>metricName</i> as specified above, // * and the Prometheus registry where the new metric should be registered. // * For an example see JavaDoc for {@link MetricsStore}. // */ // public MetricDef(String metricName, BiFunction<String, CollectorRegistry, T> producer) { // this.metricName = metricName; // this.producer = producer; // } // // String getMetricName() { // return metricName; // } // // BiFunction<String, CollectorRegistry, T> getProducer() { // return producer; // } // } // // Path: promagent-framework/promagent-api/src/main/java/io/promagent/hookcontext/MetricsStore.java // public class MetricsStore { // // private final CollectorRegistry registry; // private final ConcurrentMap<String, Collector> metrics = new ConcurrentHashMap<>(); // // public MetricsStore(CollectorRegistry registry) { // this.registry = registry; // } // // /** // * See {@link MetricsStore} and {@link MetricDef#MetricDef(String, BiFunction)}. // */ // @SuppressWarnings("unchecked") // public <T extends Collector> T createOrGet(MetricDef<T> metricDef) { // return (T) metrics.computeIfAbsent(metricDef.getMetricName(), s -> metricDef.getProducer().apply(metricDef.getMetricName(), registry)); // } // } // // Path: promagent-example/src/main/java/io/promagent/hooks/HttpContext.java // static final Key<String> HTTP_METHOD = new Key<>(); // // Path: promagent-example/src/main/java/io/promagent/hooks/HttpContext.java // static final Key<String> HTTP_PATH = new Key<>();
import io.promagent.annotations.After; import io.promagent.annotations.Before; import io.promagent.annotations.Hook; import io.promagent.hookcontext.MetricDef; import io.promagent.hookcontext.MetricsStore; import io.prometheus.client.Counter; import io.prometheus.client.Summary; import java.util.concurrent.TimeUnit; import static io.promagent.hooks.HttpContext.HTTP_METHOD; import static io.promagent.hooks.HttpContext.HTTP_PATH;
// Copyright 2017 The Promagent Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package io.promagent.hooks; @Hook(instruments = { "java.sql.Statement", "java.sql.Connection" }) public class JdbcHook { private final Counter sqlQueriesTotal; private final Summary sqlQueriesDuration; private long startTime = 0; public JdbcHook(MetricsStore metricsStore) {
// Path: promagent-framework/promagent-api/src/main/java/io/promagent/hookcontext/MetricDef.java // public class MetricDef<T extends Collector> { // // private final String metricName; // private final BiFunction<String, CollectorRegistry, T> producer; // // /** // * See {@link MetricsStore}. // * @param metricName Name of the Prometheus metric, like <tt>"http_requests_total"</tt>. // * @param producer Function to create a new metric and register it with the registry. // * This function will only be called once, subsequent calls to {@link MetricsStore#createOrGet(MetricDef)} // * will return the previously created metric with the specified name. // * The two parameters are the <i>metricName</i> as specified above, // * and the Prometheus registry where the new metric should be registered. // * For an example see JavaDoc for {@link MetricsStore}. // */ // public MetricDef(String metricName, BiFunction<String, CollectorRegistry, T> producer) { // this.metricName = metricName; // this.producer = producer; // } // // String getMetricName() { // return metricName; // } // // BiFunction<String, CollectorRegistry, T> getProducer() { // return producer; // } // } // // Path: promagent-framework/promagent-api/src/main/java/io/promagent/hookcontext/MetricsStore.java // public class MetricsStore { // // private final CollectorRegistry registry; // private final ConcurrentMap<String, Collector> metrics = new ConcurrentHashMap<>(); // // public MetricsStore(CollectorRegistry registry) { // this.registry = registry; // } // // /** // * See {@link MetricsStore} and {@link MetricDef#MetricDef(String, BiFunction)}. // */ // @SuppressWarnings("unchecked") // public <T extends Collector> T createOrGet(MetricDef<T> metricDef) { // return (T) metrics.computeIfAbsent(metricDef.getMetricName(), s -> metricDef.getProducer().apply(metricDef.getMetricName(), registry)); // } // } // // Path: promagent-example/src/main/java/io/promagent/hooks/HttpContext.java // static final Key<String> HTTP_METHOD = new Key<>(); // // Path: promagent-example/src/main/java/io/promagent/hooks/HttpContext.java // static final Key<String> HTTP_PATH = new Key<>(); // Path: promagent-example/src/main/java/io/promagent/hooks/JdbcHook.java import io.promagent.annotations.After; import io.promagent.annotations.Before; import io.promagent.annotations.Hook; import io.promagent.hookcontext.MetricDef; import io.promagent.hookcontext.MetricsStore; import io.prometheus.client.Counter; import io.prometheus.client.Summary; import java.util.concurrent.TimeUnit; import static io.promagent.hooks.HttpContext.HTTP_METHOD; import static io.promagent.hooks.HttpContext.HTTP_PATH; // Copyright 2017 The Promagent Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package io.promagent.hooks; @Hook(instruments = { "java.sql.Statement", "java.sql.Connection" }) public class JdbcHook { private final Counter sqlQueriesTotal; private final Summary sqlQueriesDuration; private long startTime = 0; public JdbcHook(MetricsStore metricsStore) {
sqlQueriesTotal = metricsStore.createOrGet(new MetricDef<>(
fstab/promagent
promagent-example/src/main/java/io/promagent/hooks/JdbcHook.java
// Path: promagent-framework/promagent-api/src/main/java/io/promagent/hookcontext/MetricDef.java // public class MetricDef<T extends Collector> { // // private final String metricName; // private final BiFunction<String, CollectorRegistry, T> producer; // // /** // * See {@link MetricsStore}. // * @param metricName Name of the Prometheus metric, like <tt>"http_requests_total"</tt>. // * @param producer Function to create a new metric and register it with the registry. // * This function will only be called once, subsequent calls to {@link MetricsStore#createOrGet(MetricDef)} // * will return the previously created metric with the specified name. // * The two parameters are the <i>metricName</i> as specified above, // * and the Prometheus registry where the new metric should be registered. // * For an example see JavaDoc for {@link MetricsStore}. // */ // public MetricDef(String metricName, BiFunction<String, CollectorRegistry, T> producer) { // this.metricName = metricName; // this.producer = producer; // } // // String getMetricName() { // return metricName; // } // // BiFunction<String, CollectorRegistry, T> getProducer() { // return producer; // } // } // // Path: promagent-framework/promagent-api/src/main/java/io/promagent/hookcontext/MetricsStore.java // public class MetricsStore { // // private final CollectorRegistry registry; // private final ConcurrentMap<String, Collector> metrics = new ConcurrentHashMap<>(); // // public MetricsStore(CollectorRegistry registry) { // this.registry = registry; // } // // /** // * See {@link MetricsStore} and {@link MetricDef#MetricDef(String, BiFunction)}. // */ // @SuppressWarnings("unchecked") // public <T extends Collector> T createOrGet(MetricDef<T> metricDef) { // return (T) metrics.computeIfAbsent(metricDef.getMetricName(), s -> metricDef.getProducer().apply(metricDef.getMetricName(), registry)); // } // } // // Path: promagent-example/src/main/java/io/promagent/hooks/HttpContext.java // static final Key<String> HTTP_METHOD = new Key<>(); // // Path: promagent-example/src/main/java/io/promagent/hooks/HttpContext.java // static final Key<String> HTTP_PATH = new Key<>();
import io.promagent.annotations.After; import io.promagent.annotations.Before; import io.promagent.annotations.Hook; import io.promagent.hookcontext.MetricDef; import io.promagent.hookcontext.MetricsStore; import io.prometheus.client.Counter; import io.prometheus.client.Summary; import java.util.concurrent.TimeUnit; import static io.promagent.hooks.HttpContext.HTTP_METHOD; import static io.promagent.hooks.HttpContext.HTTP_PATH;
@Before(method = {"execute", "executeUpdate", "executeLargeUpdate", "prepareStatement"}) public void before(String sql, int autoGeneratedKeys) { before(sql); } @Before(method = {"execute", "executeUpdate", "executeLargeUpdate", "prepareStatement"}) public void before(String sql, int[] columnIndexes) { before(sql); } @Before(method = {"execute", "executeUpdate", "executeLargeUpdate", "prepareStatement"}) public void before(String sql, String[] columnNames) { before(sql); } @Before(method = {"prepareStatement", "prepareCall"}) public void before(String sql, int resultSetType, int resultSetConcurrency) { before(sql); } @Before(method = {"prepareStatement", "prepareCall"}) public void before(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) { before(sql); } // --- after @After(method = {"execute", "executeQuery", "executeUpdate", "executeLargeUpdate", "prepareStatement", "prepareCall"}) public void after(String sql) throws Exception { double duration = ((double) System.nanoTime() - startTime) / (double) TimeUnit.SECONDS.toNanos(1L);
// Path: promagent-framework/promagent-api/src/main/java/io/promagent/hookcontext/MetricDef.java // public class MetricDef<T extends Collector> { // // private final String metricName; // private final BiFunction<String, CollectorRegistry, T> producer; // // /** // * See {@link MetricsStore}. // * @param metricName Name of the Prometheus metric, like <tt>"http_requests_total"</tt>. // * @param producer Function to create a new metric and register it with the registry. // * This function will only be called once, subsequent calls to {@link MetricsStore#createOrGet(MetricDef)} // * will return the previously created metric with the specified name. // * The two parameters are the <i>metricName</i> as specified above, // * and the Prometheus registry where the new metric should be registered. // * For an example see JavaDoc for {@link MetricsStore}. // */ // public MetricDef(String metricName, BiFunction<String, CollectorRegistry, T> producer) { // this.metricName = metricName; // this.producer = producer; // } // // String getMetricName() { // return metricName; // } // // BiFunction<String, CollectorRegistry, T> getProducer() { // return producer; // } // } // // Path: promagent-framework/promagent-api/src/main/java/io/promagent/hookcontext/MetricsStore.java // public class MetricsStore { // // private final CollectorRegistry registry; // private final ConcurrentMap<String, Collector> metrics = new ConcurrentHashMap<>(); // // public MetricsStore(CollectorRegistry registry) { // this.registry = registry; // } // // /** // * See {@link MetricsStore} and {@link MetricDef#MetricDef(String, BiFunction)}. // */ // @SuppressWarnings("unchecked") // public <T extends Collector> T createOrGet(MetricDef<T> metricDef) { // return (T) metrics.computeIfAbsent(metricDef.getMetricName(), s -> metricDef.getProducer().apply(metricDef.getMetricName(), registry)); // } // } // // Path: promagent-example/src/main/java/io/promagent/hooks/HttpContext.java // static final Key<String> HTTP_METHOD = new Key<>(); // // Path: promagent-example/src/main/java/io/promagent/hooks/HttpContext.java // static final Key<String> HTTP_PATH = new Key<>(); // Path: promagent-example/src/main/java/io/promagent/hooks/JdbcHook.java import io.promagent.annotations.After; import io.promagent.annotations.Before; import io.promagent.annotations.Hook; import io.promagent.hookcontext.MetricDef; import io.promagent.hookcontext.MetricsStore; import io.prometheus.client.Counter; import io.prometheus.client.Summary; import java.util.concurrent.TimeUnit; import static io.promagent.hooks.HttpContext.HTTP_METHOD; import static io.promagent.hooks.HttpContext.HTTP_PATH; @Before(method = {"execute", "executeUpdate", "executeLargeUpdate", "prepareStatement"}) public void before(String sql, int autoGeneratedKeys) { before(sql); } @Before(method = {"execute", "executeUpdate", "executeLargeUpdate", "prepareStatement"}) public void before(String sql, int[] columnIndexes) { before(sql); } @Before(method = {"execute", "executeUpdate", "executeLargeUpdate", "prepareStatement"}) public void before(String sql, String[] columnNames) { before(sql); } @Before(method = {"prepareStatement", "prepareCall"}) public void before(String sql, int resultSetType, int resultSetConcurrency) { before(sql); } @Before(method = {"prepareStatement", "prepareCall"}) public void before(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) { before(sql); } // --- after @After(method = {"execute", "executeQuery", "executeUpdate", "executeLargeUpdate", "prepareStatement", "prepareCall"}) public void after(String sql) throws Exception { double duration = ((double) System.nanoTime() - startTime) / (double) TimeUnit.SECONDS.toNanos(1L);
String method = HttpContext.get(HTTP_METHOD).orElse("no http context");
fstab/promagent
promagent-example/src/main/java/io/promagent/hooks/JdbcHook.java
// Path: promagent-framework/promagent-api/src/main/java/io/promagent/hookcontext/MetricDef.java // public class MetricDef<T extends Collector> { // // private final String metricName; // private final BiFunction<String, CollectorRegistry, T> producer; // // /** // * See {@link MetricsStore}. // * @param metricName Name of the Prometheus metric, like <tt>"http_requests_total"</tt>. // * @param producer Function to create a new metric and register it with the registry. // * This function will only be called once, subsequent calls to {@link MetricsStore#createOrGet(MetricDef)} // * will return the previously created metric with the specified name. // * The two parameters are the <i>metricName</i> as specified above, // * and the Prometheus registry where the new metric should be registered. // * For an example see JavaDoc for {@link MetricsStore}. // */ // public MetricDef(String metricName, BiFunction<String, CollectorRegistry, T> producer) { // this.metricName = metricName; // this.producer = producer; // } // // String getMetricName() { // return metricName; // } // // BiFunction<String, CollectorRegistry, T> getProducer() { // return producer; // } // } // // Path: promagent-framework/promagent-api/src/main/java/io/promagent/hookcontext/MetricsStore.java // public class MetricsStore { // // private final CollectorRegistry registry; // private final ConcurrentMap<String, Collector> metrics = new ConcurrentHashMap<>(); // // public MetricsStore(CollectorRegistry registry) { // this.registry = registry; // } // // /** // * See {@link MetricsStore} and {@link MetricDef#MetricDef(String, BiFunction)}. // */ // @SuppressWarnings("unchecked") // public <T extends Collector> T createOrGet(MetricDef<T> metricDef) { // return (T) metrics.computeIfAbsent(metricDef.getMetricName(), s -> metricDef.getProducer().apply(metricDef.getMetricName(), registry)); // } // } // // Path: promagent-example/src/main/java/io/promagent/hooks/HttpContext.java // static final Key<String> HTTP_METHOD = new Key<>(); // // Path: promagent-example/src/main/java/io/promagent/hooks/HttpContext.java // static final Key<String> HTTP_PATH = new Key<>();
import io.promagent.annotations.After; import io.promagent.annotations.Before; import io.promagent.annotations.Hook; import io.promagent.hookcontext.MetricDef; import io.promagent.hookcontext.MetricsStore; import io.prometheus.client.Counter; import io.prometheus.client.Summary; import java.util.concurrent.TimeUnit; import static io.promagent.hooks.HttpContext.HTTP_METHOD; import static io.promagent.hooks.HttpContext.HTTP_PATH;
public void before(String sql, int autoGeneratedKeys) { before(sql); } @Before(method = {"execute", "executeUpdate", "executeLargeUpdate", "prepareStatement"}) public void before(String sql, int[] columnIndexes) { before(sql); } @Before(method = {"execute", "executeUpdate", "executeLargeUpdate", "prepareStatement"}) public void before(String sql, String[] columnNames) { before(sql); } @Before(method = {"prepareStatement", "prepareCall"}) public void before(String sql, int resultSetType, int resultSetConcurrency) { before(sql); } @Before(method = {"prepareStatement", "prepareCall"}) public void before(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) { before(sql); } // --- after @After(method = {"execute", "executeQuery", "executeUpdate", "executeLargeUpdate", "prepareStatement", "prepareCall"}) public void after(String sql) throws Exception { double duration = ((double) System.nanoTime() - startTime) / (double) TimeUnit.SECONDS.toNanos(1L); String method = HttpContext.get(HTTP_METHOD).orElse("no http context");
// Path: promagent-framework/promagent-api/src/main/java/io/promagent/hookcontext/MetricDef.java // public class MetricDef<T extends Collector> { // // private final String metricName; // private final BiFunction<String, CollectorRegistry, T> producer; // // /** // * See {@link MetricsStore}. // * @param metricName Name of the Prometheus metric, like <tt>"http_requests_total"</tt>. // * @param producer Function to create a new metric and register it with the registry. // * This function will only be called once, subsequent calls to {@link MetricsStore#createOrGet(MetricDef)} // * will return the previously created metric with the specified name. // * The two parameters are the <i>metricName</i> as specified above, // * and the Prometheus registry where the new metric should be registered. // * For an example see JavaDoc for {@link MetricsStore}. // */ // public MetricDef(String metricName, BiFunction<String, CollectorRegistry, T> producer) { // this.metricName = metricName; // this.producer = producer; // } // // String getMetricName() { // return metricName; // } // // BiFunction<String, CollectorRegistry, T> getProducer() { // return producer; // } // } // // Path: promagent-framework/promagent-api/src/main/java/io/promagent/hookcontext/MetricsStore.java // public class MetricsStore { // // private final CollectorRegistry registry; // private final ConcurrentMap<String, Collector> metrics = new ConcurrentHashMap<>(); // // public MetricsStore(CollectorRegistry registry) { // this.registry = registry; // } // // /** // * See {@link MetricsStore} and {@link MetricDef#MetricDef(String, BiFunction)}. // */ // @SuppressWarnings("unchecked") // public <T extends Collector> T createOrGet(MetricDef<T> metricDef) { // return (T) metrics.computeIfAbsent(metricDef.getMetricName(), s -> metricDef.getProducer().apply(metricDef.getMetricName(), registry)); // } // } // // Path: promagent-example/src/main/java/io/promagent/hooks/HttpContext.java // static final Key<String> HTTP_METHOD = new Key<>(); // // Path: promagent-example/src/main/java/io/promagent/hooks/HttpContext.java // static final Key<String> HTTP_PATH = new Key<>(); // Path: promagent-example/src/main/java/io/promagent/hooks/JdbcHook.java import io.promagent.annotations.After; import io.promagent.annotations.Before; import io.promagent.annotations.Hook; import io.promagent.hookcontext.MetricDef; import io.promagent.hookcontext.MetricsStore; import io.prometheus.client.Counter; import io.prometheus.client.Summary; import java.util.concurrent.TimeUnit; import static io.promagent.hooks.HttpContext.HTTP_METHOD; import static io.promagent.hooks.HttpContext.HTTP_PATH; public void before(String sql, int autoGeneratedKeys) { before(sql); } @Before(method = {"execute", "executeUpdate", "executeLargeUpdate", "prepareStatement"}) public void before(String sql, int[] columnIndexes) { before(sql); } @Before(method = {"execute", "executeUpdate", "executeLargeUpdate", "prepareStatement"}) public void before(String sql, String[] columnNames) { before(sql); } @Before(method = {"prepareStatement", "prepareCall"}) public void before(String sql, int resultSetType, int resultSetConcurrency) { before(sql); } @Before(method = {"prepareStatement", "prepareCall"}) public void before(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) { before(sql); } // --- after @After(method = {"execute", "executeQuery", "executeUpdate", "executeLargeUpdate", "prepareStatement", "prepareCall"}) public void after(String sql) throws Exception { double duration = ((double) System.nanoTime() - startTime) / (double) TimeUnit.SECONDS.toNanos(1L); String method = HttpContext.get(HTTP_METHOD).orElse("no http context");
String path = HttpContext.get(HTTP_PATH).orElse("no http context");
fstab/promagent
promagent-framework/promagent-agent/src/test/java/io/promagent/agent/JarFilesTest.java
// Path: promagent-framework/promagent-agent/src/main/java/io/promagent/agent/JarFiles.java // static Path findAgentJarFromCmdline(List<String> cmdlineArgs) { // Pattern p = Pattern.compile("^-javaagent:(.*promagent([^/]*).jar)(=.*)?$"); // for (String arg : cmdlineArgs) { // Matcher m = p.matcher(arg); // if (m.matches()) { // return Paths.get(m.group(1)); // } // } // throw new RuntimeException("Failed to locate promagent.jar file."); // }
import org.junit.jupiter.api.Test; import static io.promagent.agent.JarFiles.findAgentJarFromCmdline; import static java.util.Arrays.asList; import static org.junit.jupiter.api.Assertions.*;
// Copyright 2017 The Promagent Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package io.promagent.agent; class JarFilesTest { @Test void testCmdlineParserWildfly() { // The command line arguments are taken from the Wildfly application server example. String[] cmdlineArgs = new String[]{ "-D[Standalone]", "-Xbootclasspath/p:/tmp/wildfly-10.1.0.Final/modules/system/layers/base/org/jboss/logmanager/main/jboss-logmanager-2.0.4.Final.jar", "-Djboss.modules.system.pkgs=org.jboss.logmanager,io.promagent.agent", "-Djava.util.logging.manager=org.jboss.logmanager.LogManager", "-javaagent:../promagent/promagent-dist/target/promagent.jar=port=9300", "-Dorg.jboss.boot.log.file=/tmp/wildfly-10.1.0.Final/standalone/log/server.log", "-Dlogging.configuration=file:/tmp/wildfly-10.1.0.Final/standalone/configuration/logging.properties" };
// Path: promagent-framework/promagent-agent/src/main/java/io/promagent/agent/JarFiles.java // static Path findAgentJarFromCmdline(List<String> cmdlineArgs) { // Pattern p = Pattern.compile("^-javaagent:(.*promagent([^/]*).jar)(=.*)?$"); // for (String arg : cmdlineArgs) { // Matcher m = p.matcher(arg); // if (m.matches()) { // return Paths.get(m.group(1)); // } // } // throw new RuntimeException("Failed to locate promagent.jar file."); // } // Path: promagent-framework/promagent-agent/src/test/java/io/promagent/agent/JarFilesTest.java import org.junit.jupiter.api.Test; import static io.promagent.agent.JarFiles.findAgentJarFromCmdline; import static java.util.Arrays.asList; import static org.junit.jupiter.api.Assertions.*; // Copyright 2017 The Promagent Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package io.promagent.agent; class JarFilesTest { @Test void testCmdlineParserWildfly() { // The command line arguments are taken from the Wildfly application server example. String[] cmdlineArgs = new String[]{ "-D[Standalone]", "-Xbootclasspath/p:/tmp/wildfly-10.1.0.Final/modules/system/layers/base/org/jboss/logmanager/main/jboss-logmanager-2.0.4.Final.jar", "-Djboss.modules.system.pkgs=org.jboss.logmanager,io.promagent.agent", "-Djava.util.logging.manager=org.jboss.logmanager.LogManager", "-javaagent:../promagent/promagent-dist/target/promagent.jar=port=9300", "-Dorg.jboss.boot.log.file=/tmp/wildfly-10.1.0.Final/standalone/log/server.log", "-Dlogging.configuration=file:/tmp/wildfly-10.1.0.Final/standalone/configuration/logging.properties" };
assertEquals("../promagent/promagent-dist/target/promagent.jar", findAgentJarFromCmdline(asList(cmdlineArgs)).toString());
fstab/promagent
promagent-framework/promagent-internal/src/main/java/io/promagent/internal/PromagentAdvice.java
// Path: promagent-framework/promagent-agent/src/main/java/io/promagent/agent/ClassLoaderCache.java // public class ClassLoaderCache { // // private static ClassLoaderCache instance; // // // TODO: The cache does not free class loaders when applications are undeployed. Maybe use WeakHashMap? // private final Map<ClassLoader, PerDeploymentClassLoader> cache = new HashMap<>(); // private final URLClassLoader sharedClassLoader; // shared across multiple deployments // private final List<Path> perDeploymentJars; // one class loader for each deployment for these JARs // // private ClassLoaderCache(JarFiles jarFiles) { // sharedClassLoader = new URLClassLoader(pathsToURLs(jarFiles.getSharedJars())); // perDeploymentJars = jarFiles.getPerDeploymentJars(); // } // // public static synchronized ClassLoaderCache getInstance() { // if (instance == null) { // instance = new ClassLoaderCache(JarFiles.extract()); // } // return instance; // } // // public List<Path> getPerDeploymentJars() { // return perDeploymentJars; // } // // public synchronized ClassLoader currentClassLoader() { // ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); // if (! cache.containsKey(contextClassLoader)) { // cache.put(contextClassLoader, new PerDeploymentClassLoader(pathsToURLs(perDeploymentJars), sharedClassLoader, contextClassLoader)); // } // return cache.get(contextClassLoader); // } // // private static URL[] pathsToURLs(List<Path> paths) { // try { // URL[] result = new URL[paths.size()]; // for (int i=0; i<paths.size(); i++) { // result[i] = paths.get(i).toUri().toURL(); // } // return result; // } catch (MalformedURLException e) { // throw new RuntimeException(e); // } // } // }
import io.promagent.agent.ClassLoaderCache; import net.bytebuddy.implementation.bytecode.assign.Assigner; import java.lang.reflect.Method; import java.util.List; import static net.bytebuddy.asm.Advice.*;
// Copyright 2017 The Promagent Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package io.promagent.internal; public class PromagentAdvice { // TODO: // Should we move this class into it's own maven module // to make clear that it cannot reference other classes from promagent-internal? @OnMethodEnter @SuppressWarnings("unchecked") public static List<Object> before( @This(optional = true) Object that, @Origin Method method, @AllArguments Object[] args ) { // that is null when instrumenting static methods. Class<?> clazz = that != null ? that.getClass() : method.getDeclaringClass(); try { // The following code is equivalent to: // return Delegator.before(that, method, args); // However, the Delegator class will not be available in the context of the instrumented method, // so we must use our agent class loader to load the Delegator class and do the call via reflection.
// Path: promagent-framework/promagent-agent/src/main/java/io/promagent/agent/ClassLoaderCache.java // public class ClassLoaderCache { // // private static ClassLoaderCache instance; // // // TODO: The cache does not free class loaders when applications are undeployed. Maybe use WeakHashMap? // private final Map<ClassLoader, PerDeploymentClassLoader> cache = new HashMap<>(); // private final URLClassLoader sharedClassLoader; // shared across multiple deployments // private final List<Path> perDeploymentJars; // one class loader for each deployment for these JARs // // private ClassLoaderCache(JarFiles jarFiles) { // sharedClassLoader = new URLClassLoader(pathsToURLs(jarFiles.getSharedJars())); // perDeploymentJars = jarFiles.getPerDeploymentJars(); // } // // public static synchronized ClassLoaderCache getInstance() { // if (instance == null) { // instance = new ClassLoaderCache(JarFiles.extract()); // } // return instance; // } // // public List<Path> getPerDeploymentJars() { // return perDeploymentJars; // } // // public synchronized ClassLoader currentClassLoader() { // ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); // if (! cache.containsKey(contextClassLoader)) { // cache.put(contextClassLoader, new PerDeploymentClassLoader(pathsToURLs(perDeploymentJars), sharedClassLoader, contextClassLoader)); // } // return cache.get(contextClassLoader); // } // // private static URL[] pathsToURLs(List<Path> paths) { // try { // URL[] result = new URL[paths.size()]; // for (int i=0; i<paths.size(); i++) { // result[i] = paths.get(i).toUri().toURL(); // } // return result; // } catch (MalformedURLException e) { // throw new RuntimeException(e); // } // } // } // Path: promagent-framework/promagent-internal/src/main/java/io/promagent/internal/PromagentAdvice.java import io.promagent.agent.ClassLoaderCache; import net.bytebuddy.implementation.bytecode.assign.Assigner; import java.lang.reflect.Method; import java.util.List; import static net.bytebuddy.asm.Advice.*; // Copyright 2017 The Promagent Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package io.promagent.internal; public class PromagentAdvice { // TODO: // Should we move this class into it's own maven module // to make clear that it cannot reference other classes from promagent-internal? @OnMethodEnter @SuppressWarnings("unchecked") public static List<Object> before( @This(optional = true) Object that, @Origin Method method, @AllArguments Object[] args ) { // that is null when instrumenting static methods. Class<?> clazz = that != null ? that.getClass() : method.getDeclaringClass(); try { // The following code is equivalent to: // return Delegator.before(that, method, args); // However, the Delegator class will not be available in the context of the instrumented method, // so we must use our agent class loader to load the Delegator class and do the call via reflection.
Class<?> delegator = ClassLoaderCache.getInstance().currentClassLoader().loadClass("io.promagent.internal.Delegator");
fstab/promagent
promagent-framework/promagent-internal/src/main/java/io/promagent/internal/HookMetadataParser.java
// Path: promagent-framework/promagent-internal/src/main/java/io/promagent/internal/HookMetadata.java // public static class MethodSignature implements Comparable<MethodSignature> { // // private final String methodName; // private final List<String> parameterTypes; // // public MethodSignature(String methodName, List<String> parameterTypes) { // this.methodName = methodName; // this.parameterTypes = Collections.unmodifiableList(new ArrayList<>(parameterTypes)); // } // // public String getMethodName() { // return methodName; // } // // public List<String> getParameterTypes() { // return parameterTypes; // } // // @Override // public String toString() { // return methodName + "(" + String.join(", ", parameterTypes) + ")"; // } // // @Override // public boolean equals(Object o) { // return o != null && getClass() == o.getClass() && compareTo((MethodSignature) o) == 0; // } // // @Override // public int hashCode() { // return Objects.hash(toString()); // } // // @Override // public int compareTo(MethodSignature o) { // return Comparator // .comparing(MethodSignature::getMethodName) // .thenComparing(MethodSignature::getParameterTypes, new LexicographicalComparator<>()) // .compare(this, o); // } // }
import io.promagent.annotations.After; import io.promagent.annotations.Before; import io.promagent.annotations.Returned; import io.promagent.annotations.Thrown; import io.promagent.internal.HookMetadata.MethodSignature; import net.bytebuddy.jar.asm.*; import org.apache.commons.io.IOUtils; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.util.*; import java.util.function.Consumer; import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.Stream; import java.util.zip.ZipEntry; import java.util.zip.ZipFile;
} /** * Helper to create {@link HookMetadata} isntances. */ private static class HookMetadataBuilder { private String hookClassName; private List<String> instruments = new ArrayList<>(); private List<MethodSignatureBuilder> methods = new ArrayList<>(); private HookMetadataBuilder(String hookClassName) { this.hookClassName = hookClassName; } private void addInstruments(String instruments) { this.instruments.add(instruments); } private MethodSignatureBuilder newMethodSignature(List<String> parameterTypes) { MethodSignatureBuilder builder = new MethodSignatureBuilder(); for (String parameterType : parameterTypes) { builder.addParameterType(parameterType); } methods.add(builder); return builder; } private HookMetadata build() {
// Path: promagent-framework/promagent-internal/src/main/java/io/promagent/internal/HookMetadata.java // public static class MethodSignature implements Comparable<MethodSignature> { // // private final String methodName; // private final List<String> parameterTypes; // // public MethodSignature(String methodName, List<String> parameterTypes) { // this.methodName = methodName; // this.parameterTypes = Collections.unmodifiableList(new ArrayList<>(parameterTypes)); // } // // public String getMethodName() { // return methodName; // } // // public List<String> getParameterTypes() { // return parameterTypes; // } // // @Override // public String toString() { // return methodName + "(" + String.join(", ", parameterTypes) + ")"; // } // // @Override // public boolean equals(Object o) { // return o != null && getClass() == o.getClass() && compareTo((MethodSignature) o) == 0; // } // // @Override // public int hashCode() { // return Objects.hash(toString()); // } // // @Override // public int compareTo(MethodSignature o) { // return Comparator // .comparing(MethodSignature::getMethodName) // .thenComparing(MethodSignature::getParameterTypes, new LexicographicalComparator<>()) // .compare(this, o); // } // } // Path: promagent-framework/promagent-internal/src/main/java/io/promagent/internal/HookMetadataParser.java import io.promagent.annotations.After; import io.promagent.annotations.Before; import io.promagent.annotations.Returned; import io.promagent.annotations.Thrown; import io.promagent.internal.HookMetadata.MethodSignature; import net.bytebuddy.jar.asm.*; import org.apache.commons.io.IOUtils; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.util.*; import java.util.function.Consumer; import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.Stream; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; } /** * Helper to create {@link HookMetadata} isntances. */ private static class HookMetadataBuilder { private String hookClassName; private List<String> instruments = new ArrayList<>(); private List<MethodSignatureBuilder> methods = new ArrayList<>(); private HookMetadataBuilder(String hookClassName) { this.hookClassName = hookClassName; } private void addInstruments(String instruments) { this.instruments.add(instruments); } private MethodSignatureBuilder newMethodSignature(List<String> parameterTypes) { MethodSignatureBuilder builder = new MethodSignatureBuilder(); for (String parameterType : parameterTypes) { builder.addParameterType(parameterType); } methods.add(builder); return builder; } private HookMetadata build() {
SortedSet<MethodSignature> methodSignatures = new TreeSet<>();
fstab/promagent
promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/hooks/LifecycleHookSkipFalse.java
// Path: promagent-framework/promagent-api/src/main/java/io/promagent/hookcontext/MetricsStore.java // public class MetricsStore { // // private final CollectorRegistry registry; // private final ConcurrentMap<String, Collector> metrics = new ConcurrentHashMap<>(); // // public MetricsStore(CollectorRegistry registry) { // this.registry = registry; // } // // /** // * See {@link MetricsStore} and {@link MetricDef#MetricDef(String, BiFunction)}. // */ // @SuppressWarnings("unchecked") // public <T extends Collector> T createOrGet(MetricDef<T> metricDef) { // return (T) metrics.computeIfAbsent(metricDef.getMetricName(), s -> metricDef.getProducer().apply(metricDef.getMetricName(), registry)); // } // } // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/MethodCallCounter.java // public class MethodCallCounter { // // public static void reset() { // captures.clear(); // } // // public static void observe(Object hook, String methodName, Object... args) { // captures.add(new Capture(hook, methodName, args)); // } // // public static void assertNumCalls(int expectedNumberOfCalls, Class<?> hookClass, String hookMethod, Object... expectedArgs) { // List<Capture> matching = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .filter(c -> c.hookMethod.equals(hookMethod)) // .filter(c -> Arrays.equals(expectedArgs, c.args)) // .collect(Collectors.toList()); // Assertions.assertEquals(expectedNumberOfCalls, matching.size()); // } // // // special case for the varargsMixed test // public static void assertNumCalls(int expectedNumberOfCalls, Class<?> hookClass, String hookMethod, String firstString, String... moreStrings) { // List<Capture> matching = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .filter(c -> c.hookMethod.equals(hookMethod)) // .filter(c -> c.args.length == 2) // .filter(c -> Objects.equals(firstString, c.args[0])) // .filter(c -> Arrays.equals(moreStrings, (String[]) c.args[1])) // .collect(Collectors.toList()); // Assertions.assertEquals(expectedNumberOfCalls, matching.size()); // } // // public static void assertNumHookInstances(int expectedNumberOfInstances, Class<?> hookClass) { // long actualNumberOfInstances = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .map(c -> c.hook) // .distinct() // .count(); // Assertions.assertEquals(expectedNumberOfInstances, (int) actualNumberOfInstances); // } // // private static class Capture { // final Object hook; // final String hookMethod; // final Object[] args; // // Capture(Object hook, String hookMethod, Object[] args) { // this.hook = hook; // this.hookMethod = hookMethod; // this.args = args; // } // } // // private static final List<Capture> captures = Collections.synchronizedList(new ArrayList<>()); // // private MethodCallCounter() {} // } // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/classes/Fruit.java // public class Fruit { // public static class Orange extends Fruit{} // } // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/classes/Fruit.java // public static class Orange extends Fruit{} // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/classes/ParameterTypesExample.java // public class ParameterTypesExample implements IParameterTypesExample { // // @Override // public void noParam() {} // // @Override // public void primitiveTypes(byte b, short s, int i, long l, float f, double d, boolean x, char c) {} // // @Override // public void boxedTypes(Byte b, Short s, Integer i, Long l, Float f, Double d, Boolean x, Character c) {} // // @Override // public void objects(Object o, Fruit f, Fruit.Orange x) {} // // @Override // public void primitiveArrays(byte[] b, short[] s, int[] i, long[] l, float[] f, double[] d, boolean[] x, char[] c) {} // // @Override // public void boxedArrays(Byte[] b, Short[] s, Integer[] i, Long[] l, Float[] f, Double[] d, Boolean[] x, Character[] c) {} // // @Override // public void objectArrays(Object[] o, Fruit[] f, Fruit.Orange[] x) {} // // @Override // public void generics(List<Object> objectList, List<Fruit> fruitList, List<Fruit.Orange> orangeList) {} // // @Override // public void varargsExplicit(Object... args) {} // // @Override // public void varargsImplicit(Object[] args) {} // // @Override // public void varargsMixed(String s, String... more) {} // // @Override // public void recursive(int nRecursiveCalls) { // if (nRecursiveCalls > 0) { // recursive(nRecursiveCalls - 1); // } // } // }
import io.promagent.annotations.After; import io.promagent.annotations.Before; import io.promagent.annotations.Hook; import io.promagent.hookcontext.MetricsStore; import io.promagent.internal.instrumentationtests.MethodCallCounter; import io.promagent.internal.instrumentationtests.classes.Fruit; import io.promagent.internal.instrumentationtests.classes.Fruit.Orange; import io.promagent.internal.instrumentationtests.classes.ParameterTypesExample;
package io.promagent.internal.instrumentationtests.hooks; /** * Instrument all methods in {@link ParameterTypesExample}. */ @Hook( instruments = "io.promagent.internal.instrumentationtests.classes.ParameterTypesExample", skipNestedCalls = false ) public class LifecycleHookSkipFalse {
// Path: promagent-framework/promagent-api/src/main/java/io/promagent/hookcontext/MetricsStore.java // public class MetricsStore { // // private final CollectorRegistry registry; // private final ConcurrentMap<String, Collector> metrics = new ConcurrentHashMap<>(); // // public MetricsStore(CollectorRegistry registry) { // this.registry = registry; // } // // /** // * See {@link MetricsStore} and {@link MetricDef#MetricDef(String, BiFunction)}. // */ // @SuppressWarnings("unchecked") // public <T extends Collector> T createOrGet(MetricDef<T> metricDef) { // return (T) metrics.computeIfAbsent(metricDef.getMetricName(), s -> metricDef.getProducer().apply(metricDef.getMetricName(), registry)); // } // } // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/MethodCallCounter.java // public class MethodCallCounter { // // public static void reset() { // captures.clear(); // } // // public static void observe(Object hook, String methodName, Object... args) { // captures.add(new Capture(hook, methodName, args)); // } // // public static void assertNumCalls(int expectedNumberOfCalls, Class<?> hookClass, String hookMethod, Object... expectedArgs) { // List<Capture> matching = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .filter(c -> c.hookMethod.equals(hookMethod)) // .filter(c -> Arrays.equals(expectedArgs, c.args)) // .collect(Collectors.toList()); // Assertions.assertEquals(expectedNumberOfCalls, matching.size()); // } // // // special case for the varargsMixed test // public static void assertNumCalls(int expectedNumberOfCalls, Class<?> hookClass, String hookMethod, String firstString, String... moreStrings) { // List<Capture> matching = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .filter(c -> c.hookMethod.equals(hookMethod)) // .filter(c -> c.args.length == 2) // .filter(c -> Objects.equals(firstString, c.args[0])) // .filter(c -> Arrays.equals(moreStrings, (String[]) c.args[1])) // .collect(Collectors.toList()); // Assertions.assertEquals(expectedNumberOfCalls, matching.size()); // } // // public static void assertNumHookInstances(int expectedNumberOfInstances, Class<?> hookClass) { // long actualNumberOfInstances = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .map(c -> c.hook) // .distinct() // .count(); // Assertions.assertEquals(expectedNumberOfInstances, (int) actualNumberOfInstances); // } // // private static class Capture { // final Object hook; // final String hookMethod; // final Object[] args; // // Capture(Object hook, String hookMethod, Object[] args) { // this.hook = hook; // this.hookMethod = hookMethod; // this.args = args; // } // } // // private static final List<Capture> captures = Collections.synchronizedList(new ArrayList<>()); // // private MethodCallCounter() {} // } // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/classes/Fruit.java // public class Fruit { // public static class Orange extends Fruit{} // } // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/classes/Fruit.java // public static class Orange extends Fruit{} // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/classes/ParameterTypesExample.java // public class ParameterTypesExample implements IParameterTypesExample { // // @Override // public void noParam() {} // // @Override // public void primitiveTypes(byte b, short s, int i, long l, float f, double d, boolean x, char c) {} // // @Override // public void boxedTypes(Byte b, Short s, Integer i, Long l, Float f, Double d, Boolean x, Character c) {} // // @Override // public void objects(Object o, Fruit f, Fruit.Orange x) {} // // @Override // public void primitiveArrays(byte[] b, short[] s, int[] i, long[] l, float[] f, double[] d, boolean[] x, char[] c) {} // // @Override // public void boxedArrays(Byte[] b, Short[] s, Integer[] i, Long[] l, Float[] f, Double[] d, Boolean[] x, Character[] c) {} // // @Override // public void objectArrays(Object[] o, Fruit[] f, Fruit.Orange[] x) {} // // @Override // public void generics(List<Object> objectList, List<Fruit> fruitList, List<Fruit.Orange> orangeList) {} // // @Override // public void varargsExplicit(Object... args) {} // // @Override // public void varargsImplicit(Object[] args) {} // // @Override // public void varargsMixed(String s, String... more) {} // // @Override // public void recursive(int nRecursiveCalls) { // if (nRecursiveCalls > 0) { // recursive(nRecursiveCalls - 1); // } // } // } // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/hooks/LifecycleHookSkipFalse.java import io.promagent.annotations.After; import io.promagent.annotations.Before; import io.promagent.annotations.Hook; import io.promagent.hookcontext.MetricsStore; import io.promagent.internal.instrumentationtests.MethodCallCounter; import io.promagent.internal.instrumentationtests.classes.Fruit; import io.promagent.internal.instrumentationtests.classes.Fruit.Orange; import io.promagent.internal.instrumentationtests.classes.ParameterTypesExample; package io.promagent.internal.instrumentationtests.hooks; /** * Instrument all methods in {@link ParameterTypesExample}. */ @Hook( instruments = "io.promagent.internal.instrumentationtests.classes.ParameterTypesExample", skipNestedCalls = false ) public class LifecycleHookSkipFalse {
public LifecycleHookSkipFalse(MetricsStore m) {}
fstab/promagent
promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/hooks/LifecycleHookSkipFalse.java
// Path: promagent-framework/promagent-api/src/main/java/io/promagent/hookcontext/MetricsStore.java // public class MetricsStore { // // private final CollectorRegistry registry; // private final ConcurrentMap<String, Collector> metrics = new ConcurrentHashMap<>(); // // public MetricsStore(CollectorRegistry registry) { // this.registry = registry; // } // // /** // * See {@link MetricsStore} and {@link MetricDef#MetricDef(String, BiFunction)}. // */ // @SuppressWarnings("unchecked") // public <T extends Collector> T createOrGet(MetricDef<T> metricDef) { // return (T) metrics.computeIfAbsent(metricDef.getMetricName(), s -> metricDef.getProducer().apply(metricDef.getMetricName(), registry)); // } // } // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/MethodCallCounter.java // public class MethodCallCounter { // // public static void reset() { // captures.clear(); // } // // public static void observe(Object hook, String methodName, Object... args) { // captures.add(new Capture(hook, methodName, args)); // } // // public static void assertNumCalls(int expectedNumberOfCalls, Class<?> hookClass, String hookMethod, Object... expectedArgs) { // List<Capture> matching = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .filter(c -> c.hookMethod.equals(hookMethod)) // .filter(c -> Arrays.equals(expectedArgs, c.args)) // .collect(Collectors.toList()); // Assertions.assertEquals(expectedNumberOfCalls, matching.size()); // } // // // special case for the varargsMixed test // public static void assertNumCalls(int expectedNumberOfCalls, Class<?> hookClass, String hookMethod, String firstString, String... moreStrings) { // List<Capture> matching = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .filter(c -> c.hookMethod.equals(hookMethod)) // .filter(c -> c.args.length == 2) // .filter(c -> Objects.equals(firstString, c.args[0])) // .filter(c -> Arrays.equals(moreStrings, (String[]) c.args[1])) // .collect(Collectors.toList()); // Assertions.assertEquals(expectedNumberOfCalls, matching.size()); // } // // public static void assertNumHookInstances(int expectedNumberOfInstances, Class<?> hookClass) { // long actualNumberOfInstances = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .map(c -> c.hook) // .distinct() // .count(); // Assertions.assertEquals(expectedNumberOfInstances, (int) actualNumberOfInstances); // } // // private static class Capture { // final Object hook; // final String hookMethod; // final Object[] args; // // Capture(Object hook, String hookMethod, Object[] args) { // this.hook = hook; // this.hookMethod = hookMethod; // this.args = args; // } // } // // private static final List<Capture> captures = Collections.synchronizedList(new ArrayList<>()); // // private MethodCallCounter() {} // } // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/classes/Fruit.java // public class Fruit { // public static class Orange extends Fruit{} // } // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/classes/Fruit.java // public static class Orange extends Fruit{} // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/classes/ParameterTypesExample.java // public class ParameterTypesExample implements IParameterTypesExample { // // @Override // public void noParam() {} // // @Override // public void primitiveTypes(byte b, short s, int i, long l, float f, double d, boolean x, char c) {} // // @Override // public void boxedTypes(Byte b, Short s, Integer i, Long l, Float f, Double d, Boolean x, Character c) {} // // @Override // public void objects(Object o, Fruit f, Fruit.Orange x) {} // // @Override // public void primitiveArrays(byte[] b, short[] s, int[] i, long[] l, float[] f, double[] d, boolean[] x, char[] c) {} // // @Override // public void boxedArrays(Byte[] b, Short[] s, Integer[] i, Long[] l, Float[] f, Double[] d, Boolean[] x, Character[] c) {} // // @Override // public void objectArrays(Object[] o, Fruit[] f, Fruit.Orange[] x) {} // // @Override // public void generics(List<Object> objectList, List<Fruit> fruitList, List<Fruit.Orange> orangeList) {} // // @Override // public void varargsExplicit(Object... args) {} // // @Override // public void varargsImplicit(Object[] args) {} // // @Override // public void varargsMixed(String s, String... more) {} // // @Override // public void recursive(int nRecursiveCalls) { // if (nRecursiveCalls > 0) { // recursive(nRecursiveCalls - 1); // } // } // }
import io.promagent.annotations.After; import io.promagent.annotations.Before; import io.promagent.annotations.Hook; import io.promagent.hookcontext.MetricsStore; import io.promagent.internal.instrumentationtests.MethodCallCounter; import io.promagent.internal.instrumentationtests.classes.Fruit; import io.promagent.internal.instrumentationtests.classes.Fruit.Orange; import io.promagent.internal.instrumentationtests.classes.ParameterTypesExample;
package io.promagent.internal.instrumentationtests.hooks; /** * Instrument all methods in {@link ParameterTypesExample}. */ @Hook( instruments = "io.promagent.internal.instrumentationtests.classes.ParameterTypesExample", skipNestedCalls = false ) public class LifecycleHookSkipFalse { public LifecycleHookSkipFalse(MetricsStore m) {} @Before(method = "recursive") public void before(int n) {
// Path: promagent-framework/promagent-api/src/main/java/io/promagent/hookcontext/MetricsStore.java // public class MetricsStore { // // private final CollectorRegistry registry; // private final ConcurrentMap<String, Collector> metrics = new ConcurrentHashMap<>(); // // public MetricsStore(CollectorRegistry registry) { // this.registry = registry; // } // // /** // * See {@link MetricsStore} and {@link MetricDef#MetricDef(String, BiFunction)}. // */ // @SuppressWarnings("unchecked") // public <T extends Collector> T createOrGet(MetricDef<T> metricDef) { // return (T) metrics.computeIfAbsent(metricDef.getMetricName(), s -> metricDef.getProducer().apply(metricDef.getMetricName(), registry)); // } // } // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/MethodCallCounter.java // public class MethodCallCounter { // // public static void reset() { // captures.clear(); // } // // public static void observe(Object hook, String methodName, Object... args) { // captures.add(new Capture(hook, methodName, args)); // } // // public static void assertNumCalls(int expectedNumberOfCalls, Class<?> hookClass, String hookMethod, Object... expectedArgs) { // List<Capture> matching = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .filter(c -> c.hookMethod.equals(hookMethod)) // .filter(c -> Arrays.equals(expectedArgs, c.args)) // .collect(Collectors.toList()); // Assertions.assertEquals(expectedNumberOfCalls, matching.size()); // } // // // special case for the varargsMixed test // public static void assertNumCalls(int expectedNumberOfCalls, Class<?> hookClass, String hookMethod, String firstString, String... moreStrings) { // List<Capture> matching = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .filter(c -> c.hookMethod.equals(hookMethod)) // .filter(c -> c.args.length == 2) // .filter(c -> Objects.equals(firstString, c.args[0])) // .filter(c -> Arrays.equals(moreStrings, (String[]) c.args[1])) // .collect(Collectors.toList()); // Assertions.assertEquals(expectedNumberOfCalls, matching.size()); // } // // public static void assertNumHookInstances(int expectedNumberOfInstances, Class<?> hookClass) { // long actualNumberOfInstances = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .map(c -> c.hook) // .distinct() // .count(); // Assertions.assertEquals(expectedNumberOfInstances, (int) actualNumberOfInstances); // } // // private static class Capture { // final Object hook; // final String hookMethod; // final Object[] args; // // Capture(Object hook, String hookMethod, Object[] args) { // this.hook = hook; // this.hookMethod = hookMethod; // this.args = args; // } // } // // private static final List<Capture> captures = Collections.synchronizedList(new ArrayList<>()); // // private MethodCallCounter() {} // } // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/classes/Fruit.java // public class Fruit { // public static class Orange extends Fruit{} // } // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/classes/Fruit.java // public static class Orange extends Fruit{} // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/classes/ParameterTypesExample.java // public class ParameterTypesExample implements IParameterTypesExample { // // @Override // public void noParam() {} // // @Override // public void primitiveTypes(byte b, short s, int i, long l, float f, double d, boolean x, char c) {} // // @Override // public void boxedTypes(Byte b, Short s, Integer i, Long l, Float f, Double d, Boolean x, Character c) {} // // @Override // public void objects(Object o, Fruit f, Fruit.Orange x) {} // // @Override // public void primitiveArrays(byte[] b, short[] s, int[] i, long[] l, float[] f, double[] d, boolean[] x, char[] c) {} // // @Override // public void boxedArrays(Byte[] b, Short[] s, Integer[] i, Long[] l, Float[] f, Double[] d, Boolean[] x, Character[] c) {} // // @Override // public void objectArrays(Object[] o, Fruit[] f, Fruit.Orange[] x) {} // // @Override // public void generics(List<Object> objectList, List<Fruit> fruitList, List<Fruit.Orange> orangeList) {} // // @Override // public void varargsExplicit(Object... args) {} // // @Override // public void varargsImplicit(Object[] args) {} // // @Override // public void varargsMixed(String s, String... more) {} // // @Override // public void recursive(int nRecursiveCalls) { // if (nRecursiveCalls > 0) { // recursive(nRecursiveCalls - 1); // } // } // } // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/hooks/LifecycleHookSkipFalse.java import io.promagent.annotations.After; import io.promagent.annotations.Before; import io.promagent.annotations.Hook; import io.promagent.hookcontext.MetricsStore; import io.promagent.internal.instrumentationtests.MethodCallCounter; import io.promagent.internal.instrumentationtests.classes.Fruit; import io.promagent.internal.instrumentationtests.classes.Fruit.Orange; import io.promagent.internal.instrumentationtests.classes.ParameterTypesExample; package io.promagent.internal.instrumentationtests.hooks; /** * Instrument all methods in {@link ParameterTypesExample}. */ @Hook( instruments = "io.promagent.internal.instrumentationtests.classes.ParameterTypesExample", skipNestedCalls = false ) public class LifecycleHookSkipFalse { public LifecycleHookSkipFalse(MetricsStore m) {} @Before(method = "recursive") public void before(int n) {
MethodCallCounter.observe(this, "before", n);
fstab/promagent
promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/hooks/OnlyAfterHook.java
// Path: promagent-framework/promagent-api/src/main/java/io/promagent/hookcontext/MetricsStore.java // public class MetricsStore { // // private final CollectorRegistry registry; // private final ConcurrentMap<String, Collector> metrics = new ConcurrentHashMap<>(); // // public MetricsStore(CollectorRegistry registry) { // this.registry = registry; // } // // /** // * See {@link MetricsStore} and {@link MetricDef#MetricDef(String, BiFunction)}. // */ // @SuppressWarnings("unchecked") // public <T extends Collector> T createOrGet(MetricDef<T> metricDef) { // return (T) metrics.computeIfAbsent(metricDef.getMetricName(), s -> metricDef.getProducer().apply(metricDef.getMetricName(), registry)); // } // } // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/MethodCallCounter.java // public class MethodCallCounter { // // public static void reset() { // captures.clear(); // } // // public static void observe(Object hook, String methodName, Object... args) { // captures.add(new Capture(hook, methodName, args)); // } // // public static void assertNumCalls(int expectedNumberOfCalls, Class<?> hookClass, String hookMethod, Object... expectedArgs) { // List<Capture> matching = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .filter(c -> c.hookMethod.equals(hookMethod)) // .filter(c -> Arrays.equals(expectedArgs, c.args)) // .collect(Collectors.toList()); // Assertions.assertEquals(expectedNumberOfCalls, matching.size()); // } // // // special case for the varargsMixed test // public static void assertNumCalls(int expectedNumberOfCalls, Class<?> hookClass, String hookMethod, String firstString, String... moreStrings) { // List<Capture> matching = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .filter(c -> c.hookMethod.equals(hookMethod)) // .filter(c -> c.args.length == 2) // .filter(c -> Objects.equals(firstString, c.args[0])) // .filter(c -> Arrays.equals(moreStrings, (String[]) c.args[1])) // .collect(Collectors.toList()); // Assertions.assertEquals(expectedNumberOfCalls, matching.size()); // } // // public static void assertNumHookInstances(int expectedNumberOfInstances, Class<?> hookClass) { // long actualNumberOfInstances = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .map(c -> c.hook) // .distinct() // .count(); // Assertions.assertEquals(expectedNumberOfInstances, (int) actualNumberOfInstances); // } // // private static class Capture { // final Object hook; // final String hookMethod; // final Object[] args; // // Capture(Object hook, String hookMethod, Object[] args) { // this.hook = hook; // this.hookMethod = hookMethod; // this.args = args; // } // } // // private static final List<Capture> captures = Collections.synchronizedList(new ArrayList<>()); // // private MethodCallCounter() {} // } // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/classes/Fruit.java // public class Fruit { // public static class Orange extends Fruit{} // }
import io.promagent.annotations.After; import io.promagent.annotations.Hook; import io.promagent.hookcontext.MetricsStore; import io.promagent.internal.instrumentationtests.MethodCallCounter; import io.promagent.internal.instrumentationtests.classes.Fruit;
package io.promagent.internal.instrumentationtests.hooks; /** * Test hook with no @Before method. */ @Hook(instruments = "io.promagent.internal.instrumentationtests.classes.ParameterTypesExample") public class OnlyAfterHook {
// Path: promagent-framework/promagent-api/src/main/java/io/promagent/hookcontext/MetricsStore.java // public class MetricsStore { // // private final CollectorRegistry registry; // private final ConcurrentMap<String, Collector> metrics = new ConcurrentHashMap<>(); // // public MetricsStore(CollectorRegistry registry) { // this.registry = registry; // } // // /** // * See {@link MetricsStore} and {@link MetricDef#MetricDef(String, BiFunction)}. // */ // @SuppressWarnings("unchecked") // public <T extends Collector> T createOrGet(MetricDef<T> metricDef) { // return (T) metrics.computeIfAbsent(metricDef.getMetricName(), s -> metricDef.getProducer().apply(metricDef.getMetricName(), registry)); // } // } // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/MethodCallCounter.java // public class MethodCallCounter { // // public static void reset() { // captures.clear(); // } // // public static void observe(Object hook, String methodName, Object... args) { // captures.add(new Capture(hook, methodName, args)); // } // // public static void assertNumCalls(int expectedNumberOfCalls, Class<?> hookClass, String hookMethod, Object... expectedArgs) { // List<Capture> matching = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .filter(c -> c.hookMethod.equals(hookMethod)) // .filter(c -> Arrays.equals(expectedArgs, c.args)) // .collect(Collectors.toList()); // Assertions.assertEquals(expectedNumberOfCalls, matching.size()); // } // // // special case for the varargsMixed test // public static void assertNumCalls(int expectedNumberOfCalls, Class<?> hookClass, String hookMethod, String firstString, String... moreStrings) { // List<Capture> matching = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .filter(c -> c.hookMethod.equals(hookMethod)) // .filter(c -> c.args.length == 2) // .filter(c -> Objects.equals(firstString, c.args[0])) // .filter(c -> Arrays.equals(moreStrings, (String[]) c.args[1])) // .collect(Collectors.toList()); // Assertions.assertEquals(expectedNumberOfCalls, matching.size()); // } // // public static void assertNumHookInstances(int expectedNumberOfInstances, Class<?> hookClass) { // long actualNumberOfInstances = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .map(c -> c.hook) // .distinct() // .count(); // Assertions.assertEquals(expectedNumberOfInstances, (int) actualNumberOfInstances); // } // // private static class Capture { // final Object hook; // final String hookMethod; // final Object[] args; // // Capture(Object hook, String hookMethod, Object[] args) { // this.hook = hook; // this.hookMethod = hookMethod; // this.args = args; // } // } // // private static final List<Capture> captures = Collections.synchronizedList(new ArrayList<>()); // // private MethodCallCounter() {} // } // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/classes/Fruit.java // public class Fruit { // public static class Orange extends Fruit{} // } // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/hooks/OnlyAfterHook.java import io.promagent.annotations.After; import io.promagent.annotations.Hook; import io.promagent.hookcontext.MetricsStore; import io.promagent.internal.instrumentationtests.MethodCallCounter; import io.promagent.internal.instrumentationtests.classes.Fruit; package io.promagent.internal.instrumentationtests.hooks; /** * Test hook with no @Before method. */ @Hook(instruments = "io.promagent.internal.instrumentationtests.classes.ParameterTypesExample") public class OnlyAfterHook {
public OnlyAfterHook(MetricsStore m) {}
fstab/promagent
promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/hooks/OnlyAfterHook.java
// Path: promagent-framework/promagent-api/src/main/java/io/promagent/hookcontext/MetricsStore.java // public class MetricsStore { // // private final CollectorRegistry registry; // private final ConcurrentMap<String, Collector> metrics = new ConcurrentHashMap<>(); // // public MetricsStore(CollectorRegistry registry) { // this.registry = registry; // } // // /** // * See {@link MetricsStore} and {@link MetricDef#MetricDef(String, BiFunction)}. // */ // @SuppressWarnings("unchecked") // public <T extends Collector> T createOrGet(MetricDef<T> metricDef) { // return (T) metrics.computeIfAbsent(metricDef.getMetricName(), s -> metricDef.getProducer().apply(metricDef.getMetricName(), registry)); // } // } // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/MethodCallCounter.java // public class MethodCallCounter { // // public static void reset() { // captures.clear(); // } // // public static void observe(Object hook, String methodName, Object... args) { // captures.add(new Capture(hook, methodName, args)); // } // // public static void assertNumCalls(int expectedNumberOfCalls, Class<?> hookClass, String hookMethod, Object... expectedArgs) { // List<Capture> matching = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .filter(c -> c.hookMethod.equals(hookMethod)) // .filter(c -> Arrays.equals(expectedArgs, c.args)) // .collect(Collectors.toList()); // Assertions.assertEquals(expectedNumberOfCalls, matching.size()); // } // // // special case for the varargsMixed test // public static void assertNumCalls(int expectedNumberOfCalls, Class<?> hookClass, String hookMethod, String firstString, String... moreStrings) { // List<Capture> matching = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .filter(c -> c.hookMethod.equals(hookMethod)) // .filter(c -> c.args.length == 2) // .filter(c -> Objects.equals(firstString, c.args[0])) // .filter(c -> Arrays.equals(moreStrings, (String[]) c.args[1])) // .collect(Collectors.toList()); // Assertions.assertEquals(expectedNumberOfCalls, matching.size()); // } // // public static void assertNumHookInstances(int expectedNumberOfInstances, Class<?> hookClass) { // long actualNumberOfInstances = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .map(c -> c.hook) // .distinct() // .count(); // Assertions.assertEquals(expectedNumberOfInstances, (int) actualNumberOfInstances); // } // // private static class Capture { // final Object hook; // final String hookMethod; // final Object[] args; // // Capture(Object hook, String hookMethod, Object[] args) { // this.hook = hook; // this.hookMethod = hookMethod; // this.args = args; // } // } // // private static final List<Capture> captures = Collections.synchronizedList(new ArrayList<>()); // // private MethodCallCounter() {} // } // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/classes/Fruit.java // public class Fruit { // public static class Orange extends Fruit{} // }
import io.promagent.annotations.After; import io.promagent.annotations.Hook; import io.promagent.hookcontext.MetricsStore; import io.promagent.internal.instrumentationtests.MethodCallCounter; import io.promagent.internal.instrumentationtests.classes.Fruit;
package io.promagent.internal.instrumentationtests.hooks; /** * Test hook with no @Before method. */ @Hook(instruments = "io.promagent.internal.instrumentationtests.classes.ParameterTypesExample") public class OnlyAfterHook { public OnlyAfterHook(MetricsStore m) {} @After(method = "objects")
// Path: promagent-framework/promagent-api/src/main/java/io/promagent/hookcontext/MetricsStore.java // public class MetricsStore { // // private final CollectorRegistry registry; // private final ConcurrentMap<String, Collector> metrics = new ConcurrentHashMap<>(); // // public MetricsStore(CollectorRegistry registry) { // this.registry = registry; // } // // /** // * See {@link MetricsStore} and {@link MetricDef#MetricDef(String, BiFunction)}. // */ // @SuppressWarnings("unchecked") // public <T extends Collector> T createOrGet(MetricDef<T> metricDef) { // return (T) metrics.computeIfAbsent(metricDef.getMetricName(), s -> metricDef.getProducer().apply(metricDef.getMetricName(), registry)); // } // } // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/MethodCallCounter.java // public class MethodCallCounter { // // public static void reset() { // captures.clear(); // } // // public static void observe(Object hook, String methodName, Object... args) { // captures.add(new Capture(hook, methodName, args)); // } // // public static void assertNumCalls(int expectedNumberOfCalls, Class<?> hookClass, String hookMethod, Object... expectedArgs) { // List<Capture> matching = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .filter(c -> c.hookMethod.equals(hookMethod)) // .filter(c -> Arrays.equals(expectedArgs, c.args)) // .collect(Collectors.toList()); // Assertions.assertEquals(expectedNumberOfCalls, matching.size()); // } // // // special case for the varargsMixed test // public static void assertNumCalls(int expectedNumberOfCalls, Class<?> hookClass, String hookMethod, String firstString, String... moreStrings) { // List<Capture> matching = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .filter(c -> c.hookMethod.equals(hookMethod)) // .filter(c -> c.args.length == 2) // .filter(c -> Objects.equals(firstString, c.args[0])) // .filter(c -> Arrays.equals(moreStrings, (String[]) c.args[1])) // .collect(Collectors.toList()); // Assertions.assertEquals(expectedNumberOfCalls, matching.size()); // } // // public static void assertNumHookInstances(int expectedNumberOfInstances, Class<?> hookClass) { // long actualNumberOfInstances = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .map(c -> c.hook) // .distinct() // .count(); // Assertions.assertEquals(expectedNumberOfInstances, (int) actualNumberOfInstances); // } // // private static class Capture { // final Object hook; // final String hookMethod; // final Object[] args; // // Capture(Object hook, String hookMethod, Object[] args) { // this.hook = hook; // this.hookMethod = hookMethod; // this.args = args; // } // } // // private static final List<Capture> captures = Collections.synchronizedList(new ArrayList<>()); // // private MethodCallCounter() {} // } // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/classes/Fruit.java // public class Fruit { // public static class Orange extends Fruit{} // } // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/hooks/OnlyAfterHook.java import io.promagent.annotations.After; import io.promagent.annotations.Hook; import io.promagent.hookcontext.MetricsStore; import io.promagent.internal.instrumentationtests.MethodCallCounter; import io.promagent.internal.instrumentationtests.classes.Fruit; package io.promagent.internal.instrumentationtests.hooks; /** * Test hook with no @Before method. */ @Hook(instruments = "io.promagent.internal.instrumentationtests.classes.ParameterTypesExample") public class OnlyAfterHook { public OnlyAfterHook(MetricsStore m) {} @After(method = "objects")
public void after(Object o, Fruit f, Fruit.Orange x) {
fstab/promagent
promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/hooks/OnlyAfterHook.java
// Path: promagent-framework/promagent-api/src/main/java/io/promagent/hookcontext/MetricsStore.java // public class MetricsStore { // // private final CollectorRegistry registry; // private final ConcurrentMap<String, Collector> metrics = new ConcurrentHashMap<>(); // // public MetricsStore(CollectorRegistry registry) { // this.registry = registry; // } // // /** // * See {@link MetricsStore} and {@link MetricDef#MetricDef(String, BiFunction)}. // */ // @SuppressWarnings("unchecked") // public <T extends Collector> T createOrGet(MetricDef<T> metricDef) { // return (T) metrics.computeIfAbsent(metricDef.getMetricName(), s -> metricDef.getProducer().apply(metricDef.getMetricName(), registry)); // } // } // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/MethodCallCounter.java // public class MethodCallCounter { // // public static void reset() { // captures.clear(); // } // // public static void observe(Object hook, String methodName, Object... args) { // captures.add(new Capture(hook, methodName, args)); // } // // public static void assertNumCalls(int expectedNumberOfCalls, Class<?> hookClass, String hookMethod, Object... expectedArgs) { // List<Capture> matching = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .filter(c -> c.hookMethod.equals(hookMethod)) // .filter(c -> Arrays.equals(expectedArgs, c.args)) // .collect(Collectors.toList()); // Assertions.assertEquals(expectedNumberOfCalls, matching.size()); // } // // // special case for the varargsMixed test // public static void assertNumCalls(int expectedNumberOfCalls, Class<?> hookClass, String hookMethod, String firstString, String... moreStrings) { // List<Capture> matching = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .filter(c -> c.hookMethod.equals(hookMethod)) // .filter(c -> c.args.length == 2) // .filter(c -> Objects.equals(firstString, c.args[0])) // .filter(c -> Arrays.equals(moreStrings, (String[]) c.args[1])) // .collect(Collectors.toList()); // Assertions.assertEquals(expectedNumberOfCalls, matching.size()); // } // // public static void assertNumHookInstances(int expectedNumberOfInstances, Class<?> hookClass) { // long actualNumberOfInstances = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .map(c -> c.hook) // .distinct() // .count(); // Assertions.assertEquals(expectedNumberOfInstances, (int) actualNumberOfInstances); // } // // private static class Capture { // final Object hook; // final String hookMethod; // final Object[] args; // // Capture(Object hook, String hookMethod, Object[] args) { // this.hook = hook; // this.hookMethod = hookMethod; // this.args = args; // } // } // // private static final List<Capture> captures = Collections.synchronizedList(new ArrayList<>()); // // private MethodCallCounter() {} // } // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/classes/Fruit.java // public class Fruit { // public static class Orange extends Fruit{} // }
import io.promagent.annotations.After; import io.promagent.annotations.Hook; import io.promagent.hookcontext.MetricsStore; import io.promagent.internal.instrumentationtests.MethodCallCounter; import io.promagent.internal.instrumentationtests.classes.Fruit;
package io.promagent.internal.instrumentationtests.hooks; /** * Test hook with no @Before method. */ @Hook(instruments = "io.promagent.internal.instrumentationtests.classes.ParameterTypesExample") public class OnlyAfterHook { public OnlyAfterHook(MetricsStore m) {} @After(method = "objects") public void after(Object o, Fruit f, Fruit.Orange x) {
// Path: promagent-framework/promagent-api/src/main/java/io/promagent/hookcontext/MetricsStore.java // public class MetricsStore { // // private final CollectorRegistry registry; // private final ConcurrentMap<String, Collector> metrics = new ConcurrentHashMap<>(); // // public MetricsStore(CollectorRegistry registry) { // this.registry = registry; // } // // /** // * See {@link MetricsStore} and {@link MetricDef#MetricDef(String, BiFunction)}. // */ // @SuppressWarnings("unchecked") // public <T extends Collector> T createOrGet(MetricDef<T> metricDef) { // return (T) metrics.computeIfAbsent(metricDef.getMetricName(), s -> metricDef.getProducer().apply(metricDef.getMetricName(), registry)); // } // } // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/MethodCallCounter.java // public class MethodCallCounter { // // public static void reset() { // captures.clear(); // } // // public static void observe(Object hook, String methodName, Object... args) { // captures.add(new Capture(hook, methodName, args)); // } // // public static void assertNumCalls(int expectedNumberOfCalls, Class<?> hookClass, String hookMethod, Object... expectedArgs) { // List<Capture> matching = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .filter(c -> c.hookMethod.equals(hookMethod)) // .filter(c -> Arrays.equals(expectedArgs, c.args)) // .collect(Collectors.toList()); // Assertions.assertEquals(expectedNumberOfCalls, matching.size()); // } // // // special case for the varargsMixed test // public static void assertNumCalls(int expectedNumberOfCalls, Class<?> hookClass, String hookMethod, String firstString, String... moreStrings) { // List<Capture> matching = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .filter(c -> c.hookMethod.equals(hookMethod)) // .filter(c -> c.args.length == 2) // .filter(c -> Objects.equals(firstString, c.args[0])) // .filter(c -> Arrays.equals(moreStrings, (String[]) c.args[1])) // .collect(Collectors.toList()); // Assertions.assertEquals(expectedNumberOfCalls, matching.size()); // } // // public static void assertNumHookInstances(int expectedNumberOfInstances, Class<?> hookClass) { // long actualNumberOfInstances = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .map(c -> c.hook) // .distinct() // .count(); // Assertions.assertEquals(expectedNumberOfInstances, (int) actualNumberOfInstances); // } // // private static class Capture { // final Object hook; // final String hookMethod; // final Object[] args; // // Capture(Object hook, String hookMethod, Object[] args) { // this.hook = hook; // this.hookMethod = hookMethod; // this.args = args; // } // } // // private static final List<Capture> captures = Collections.synchronizedList(new ArrayList<>()); // // private MethodCallCounter() {} // } // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/classes/Fruit.java // public class Fruit { // public static class Orange extends Fruit{} // } // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/hooks/OnlyAfterHook.java import io.promagent.annotations.After; import io.promagent.annotations.Hook; import io.promagent.hookcontext.MetricsStore; import io.promagent.internal.instrumentationtests.MethodCallCounter; import io.promagent.internal.instrumentationtests.classes.Fruit; package io.promagent.internal.instrumentationtests.hooks; /** * Test hook with no @Before method. */ @Hook(instruments = "io.promagent.internal.instrumentationtests.classes.ParameterTypesExample") public class OnlyAfterHook { public OnlyAfterHook(MetricsStore m) {} @After(method = "objects") public void after(Object o, Fruit f, Fruit.Orange x) {
MethodCallCounter.observe(this, "after", o, f, x);
fstab/promagent
promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/hooks/StaticFinalTestHook.java
// Path: promagent-framework/promagent-api/src/main/java/io/promagent/hookcontext/MetricsStore.java // public class MetricsStore { // // private final CollectorRegistry registry; // private final ConcurrentMap<String, Collector> metrics = new ConcurrentHashMap<>(); // // public MetricsStore(CollectorRegistry registry) { // this.registry = registry; // } // // /** // * See {@link MetricsStore} and {@link MetricDef#MetricDef(String, BiFunction)}. // */ // @SuppressWarnings("unchecked") // public <T extends Collector> T createOrGet(MetricDef<T> metricDef) { // return (T) metrics.computeIfAbsent(metricDef.getMetricName(), s -> metricDef.getProducer().apply(metricDef.getMetricName(), registry)); // } // } // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/MethodCallCounter.java // public class MethodCallCounter { // // public static void reset() { // captures.clear(); // } // // public static void observe(Object hook, String methodName, Object... args) { // captures.add(new Capture(hook, methodName, args)); // } // // public static void assertNumCalls(int expectedNumberOfCalls, Class<?> hookClass, String hookMethod, Object... expectedArgs) { // List<Capture> matching = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .filter(c -> c.hookMethod.equals(hookMethod)) // .filter(c -> Arrays.equals(expectedArgs, c.args)) // .collect(Collectors.toList()); // Assertions.assertEquals(expectedNumberOfCalls, matching.size()); // } // // // special case for the varargsMixed test // public static void assertNumCalls(int expectedNumberOfCalls, Class<?> hookClass, String hookMethod, String firstString, String... moreStrings) { // List<Capture> matching = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .filter(c -> c.hookMethod.equals(hookMethod)) // .filter(c -> c.args.length == 2) // .filter(c -> Objects.equals(firstString, c.args[0])) // .filter(c -> Arrays.equals(moreStrings, (String[]) c.args[1])) // .collect(Collectors.toList()); // Assertions.assertEquals(expectedNumberOfCalls, matching.size()); // } // // public static void assertNumHookInstances(int expectedNumberOfInstances, Class<?> hookClass) { // long actualNumberOfInstances = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .map(c -> c.hook) // .distinct() // .count(); // Assertions.assertEquals(expectedNumberOfInstances, (int) actualNumberOfInstances); // } // // private static class Capture { // final Object hook; // final String hookMethod; // final Object[] args; // // Capture(Object hook, String hookMethod, Object[] args) { // this.hook = hook; // this.hookMethod = hookMethod; // this.args = args; // } // } // // private static final List<Capture> captures = Collections.synchronizedList(new ArrayList<>()); // // private MethodCallCounter() {} // }
import io.promagent.annotations.After; import io.promagent.annotations.Before; import io.promagent.annotations.Hook; import io.promagent.hookcontext.MetricsStore; import io.promagent.internal.instrumentationtests.MethodCallCounter;
package io.promagent.internal.instrumentationtests.hooks; @Hook(instruments = "io.promagent.internal.instrumentationtests.classes.StaticFinalExample") public class StaticFinalTestHook {
// Path: promagent-framework/promagent-api/src/main/java/io/promagent/hookcontext/MetricsStore.java // public class MetricsStore { // // private final CollectorRegistry registry; // private final ConcurrentMap<String, Collector> metrics = new ConcurrentHashMap<>(); // // public MetricsStore(CollectorRegistry registry) { // this.registry = registry; // } // // /** // * See {@link MetricsStore} and {@link MetricDef#MetricDef(String, BiFunction)}. // */ // @SuppressWarnings("unchecked") // public <T extends Collector> T createOrGet(MetricDef<T> metricDef) { // return (T) metrics.computeIfAbsent(metricDef.getMetricName(), s -> metricDef.getProducer().apply(metricDef.getMetricName(), registry)); // } // } // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/MethodCallCounter.java // public class MethodCallCounter { // // public static void reset() { // captures.clear(); // } // // public static void observe(Object hook, String methodName, Object... args) { // captures.add(new Capture(hook, methodName, args)); // } // // public static void assertNumCalls(int expectedNumberOfCalls, Class<?> hookClass, String hookMethod, Object... expectedArgs) { // List<Capture> matching = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .filter(c -> c.hookMethod.equals(hookMethod)) // .filter(c -> Arrays.equals(expectedArgs, c.args)) // .collect(Collectors.toList()); // Assertions.assertEquals(expectedNumberOfCalls, matching.size()); // } // // // special case for the varargsMixed test // public static void assertNumCalls(int expectedNumberOfCalls, Class<?> hookClass, String hookMethod, String firstString, String... moreStrings) { // List<Capture> matching = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .filter(c -> c.hookMethod.equals(hookMethod)) // .filter(c -> c.args.length == 2) // .filter(c -> Objects.equals(firstString, c.args[0])) // .filter(c -> Arrays.equals(moreStrings, (String[]) c.args[1])) // .collect(Collectors.toList()); // Assertions.assertEquals(expectedNumberOfCalls, matching.size()); // } // // public static void assertNumHookInstances(int expectedNumberOfInstances, Class<?> hookClass) { // long actualNumberOfInstances = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .map(c -> c.hook) // .distinct() // .count(); // Assertions.assertEquals(expectedNumberOfInstances, (int) actualNumberOfInstances); // } // // private static class Capture { // final Object hook; // final String hookMethod; // final Object[] args; // // Capture(Object hook, String hookMethod, Object[] args) { // this.hook = hook; // this.hookMethod = hookMethod; // this.args = args; // } // } // // private static final List<Capture> captures = Collections.synchronizedList(new ArrayList<>()); // // private MethodCallCounter() {} // } // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/hooks/StaticFinalTestHook.java import io.promagent.annotations.After; import io.promagent.annotations.Before; import io.promagent.annotations.Hook; import io.promagent.hookcontext.MetricsStore; import io.promagent.internal.instrumentationtests.MethodCallCounter; package io.promagent.internal.instrumentationtests.hooks; @Hook(instruments = "io.promagent.internal.instrumentationtests.classes.StaticFinalExample") public class StaticFinalTestHook {
public StaticFinalTestHook(MetricsStore m) {}
fstab/promagent
promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/hooks/StaticFinalTestHook.java
// Path: promagent-framework/promagent-api/src/main/java/io/promagent/hookcontext/MetricsStore.java // public class MetricsStore { // // private final CollectorRegistry registry; // private final ConcurrentMap<String, Collector> metrics = new ConcurrentHashMap<>(); // // public MetricsStore(CollectorRegistry registry) { // this.registry = registry; // } // // /** // * See {@link MetricsStore} and {@link MetricDef#MetricDef(String, BiFunction)}. // */ // @SuppressWarnings("unchecked") // public <T extends Collector> T createOrGet(MetricDef<T> metricDef) { // return (T) metrics.computeIfAbsent(metricDef.getMetricName(), s -> metricDef.getProducer().apply(metricDef.getMetricName(), registry)); // } // } // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/MethodCallCounter.java // public class MethodCallCounter { // // public static void reset() { // captures.clear(); // } // // public static void observe(Object hook, String methodName, Object... args) { // captures.add(new Capture(hook, methodName, args)); // } // // public static void assertNumCalls(int expectedNumberOfCalls, Class<?> hookClass, String hookMethod, Object... expectedArgs) { // List<Capture> matching = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .filter(c -> c.hookMethod.equals(hookMethod)) // .filter(c -> Arrays.equals(expectedArgs, c.args)) // .collect(Collectors.toList()); // Assertions.assertEquals(expectedNumberOfCalls, matching.size()); // } // // // special case for the varargsMixed test // public static void assertNumCalls(int expectedNumberOfCalls, Class<?> hookClass, String hookMethod, String firstString, String... moreStrings) { // List<Capture> matching = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .filter(c -> c.hookMethod.equals(hookMethod)) // .filter(c -> c.args.length == 2) // .filter(c -> Objects.equals(firstString, c.args[0])) // .filter(c -> Arrays.equals(moreStrings, (String[]) c.args[1])) // .collect(Collectors.toList()); // Assertions.assertEquals(expectedNumberOfCalls, matching.size()); // } // // public static void assertNumHookInstances(int expectedNumberOfInstances, Class<?> hookClass) { // long actualNumberOfInstances = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .map(c -> c.hook) // .distinct() // .count(); // Assertions.assertEquals(expectedNumberOfInstances, (int) actualNumberOfInstances); // } // // private static class Capture { // final Object hook; // final String hookMethod; // final Object[] args; // // Capture(Object hook, String hookMethod, Object[] args) { // this.hook = hook; // this.hookMethod = hookMethod; // this.args = args; // } // } // // private static final List<Capture> captures = Collections.synchronizedList(new ArrayList<>()); // // private MethodCallCounter() {} // }
import io.promagent.annotations.After; import io.promagent.annotations.Before; import io.promagent.annotations.Hook; import io.promagent.hookcontext.MetricsStore; import io.promagent.internal.instrumentationtests.MethodCallCounter;
package io.promagent.internal.instrumentationtests.hooks; @Hook(instruments = "io.promagent.internal.instrumentationtests.classes.StaticFinalExample") public class StaticFinalTestHook { public StaticFinalTestHook(MetricsStore m) {} @Before(method = { "helloPublic", "helloPublicFinal", "helloPublicStatic", "helloPublicStaticFinal" }) public void before(String name) {
// Path: promagent-framework/promagent-api/src/main/java/io/promagent/hookcontext/MetricsStore.java // public class MetricsStore { // // private final CollectorRegistry registry; // private final ConcurrentMap<String, Collector> metrics = new ConcurrentHashMap<>(); // // public MetricsStore(CollectorRegistry registry) { // this.registry = registry; // } // // /** // * See {@link MetricsStore} and {@link MetricDef#MetricDef(String, BiFunction)}. // */ // @SuppressWarnings("unchecked") // public <T extends Collector> T createOrGet(MetricDef<T> metricDef) { // return (T) metrics.computeIfAbsent(metricDef.getMetricName(), s -> metricDef.getProducer().apply(metricDef.getMetricName(), registry)); // } // } // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/MethodCallCounter.java // public class MethodCallCounter { // // public static void reset() { // captures.clear(); // } // // public static void observe(Object hook, String methodName, Object... args) { // captures.add(new Capture(hook, methodName, args)); // } // // public static void assertNumCalls(int expectedNumberOfCalls, Class<?> hookClass, String hookMethod, Object... expectedArgs) { // List<Capture> matching = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .filter(c -> c.hookMethod.equals(hookMethod)) // .filter(c -> Arrays.equals(expectedArgs, c.args)) // .collect(Collectors.toList()); // Assertions.assertEquals(expectedNumberOfCalls, matching.size()); // } // // // special case for the varargsMixed test // public static void assertNumCalls(int expectedNumberOfCalls, Class<?> hookClass, String hookMethod, String firstString, String... moreStrings) { // List<Capture> matching = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .filter(c -> c.hookMethod.equals(hookMethod)) // .filter(c -> c.args.length == 2) // .filter(c -> Objects.equals(firstString, c.args[0])) // .filter(c -> Arrays.equals(moreStrings, (String[]) c.args[1])) // .collect(Collectors.toList()); // Assertions.assertEquals(expectedNumberOfCalls, matching.size()); // } // // public static void assertNumHookInstances(int expectedNumberOfInstances, Class<?> hookClass) { // long actualNumberOfInstances = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .map(c -> c.hook) // .distinct() // .count(); // Assertions.assertEquals(expectedNumberOfInstances, (int) actualNumberOfInstances); // } // // private static class Capture { // final Object hook; // final String hookMethod; // final Object[] args; // // Capture(Object hook, String hookMethod, Object[] args) { // this.hook = hook; // this.hookMethod = hookMethod; // this.args = args; // } // } // // private static final List<Capture> captures = Collections.synchronizedList(new ArrayList<>()); // // private MethodCallCounter() {} // } // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/hooks/StaticFinalTestHook.java import io.promagent.annotations.After; import io.promagent.annotations.Before; import io.promagent.annotations.Hook; import io.promagent.hookcontext.MetricsStore; import io.promagent.internal.instrumentationtests.MethodCallCounter; package io.promagent.internal.instrumentationtests.hooks; @Hook(instruments = "io.promagent.internal.instrumentationtests.classes.StaticFinalExample") public class StaticFinalTestHook { public StaticFinalTestHook(MetricsStore m) {} @Before(method = { "helloPublic", "helloPublicFinal", "helloPublicStatic", "helloPublicStaticFinal" }) public void before(String name) {
MethodCallCounter.observe(this, "before", name);
fstab/promagent
promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/hooks/LifecycleHookSkipTrue.java
// Path: promagent-framework/promagent-api/src/main/java/io/promagent/hookcontext/MetricsStore.java // public class MetricsStore { // // private final CollectorRegistry registry; // private final ConcurrentMap<String, Collector> metrics = new ConcurrentHashMap<>(); // // public MetricsStore(CollectorRegistry registry) { // this.registry = registry; // } // // /** // * See {@link MetricsStore} and {@link MetricDef#MetricDef(String, BiFunction)}. // */ // @SuppressWarnings("unchecked") // public <T extends Collector> T createOrGet(MetricDef<T> metricDef) { // return (T) metrics.computeIfAbsent(metricDef.getMetricName(), s -> metricDef.getProducer().apply(metricDef.getMetricName(), registry)); // } // } // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/MethodCallCounter.java // public class MethodCallCounter { // // public static void reset() { // captures.clear(); // } // // public static void observe(Object hook, String methodName, Object... args) { // captures.add(new Capture(hook, methodName, args)); // } // // public static void assertNumCalls(int expectedNumberOfCalls, Class<?> hookClass, String hookMethod, Object... expectedArgs) { // List<Capture> matching = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .filter(c -> c.hookMethod.equals(hookMethod)) // .filter(c -> Arrays.equals(expectedArgs, c.args)) // .collect(Collectors.toList()); // Assertions.assertEquals(expectedNumberOfCalls, matching.size()); // } // // // special case for the varargsMixed test // public static void assertNumCalls(int expectedNumberOfCalls, Class<?> hookClass, String hookMethod, String firstString, String... moreStrings) { // List<Capture> matching = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .filter(c -> c.hookMethod.equals(hookMethod)) // .filter(c -> c.args.length == 2) // .filter(c -> Objects.equals(firstString, c.args[0])) // .filter(c -> Arrays.equals(moreStrings, (String[]) c.args[1])) // .collect(Collectors.toList()); // Assertions.assertEquals(expectedNumberOfCalls, matching.size()); // } // // public static void assertNumHookInstances(int expectedNumberOfInstances, Class<?> hookClass) { // long actualNumberOfInstances = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .map(c -> c.hook) // .distinct() // .count(); // Assertions.assertEquals(expectedNumberOfInstances, (int) actualNumberOfInstances); // } // // private static class Capture { // final Object hook; // final String hookMethod; // final Object[] args; // // Capture(Object hook, String hookMethod, Object[] args) { // this.hook = hook; // this.hookMethod = hookMethod; // this.args = args; // } // } // // private static final List<Capture> captures = Collections.synchronizedList(new ArrayList<>()); // // private MethodCallCounter() {} // } // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/classes/Fruit.java // public class Fruit { // public static class Orange extends Fruit{} // } // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/classes/Fruit.java // public static class Orange extends Fruit{} // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/classes/ParameterTypesExample.java // public class ParameterTypesExample implements IParameterTypesExample { // // @Override // public void noParam() {} // // @Override // public void primitiveTypes(byte b, short s, int i, long l, float f, double d, boolean x, char c) {} // // @Override // public void boxedTypes(Byte b, Short s, Integer i, Long l, Float f, Double d, Boolean x, Character c) {} // // @Override // public void objects(Object o, Fruit f, Fruit.Orange x) {} // // @Override // public void primitiveArrays(byte[] b, short[] s, int[] i, long[] l, float[] f, double[] d, boolean[] x, char[] c) {} // // @Override // public void boxedArrays(Byte[] b, Short[] s, Integer[] i, Long[] l, Float[] f, Double[] d, Boolean[] x, Character[] c) {} // // @Override // public void objectArrays(Object[] o, Fruit[] f, Fruit.Orange[] x) {} // // @Override // public void generics(List<Object> objectList, List<Fruit> fruitList, List<Fruit.Orange> orangeList) {} // // @Override // public void varargsExplicit(Object... args) {} // // @Override // public void varargsImplicit(Object[] args) {} // // @Override // public void varargsMixed(String s, String... more) {} // // @Override // public void recursive(int nRecursiveCalls) { // if (nRecursiveCalls > 0) { // recursive(nRecursiveCalls - 1); // } // } // }
import io.promagent.annotations.After; import io.promagent.annotations.Before; import io.promagent.annotations.Hook; import io.promagent.hookcontext.MetricsStore; import io.promagent.internal.instrumentationtests.MethodCallCounter; import io.promagent.internal.instrumentationtests.classes.Fruit; import io.promagent.internal.instrumentationtests.classes.Fruit.Orange; import io.promagent.internal.instrumentationtests.classes.ParameterTypesExample; import java.util.List;
package io.promagent.internal.instrumentationtests.hooks; /** * Instrument all methods in {@link ParameterTypesExample}. */ @Hook( instruments = "io.promagent.internal.instrumentationtests.classes.ParameterTypesExample", skipNestedCalls = true ) public class LifecycleHookSkipTrue {
// Path: promagent-framework/promagent-api/src/main/java/io/promagent/hookcontext/MetricsStore.java // public class MetricsStore { // // private final CollectorRegistry registry; // private final ConcurrentMap<String, Collector> metrics = new ConcurrentHashMap<>(); // // public MetricsStore(CollectorRegistry registry) { // this.registry = registry; // } // // /** // * See {@link MetricsStore} and {@link MetricDef#MetricDef(String, BiFunction)}. // */ // @SuppressWarnings("unchecked") // public <T extends Collector> T createOrGet(MetricDef<T> metricDef) { // return (T) metrics.computeIfAbsent(metricDef.getMetricName(), s -> metricDef.getProducer().apply(metricDef.getMetricName(), registry)); // } // } // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/MethodCallCounter.java // public class MethodCallCounter { // // public static void reset() { // captures.clear(); // } // // public static void observe(Object hook, String methodName, Object... args) { // captures.add(new Capture(hook, methodName, args)); // } // // public static void assertNumCalls(int expectedNumberOfCalls, Class<?> hookClass, String hookMethod, Object... expectedArgs) { // List<Capture> matching = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .filter(c -> c.hookMethod.equals(hookMethod)) // .filter(c -> Arrays.equals(expectedArgs, c.args)) // .collect(Collectors.toList()); // Assertions.assertEquals(expectedNumberOfCalls, matching.size()); // } // // // special case for the varargsMixed test // public static void assertNumCalls(int expectedNumberOfCalls, Class<?> hookClass, String hookMethod, String firstString, String... moreStrings) { // List<Capture> matching = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .filter(c -> c.hookMethod.equals(hookMethod)) // .filter(c -> c.args.length == 2) // .filter(c -> Objects.equals(firstString, c.args[0])) // .filter(c -> Arrays.equals(moreStrings, (String[]) c.args[1])) // .collect(Collectors.toList()); // Assertions.assertEquals(expectedNumberOfCalls, matching.size()); // } // // public static void assertNumHookInstances(int expectedNumberOfInstances, Class<?> hookClass) { // long actualNumberOfInstances = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .map(c -> c.hook) // .distinct() // .count(); // Assertions.assertEquals(expectedNumberOfInstances, (int) actualNumberOfInstances); // } // // private static class Capture { // final Object hook; // final String hookMethod; // final Object[] args; // // Capture(Object hook, String hookMethod, Object[] args) { // this.hook = hook; // this.hookMethod = hookMethod; // this.args = args; // } // } // // private static final List<Capture> captures = Collections.synchronizedList(new ArrayList<>()); // // private MethodCallCounter() {} // } // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/classes/Fruit.java // public class Fruit { // public static class Orange extends Fruit{} // } // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/classes/Fruit.java // public static class Orange extends Fruit{} // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/classes/ParameterTypesExample.java // public class ParameterTypesExample implements IParameterTypesExample { // // @Override // public void noParam() {} // // @Override // public void primitiveTypes(byte b, short s, int i, long l, float f, double d, boolean x, char c) {} // // @Override // public void boxedTypes(Byte b, Short s, Integer i, Long l, Float f, Double d, Boolean x, Character c) {} // // @Override // public void objects(Object o, Fruit f, Fruit.Orange x) {} // // @Override // public void primitiveArrays(byte[] b, short[] s, int[] i, long[] l, float[] f, double[] d, boolean[] x, char[] c) {} // // @Override // public void boxedArrays(Byte[] b, Short[] s, Integer[] i, Long[] l, Float[] f, Double[] d, Boolean[] x, Character[] c) {} // // @Override // public void objectArrays(Object[] o, Fruit[] f, Fruit.Orange[] x) {} // // @Override // public void generics(List<Object> objectList, List<Fruit> fruitList, List<Fruit.Orange> orangeList) {} // // @Override // public void varargsExplicit(Object... args) {} // // @Override // public void varargsImplicit(Object[] args) {} // // @Override // public void varargsMixed(String s, String... more) {} // // @Override // public void recursive(int nRecursiveCalls) { // if (nRecursiveCalls > 0) { // recursive(nRecursiveCalls - 1); // } // } // } // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/hooks/LifecycleHookSkipTrue.java import io.promagent.annotations.After; import io.promagent.annotations.Before; import io.promagent.annotations.Hook; import io.promagent.hookcontext.MetricsStore; import io.promagent.internal.instrumentationtests.MethodCallCounter; import io.promagent.internal.instrumentationtests.classes.Fruit; import io.promagent.internal.instrumentationtests.classes.Fruit.Orange; import io.promagent.internal.instrumentationtests.classes.ParameterTypesExample; import java.util.List; package io.promagent.internal.instrumentationtests.hooks; /** * Instrument all methods in {@link ParameterTypesExample}. */ @Hook( instruments = "io.promagent.internal.instrumentationtests.classes.ParameterTypesExample", skipNestedCalls = true ) public class LifecycleHookSkipTrue {
public LifecycleHookSkipTrue(MetricsStore m) {}
fstab/promagent
promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/hooks/LifecycleHookSkipTrue.java
// Path: promagent-framework/promagent-api/src/main/java/io/promagent/hookcontext/MetricsStore.java // public class MetricsStore { // // private final CollectorRegistry registry; // private final ConcurrentMap<String, Collector> metrics = new ConcurrentHashMap<>(); // // public MetricsStore(CollectorRegistry registry) { // this.registry = registry; // } // // /** // * See {@link MetricsStore} and {@link MetricDef#MetricDef(String, BiFunction)}. // */ // @SuppressWarnings("unchecked") // public <T extends Collector> T createOrGet(MetricDef<T> metricDef) { // return (T) metrics.computeIfAbsent(metricDef.getMetricName(), s -> metricDef.getProducer().apply(metricDef.getMetricName(), registry)); // } // } // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/MethodCallCounter.java // public class MethodCallCounter { // // public static void reset() { // captures.clear(); // } // // public static void observe(Object hook, String methodName, Object... args) { // captures.add(new Capture(hook, methodName, args)); // } // // public static void assertNumCalls(int expectedNumberOfCalls, Class<?> hookClass, String hookMethod, Object... expectedArgs) { // List<Capture> matching = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .filter(c -> c.hookMethod.equals(hookMethod)) // .filter(c -> Arrays.equals(expectedArgs, c.args)) // .collect(Collectors.toList()); // Assertions.assertEquals(expectedNumberOfCalls, matching.size()); // } // // // special case for the varargsMixed test // public static void assertNumCalls(int expectedNumberOfCalls, Class<?> hookClass, String hookMethod, String firstString, String... moreStrings) { // List<Capture> matching = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .filter(c -> c.hookMethod.equals(hookMethod)) // .filter(c -> c.args.length == 2) // .filter(c -> Objects.equals(firstString, c.args[0])) // .filter(c -> Arrays.equals(moreStrings, (String[]) c.args[1])) // .collect(Collectors.toList()); // Assertions.assertEquals(expectedNumberOfCalls, matching.size()); // } // // public static void assertNumHookInstances(int expectedNumberOfInstances, Class<?> hookClass) { // long actualNumberOfInstances = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .map(c -> c.hook) // .distinct() // .count(); // Assertions.assertEquals(expectedNumberOfInstances, (int) actualNumberOfInstances); // } // // private static class Capture { // final Object hook; // final String hookMethod; // final Object[] args; // // Capture(Object hook, String hookMethod, Object[] args) { // this.hook = hook; // this.hookMethod = hookMethod; // this.args = args; // } // } // // private static final List<Capture> captures = Collections.synchronizedList(new ArrayList<>()); // // private MethodCallCounter() {} // } // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/classes/Fruit.java // public class Fruit { // public static class Orange extends Fruit{} // } // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/classes/Fruit.java // public static class Orange extends Fruit{} // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/classes/ParameterTypesExample.java // public class ParameterTypesExample implements IParameterTypesExample { // // @Override // public void noParam() {} // // @Override // public void primitiveTypes(byte b, short s, int i, long l, float f, double d, boolean x, char c) {} // // @Override // public void boxedTypes(Byte b, Short s, Integer i, Long l, Float f, Double d, Boolean x, Character c) {} // // @Override // public void objects(Object o, Fruit f, Fruit.Orange x) {} // // @Override // public void primitiveArrays(byte[] b, short[] s, int[] i, long[] l, float[] f, double[] d, boolean[] x, char[] c) {} // // @Override // public void boxedArrays(Byte[] b, Short[] s, Integer[] i, Long[] l, Float[] f, Double[] d, Boolean[] x, Character[] c) {} // // @Override // public void objectArrays(Object[] o, Fruit[] f, Fruit.Orange[] x) {} // // @Override // public void generics(List<Object> objectList, List<Fruit> fruitList, List<Fruit.Orange> orangeList) {} // // @Override // public void varargsExplicit(Object... args) {} // // @Override // public void varargsImplicit(Object[] args) {} // // @Override // public void varargsMixed(String s, String... more) {} // // @Override // public void recursive(int nRecursiveCalls) { // if (nRecursiveCalls > 0) { // recursive(nRecursiveCalls - 1); // } // } // }
import io.promagent.annotations.After; import io.promagent.annotations.Before; import io.promagent.annotations.Hook; import io.promagent.hookcontext.MetricsStore; import io.promagent.internal.instrumentationtests.MethodCallCounter; import io.promagent.internal.instrumentationtests.classes.Fruit; import io.promagent.internal.instrumentationtests.classes.Fruit.Orange; import io.promagent.internal.instrumentationtests.classes.ParameterTypesExample; import java.util.List;
package io.promagent.internal.instrumentationtests.hooks; /** * Instrument all methods in {@link ParameterTypesExample}. */ @Hook( instruments = "io.promagent.internal.instrumentationtests.classes.ParameterTypesExample", skipNestedCalls = true ) public class LifecycleHookSkipTrue { public LifecycleHookSkipTrue(MetricsStore m) {} @Before(method = "recursive") public void before(int n) {
// Path: promagent-framework/promagent-api/src/main/java/io/promagent/hookcontext/MetricsStore.java // public class MetricsStore { // // private final CollectorRegistry registry; // private final ConcurrentMap<String, Collector> metrics = new ConcurrentHashMap<>(); // // public MetricsStore(CollectorRegistry registry) { // this.registry = registry; // } // // /** // * See {@link MetricsStore} and {@link MetricDef#MetricDef(String, BiFunction)}. // */ // @SuppressWarnings("unchecked") // public <T extends Collector> T createOrGet(MetricDef<T> metricDef) { // return (T) metrics.computeIfAbsent(metricDef.getMetricName(), s -> metricDef.getProducer().apply(metricDef.getMetricName(), registry)); // } // } // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/MethodCallCounter.java // public class MethodCallCounter { // // public static void reset() { // captures.clear(); // } // // public static void observe(Object hook, String methodName, Object... args) { // captures.add(new Capture(hook, methodName, args)); // } // // public static void assertNumCalls(int expectedNumberOfCalls, Class<?> hookClass, String hookMethod, Object... expectedArgs) { // List<Capture> matching = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .filter(c -> c.hookMethod.equals(hookMethod)) // .filter(c -> Arrays.equals(expectedArgs, c.args)) // .collect(Collectors.toList()); // Assertions.assertEquals(expectedNumberOfCalls, matching.size()); // } // // // special case for the varargsMixed test // public static void assertNumCalls(int expectedNumberOfCalls, Class<?> hookClass, String hookMethod, String firstString, String... moreStrings) { // List<Capture> matching = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .filter(c -> c.hookMethod.equals(hookMethod)) // .filter(c -> c.args.length == 2) // .filter(c -> Objects.equals(firstString, c.args[0])) // .filter(c -> Arrays.equals(moreStrings, (String[]) c.args[1])) // .collect(Collectors.toList()); // Assertions.assertEquals(expectedNumberOfCalls, matching.size()); // } // // public static void assertNumHookInstances(int expectedNumberOfInstances, Class<?> hookClass) { // long actualNumberOfInstances = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .map(c -> c.hook) // .distinct() // .count(); // Assertions.assertEquals(expectedNumberOfInstances, (int) actualNumberOfInstances); // } // // private static class Capture { // final Object hook; // final String hookMethod; // final Object[] args; // // Capture(Object hook, String hookMethod, Object[] args) { // this.hook = hook; // this.hookMethod = hookMethod; // this.args = args; // } // } // // private static final List<Capture> captures = Collections.synchronizedList(new ArrayList<>()); // // private MethodCallCounter() {} // } // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/classes/Fruit.java // public class Fruit { // public static class Orange extends Fruit{} // } // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/classes/Fruit.java // public static class Orange extends Fruit{} // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/classes/ParameterTypesExample.java // public class ParameterTypesExample implements IParameterTypesExample { // // @Override // public void noParam() {} // // @Override // public void primitiveTypes(byte b, short s, int i, long l, float f, double d, boolean x, char c) {} // // @Override // public void boxedTypes(Byte b, Short s, Integer i, Long l, Float f, Double d, Boolean x, Character c) {} // // @Override // public void objects(Object o, Fruit f, Fruit.Orange x) {} // // @Override // public void primitiveArrays(byte[] b, short[] s, int[] i, long[] l, float[] f, double[] d, boolean[] x, char[] c) {} // // @Override // public void boxedArrays(Byte[] b, Short[] s, Integer[] i, Long[] l, Float[] f, Double[] d, Boolean[] x, Character[] c) {} // // @Override // public void objectArrays(Object[] o, Fruit[] f, Fruit.Orange[] x) {} // // @Override // public void generics(List<Object> objectList, List<Fruit> fruitList, List<Fruit.Orange> orangeList) {} // // @Override // public void varargsExplicit(Object... args) {} // // @Override // public void varargsImplicit(Object[] args) {} // // @Override // public void varargsMixed(String s, String... more) {} // // @Override // public void recursive(int nRecursiveCalls) { // if (nRecursiveCalls > 0) { // recursive(nRecursiveCalls - 1); // } // } // } // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/hooks/LifecycleHookSkipTrue.java import io.promagent.annotations.After; import io.promagent.annotations.Before; import io.promagent.annotations.Hook; import io.promagent.hookcontext.MetricsStore; import io.promagent.internal.instrumentationtests.MethodCallCounter; import io.promagent.internal.instrumentationtests.classes.Fruit; import io.promagent.internal.instrumentationtests.classes.Fruit.Orange; import io.promagent.internal.instrumentationtests.classes.ParameterTypesExample; import java.util.List; package io.promagent.internal.instrumentationtests.hooks; /** * Instrument all methods in {@link ParameterTypesExample}. */ @Hook( instruments = "io.promagent.internal.instrumentationtests.classes.ParameterTypesExample", skipNestedCalls = true ) public class LifecycleHookSkipTrue { public LifecycleHookSkipTrue(MetricsStore m) {} @Before(method = "recursive") public void before(int n) {
MethodCallCounter.observe(this, "before", n);
fstab/promagent
promagent-example/src/main/java/io/promagent/hooks/ServletHook.java
// Path: promagent-framework/promagent-api/src/main/java/io/promagent/hookcontext/MetricDef.java // public class MetricDef<T extends Collector> { // // private final String metricName; // private final BiFunction<String, CollectorRegistry, T> producer; // // /** // * See {@link MetricsStore}. // * @param metricName Name of the Prometheus metric, like <tt>"http_requests_total"</tt>. // * @param producer Function to create a new metric and register it with the registry. // * This function will only be called once, subsequent calls to {@link MetricsStore#createOrGet(MetricDef)} // * will return the previously created metric with the specified name. // * The two parameters are the <i>metricName</i> as specified above, // * and the Prometheus registry where the new metric should be registered. // * For an example see JavaDoc for {@link MetricsStore}. // */ // public MetricDef(String metricName, BiFunction<String, CollectorRegistry, T> producer) { // this.metricName = metricName; // this.producer = producer; // } // // String getMetricName() { // return metricName; // } // // BiFunction<String, CollectorRegistry, T> getProducer() { // return producer; // } // } // // Path: promagent-framework/promagent-api/src/main/java/io/promagent/hookcontext/MetricsStore.java // public class MetricsStore { // // private final CollectorRegistry registry; // private final ConcurrentMap<String, Collector> metrics = new ConcurrentHashMap<>(); // // public MetricsStore(CollectorRegistry registry) { // this.registry = registry; // } // // /** // * See {@link MetricsStore} and {@link MetricDef#MetricDef(String, BiFunction)}. // */ // @SuppressWarnings("unchecked") // public <T extends Collector> T createOrGet(MetricDef<T> metricDef) { // return (T) metrics.computeIfAbsent(metricDef.getMetricName(), s -> metricDef.getProducer().apply(metricDef.getMetricName(), registry)); // } // } // // Path: promagent-example/src/main/java/io/promagent/hooks/HttpContext.java // static final Key<String> HTTP_METHOD = new Key<>(); // // Path: promagent-example/src/main/java/io/promagent/hooks/HttpContext.java // static final Key<String> HTTP_PATH = new Key<>();
import io.promagent.annotations.After; import io.promagent.annotations.Before; import io.promagent.annotations.Hook; import io.promagent.hookcontext.MetricDef; import io.promagent.hookcontext.MetricsStore; import io.prometheus.client.Counter; import io.prometheus.client.Summary; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.concurrent.TimeUnit; import static io.promagent.hooks.HttpContext.HTTP_METHOD; import static io.promagent.hooks.HttpContext.HTTP_PATH;
// Copyright 2017 The Promagent Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package io.promagent.hooks; @Hook(instruments = { "javax.servlet.Servlet", "javax.servlet.Filter" }) public class ServletHook { private final Counter httpRequestsTotal; private final Summary httpRequestsDuration; private long startTime = 0;
// Path: promagent-framework/promagent-api/src/main/java/io/promagent/hookcontext/MetricDef.java // public class MetricDef<T extends Collector> { // // private final String metricName; // private final BiFunction<String, CollectorRegistry, T> producer; // // /** // * See {@link MetricsStore}. // * @param metricName Name of the Prometheus metric, like <tt>"http_requests_total"</tt>. // * @param producer Function to create a new metric and register it with the registry. // * This function will only be called once, subsequent calls to {@link MetricsStore#createOrGet(MetricDef)} // * will return the previously created metric with the specified name. // * The two parameters are the <i>metricName</i> as specified above, // * and the Prometheus registry where the new metric should be registered. // * For an example see JavaDoc for {@link MetricsStore}. // */ // public MetricDef(String metricName, BiFunction<String, CollectorRegistry, T> producer) { // this.metricName = metricName; // this.producer = producer; // } // // String getMetricName() { // return metricName; // } // // BiFunction<String, CollectorRegistry, T> getProducer() { // return producer; // } // } // // Path: promagent-framework/promagent-api/src/main/java/io/promagent/hookcontext/MetricsStore.java // public class MetricsStore { // // private final CollectorRegistry registry; // private final ConcurrentMap<String, Collector> metrics = new ConcurrentHashMap<>(); // // public MetricsStore(CollectorRegistry registry) { // this.registry = registry; // } // // /** // * See {@link MetricsStore} and {@link MetricDef#MetricDef(String, BiFunction)}. // */ // @SuppressWarnings("unchecked") // public <T extends Collector> T createOrGet(MetricDef<T> metricDef) { // return (T) metrics.computeIfAbsent(metricDef.getMetricName(), s -> metricDef.getProducer().apply(metricDef.getMetricName(), registry)); // } // } // // Path: promagent-example/src/main/java/io/promagent/hooks/HttpContext.java // static final Key<String> HTTP_METHOD = new Key<>(); // // Path: promagent-example/src/main/java/io/promagent/hooks/HttpContext.java // static final Key<String> HTTP_PATH = new Key<>(); // Path: promagent-example/src/main/java/io/promagent/hooks/ServletHook.java import io.promagent.annotations.After; import io.promagent.annotations.Before; import io.promagent.annotations.Hook; import io.promagent.hookcontext.MetricDef; import io.promagent.hookcontext.MetricsStore; import io.prometheus.client.Counter; import io.prometheus.client.Summary; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.concurrent.TimeUnit; import static io.promagent.hooks.HttpContext.HTTP_METHOD; import static io.promagent.hooks.HttpContext.HTTP_PATH; // Copyright 2017 The Promagent Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package io.promagent.hooks; @Hook(instruments = { "javax.servlet.Servlet", "javax.servlet.Filter" }) public class ServletHook { private final Counter httpRequestsTotal; private final Summary httpRequestsDuration; private long startTime = 0;
public ServletHook(MetricsStore metricsStore) {
fstab/promagent
promagent-example/src/main/java/io/promagent/hooks/ServletHook.java
// Path: promagent-framework/promagent-api/src/main/java/io/promagent/hookcontext/MetricDef.java // public class MetricDef<T extends Collector> { // // private final String metricName; // private final BiFunction<String, CollectorRegistry, T> producer; // // /** // * See {@link MetricsStore}. // * @param metricName Name of the Prometheus metric, like <tt>"http_requests_total"</tt>. // * @param producer Function to create a new metric and register it with the registry. // * This function will only be called once, subsequent calls to {@link MetricsStore#createOrGet(MetricDef)} // * will return the previously created metric with the specified name. // * The two parameters are the <i>metricName</i> as specified above, // * and the Prometheus registry where the new metric should be registered. // * For an example see JavaDoc for {@link MetricsStore}. // */ // public MetricDef(String metricName, BiFunction<String, CollectorRegistry, T> producer) { // this.metricName = metricName; // this.producer = producer; // } // // String getMetricName() { // return metricName; // } // // BiFunction<String, CollectorRegistry, T> getProducer() { // return producer; // } // } // // Path: promagent-framework/promagent-api/src/main/java/io/promagent/hookcontext/MetricsStore.java // public class MetricsStore { // // private final CollectorRegistry registry; // private final ConcurrentMap<String, Collector> metrics = new ConcurrentHashMap<>(); // // public MetricsStore(CollectorRegistry registry) { // this.registry = registry; // } // // /** // * See {@link MetricsStore} and {@link MetricDef#MetricDef(String, BiFunction)}. // */ // @SuppressWarnings("unchecked") // public <T extends Collector> T createOrGet(MetricDef<T> metricDef) { // return (T) metrics.computeIfAbsent(metricDef.getMetricName(), s -> metricDef.getProducer().apply(metricDef.getMetricName(), registry)); // } // } // // Path: promagent-example/src/main/java/io/promagent/hooks/HttpContext.java // static final Key<String> HTTP_METHOD = new Key<>(); // // Path: promagent-example/src/main/java/io/promagent/hooks/HttpContext.java // static final Key<String> HTTP_PATH = new Key<>();
import io.promagent.annotations.After; import io.promagent.annotations.Before; import io.promagent.annotations.Hook; import io.promagent.hookcontext.MetricDef; import io.promagent.hookcontext.MetricsStore; import io.prometheus.client.Counter; import io.prometheus.client.Summary; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.concurrent.TimeUnit; import static io.promagent.hooks.HttpContext.HTTP_METHOD; import static io.promagent.hooks.HttpContext.HTTP_PATH;
// Copyright 2017 The Promagent Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package io.promagent.hooks; @Hook(instruments = { "javax.servlet.Servlet", "javax.servlet.Filter" }) public class ServletHook { private final Counter httpRequestsTotal; private final Summary httpRequestsDuration; private long startTime = 0; public ServletHook(MetricsStore metricsStore) {
// Path: promagent-framework/promagent-api/src/main/java/io/promagent/hookcontext/MetricDef.java // public class MetricDef<T extends Collector> { // // private final String metricName; // private final BiFunction<String, CollectorRegistry, T> producer; // // /** // * See {@link MetricsStore}. // * @param metricName Name of the Prometheus metric, like <tt>"http_requests_total"</tt>. // * @param producer Function to create a new metric and register it with the registry. // * This function will only be called once, subsequent calls to {@link MetricsStore#createOrGet(MetricDef)} // * will return the previously created metric with the specified name. // * The two parameters are the <i>metricName</i> as specified above, // * and the Prometheus registry where the new metric should be registered. // * For an example see JavaDoc for {@link MetricsStore}. // */ // public MetricDef(String metricName, BiFunction<String, CollectorRegistry, T> producer) { // this.metricName = metricName; // this.producer = producer; // } // // String getMetricName() { // return metricName; // } // // BiFunction<String, CollectorRegistry, T> getProducer() { // return producer; // } // } // // Path: promagent-framework/promagent-api/src/main/java/io/promagent/hookcontext/MetricsStore.java // public class MetricsStore { // // private final CollectorRegistry registry; // private final ConcurrentMap<String, Collector> metrics = new ConcurrentHashMap<>(); // // public MetricsStore(CollectorRegistry registry) { // this.registry = registry; // } // // /** // * See {@link MetricsStore} and {@link MetricDef#MetricDef(String, BiFunction)}. // */ // @SuppressWarnings("unchecked") // public <T extends Collector> T createOrGet(MetricDef<T> metricDef) { // return (T) metrics.computeIfAbsent(metricDef.getMetricName(), s -> metricDef.getProducer().apply(metricDef.getMetricName(), registry)); // } // } // // Path: promagent-example/src/main/java/io/promagent/hooks/HttpContext.java // static final Key<String> HTTP_METHOD = new Key<>(); // // Path: promagent-example/src/main/java/io/promagent/hooks/HttpContext.java // static final Key<String> HTTP_PATH = new Key<>(); // Path: promagent-example/src/main/java/io/promagent/hooks/ServletHook.java import io.promagent.annotations.After; import io.promagent.annotations.Before; import io.promagent.annotations.Hook; import io.promagent.hookcontext.MetricDef; import io.promagent.hookcontext.MetricsStore; import io.prometheus.client.Counter; import io.prometheus.client.Summary; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.concurrent.TimeUnit; import static io.promagent.hooks.HttpContext.HTTP_METHOD; import static io.promagent.hooks.HttpContext.HTTP_PATH; // Copyright 2017 The Promagent Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package io.promagent.hooks; @Hook(instruments = { "javax.servlet.Servlet", "javax.servlet.Filter" }) public class ServletHook { private final Counter httpRequestsTotal; private final Summary httpRequestsDuration; private long startTime = 0; public ServletHook(MetricsStore metricsStore) {
httpRequestsTotal = metricsStore.createOrGet(new MetricDef<>(
fstab/promagent
promagent-example/src/main/java/io/promagent/hooks/ServletHook.java
// Path: promagent-framework/promagent-api/src/main/java/io/promagent/hookcontext/MetricDef.java // public class MetricDef<T extends Collector> { // // private final String metricName; // private final BiFunction<String, CollectorRegistry, T> producer; // // /** // * See {@link MetricsStore}. // * @param metricName Name of the Prometheus metric, like <tt>"http_requests_total"</tt>. // * @param producer Function to create a new metric and register it with the registry. // * This function will only be called once, subsequent calls to {@link MetricsStore#createOrGet(MetricDef)} // * will return the previously created metric with the specified name. // * The two parameters are the <i>metricName</i> as specified above, // * and the Prometheus registry where the new metric should be registered. // * For an example see JavaDoc for {@link MetricsStore}. // */ // public MetricDef(String metricName, BiFunction<String, CollectorRegistry, T> producer) { // this.metricName = metricName; // this.producer = producer; // } // // String getMetricName() { // return metricName; // } // // BiFunction<String, CollectorRegistry, T> getProducer() { // return producer; // } // } // // Path: promagent-framework/promagent-api/src/main/java/io/promagent/hookcontext/MetricsStore.java // public class MetricsStore { // // private final CollectorRegistry registry; // private final ConcurrentMap<String, Collector> metrics = new ConcurrentHashMap<>(); // // public MetricsStore(CollectorRegistry registry) { // this.registry = registry; // } // // /** // * See {@link MetricsStore} and {@link MetricDef#MetricDef(String, BiFunction)}. // */ // @SuppressWarnings("unchecked") // public <T extends Collector> T createOrGet(MetricDef<T> metricDef) { // return (T) metrics.computeIfAbsent(metricDef.getMetricName(), s -> metricDef.getProducer().apply(metricDef.getMetricName(), registry)); // } // } // // Path: promagent-example/src/main/java/io/promagent/hooks/HttpContext.java // static final Key<String> HTTP_METHOD = new Key<>(); // // Path: promagent-example/src/main/java/io/promagent/hooks/HttpContext.java // static final Key<String> HTTP_PATH = new Key<>();
import io.promagent.annotations.After; import io.promagent.annotations.Before; import io.promagent.annotations.Hook; import io.promagent.hookcontext.MetricDef; import io.promagent.hookcontext.MetricsStore; import io.prometheus.client.Counter; import io.prometheus.client.Summary; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.concurrent.TimeUnit; import static io.promagent.hooks.HttpContext.HTTP_METHOD; import static io.promagent.hooks.HttpContext.HTTP_PATH;
private String stripPathParameters(String path) { // The URL path may include path parameters. // For example, REST URLs for querying an item might look like this: // // /item/1 // /item/2 // /item/3 // etc. // // We don't want to create a new Prometheus label for each of these paths. // Rather, we want a single label like this: // // /item/{id} // // This method replaces path parameters with placeholders. It is application specific and // should be adapted depending on the actual paths in an application. // For the demo, we just replace all numbers with {id}. return path .replaceAll("/[0-9]+", "/{id}") .replaceAll("/;jsessionid=\\w*", "") .replaceAll("/$", "") .replaceAll("\\?.*", ""); // Also remove path parameters, like "?jsessionid=..." } @Before(method = {"service", "doFilter"}) public void before(ServletRequest request, ServletResponse response) { if (HttpServletRequest.class.isAssignableFrom(request.getClass()) && HttpServletResponse.class.isAssignableFrom(response.getClass())) { HttpServletRequest req = (HttpServletRequest) request;
// Path: promagent-framework/promagent-api/src/main/java/io/promagent/hookcontext/MetricDef.java // public class MetricDef<T extends Collector> { // // private final String metricName; // private final BiFunction<String, CollectorRegistry, T> producer; // // /** // * See {@link MetricsStore}. // * @param metricName Name of the Prometheus metric, like <tt>"http_requests_total"</tt>. // * @param producer Function to create a new metric and register it with the registry. // * This function will only be called once, subsequent calls to {@link MetricsStore#createOrGet(MetricDef)} // * will return the previously created metric with the specified name. // * The two parameters are the <i>metricName</i> as specified above, // * and the Prometheus registry where the new metric should be registered. // * For an example see JavaDoc for {@link MetricsStore}. // */ // public MetricDef(String metricName, BiFunction<String, CollectorRegistry, T> producer) { // this.metricName = metricName; // this.producer = producer; // } // // String getMetricName() { // return metricName; // } // // BiFunction<String, CollectorRegistry, T> getProducer() { // return producer; // } // } // // Path: promagent-framework/promagent-api/src/main/java/io/promagent/hookcontext/MetricsStore.java // public class MetricsStore { // // private final CollectorRegistry registry; // private final ConcurrentMap<String, Collector> metrics = new ConcurrentHashMap<>(); // // public MetricsStore(CollectorRegistry registry) { // this.registry = registry; // } // // /** // * See {@link MetricsStore} and {@link MetricDef#MetricDef(String, BiFunction)}. // */ // @SuppressWarnings("unchecked") // public <T extends Collector> T createOrGet(MetricDef<T> metricDef) { // return (T) metrics.computeIfAbsent(metricDef.getMetricName(), s -> metricDef.getProducer().apply(metricDef.getMetricName(), registry)); // } // } // // Path: promagent-example/src/main/java/io/promagent/hooks/HttpContext.java // static final Key<String> HTTP_METHOD = new Key<>(); // // Path: promagent-example/src/main/java/io/promagent/hooks/HttpContext.java // static final Key<String> HTTP_PATH = new Key<>(); // Path: promagent-example/src/main/java/io/promagent/hooks/ServletHook.java import io.promagent.annotations.After; import io.promagent.annotations.Before; import io.promagent.annotations.Hook; import io.promagent.hookcontext.MetricDef; import io.promagent.hookcontext.MetricsStore; import io.prometheus.client.Counter; import io.prometheus.client.Summary; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.concurrent.TimeUnit; import static io.promagent.hooks.HttpContext.HTTP_METHOD; import static io.promagent.hooks.HttpContext.HTTP_PATH; private String stripPathParameters(String path) { // The URL path may include path parameters. // For example, REST URLs for querying an item might look like this: // // /item/1 // /item/2 // /item/3 // etc. // // We don't want to create a new Prometheus label for each of these paths. // Rather, we want a single label like this: // // /item/{id} // // This method replaces path parameters with placeholders. It is application specific and // should be adapted depending on the actual paths in an application. // For the demo, we just replace all numbers with {id}. return path .replaceAll("/[0-9]+", "/{id}") .replaceAll("/;jsessionid=\\w*", "") .replaceAll("/$", "") .replaceAll("\\?.*", ""); // Also remove path parameters, like "?jsessionid=..." } @Before(method = {"service", "doFilter"}) public void before(ServletRequest request, ServletResponse response) { if (HttpServletRequest.class.isAssignableFrom(request.getClass()) && HttpServletResponse.class.isAssignableFrom(response.getClass())) { HttpServletRequest req = (HttpServletRequest) request;
HttpContext.put(HTTP_METHOD, req.getMethod());
fstab/promagent
promagent-example/src/main/java/io/promagent/hooks/ServletHook.java
// Path: promagent-framework/promagent-api/src/main/java/io/promagent/hookcontext/MetricDef.java // public class MetricDef<T extends Collector> { // // private final String metricName; // private final BiFunction<String, CollectorRegistry, T> producer; // // /** // * See {@link MetricsStore}. // * @param metricName Name of the Prometheus metric, like <tt>"http_requests_total"</tt>. // * @param producer Function to create a new metric and register it with the registry. // * This function will only be called once, subsequent calls to {@link MetricsStore#createOrGet(MetricDef)} // * will return the previously created metric with the specified name. // * The two parameters are the <i>metricName</i> as specified above, // * and the Prometheus registry where the new metric should be registered. // * For an example see JavaDoc for {@link MetricsStore}. // */ // public MetricDef(String metricName, BiFunction<String, CollectorRegistry, T> producer) { // this.metricName = metricName; // this.producer = producer; // } // // String getMetricName() { // return metricName; // } // // BiFunction<String, CollectorRegistry, T> getProducer() { // return producer; // } // } // // Path: promagent-framework/promagent-api/src/main/java/io/promagent/hookcontext/MetricsStore.java // public class MetricsStore { // // private final CollectorRegistry registry; // private final ConcurrentMap<String, Collector> metrics = new ConcurrentHashMap<>(); // // public MetricsStore(CollectorRegistry registry) { // this.registry = registry; // } // // /** // * See {@link MetricsStore} and {@link MetricDef#MetricDef(String, BiFunction)}. // */ // @SuppressWarnings("unchecked") // public <T extends Collector> T createOrGet(MetricDef<T> metricDef) { // return (T) metrics.computeIfAbsent(metricDef.getMetricName(), s -> metricDef.getProducer().apply(metricDef.getMetricName(), registry)); // } // } // // Path: promagent-example/src/main/java/io/promagent/hooks/HttpContext.java // static final Key<String> HTTP_METHOD = new Key<>(); // // Path: promagent-example/src/main/java/io/promagent/hooks/HttpContext.java // static final Key<String> HTTP_PATH = new Key<>();
import io.promagent.annotations.After; import io.promagent.annotations.Before; import io.promagent.annotations.Hook; import io.promagent.hookcontext.MetricDef; import io.promagent.hookcontext.MetricsStore; import io.prometheus.client.Counter; import io.prometheus.client.Summary; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.concurrent.TimeUnit; import static io.promagent.hooks.HttpContext.HTTP_METHOD; import static io.promagent.hooks.HttpContext.HTTP_PATH;
// The URL path may include path parameters. // For example, REST URLs for querying an item might look like this: // // /item/1 // /item/2 // /item/3 // etc. // // We don't want to create a new Prometheus label for each of these paths. // Rather, we want a single label like this: // // /item/{id} // // This method replaces path parameters with placeholders. It is application specific and // should be adapted depending on the actual paths in an application. // For the demo, we just replace all numbers with {id}. return path .replaceAll("/[0-9]+", "/{id}") .replaceAll("/;jsessionid=\\w*", "") .replaceAll("/$", "") .replaceAll("\\?.*", ""); // Also remove path parameters, like "?jsessionid=..." } @Before(method = {"service", "doFilter"}) public void before(ServletRequest request, ServletResponse response) { if (HttpServletRequest.class.isAssignableFrom(request.getClass()) && HttpServletResponse.class.isAssignableFrom(response.getClass())) { HttpServletRequest req = (HttpServletRequest) request; HttpContext.put(HTTP_METHOD, req.getMethod());
// Path: promagent-framework/promagent-api/src/main/java/io/promagent/hookcontext/MetricDef.java // public class MetricDef<T extends Collector> { // // private final String metricName; // private final BiFunction<String, CollectorRegistry, T> producer; // // /** // * See {@link MetricsStore}. // * @param metricName Name of the Prometheus metric, like <tt>"http_requests_total"</tt>. // * @param producer Function to create a new metric and register it with the registry. // * This function will only be called once, subsequent calls to {@link MetricsStore#createOrGet(MetricDef)} // * will return the previously created metric with the specified name. // * The two parameters are the <i>metricName</i> as specified above, // * and the Prometheus registry where the new metric should be registered. // * For an example see JavaDoc for {@link MetricsStore}. // */ // public MetricDef(String metricName, BiFunction<String, CollectorRegistry, T> producer) { // this.metricName = metricName; // this.producer = producer; // } // // String getMetricName() { // return metricName; // } // // BiFunction<String, CollectorRegistry, T> getProducer() { // return producer; // } // } // // Path: promagent-framework/promagent-api/src/main/java/io/promagent/hookcontext/MetricsStore.java // public class MetricsStore { // // private final CollectorRegistry registry; // private final ConcurrentMap<String, Collector> metrics = new ConcurrentHashMap<>(); // // public MetricsStore(CollectorRegistry registry) { // this.registry = registry; // } // // /** // * See {@link MetricsStore} and {@link MetricDef#MetricDef(String, BiFunction)}. // */ // @SuppressWarnings("unchecked") // public <T extends Collector> T createOrGet(MetricDef<T> metricDef) { // return (T) metrics.computeIfAbsent(metricDef.getMetricName(), s -> metricDef.getProducer().apply(metricDef.getMetricName(), registry)); // } // } // // Path: promagent-example/src/main/java/io/promagent/hooks/HttpContext.java // static final Key<String> HTTP_METHOD = new Key<>(); // // Path: promagent-example/src/main/java/io/promagent/hooks/HttpContext.java // static final Key<String> HTTP_PATH = new Key<>(); // Path: promagent-example/src/main/java/io/promagent/hooks/ServletHook.java import io.promagent.annotations.After; import io.promagent.annotations.Before; import io.promagent.annotations.Hook; import io.promagent.hookcontext.MetricDef; import io.promagent.hookcontext.MetricsStore; import io.prometheus.client.Counter; import io.prometheus.client.Summary; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.concurrent.TimeUnit; import static io.promagent.hooks.HttpContext.HTTP_METHOD; import static io.promagent.hooks.HttpContext.HTTP_PATH; // The URL path may include path parameters. // For example, REST URLs for querying an item might look like this: // // /item/1 // /item/2 // /item/3 // etc. // // We don't want to create a new Prometheus label for each of these paths. // Rather, we want a single label like this: // // /item/{id} // // This method replaces path parameters with placeholders. It is application specific and // should be adapted depending on the actual paths in an application. // For the demo, we just replace all numbers with {id}. return path .replaceAll("/[0-9]+", "/{id}") .replaceAll("/;jsessionid=\\w*", "") .replaceAll("/$", "") .replaceAll("\\?.*", ""); // Also remove path parameters, like "?jsessionid=..." } @Before(method = {"service", "doFilter"}) public void before(ServletRequest request, ServletResponse response) { if (HttpServletRequest.class.isAssignableFrom(request.getClass()) && HttpServletResponse.class.isAssignableFrom(response.getClass())) { HttpServletRequest req = (HttpServletRequest) request; HttpContext.put(HTTP_METHOD, req.getMethod());
HttpContext.put(HTTP_PATH, stripPathParameters(req.getRequestURI()));
fstab/promagent
promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/hooks/ParameterTypesHook.java
// Path: promagent-framework/promagent-api/src/main/java/io/promagent/hookcontext/MetricsStore.java // public class MetricsStore { // // private final CollectorRegistry registry; // private final ConcurrentMap<String, Collector> metrics = new ConcurrentHashMap<>(); // // public MetricsStore(CollectorRegistry registry) { // this.registry = registry; // } // // /** // * See {@link MetricsStore} and {@link MetricDef#MetricDef(String, BiFunction)}. // */ // @SuppressWarnings("unchecked") // public <T extends Collector> T createOrGet(MetricDef<T> metricDef) { // return (T) metrics.computeIfAbsent(metricDef.getMetricName(), s -> metricDef.getProducer().apply(metricDef.getMetricName(), registry)); // } // } // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/MethodCallCounter.java // public class MethodCallCounter { // // public static void reset() { // captures.clear(); // } // // public static void observe(Object hook, String methodName, Object... args) { // captures.add(new Capture(hook, methodName, args)); // } // // public static void assertNumCalls(int expectedNumberOfCalls, Class<?> hookClass, String hookMethod, Object... expectedArgs) { // List<Capture> matching = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .filter(c -> c.hookMethod.equals(hookMethod)) // .filter(c -> Arrays.equals(expectedArgs, c.args)) // .collect(Collectors.toList()); // Assertions.assertEquals(expectedNumberOfCalls, matching.size()); // } // // // special case for the varargsMixed test // public static void assertNumCalls(int expectedNumberOfCalls, Class<?> hookClass, String hookMethod, String firstString, String... moreStrings) { // List<Capture> matching = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .filter(c -> c.hookMethod.equals(hookMethod)) // .filter(c -> c.args.length == 2) // .filter(c -> Objects.equals(firstString, c.args[0])) // .filter(c -> Arrays.equals(moreStrings, (String[]) c.args[1])) // .collect(Collectors.toList()); // Assertions.assertEquals(expectedNumberOfCalls, matching.size()); // } // // public static void assertNumHookInstances(int expectedNumberOfInstances, Class<?> hookClass) { // long actualNumberOfInstances = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .map(c -> c.hook) // .distinct() // .count(); // Assertions.assertEquals(expectedNumberOfInstances, (int) actualNumberOfInstances); // } // // private static class Capture { // final Object hook; // final String hookMethod; // final Object[] args; // // Capture(Object hook, String hookMethod, Object[] args) { // this.hook = hook; // this.hookMethod = hookMethod; // this.args = args; // } // } // // private static final List<Capture> captures = Collections.synchronizedList(new ArrayList<>()); // // private MethodCallCounter() {} // } // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/classes/Fruit.java // public class Fruit { // public static class Orange extends Fruit{} // } // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/classes/Fruit.java // public static class Orange extends Fruit{} // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/classes/ParameterTypesExample.java // public class ParameterTypesExample implements IParameterTypesExample { // // @Override // public void noParam() {} // // @Override // public void primitiveTypes(byte b, short s, int i, long l, float f, double d, boolean x, char c) {} // // @Override // public void boxedTypes(Byte b, Short s, Integer i, Long l, Float f, Double d, Boolean x, Character c) {} // // @Override // public void objects(Object o, Fruit f, Fruit.Orange x) {} // // @Override // public void primitiveArrays(byte[] b, short[] s, int[] i, long[] l, float[] f, double[] d, boolean[] x, char[] c) {} // // @Override // public void boxedArrays(Byte[] b, Short[] s, Integer[] i, Long[] l, Float[] f, Double[] d, Boolean[] x, Character[] c) {} // // @Override // public void objectArrays(Object[] o, Fruit[] f, Fruit.Orange[] x) {} // // @Override // public void generics(List<Object> objectList, List<Fruit> fruitList, List<Fruit.Orange> orangeList) {} // // @Override // public void varargsExplicit(Object... args) {} // // @Override // public void varargsImplicit(Object[] args) {} // // @Override // public void varargsMixed(String s, String... more) {} // // @Override // public void recursive(int nRecursiveCalls) { // if (nRecursiveCalls > 0) { // recursive(nRecursiveCalls - 1); // } // } // }
import io.promagent.annotations.After; import io.promagent.annotations.Before; import io.promagent.annotations.Hook; import io.promagent.hookcontext.MetricsStore; import io.promagent.internal.instrumentationtests.MethodCallCounter; import io.promagent.internal.instrumentationtests.classes.Fruit; import io.promagent.internal.instrumentationtests.classes.Fruit.Orange; import io.promagent.internal.instrumentationtests.classes.ParameterTypesExample; import java.util.List;
package io.promagent.internal.instrumentationtests.hooks; /** * Instrument all methods in {@link ParameterTypesExample}. */ @Hook(instruments = "io.promagent.internal.instrumentationtests.classes.ParameterTypesExample") public class ParameterTypesHook {
// Path: promagent-framework/promagent-api/src/main/java/io/promagent/hookcontext/MetricsStore.java // public class MetricsStore { // // private final CollectorRegistry registry; // private final ConcurrentMap<String, Collector> metrics = new ConcurrentHashMap<>(); // // public MetricsStore(CollectorRegistry registry) { // this.registry = registry; // } // // /** // * See {@link MetricsStore} and {@link MetricDef#MetricDef(String, BiFunction)}. // */ // @SuppressWarnings("unchecked") // public <T extends Collector> T createOrGet(MetricDef<T> metricDef) { // return (T) metrics.computeIfAbsent(metricDef.getMetricName(), s -> metricDef.getProducer().apply(metricDef.getMetricName(), registry)); // } // } // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/MethodCallCounter.java // public class MethodCallCounter { // // public static void reset() { // captures.clear(); // } // // public static void observe(Object hook, String methodName, Object... args) { // captures.add(new Capture(hook, methodName, args)); // } // // public static void assertNumCalls(int expectedNumberOfCalls, Class<?> hookClass, String hookMethod, Object... expectedArgs) { // List<Capture> matching = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .filter(c -> c.hookMethod.equals(hookMethod)) // .filter(c -> Arrays.equals(expectedArgs, c.args)) // .collect(Collectors.toList()); // Assertions.assertEquals(expectedNumberOfCalls, matching.size()); // } // // // special case for the varargsMixed test // public static void assertNumCalls(int expectedNumberOfCalls, Class<?> hookClass, String hookMethod, String firstString, String... moreStrings) { // List<Capture> matching = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .filter(c -> c.hookMethod.equals(hookMethod)) // .filter(c -> c.args.length == 2) // .filter(c -> Objects.equals(firstString, c.args[0])) // .filter(c -> Arrays.equals(moreStrings, (String[]) c.args[1])) // .collect(Collectors.toList()); // Assertions.assertEquals(expectedNumberOfCalls, matching.size()); // } // // public static void assertNumHookInstances(int expectedNumberOfInstances, Class<?> hookClass) { // long actualNumberOfInstances = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .map(c -> c.hook) // .distinct() // .count(); // Assertions.assertEquals(expectedNumberOfInstances, (int) actualNumberOfInstances); // } // // private static class Capture { // final Object hook; // final String hookMethod; // final Object[] args; // // Capture(Object hook, String hookMethod, Object[] args) { // this.hook = hook; // this.hookMethod = hookMethod; // this.args = args; // } // } // // private static final List<Capture> captures = Collections.synchronizedList(new ArrayList<>()); // // private MethodCallCounter() {} // } // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/classes/Fruit.java // public class Fruit { // public static class Orange extends Fruit{} // } // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/classes/Fruit.java // public static class Orange extends Fruit{} // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/classes/ParameterTypesExample.java // public class ParameterTypesExample implements IParameterTypesExample { // // @Override // public void noParam() {} // // @Override // public void primitiveTypes(byte b, short s, int i, long l, float f, double d, boolean x, char c) {} // // @Override // public void boxedTypes(Byte b, Short s, Integer i, Long l, Float f, Double d, Boolean x, Character c) {} // // @Override // public void objects(Object o, Fruit f, Fruit.Orange x) {} // // @Override // public void primitiveArrays(byte[] b, short[] s, int[] i, long[] l, float[] f, double[] d, boolean[] x, char[] c) {} // // @Override // public void boxedArrays(Byte[] b, Short[] s, Integer[] i, Long[] l, Float[] f, Double[] d, Boolean[] x, Character[] c) {} // // @Override // public void objectArrays(Object[] o, Fruit[] f, Fruit.Orange[] x) {} // // @Override // public void generics(List<Object> objectList, List<Fruit> fruitList, List<Fruit.Orange> orangeList) {} // // @Override // public void varargsExplicit(Object... args) {} // // @Override // public void varargsImplicit(Object[] args) {} // // @Override // public void varargsMixed(String s, String... more) {} // // @Override // public void recursive(int nRecursiveCalls) { // if (nRecursiveCalls > 0) { // recursive(nRecursiveCalls - 1); // } // } // } // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/hooks/ParameterTypesHook.java import io.promagent.annotations.After; import io.promagent.annotations.Before; import io.promagent.annotations.Hook; import io.promagent.hookcontext.MetricsStore; import io.promagent.internal.instrumentationtests.MethodCallCounter; import io.promagent.internal.instrumentationtests.classes.Fruit; import io.promagent.internal.instrumentationtests.classes.Fruit.Orange; import io.promagent.internal.instrumentationtests.classes.ParameterTypesExample; import java.util.List; package io.promagent.internal.instrumentationtests.hooks; /** * Instrument all methods in {@link ParameterTypesExample}. */ @Hook(instruments = "io.promagent.internal.instrumentationtests.classes.ParameterTypesExample") public class ParameterTypesHook {
public ParameterTypesHook(MetricsStore m) {}
fstab/promagent
promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/hooks/ParameterTypesHook.java
// Path: promagent-framework/promagent-api/src/main/java/io/promagent/hookcontext/MetricsStore.java // public class MetricsStore { // // private final CollectorRegistry registry; // private final ConcurrentMap<String, Collector> metrics = new ConcurrentHashMap<>(); // // public MetricsStore(CollectorRegistry registry) { // this.registry = registry; // } // // /** // * See {@link MetricsStore} and {@link MetricDef#MetricDef(String, BiFunction)}. // */ // @SuppressWarnings("unchecked") // public <T extends Collector> T createOrGet(MetricDef<T> metricDef) { // return (T) metrics.computeIfAbsent(metricDef.getMetricName(), s -> metricDef.getProducer().apply(metricDef.getMetricName(), registry)); // } // } // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/MethodCallCounter.java // public class MethodCallCounter { // // public static void reset() { // captures.clear(); // } // // public static void observe(Object hook, String methodName, Object... args) { // captures.add(new Capture(hook, methodName, args)); // } // // public static void assertNumCalls(int expectedNumberOfCalls, Class<?> hookClass, String hookMethod, Object... expectedArgs) { // List<Capture> matching = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .filter(c -> c.hookMethod.equals(hookMethod)) // .filter(c -> Arrays.equals(expectedArgs, c.args)) // .collect(Collectors.toList()); // Assertions.assertEquals(expectedNumberOfCalls, matching.size()); // } // // // special case for the varargsMixed test // public static void assertNumCalls(int expectedNumberOfCalls, Class<?> hookClass, String hookMethod, String firstString, String... moreStrings) { // List<Capture> matching = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .filter(c -> c.hookMethod.equals(hookMethod)) // .filter(c -> c.args.length == 2) // .filter(c -> Objects.equals(firstString, c.args[0])) // .filter(c -> Arrays.equals(moreStrings, (String[]) c.args[1])) // .collect(Collectors.toList()); // Assertions.assertEquals(expectedNumberOfCalls, matching.size()); // } // // public static void assertNumHookInstances(int expectedNumberOfInstances, Class<?> hookClass) { // long actualNumberOfInstances = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .map(c -> c.hook) // .distinct() // .count(); // Assertions.assertEquals(expectedNumberOfInstances, (int) actualNumberOfInstances); // } // // private static class Capture { // final Object hook; // final String hookMethod; // final Object[] args; // // Capture(Object hook, String hookMethod, Object[] args) { // this.hook = hook; // this.hookMethod = hookMethod; // this.args = args; // } // } // // private static final List<Capture> captures = Collections.synchronizedList(new ArrayList<>()); // // private MethodCallCounter() {} // } // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/classes/Fruit.java // public class Fruit { // public static class Orange extends Fruit{} // } // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/classes/Fruit.java // public static class Orange extends Fruit{} // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/classes/ParameterTypesExample.java // public class ParameterTypesExample implements IParameterTypesExample { // // @Override // public void noParam() {} // // @Override // public void primitiveTypes(byte b, short s, int i, long l, float f, double d, boolean x, char c) {} // // @Override // public void boxedTypes(Byte b, Short s, Integer i, Long l, Float f, Double d, Boolean x, Character c) {} // // @Override // public void objects(Object o, Fruit f, Fruit.Orange x) {} // // @Override // public void primitiveArrays(byte[] b, short[] s, int[] i, long[] l, float[] f, double[] d, boolean[] x, char[] c) {} // // @Override // public void boxedArrays(Byte[] b, Short[] s, Integer[] i, Long[] l, Float[] f, Double[] d, Boolean[] x, Character[] c) {} // // @Override // public void objectArrays(Object[] o, Fruit[] f, Fruit.Orange[] x) {} // // @Override // public void generics(List<Object> objectList, List<Fruit> fruitList, List<Fruit.Orange> orangeList) {} // // @Override // public void varargsExplicit(Object... args) {} // // @Override // public void varargsImplicit(Object[] args) {} // // @Override // public void varargsMixed(String s, String... more) {} // // @Override // public void recursive(int nRecursiveCalls) { // if (nRecursiveCalls > 0) { // recursive(nRecursiveCalls - 1); // } // } // }
import io.promagent.annotations.After; import io.promagent.annotations.Before; import io.promagent.annotations.Hook; import io.promagent.hookcontext.MetricsStore; import io.promagent.internal.instrumentationtests.MethodCallCounter; import io.promagent.internal.instrumentationtests.classes.Fruit; import io.promagent.internal.instrumentationtests.classes.Fruit.Orange; import io.promagent.internal.instrumentationtests.classes.ParameterTypesExample; import java.util.List;
package io.promagent.internal.instrumentationtests.hooks; /** * Instrument all methods in {@link ParameterTypesExample}. */ @Hook(instruments = "io.promagent.internal.instrumentationtests.classes.ParameterTypesExample") public class ParameterTypesHook { public ParameterTypesHook(MetricsStore m) {} @Before(method = "noParam") public void before() {
// Path: promagent-framework/promagent-api/src/main/java/io/promagent/hookcontext/MetricsStore.java // public class MetricsStore { // // private final CollectorRegistry registry; // private final ConcurrentMap<String, Collector> metrics = new ConcurrentHashMap<>(); // // public MetricsStore(CollectorRegistry registry) { // this.registry = registry; // } // // /** // * See {@link MetricsStore} and {@link MetricDef#MetricDef(String, BiFunction)}. // */ // @SuppressWarnings("unchecked") // public <T extends Collector> T createOrGet(MetricDef<T> metricDef) { // return (T) metrics.computeIfAbsent(metricDef.getMetricName(), s -> metricDef.getProducer().apply(metricDef.getMetricName(), registry)); // } // } // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/MethodCallCounter.java // public class MethodCallCounter { // // public static void reset() { // captures.clear(); // } // // public static void observe(Object hook, String methodName, Object... args) { // captures.add(new Capture(hook, methodName, args)); // } // // public static void assertNumCalls(int expectedNumberOfCalls, Class<?> hookClass, String hookMethod, Object... expectedArgs) { // List<Capture> matching = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .filter(c -> c.hookMethod.equals(hookMethod)) // .filter(c -> Arrays.equals(expectedArgs, c.args)) // .collect(Collectors.toList()); // Assertions.assertEquals(expectedNumberOfCalls, matching.size()); // } // // // special case for the varargsMixed test // public static void assertNumCalls(int expectedNumberOfCalls, Class<?> hookClass, String hookMethod, String firstString, String... moreStrings) { // List<Capture> matching = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .filter(c -> c.hookMethod.equals(hookMethod)) // .filter(c -> c.args.length == 2) // .filter(c -> Objects.equals(firstString, c.args[0])) // .filter(c -> Arrays.equals(moreStrings, (String[]) c.args[1])) // .collect(Collectors.toList()); // Assertions.assertEquals(expectedNumberOfCalls, matching.size()); // } // // public static void assertNumHookInstances(int expectedNumberOfInstances, Class<?> hookClass) { // long actualNumberOfInstances = captures.stream() // .filter(c -> c.hook.getClass().equals(hookClass)) // .map(c -> c.hook) // .distinct() // .count(); // Assertions.assertEquals(expectedNumberOfInstances, (int) actualNumberOfInstances); // } // // private static class Capture { // final Object hook; // final String hookMethod; // final Object[] args; // // Capture(Object hook, String hookMethod, Object[] args) { // this.hook = hook; // this.hookMethod = hookMethod; // this.args = args; // } // } // // private static final List<Capture> captures = Collections.synchronizedList(new ArrayList<>()); // // private MethodCallCounter() {} // } // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/classes/Fruit.java // public class Fruit { // public static class Orange extends Fruit{} // } // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/classes/Fruit.java // public static class Orange extends Fruit{} // // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/classes/ParameterTypesExample.java // public class ParameterTypesExample implements IParameterTypesExample { // // @Override // public void noParam() {} // // @Override // public void primitiveTypes(byte b, short s, int i, long l, float f, double d, boolean x, char c) {} // // @Override // public void boxedTypes(Byte b, Short s, Integer i, Long l, Float f, Double d, Boolean x, Character c) {} // // @Override // public void objects(Object o, Fruit f, Fruit.Orange x) {} // // @Override // public void primitiveArrays(byte[] b, short[] s, int[] i, long[] l, float[] f, double[] d, boolean[] x, char[] c) {} // // @Override // public void boxedArrays(Byte[] b, Short[] s, Integer[] i, Long[] l, Float[] f, Double[] d, Boolean[] x, Character[] c) {} // // @Override // public void objectArrays(Object[] o, Fruit[] f, Fruit.Orange[] x) {} // // @Override // public void generics(List<Object> objectList, List<Fruit> fruitList, List<Fruit.Orange> orangeList) {} // // @Override // public void varargsExplicit(Object... args) {} // // @Override // public void varargsImplicit(Object[] args) {} // // @Override // public void varargsMixed(String s, String... more) {} // // @Override // public void recursive(int nRecursiveCalls) { // if (nRecursiveCalls > 0) { // recursive(nRecursiveCalls - 1); // } // } // } // Path: promagent-framework/promagent-internal/src/test/java/io/promagent/internal/instrumentationtests/hooks/ParameterTypesHook.java import io.promagent.annotations.After; import io.promagent.annotations.Before; import io.promagent.annotations.Hook; import io.promagent.hookcontext.MetricsStore; import io.promagent.internal.instrumentationtests.MethodCallCounter; import io.promagent.internal.instrumentationtests.classes.Fruit; import io.promagent.internal.instrumentationtests.classes.Fruit.Orange; import io.promagent.internal.instrumentationtests.classes.ParameterTypesExample; import java.util.List; package io.promagent.internal.instrumentationtests.hooks; /** * Instrument all methods in {@link ParameterTypesExample}. */ @Hook(instruments = "io.promagent.internal.instrumentationtests.classes.ParameterTypesExample") public class ParameterTypesHook { public ParameterTypesHook(MetricsStore m) {} @Before(method = "noParam") public void before() {
MethodCallCounter.observe(this, "before");
thehiflyer/Fettle
src/test/java/se/fearless/fettle/Example.java
// Path: src/main/java/se/fearless/fettle/builder/StateMachineBuilder.java // public class StateMachineBuilder<S, E, C> { // private final List<TransitionBuilder<S, E, C>> transitionBuilders = GuavaReplacement.newArrayList(); // private final List<EntryExitActionBuilder<S, E, C>> entryExitActions = GuavaReplacement.newArrayList(); // private final Class<S> stateClass; // private final Class<E> eventClass; // private C defaultContext; // // // private StateMachineBuilder(Class<S> stateClass, Class<E> eventClass) { // this.stateClass = stateClass; // this.eventClass = eventClass; // } // // public static <S, E, C> StateMachineBuilder<S, E, C> create(Class<S> stateClass, Class<E> eventClass) { // return new StateMachineBuilder<>(stateClass, eventClass); // } // // public Transition<S, E, C> transition() { // TransitionBuilder<S, E, C> transition = new TransitionBuilder<>(); // transitionBuilders.add(transition); // return transition; // } // // public EntryExit<S, E, C> onEntry(S state) { // EntryExitActionBuilder<S, E, C> actionBuilder = EntryExitActionBuilder.entry(state); // entryExitActions.add(actionBuilder); // return actionBuilder; // } // // public EntryExit<S, E, C> onExit(S state) { // EntryExitActionBuilder<S, E, C> actionBuilder = EntryExitActionBuilder.exit(state); // entryExitActions.add(actionBuilder); // return actionBuilder; // } // // public StateMachineBuilder<S, E, C> defaultContext(C defaultContext) { // this.defaultContext = defaultContext; // return this; // } // // /** // * Builds a state machine with the transitions and states configured by the builder. // * Note that consecutive calls to this method will not share transition models and it's therefore inefficient to // * use this method to create large number of state machines. This method can be considered as a short hand for // * cases when just one state machine of a certain configuration is needed. // * @param initial the state the machine will be in when created // * @return a new state machine configured with all the transitions and actions specified using this builder // * @throws IllegalArgumentException if the initial state is null // */ // public StateMachine<S, E, C> build(S initial) { // @SuppressWarnings("unchecked") // StateMachineTemplate<S, E, C> build = buildTransitionModel(); // return build.newStateMachine(initial); // } // // /** // * Builds a state machine template capable of creating many instances all sharing the same // * state transitions and actions but all with their own current state. // * This is more memory efficient and is good when you need a large number of identical state machine instances. // * // * @return a state machine template configured with all the transitions and actions specified using this builder // */ // public StateMachineTemplate<S, E, C> buildTransitionModel() { // MutableTransitionModelImpl<S, E, C> template = MutableTransitionModelImpl.create(stateClass, eventClass, defaultContext); // for (TransitionBuilder<S, E, C> transitionBuilder : transitionBuilders) { // transitionBuilder.addToTransitionModel(template); // } // for (EntryExitActionBuilder<S, E, C> entryExitAction : entryExitActions) { // entryExitAction.addToMachine(template); // } // return template; // } // } // // Path: src/main/java/se/fearless/fettle/util/GuavaReplacement.java // public class GuavaReplacement { // private GuavaReplacement() { // } // // public static <T> List<T> newArrayList() { // return new ArrayList<>(); // } // // public static <K, V> Map<K, V> newHashMap() { // return new HashMap<>(); // } // }
import com.google.common.collect.Lists; import org.junit.Test; import se.fearless.fettle.builder.StateMachineBuilder; import se.fearless.fettle.util.GuavaReplacement; import java.util.List; import static org.junit.Assert.assertEquals;
package se.fearless.fettle; public class Example { @Test public void usingBuilder() {
// Path: src/main/java/se/fearless/fettle/builder/StateMachineBuilder.java // public class StateMachineBuilder<S, E, C> { // private final List<TransitionBuilder<S, E, C>> transitionBuilders = GuavaReplacement.newArrayList(); // private final List<EntryExitActionBuilder<S, E, C>> entryExitActions = GuavaReplacement.newArrayList(); // private final Class<S> stateClass; // private final Class<E> eventClass; // private C defaultContext; // // // private StateMachineBuilder(Class<S> stateClass, Class<E> eventClass) { // this.stateClass = stateClass; // this.eventClass = eventClass; // } // // public static <S, E, C> StateMachineBuilder<S, E, C> create(Class<S> stateClass, Class<E> eventClass) { // return new StateMachineBuilder<>(stateClass, eventClass); // } // // public Transition<S, E, C> transition() { // TransitionBuilder<S, E, C> transition = new TransitionBuilder<>(); // transitionBuilders.add(transition); // return transition; // } // // public EntryExit<S, E, C> onEntry(S state) { // EntryExitActionBuilder<S, E, C> actionBuilder = EntryExitActionBuilder.entry(state); // entryExitActions.add(actionBuilder); // return actionBuilder; // } // // public EntryExit<S, E, C> onExit(S state) { // EntryExitActionBuilder<S, E, C> actionBuilder = EntryExitActionBuilder.exit(state); // entryExitActions.add(actionBuilder); // return actionBuilder; // } // // public StateMachineBuilder<S, E, C> defaultContext(C defaultContext) { // this.defaultContext = defaultContext; // return this; // } // // /** // * Builds a state machine with the transitions and states configured by the builder. // * Note that consecutive calls to this method will not share transition models and it's therefore inefficient to // * use this method to create large number of state machines. This method can be considered as a short hand for // * cases when just one state machine of a certain configuration is needed. // * @param initial the state the machine will be in when created // * @return a new state machine configured with all the transitions and actions specified using this builder // * @throws IllegalArgumentException if the initial state is null // */ // public StateMachine<S, E, C> build(S initial) { // @SuppressWarnings("unchecked") // StateMachineTemplate<S, E, C> build = buildTransitionModel(); // return build.newStateMachine(initial); // } // // /** // * Builds a state machine template capable of creating many instances all sharing the same // * state transitions and actions but all with their own current state. // * This is more memory efficient and is good when you need a large number of identical state machine instances. // * // * @return a state machine template configured with all the transitions and actions specified using this builder // */ // public StateMachineTemplate<S, E, C> buildTransitionModel() { // MutableTransitionModelImpl<S, E, C> template = MutableTransitionModelImpl.create(stateClass, eventClass, defaultContext); // for (TransitionBuilder<S, E, C> transitionBuilder : transitionBuilders) { // transitionBuilder.addToTransitionModel(template); // } // for (EntryExitActionBuilder<S, E, C> entryExitAction : entryExitActions) { // entryExitAction.addToMachine(template); // } // return template; // } // } // // Path: src/main/java/se/fearless/fettle/util/GuavaReplacement.java // public class GuavaReplacement { // private GuavaReplacement() { // } // // public static <T> List<T> newArrayList() { // return new ArrayList<>(); // } // // public static <K, V> Map<K, V> newHashMap() { // return new HashMap<>(); // } // } // Path: src/test/java/se/fearless/fettle/Example.java import com.google.common.collect.Lists; import org.junit.Test; import se.fearless.fettle.builder.StateMachineBuilder; import se.fearless.fettle.util.GuavaReplacement; import java.util.List; import static org.junit.Assert.assertEquals; package se.fearless.fettle; public class Example { @Test public void usingBuilder() {
StateMachineBuilder<States, String, Void> builder = Fettle.newBuilder(States.class, String.class);
thehiflyer/Fettle
src/test/java/se/fearless/fettle/Example.java
// Path: src/main/java/se/fearless/fettle/builder/StateMachineBuilder.java // public class StateMachineBuilder<S, E, C> { // private final List<TransitionBuilder<S, E, C>> transitionBuilders = GuavaReplacement.newArrayList(); // private final List<EntryExitActionBuilder<S, E, C>> entryExitActions = GuavaReplacement.newArrayList(); // private final Class<S> stateClass; // private final Class<E> eventClass; // private C defaultContext; // // // private StateMachineBuilder(Class<S> stateClass, Class<E> eventClass) { // this.stateClass = stateClass; // this.eventClass = eventClass; // } // // public static <S, E, C> StateMachineBuilder<S, E, C> create(Class<S> stateClass, Class<E> eventClass) { // return new StateMachineBuilder<>(stateClass, eventClass); // } // // public Transition<S, E, C> transition() { // TransitionBuilder<S, E, C> transition = new TransitionBuilder<>(); // transitionBuilders.add(transition); // return transition; // } // // public EntryExit<S, E, C> onEntry(S state) { // EntryExitActionBuilder<S, E, C> actionBuilder = EntryExitActionBuilder.entry(state); // entryExitActions.add(actionBuilder); // return actionBuilder; // } // // public EntryExit<S, E, C> onExit(S state) { // EntryExitActionBuilder<S, E, C> actionBuilder = EntryExitActionBuilder.exit(state); // entryExitActions.add(actionBuilder); // return actionBuilder; // } // // public StateMachineBuilder<S, E, C> defaultContext(C defaultContext) { // this.defaultContext = defaultContext; // return this; // } // // /** // * Builds a state machine with the transitions and states configured by the builder. // * Note that consecutive calls to this method will not share transition models and it's therefore inefficient to // * use this method to create large number of state machines. This method can be considered as a short hand for // * cases when just one state machine of a certain configuration is needed. // * @param initial the state the machine will be in when created // * @return a new state machine configured with all the transitions and actions specified using this builder // * @throws IllegalArgumentException if the initial state is null // */ // public StateMachine<S, E, C> build(S initial) { // @SuppressWarnings("unchecked") // StateMachineTemplate<S, E, C> build = buildTransitionModel(); // return build.newStateMachine(initial); // } // // /** // * Builds a state machine template capable of creating many instances all sharing the same // * state transitions and actions but all with their own current state. // * This is more memory efficient and is good when you need a large number of identical state machine instances. // * // * @return a state machine template configured with all the transitions and actions specified using this builder // */ // public StateMachineTemplate<S, E, C> buildTransitionModel() { // MutableTransitionModelImpl<S, E, C> template = MutableTransitionModelImpl.create(stateClass, eventClass, defaultContext); // for (TransitionBuilder<S, E, C> transitionBuilder : transitionBuilders) { // transitionBuilder.addToTransitionModel(template); // } // for (EntryExitActionBuilder<S, E, C> entryExitAction : entryExitActions) { // entryExitAction.addToMachine(template); // } // return template; // } // } // // Path: src/main/java/se/fearless/fettle/util/GuavaReplacement.java // public class GuavaReplacement { // private GuavaReplacement() { // } // // public static <T> List<T> newArrayList() { // return new ArrayList<>(); // } // // public static <K, V> Map<K, V> newHashMap() { // return new HashMap<>(); // } // }
import com.google.common.collect.Lists; import org.junit.Test; import se.fearless.fettle.builder.StateMachineBuilder; import se.fearless.fettle.util.GuavaReplacement; import java.util.List; import static org.junit.Assert.assertEquals;
assertEquals(States.ONE, stateMachine.getCurrentState()); } @Test public void whenExample() throws Exception { StateMachineBuilder<States, String, Arguments> builder = Fettle.newBuilder(States.class, String.class); Condition<Arguments> firstArgIsOne = args -> args.getNumberOfArguments() > 0 && args.getFirst().equals(1); Condition<Arguments> noArguments = args -> args.getNumberOfArguments() == 0; builder.transition().from(States.INITIAL).to(States.ONE).on("tick").when(BasicConditions.or(firstArgIsOne, noArguments)); StateMachine<States, String, Arguments> stateMachine = builder.build(States.INITIAL); stateMachine.fireEvent("tick", new Arguments(3)); assertEquals(States.INITIAL, stateMachine.getCurrentState()); stateMachine.fireEvent("tick", Arguments.NO_ARGS); assertEquals(States.ONE, stateMachine.getCurrentState()); } @Test public void transitionActionExample() throws Exception { StateMachineBuilder<States, String, Void> builder = Fettle.newBuilder(States.class, String.class); Action<States, String, Void> action1 = (from, to, causedBy, ignored, statesStringStateMachine) -> { // do whatever is desired }; Action<States, String, Void> action2 = (from, to, causedBy, ignored, statesStringStateMachine) -> { // do whatever is desired };
// Path: src/main/java/se/fearless/fettle/builder/StateMachineBuilder.java // public class StateMachineBuilder<S, E, C> { // private final List<TransitionBuilder<S, E, C>> transitionBuilders = GuavaReplacement.newArrayList(); // private final List<EntryExitActionBuilder<S, E, C>> entryExitActions = GuavaReplacement.newArrayList(); // private final Class<S> stateClass; // private final Class<E> eventClass; // private C defaultContext; // // // private StateMachineBuilder(Class<S> stateClass, Class<E> eventClass) { // this.stateClass = stateClass; // this.eventClass = eventClass; // } // // public static <S, E, C> StateMachineBuilder<S, E, C> create(Class<S> stateClass, Class<E> eventClass) { // return new StateMachineBuilder<>(stateClass, eventClass); // } // // public Transition<S, E, C> transition() { // TransitionBuilder<S, E, C> transition = new TransitionBuilder<>(); // transitionBuilders.add(transition); // return transition; // } // // public EntryExit<S, E, C> onEntry(S state) { // EntryExitActionBuilder<S, E, C> actionBuilder = EntryExitActionBuilder.entry(state); // entryExitActions.add(actionBuilder); // return actionBuilder; // } // // public EntryExit<S, E, C> onExit(S state) { // EntryExitActionBuilder<S, E, C> actionBuilder = EntryExitActionBuilder.exit(state); // entryExitActions.add(actionBuilder); // return actionBuilder; // } // // public StateMachineBuilder<S, E, C> defaultContext(C defaultContext) { // this.defaultContext = defaultContext; // return this; // } // // /** // * Builds a state machine with the transitions and states configured by the builder. // * Note that consecutive calls to this method will not share transition models and it's therefore inefficient to // * use this method to create large number of state machines. This method can be considered as a short hand for // * cases when just one state machine of a certain configuration is needed. // * @param initial the state the machine will be in when created // * @return a new state machine configured with all the transitions and actions specified using this builder // * @throws IllegalArgumentException if the initial state is null // */ // public StateMachine<S, E, C> build(S initial) { // @SuppressWarnings("unchecked") // StateMachineTemplate<S, E, C> build = buildTransitionModel(); // return build.newStateMachine(initial); // } // // /** // * Builds a state machine template capable of creating many instances all sharing the same // * state transitions and actions but all with their own current state. // * This is more memory efficient and is good when you need a large number of identical state machine instances. // * // * @return a state machine template configured with all the transitions and actions specified using this builder // */ // public StateMachineTemplate<S, E, C> buildTransitionModel() { // MutableTransitionModelImpl<S, E, C> template = MutableTransitionModelImpl.create(stateClass, eventClass, defaultContext); // for (TransitionBuilder<S, E, C> transitionBuilder : transitionBuilders) { // transitionBuilder.addToTransitionModel(template); // } // for (EntryExitActionBuilder<S, E, C> entryExitAction : entryExitActions) { // entryExitAction.addToMachine(template); // } // return template; // } // } // // Path: src/main/java/se/fearless/fettle/util/GuavaReplacement.java // public class GuavaReplacement { // private GuavaReplacement() { // } // // public static <T> List<T> newArrayList() { // return new ArrayList<>(); // } // // public static <K, V> Map<K, V> newHashMap() { // return new HashMap<>(); // } // } // Path: src/test/java/se/fearless/fettle/Example.java import com.google.common.collect.Lists; import org.junit.Test; import se.fearless.fettle.builder.StateMachineBuilder; import se.fearless.fettle.util.GuavaReplacement; import java.util.List; import static org.junit.Assert.assertEquals; assertEquals(States.ONE, stateMachine.getCurrentState()); } @Test public void whenExample() throws Exception { StateMachineBuilder<States, String, Arguments> builder = Fettle.newBuilder(States.class, String.class); Condition<Arguments> firstArgIsOne = args -> args.getNumberOfArguments() > 0 && args.getFirst().equals(1); Condition<Arguments> noArguments = args -> args.getNumberOfArguments() == 0; builder.transition().from(States.INITIAL).to(States.ONE).on("tick").when(BasicConditions.or(firstArgIsOne, noArguments)); StateMachine<States, String, Arguments> stateMachine = builder.build(States.INITIAL); stateMachine.fireEvent("tick", new Arguments(3)); assertEquals(States.INITIAL, stateMachine.getCurrentState()); stateMachine.fireEvent("tick", Arguments.NO_ARGS); assertEquals(States.ONE, stateMachine.getCurrentState()); } @Test public void transitionActionExample() throws Exception { StateMachineBuilder<States, String, Void> builder = Fettle.newBuilder(States.class, String.class); Action<States, String, Void> action1 = (from, to, causedBy, ignored, statesStringStateMachine) -> { // do whatever is desired }; Action<States, String, Void> action2 = (from, to, causedBy, ignored, statesStringStateMachine) -> { // do whatever is desired };
List<Action<States, String, Void>> actions = GuavaReplacement.newArrayList();
thehiflyer/Fettle
src/test/java/se/fearless/fettle/InternalTransitionsTest.java
// Path: src/main/java/se/fearless/fettle/builder/StateMachineBuilder.java // public class StateMachineBuilder<S, E, C> { // private final List<TransitionBuilder<S, E, C>> transitionBuilders = GuavaReplacement.newArrayList(); // private final List<EntryExitActionBuilder<S, E, C>> entryExitActions = GuavaReplacement.newArrayList(); // private final Class<S> stateClass; // private final Class<E> eventClass; // private C defaultContext; // // // private StateMachineBuilder(Class<S> stateClass, Class<E> eventClass) { // this.stateClass = stateClass; // this.eventClass = eventClass; // } // // public static <S, E, C> StateMachineBuilder<S, E, C> create(Class<S> stateClass, Class<E> eventClass) { // return new StateMachineBuilder<>(stateClass, eventClass); // } // // public Transition<S, E, C> transition() { // TransitionBuilder<S, E, C> transition = new TransitionBuilder<>(); // transitionBuilders.add(transition); // return transition; // } // // public EntryExit<S, E, C> onEntry(S state) { // EntryExitActionBuilder<S, E, C> actionBuilder = EntryExitActionBuilder.entry(state); // entryExitActions.add(actionBuilder); // return actionBuilder; // } // // public EntryExit<S, E, C> onExit(S state) { // EntryExitActionBuilder<S, E, C> actionBuilder = EntryExitActionBuilder.exit(state); // entryExitActions.add(actionBuilder); // return actionBuilder; // } // // public StateMachineBuilder<S, E, C> defaultContext(C defaultContext) { // this.defaultContext = defaultContext; // return this; // } // // /** // * Builds a state machine with the transitions and states configured by the builder. // * Note that consecutive calls to this method will not share transition models and it's therefore inefficient to // * use this method to create large number of state machines. This method can be considered as a short hand for // * cases when just one state machine of a certain configuration is needed. // * @param initial the state the machine will be in when created // * @return a new state machine configured with all the transitions and actions specified using this builder // * @throws IllegalArgumentException if the initial state is null // */ // public StateMachine<S, E, C> build(S initial) { // @SuppressWarnings("unchecked") // StateMachineTemplate<S, E, C> build = buildTransitionModel(); // return build.newStateMachine(initial); // } // // /** // * Builds a state machine template capable of creating many instances all sharing the same // * state transitions and actions but all with their own current state. // * This is more memory efficient and is good when you need a large number of identical state machine instances. // * // * @return a state machine template configured with all the transitions and actions specified using this builder // */ // public StateMachineTemplate<S, E, C> buildTransitionModel() { // MutableTransitionModelImpl<S, E, C> template = MutableTransitionModelImpl.create(stateClass, eventClass, defaultContext); // for (TransitionBuilder<S, E, C> transitionBuilder : transitionBuilders) { // transitionBuilder.addToTransitionModel(template); // } // for (EntryExitActionBuilder<S, E, C> entryExitAction : entryExitActions) { // entryExitAction.addToMachine(template); // } // return template; // } // }
import org.junit.Before; import org.junit.Test; import se.fearless.fettle.builder.StateMachineBuilder; import se.mockachino.annotations.Mock; import static se.mockachino.Mockachino.setupMocks; import static se.mockachino.Mockachino.verifyNever; import static se.mockachino.Mockachino.verifyOnce; import static se.mockachino.matchers.Matchers.any;
package se.fearless.fettle; public class InternalTransitionsTest { private static final String INTERNAL_TRANSITION_TRIGGER = "internal"; @Mock private Action<States, String, Void> transitionAction; @Mock private Action<States, String, Void> entryAction; @Mock private Action<States, String, Void> exitAction; private StateMachine<States, String, Void> stateMachine; @Before public void setUp() throws Exception { setupMocks(this);
// Path: src/main/java/se/fearless/fettle/builder/StateMachineBuilder.java // public class StateMachineBuilder<S, E, C> { // private final List<TransitionBuilder<S, E, C>> transitionBuilders = GuavaReplacement.newArrayList(); // private final List<EntryExitActionBuilder<S, E, C>> entryExitActions = GuavaReplacement.newArrayList(); // private final Class<S> stateClass; // private final Class<E> eventClass; // private C defaultContext; // // // private StateMachineBuilder(Class<S> stateClass, Class<E> eventClass) { // this.stateClass = stateClass; // this.eventClass = eventClass; // } // // public static <S, E, C> StateMachineBuilder<S, E, C> create(Class<S> stateClass, Class<E> eventClass) { // return new StateMachineBuilder<>(stateClass, eventClass); // } // // public Transition<S, E, C> transition() { // TransitionBuilder<S, E, C> transition = new TransitionBuilder<>(); // transitionBuilders.add(transition); // return transition; // } // // public EntryExit<S, E, C> onEntry(S state) { // EntryExitActionBuilder<S, E, C> actionBuilder = EntryExitActionBuilder.entry(state); // entryExitActions.add(actionBuilder); // return actionBuilder; // } // // public EntryExit<S, E, C> onExit(S state) { // EntryExitActionBuilder<S, E, C> actionBuilder = EntryExitActionBuilder.exit(state); // entryExitActions.add(actionBuilder); // return actionBuilder; // } // // public StateMachineBuilder<S, E, C> defaultContext(C defaultContext) { // this.defaultContext = defaultContext; // return this; // } // // /** // * Builds a state machine with the transitions and states configured by the builder. // * Note that consecutive calls to this method will not share transition models and it's therefore inefficient to // * use this method to create large number of state machines. This method can be considered as a short hand for // * cases when just one state machine of a certain configuration is needed. // * @param initial the state the machine will be in when created // * @return a new state machine configured with all the transitions and actions specified using this builder // * @throws IllegalArgumentException if the initial state is null // */ // public StateMachine<S, E, C> build(S initial) { // @SuppressWarnings("unchecked") // StateMachineTemplate<S, E, C> build = buildTransitionModel(); // return build.newStateMachine(initial); // } // // /** // * Builds a state machine template capable of creating many instances all sharing the same // * state transitions and actions but all with their own current state. // * This is more memory efficient and is good when you need a large number of identical state machine instances. // * // * @return a state machine template configured with all the transitions and actions specified using this builder // */ // public StateMachineTemplate<S, E, C> buildTransitionModel() { // MutableTransitionModelImpl<S, E, C> template = MutableTransitionModelImpl.create(stateClass, eventClass, defaultContext); // for (TransitionBuilder<S, E, C> transitionBuilder : transitionBuilders) { // transitionBuilder.addToTransitionModel(template); // } // for (EntryExitActionBuilder<S, E, C> entryExitAction : entryExitActions) { // entryExitAction.addToMachine(template); // } // return template; // } // } // Path: src/test/java/se/fearless/fettle/InternalTransitionsTest.java import org.junit.Before; import org.junit.Test; import se.fearless.fettle.builder.StateMachineBuilder; import se.mockachino.annotations.Mock; import static se.mockachino.Mockachino.setupMocks; import static se.mockachino.Mockachino.verifyNever; import static se.mockachino.Mockachino.verifyOnce; import static se.mockachino.matchers.Matchers.any; package se.fearless.fettle; public class InternalTransitionsTest { private static final String INTERNAL_TRANSITION_TRIGGER = "internal"; @Mock private Action<States, String, Void> transitionAction; @Mock private Action<States, String, Void> entryAction; @Mock private Action<States, String, Void> exitAction; private StateMachine<States, String, Void> stateMachine; @Before public void setUp() throws Exception { setupMocks(this);
StateMachineBuilder<States, String, Void> builder = Fettle.newBuilder(States.class, String.class);
thehiflyer/Fettle
src/test/java/se/fearless/fettle/MovementUsecase.java
// Path: src/main/java/se/fearless/fettle/impl/MutableTransitionModelImpl.java // public class MutableTransitionModelImpl<S, E, C> extends AbstractTransitionModel<S, E, C> implements MutableTransitionModel<S, E, C> { // // private MutableTransitionModelImpl(Class<S> stateClass, Class<E> eventClass, C defaultContext) { // super(stateClass, eventClass, defaultContext); // } // // public static <S, E, C> MutableTransitionModelImpl<S, E, C> create(Class<S> stateClass, Class<E> eventClass, C defaultContext) { // return new MutableTransitionModelImpl<>(stateClass, eventClass, defaultContext); // } // // public static <S, E, C> MutableTransitionModelImpl<S, E, C> create(Class<S> stateClass, Class<E> eventClass) { // return new MutableTransitionModelImpl<>(stateClass, eventClass, null); // } // // @Override // public StateMachine<S, E, C> newStateMachine(S init) { // return newStateMachine(init, new ReentrantLock()); // } // // // @Override // public StateMachine<S, E, C> newStateMachine(S init, Lock lock) { // return new TemplateBasedStateMachine<>(this, init, lock); // } // // // @Override // public StateMachineTemplate<S, E, C> createImmutableClone() { // return new ImmutableTransitionModel<>(stateClass, eventClass, transitionMap, fromAllTransitions, exitActions, enterActions, defaultContext); // } // // @Override // public void addTransition(S from, S to, E event, Condition<C> condition, List<Action<S, E, C>> actions) { // addTransition(from, event, new BasicTransition<>(to, condition, actions)); // } // // @Override // public void addInternalTransition(S from, S to, E event, Condition<C> condition, List<Action<S, E, C>> actions) { // addTransition(from, event, new InternalTransition<>(to, condition, actions)); // } // // private void addTransition(S from, E event, Transition<S, E, C> transition) { // Map<E, Collection<Transition<S, E, C>>> map = transitionMap.computeIfAbsent(from, k -> createMap(eventClass)); // Collection<Transition<S, E, C>> transitions = map.computeIfAbsent(event, k -> GuavaReplacement.newArrayList()); // transitions.add(transition); // } // // @Override // public void addFromAllTransition(S to, E event, Condition<C> condition, List<Action<S, E, C>> actions) { // Collection<Transition<S, E, C>> transitions = fromAllTransitions.computeIfAbsent(event, k -> GuavaReplacement.newArrayList()); // transitions.add(new BasicTransition<>(to, condition, actions)); // } // // @Override // public void addEntryAction(S entryState, Action<S, E, C> action) { // addAction(entryState, action, enterActions); // } // // private void addAction(S entryState, Action<S, E, C> action, Map<S, Collection<Action<S, E, C>>> map) { // Collection<Action<S, E, C>> collection = map.computeIfAbsent(entryState, k -> GuavaReplacement.newArrayList()); // collection.add(action); // } // // @Override // public void addExitAction(S exitState, Action<S, E, C> action) { // addAction(exitState, action, exitActions); // } // }
import org.junit.Test; import se.fearless.fettle.impl.MutableTransitionModelImpl; import se.mockachino.Mockachino; import java.util.Collections; import java.util.List; import static org.junit.Assert.assertEquals;
package se.fearless.fettle; public class MovementUsecase { private interface State { } private enum MovementEvents { RELEASED_SPACE, HIT_GROUND, ON_UPDATE, PRESSED_SPACE } @Test public void testMovement() { State walking = Mockachino.mock(State.class); State jumping = Mockachino.mock(State.class); State falling = Mockachino.mock(State.class); State crashed = Mockachino.mock(State.class); State jetpackthrust = Mockachino.mock(State.class);
// Path: src/main/java/se/fearless/fettle/impl/MutableTransitionModelImpl.java // public class MutableTransitionModelImpl<S, E, C> extends AbstractTransitionModel<S, E, C> implements MutableTransitionModel<S, E, C> { // // private MutableTransitionModelImpl(Class<S> stateClass, Class<E> eventClass, C defaultContext) { // super(stateClass, eventClass, defaultContext); // } // // public static <S, E, C> MutableTransitionModelImpl<S, E, C> create(Class<S> stateClass, Class<E> eventClass, C defaultContext) { // return new MutableTransitionModelImpl<>(stateClass, eventClass, defaultContext); // } // // public static <S, E, C> MutableTransitionModelImpl<S, E, C> create(Class<S> stateClass, Class<E> eventClass) { // return new MutableTransitionModelImpl<>(stateClass, eventClass, null); // } // // @Override // public StateMachine<S, E, C> newStateMachine(S init) { // return newStateMachine(init, new ReentrantLock()); // } // // // @Override // public StateMachine<S, E, C> newStateMachine(S init, Lock lock) { // return new TemplateBasedStateMachine<>(this, init, lock); // } // // // @Override // public StateMachineTemplate<S, E, C> createImmutableClone() { // return new ImmutableTransitionModel<>(stateClass, eventClass, transitionMap, fromAllTransitions, exitActions, enterActions, defaultContext); // } // // @Override // public void addTransition(S from, S to, E event, Condition<C> condition, List<Action<S, E, C>> actions) { // addTransition(from, event, new BasicTransition<>(to, condition, actions)); // } // // @Override // public void addInternalTransition(S from, S to, E event, Condition<C> condition, List<Action<S, E, C>> actions) { // addTransition(from, event, new InternalTransition<>(to, condition, actions)); // } // // private void addTransition(S from, E event, Transition<S, E, C> transition) { // Map<E, Collection<Transition<S, E, C>>> map = transitionMap.computeIfAbsent(from, k -> createMap(eventClass)); // Collection<Transition<S, E, C>> transitions = map.computeIfAbsent(event, k -> GuavaReplacement.newArrayList()); // transitions.add(transition); // } // // @Override // public void addFromAllTransition(S to, E event, Condition<C> condition, List<Action<S, E, C>> actions) { // Collection<Transition<S, E, C>> transitions = fromAllTransitions.computeIfAbsent(event, k -> GuavaReplacement.newArrayList()); // transitions.add(new BasicTransition<>(to, condition, actions)); // } // // @Override // public void addEntryAction(S entryState, Action<S, E, C> action) { // addAction(entryState, action, enterActions); // } // // private void addAction(S entryState, Action<S, E, C> action, Map<S, Collection<Action<S, E, C>>> map) { // Collection<Action<S, E, C>> collection = map.computeIfAbsent(entryState, k -> GuavaReplacement.newArrayList()); // collection.add(action); // } // // @Override // public void addExitAction(S exitState, Action<S, E, C> action) { // addAction(exitState, action, exitActions); // } // } // Path: src/test/java/se/fearless/fettle/MovementUsecase.java import org.junit.Test; import se.fearless.fettle.impl.MutableTransitionModelImpl; import se.mockachino.Mockachino; import java.util.Collections; import java.util.List; import static org.junit.Assert.assertEquals; package se.fearless.fettle; public class MovementUsecase { private interface State { } private enum MovementEvents { RELEASED_SPACE, HIT_GROUND, ON_UPDATE, PRESSED_SPACE } @Test public void testMovement() { State walking = Mockachino.mock(State.class); State jumping = Mockachino.mock(State.class); State falling = Mockachino.mock(State.class); State crashed = Mockachino.mock(State.class); State jetpackthrust = Mockachino.mock(State.class);
MutableTransitionModelImpl<State, MovementEvents, Void> model = MutableTransitionModelImpl.create(State.class, MovementEvents.class);
thehiflyer/Fettle
src/test/java/se/fearless/fettle/FettleTest.java
// Path: src/main/java/se/fearless/fettle/builder/StateMachineBuilder.java // public class StateMachineBuilder<S, E, C> { // private final List<TransitionBuilder<S, E, C>> transitionBuilders = GuavaReplacement.newArrayList(); // private final List<EntryExitActionBuilder<S, E, C>> entryExitActions = GuavaReplacement.newArrayList(); // private final Class<S> stateClass; // private final Class<E> eventClass; // private C defaultContext; // // // private StateMachineBuilder(Class<S> stateClass, Class<E> eventClass) { // this.stateClass = stateClass; // this.eventClass = eventClass; // } // // public static <S, E, C> StateMachineBuilder<S, E, C> create(Class<S> stateClass, Class<E> eventClass) { // return new StateMachineBuilder<>(stateClass, eventClass); // } // // public Transition<S, E, C> transition() { // TransitionBuilder<S, E, C> transition = new TransitionBuilder<>(); // transitionBuilders.add(transition); // return transition; // } // // public EntryExit<S, E, C> onEntry(S state) { // EntryExitActionBuilder<S, E, C> actionBuilder = EntryExitActionBuilder.entry(state); // entryExitActions.add(actionBuilder); // return actionBuilder; // } // // public EntryExit<S, E, C> onExit(S state) { // EntryExitActionBuilder<S, E, C> actionBuilder = EntryExitActionBuilder.exit(state); // entryExitActions.add(actionBuilder); // return actionBuilder; // } // // public StateMachineBuilder<S, E, C> defaultContext(C defaultContext) { // this.defaultContext = defaultContext; // return this; // } // // /** // * Builds a state machine with the transitions and states configured by the builder. // * Note that consecutive calls to this method will not share transition models and it's therefore inefficient to // * use this method to create large number of state machines. This method can be considered as a short hand for // * cases when just one state machine of a certain configuration is needed. // * @param initial the state the machine will be in when created // * @return a new state machine configured with all the transitions and actions specified using this builder // * @throws IllegalArgumentException if the initial state is null // */ // public StateMachine<S, E, C> build(S initial) { // @SuppressWarnings("unchecked") // StateMachineTemplate<S, E, C> build = buildTransitionModel(); // return build.newStateMachine(initial); // } // // /** // * Builds a state machine template capable of creating many instances all sharing the same // * state transitions and actions but all with their own current state. // * This is more memory efficient and is good when you need a large number of identical state machine instances. // * // * @return a state machine template configured with all the transitions and actions specified using this builder // */ // public StateMachineTemplate<S, E, C> buildTransitionModel() { // MutableTransitionModelImpl<S, E, C> template = MutableTransitionModelImpl.create(stateClass, eventClass, defaultContext); // for (TransitionBuilder<S, E, C> transitionBuilder : transitionBuilders) { // transitionBuilder.addToTransitionModel(template); // } // for (EntryExitActionBuilder<S, E, C> entryExitAction : entryExitActions) { // entryExitAction.addToMachine(template); // } // return template; // } // }
import org.junit.Test; import se.fearless.fettle.builder.StateMachineBuilder; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull;
package se.fearless.fettle; public class FettleTest { @Test public void useOfUtil() { MutableTransitionModel<States, String, Void> transitionModel = Fettle.newTransitionModel(States.class, String.class); assertNotNull(transitionModel);
// Path: src/main/java/se/fearless/fettle/builder/StateMachineBuilder.java // public class StateMachineBuilder<S, E, C> { // private final List<TransitionBuilder<S, E, C>> transitionBuilders = GuavaReplacement.newArrayList(); // private final List<EntryExitActionBuilder<S, E, C>> entryExitActions = GuavaReplacement.newArrayList(); // private final Class<S> stateClass; // private final Class<E> eventClass; // private C defaultContext; // // // private StateMachineBuilder(Class<S> stateClass, Class<E> eventClass) { // this.stateClass = stateClass; // this.eventClass = eventClass; // } // // public static <S, E, C> StateMachineBuilder<S, E, C> create(Class<S> stateClass, Class<E> eventClass) { // return new StateMachineBuilder<>(stateClass, eventClass); // } // // public Transition<S, E, C> transition() { // TransitionBuilder<S, E, C> transition = new TransitionBuilder<>(); // transitionBuilders.add(transition); // return transition; // } // // public EntryExit<S, E, C> onEntry(S state) { // EntryExitActionBuilder<S, E, C> actionBuilder = EntryExitActionBuilder.entry(state); // entryExitActions.add(actionBuilder); // return actionBuilder; // } // // public EntryExit<S, E, C> onExit(S state) { // EntryExitActionBuilder<S, E, C> actionBuilder = EntryExitActionBuilder.exit(state); // entryExitActions.add(actionBuilder); // return actionBuilder; // } // // public StateMachineBuilder<S, E, C> defaultContext(C defaultContext) { // this.defaultContext = defaultContext; // return this; // } // // /** // * Builds a state machine with the transitions and states configured by the builder. // * Note that consecutive calls to this method will not share transition models and it's therefore inefficient to // * use this method to create large number of state machines. This method can be considered as a short hand for // * cases when just one state machine of a certain configuration is needed. // * @param initial the state the machine will be in when created // * @return a new state machine configured with all the transitions and actions specified using this builder // * @throws IllegalArgumentException if the initial state is null // */ // public StateMachine<S, E, C> build(S initial) { // @SuppressWarnings("unchecked") // StateMachineTemplate<S, E, C> build = buildTransitionModel(); // return build.newStateMachine(initial); // } // // /** // * Builds a state machine template capable of creating many instances all sharing the same // * state transitions and actions but all with their own current state. // * This is more memory efficient and is good when you need a large number of identical state machine instances. // * // * @return a state machine template configured with all the transitions and actions specified using this builder // */ // public StateMachineTemplate<S, E, C> buildTransitionModel() { // MutableTransitionModelImpl<S, E, C> template = MutableTransitionModelImpl.create(stateClass, eventClass, defaultContext); // for (TransitionBuilder<S, E, C> transitionBuilder : transitionBuilders) { // transitionBuilder.addToTransitionModel(template); // } // for (EntryExitActionBuilder<S, E, C> entryExitAction : entryExitActions) { // entryExitAction.addToMachine(template); // } // return template; // } // } // Path: src/test/java/se/fearless/fettle/FettleTest.java import org.junit.Test; import se.fearless.fettle.builder.StateMachineBuilder; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; package se.fearless.fettle; public class FettleTest { @Test public void useOfUtil() { MutableTransitionModel<States, String, Void> transitionModel = Fettle.newTransitionModel(States.class, String.class); assertNotNull(transitionModel);
StateMachineBuilder<States, String, Void> builder = Fettle.newBuilder(States.class, String.class);
thehiflyer/Fettle
src/main/java/se/fearless/fettle/impl/AbstractTransition.java
// Path: src/main/java/se/fearless/fettle/Action.java // public interface Action<S, E, C> { // /** // * Called when a transition occurs // * @param from the state the machine was in before the transition // * @param to the state the machine is in after the transition // * @param causedBy the event that triggered the transition // * @param context the context in which the event was fired supplied to the transition // * @param stateMachine the machine for which the transition occurred // */ // void onTransition(S from, S to, E causedBy, C context, StateMachine<S, E, C> stateMachine); // } // // Path: src/main/java/se/fearless/fettle/Condition.java // public interface Condition<C> { // boolean isSatisfied(C context); // } // // Path: src/main/java/se/fearless/fettle/StateMachine.java // public interface StateMachine<S, E, C> { // /** // * Gets the current state of the machine // * // * @return the state the machine is currently in // */ // S getCurrentState(); // // /** // * Fires an event at the state machine, possibly triggering a state change // * // * @param event the event that is fired // * @return true if the event resulted in a state change, false otherwise // */ // boolean fireEvent(E event); // // /** // * Fires an event at the state machine, possibly triggering a state change // * // * @param event the event that is fired // * @param context the context to be sent to any actions that are run on a state change. Used to supply parameters to // * actions and conditions // * @return true if the event resulted in a state change, false otherwise // */ // boolean fireEvent(E event, C context); // // /** // * Sets the state of the state machine to the rawState even if there are no transitions leading to it // * No transition, entry or exit actions are run // * // * @param rawState the state the machine will be in after this method is called // */ // void rawSetState(S rawState); // // /** // * Forces the state machine to enter the forcedState even if there are no transitions leading to it // * No transition actions are run but exit actions on the current state and entry actions on the new state are run // * // * @param forcedState the state the machine will be in after this method is called // * @return true if the state machine changed state // */ // boolean forceSetState(S forcedState); // // /** // * Returns all possible transitions from a given state grouped by the event that triggers the transition. // * @param fromState the state to retrieve the outgoing transitions from. // * @return a map from all registered events in the fromState to the transitions they would trigger if fired. // */ // Map<E, Collection<? extends Transition<S, E, C>>> getPossibleTransitions(S fromState); // } // // Path: src/main/java/se/fearless/fettle/Transition.java // public interface Transition<S, E, C> { // S getTo(); // // boolean isSatisfied(C context); // // void onTransition(S from, S to, E event, C context, StateMachine<S, E, C> statemachine); // // boolean shouldExecuteEntryAndExitActions(); // } // // Path: src/main/java/se/fearless/fettle/util/GuavaReplacement.java // public class GuavaReplacement { // private GuavaReplacement() { // } // // public static <T> List<T> newArrayList() { // return new ArrayList<>(); // } // // public static <K, V> Map<K, V> newHashMap() { // return new HashMap<>(); // } // }
import se.fearless.fettle.Action; import se.fearless.fettle.Condition; import se.fearless.fettle.StateMachine; import se.fearless.fettle.Transition; import se.fearless.fettle.util.GuavaReplacement; import java.util.Collection;
package se.fearless.fettle.impl; public abstract class AbstractTransition<S, E, C> implements Transition<S, E, C> { protected final S to;
// Path: src/main/java/se/fearless/fettle/Action.java // public interface Action<S, E, C> { // /** // * Called when a transition occurs // * @param from the state the machine was in before the transition // * @param to the state the machine is in after the transition // * @param causedBy the event that triggered the transition // * @param context the context in which the event was fired supplied to the transition // * @param stateMachine the machine for which the transition occurred // */ // void onTransition(S from, S to, E causedBy, C context, StateMachine<S, E, C> stateMachine); // } // // Path: src/main/java/se/fearless/fettle/Condition.java // public interface Condition<C> { // boolean isSatisfied(C context); // } // // Path: src/main/java/se/fearless/fettle/StateMachine.java // public interface StateMachine<S, E, C> { // /** // * Gets the current state of the machine // * // * @return the state the machine is currently in // */ // S getCurrentState(); // // /** // * Fires an event at the state machine, possibly triggering a state change // * // * @param event the event that is fired // * @return true if the event resulted in a state change, false otherwise // */ // boolean fireEvent(E event); // // /** // * Fires an event at the state machine, possibly triggering a state change // * // * @param event the event that is fired // * @param context the context to be sent to any actions that are run on a state change. Used to supply parameters to // * actions and conditions // * @return true if the event resulted in a state change, false otherwise // */ // boolean fireEvent(E event, C context); // // /** // * Sets the state of the state machine to the rawState even if there are no transitions leading to it // * No transition, entry or exit actions are run // * // * @param rawState the state the machine will be in after this method is called // */ // void rawSetState(S rawState); // // /** // * Forces the state machine to enter the forcedState even if there are no transitions leading to it // * No transition actions are run but exit actions on the current state and entry actions on the new state are run // * // * @param forcedState the state the machine will be in after this method is called // * @return true if the state machine changed state // */ // boolean forceSetState(S forcedState); // // /** // * Returns all possible transitions from a given state grouped by the event that triggers the transition. // * @param fromState the state to retrieve the outgoing transitions from. // * @return a map from all registered events in the fromState to the transitions they would trigger if fired. // */ // Map<E, Collection<? extends Transition<S, E, C>>> getPossibleTransitions(S fromState); // } // // Path: src/main/java/se/fearless/fettle/Transition.java // public interface Transition<S, E, C> { // S getTo(); // // boolean isSatisfied(C context); // // void onTransition(S from, S to, E event, C context, StateMachine<S, E, C> statemachine); // // boolean shouldExecuteEntryAndExitActions(); // } // // Path: src/main/java/se/fearless/fettle/util/GuavaReplacement.java // public class GuavaReplacement { // private GuavaReplacement() { // } // // public static <T> List<T> newArrayList() { // return new ArrayList<>(); // } // // public static <K, V> Map<K, V> newHashMap() { // return new HashMap<>(); // } // } // Path: src/main/java/se/fearless/fettle/impl/AbstractTransition.java import se.fearless.fettle.Action; import se.fearless.fettle.Condition; import se.fearless.fettle.StateMachine; import se.fearless.fettle.Transition; import se.fearless.fettle.util.GuavaReplacement; import java.util.Collection; package se.fearless.fettle.impl; public abstract class AbstractTransition<S, E, C> implements Transition<S, E, C> { protected final S to;
protected final Condition<C> condition;
thehiflyer/Fettle
src/main/java/se/fearless/fettle/impl/AbstractTransition.java
// Path: src/main/java/se/fearless/fettle/Action.java // public interface Action<S, E, C> { // /** // * Called when a transition occurs // * @param from the state the machine was in before the transition // * @param to the state the machine is in after the transition // * @param causedBy the event that triggered the transition // * @param context the context in which the event was fired supplied to the transition // * @param stateMachine the machine for which the transition occurred // */ // void onTransition(S from, S to, E causedBy, C context, StateMachine<S, E, C> stateMachine); // } // // Path: src/main/java/se/fearless/fettle/Condition.java // public interface Condition<C> { // boolean isSatisfied(C context); // } // // Path: src/main/java/se/fearless/fettle/StateMachine.java // public interface StateMachine<S, E, C> { // /** // * Gets the current state of the machine // * // * @return the state the machine is currently in // */ // S getCurrentState(); // // /** // * Fires an event at the state machine, possibly triggering a state change // * // * @param event the event that is fired // * @return true if the event resulted in a state change, false otherwise // */ // boolean fireEvent(E event); // // /** // * Fires an event at the state machine, possibly triggering a state change // * // * @param event the event that is fired // * @param context the context to be sent to any actions that are run on a state change. Used to supply parameters to // * actions and conditions // * @return true if the event resulted in a state change, false otherwise // */ // boolean fireEvent(E event, C context); // // /** // * Sets the state of the state machine to the rawState even if there are no transitions leading to it // * No transition, entry or exit actions are run // * // * @param rawState the state the machine will be in after this method is called // */ // void rawSetState(S rawState); // // /** // * Forces the state machine to enter the forcedState even if there are no transitions leading to it // * No transition actions are run but exit actions on the current state and entry actions on the new state are run // * // * @param forcedState the state the machine will be in after this method is called // * @return true if the state machine changed state // */ // boolean forceSetState(S forcedState); // // /** // * Returns all possible transitions from a given state grouped by the event that triggers the transition. // * @param fromState the state to retrieve the outgoing transitions from. // * @return a map from all registered events in the fromState to the transitions they would trigger if fired. // */ // Map<E, Collection<? extends Transition<S, E, C>>> getPossibleTransitions(S fromState); // } // // Path: src/main/java/se/fearless/fettle/Transition.java // public interface Transition<S, E, C> { // S getTo(); // // boolean isSatisfied(C context); // // void onTransition(S from, S to, E event, C context, StateMachine<S, E, C> statemachine); // // boolean shouldExecuteEntryAndExitActions(); // } // // Path: src/main/java/se/fearless/fettle/util/GuavaReplacement.java // public class GuavaReplacement { // private GuavaReplacement() { // } // // public static <T> List<T> newArrayList() { // return new ArrayList<>(); // } // // public static <K, V> Map<K, V> newHashMap() { // return new HashMap<>(); // } // }
import se.fearless.fettle.Action; import se.fearless.fettle.Condition; import se.fearless.fettle.StateMachine; import se.fearless.fettle.Transition; import se.fearless.fettle.util.GuavaReplacement; import java.util.Collection;
package se.fearless.fettle.impl; public abstract class AbstractTransition<S, E, C> implements Transition<S, E, C> { protected final S to; protected final Condition<C> condition;
// Path: src/main/java/se/fearless/fettle/Action.java // public interface Action<S, E, C> { // /** // * Called when a transition occurs // * @param from the state the machine was in before the transition // * @param to the state the machine is in after the transition // * @param causedBy the event that triggered the transition // * @param context the context in which the event was fired supplied to the transition // * @param stateMachine the machine for which the transition occurred // */ // void onTransition(S from, S to, E causedBy, C context, StateMachine<S, E, C> stateMachine); // } // // Path: src/main/java/se/fearless/fettle/Condition.java // public interface Condition<C> { // boolean isSatisfied(C context); // } // // Path: src/main/java/se/fearless/fettle/StateMachine.java // public interface StateMachine<S, E, C> { // /** // * Gets the current state of the machine // * // * @return the state the machine is currently in // */ // S getCurrentState(); // // /** // * Fires an event at the state machine, possibly triggering a state change // * // * @param event the event that is fired // * @return true if the event resulted in a state change, false otherwise // */ // boolean fireEvent(E event); // // /** // * Fires an event at the state machine, possibly triggering a state change // * // * @param event the event that is fired // * @param context the context to be sent to any actions that are run on a state change. Used to supply parameters to // * actions and conditions // * @return true if the event resulted in a state change, false otherwise // */ // boolean fireEvent(E event, C context); // // /** // * Sets the state of the state machine to the rawState even if there are no transitions leading to it // * No transition, entry or exit actions are run // * // * @param rawState the state the machine will be in after this method is called // */ // void rawSetState(S rawState); // // /** // * Forces the state machine to enter the forcedState even if there are no transitions leading to it // * No transition actions are run but exit actions on the current state and entry actions on the new state are run // * // * @param forcedState the state the machine will be in after this method is called // * @return true if the state machine changed state // */ // boolean forceSetState(S forcedState); // // /** // * Returns all possible transitions from a given state grouped by the event that triggers the transition. // * @param fromState the state to retrieve the outgoing transitions from. // * @return a map from all registered events in the fromState to the transitions they would trigger if fired. // */ // Map<E, Collection<? extends Transition<S, E, C>>> getPossibleTransitions(S fromState); // } // // Path: src/main/java/se/fearless/fettle/Transition.java // public interface Transition<S, E, C> { // S getTo(); // // boolean isSatisfied(C context); // // void onTransition(S from, S to, E event, C context, StateMachine<S, E, C> statemachine); // // boolean shouldExecuteEntryAndExitActions(); // } // // Path: src/main/java/se/fearless/fettle/util/GuavaReplacement.java // public class GuavaReplacement { // private GuavaReplacement() { // } // // public static <T> List<T> newArrayList() { // return new ArrayList<>(); // } // // public static <K, V> Map<K, V> newHashMap() { // return new HashMap<>(); // } // } // Path: src/main/java/se/fearless/fettle/impl/AbstractTransition.java import se.fearless.fettle.Action; import se.fearless.fettle.Condition; import se.fearless.fettle.StateMachine; import se.fearless.fettle.Transition; import se.fearless.fettle.util.GuavaReplacement; import java.util.Collection; package se.fearless.fettle.impl; public abstract class AbstractTransition<S, E, C> implements Transition<S, E, C> { protected final S to; protected final Condition<C> condition;
protected final Collection<Action<S, E, C>> actions = GuavaReplacement.newArrayList();
thehiflyer/Fettle
src/main/java/se/fearless/fettle/impl/AbstractTransition.java
// Path: src/main/java/se/fearless/fettle/Action.java // public interface Action<S, E, C> { // /** // * Called when a transition occurs // * @param from the state the machine was in before the transition // * @param to the state the machine is in after the transition // * @param causedBy the event that triggered the transition // * @param context the context in which the event was fired supplied to the transition // * @param stateMachine the machine for which the transition occurred // */ // void onTransition(S from, S to, E causedBy, C context, StateMachine<S, E, C> stateMachine); // } // // Path: src/main/java/se/fearless/fettle/Condition.java // public interface Condition<C> { // boolean isSatisfied(C context); // } // // Path: src/main/java/se/fearless/fettle/StateMachine.java // public interface StateMachine<S, E, C> { // /** // * Gets the current state of the machine // * // * @return the state the machine is currently in // */ // S getCurrentState(); // // /** // * Fires an event at the state machine, possibly triggering a state change // * // * @param event the event that is fired // * @return true if the event resulted in a state change, false otherwise // */ // boolean fireEvent(E event); // // /** // * Fires an event at the state machine, possibly triggering a state change // * // * @param event the event that is fired // * @param context the context to be sent to any actions that are run on a state change. Used to supply parameters to // * actions and conditions // * @return true if the event resulted in a state change, false otherwise // */ // boolean fireEvent(E event, C context); // // /** // * Sets the state of the state machine to the rawState even if there are no transitions leading to it // * No transition, entry or exit actions are run // * // * @param rawState the state the machine will be in after this method is called // */ // void rawSetState(S rawState); // // /** // * Forces the state machine to enter the forcedState even if there are no transitions leading to it // * No transition actions are run but exit actions on the current state and entry actions on the new state are run // * // * @param forcedState the state the machine will be in after this method is called // * @return true if the state machine changed state // */ // boolean forceSetState(S forcedState); // // /** // * Returns all possible transitions from a given state grouped by the event that triggers the transition. // * @param fromState the state to retrieve the outgoing transitions from. // * @return a map from all registered events in the fromState to the transitions they would trigger if fired. // */ // Map<E, Collection<? extends Transition<S, E, C>>> getPossibleTransitions(S fromState); // } // // Path: src/main/java/se/fearless/fettle/Transition.java // public interface Transition<S, E, C> { // S getTo(); // // boolean isSatisfied(C context); // // void onTransition(S from, S to, E event, C context, StateMachine<S, E, C> statemachine); // // boolean shouldExecuteEntryAndExitActions(); // } // // Path: src/main/java/se/fearless/fettle/util/GuavaReplacement.java // public class GuavaReplacement { // private GuavaReplacement() { // } // // public static <T> List<T> newArrayList() { // return new ArrayList<>(); // } // // public static <K, V> Map<K, V> newHashMap() { // return new HashMap<>(); // } // }
import se.fearless.fettle.Action; import se.fearless.fettle.Condition; import se.fearless.fettle.StateMachine; import se.fearless.fettle.Transition; import se.fearless.fettle.util.GuavaReplacement; import java.util.Collection;
package se.fearless.fettle.impl; public abstract class AbstractTransition<S, E, C> implements Transition<S, E, C> { protected final S to; protected final Condition<C> condition;
// Path: src/main/java/se/fearless/fettle/Action.java // public interface Action<S, E, C> { // /** // * Called when a transition occurs // * @param from the state the machine was in before the transition // * @param to the state the machine is in after the transition // * @param causedBy the event that triggered the transition // * @param context the context in which the event was fired supplied to the transition // * @param stateMachine the machine for which the transition occurred // */ // void onTransition(S from, S to, E causedBy, C context, StateMachine<S, E, C> stateMachine); // } // // Path: src/main/java/se/fearless/fettle/Condition.java // public interface Condition<C> { // boolean isSatisfied(C context); // } // // Path: src/main/java/se/fearless/fettle/StateMachine.java // public interface StateMachine<S, E, C> { // /** // * Gets the current state of the machine // * // * @return the state the machine is currently in // */ // S getCurrentState(); // // /** // * Fires an event at the state machine, possibly triggering a state change // * // * @param event the event that is fired // * @return true if the event resulted in a state change, false otherwise // */ // boolean fireEvent(E event); // // /** // * Fires an event at the state machine, possibly triggering a state change // * // * @param event the event that is fired // * @param context the context to be sent to any actions that are run on a state change. Used to supply parameters to // * actions and conditions // * @return true if the event resulted in a state change, false otherwise // */ // boolean fireEvent(E event, C context); // // /** // * Sets the state of the state machine to the rawState even if there are no transitions leading to it // * No transition, entry or exit actions are run // * // * @param rawState the state the machine will be in after this method is called // */ // void rawSetState(S rawState); // // /** // * Forces the state machine to enter the forcedState even if there are no transitions leading to it // * No transition actions are run but exit actions on the current state and entry actions on the new state are run // * // * @param forcedState the state the machine will be in after this method is called // * @return true if the state machine changed state // */ // boolean forceSetState(S forcedState); // // /** // * Returns all possible transitions from a given state grouped by the event that triggers the transition. // * @param fromState the state to retrieve the outgoing transitions from. // * @return a map from all registered events in the fromState to the transitions they would trigger if fired. // */ // Map<E, Collection<? extends Transition<S, E, C>>> getPossibleTransitions(S fromState); // } // // Path: src/main/java/se/fearless/fettle/Transition.java // public interface Transition<S, E, C> { // S getTo(); // // boolean isSatisfied(C context); // // void onTransition(S from, S to, E event, C context, StateMachine<S, E, C> statemachine); // // boolean shouldExecuteEntryAndExitActions(); // } // // Path: src/main/java/se/fearless/fettle/util/GuavaReplacement.java // public class GuavaReplacement { // private GuavaReplacement() { // } // // public static <T> List<T> newArrayList() { // return new ArrayList<>(); // } // // public static <K, V> Map<K, V> newHashMap() { // return new HashMap<>(); // } // } // Path: src/main/java/se/fearless/fettle/impl/AbstractTransition.java import se.fearless.fettle.Action; import se.fearless.fettle.Condition; import se.fearless.fettle.StateMachine; import se.fearless.fettle.Transition; import se.fearless.fettle.util.GuavaReplacement; import java.util.Collection; package se.fearless.fettle.impl; public abstract class AbstractTransition<S, E, C> implements Transition<S, E, C> { protected final S to; protected final Condition<C> condition;
protected final Collection<Action<S, E, C>> actions = GuavaReplacement.newArrayList();
thehiflyer/Fettle
src/main/java/se/fearless/fettle/impl/AbstractTransition.java
// Path: src/main/java/se/fearless/fettle/Action.java // public interface Action<S, E, C> { // /** // * Called when a transition occurs // * @param from the state the machine was in before the transition // * @param to the state the machine is in after the transition // * @param causedBy the event that triggered the transition // * @param context the context in which the event was fired supplied to the transition // * @param stateMachine the machine for which the transition occurred // */ // void onTransition(S from, S to, E causedBy, C context, StateMachine<S, E, C> stateMachine); // } // // Path: src/main/java/se/fearless/fettle/Condition.java // public interface Condition<C> { // boolean isSatisfied(C context); // } // // Path: src/main/java/se/fearless/fettle/StateMachine.java // public interface StateMachine<S, E, C> { // /** // * Gets the current state of the machine // * // * @return the state the machine is currently in // */ // S getCurrentState(); // // /** // * Fires an event at the state machine, possibly triggering a state change // * // * @param event the event that is fired // * @return true if the event resulted in a state change, false otherwise // */ // boolean fireEvent(E event); // // /** // * Fires an event at the state machine, possibly triggering a state change // * // * @param event the event that is fired // * @param context the context to be sent to any actions that are run on a state change. Used to supply parameters to // * actions and conditions // * @return true if the event resulted in a state change, false otherwise // */ // boolean fireEvent(E event, C context); // // /** // * Sets the state of the state machine to the rawState even if there are no transitions leading to it // * No transition, entry or exit actions are run // * // * @param rawState the state the machine will be in after this method is called // */ // void rawSetState(S rawState); // // /** // * Forces the state machine to enter the forcedState even if there are no transitions leading to it // * No transition actions are run but exit actions on the current state and entry actions on the new state are run // * // * @param forcedState the state the machine will be in after this method is called // * @return true if the state machine changed state // */ // boolean forceSetState(S forcedState); // // /** // * Returns all possible transitions from a given state grouped by the event that triggers the transition. // * @param fromState the state to retrieve the outgoing transitions from. // * @return a map from all registered events in the fromState to the transitions they would trigger if fired. // */ // Map<E, Collection<? extends Transition<S, E, C>>> getPossibleTransitions(S fromState); // } // // Path: src/main/java/se/fearless/fettle/Transition.java // public interface Transition<S, E, C> { // S getTo(); // // boolean isSatisfied(C context); // // void onTransition(S from, S to, E event, C context, StateMachine<S, E, C> statemachine); // // boolean shouldExecuteEntryAndExitActions(); // } // // Path: src/main/java/se/fearless/fettle/util/GuavaReplacement.java // public class GuavaReplacement { // private GuavaReplacement() { // } // // public static <T> List<T> newArrayList() { // return new ArrayList<>(); // } // // public static <K, V> Map<K, V> newHashMap() { // return new HashMap<>(); // } // }
import se.fearless.fettle.Action; import se.fearless.fettle.Condition; import se.fearless.fettle.StateMachine; import se.fearless.fettle.Transition; import se.fearless.fettle.util.GuavaReplacement; import java.util.Collection;
package se.fearless.fettle.impl; public abstract class AbstractTransition<S, E, C> implements Transition<S, E, C> { protected final S to; protected final Condition<C> condition; protected final Collection<Action<S, E, C>> actions = GuavaReplacement.newArrayList(); public AbstractTransition(S to, Condition<C> condition, Collection<Action<S, E, C>> actions) { this.condition = condition; this.to = to; this.actions.addAll(actions); } @Override public S getTo() { return to; } @Override public boolean isSatisfied(C context) { return condition.isSatisfied(context); } public Condition<C> getCondition() { return condition; } @Override
// Path: src/main/java/se/fearless/fettle/Action.java // public interface Action<S, E, C> { // /** // * Called when a transition occurs // * @param from the state the machine was in before the transition // * @param to the state the machine is in after the transition // * @param causedBy the event that triggered the transition // * @param context the context in which the event was fired supplied to the transition // * @param stateMachine the machine for which the transition occurred // */ // void onTransition(S from, S to, E causedBy, C context, StateMachine<S, E, C> stateMachine); // } // // Path: src/main/java/se/fearless/fettle/Condition.java // public interface Condition<C> { // boolean isSatisfied(C context); // } // // Path: src/main/java/se/fearless/fettle/StateMachine.java // public interface StateMachine<S, E, C> { // /** // * Gets the current state of the machine // * // * @return the state the machine is currently in // */ // S getCurrentState(); // // /** // * Fires an event at the state machine, possibly triggering a state change // * // * @param event the event that is fired // * @return true if the event resulted in a state change, false otherwise // */ // boolean fireEvent(E event); // // /** // * Fires an event at the state machine, possibly triggering a state change // * // * @param event the event that is fired // * @param context the context to be sent to any actions that are run on a state change. Used to supply parameters to // * actions and conditions // * @return true if the event resulted in a state change, false otherwise // */ // boolean fireEvent(E event, C context); // // /** // * Sets the state of the state machine to the rawState even if there are no transitions leading to it // * No transition, entry or exit actions are run // * // * @param rawState the state the machine will be in after this method is called // */ // void rawSetState(S rawState); // // /** // * Forces the state machine to enter the forcedState even if there are no transitions leading to it // * No transition actions are run but exit actions on the current state and entry actions on the new state are run // * // * @param forcedState the state the machine will be in after this method is called // * @return true if the state machine changed state // */ // boolean forceSetState(S forcedState); // // /** // * Returns all possible transitions from a given state grouped by the event that triggers the transition. // * @param fromState the state to retrieve the outgoing transitions from. // * @return a map from all registered events in the fromState to the transitions they would trigger if fired. // */ // Map<E, Collection<? extends Transition<S, E, C>>> getPossibleTransitions(S fromState); // } // // Path: src/main/java/se/fearless/fettle/Transition.java // public interface Transition<S, E, C> { // S getTo(); // // boolean isSatisfied(C context); // // void onTransition(S from, S to, E event, C context, StateMachine<S, E, C> statemachine); // // boolean shouldExecuteEntryAndExitActions(); // } // // Path: src/main/java/se/fearless/fettle/util/GuavaReplacement.java // public class GuavaReplacement { // private GuavaReplacement() { // } // // public static <T> List<T> newArrayList() { // return new ArrayList<>(); // } // // public static <K, V> Map<K, V> newHashMap() { // return new HashMap<>(); // } // } // Path: src/main/java/se/fearless/fettle/impl/AbstractTransition.java import se.fearless.fettle.Action; import se.fearless.fettle.Condition; import se.fearless.fettle.StateMachine; import se.fearless.fettle.Transition; import se.fearless.fettle.util.GuavaReplacement; import java.util.Collection; package se.fearless.fettle.impl; public abstract class AbstractTransition<S, E, C> implements Transition<S, E, C> { protected final S to; protected final Condition<C> condition; protected final Collection<Action<S, E, C>> actions = GuavaReplacement.newArrayList(); public AbstractTransition(S to, Condition<C> condition, Collection<Action<S, E, C>> actions) { this.condition = condition; this.to = to; this.actions.addAll(actions); } @Override public S getTo() { return to; } @Override public boolean isSatisfied(C context) { return condition.isSatisfied(context); } public Condition<C> getCondition() { return condition; } @Override
public void onTransition(S from, S to, E event, C context, StateMachine<S, E, C> statemachine) {
thehiflyer/Fettle
src/test/java/se/fearless/fettle/CompleteCoverageTest.java
// Path: src/main/java/se/fearless/fettle/util/GuavaReplacement.java // public class GuavaReplacement { // private GuavaReplacement() { // } // // public static <T> List<T> newArrayList() { // return new ArrayList<>(); // } // // public static <K, V> Map<K, V> newHashMap() { // return new HashMap<>(); // } // }
import org.junit.Test; import se.fearless.fettle.util.GuavaReplacement; import java.lang.reflect.Constructor;
package se.fearless.fettle; /** * The tests in here are not really tests and are not useful for anything but getting the coverage to 100%. * I don't care about that metric hitting 100 as much as it makes any place I've missed to cover really stand out */ public class CompleteCoverageTest { @Test public void createGuavaReplacement() throws Exception {
// Path: src/main/java/se/fearless/fettle/util/GuavaReplacement.java // public class GuavaReplacement { // private GuavaReplacement() { // } // // public static <T> List<T> newArrayList() { // return new ArrayList<>(); // } // // public static <K, V> Map<K, V> newHashMap() { // return new HashMap<>(); // } // } // Path: src/test/java/se/fearless/fettle/CompleteCoverageTest.java import org.junit.Test; import se.fearless.fettle.util.GuavaReplacement; import java.lang.reflect.Constructor; package se.fearless.fettle; /** * The tests in here are not really tests and are not useful for anything but getting the coverage to 100%. * I don't care about that metric hitting 100 as much as it makes any place I've missed to cover really stand out */ public class CompleteCoverageTest { @Test public void createGuavaReplacement() throws Exception {
Constructor<?>[] constructors = GuavaReplacement.class.getDeclaredConstructors();
thehiflyer/Fettle
src/main/java/se/fearless/fettle/impl/TemplateBasedStateMachine.java
// Path: src/main/java/se/fearless/fettle/StateMachine.java // public interface StateMachine<S, E, C> { // /** // * Gets the current state of the machine // * // * @return the state the machine is currently in // */ // S getCurrentState(); // // /** // * Fires an event at the state machine, possibly triggering a state change // * // * @param event the event that is fired // * @return true if the event resulted in a state change, false otherwise // */ // boolean fireEvent(E event); // // /** // * Fires an event at the state machine, possibly triggering a state change // * // * @param event the event that is fired // * @param context the context to be sent to any actions that are run on a state change. Used to supply parameters to // * actions and conditions // * @return true if the event resulted in a state change, false otherwise // */ // boolean fireEvent(E event, C context); // // /** // * Sets the state of the state machine to the rawState even if there are no transitions leading to it // * No transition, entry or exit actions are run // * // * @param rawState the state the machine will be in after this method is called // */ // void rawSetState(S rawState); // // /** // * Forces the state machine to enter the forcedState even if there are no transitions leading to it // * No transition actions are run but exit actions on the current state and entry actions on the new state are run // * // * @param forcedState the state the machine will be in after this method is called // * @return true if the state machine changed state // */ // boolean forceSetState(S forcedState); // // /** // * Returns all possible transitions from a given state grouped by the event that triggers the transition. // * @param fromState the state to retrieve the outgoing transitions from. // * @return a map from all registered events in the fromState to the transitions they would trigger if fired. // */ // Map<E, Collection<? extends Transition<S, E, C>>> getPossibleTransitions(S fromState); // } // // Path: src/main/java/se/fearless/fettle/Transition.java // public interface Transition<S, E, C> { // S getTo(); // // boolean isSatisfied(C context); // // void onTransition(S from, S to, E event, C context, StateMachine<S, E, C> statemachine); // // boolean shouldExecuteEntryAndExitActions(); // } // // Path: src/main/java/se/fearless/fettle/TransitionModel.java // public interface TransitionModel<S, E, C> { // // /** // * Fires the event at the state machine. This can result in a state change and trigger actions to be run. // * @param machine the machine to fire the event at // * @param event the event to fire // * @param context the context to use for transition conditions and actions. The context can be used to // * supply arguments to actions. // * @return true if a state change was triggered, false otherwise. // * Note that this will return true if a transition to the same state occurs // */ // boolean fireEvent(StateMachine<S, E, C> machine, E event, C context); // // /** // * Forces the state machine to enter the forcedState even if there are no transitions to that state. // * No transition actions are run but exit actions on the current state and entry actions on the new state are run // * @param stateMachine the state machine to force the state for // * @param forcedState the state the machine will be in after this method // * @return true if the state was changed // */ // boolean forceSetState(StateMachine<S, E, C> stateMachine, S forcedState); // // C getDefaultContext(); // // Map<E, Collection<? extends Transition<S, E, C>>> getPossibleTransitions(S fromState); // } // // Path: src/main/resources/super/java/util/concurrent/locks/Lock.java // public interface Lock { // void lock(); // void unlock(); // }
import se.fearless.fettle.StateMachine; import se.fearless.fettle.Transition; import se.fearless.fettle.TransitionModel; import java.util.Collection; import java.util.Map; import java.util.concurrent.locks.Lock;
package se.fearless.fettle.impl; public class TemplateBasedStateMachine<S, E, C> implements StateMachine<S, E, C> { private final TransitionModel<S, E, C> model;
// Path: src/main/java/se/fearless/fettle/StateMachine.java // public interface StateMachine<S, E, C> { // /** // * Gets the current state of the machine // * // * @return the state the machine is currently in // */ // S getCurrentState(); // // /** // * Fires an event at the state machine, possibly triggering a state change // * // * @param event the event that is fired // * @return true if the event resulted in a state change, false otherwise // */ // boolean fireEvent(E event); // // /** // * Fires an event at the state machine, possibly triggering a state change // * // * @param event the event that is fired // * @param context the context to be sent to any actions that are run on a state change. Used to supply parameters to // * actions and conditions // * @return true if the event resulted in a state change, false otherwise // */ // boolean fireEvent(E event, C context); // // /** // * Sets the state of the state machine to the rawState even if there are no transitions leading to it // * No transition, entry or exit actions are run // * // * @param rawState the state the machine will be in after this method is called // */ // void rawSetState(S rawState); // // /** // * Forces the state machine to enter the forcedState even if there are no transitions leading to it // * No transition actions are run but exit actions on the current state and entry actions on the new state are run // * // * @param forcedState the state the machine will be in after this method is called // * @return true if the state machine changed state // */ // boolean forceSetState(S forcedState); // // /** // * Returns all possible transitions from a given state grouped by the event that triggers the transition. // * @param fromState the state to retrieve the outgoing transitions from. // * @return a map from all registered events in the fromState to the transitions they would trigger if fired. // */ // Map<E, Collection<? extends Transition<S, E, C>>> getPossibleTransitions(S fromState); // } // // Path: src/main/java/se/fearless/fettle/Transition.java // public interface Transition<S, E, C> { // S getTo(); // // boolean isSatisfied(C context); // // void onTransition(S from, S to, E event, C context, StateMachine<S, E, C> statemachine); // // boolean shouldExecuteEntryAndExitActions(); // } // // Path: src/main/java/se/fearless/fettle/TransitionModel.java // public interface TransitionModel<S, E, C> { // // /** // * Fires the event at the state machine. This can result in a state change and trigger actions to be run. // * @param machine the machine to fire the event at // * @param event the event to fire // * @param context the context to use for transition conditions and actions. The context can be used to // * supply arguments to actions. // * @return true if a state change was triggered, false otherwise. // * Note that this will return true if a transition to the same state occurs // */ // boolean fireEvent(StateMachine<S, E, C> machine, E event, C context); // // /** // * Forces the state machine to enter the forcedState even if there are no transitions to that state. // * No transition actions are run but exit actions on the current state and entry actions on the new state are run // * @param stateMachine the state machine to force the state for // * @param forcedState the state the machine will be in after this method // * @return true if the state was changed // */ // boolean forceSetState(StateMachine<S, E, C> stateMachine, S forcedState); // // C getDefaultContext(); // // Map<E, Collection<? extends Transition<S, E, C>>> getPossibleTransitions(S fromState); // } // // Path: src/main/resources/super/java/util/concurrent/locks/Lock.java // public interface Lock { // void lock(); // void unlock(); // } // Path: src/main/java/se/fearless/fettle/impl/TemplateBasedStateMachine.java import se.fearless.fettle.StateMachine; import se.fearless.fettle.Transition; import se.fearless.fettle.TransitionModel; import java.util.Collection; import java.util.Map; import java.util.concurrent.locks.Lock; package se.fearless.fettle.impl; public class TemplateBasedStateMachine<S, E, C> implements StateMachine<S, E, C> { private final TransitionModel<S, E, C> model;
private final Lock lock;
thehiflyer/Fettle
src/main/java/se/fearless/fettle/impl/TemplateBasedStateMachine.java
// Path: src/main/java/se/fearless/fettle/StateMachine.java // public interface StateMachine<S, E, C> { // /** // * Gets the current state of the machine // * // * @return the state the machine is currently in // */ // S getCurrentState(); // // /** // * Fires an event at the state machine, possibly triggering a state change // * // * @param event the event that is fired // * @return true if the event resulted in a state change, false otherwise // */ // boolean fireEvent(E event); // // /** // * Fires an event at the state machine, possibly triggering a state change // * // * @param event the event that is fired // * @param context the context to be sent to any actions that are run on a state change. Used to supply parameters to // * actions and conditions // * @return true if the event resulted in a state change, false otherwise // */ // boolean fireEvent(E event, C context); // // /** // * Sets the state of the state machine to the rawState even if there are no transitions leading to it // * No transition, entry or exit actions are run // * // * @param rawState the state the machine will be in after this method is called // */ // void rawSetState(S rawState); // // /** // * Forces the state machine to enter the forcedState even if there are no transitions leading to it // * No transition actions are run but exit actions on the current state and entry actions on the new state are run // * // * @param forcedState the state the machine will be in after this method is called // * @return true if the state machine changed state // */ // boolean forceSetState(S forcedState); // // /** // * Returns all possible transitions from a given state grouped by the event that triggers the transition. // * @param fromState the state to retrieve the outgoing transitions from. // * @return a map from all registered events in the fromState to the transitions they would trigger if fired. // */ // Map<E, Collection<? extends Transition<S, E, C>>> getPossibleTransitions(S fromState); // } // // Path: src/main/java/se/fearless/fettle/Transition.java // public interface Transition<S, E, C> { // S getTo(); // // boolean isSatisfied(C context); // // void onTransition(S from, S to, E event, C context, StateMachine<S, E, C> statemachine); // // boolean shouldExecuteEntryAndExitActions(); // } // // Path: src/main/java/se/fearless/fettle/TransitionModel.java // public interface TransitionModel<S, E, C> { // // /** // * Fires the event at the state machine. This can result in a state change and trigger actions to be run. // * @param machine the machine to fire the event at // * @param event the event to fire // * @param context the context to use for transition conditions and actions. The context can be used to // * supply arguments to actions. // * @return true if a state change was triggered, false otherwise. // * Note that this will return true if a transition to the same state occurs // */ // boolean fireEvent(StateMachine<S, E, C> machine, E event, C context); // // /** // * Forces the state machine to enter the forcedState even if there are no transitions to that state. // * No transition actions are run but exit actions on the current state and entry actions on the new state are run // * @param stateMachine the state machine to force the state for // * @param forcedState the state the machine will be in after this method // * @return true if the state was changed // */ // boolean forceSetState(StateMachine<S, E, C> stateMachine, S forcedState); // // C getDefaultContext(); // // Map<E, Collection<? extends Transition<S, E, C>>> getPossibleTransitions(S fromState); // } // // Path: src/main/resources/super/java/util/concurrent/locks/Lock.java // public interface Lock { // void lock(); // void unlock(); // }
import se.fearless.fettle.StateMachine; import se.fearless.fettle.Transition; import se.fearless.fettle.TransitionModel; import java.util.Collection; import java.util.Map; import java.util.concurrent.locks.Lock;
@Override public boolean fireEvent(E event, C context) { lock.lock(); try { return model.fireEvent(this, event, context); } finally { lock.unlock(); } } @Override public void rawSetState(S rawState) { lock.lock(); currentState = rawState; lock.unlock(); } @Override public boolean forceSetState(S forcedState) { lock.lock(); try { return model.forceSetState(this, forcedState); } finally { lock.unlock(); } } @Override
// Path: src/main/java/se/fearless/fettle/StateMachine.java // public interface StateMachine<S, E, C> { // /** // * Gets the current state of the machine // * // * @return the state the machine is currently in // */ // S getCurrentState(); // // /** // * Fires an event at the state machine, possibly triggering a state change // * // * @param event the event that is fired // * @return true if the event resulted in a state change, false otherwise // */ // boolean fireEvent(E event); // // /** // * Fires an event at the state machine, possibly triggering a state change // * // * @param event the event that is fired // * @param context the context to be sent to any actions that are run on a state change. Used to supply parameters to // * actions and conditions // * @return true if the event resulted in a state change, false otherwise // */ // boolean fireEvent(E event, C context); // // /** // * Sets the state of the state machine to the rawState even if there are no transitions leading to it // * No transition, entry or exit actions are run // * // * @param rawState the state the machine will be in after this method is called // */ // void rawSetState(S rawState); // // /** // * Forces the state machine to enter the forcedState even if there are no transitions leading to it // * No transition actions are run but exit actions on the current state and entry actions on the new state are run // * // * @param forcedState the state the machine will be in after this method is called // * @return true if the state machine changed state // */ // boolean forceSetState(S forcedState); // // /** // * Returns all possible transitions from a given state grouped by the event that triggers the transition. // * @param fromState the state to retrieve the outgoing transitions from. // * @return a map from all registered events in the fromState to the transitions they would trigger if fired. // */ // Map<E, Collection<? extends Transition<S, E, C>>> getPossibleTransitions(S fromState); // } // // Path: src/main/java/se/fearless/fettle/Transition.java // public interface Transition<S, E, C> { // S getTo(); // // boolean isSatisfied(C context); // // void onTransition(S from, S to, E event, C context, StateMachine<S, E, C> statemachine); // // boolean shouldExecuteEntryAndExitActions(); // } // // Path: src/main/java/se/fearless/fettle/TransitionModel.java // public interface TransitionModel<S, E, C> { // // /** // * Fires the event at the state machine. This can result in a state change and trigger actions to be run. // * @param machine the machine to fire the event at // * @param event the event to fire // * @param context the context to use for transition conditions and actions. The context can be used to // * supply arguments to actions. // * @return true if a state change was triggered, false otherwise. // * Note that this will return true if a transition to the same state occurs // */ // boolean fireEvent(StateMachine<S, E, C> machine, E event, C context); // // /** // * Forces the state machine to enter the forcedState even if there are no transitions to that state. // * No transition actions are run but exit actions on the current state and entry actions on the new state are run // * @param stateMachine the state machine to force the state for // * @param forcedState the state the machine will be in after this method // * @return true if the state was changed // */ // boolean forceSetState(StateMachine<S, E, C> stateMachine, S forcedState); // // C getDefaultContext(); // // Map<E, Collection<? extends Transition<S, E, C>>> getPossibleTransitions(S fromState); // } // // Path: src/main/resources/super/java/util/concurrent/locks/Lock.java // public interface Lock { // void lock(); // void unlock(); // } // Path: src/main/java/se/fearless/fettle/impl/TemplateBasedStateMachine.java import se.fearless.fettle.StateMachine; import se.fearless.fettle.Transition; import se.fearless.fettle.TransitionModel; import java.util.Collection; import java.util.Map; import java.util.concurrent.locks.Lock; @Override public boolean fireEvent(E event, C context) { lock.lock(); try { return model.fireEvent(this, event, context); } finally { lock.unlock(); } } @Override public void rawSetState(S rawState) { lock.lock(); currentState = rawState; lock.unlock(); } @Override public boolean forceSetState(S forcedState) { lock.lock(); try { return model.forceSetState(this, forcedState); } finally { lock.unlock(); } } @Override
public Map<E, Collection<? extends Transition<S, E, C>>> getPossibleTransitions(S fromState) {
thehiflyer/Fettle
src/main/java/se/fearless/fettle/impl/AbstractTransitionModel.java
// Path: src/main/java/se/fearless/fettle/Action.java // public interface Action<S, E, C> { // /** // * Called when a transition occurs // * @param from the state the machine was in before the transition // * @param to the state the machine is in after the transition // * @param causedBy the event that triggered the transition // * @param context the context in which the event was fired supplied to the transition // * @param stateMachine the machine for which the transition occurred // */ // void onTransition(S from, S to, E causedBy, C context, StateMachine<S, E, C> stateMachine); // } // // Path: src/main/java/se/fearless/fettle/StateMachine.java // public interface StateMachine<S, E, C> { // /** // * Gets the current state of the machine // * // * @return the state the machine is currently in // */ // S getCurrentState(); // // /** // * Fires an event at the state machine, possibly triggering a state change // * // * @param event the event that is fired // * @return true if the event resulted in a state change, false otherwise // */ // boolean fireEvent(E event); // // /** // * Fires an event at the state machine, possibly triggering a state change // * // * @param event the event that is fired // * @param context the context to be sent to any actions that are run on a state change. Used to supply parameters to // * actions and conditions // * @return true if the event resulted in a state change, false otherwise // */ // boolean fireEvent(E event, C context); // // /** // * Sets the state of the state machine to the rawState even if there are no transitions leading to it // * No transition, entry or exit actions are run // * // * @param rawState the state the machine will be in after this method is called // */ // void rawSetState(S rawState); // // /** // * Forces the state machine to enter the forcedState even if there are no transitions leading to it // * No transition actions are run but exit actions on the current state and entry actions on the new state are run // * // * @param forcedState the state the machine will be in after this method is called // * @return true if the state machine changed state // */ // boolean forceSetState(S forcedState); // // /** // * Returns all possible transitions from a given state grouped by the event that triggers the transition. // * @param fromState the state to retrieve the outgoing transitions from. // * @return a map from all registered events in the fromState to the transitions they would trigger if fired. // */ // Map<E, Collection<? extends Transition<S, E, C>>> getPossibleTransitions(S fromState); // } // // Path: src/main/java/se/fearless/fettle/Transition.java // public interface Transition<S, E, C> { // S getTo(); // // boolean isSatisfied(C context); // // void onTransition(S from, S to, E event, C context, StateMachine<S, E, C> statemachine); // // boolean shouldExecuteEntryAndExitActions(); // } // // Path: src/main/java/se/fearless/fettle/TransitionModel.java // public interface TransitionModel<S, E, C> { // // /** // * Fires the event at the state machine. This can result in a state change and trigger actions to be run. // * @param machine the machine to fire the event at // * @param event the event to fire // * @param context the context to use for transition conditions and actions. The context can be used to // * supply arguments to actions. // * @return true if a state change was triggered, false otherwise. // * Note that this will return true if a transition to the same state occurs // */ // boolean fireEvent(StateMachine<S, E, C> machine, E event, C context); // // /** // * Forces the state machine to enter the forcedState even if there are no transitions to that state. // * No transition actions are run but exit actions on the current state and entry actions on the new state are run // * @param stateMachine the state machine to force the state for // * @param forcedState the state the machine will be in after this method // * @return true if the state was changed // */ // boolean forceSetState(StateMachine<S, E, C> stateMachine, S forcedState); // // C getDefaultContext(); // // Map<E, Collection<? extends Transition<S, E, C>>> getPossibleTransitions(S fromState); // } // // Path: src/main/java/se/fearless/fettle/util/GuavaReplacement.java // public class GuavaReplacement { // private GuavaReplacement() { // } // // public static <T> List<T> newArrayList() { // return new ArrayList<>(); // } // // public static <K, V> Map<K, V> newHashMap() { // return new HashMap<>(); // } // }
import se.fearless.fettle.Action; import se.fearless.fettle.StateMachine; import se.fearless.fettle.Transition; import se.fearless.fettle.TransitionModel; import se.fearless.fettle.util.GuavaReplacement; import java.util.Collection; import java.util.Collections; import java.util.EnumMap; import java.util.Map;
package se.fearless.fettle.impl; public abstract class AbstractTransitionModel<S, E, C> implements TransitionModel<S, E, C> { protected final Map<S, Map<E, Collection<Transition<S, E, C>>>> transitionMap; protected final Map<E, Collection<Transition<S, E, C>>> fromAllTransitions;
// Path: src/main/java/se/fearless/fettle/Action.java // public interface Action<S, E, C> { // /** // * Called when a transition occurs // * @param from the state the machine was in before the transition // * @param to the state the machine is in after the transition // * @param causedBy the event that triggered the transition // * @param context the context in which the event was fired supplied to the transition // * @param stateMachine the machine for which the transition occurred // */ // void onTransition(S from, S to, E causedBy, C context, StateMachine<S, E, C> stateMachine); // } // // Path: src/main/java/se/fearless/fettle/StateMachine.java // public interface StateMachine<S, E, C> { // /** // * Gets the current state of the machine // * // * @return the state the machine is currently in // */ // S getCurrentState(); // // /** // * Fires an event at the state machine, possibly triggering a state change // * // * @param event the event that is fired // * @return true if the event resulted in a state change, false otherwise // */ // boolean fireEvent(E event); // // /** // * Fires an event at the state machine, possibly triggering a state change // * // * @param event the event that is fired // * @param context the context to be sent to any actions that are run on a state change. Used to supply parameters to // * actions and conditions // * @return true if the event resulted in a state change, false otherwise // */ // boolean fireEvent(E event, C context); // // /** // * Sets the state of the state machine to the rawState even if there are no transitions leading to it // * No transition, entry or exit actions are run // * // * @param rawState the state the machine will be in after this method is called // */ // void rawSetState(S rawState); // // /** // * Forces the state machine to enter the forcedState even if there are no transitions leading to it // * No transition actions are run but exit actions on the current state and entry actions on the new state are run // * // * @param forcedState the state the machine will be in after this method is called // * @return true if the state machine changed state // */ // boolean forceSetState(S forcedState); // // /** // * Returns all possible transitions from a given state grouped by the event that triggers the transition. // * @param fromState the state to retrieve the outgoing transitions from. // * @return a map from all registered events in the fromState to the transitions they would trigger if fired. // */ // Map<E, Collection<? extends Transition<S, E, C>>> getPossibleTransitions(S fromState); // } // // Path: src/main/java/se/fearless/fettle/Transition.java // public interface Transition<S, E, C> { // S getTo(); // // boolean isSatisfied(C context); // // void onTransition(S from, S to, E event, C context, StateMachine<S, E, C> statemachine); // // boolean shouldExecuteEntryAndExitActions(); // } // // Path: src/main/java/se/fearless/fettle/TransitionModel.java // public interface TransitionModel<S, E, C> { // // /** // * Fires the event at the state machine. This can result in a state change and trigger actions to be run. // * @param machine the machine to fire the event at // * @param event the event to fire // * @param context the context to use for transition conditions and actions. The context can be used to // * supply arguments to actions. // * @return true if a state change was triggered, false otherwise. // * Note that this will return true if a transition to the same state occurs // */ // boolean fireEvent(StateMachine<S, E, C> machine, E event, C context); // // /** // * Forces the state machine to enter the forcedState even if there are no transitions to that state. // * No transition actions are run but exit actions on the current state and entry actions on the new state are run // * @param stateMachine the state machine to force the state for // * @param forcedState the state the machine will be in after this method // * @return true if the state was changed // */ // boolean forceSetState(StateMachine<S, E, C> stateMachine, S forcedState); // // C getDefaultContext(); // // Map<E, Collection<? extends Transition<S, E, C>>> getPossibleTransitions(S fromState); // } // // Path: src/main/java/se/fearless/fettle/util/GuavaReplacement.java // public class GuavaReplacement { // private GuavaReplacement() { // } // // public static <T> List<T> newArrayList() { // return new ArrayList<>(); // } // // public static <K, V> Map<K, V> newHashMap() { // return new HashMap<>(); // } // } // Path: src/main/java/se/fearless/fettle/impl/AbstractTransitionModel.java import se.fearless.fettle.Action; import se.fearless.fettle.StateMachine; import se.fearless.fettle.Transition; import se.fearless.fettle.TransitionModel; import se.fearless.fettle.util.GuavaReplacement; import java.util.Collection; import java.util.Collections; import java.util.EnumMap; import java.util.Map; package se.fearless.fettle.impl; public abstract class AbstractTransitionModel<S, E, C> implements TransitionModel<S, E, C> { protected final Map<S, Map<E, Collection<Transition<S, E, C>>>> transitionMap; protected final Map<E, Collection<Transition<S, E, C>>> fromAllTransitions;
protected final Map<S, Collection<Action<S, E, C>>> exitActions;
thehiflyer/Fettle
src/main/java/se/fearless/fettle/impl/AbstractTransitionModel.java
// Path: src/main/java/se/fearless/fettle/Action.java // public interface Action<S, E, C> { // /** // * Called when a transition occurs // * @param from the state the machine was in before the transition // * @param to the state the machine is in after the transition // * @param causedBy the event that triggered the transition // * @param context the context in which the event was fired supplied to the transition // * @param stateMachine the machine for which the transition occurred // */ // void onTransition(S from, S to, E causedBy, C context, StateMachine<S, E, C> stateMachine); // } // // Path: src/main/java/se/fearless/fettle/StateMachine.java // public interface StateMachine<S, E, C> { // /** // * Gets the current state of the machine // * // * @return the state the machine is currently in // */ // S getCurrentState(); // // /** // * Fires an event at the state machine, possibly triggering a state change // * // * @param event the event that is fired // * @return true if the event resulted in a state change, false otherwise // */ // boolean fireEvent(E event); // // /** // * Fires an event at the state machine, possibly triggering a state change // * // * @param event the event that is fired // * @param context the context to be sent to any actions that are run on a state change. Used to supply parameters to // * actions and conditions // * @return true if the event resulted in a state change, false otherwise // */ // boolean fireEvent(E event, C context); // // /** // * Sets the state of the state machine to the rawState even if there are no transitions leading to it // * No transition, entry or exit actions are run // * // * @param rawState the state the machine will be in after this method is called // */ // void rawSetState(S rawState); // // /** // * Forces the state machine to enter the forcedState even if there are no transitions leading to it // * No transition actions are run but exit actions on the current state and entry actions on the new state are run // * // * @param forcedState the state the machine will be in after this method is called // * @return true if the state machine changed state // */ // boolean forceSetState(S forcedState); // // /** // * Returns all possible transitions from a given state grouped by the event that triggers the transition. // * @param fromState the state to retrieve the outgoing transitions from. // * @return a map from all registered events in the fromState to the transitions they would trigger if fired. // */ // Map<E, Collection<? extends Transition<S, E, C>>> getPossibleTransitions(S fromState); // } // // Path: src/main/java/se/fearless/fettle/Transition.java // public interface Transition<S, E, C> { // S getTo(); // // boolean isSatisfied(C context); // // void onTransition(S from, S to, E event, C context, StateMachine<S, E, C> statemachine); // // boolean shouldExecuteEntryAndExitActions(); // } // // Path: src/main/java/se/fearless/fettle/TransitionModel.java // public interface TransitionModel<S, E, C> { // // /** // * Fires the event at the state machine. This can result in a state change and trigger actions to be run. // * @param machine the machine to fire the event at // * @param event the event to fire // * @param context the context to use for transition conditions and actions. The context can be used to // * supply arguments to actions. // * @return true if a state change was triggered, false otherwise. // * Note that this will return true if a transition to the same state occurs // */ // boolean fireEvent(StateMachine<S, E, C> machine, E event, C context); // // /** // * Forces the state machine to enter the forcedState even if there are no transitions to that state. // * No transition actions are run but exit actions on the current state and entry actions on the new state are run // * @param stateMachine the state machine to force the state for // * @param forcedState the state the machine will be in after this method // * @return true if the state was changed // */ // boolean forceSetState(StateMachine<S, E, C> stateMachine, S forcedState); // // C getDefaultContext(); // // Map<E, Collection<? extends Transition<S, E, C>>> getPossibleTransitions(S fromState); // } // // Path: src/main/java/se/fearless/fettle/util/GuavaReplacement.java // public class GuavaReplacement { // private GuavaReplacement() { // } // // public static <T> List<T> newArrayList() { // return new ArrayList<>(); // } // // public static <K, V> Map<K, V> newHashMap() { // return new HashMap<>(); // } // }
import se.fearless.fettle.Action; import se.fearless.fettle.StateMachine; import se.fearless.fettle.Transition; import se.fearless.fettle.TransitionModel; import se.fearless.fettle.util.GuavaReplacement; import java.util.Collection; import java.util.Collections; import java.util.EnumMap; import java.util.Map;
package se.fearless.fettle.impl; public abstract class AbstractTransitionModel<S, E, C> implements TransitionModel<S, E, C> { protected final Map<S, Map<E, Collection<Transition<S, E, C>>>> transitionMap; protected final Map<E, Collection<Transition<S, E, C>>> fromAllTransitions; protected final Map<S, Collection<Action<S, E, C>>> exitActions; protected final Map<S, Collection<Action<S, E, C>>> enterActions; protected final Class<S> stateClass; protected final Class<E> eventClass; protected final C defaultContext; protected AbstractTransitionModel(Class<S> stateClass, Class<E> eventClass, C defaultContext) { this.stateClass = stateClass; this.eventClass = eventClass; this.defaultContext = defaultContext; transitionMap = createMap(stateClass); exitActions = createMap(stateClass); enterActions = createMap(stateClass); fromAllTransitions = createMap(eventClass); } protected static <S, T> Map<S, T> createMap(Class<S> state) { if (state.isEnum()) { return new EnumMap(state); } else {
// Path: src/main/java/se/fearless/fettle/Action.java // public interface Action<S, E, C> { // /** // * Called when a transition occurs // * @param from the state the machine was in before the transition // * @param to the state the machine is in after the transition // * @param causedBy the event that triggered the transition // * @param context the context in which the event was fired supplied to the transition // * @param stateMachine the machine for which the transition occurred // */ // void onTransition(S from, S to, E causedBy, C context, StateMachine<S, E, C> stateMachine); // } // // Path: src/main/java/se/fearless/fettle/StateMachine.java // public interface StateMachine<S, E, C> { // /** // * Gets the current state of the machine // * // * @return the state the machine is currently in // */ // S getCurrentState(); // // /** // * Fires an event at the state machine, possibly triggering a state change // * // * @param event the event that is fired // * @return true if the event resulted in a state change, false otherwise // */ // boolean fireEvent(E event); // // /** // * Fires an event at the state machine, possibly triggering a state change // * // * @param event the event that is fired // * @param context the context to be sent to any actions that are run on a state change. Used to supply parameters to // * actions and conditions // * @return true if the event resulted in a state change, false otherwise // */ // boolean fireEvent(E event, C context); // // /** // * Sets the state of the state machine to the rawState even if there are no transitions leading to it // * No transition, entry or exit actions are run // * // * @param rawState the state the machine will be in after this method is called // */ // void rawSetState(S rawState); // // /** // * Forces the state machine to enter the forcedState even if there are no transitions leading to it // * No transition actions are run but exit actions on the current state and entry actions on the new state are run // * // * @param forcedState the state the machine will be in after this method is called // * @return true if the state machine changed state // */ // boolean forceSetState(S forcedState); // // /** // * Returns all possible transitions from a given state grouped by the event that triggers the transition. // * @param fromState the state to retrieve the outgoing transitions from. // * @return a map from all registered events in the fromState to the transitions they would trigger if fired. // */ // Map<E, Collection<? extends Transition<S, E, C>>> getPossibleTransitions(S fromState); // } // // Path: src/main/java/se/fearless/fettle/Transition.java // public interface Transition<S, E, C> { // S getTo(); // // boolean isSatisfied(C context); // // void onTransition(S from, S to, E event, C context, StateMachine<S, E, C> statemachine); // // boolean shouldExecuteEntryAndExitActions(); // } // // Path: src/main/java/se/fearless/fettle/TransitionModel.java // public interface TransitionModel<S, E, C> { // // /** // * Fires the event at the state machine. This can result in a state change and trigger actions to be run. // * @param machine the machine to fire the event at // * @param event the event to fire // * @param context the context to use for transition conditions and actions. The context can be used to // * supply arguments to actions. // * @return true if a state change was triggered, false otherwise. // * Note that this will return true if a transition to the same state occurs // */ // boolean fireEvent(StateMachine<S, E, C> machine, E event, C context); // // /** // * Forces the state machine to enter the forcedState even if there are no transitions to that state. // * No transition actions are run but exit actions on the current state and entry actions on the new state are run // * @param stateMachine the state machine to force the state for // * @param forcedState the state the machine will be in after this method // * @return true if the state was changed // */ // boolean forceSetState(StateMachine<S, E, C> stateMachine, S forcedState); // // C getDefaultContext(); // // Map<E, Collection<? extends Transition<S, E, C>>> getPossibleTransitions(S fromState); // } // // Path: src/main/java/se/fearless/fettle/util/GuavaReplacement.java // public class GuavaReplacement { // private GuavaReplacement() { // } // // public static <T> List<T> newArrayList() { // return new ArrayList<>(); // } // // public static <K, V> Map<K, V> newHashMap() { // return new HashMap<>(); // } // } // Path: src/main/java/se/fearless/fettle/impl/AbstractTransitionModel.java import se.fearless.fettle.Action; import se.fearless.fettle.StateMachine; import se.fearless.fettle.Transition; import se.fearless.fettle.TransitionModel; import se.fearless.fettle.util.GuavaReplacement; import java.util.Collection; import java.util.Collections; import java.util.EnumMap; import java.util.Map; package se.fearless.fettle.impl; public abstract class AbstractTransitionModel<S, E, C> implements TransitionModel<S, E, C> { protected final Map<S, Map<E, Collection<Transition<S, E, C>>>> transitionMap; protected final Map<E, Collection<Transition<S, E, C>>> fromAllTransitions; protected final Map<S, Collection<Action<S, E, C>>> exitActions; protected final Map<S, Collection<Action<S, E, C>>> enterActions; protected final Class<S> stateClass; protected final Class<E> eventClass; protected final C defaultContext; protected AbstractTransitionModel(Class<S> stateClass, Class<E> eventClass, C defaultContext) { this.stateClass = stateClass; this.eventClass = eventClass; this.defaultContext = defaultContext; transitionMap = createMap(stateClass); exitActions = createMap(stateClass); enterActions = createMap(stateClass); fromAllTransitions = createMap(eventClass); } protected static <S, T> Map<S, T> createMap(Class<S> state) { if (state.isEnum()) { return new EnumMap(state); } else {
return GuavaReplacement.newHashMap();
thehiflyer/Fettle
src/main/java/se/fearless/fettle/StateMachineTemplate.java
// Path: src/main/resources/super/java/util/concurrent/locks/Lock.java // public interface Lock { // void lock(); // void unlock(); // }
import java.util.concurrent.locks.Lock;
package se.fearless.fettle; public interface StateMachineTemplate<S, E, C> { /** * Creates a new state machine using the transition model as a template * @param init the state the machine will be in when created * @return a new state machine with the transitions and actions defined in this model */ StateMachine<S, E, C> newStateMachine(S init);
// Path: src/main/resources/super/java/util/concurrent/locks/Lock.java // public interface Lock { // void lock(); // void unlock(); // } // Path: src/main/java/se/fearless/fettle/StateMachineTemplate.java import java.util.concurrent.locks.Lock; package se.fearless.fettle; public interface StateMachineTemplate<S, E, C> { /** * Creates a new state machine using the transition model as a template * @param init the state the machine will be in when created * @return a new state machine with the transitions and actions defined in this model */ StateMachine<S, E, C> newStateMachine(S init);
StateMachine<S, E, C> newStateMachine(S init, Lock lock);
thehiflyer/Fettle
src/test/java/se/fearless/fettle/builder/ActionsTest.java
// Path: src/main/java/se/fearless/fettle/Action.java // public interface Action<S, E, C> { // /** // * Called when a transition occurs // * @param from the state the machine was in before the transition // * @param to the state the machine is in after the transition // * @param causedBy the event that triggered the transition // * @param context the context in which the event was fired supplied to the transition // * @param stateMachine the machine for which the transition occurred // */ // void onTransition(S from, S to, E causedBy, C context, StateMachine<S, E, C> stateMachine); // } // // Path: src/main/java/se/fearless/fettle/builder/Actions.java // static <S, E, C> List<Action<S, E, C>> actions(Action<S, E, C> action) { // return Collections.singletonList(action); // }
import com.googlecode.gentyref.TypeToken; import org.junit.Before; import org.junit.Test; import se.fearless.fettle.Action; import static org.hamcrest.CoreMatchers.hasItem; import static org.hamcrest.core.IsCollectionContaining.hasItems; import static org.junit.Assert.assertThat; import static se.fearless.fettle.builder.Actions.actions; import static se.mockachino.Mockachino.mock;
package se.fearless.fettle.builder; public class ActionsTest { private static final TypeToken<Action<String, String, Void>> ACTION_TYPE_TOKEN = new TypeToken<Action<String, String, Void>>() { }; private Action<String, String, Void> action1; private Action<String, String, Void> action2; private Action<String, String, Void> action3; private Action<String, String, Void> action4; private Action<String, String, Void> action5; @Before public void setUp() throws Exception { action1 = mock(ACTION_TYPE_TOKEN); action2 = mock(ACTION_TYPE_TOKEN); action3 = mock(ACTION_TYPE_TOKEN); action4 = mock(ACTION_TYPE_TOKEN); action5 = mock(ACTION_TYPE_TOKEN); } @Test public void singleActionIsIncludedInList() throws Exception {
// Path: src/main/java/se/fearless/fettle/Action.java // public interface Action<S, E, C> { // /** // * Called when a transition occurs // * @param from the state the machine was in before the transition // * @param to the state the machine is in after the transition // * @param causedBy the event that triggered the transition // * @param context the context in which the event was fired supplied to the transition // * @param stateMachine the machine for which the transition occurred // */ // void onTransition(S from, S to, E causedBy, C context, StateMachine<S, E, C> stateMachine); // } // // Path: src/main/java/se/fearless/fettle/builder/Actions.java // static <S, E, C> List<Action<S, E, C>> actions(Action<S, E, C> action) { // return Collections.singletonList(action); // } // Path: src/test/java/se/fearless/fettle/builder/ActionsTest.java import com.googlecode.gentyref.TypeToken; import org.junit.Before; import org.junit.Test; import se.fearless.fettle.Action; import static org.hamcrest.CoreMatchers.hasItem; import static org.hamcrest.core.IsCollectionContaining.hasItems; import static org.junit.Assert.assertThat; import static se.fearless.fettle.builder.Actions.actions; import static se.mockachino.Mockachino.mock; package se.fearless.fettle.builder; public class ActionsTest { private static final TypeToken<Action<String, String, Void>> ACTION_TYPE_TOKEN = new TypeToken<Action<String, String, Void>>() { }; private Action<String, String, Void> action1; private Action<String, String, Void> action2; private Action<String, String, Void> action3; private Action<String, String, Void> action4; private Action<String, String, Void> action5; @Before public void setUp() throws Exception { action1 = mock(ACTION_TYPE_TOKEN); action2 = mock(ACTION_TYPE_TOKEN); action3 = mock(ACTION_TYPE_TOKEN); action4 = mock(ACTION_TYPE_TOKEN); action5 = mock(ACTION_TYPE_TOKEN); } @Test public void singleActionIsIncludedInList() throws Exception {
assertThat(actions(action1), hasItem(action1));
thehiflyer/Fettle
src/main/java/se/fearless/fettle/builder/Actions.java
// Path: src/main/java/se/fearless/fettle/Action.java // public interface Action<S, E, C> { // /** // * Called when a transition occurs // * @param from the state the machine was in before the transition // * @param to the state the machine is in after the transition // * @param causedBy the event that triggered the transition // * @param context the context in which the event was fired supplied to the transition // * @param stateMachine the machine for which the transition occurred // */ // void onTransition(S from, S to, E causedBy, C context, StateMachine<S, E, C> stateMachine); // }
import se.fearless.fettle.Action; import java.util.Arrays; import java.util.Collections; import java.util.List;
package se.fearless.fettle.builder; public class Actions { private Actions() { }
// Path: src/main/java/se/fearless/fettle/Action.java // public interface Action<S, E, C> { // /** // * Called when a transition occurs // * @param from the state the machine was in before the transition // * @param to the state the machine is in after the transition // * @param causedBy the event that triggered the transition // * @param context the context in which the event was fired supplied to the transition // * @param stateMachine the machine for which the transition occurred // */ // void onTransition(S from, S to, E causedBy, C context, StateMachine<S, E, C> stateMachine); // } // Path: src/main/java/se/fearless/fettle/builder/Actions.java import se.fearless.fettle.Action; import java.util.Arrays; import java.util.Collections; import java.util.List; package se.fearless.fettle.builder; public class Actions { private Actions() { }
static <S, E, C> List<Action<S, E, C>> actions(Action<S, E, C> action) {