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
dmfs/lib-recur
src/test/java/org/dmfs/rfc5545/recur/RecurrenceRuleTest.java
// Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static <T> Matcher<T> are(Matcher<T> matcher) // { // Description description = new StringDescription(); // matcher.describeTo(description); // return describedAs(String.format("are %s", description.toString()), is(matcher)); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static Function<DateTime, Matcher<RecurrenceRule>> instances(Matcher<DateTime> dtMatchers) // { // return dateTime -> InstancesMatcher.instances(dateTime, dtMatchers); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static Function<DateTime, Matcher<RecurrenceRule>> results(int n) // { // return dateTime -> ResultsMatcher.results(dateTime, n); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static Function<DateTime, Matcher<RecurrenceRule>> startingWith(String... dates) // { // return startingWith(new Seq<>(dates)); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static Matcher<RecurrenceRule> validRule(DateTime start, Iterable<Function<DateTime, Matcher<RecurrenceRule>>> matcherFunctions) // { // return new AllOf<>(new Joined<>(new Seq<>(increasing(start)), new Mapped<>(f -> f.value(start), matcherFunctions))); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static Function<DateTime, Matcher<RecurrenceRule>> walking() // { // return WalkingStartMatcher::walking; // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/BeforeMatcher.java // public static Matcher<DateTime> before(String dateTime) // { // return before(DateTime.parse(dateTime)); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/DayOfMonthMatcher.java // public static Matcher<DateTime> onDayOfMonth(Matcher<Integer> dayMatcher) // { // return new DayOfMonthMatcher(dayMatcher); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/MonthMatcher.java // public static Matcher<DateTime> inMonth(Matcher<Integer> monthMatcher) // { // return new MonthMatcher(monthMatcher); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/WeekDayMatcher.java // public static Matcher<DateTime> onWeekDay(Matcher<Weekday> weekdayMatcher) // { // return new WeekDayMatcher(weekdayMatcher); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/YearMatcher.java // public static Matcher<DateTime> inYear(Matcher<Integer> yearMatcher) // { // return new YearMatcher(yearMatcher); // }
import org.dmfs.rfc5545.DateTime; import org.dmfs.rfc5545.Weekday; import org.junit.Test; import static org.dmfs.jems.hamcrest.matchers.SingleMatcher.hasValue; import static org.dmfs.rfc5545.Weekday.MO; import static org.dmfs.rfc5545.Weekday.TH; import static org.dmfs.rfc5545.Weekday.TU; import static org.dmfs.rfc5545.Weekday.WE; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.are; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.instances; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.results; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.startingWith; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.validRule; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.walking; import static org.dmfs.rfc5545.hamcrest.datetime.BeforeMatcher.before; import static org.dmfs.rfc5545.hamcrest.datetime.DayOfMonthMatcher.onDayOfMonth; import static org.dmfs.rfc5545.hamcrest.datetime.MonthMatcher.inMonth; import static org.dmfs.rfc5545.hamcrest.datetime.WeekDayMatcher.onWeekDay; import static org.dmfs.rfc5545.hamcrest.datetime.YearMatcher.inYear; import static org.hamcrest.Matchers.hasToString; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat;
/* * Copyright 2018 Marten Gajda <marten@dmfs.org> * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dmfs.rfc5545.recur; /** * @author Marten Gajda */ public final class RecurrenceRuleTest { @Test public void test() throws InvalidRecurrenceRuleException { assertThat(new RecurrenceRule("FREQ=WEEKLY;COUNT=1000"), is(validRule(DateTime.parse("20180101"), walking(), instances(are(onWeekDay(MO))),
// Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static <T> Matcher<T> are(Matcher<T> matcher) // { // Description description = new StringDescription(); // matcher.describeTo(description); // return describedAs(String.format("are %s", description.toString()), is(matcher)); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static Function<DateTime, Matcher<RecurrenceRule>> instances(Matcher<DateTime> dtMatchers) // { // return dateTime -> InstancesMatcher.instances(dateTime, dtMatchers); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static Function<DateTime, Matcher<RecurrenceRule>> results(int n) // { // return dateTime -> ResultsMatcher.results(dateTime, n); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static Function<DateTime, Matcher<RecurrenceRule>> startingWith(String... dates) // { // return startingWith(new Seq<>(dates)); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static Matcher<RecurrenceRule> validRule(DateTime start, Iterable<Function<DateTime, Matcher<RecurrenceRule>>> matcherFunctions) // { // return new AllOf<>(new Joined<>(new Seq<>(increasing(start)), new Mapped<>(f -> f.value(start), matcherFunctions))); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static Function<DateTime, Matcher<RecurrenceRule>> walking() // { // return WalkingStartMatcher::walking; // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/BeforeMatcher.java // public static Matcher<DateTime> before(String dateTime) // { // return before(DateTime.parse(dateTime)); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/DayOfMonthMatcher.java // public static Matcher<DateTime> onDayOfMonth(Matcher<Integer> dayMatcher) // { // return new DayOfMonthMatcher(dayMatcher); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/MonthMatcher.java // public static Matcher<DateTime> inMonth(Matcher<Integer> monthMatcher) // { // return new MonthMatcher(monthMatcher); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/WeekDayMatcher.java // public static Matcher<DateTime> onWeekDay(Matcher<Weekday> weekdayMatcher) // { // return new WeekDayMatcher(weekdayMatcher); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/YearMatcher.java // public static Matcher<DateTime> inYear(Matcher<Integer> yearMatcher) // { // return new YearMatcher(yearMatcher); // } // Path: src/test/java/org/dmfs/rfc5545/recur/RecurrenceRuleTest.java import org.dmfs.rfc5545.DateTime; import org.dmfs.rfc5545.Weekday; import org.junit.Test; import static org.dmfs.jems.hamcrest.matchers.SingleMatcher.hasValue; import static org.dmfs.rfc5545.Weekday.MO; import static org.dmfs.rfc5545.Weekday.TH; import static org.dmfs.rfc5545.Weekday.TU; import static org.dmfs.rfc5545.Weekday.WE; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.are; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.instances; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.results; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.startingWith; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.validRule; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.walking; import static org.dmfs.rfc5545.hamcrest.datetime.BeforeMatcher.before; import static org.dmfs.rfc5545.hamcrest.datetime.DayOfMonthMatcher.onDayOfMonth; import static org.dmfs.rfc5545.hamcrest.datetime.MonthMatcher.inMonth; import static org.dmfs.rfc5545.hamcrest.datetime.WeekDayMatcher.onWeekDay; import static org.dmfs.rfc5545.hamcrest.datetime.YearMatcher.inYear; import static org.hamcrest.Matchers.hasToString; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; /* * Copyright 2018 Marten Gajda <marten@dmfs.org> * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dmfs.rfc5545.recur; /** * @author Marten Gajda */ public final class RecurrenceRuleTest { @Test public void test() throws InvalidRecurrenceRuleException { assertThat(new RecurrenceRule("FREQ=WEEKLY;COUNT=1000"), is(validRule(DateTime.parse("20180101"), walking(), instances(are(onWeekDay(MO))),
results(1000))));
dmfs/lib-recur
src/test/java/org/dmfs/rfc5545/recur/RecurrenceRuleTest.java
// Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static <T> Matcher<T> are(Matcher<T> matcher) // { // Description description = new StringDescription(); // matcher.describeTo(description); // return describedAs(String.format("are %s", description.toString()), is(matcher)); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static Function<DateTime, Matcher<RecurrenceRule>> instances(Matcher<DateTime> dtMatchers) // { // return dateTime -> InstancesMatcher.instances(dateTime, dtMatchers); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static Function<DateTime, Matcher<RecurrenceRule>> results(int n) // { // return dateTime -> ResultsMatcher.results(dateTime, n); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static Function<DateTime, Matcher<RecurrenceRule>> startingWith(String... dates) // { // return startingWith(new Seq<>(dates)); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static Matcher<RecurrenceRule> validRule(DateTime start, Iterable<Function<DateTime, Matcher<RecurrenceRule>>> matcherFunctions) // { // return new AllOf<>(new Joined<>(new Seq<>(increasing(start)), new Mapped<>(f -> f.value(start), matcherFunctions))); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static Function<DateTime, Matcher<RecurrenceRule>> walking() // { // return WalkingStartMatcher::walking; // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/BeforeMatcher.java // public static Matcher<DateTime> before(String dateTime) // { // return before(DateTime.parse(dateTime)); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/DayOfMonthMatcher.java // public static Matcher<DateTime> onDayOfMonth(Matcher<Integer> dayMatcher) // { // return new DayOfMonthMatcher(dayMatcher); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/MonthMatcher.java // public static Matcher<DateTime> inMonth(Matcher<Integer> monthMatcher) // { // return new MonthMatcher(monthMatcher); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/WeekDayMatcher.java // public static Matcher<DateTime> onWeekDay(Matcher<Weekday> weekdayMatcher) // { // return new WeekDayMatcher(weekdayMatcher); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/YearMatcher.java // public static Matcher<DateTime> inYear(Matcher<Integer> yearMatcher) // { // return new YearMatcher(yearMatcher); // }
import org.dmfs.rfc5545.DateTime; import org.dmfs.rfc5545.Weekday; import org.junit.Test; import static org.dmfs.jems.hamcrest.matchers.SingleMatcher.hasValue; import static org.dmfs.rfc5545.Weekday.MO; import static org.dmfs.rfc5545.Weekday.TH; import static org.dmfs.rfc5545.Weekday.TU; import static org.dmfs.rfc5545.Weekday.WE; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.are; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.instances; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.results; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.startingWith; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.validRule; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.walking; import static org.dmfs.rfc5545.hamcrest.datetime.BeforeMatcher.before; import static org.dmfs.rfc5545.hamcrest.datetime.DayOfMonthMatcher.onDayOfMonth; import static org.dmfs.rfc5545.hamcrest.datetime.MonthMatcher.inMonth; import static org.dmfs.rfc5545.hamcrest.datetime.WeekDayMatcher.onWeekDay; import static org.dmfs.rfc5545.hamcrest.datetime.YearMatcher.inYear; import static org.hamcrest.Matchers.hasToString; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat;
/* * Copyright 2018 Marten Gajda <marten@dmfs.org> * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dmfs.rfc5545.recur; /** * @author Marten Gajda */ public final class RecurrenceRuleTest { @Test public void test() throws InvalidRecurrenceRuleException { assertThat(new RecurrenceRule("FREQ=WEEKLY;COUNT=1000"), is(validRule(DateTime.parse("20180101"), walking(), instances(are(onWeekDay(MO))), results(1000)))); assertThat(new RecurrenceRule("FREQ=MONTHLY;INTERVAL=1;BYDAY=+3TH;UNTIL=20140101T045959Z;WKST=SU"), is(validRule(DateTime.parse("20130101T050000Z"), walking(),
// Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static <T> Matcher<T> are(Matcher<T> matcher) // { // Description description = new StringDescription(); // matcher.describeTo(description); // return describedAs(String.format("are %s", description.toString()), is(matcher)); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static Function<DateTime, Matcher<RecurrenceRule>> instances(Matcher<DateTime> dtMatchers) // { // return dateTime -> InstancesMatcher.instances(dateTime, dtMatchers); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static Function<DateTime, Matcher<RecurrenceRule>> results(int n) // { // return dateTime -> ResultsMatcher.results(dateTime, n); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static Function<DateTime, Matcher<RecurrenceRule>> startingWith(String... dates) // { // return startingWith(new Seq<>(dates)); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static Matcher<RecurrenceRule> validRule(DateTime start, Iterable<Function<DateTime, Matcher<RecurrenceRule>>> matcherFunctions) // { // return new AllOf<>(new Joined<>(new Seq<>(increasing(start)), new Mapped<>(f -> f.value(start), matcherFunctions))); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static Function<DateTime, Matcher<RecurrenceRule>> walking() // { // return WalkingStartMatcher::walking; // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/BeforeMatcher.java // public static Matcher<DateTime> before(String dateTime) // { // return before(DateTime.parse(dateTime)); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/DayOfMonthMatcher.java // public static Matcher<DateTime> onDayOfMonth(Matcher<Integer> dayMatcher) // { // return new DayOfMonthMatcher(dayMatcher); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/MonthMatcher.java // public static Matcher<DateTime> inMonth(Matcher<Integer> monthMatcher) // { // return new MonthMatcher(monthMatcher); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/WeekDayMatcher.java // public static Matcher<DateTime> onWeekDay(Matcher<Weekday> weekdayMatcher) // { // return new WeekDayMatcher(weekdayMatcher); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/YearMatcher.java // public static Matcher<DateTime> inYear(Matcher<Integer> yearMatcher) // { // return new YearMatcher(yearMatcher); // } // Path: src/test/java/org/dmfs/rfc5545/recur/RecurrenceRuleTest.java import org.dmfs.rfc5545.DateTime; import org.dmfs.rfc5545.Weekday; import org.junit.Test; import static org.dmfs.jems.hamcrest.matchers.SingleMatcher.hasValue; import static org.dmfs.rfc5545.Weekday.MO; import static org.dmfs.rfc5545.Weekday.TH; import static org.dmfs.rfc5545.Weekday.TU; import static org.dmfs.rfc5545.Weekday.WE; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.are; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.instances; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.results; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.startingWith; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.validRule; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.walking; import static org.dmfs.rfc5545.hamcrest.datetime.BeforeMatcher.before; import static org.dmfs.rfc5545.hamcrest.datetime.DayOfMonthMatcher.onDayOfMonth; import static org.dmfs.rfc5545.hamcrest.datetime.MonthMatcher.inMonth; import static org.dmfs.rfc5545.hamcrest.datetime.WeekDayMatcher.onWeekDay; import static org.dmfs.rfc5545.hamcrest.datetime.YearMatcher.inYear; import static org.hamcrest.Matchers.hasToString; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; /* * Copyright 2018 Marten Gajda <marten@dmfs.org> * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dmfs.rfc5545.recur; /** * @author Marten Gajda */ public final class RecurrenceRuleTest { @Test public void test() throws InvalidRecurrenceRuleException { assertThat(new RecurrenceRule("FREQ=WEEKLY;COUNT=1000"), is(validRule(DateTime.parse("20180101"), walking(), instances(are(onWeekDay(MO))), results(1000)))); assertThat(new RecurrenceRule("FREQ=MONTHLY;INTERVAL=1;BYDAY=+3TH;UNTIL=20140101T045959Z;WKST=SU"), is(validRule(DateTime.parse("20130101T050000Z"), walking(),
instances(are(onWeekDay(TH), onDayOfMonth(15, 16, 17, 18, 19, 20, 21), inYear(2013), before("20140101T050000Z"))),
dmfs/lib-recur
src/test/java/org/dmfs/rfc5545/recur/RecurrenceRuleTest.java
// Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static <T> Matcher<T> are(Matcher<T> matcher) // { // Description description = new StringDescription(); // matcher.describeTo(description); // return describedAs(String.format("are %s", description.toString()), is(matcher)); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static Function<DateTime, Matcher<RecurrenceRule>> instances(Matcher<DateTime> dtMatchers) // { // return dateTime -> InstancesMatcher.instances(dateTime, dtMatchers); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static Function<DateTime, Matcher<RecurrenceRule>> results(int n) // { // return dateTime -> ResultsMatcher.results(dateTime, n); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static Function<DateTime, Matcher<RecurrenceRule>> startingWith(String... dates) // { // return startingWith(new Seq<>(dates)); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static Matcher<RecurrenceRule> validRule(DateTime start, Iterable<Function<DateTime, Matcher<RecurrenceRule>>> matcherFunctions) // { // return new AllOf<>(new Joined<>(new Seq<>(increasing(start)), new Mapped<>(f -> f.value(start), matcherFunctions))); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static Function<DateTime, Matcher<RecurrenceRule>> walking() // { // return WalkingStartMatcher::walking; // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/BeforeMatcher.java // public static Matcher<DateTime> before(String dateTime) // { // return before(DateTime.parse(dateTime)); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/DayOfMonthMatcher.java // public static Matcher<DateTime> onDayOfMonth(Matcher<Integer> dayMatcher) // { // return new DayOfMonthMatcher(dayMatcher); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/MonthMatcher.java // public static Matcher<DateTime> inMonth(Matcher<Integer> monthMatcher) // { // return new MonthMatcher(monthMatcher); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/WeekDayMatcher.java // public static Matcher<DateTime> onWeekDay(Matcher<Weekday> weekdayMatcher) // { // return new WeekDayMatcher(weekdayMatcher); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/YearMatcher.java // public static Matcher<DateTime> inYear(Matcher<Integer> yearMatcher) // { // return new YearMatcher(yearMatcher); // }
import org.dmfs.rfc5545.DateTime; import org.dmfs.rfc5545.Weekday; import org.junit.Test; import static org.dmfs.jems.hamcrest.matchers.SingleMatcher.hasValue; import static org.dmfs.rfc5545.Weekday.MO; import static org.dmfs.rfc5545.Weekday.TH; import static org.dmfs.rfc5545.Weekday.TU; import static org.dmfs.rfc5545.Weekday.WE; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.are; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.instances; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.results; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.startingWith; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.validRule; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.walking; import static org.dmfs.rfc5545.hamcrest.datetime.BeforeMatcher.before; import static org.dmfs.rfc5545.hamcrest.datetime.DayOfMonthMatcher.onDayOfMonth; import static org.dmfs.rfc5545.hamcrest.datetime.MonthMatcher.inMonth; import static org.dmfs.rfc5545.hamcrest.datetime.WeekDayMatcher.onWeekDay; import static org.dmfs.rfc5545.hamcrest.datetime.YearMatcher.inYear; import static org.hamcrest.Matchers.hasToString; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat;
/* * Copyright 2018 Marten Gajda <marten@dmfs.org> * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dmfs.rfc5545.recur; /** * @author Marten Gajda */ public final class RecurrenceRuleTest { @Test public void test() throws InvalidRecurrenceRuleException { assertThat(new RecurrenceRule("FREQ=WEEKLY;COUNT=1000"), is(validRule(DateTime.parse("20180101"), walking(), instances(are(onWeekDay(MO))), results(1000)))); assertThat(new RecurrenceRule("FREQ=MONTHLY;INTERVAL=1;BYDAY=+3TH;UNTIL=20140101T045959Z;WKST=SU"), is(validRule(DateTime.parse("20130101T050000Z"), walking(),
// Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static <T> Matcher<T> are(Matcher<T> matcher) // { // Description description = new StringDescription(); // matcher.describeTo(description); // return describedAs(String.format("are %s", description.toString()), is(matcher)); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static Function<DateTime, Matcher<RecurrenceRule>> instances(Matcher<DateTime> dtMatchers) // { // return dateTime -> InstancesMatcher.instances(dateTime, dtMatchers); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static Function<DateTime, Matcher<RecurrenceRule>> results(int n) // { // return dateTime -> ResultsMatcher.results(dateTime, n); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static Function<DateTime, Matcher<RecurrenceRule>> startingWith(String... dates) // { // return startingWith(new Seq<>(dates)); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static Matcher<RecurrenceRule> validRule(DateTime start, Iterable<Function<DateTime, Matcher<RecurrenceRule>>> matcherFunctions) // { // return new AllOf<>(new Joined<>(new Seq<>(increasing(start)), new Mapped<>(f -> f.value(start), matcherFunctions))); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static Function<DateTime, Matcher<RecurrenceRule>> walking() // { // return WalkingStartMatcher::walking; // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/BeforeMatcher.java // public static Matcher<DateTime> before(String dateTime) // { // return before(DateTime.parse(dateTime)); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/DayOfMonthMatcher.java // public static Matcher<DateTime> onDayOfMonth(Matcher<Integer> dayMatcher) // { // return new DayOfMonthMatcher(dayMatcher); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/MonthMatcher.java // public static Matcher<DateTime> inMonth(Matcher<Integer> monthMatcher) // { // return new MonthMatcher(monthMatcher); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/WeekDayMatcher.java // public static Matcher<DateTime> onWeekDay(Matcher<Weekday> weekdayMatcher) // { // return new WeekDayMatcher(weekdayMatcher); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/YearMatcher.java // public static Matcher<DateTime> inYear(Matcher<Integer> yearMatcher) // { // return new YearMatcher(yearMatcher); // } // Path: src/test/java/org/dmfs/rfc5545/recur/RecurrenceRuleTest.java import org.dmfs.rfc5545.DateTime; import org.dmfs.rfc5545.Weekday; import org.junit.Test; import static org.dmfs.jems.hamcrest.matchers.SingleMatcher.hasValue; import static org.dmfs.rfc5545.Weekday.MO; import static org.dmfs.rfc5545.Weekday.TH; import static org.dmfs.rfc5545.Weekday.TU; import static org.dmfs.rfc5545.Weekday.WE; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.are; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.instances; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.results; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.startingWith; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.validRule; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.walking; import static org.dmfs.rfc5545.hamcrest.datetime.BeforeMatcher.before; import static org.dmfs.rfc5545.hamcrest.datetime.DayOfMonthMatcher.onDayOfMonth; import static org.dmfs.rfc5545.hamcrest.datetime.MonthMatcher.inMonth; import static org.dmfs.rfc5545.hamcrest.datetime.WeekDayMatcher.onWeekDay; import static org.dmfs.rfc5545.hamcrest.datetime.YearMatcher.inYear; import static org.hamcrest.Matchers.hasToString; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; /* * Copyright 2018 Marten Gajda <marten@dmfs.org> * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dmfs.rfc5545.recur; /** * @author Marten Gajda */ public final class RecurrenceRuleTest { @Test public void test() throws InvalidRecurrenceRuleException { assertThat(new RecurrenceRule("FREQ=WEEKLY;COUNT=1000"), is(validRule(DateTime.parse("20180101"), walking(), instances(are(onWeekDay(MO))), results(1000)))); assertThat(new RecurrenceRule("FREQ=MONTHLY;INTERVAL=1;BYDAY=+3TH;UNTIL=20140101T045959Z;WKST=SU"), is(validRule(DateTime.parse("20130101T050000Z"), walking(),
instances(are(onWeekDay(TH), onDayOfMonth(15, 16, 17, 18, 19, 20, 21), inYear(2013), before("20140101T050000Z"))),
dmfs/lib-recur
src/test/java/org/dmfs/rfc5545/recur/RecurrenceRuleTest.java
// Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static <T> Matcher<T> are(Matcher<T> matcher) // { // Description description = new StringDescription(); // matcher.describeTo(description); // return describedAs(String.format("are %s", description.toString()), is(matcher)); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static Function<DateTime, Matcher<RecurrenceRule>> instances(Matcher<DateTime> dtMatchers) // { // return dateTime -> InstancesMatcher.instances(dateTime, dtMatchers); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static Function<DateTime, Matcher<RecurrenceRule>> results(int n) // { // return dateTime -> ResultsMatcher.results(dateTime, n); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static Function<DateTime, Matcher<RecurrenceRule>> startingWith(String... dates) // { // return startingWith(new Seq<>(dates)); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static Matcher<RecurrenceRule> validRule(DateTime start, Iterable<Function<DateTime, Matcher<RecurrenceRule>>> matcherFunctions) // { // return new AllOf<>(new Joined<>(new Seq<>(increasing(start)), new Mapped<>(f -> f.value(start), matcherFunctions))); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static Function<DateTime, Matcher<RecurrenceRule>> walking() // { // return WalkingStartMatcher::walking; // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/BeforeMatcher.java // public static Matcher<DateTime> before(String dateTime) // { // return before(DateTime.parse(dateTime)); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/DayOfMonthMatcher.java // public static Matcher<DateTime> onDayOfMonth(Matcher<Integer> dayMatcher) // { // return new DayOfMonthMatcher(dayMatcher); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/MonthMatcher.java // public static Matcher<DateTime> inMonth(Matcher<Integer> monthMatcher) // { // return new MonthMatcher(monthMatcher); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/WeekDayMatcher.java // public static Matcher<DateTime> onWeekDay(Matcher<Weekday> weekdayMatcher) // { // return new WeekDayMatcher(weekdayMatcher); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/YearMatcher.java // public static Matcher<DateTime> inYear(Matcher<Integer> yearMatcher) // { // return new YearMatcher(yearMatcher); // }
import org.dmfs.rfc5545.DateTime; import org.dmfs.rfc5545.Weekday; import org.junit.Test; import static org.dmfs.jems.hamcrest.matchers.SingleMatcher.hasValue; import static org.dmfs.rfc5545.Weekday.MO; import static org.dmfs.rfc5545.Weekday.TH; import static org.dmfs.rfc5545.Weekday.TU; import static org.dmfs.rfc5545.Weekday.WE; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.are; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.instances; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.results; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.startingWith; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.validRule; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.walking; import static org.dmfs.rfc5545.hamcrest.datetime.BeforeMatcher.before; import static org.dmfs.rfc5545.hamcrest.datetime.DayOfMonthMatcher.onDayOfMonth; import static org.dmfs.rfc5545.hamcrest.datetime.MonthMatcher.inMonth; import static org.dmfs.rfc5545.hamcrest.datetime.WeekDayMatcher.onWeekDay; import static org.dmfs.rfc5545.hamcrest.datetime.YearMatcher.inYear; import static org.hamcrest.Matchers.hasToString; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat;
/* * Copyright 2018 Marten Gajda <marten@dmfs.org> * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dmfs.rfc5545.recur; /** * @author Marten Gajda */ public final class RecurrenceRuleTest { @Test public void test() throws InvalidRecurrenceRuleException { assertThat(new RecurrenceRule("FREQ=WEEKLY;COUNT=1000"), is(validRule(DateTime.parse("20180101"), walking(), instances(are(onWeekDay(MO))), results(1000)))); assertThat(new RecurrenceRule("FREQ=MONTHLY;INTERVAL=1;BYDAY=+3TH;UNTIL=20140101T045959Z;WKST=SU"), is(validRule(DateTime.parse("20130101T050000Z"), walking(),
// Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static <T> Matcher<T> are(Matcher<T> matcher) // { // Description description = new StringDescription(); // matcher.describeTo(description); // return describedAs(String.format("are %s", description.toString()), is(matcher)); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static Function<DateTime, Matcher<RecurrenceRule>> instances(Matcher<DateTime> dtMatchers) // { // return dateTime -> InstancesMatcher.instances(dateTime, dtMatchers); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static Function<DateTime, Matcher<RecurrenceRule>> results(int n) // { // return dateTime -> ResultsMatcher.results(dateTime, n); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static Function<DateTime, Matcher<RecurrenceRule>> startingWith(String... dates) // { // return startingWith(new Seq<>(dates)); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static Matcher<RecurrenceRule> validRule(DateTime start, Iterable<Function<DateTime, Matcher<RecurrenceRule>>> matcherFunctions) // { // return new AllOf<>(new Joined<>(new Seq<>(increasing(start)), new Mapped<>(f -> f.value(start), matcherFunctions))); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static Function<DateTime, Matcher<RecurrenceRule>> walking() // { // return WalkingStartMatcher::walking; // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/BeforeMatcher.java // public static Matcher<DateTime> before(String dateTime) // { // return before(DateTime.parse(dateTime)); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/DayOfMonthMatcher.java // public static Matcher<DateTime> onDayOfMonth(Matcher<Integer> dayMatcher) // { // return new DayOfMonthMatcher(dayMatcher); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/MonthMatcher.java // public static Matcher<DateTime> inMonth(Matcher<Integer> monthMatcher) // { // return new MonthMatcher(monthMatcher); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/WeekDayMatcher.java // public static Matcher<DateTime> onWeekDay(Matcher<Weekday> weekdayMatcher) // { // return new WeekDayMatcher(weekdayMatcher); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/YearMatcher.java // public static Matcher<DateTime> inYear(Matcher<Integer> yearMatcher) // { // return new YearMatcher(yearMatcher); // } // Path: src/test/java/org/dmfs/rfc5545/recur/RecurrenceRuleTest.java import org.dmfs.rfc5545.DateTime; import org.dmfs.rfc5545.Weekday; import org.junit.Test; import static org.dmfs.jems.hamcrest.matchers.SingleMatcher.hasValue; import static org.dmfs.rfc5545.Weekday.MO; import static org.dmfs.rfc5545.Weekday.TH; import static org.dmfs.rfc5545.Weekday.TU; import static org.dmfs.rfc5545.Weekday.WE; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.are; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.instances; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.results; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.startingWith; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.validRule; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.walking; import static org.dmfs.rfc5545.hamcrest.datetime.BeforeMatcher.before; import static org.dmfs.rfc5545.hamcrest.datetime.DayOfMonthMatcher.onDayOfMonth; import static org.dmfs.rfc5545.hamcrest.datetime.MonthMatcher.inMonth; import static org.dmfs.rfc5545.hamcrest.datetime.WeekDayMatcher.onWeekDay; import static org.dmfs.rfc5545.hamcrest.datetime.YearMatcher.inYear; import static org.hamcrest.Matchers.hasToString; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; /* * Copyright 2018 Marten Gajda <marten@dmfs.org> * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dmfs.rfc5545.recur; /** * @author Marten Gajda */ public final class RecurrenceRuleTest { @Test public void test() throws InvalidRecurrenceRuleException { assertThat(new RecurrenceRule("FREQ=WEEKLY;COUNT=1000"), is(validRule(DateTime.parse("20180101"), walking(), instances(are(onWeekDay(MO))), results(1000)))); assertThat(new RecurrenceRule("FREQ=MONTHLY;INTERVAL=1;BYDAY=+3TH;UNTIL=20140101T045959Z;WKST=SU"), is(validRule(DateTime.parse("20130101T050000Z"), walking(),
instances(are(onWeekDay(TH), onDayOfMonth(15, 16, 17, 18, 19, 20, 21), inYear(2013), before("20140101T050000Z"))),
dmfs/lib-recur
lib-recur-hamcrest/src/test/java/org/dmfs/rfc5545/hamcrest/datetime/DayOfYearMatcherTest.java
// Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/DayOfYearMatcher.java // public static Matcher<DateTime> onDayOfYear(Matcher<Integer> dayMatcher) // { // return new DayOfYearMatcher(dayMatcher); // }
import org.dmfs.rfc5545.DateTime; import org.hamcrest.Matcher; import org.hamcrest.core.AllOf; import org.junit.Test; import static org.dmfs.jems.hamcrest.matchers.matcher.MatcherMatcher.describesAs; import static org.dmfs.jems.hamcrest.matchers.matcher.MatcherMatcher.matches; import static org.dmfs.jems.hamcrest.matchers.matcher.MatcherMatcher.mismatches; import static org.dmfs.rfc5545.hamcrest.datetime.DayOfYearMatcher.onDayOfYear; import static org.junit.Assert.assertThat;
/* * Copyright 2018 Marten Gajda <marten@dmfs.org> * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dmfs.rfc5545.hamcrest.datetime; /** * Unit test for {@link DayOfYearMatcher}. * * @author Marten Gajda */ public class DayOfYearMatcherTest { @Test public void test() throws Exception {
// Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/DayOfYearMatcher.java // public static Matcher<DateTime> onDayOfYear(Matcher<Integer> dayMatcher) // { // return new DayOfYearMatcher(dayMatcher); // } // Path: lib-recur-hamcrest/src/test/java/org/dmfs/rfc5545/hamcrest/datetime/DayOfYearMatcherTest.java import org.dmfs.rfc5545.DateTime; import org.hamcrest.Matcher; import org.hamcrest.core.AllOf; import org.junit.Test; import static org.dmfs.jems.hamcrest.matchers.matcher.MatcherMatcher.describesAs; import static org.dmfs.jems.hamcrest.matchers.matcher.MatcherMatcher.matches; import static org.dmfs.jems.hamcrest.matchers.matcher.MatcherMatcher.mismatches; import static org.dmfs.rfc5545.hamcrest.datetime.DayOfYearMatcher.onDayOfYear; import static org.junit.Assert.assertThat; /* * Copyright 2018 Marten Gajda <marten@dmfs.org> * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dmfs.rfc5545.hamcrest.datetime; /** * Unit test for {@link DayOfYearMatcher}. * * @author Marten Gajda */ public class DayOfYearMatcherTest { @Test public void test() throws Exception {
assertThat(onDayOfYear(10),
dmfs/lib-recur
src/test/java/org/dmfs/rfc5545/recur/RecurrenceIteratorTest.java
// Path: src/main/java/org/dmfs/rfc5545/recur/RecurrenceRule.java // public enum RfcMode // { // /** // * Parses recurrence rules according to <a href="http://tools.ietf.org/html/rfc2445#section-4.3.10">RFC 2445</a>. Every error will cause an exception to // * be thrown. // */ // RFC2445_STRICT, // // /** // * Parses recurrence rules according to <a href="http://tools.ietf.org/html/rfc2445#section-4.3.10">RFC 2445</a> in a more tolerant way. The parser will // * just skip invalid parts in the rule and won't complain as long as the result is a valid rule. <p> This mode also accepts rules that comply with <a // * href="http://tools.ietf.org/html/rfc5545#section-3.3.10">RFC 5545</a>. </p> <p> <strong>Note:</strong> Using this mode rules are evaluated // * differently than with {@link #RFC5545_LAX}. {@link #RFC5545_LAX} will just drop all invalid parts and evaluate the rule according to RFC 5545. This // * mode will evaluate all rules. <p> Also this mode will output rules that comply with RFC 2445. </p> // */ // RFC2445_LAX, // // /** // * Parses recurrence rules according to <a href="http://tools.ietf.org/html/rfc5545#section-3.3.10">RFC 5545</a>. Every error will cause an exception to // * be thrown. // */ // RFC5545_STRICT, // // /** // * Parses recurrence rules according to <a href="http://tools.ietf.org/html/rfc5545#section-3.3.10">RFC 5545</a> in a more tolerant way. The parser will // * just skip invalid parts in the rule and won't complain as long as the result is a valid rule. <p> This mode also accepts rules that comply with <a // * href="http://tools.ietf.org/html/rfc2445#section-4.3.10">RFC 2445</a> but not with RFC 5545. </p> <p> <strong>Note:</strong> Using this mode rules // * are evaluated differently than with {@link #RFC2445_LAX}. This mode will just drop all invalid parts and evaluate the rule according to RFC 5545. // * {@link #RFC2445_LAX} will evaluate all rules. <p> Also this mode will output rules that comply with RFC 5545. </p> // */ // RFC5545_LAX; // } // // Path: src/main/java/org/dmfs/rfc5545/recur/RecurrenceRule.java // public enum Skip // { // /** // * OMIT is the default value. It means that non-existing dates are just ignored. // */ // OMIT, // // /** // * BACKWARD means that non-existing instanced get rolled back to the previous day (for leap days) or month (for leap months). // */ // BACKWARD, // // /** // * FORWARD means that non-existing instanced get rolled forward to the next day (for leap days) or month (for leap months). // */ // FORWARD; // }
import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import org.dmfs.rfc5545.DateTime; import org.dmfs.rfc5545.recur.RecurrenceRule.RfcMode; import org.dmfs.rfc5545.recur.RecurrenceRule.Skip; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import java.util.Calendar; import java.util.LinkedList; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse;
RecurrenceRule r = new RecurrenceRule(rule.rule, rule.mode); DateTime start = null; if (rule.start != null) { start = rule.start; } else if (!rule.floating) { start = ABSOLUTE_TEST_START_DATE; } else if (!rule.allday) { start = FLOATING_TEST_START_DATE; } else { start = ALLDAY_TEST_START_DATE; } // no instance should be before this day DateTime lastInstance = new DateTime(DateTime.UTC, 1900, 0, 1, 0, 0, 0); int count = 0; RecurrenceRuleIterator it = r.iterator(start); while (it.hasNext()) { DateTime instance = it.nextDateTime(); // check that the previous instance is always before the next instance String errMsg = ""; errMsg = "instance no " + count + " " + lastInstance + " not before " + instance + " in rule "
// Path: src/main/java/org/dmfs/rfc5545/recur/RecurrenceRule.java // public enum RfcMode // { // /** // * Parses recurrence rules according to <a href="http://tools.ietf.org/html/rfc2445#section-4.3.10">RFC 2445</a>. Every error will cause an exception to // * be thrown. // */ // RFC2445_STRICT, // // /** // * Parses recurrence rules according to <a href="http://tools.ietf.org/html/rfc2445#section-4.3.10">RFC 2445</a> in a more tolerant way. The parser will // * just skip invalid parts in the rule and won't complain as long as the result is a valid rule. <p> This mode also accepts rules that comply with <a // * href="http://tools.ietf.org/html/rfc5545#section-3.3.10">RFC 5545</a>. </p> <p> <strong>Note:</strong> Using this mode rules are evaluated // * differently than with {@link #RFC5545_LAX}. {@link #RFC5545_LAX} will just drop all invalid parts and evaluate the rule according to RFC 5545. This // * mode will evaluate all rules. <p> Also this mode will output rules that comply with RFC 2445. </p> // */ // RFC2445_LAX, // // /** // * Parses recurrence rules according to <a href="http://tools.ietf.org/html/rfc5545#section-3.3.10">RFC 5545</a>. Every error will cause an exception to // * be thrown. // */ // RFC5545_STRICT, // // /** // * Parses recurrence rules according to <a href="http://tools.ietf.org/html/rfc5545#section-3.3.10">RFC 5545</a> in a more tolerant way. The parser will // * just skip invalid parts in the rule and won't complain as long as the result is a valid rule. <p> This mode also accepts rules that comply with <a // * href="http://tools.ietf.org/html/rfc2445#section-4.3.10">RFC 2445</a> but not with RFC 5545. </p> <p> <strong>Note:</strong> Using this mode rules // * are evaluated differently than with {@link #RFC2445_LAX}. This mode will just drop all invalid parts and evaluate the rule according to RFC 5545. // * {@link #RFC2445_LAX} will evaluate all rules. <p> Also this mode will output rules that comply with RFC 5545. </p> // */ // RFC5545_LAX; // } // // Path: src/main/java/org/dmfs/rfc5545/recur/RecurrenceRule.java // public enum Skip // { // /** // * OMIT is the default value. It means that non-existing dates are just ignored. // */ // OMIT, // // /** // * BACKWARD means that non-existing instanced get rolled back to the previous day (for leap days) or month (for leap months). // */ // BACKWARD, // // /** // * FORWARD means that non-existing instanced get rolled forward to the next day (for leap days) or month (for leap months). // */ // FORWARD; // } // Path: src/test/java/org/dmfs/rfc5545/recur/RecurrenceIteratorTest.java import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import org.dmfs.rfc5545.DateTime; import org.dmfs.rfc5545.recur.RecurrenceRule.RfcMode; import org.dmfs.rfc5545.recur.RecurrenceRule.Skip; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import java.util.Calendar; import java.util.LinkedList; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; RecurrenceRule r = new RecurrenceRule(rule.rule, rule.mode); DateTime start = null; if (rule.start != null) { start = rule.start; } else if (!rule.floating) { start = ABSOLUTE_TEST_START_DATE; } else if (!rule.allday) { start = FLOATING_TEST_START_DATE; } else { start = ALLDAY_TEST_START_DATE; } // no instance should be before this day DateTime lastInstance = new DateTime(DateTime.UTC, 1900, 0, 1, 0, 0, 0); int count = 0; RecurrenceRuleIterator it = r.iterator(start); while (it.hasNext()) { DateTime instance = it.nextDateTime(); // check that the previous instance is always before the next instance String errMsg = ""; errMsg = "instance no " + count + " " + lastInstance + " not before " + instance + " in rule "
+ new RecurrenceRule(rule.rule, RfcMode.RFC5545_LAX).toString();
dmfs/lib-recur
src/test/java/org/dmfs/rfc5545/recur/RecurrenceIteratorTest.java
// Path: src/main/java/org/dmfs/rfc5545/recur/RecurrenceRule.java // public enum RfcMode // { // /** // * Parses recurrence rules according to <a href="http://tools.ietf.org/html/rfc2445#section-4.3.10">RFC 2445</a>. Every error will cause an exception to // * be thrown. // */ // RFC2445_STRICT, // // /** // * Parses recurrence rules according to <a href="http://tools.ietf.org/html/rfc2445#section-4.3.10">RFC 2445</a> in a more tolerant way. The parser will // * just skip invalid parts in the rule and won't complain as long as the result is a valid rule. <p> This mode also accepts rules that comply with <a // * href="http://tools.ietf.org/html/rfc5545#section-3.3.10">RFC 5545</a>. </p> <p> <strong>Note:</strong> Using this mode rules are evaluated // * differently than with {@link #RFC5545_LAX}. {@link #RFC5545_LAX} will just drop all invalid parts and evaluate the rule according to RFC 5545. This // * mode will evaluate all rules. <p> Also this mode will output rules that comply with RFC 2445. </p> // */ // RFC2445_LAX, // // /** // * Parses recurrence rules according to <a href="http://tools.ietf.org/html/rfc5545#section-3.3.10">RFC 5545</a>. Every error will cause an exception to // * be thrown. // */ // RFC5545_STRICT, // // /** // * Parses recurrence rules according to <a href="http://tools.ietf.org/html/rfc5545#section-3.3.10">RFC 5545</a> in a more tolerant way. The parser will // * just skip invalid parts in the rule and won't complain as long as the result is a valid rule. <p> This mode also accepts rules that comply with <a // * href="http://tools.ietf.org/html/rfc2445#section-4.3.10">RFC 2445</a> but not with RFC 5545. </p> <p> <strong>Note:</strong> Using this mode rules // * are evaluated differently than with {@link #RFC2445_LAX}. This mode will just drop all invalid parts and evaluate the rule according to RFC 5545. // * {@link #RFC2445_LAX} will evaluate all rules. <p> Also this mode will output rules that comply with RFC 5545. </p> // */ // RFC5545_LAX; // } // // Path: src/main/java/org/dmfs/rfc5545/recur/RecurrenceRule.java // public enum Skip // { // /** // * OMIT is the default value. It means that non-existing dates are just ignored. // */ // OMIT, // // /** // * BACKWARD means that non-existing instanced get rolled back to the previous day (for leap days) or month (for leap months). // */ // BACKWARD, // // /** // * FORWARD means that non-existing instanced get rolled forward to the next day (for leap days) or month (for leap months). // */ // FORWARD; // }
import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import org.dmfs.rfc5545.DateTime; import org.dmfs.rfc5545.recur.RecurrenceRule.RfcMode; import org.dmfs.rfc5545.recur.RecurrenceRule.Skip; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import java.util.Calendar; import java.util.LinkedList; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse;
count++; if (count == MAX_ITERATIONS) { break; } } } } /** * This test ensures that the rule is correctly evaluated when you move the start to a later instance. To do so it iterates over one rule and starts a new * iteration for every instance (using that instance as the start date). Then it compares the next instances of both iterations. * * @throws InvalidRecurrenceRuleException */ @Test public void testWalkingStart() throws InvalidRecurrenceRuleException { for (TestRule rule : mTestRules) { DateTime lastInstance = null; List<RecurrenceRuleIterator> instanceIterators = new LinkedList<RecurrenceRuleIterator>(); try { RecurrenceRule r1 = new RecurrenceRule(rule.rule, rule.mode);
// Path: src/main/java/org/dmfs/rfc5545/recur/RecurrenceRule.java // public enum RfcMode // { // /** // * Parses recurrence rules according to <a href="http://tools.ietf.org/html/rfc2445#section-4.3.10">RFC 2445</a>. Every error will cause an exception to // * be thrown. // */ // RFC2445_STRICT, // // /** // * Parses recurrence rules according to <a href="http://tools.ietf.org/html/rfc2445#section-4.3.10">RFC 2445</a> in a more tolerant way. The parser will // * just skip invalid parts in the rule and won't complain as long as the result is a valid rule. <p> This mode also accepts rules that comply with <a // * href="http://tools.ietf.org/html/rfc5545#section-3.3.10">RFC 5545</a>. </p> <p> <strong>Note:</strong> Using this mode rules are evaluated // * differently than with {@link #RFC5545_LAX}. {@link #RFC5545_LAX} will just drop all invalid parts and evaluate the rule according to RFC 5545. This // * mode will evaluate all rules. <p> Also this mode will output rules that comply with RFC 2445. </p> // */ // RFC2445_LAX, // // /** // * Parses recurrence rules according to <a href="http://tools.ietf.org/html/rfc5545#section-3.3.10">RFC 5545</a>. Every error will cause an exception to // * be thrown. // */ // RFC5545_STRICT, // // /** // * Parses recurrence rules according to <a href="http://tools.ietf.org/html/rfc5545#section-3.3.10">RFC 5545</a> in a more tolerant way. The parser will // * just skip invalid parts in the rule and won't complain as long as the result is a valid rule. <p> This mode also accepts rules that comply with <a // * href="http://tools.ietf.org/html/rfc2445#section-4.3.10">RFC 2445</a> but not with RFC 5545. </p> <p> <strong>Note:</strong> Using this mode rules // * are evaluated differently than with {@link #RFC2445_LAX}. This mode will just drop all invalid parts and evaluate the rule according to RFC 5545. // * {@link #RFC2445_LAX} will evaluate all rules. <p> Also this mode will output rules that comply with RFC 5545. </p> // */ // RFC5545_LAX; // } // // Path: src/main/java/org/dmfs/rfc5545/recur/RecurrenceRule.java // public enum Skip // { // /** // * OMIT is the default value. It means that non-existing dates are just ignored. // */ // OMIT, // // /** // * BACKWARD means that non-existing instanced get rolled back to the previous day (for leap days) or month (for leap months). // */ // BACKWARD, // // /** // * FORWARD means that non-existing instanced get rolled forward to the next day (for leap days) or month (for leap months). // */ // FORWARD; // } // Path: src/test/java/org/dmfs/rfc5545/recur/RecurrenceIteratorTest.java import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import org.dmfs.rfc5545.DateTime; import org.dmfs.rfc5545.recur.RecurrenceRule.RfcMode; import org.dmfs.rfc5545.recur.RecurrenceRule.Skip; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import java.util.Calendar; import java.util.LinkedList; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; count++; if (count == MAX_ITERATIONS) { break; } } } } /** * This test ensures that the rule is correctly evaluated when you move the start to a later instance. To do so it iterates over one rule and starts a new * iteration for every instance (using that instance as the start date). Then it compares the next instances of both iterations. * * @throws InvalidRecurrenceRuleException */ @Test public void testWalkingStart() throws InvalidRecurrenceRuleException { for (TestRule rule : mTestRules) { DateTime lastInstance = null; List<RecurrenceRuleIterator> instanceIterators = new LinkedList<RecurrenceRuleIterator>(); try { RecurrenceRule r1 = new RecurrenceRule(rule.rule, rule.mode);
if (r1.getSkip() != Skip.OMIT)
dmfs/lib-recur
src/main/java/org/dmfs/rfc5545/recurrenceset/RecurrenceSet.java
// Path: src/main/java/org/dmfs/rfc5545/recurrenceset/AbstractRecurrenceAdapter.java // interface InstanceIterator // { // // /** // * Check if there is at least one more instance to iterate. // * // * @return <code>true</code> if the next call to {@link #next()} will return another instance, <code>false</code> otherwise. // */ // abstract boolean hasNext(); // // /** // * Get the next instance of this set. Do not call this if {@link #hasNext()} returns <code>false</code>. // * // * @return The time in milliseconds since the epoch of the next instance. // * // * @throws ArrayIndexOutOfBoundsException // * if there are no more instances. // */ // abstract long next(); // // /** // * Skip all instances till <code>until</code>. If <code>until</code> is an instance itself it will be the next iterated instance. If the rule doesn't // * recur till that date the next call to {@link #hasNext()} will return <code>false</code>. // * // * @param until // * A time stamp of the date to fast forward to. // */ // abstract void fastForward(long until); // // }
import org.dmfs.rfc5545.recurrenceset.AbstractRecurrenceAdapter.InstanceIterator; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.TimeZone;
/* * Copyright (C) 2013 Marten Gajda <marten@dmfs.org> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.dmfs.rfc5545.recurrenceset; /** * A recurrence set. A recurrence set consists of all instances defined by a recurrence rule or a list if instances except for exception instances. Exception * instances are defined by exceptions rules or lists of exception instances. <p> This class allows you to add any number of recurrence rules, recurrence * instances, exception rules and exception instance. It returns an {@link Iterator} that iterates all resulting instances. </p> * * @author Marten Gajda */ public class RecurrenceSet { /** * All the instances in the set. Not all of them may be iterated, since instances that are exceptions will be skipped. */ private final List<AbstractRecurrenceAdapter> mInstances = new ArrayList<AbstractRecurrenceAdapter>(); /** * All exceptions in the set. */ private List<AbstractRecurrenceAdapter> mExceptions = null; /** * Indicates if the recurrence set is infinite. */ private boolean mIsInfinite = false; /** * Add instances to the set of instances. * * @param adapter * An {@link AbstractRecurrenceAdapter} that defines instances. */ public void addInstances(AbstractRecurrenceAdapter adapter) { mInstances.add(adapter); // the entire set is infinite if there is at least one infinite instance set mIsInfinite |= adapter.isInfinite(); } /** * Add exceptions to the set of instances (i.e. effectively remove instances from the instance set). * * @param adapter * An {@link AbstractRecurrenceAdapter} that defines instances. */ public void addExceptions(AbstractRecurrenceAdapter adapter) { if (mExceptions == null) { mExceptions = new ArrayList<AbstractRecurrenceAdapter>(); } mExceptions.add(adapter); } /** * Get an iterator for the specified start time. * * @param timezone * The {@link TimeZone} of the first instance. * @param start * The start time in milliseconds since the epoch. * * @return A {@link RecurrenceSetIterator} that iterates all instances. */ public RecurrenceSetIterator iterator(TimeZone timezone, long start) { return iterator(timezone, start, Long.MAX_VALUE); } /** * Return a new {@link RecurrenceSetIterator} for this recurrence set. * * @param timezone * The {@link TimeZone} of the first instance. * @param start * The start time in milliseconds since the epoch. * @param end * The end of the time range to iterate in milliseconds since the epoch. * * @return A {@link RecurrenceSetIterator} that iterates all instances. */ public RecurrenceSetIterator iterator(TimeZone timezone, long start, long end) {
// Path: src/main/java/org/dmfs/rfc5545/recurrenceset/AbstractRecurrenceAdapter.java // interface InstanceIterator // { // // /** // * Check if there is at least one more instance to iterate. // * // * @return <code>true</code> if the next call to {@link #next()} will return another instance, <code>false</code> otherwise. // */ // abstract boolean hasNext(); // // /** // * Get the next instance of this set. Do not call this if {@link #hasNext()} returns <code>false</code>. // * // * @return The time in milliseconds since the epoch of the next instance. // * // * @throws ArrayIndexOutOfBoundsException // * if there are no more instances. // */ // abstract long next(); // // /** // * Skip all instances till <code>until</code>. If <code>until</code> is an instance itself it will be the next iterated instance. If the rule doesn't // * recur till that date the next call to {@link #hasNext()} will return <code>false</code>. // * // * @param until // * A time stamp of the date to fast forward to. // */ // abstract void fastForward(long until); // // } // Path: src/main/java/org/dmfs/rfc5545/recurrenceset/RecurrenceSet.java import org.dmfs.rfc5545.recurrenceset.AbstractRecurrenceAdapter.InstanceIterator; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.TimeZone; /* * Copyright (C) 2013 Marten Gajda <marten@dmfs.org> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.dmfs.rfc5545.recurrenceset; /** * A recurrence set. A recurrence set consists of all instances defined by a recurrence rule or a list if instances except for exception instances. Exception * instances are defined by exceptions rules or lists of exception instances. <p> This class allows you to add any number of recurrence rules, recurrence * instances, exception rules and exception instance. It returns an {@link Iterator} that iterates all resulting instances. </p> * * @author Marten Gajda */ public class RecurrenceSet { /** * All the instances in the set. Not all of them may be iterated, since instances that are exceptions will be skipped. */ private final List<AbstractRecurrenceAdapter> mInstances = new ArrayList<AbstractRecurrenceAdapter>(); /** * All exceptions in the set. */ private List<AbstractRecurrenceAdapter> mExceptions = null; /** * Indicates if the recurrence set is infinite. */ private boolean mIsInfinite = false; /** * Add instances to the set of instances. * * @param adapter * An {@link AbstractRecurrenceAdapter} that defines instances. */ public void addInstances(AbstractRecurrenceAdapter adapter) { mInstances.add(adapter); // the entire set is infinite if there is at least one infinite instance set mIsInfinite |= adapter.isInfinite(); } /** * Add exceptions to the set of instances (i.e. effectively remove instances from the instance set). * * @param adapter * An {@link AbstractRecurrenceAdapter} that defines instances. */ public void addExceptions(AbstractRecurrenceAdapter adapter) { if (mExceptions == null) { mExceptions = new ArrayList<AbstractRecurrenceAdapter>(); } mExceptions.add(adapter); } /** * Get an iterator for the specified start time. * * @param timezone * The {@link TimeZone} of the first instance. * @param start * The start time in milliseconds since the epoch. * * @return A {@link RecurrenceSetIterator} that iterates all instances. */ public RecurrenceSetIterator iterator(TimeZone timezone, long start) { return iterator(timezone, start, Long.MAX_VALUE); } /** * Return a new {@link RecurrenceSetIterator} for this recurrence set. * * @param timezone * The {@link TimeZone} of the first instance. * @param start * The start time in milliseconds since the epoch. * @param end * The end of the time range to iterate in milliseconds since the epoch. * * @return A {@link RecurrenceSetIterator} that iterates all instances. */ public RecurrenceSetIterator iterator(TimeZone timezone, long start, long end) {
List<InstanceIterator> instances = new ArrayList<InstanceIterator>(mInstances.size());
dmfs/lib-recur
lib-recur-hamcrest/src/test/java/org/dmfs/rfc5545/hamcrest/datetime/WeekOfYearMatcherTest.java
// Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/WeekOfYearMatcher.java // public static Matcher<DateTime> inWeekOfYear(Matcher<Integer> weekOfYearMatcher) // { // return new WeekOfYearMatcher(weekOfYearMatcher); // }
import org.dmfs.rfc5545.DateTime; import org.hamcrest.Matcher; import org.hamcrest.core.AllOf; import org.junit.Test; import static org.dmfs.jems.hamcrest.matchers.matcher.MatcherMatcher.describesAs; import static org.dmfs.jems.hamcrest.matchers.matcher.MatcherMatcher.matches; import static org.dmfs.jems.hamcrest.matchers.matcher.MatcherMatcher.mismatches; import static org.dmfs.rfc5545.hamcrest.datetime.WeekOfYearMatcher.inWeekOfYear; import static org.junit.Assert.assertThat;
/* * Copyright 2018 Marten Gajda <marten@dmfs.org> * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dmfs.rfc5545.hamcrest.datetime; /** * Unit test for {@link WeekOfYearMatcher}. * * @author Marten Gajda */ public class WeekOfYearMatcherTest { @Test public void test() throws Exception {
// Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/WeekOfYearMatcher.java // public static Matcher<DateTime> inWeekOfYear(Matcher<Integer> weekOfYearMatcher) // { // return new WeekOfYearMatcher(weekOfYearMatcher); // } // Path: lib-recur-hamcrest/src/test/java/org/dmfs/rfc5545/hamcrest/datetime/WeekOfYearMatcherTest.java import org.dmfs.rfc5545.DateTime; import org.hamcrest.Matcher; import org.hamcrest.core.AllOf; import org.junit.Test; import static org.dmfs.jems.hamcrest.matchers.matcher.MatcherMatcher.describesAs; import static org.dmfs.jems.hamcrest.matchers.matcher.MatcherMatcher.matches; import static org.dmfs.jems.hamcrest.matchers.matcher.MatcherMatcher.mismatches; import static org.dmfs.rfc5545.hamcrest.datetime.WeekOfYearMatcher.inWeekOfYear; import static org.junit.Assert.assertThat; /* * Copyright 2018 Marten Gajda <marten@dmfs.org> * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dmfs.rfc5545.hamcrest.datetime; /** * Unit test for {@link WeekOfYearMatcher}. * * @author Marten Gajda */ public class WeekOfYearMatcherTest { @Test public void test() throws Exception {
assertThat(inWeekOfYear(16),
dmfs/lib-recur
src/main/java/org/dmfs/rfc5545/recurrenceset/RecurrenceSetIterator.java
// Path: src/main/java/org/dmfs/rfc5545/recurrenceset/AbstractRecurrenceAdapter.java // interface InstanceIterator // { // // /** // * Check if there is at least one more instance to iterate. // * // * @return <code>true</code> if the next call to {@link #next()} will return another instance, <code>false</code> otherwise. // */ // abstract boolean hasNext(); // // /** // * Get the next instance of this set. Do not call this if {@link #hasNext()} returns <code>false</code>. // * // * @return The time in milliseconds since the epoch of the next instance. // * // * @throws ArrayIndexOutOfBoundsException // * if there are no more instances. // */ // abstract long next(); // // /** // * Skip all instances till <code>until</code>. If <code>until</code> is an instance itself it will be the next iterated instance. If the rule doesn't // * recur till that date the next call to {@link #hasNext()} will return <code>false</code>. // * // * @param until // * A time stamp of the date to fast forward to. // */ // abstract void fastForward(long until); // // }
import org.dmfs.rfc5545.recurrenceset.AbstractRecurrenceAdapter.InstanceIterator; import java.util.List; import java.util.Locale;
/* * Copyright (C) 2013 Marten Gajda <marten@dmfs.org> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.dmfs.rfc5545.recurrenceset; /** * An iterator for recurrence sets. It takes a number of {@link AbstractRecurrenceAdapter}s for instances and exceptions and iterates all resulting instances * (i.e. only the instances, not the exceptions). <p> This class doesn't implement the {@link InstanceIterator} interface for one reasons: </p> <ul> <li>An * {@link InstanceIterator} always returns an {@link Object}, so instead of a primitive <code>long</code> we would have to return a {@link Long}. That is an * additional object which doesn't have any advantage.</li> </ul> * * @author Marten Gajda */ public class RecurrenceSetIterator { /** * Throw if we skipped this many instances in a line, because they were exceptions. */ private final static int MAX_SKIPPED_INSTANCES = 1000;
// Path: src/main/java/org/dmfs/rfc5545/recurrenceset/AbstractRecurrenceAdapter.java // interface InstanceIterator // { // // /** // * Check if there is at least one more instance to iterate. // * // * @return <code>true</code> if the next call to {@link #next()} will return another instance, <code>false</code> otherwise. // */ // abstract boolean hasNext(); // // /** // * Get the next instance of this set. Do not call this if {@link #hasNext()} returns <code>false</code>. // * // * @return The time in milliseconds since the epoch of the next instance. // * // * @throws ArrayIndexOutOfBoundsException // * if there are no more instances. // */ // abstract long next(); // // /** // * Skip all instances till <code>until</code>. If <code>until</code> is an instance itself it will be the next iterated instance. If the rule doesn't // * recur till that date the next call to {@link #hasNext()} will return <code>false</code>. // * // * @param until // * A time stamp of the date to fast forward to. // */ // abstract void fastForward(long until); // // } // Path: src/main/java/org/dmfs/rfc5545/recurrenceset/RecurrenceSetIterator.java import org.dmfs.rfc5545.recurrenceset.AbstractRecurrenceAdapter.InstanceIterator; import java.util.List; import java.util.Locale; /* * Copyright (C) 2013 Marten Gajda <marten@dmfs.org> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.dmfs.rfc5545.recurrenceset; /** * An iterator for recurrence sets. It takes a number of {@link AbstractRecurrenceAdapter}s for instances and exceptions and iterates all resulting instances * (i.e. only the instances, not the exceptions). <p> This class doesn't implement the {@link InstanceIterator} interface for one reasons: </p> <ul> <li>An * {@link InstanceIterator} always returns an {@link Object}, so instead of a primitive <code>long</code> we would have to return a {@link Long}. That is an * additional object which doesn't have any advantage.</li> </ul> * * @author Marten Gajda */ public class RecurrenceSetIterator { /** * Throw if we skipped this many instances in a line, because they were exceptions. */ private final static int MAX_SKIPPED_INSTANCES = 1000;
private final InstanceIterator mInstances;
dmfs/lib-recur
src/main/java/org/dmfs/rfc5545/recur/ByDayWeeklyExpander.java
// Path: src/main/java/org/dmfs/rfc5545/recur/RecurrenceRule.java // public static class WeekdayNum // { // /** // * The position of this weekday in the interval. This value is <code>0</code> if this instance means every occurrence of {@link #weekday} in the // * interval. // */ // public final int pos; // // /** // * The {@link Weekday}. // */ // public final Weekday weekday; // // // /** // * Create a new WeekdayNum instance. // * <p> // * TODO: update range check // * // * @param pos // * The position of the weekday in the Interval or <code>0</code> for every occurrence of the weekday. // * @param weekday // * The {@link Weekday}. // */ // public WeekdayNum(int pos, Weekday weekday) // { // if (pos < -53 || pos > 53) // { // throw new IllegalArgumentException("position " + pos + " of week day out of range"); // } // this.pos = pos; // this.weekday = weekday; // } // // // /** // * Parse a weekdaynum String as defined in <a href="http://tools.ietf.org/html/rfc5545#section-3.3.10">RFC 5545</a> (this definition equals the // * definition in RFC 2445). // * // * @param value // * The weekdaynum String to parse. // * @param tolerant // * Set to <code>true</code> to be tolerant and accept values outside of the allowed range. // * // * @return A new {@link WeekdayNum} instance. // * // * @throws InvalidRecurrenceRuleException // * If the weekdaynum string is invalid. // */ // public static WeekdayNum valueOf(String value, boolean tolerant) throws InvalidRecurrenceRuleException // { // try // { // int len = value.length(); // if (len > 2) // { // // includes a position // int pos = Integer.parseInt(value.substring(value.charAt(0) == '+' ? 1 : 0, len - 2)); // if (!tolerant && (pos == 0 || pos < -53 || pos > 53)) // { // throw new InvalidRecurrenceRuleException("invalid weeknum: '" + value + "'"); // } // return new WeekdayNum(pos, Weekday.valueOf(value.substring(len - 2))); // } // else // { // return new WeekdayNum(0, Weekday.valueOf(value)); // } // } // catch (Exception e) // { // throw new InvalidRecurrenceRuleException("invalid weeknum: '" + value + "'", e); // } // } // // // /** // * Parse a weekdaynum String as defined in <a href="http://tools.ietf.org/html/rfc5545#section-3.3.10">RFC 5545</a> (this definition equals the // * definition in RFC 2445). In contrast to {@link #valueOf(String, boolean)} this method is always strict and throws on every invalid value. // * // * @param value // * The weekdaynum String to parse. // * // * @return A new {@link WeekdayNum} instance. // * // * @throws InvalidRecurrenceRuleException // * If the weekdaynum string is invalid. // */ // public static WeekdayNum valueOf(String value) throws InvalidRecurrenceRuleException // { // return valueOf(value, false); // } // // // @Override // public String toString() // { // return pos == 0 ? weekday.name() : Integer.valueOf(pos) + weekday.name(); // } // }
import org.dmfs.rfc5545.calendarmetrics.CalendarMetrics; import org.dmfs.rfc5545.recur.RecurrenceRule.WeekdayNum; import java.util.List;
/* * Copyright 2018 Marten Gajda <marten@dmfs.org> * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dmfs.rfc5545.recur; /** * An expander that expands recurrence rules by day of week in a weekly scope. * * @author Marten Gajda */ final class ByDayWeeklyExpander extends ByExpander { /** * The bitmap of week days to expand. */ private final int mDayBitMap; public ByDayWeeklyExpander(RecurrenceRule rule, RuleIterator previous, CalendarMetrics calendarTools, long start) { super(previous, calendarTools, start); // get the list of WeekDayNums and convert it into an array
// Path: src/main/java/org/dmfs/rfc5545/recur/RecurrenceRule.java // public static class WeekdayNum // { // /** // * The position of this weekday in the interval. This value is <code>0</code> if this instance means every occurrence of {@link #weekday} in the // * interval. // */ // public final int pos; // // /** // * The {@link Weekday}. // */ // public final Weekday weekday; // // // /** // * Create a new WeekdayNum instance. // * <p> // * TODO: update range check // * // * @param pos // * The position of the weekday in the Interval or <code>0</code> for every occurrence of the weekday. // * @param weekday // * The {@link Weekday}. // */ // public WeekdayNum(int pos, Weekday weekday) // { // if (pos < -53 || pos > 53) // { // throw new IllegalArgumentException("position " + pos + " of week day out of range"); // } // this.pos = pos; // this.weekday = weekday; // } // // // /** // * Parse a weekdaynum String as defined in <a href="http://tools.ietf.org/html/rfc5545#section-3.3.10">RFC 5545</a> (this definition equals the // * definition in RFC 2445). // * // * @param value // * The weekdaynum String to parse. // * @param tolerant // * Set to <code>true</code> to be tolerant and accept values outside of the allowed range. // * // * @return A new {@link WeekdayNum} instance. // * // * @throws InvalidRecurrenceRuleException // * If the weekdaynum string is invalid. // */ // public static WeekdayNum valueOf(String value, boolean tolerant) throws InvalidRecurrenceRuleException // { // try // { // int len = value.length(); // if (len > 2) // { // // includes a position // int pos = Integer.parseInt(value.substring(value.charAt(0) == '+' ? 1 : 0, len - 2)); // if (!tolerant && (pos == 0 || pos < -53 || pos > 53)) // { // throw new InvalidRecurrenceRuleException("invalid weeknum: '" + value + "'"); // } // return new WeekdayNum(pos, Weekday.valueOf(value.substring(len - 2))); // } // else // { // return new WeekdayNum(0, Weekday.valueOf(value)); // } // } // catch (Exception e) // { // throw new InvalidRecurrenceRuleException("invalid weeknum: '" + value + "'", e); // } // } // // // /** // * Parse a weekdaynum String as defined in <a href="http://tools.ietf.org/html/rfc5545#section-3.3.10">RFC 5545</a> (this definition equals the // * definition in RFC 2445). In contrast to {@link #valueOf(String, boolean)} this method is always strict and throws on every invalid value. // * // * @param value // * The weekdaynum String to parse. // * // * @return A new {@link WeekdayNum} instance. // * // * @throws InvalidRecurrenceRuleException // * If the weekdaynum string is invalid. // */ // public static WeekdayNum valueOf(String value) throws InvalidRecurrenceRuleException // { // return valueOf(value, false); // } // // // @Override // public String toString() // { // return pos == 0 ? weekday.name() : Integer.valueOf(pos) + weekday.name(); // } // } // Path: src/main/java/org/dmfs/rfc5545/recur/ByDayWeeklyExpander.java import org.dmfs.rfc5545.calendarmetrics.CalendarMetrics; import org.dmfs.rfc5545.recur.RecurrenceRule.WeekdayNum; import java.util.List; /* * Copyright 2018 Marten Gajda <marten@dmfs.org> * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dmfs.rfc5545.recur; /** * An expander that expands recurrence rules by day of week in a weekly scope. * * @author Marten Gajda */ final class ByDayWeeklyExpander extends ByExpander { /** * The bitmap of week days to expand. */ private final int mDayBitMap; public ByDayWeeklyExpander(RecurrenceRule rule, RuleIterator previous, CalendarMetrics calendarTools, long start) { super(previous, calendarTools, start); // get the list of WeekDayNums and convert it into an array
List<WeekdayNum> byDay = rule.getByDayPart();
dmfs/lib-recur
src/test/java/org/dmfs/rfc5545/recur/RScaleTest.java
// Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static <T> Matcher<T> are(Matcher<T> matcher) // { // Description description = new StringDescription(); // matcher.describeTo(description); // return describedAs(String.format("are %s", description.toString()), is(matcher)); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static Function<DateTime, Matcher<RecurrenceRule>> instances(Matcher<DateTime> dtMatchers) // { // return dateTime -> InstancesMatcher.instances(dateTime, dtMatchers); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static Function<DateTime, Matcher<RecurrenceRule>> startingWith(String... dates) // { // return startingWith(new Seq<>(dates)); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static Matcher<RecurrenceRule> validRule(DateTime start, Iterable<Function<DateTime, Matcher<RecurrenceRule>>> matcherFunctions) // { // return new AllOf<>(new Joined<>(new Seq<>(increasing(start)), new Mapped<>(f -> f.value(start), matcherFunctions))); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/DayOfMonthMatcher.java // public static Matcher<DateTime> onDayOfMonth(Matcher<Integer> dayMatcher) // { // return new DayOfMonthMatcher(dayMatcher); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/DayOfYearMatcher.java // public static Matcher<DateTime> onDayOfYear(Matcher<Integer> dayMatcher) // { // return new DayOfYearMatcher(dayMatcher); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/MonthMatcher.java // public static Matcher<DateTime> inMonth(Matcher<Integer> monthMatcher) // { // return new MonthMatcher(monthMatcher); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/WeekOfYearMatcher.java // public static Matcher<DateTime> inWeekOfYear(Matcher<Integer> weekOfYearMatcher) // { // return new WeekOfYearMatcher(weekOfYearMatcher); // }
import org.dmfs.rfc5545.DateTime; import org.junit.Test; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.are; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.instances; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.startingWith; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.validRule; import static org.dmfs.rfc5545.hamcrest.datetime.DayOfMonthMatcher.onDayOfMonth; import static org.dmfs.rfc5545.hamcrest.datetime.DayOfYearMatcher.onDayOfYear; import static org.dmfs.rfc5545.hamcrest.datetime.MonthMatcher.inMonth; import static org.dmfs.rfc5545.hamcrest.datetime.WeekOfYearMatcher.inWeekOfYear; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat;
/* * Copyright 2018 Marten Gajda <marten@dmfs.org> * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dmfs.rfc5545.recur; /** * @author Marten Gajda */ public final class RScaleTest { @Test public void testByYearDaySkip() throws InvalidRecurrenceRuleException { assertThat(new RecurrenceRule("FREQ=YEARLY;RSCALE=GREGORIAN;BYYEARDAY=366"),
// Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static <T> Matcher<T> are(Matcher<T> matcher) // { // Description description = new StringDescription(); // matcher.describeTo(description); // return describedAs(String.format("are %s", description.toString()), is(matcher)); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static Function<DateTime, Matcher<RecurrenceRule>> instances(Matcher<DateTime> dtMatchers) // { // return dateTime -> InstancesMatcher.instances(dateTime, dtMatchers); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static Function<DateTime, Matcher<RecurrenceRule>> startingWith(String... dates) // { // return startingWith(new Seq<>(dates)); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static Matcher<RecurrenceRule> validRule(DateTime start, Iterable<Function<DateTime, Matcher<RecurrenceRule>>> matcherFunctions) // { // return new AllOf<>(new Joined<>(new Seq<>(increasing(start)), new Mapped<>(f -> f.value(start), matcherFunctions))); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/DayOfMonthMatcher.java // public static Matcher<DateTime> onDayOfMonth(Matcher<Integer> dayMatcher) // { // return new DayOfMonthMatcher(dayMatcher); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/DayOfYearMatcher.java // public static Matcher<DateTime> onDayOfYear(Matcher<Integer> dayMatcher) // { // return new DayOfYearMatcher(dayMatcher); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/MonthMatcher.java // public static Matcher<DateTime> inMonth(Matcher<Integer> monthMatcher) // { // return new MonthMatcher(monthMatcher); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/WeekOfYearMatcher.java // public static Matcher<DateTime> inWeekOfYear(Matcher<Integer> weekOfYearMatcher) // { // return new WeekOfYearMatcher(weekOfYearMatcher); // } // Path: src/test/java/org/dmfs/rfc5545/recur/RScaleTest.java import org.dmfs.rfc5545.DateTime; import org.junit.Test; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.are; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.instances; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.startingWith; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.validRule; import static org.dmfs.rfc5545.hamcrest.datetime.DayOfMonthMatcher.onDayOfMonth; import static org.dmfs.rfc5545.hamcrest.datetime.DayOfYearMatcher.onDayOfYear; import static org.dmfs.rfc5545.hamcrest.datetime.MonthMatcher.inMonth; import static org.dmfs.rfc5545.hamcrest.datetime.WeekOfYearMatcher.inWeekOfYear; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; /* * Copyright 2018 Marten Gajda <marten@dmfs.org> * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dmfs.rfc5545.recur; /** * @author Marten Gajda */ public final class RScaleTest { @Test public void testByYearDaySkip() throws InvalidRecurrenceRuleException { assertThat(new RecurrenceRule("FREQ=YEARLY;RSCALE=GREGORIAN;BYYEARDAY=366"),
is(validRule(DateTime.parse("20121231"),
dmfs/lib-recur
src/test/java/org/dmfs/rfc5545/recur/RScaleTest.java
// Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static <T> Matcher<T> are(Matcher<T> matcher) // { // Description description = new StringDescription(); // matcher.describeTo(description); // return describedAs(String.format("are %s", description.toString()), is(matcher)); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static Function<DateTime, Matcher<RecurrenceRule>> instances(Matcher<DateTime> dtMatchers) // { // return dateTime -> InstancesMatcher.instances(dateTime, dtMatchers); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static Function<DateTime, Matcher<RecurrenceRule>> startingWith(String... dates) // { // return startingWith(new Seq<>(dates)); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static Matcher<RecurrenceRule> validRule(DateTime start, Iterable<Function<DateTime, Matcher<RecurrenceRule>>> matcherFunctions) // { // return new AllOf<>(new Joined<>(new Seq<>(increasing(start)), new Mapped<>(f -> f.value(start), matcherFunctions))); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/DayOfMonthMatcher.java // public static Matcher<DateTime> onDayOfMonth(Matcher<Integer> dayMatcher) // { // return new DayOfMonthMatcher(dayMatcher); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/DayOfYearMatcher.java // public static Matcher<DateTime> onDayOfYear(Matcher<Integer> dayMatcher) // { // return new DayOfYearMatcher(dayMatcher); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/MonthMatcher.java // public static Matcher<DateTime> inMonth(Matcher<Integer> monthMatcher) // { // return new MonthMatcher(monthMatcher); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/WeekOfYearMatcher.java // public static Matcher<DateTime> inWeekOfYear(Matcher<Integer> weekOfYearMatcher) // { // return new WeekOfYearMatcher(weekOfYearMatcher); // }
import org.dmfs.rfc5545.DateTime; import org.junit.Test; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.are; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.instances; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.startingWith; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.validRule; import static org.dmfs.rfc5545.hamcrest.datetime.DayOfMonthMatcher.onDayOfMonth; import static org.dmfs.rfc5545.hamcrest.datetime.DayOfYearMatcher.onDayOfYear; import static org.dmfs.rfc5545.hamcrest.datetime.MonthMatcher.inMonth; import static org.dmfs.rfc5545.hamcrest.datetime.WeekOfYearMatcher.inWeekOfYear; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat;
/* * Copyright 2018 Marten Gajda <marten@dmfs.org> * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dmfs.rfc5545.recur; /** * @author Marten Gajda */ public final class RScaleTest { @Test public void testByYearDaySkip() throws InvalidRecurrenceRuleException { assertThat(new RecurrenceRule("FREQ=YEARLY;RSCALE=GREGORIAN;BYYEARDAY=366"), is(validRule(DateTime.parse("20121231"),
// Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static <T> Matcher<T> are(Matcher<T> matcher) // { // Description description = new StringDescription(); // matcher.describeTo(description); // return describedAs(String.format("are %s", description.toString()), is(matcher)); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static Function<DateTime, Matcher<RecurrenceRule>> instances(Matcher<DateTime> dtMatchers) // { // return dateTime -> InstancesMatcher.instances(dateTime, dtMatchers); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static Function<DateTime, Matcher<RecurrenceRule>> startingWith(String... dates) // { // return startingWith(new Seq<>(dates)); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static Matcher<RecurrenceRule> validRule(DateTime start, Iterable<Function<DateTime, Matcher<RecurrenceRule>>> matcherFunctions) // { // return new AllOf<>(new Joined<>(new Seq<>(increasing(start)), new Mapped<>(f -> f.value(start), matcherFunctions))); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/DayOfMonthMatcher.java // public static Matcher<DateTime> onDayOfMonth(Matcher<Integer> dayMatcher) // { // return new DayOfMonthMatcher(dayMatcher); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/DayOfYearMatcher.java // public static Matcher<DateTime> onDayOfYear(Matcher<Integer> dayMatcher) // { // return new DayOfYearMatcher(dayMatcher); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/MonthMatcher.java // public static Matcher<DateTime> inMonth(Matcher<Integer> monthMatcher) // { // return new MonthMatcher(monthMatcher); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/WeekOfYearMatcher.java // public static Matcher<DateTime> inWeekOfYear(Matcher<Integer> weekOfYearMatcher) // { // return new WeekOfYearMatcher(weekOfYearMatcher); // } // Path: src/test/java/org/dmfs/rfc5545/recur/RScaleTest.java import org.dmfs.rfc5545.DateTime; import org.junit.Test; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.are; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.instances; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.startingWith; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.validRule; import static org.dmfs.rfc5545.hamcrest.datetime.DayOfMonthMatcher.onDayOfMonth; import static org.dmfs.rfc5545.hamcrest.datetime.DayOfYearMatcher.onDayOfYear; import static org.dmfs.rfc5545.hamcrest.datetime.MonthMatcher.inMonth; import static org.dmfs.rfc5545.hamcrest.datetime.WeekOfYearMatcher.inWeekOfYear; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; /* * Copyright 2018 Marten Gajda <marten@dmfs.org> * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dmfs.rfc5545.recur; /** * @author Marten Gajda */ public final class RScaleTest { @Test public void testByYearDaySkip() throws InvalidRecurrenceRuleException { assertThat(new RecurrenceRule("FREQ=YEARLY;RSCALE=GREGORIAN;BYYEARDAY=366"), is(validRule(DateTime.parse("20121231"),
instances(are(onDayOfMonth(31), inMonth(12))),
dmfs/lib-recur
src/test/java/org/dmfs/rfc5545/recur/RScaleTest.java
// Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static <T> Matcher<T> are(Matcher<T> matcher) // { // Description description = new StringDescription(); // matcher.describeTo(description); // return describedAs(String.format("are %s", description.toString()), is(matcher)); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static Function<DateTime, Matcher<RecurrenceRule>> instances(Matcher<DateTime> dtMatchers) // { // return dateTime -> InstancesMatcher.instances(dateTime, dtMatchers); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static Function<DateTime, Matcher<RecurrenceRule>> startingWith(String... dates) // { // return startingWith(new Seq<>(dates)); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static Matcher<RecurrenceRule> validRule(DateTime start, Iterable<Function<DateTime, Matcher<RecurrenceRule>>> matcherFunctions) // { // return new AllOf<>(new Joined<>(new Seq<>(increasing(start)), new Mapped<>(f -> f.value(start), matcherFunctions))); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/DayOfMonthMatcher.java // public static Matcher<DateTime> onDayOfMonth(Matcher<Integer> dayMatcher) // { // return new DayOfMonthMatcher(dayMatcher); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/DayOfYearMatcher.java // public static Matcher<DateTime> onDayOfYear(Matcher<Integer> dayMatcher) // { // return new DayOfYearMatcher(dayMatcher); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/MonthMatcher.java // public static Matcher<DateTime> inMonth(Matcher<Integer> monthMatcher) // { // return new MonthMatcher(monthMatcher); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/WeekOfYearMatcher.java // public static Matcher<DateTime> inWeekOfYear(Matcher<Integer> weekOfYearMatcher) // { // return new WeekOfYearMatcher(weekOfYearMatcher); // }
import org.dmfs.rfc5545.DateTime; import org.junit.Test; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.are; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.instances; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.startingWith; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.validRule; import static org.dmfs.rfc5545.hamcrest.datetime.DayOfMonthMatcher.onDayOfMonth; import static org.dmfs.rfc5545.hamcrest.datetime.DayOfYearMatcher.onDayOfYear; import static org.dmfs.rfc5545.hamcrest.datetime.MonthMatcher.inMonth; import static org.dmfs.rfc5545.hamcrest.datetime.WeekOfYearMatcher.inWeekOfYear; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat;
/* * Copyright 2018 Marten Gajda <marten@dmfs.org> * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dmfs.rfc5545.recur; /** * @author Marten Gajda */ public final class RScaleTest { @Test public void testByYearDaySkip() throws InvalidRecurrenceRuleException { assertThat(new RecurrenceRule("FREQ=YEARLY;RSCALE=GREGORIAN;BYYEARDAY=366"), is(validRule(DateTime.parse("20121231"),
// Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static <T> Matcher<T> are(Matcher<T> matcher) // { // Description description = new StringDescription(); // matcher.describeTo(description); // return describedAs(String.format("are %s", description.toString()), is(matcher)); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static Function<DateTime, Matcher<RecurrenceRule>> instances(Matcher<DateTime> dtMatchers) // { // return dateTime -> InstancesMatcher.instances(dateTime, dtMatchers); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static Function<DateTime, Matcher<RecurrenceRule>> startingWith(String... dates) // { // return startingWith(new Seq<>(dates)); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static Matcher<RecurrenceRule> validRule(DateTime start, Iterable<Function<DateTime, Matcher<RecurrenceRule>>> matcherFunctions) // { // return new AllOf<>(new Joined<>(new Seq<>(increasing(start)), new Mapped<>(f -> f.value(start), matcherFunctions))); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/DayOfMonthMatcher.java // public static Matcher<DateTime> onDayOfMonth(Matcher<Integer> dayMatcher) // { // return new DayOfMonthMatcher(dayMatcher); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/DayOfYearMatcher.java // public static Matcher<DateTime> onDayOfYear(Matcher<Integer> dayMatcher) // { // return new DayOfYearMatcher(dayMatcher); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/MonthMatcher.java // public static Matcher<DateTime> inMonth(Matcher<Integer> monthMatcher) // { // return new MonthMatcher(monthMatcher); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/WeekOfYearMatcher.java // public static Matcher<DateTime> inWeekOfYear(Matcher<Integer> weekOfYearMatcher) // { // return new WeekOfYearMatcher(weekOfYearMatcher); // } // Path: src/test/java/org/dmfs/rfc5545/recur/RScaleTest.java import org.dmfs.rfc5545.DateTime; import org.junit.Test; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.are; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.instances; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.startingWith; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.validRule; import static org.dmfs.rfc5545.hamcrest.datetime.DayOfMonthMatcher.onDayOfMonth; import static org.dmfs.rfc5545.hamcrest.datetime.DayOfYearMatcher.onDayOfYear; import static org.dmfs.rfc5545.hamcrest.datetime.MonthMatcher.inMonth; import static org.dmfs.rfc5545.hamcrest.datetime.WeekOfYearMatcher.inWeekOfYear; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; /* * Copyright 2018 Marten Gajda <marten@dmfs.org> * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dmfs.rfc5545.recur; /** * @author Marten Gajda */ public final class RScaleTest { @Test public void testByYearDaySkip() throws InvalidRecurrenceRuleException { assertThat(new RecurrenceRule("FREQ=YEARLY;RSCALE=GREGORIAN;BYYEARDAY=366"), is(validRule(DateTime.parse("20121231"),
instances(are(onDayOfMonth(31), inMonth(12))),
dmfs/lib-recur
src/test/java/org/dmfs/rfc5545/recur/RScaleTest.java
// Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static <T> Matcher<T> are(Matcher<T> matcher) // { // Description description = new StringDescription(); // matcher.describeTo(description); // return describedAs(String.format("are %s", description.toString()), is(matcher)); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static Function<DateTime, Matcher<RecurrenceRule>> instances(Matcher<DateTime> dtMatchers) // { // return dateTime -> InstancesMatcher.instances(dateTime, dtMatchers); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static Function<DateTime, Matcher<RecurrenceRule>> startingWith(String... dates) // { // return startingWith(new Seq<>(dates)); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static Matcher<RecurrenceRule> validRule(DateTime start, Iterable<Function<DateTime, Matcher<RecurrenceRule>>> matcherFunctions) // { // return new AllOf<>(new Joined<>(new Seq<>(increasing(start)), new Mapped<>(f -> f.value(start), matcherFunctions))); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/DayOfMonthMatcher.java // public static Matcher<DateTime> onDayOfMonth(Matcher<Integer> dayMatcher) // { // return new DayOfMonthMatcher(dayMatcher); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/DayOfYearMatcher.java // public static Matcher<DateTime> onDayOfYear(Matcher<Integer> dayMatcher) // { // return new DayOfYearMatcher(dayMatcher); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/MonthMatcher.java // public static Matcher<DateTime> inMonth(Matcher<Integer> monthMatcher) // { // return new MonthMatcher(monthMatcher); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/WeekOfYearMatcher.java // public static Matcher<DateTime> inWeekOfYear(Matcher<Integer> weekOfYearMatcher) // { // return new WeekOfYearMatcher(weekOfYearMatcher); // }
import org.dmfs.rfc5545.DateTime; import org.junit.Test; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.are; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.instances; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.startingWith; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.validRule; import static org.dmfs.rfc5545.hamcrest.datetime.DayOfMonthMatcher.onDayOfMonth; import static org.dmfs.rfc5545.hamcrest.datetime.DayOfYearMatcher.onDayOfYear; import static org.dmfs.rfc5545.hamcrest.datetime.MonthMatcher.inMonth; import static org.dmfs.rfc5545.hamcrest.datetime.WeekOfYearMatcher.inWeekOfYear; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat;
/* * Copyright 2018 Marten Gajda <marten@dmfs.org> * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dmfs.rfc5545.recur; /** * @author Marten Gajda */ public final class RScaleTest { @Test public void testByYearDaySkip() throws InvalidRecurrenceRuleException { assertThat(new RecurrenceRule("FREQ=YEARLY;RSCALE=GREGORIAN;BYYEARDAY=366"), is(validRule(DateTime.parse("20121231"),
// Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static <T> Matcher<T> are(Matcher<T> matcher) // { // Description description = new StringDescription(); // matcher.describeTo(description); // return describedAs(String.format("are %s", description.toString()), is(matcher)); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static Function<DateTime, Matcher<RecurrenceRule>> instances(Matcher<DateTime> dtMatchers) // { // return dateTime -> InstancesMatcher.instances(dateTime, dtMatchers); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static Function<DateTime, Matcher<RecurrenceRule>> startingWith(String... dates) // { // return startingWith(new Seq<>(dates)); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static Matcher<RecurrenceRule> validRule(DateTime start, Iterable<Function<DateTime, Matcher<RecurrenceRule>>> matcherFunctions) // { // return new AllOf<>(new Joined<>(new Seq<>(increasing(start)), new Mapped<>(f -> f.value(start), matcherFunctions))); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/DayOfMonthMatcher.java // public static Matcher<DateTime> onDayOfMonth(Matcher<Integer> dayMatcher) // { // return new DayOfMonthMatcher(dayMatcher); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/DayOfYearMatcher.java // public static Matcher<DateTime> onDayOfYear(Matcher<Integer> dayMatcher) // { // return new DayOfYearMatcher(dayMatcher); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/MonthMatcher.java // public static Matcher<DateTime> inMonth(Matcher<Integer> monthMatcher) // { // return new MonthMatcher(monthMatcher); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/WeekOfYearMatcher.java // public static Matcher<DateTime> inWeekOfYear(Matcher<Integer> weekOfYearMatcher) // { // return new WeekOfYearMatcher(weekOfYearMatcher); // } // Path: src/test/java/org/dmfs/rfc5545/recur/RScaleTest.java import org.dmfs.rfc5545.DateTime; import org.junit.Test; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.are; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.instances; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.startingWith; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.validRule; import static org.dmfs.rfc5545.hamcrest.datetime.DayOfMonthMatcher.onDayOfMonth; import static org.dmfs.rfc5545.hamcrest.datetime.DayOfYearMatcher.onDayOfYear; import static org.dmfs.rfc5545.hamcrest.datetime.MonthMatcher.inMonth; import static org.dmfs.rfc5545.hamcrest.datetime.WeekOfYearMatcher.inWeekOfYear; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; /* * Copyright 2018 Marten Gajda <marten@dmfs.org> * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dmfs.rfc5545.recur; /** * @author Marten Gajda */ public final class RScaleTest { @Test public void testByYearDaySkip() throws InvalidRecurrenceRuleException { assertThat(new RecurrenceRule("FREQ=YEARLY;RSCALE=GREGORIAN;BYYEARDAY=366"), is(validRule(DateTime.parse("20121231"),
instances(are(onDayOfMonth(31), inMonth(12))),
dmfs/lib-recur
src/test/java/org/dmfs/rfc5545/recur/RScaleTest.java
// Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static <T> Matcher<T> are(Matcher<T> matcher) // { // Description description = new StringDescription(); // matcher.describeTo(description); // return describedAs(String.format("are %s", description.toString()), is(matcher)); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static Function<DateTime, Matcher<RecurrenceRule>> instances(Matcher<DateTime> dtMatchers) // { // return dateTime -> InstancesMatcher.instances(dateTime, dtMatchers); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static Function<DateTime, Matcher<RecurrenceRule>> startingWith(String... dates) // { // return startingWith(new Seq<>(dates)); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static Matcher<RecurrenceRule> validRule(DateTime start, Iterable<Function<DateTime, Matcher<RecurrenceRule>>> matcherFunctions) // { // return new AllOf<>(new Joined<>(new Seq<>(increasing(start)), new Mapped<>(f -> f.value(start), matcherFunctions))); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/DayOfMonthMatcher.java // public static Matcher<DateTime> onDayOfMonth(Matcher<Integer> dayMatcher) // { // return new DayOfMonthMatcher(dayMatcher); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/DayOfYearMatcher.java // public static Matcher<DateTime> onDayOfYear(Matcher<Integer> dayMatcher) // { // return new DayOfYearMatcher(dayMatcher); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/MonthMatcher.java // public static Matcher<DateTime> inMonth(Matcher<Integer> monthMatcher) // { // return new MonthMatcher(monthMatcher); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/WeekOfYearMatcher.java // public static Matcher<DateTime> inWeekOfYear(Matcher<Integer> weekOfYearMatcher) // { // return new WeekOfYearMatcher(weekOfYearMatcher); // }
import org.dmfs.rfc5545.DateTime; import org.junit.Test; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.are; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.instances; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.startingWith; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.validRule; import static org.dmfs.rfc5545.hamcrest.datetime.DayOfMonthMatcher.onDayOfMonth; import static org.dmfs.rfc5545.hamcrest.datetime.DayOfYearMatcher.onDayOfYear; import static org.dmfs.rfc5545.hamcrest.datetime.MonthMatcher.inMonth; import static org.dmfs.rfc5545.hamcrest.datetime.WeekOfYearMatcher.inWeekOfYear; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat;
/* * Copyright 2018 Marten Gajda <marten@dmfs.org> * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dmfs.rfc5545.recur; /** * @author Marten Gajda */ public final class RScaleTest { @Test public void testByYearDaySkip() throws InvalidRecurrenceRuleException { assertThat(new RecurrenceRule("FREQ=YEARLY;RSCALE=GREGORIAN;BYYEARDAY=366"), is(validRule(DateTime.parse("20121231"),
// Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static <T> Matcher<T> are(Matcher<T> matcher) // { // Description description = new StringDescription(); // matcher.describeTo(description); // return describedAs(String.format("are %s", description.toString()), is(matcher)); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static Function<DateTime, Matcher<RecurrenceRule>> instances(Matcher<DateTime> dtMatchers) // { // return dateTime -> InstancesMatcher.instances(dateTime, dtMatchers); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static Function<DateTime, Matcher<RecurrenceRule>> startingWith(String... dates) // { // return startingWith(new Seq<>(dates)); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static Matcher<RecurrenceRule> validRule(DateTime start, Iterable<Function<DateTime, Matcher<RecurrenceRule>>> matcherFunctions) // { // return new AllOf<>(new Joined<>(new Seq<>(increasing(start)), new Mapped<>(f -> f.value(start), matcherFunctions))); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/DayOfMonthMatcher.java // public static Matcher<DateTime> onDayOfMonth(Matcher<Integer> dayMatcher) // { // return new DayOfMonthMatcher(dayMatcher); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/DayOfYearMatcher.java // public static Matcher<DateTime> onDayOfYear(Matcher<Integer> dayMatcher) // { // return new DayOfYearMatcher(dayMatcher); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/MonthMatcher.java // public static Matcher<DateTime> inMonth(Matcher<Integer> monthMatcher) // { // return new MonthMatcher(monthMatcher); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/WeekOfYearMatcher.java // public static Matcher<DateTime> inWeekOfYear(Matcher<Integer> weekOfYearMatcher) // { // return new WeekOfYearMatcher(weekOfYearMatcher); // } // Path: src/test/java/org/dmfs/rfc5545/recur/RScaleTest.java import org.dmfs.rfc5545.DateTime; import org.junit.Test; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.are; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.instances; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.startingWith; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.validRule; import static org.dmfs.rfc5545.hamcrest.datetime.DayOfMonthMatcher.onDayOfMonth; import static org.dmfs.rfc5545.hamcrest.datetime.DayOfYearMatcher.onDayOfYear; import static org.dmfs.rfc5545.hamcrest.datetime.MonthMatcher.inMonth; import static org.dmfs.rfc5545.hamcrest.datetime.WeekOfYearMatcher.inWeekOfYear; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; /* * Copyright 2018 Marten Gajda <marten@dmfs.org> * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dmfs.rfc5545.recur; /** * @author Marten Gajda */ public final class RScaleTest { @Test public void testByYearDaySkip() throws InvalidRecurrenceRuleException { assertThat(new RecurrenceRule("FREQ=YEARLY;RSCALE=GREGORIAN;BYYEARDAY=366"), is(validRule(DateTime.parse("20121231"),
instances(are(onDayOfMonth(31), inMonth(12))),
dmfs/lib-recur
src/test/java/org/dmfs/rfc5545/recur/RScaleTest.java
// Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static <T> Matcher<T> are(Matcher<T> matcher) // { // Description description = new StringDescription(); // matcher.describeTo(description); // return describedAs(String.format("are %s", description.toString()), is(matcher)); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static Function<DateTime, Matcher<RecurrenceRule>> instances(Matcher<DateTime> dtMatchers) // { // return dateTime -> InstancesMatcher.instances(dateTime, dtMatchers); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static Function<DateTime, Matcher<RecurrenceRule>> startingWith(String... dates) // { // return startingWith(new Seq<>(dates)); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static Matcher<RecurrenceRule> validRule(DateTime start, Iterable<Function<DateTime, Matcher<RecurrenceRule>>> matcherFunctions) // { // return new AllOf<>(new Joined<>(new Seq<>(increasing(start)), new Mapped<>(f -> f.value(start), matcherFunctions))); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/DayOfMonthMatcher.java // public static Matcher<DateTime> onDayOfMonth(Matcher<Integer> dayMatcher) // { // return new DayOfMonthMatcher(dayMatcher); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/DayOfYearMatcher.java // public static Matcher<DateTime> onDayOfYear(Matcher<Integer> dayMatcher) // { // return new DayOfYearMatcher(dayMatcher); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/MonthMatcher.java // public static Matcher<DateTime> inMonth(Matcher<Integer> monthMatcher) // { // return new MonthMatcher(monthMatcher); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/WeekOfYearMatcher.java // public static Matcher<DateTime> inWeekOfYear(Matcher<Integer> weekOfYearMatcher) // { // return new WeekOfYearMatcher(weekOfYearMatcher); // }
import org.dmfs.rfc5545.DateTime; import org.junit.Test; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.are; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.instances; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.startingWith; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.validRule; import static org.dmfs.rfc5545.hamcrest.datetime.DayOfMonthMatcher.onDayOfMonth; import static org.dmfs.rfc5545.hamcrest.datetime.DayOfYearMatcher.onDayOfYear; import static org.dmfs.rfc5545.hamcrest.datetime.MonthMatcher.inMonth; import static org.dmfs.rfc5545.hamcrest.datetime.WeekOfYearMatcher.inWeekOfYear; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat;
/* * Copyright 2018 Marten Gajda <marten@dmfs.org> * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dmfs.rfc5545.recur; /** * @author Marten Gajda */ public final class RScaleTest { @Test public void testByYearDaySkip() throws InvalidRecurrenceRuleException { assertThat(new RecurrenceRule("FREQ=YEARLY;RSCALE=GREGORIAN;BYYEARDAY=366"), is(validRule(DateTime.parse("20121231"), instances(are(onDayOfMonth(31), inMonth(12))),
// Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static <T> Matcher<T> are(Matcher<T> matcher) // { // Description description = new StringDescription(); // matcher.describeTo(description); // return describedAs(String.format("are %s", description.toString()), is(matcher)); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static Function<DateTime, Matcher<RecurrenceRule>> instances(Matcher<DateTime> dtMatchers) // { // return dateTime -> InstancesMatcher.instances(dateTime, dtMatchers); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static Function<DateTime, Matcher<RecurrenceRule>> startingWith(String... dates) // { // return startingWith(new Seq<>(dates)); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static Matcher<RecurrenceRule> validRule(DateTime start, Iterable<Function<DateTime, Matcher<RecurrenceRule>>> matcherFunctions) // { // return new AllOf<>(new Joined<>(new Seq<>(increasing(start)), new Mapped<>(f -> f.value(start), matcherFunctions))); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/DayOfMonthMatcher.java // public static Matcher<DateTime> onDayOfMonth(Matcher<Integer> dayMatcher) // { // return new DayOfMonthMatcher(dayMatcher); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/DayOfYearMatcher.java // public static Matcher<DateTime> onDayOfYear(Matcher<Integer> dayMatcher) // { // return new DayOfYearMatcher(dayMatcher); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/MonthMatcher.java // public static Matcher<DateTime> inMonth(Matcher<Integer> monthMatcher) // { // return new MonthMatcher(monthMatcher); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/WeekOfYearMatcher.java // public static Matcher<DateTime> inWeekOfYear(Matcher<Integer> weekOfYearMatcher) // { // return new WeekOfYearMatcher(weekOfYearMatcher); // } // Path: src/test/java/org/dmfs/rfc5545/recur/RScaleTest.java import org.dmfs.rfc5545.DateTime; import org.junit.Test; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.are; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.instances; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.startingWith; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.validRule; import static org.dmfs.rfc5545.hamcrest.datetime.DayOfMonthMatcher.onDayOfMonth; import static org.dmfs.rfc5545.hamcrest.datetime.DayOfYearMatcher.onDayOfYear; import static org.dmfs.rfc5545.hamcrest.datetime.MonthMatcher.inMonth; import static org.dmfs.rfc5545.hamcrest.datetime.WeekOfYearMatcher.inWeekOfYear; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; /* * Copyright 2018 Marten Gajda <marten@dmfs.org> * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dmfs.rfc5545.recur; /** * @author Marten Gajda */ public final class RScaleTest { @Test public void testByYearDaySkip() throws InvalidRecurrenceRuleException { assertThat(new RecurrenceRule("FREQ=YEARLY;RSCALE=GREGORIAN;BYYEARDAY=366"), is(validRule(DateTime.parse("20121231"), instances(are(onDayOfMonth(31), inMonth(12))),
startingWith("20121231", "20161231", "20201231"))));
dmfs/lib-recur
src/test/java/org/dmfs/rfc5545/recur/RScaleTest.java
// Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static <T> Matcher<T> are(Matcher<T> matcher) // { // Description description = new StringDescription(); // matcher.describeTo(description); // return describedAs(String.format("are %s", description.toString()), is(matcher)); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static Function<DateTime, Matcher<RecurrenceRule>> instances(Matcher<DateTime> dtMatchers) // { // return dateTime -> InstancesMatcher.instances(dateTime, dtMatchers); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static Function<DateTime, Matcher<RecurrenceRule>> startingWith(String... dates) // { // return startingWith(new Seq<>(dates)); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static Matcher<RecurrenceRule> validRule(DateTime start, Iterable<Function<DateTime, Matcher<RecurrenceRule>>> matcherFunctions) // { // return new AllOf<>(new Joined<>(new Seq<>(increasing(start)), new Mapped<>(f -> f.value(start), matcherFunctions))); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/DayOfMonthMatcher.java // public static Matcher<DateTime> onDayOfMonth(Matcher<Integer> dayMatcher) // { // return new DayOfMonthMatcher(dayMatcher); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/DayOfYearMatcher.java // public static Matcher<DateTime> onDayOfYear(Matcher<Integer> dayMatcher) // { // return new DayOfYearMatcher(dayMatcher); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/MonthMatcher.java // public static Matcher<DateTime> inMonth(Matcher<Integer> monthMatcher) // { // return new MonthMatcher(monthMatcher); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/WeekOfYearMatcher.java // public static Matcher<DateTime> inWeekOfYear(Matcher<Integer> weekOfYearMatcher) // { // return new WeekOfYearMatcher(weekOfYearMatcher); // }
import org.dmfs.rfc5545.DateTime; import org.junit.Test; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.are; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.instances; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.startingWith; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.validRule; import static org.dmfs.rfc5545.hamcrest.datetime.DayOfMonthMatcher.onDayOfMonth; import static org.dmfs.rfc5545.hamcrest.datetime.DayOfYearMatcher.onDayOfYear; import static org.dmfs.rfc5545.hamcrest.datetime.MonthMatcher.inMonth; import static org.dmfs.rfc5545.hamcrest.datetime.WeekOfYearMatcher.inWeekOfYear; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat;
/* * Copyright 2018 Marten Gajda <marten@dmfs.org> * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dmfs.rfc5545.recur; /** * @author Marten Gajda */ public final class RScaleTest { @Test public void testByYearDaySkip() throws InvalidRecurrenceRuleException { assertThat(new RecurrenceRule("FREQ=YEARLY;RSCALE=GREGORIAN;BYYEARDAY=366"), is(validRule(DateTime.parse("20121231"), instances(are(onDayOfMonth(31), inMonth(12))), startingWith("20121231", "20161231", "20201231")))); assertThat(new RecurrenceRule("FREQ=YEARLY;RSCALE=GREGORIAN;BYYEARDAY=366;SKIP=OMIT"), is(validRule(DateTime.parse("20121231"), instances(are(onDayOfMonth(31), inMonth(12))), startingWith("20121231", "20161231", "20201231")))); assertThat(new RecurrenceRule("FREQ=YEARLY;RSCALE=GREGORIAN;BYYEARDAY=366;SKIP=FORWARD"), is(validRule(DateTime.parse("20121231"),
// Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static <T> Matcher<T> are(Matcher<T> matcher) // { // Description description = new StringDescription(); // matcher.describeTo(description); // return describedAs(String.format("are %s", description.toString()), is(matcher)); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static Function<DateTime, Matcher<RecurrenceRule>> instances(Matcher<DateTime> dtMatchers) // { // return dateTime -> InstancesMatcher.instances(dateTime, dtMatchers); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static Function<DateTime, Matcher<RecurrenceRule>> startingWith(String... dates) // { // return startingWith(new Seq<>(dates)); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static Matcher<RecurrenceRule> validRule(DateTime start, Iterable<Function<DateTime, Matcher<RecurrenceRule>>> matcherFunctions) // { // return new AllOf<>(new Joined<>(new Seq<>(increasing(start)), new Mapped<>(f -> f.value(start), matcherFunctions))); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/DayOfMonthMatcher.java // public static Matcher<DateTime> onDayOfMonth(Matcher<Integer> dayMatcher) // { // return new DayOfMonthMatcher(dayMatcher); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/DayOfYearMatcher.java // public static Matcher<DateTime> onDayOfYear(Matcher<Integer> dayMatcher) // { // return new DayOfYearMatcher(dayMatcher); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/MonthMatcher.java // public static Matcher<DateTime> inMonth(Matcher<Integer> monthMatcher) // { // return new MonthMatcher(monthMatcher); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/WeekOfYearMatcher.java // public static Matcher<DateTime> inWeekOfYear(Matcher<Integer> weekOfYearMatcher) // { // return new WeekOfYearMatcher(weekOfYearMatcher); // } // Path: src/test/java/org/dmfs/rfc5545/recur/RScaleTest.java import org.dmfs.rfc5545.DateTime; import org.junit.Test; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.are; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.instances; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.startingWith; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.validRule; import static org.dmfs.rfc5545.hamcrest.datetime.DayOfMonthMatcher.onDayOfMonth; import static org.dmfs.rfc5545.hamcrest.datetime.DayOfYearMatcher.onDayOfYear; import static org.dmfs.rfc5545.hamcrest.datetime.MonthMatcher.inMonth; import static org.dmfs.rfc5545.hamcrest.datetime.WeekOfYearMatcher.inWeekOfYear; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; /* * Copyright 2018 Marten Gajda <marten@dmfs.org> * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dmfs.rfc5545.recur; /** * @author Marten Gajda */ public final class RScaleTest { @Test public void testByYearDaySkip() throws InvalidRecurrenceRuleException { assertThat(new RecurrenceRule("FREQ=YEARLY;RSCALE=GREGORIAN;BYYEARDAY=366"), is(validRule(DateTime.parse("20121231"), instances(are(onDayOfMonth(31), inMonth(12))), startingWith("20121231", "20161231", "20201231")))); assertThat(new RecurrenceRule("FREQ=YEARLY;RSCALE=GREGORIAN;BYYEARDAY=366;SKIP=OMIT"), is(validRule(DateTime.parse("20121231"), instances(are(onDayOfMonth(31), inMonth(12))), startingWith("20121231", "20161231", "20201231")))); assertThat(new RecurrenceRule("FREQ=YEARLY;RSCALE=GREGORIAN;BYYEARDAY=366;SKIP=FORWARD"), is(validRule(DateTime.parse("20121231"),
instances(are(onDayOfMonth(1, 31), inMonth(1, 12), onDayOfYear(1, 366))),
dmfs/lib-recur
src/test/java/org/dmfs/rfc5545/recur/RScaleTest.java
// Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static <T> Matcher<T> are(Matcher<T> matcher) // { // Description description = new StringDescription(); // matcher.describeTo(description); // return describedAs(String.format("are %s", description.toString()), is(matcher)); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static Function<DateTime, Matcher<RecurrenceRule>> instances(Matcher<DateTime> dtMatchers) // { // return dateTime -> InstancesMatcher.instances(dateTime, dtMatchers); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static Function<DateTime, Matcher<RecurrenceRule>> startingWith(String... dates) // { // return startingWith(new Seq<>(dates)); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static Matcher<RecurrenceRule> validRule(DateTime start, Iterable<Function<DateTime, Matcher<RecurrenceRule>>> matcherFunctions) // { // return new AllOf<>(new Joined<>(new Seq<>(increasing(start)), new Mapped<>(f -> f.value(start), matcherFunctions))); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/DayOfMonthMatcher.java // public static Matcher<DateTime> onDayOfMonth(Matcher<Integer> dayMatcher) // { // return new DayOfMonthMatcher(dayMatcher); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/DayOfYearMatcher.java // public static Matcher<DateTime> onDayOfYear(Matcher<Integer> dayMatcher) // { // return new DayOfYearMatcher(dayMatcher); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/MonthMatcher.java // public static Matcher<DateTime> inMonth(Matcher<Integer> monthMatcher) // { // return new MonthMatcher(monthMatcher); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/WeekOfYearMatcher.java // public static Matcher<DateTime> inWeekOfYear(Matcher<Integer> weekOfYearMatcher) // { // return new WeekOfYearMatcher(weekOfYearMatcher); // }
import org.dmfs.rfc5545.DateTime; import org.junit.Test; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.are; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.instances; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.startingWith; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.validRule; import static org.dmfs.rfc5545.hamcrest.datetime.DayOfMonthMatcher.onDayOfMonth; import static org.dmfs.rfc5545.hamcrest.datetime.DayOfYearMatcher.onDayOfYear; import static org.dmfs.rfc5545.hamcrest.datetime.MonthMatcher.inMonth; import static org.dmfs.rfc5545.hamcrest.datetime.WeekOfYearMatcher.inWeekOfYear; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat;
startingWith("20121231", "20140101", "20150101", "20160101", "20161231", "20180101", "20190101", "20200101", "20201231")))); assertThat(new RecurrenceRule("FREQ=YEARLY;RSCALE=GREGORIAN;BYYEARDAY=366;SKIP=BACKWARD"), is(validRule(DateTime.parse("20121231"), instances(are(onDayOfMonth(31), inMonth(12))), startingWith("20121231", "20131231", "20141231", "20151231", "20161231", "20171231", "20181231", "20191231", "20201231")))); assertThat(new RecurrenceRule("FREQ=YEARLY;RSCALE=GREGORIAN;BYYEARDAY=-366"), is(validRule(DateTime.parse("20120101"), instances(are(onDayOfMonth(1), inMonth(1))), startingWith("20120101", "20160101", "20200101")))); assertThat(new RecurrenceRule("FREQ=YEARLY;RSCALE=GREGORIAN;BYYEARDAY=-366;SKIP=OMIT"), is(validRule(DateTime.parse("20120101"), instances(are(onDayOfMonth(1), inMonth(1))), startingWith("20120101", "20160101", "20200101")))); assertThat(new RecurrenceRule("FREQ=YEARLY;RSCALE=GREGORIAN;BYYEARDAY=-366;SKIP=FORWARD"), is(validRule(DateTime.parse("20120101"), instances(are(onDayOfMonth(1), inMonth(1), onDayOfYear(1))), startingWith("20120101", "20130101", "20140101", "20150101", "20160101", "20170101", "20180101", "20190101", "20200101")))); assertThat(new RecurrenceRule("FREQ=YEARLY;RSCALE=GREGORIAN;BYYEARDAY=-366;SKIP=BACKWARD"), is(validRule(DateTime.parse("20120101"), instances(are(onDayOfMonth(1, 31), inMonth(1, 12))), startingWith("20120101", "20121231", "20131231", "20141231", "20160101", "20161231", "20171231", "20181231", "20200101")))); } @Test public void testByWeekNoSkip() throws InvalidRecurrenceRuleException { assertThat(new RecurrenceRule("FREQ=YEARLY;RSCALE=GREGORIAN;BYWEEKNO=53"), is(validRule(DateTime.parse("20151229"),
// Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static <T> Matcher<T> are(Matcher<T> matcher) // { // Description description = new StringDescription(); // matcher.describeTo(description); // return describedAs(String.format("are %s", description.toString()), is(matcher)); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static Function<DateTime, Matcher<RecurrenceRule>> instances(Matcher<DateTime> dtMatchers) // { // return dateTime -> InstancesMatcher.instances(dateTime, dtMatchers); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static Function<DateTime, Matcher<RecurrenceRule>> startingWith(String... dates) // { // return startingWith(new Seq<>(dates)); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/RecurrenceRuleMatcher.java // public static Matcher<RecurrenceRule> validRule(DateTime start, Iterable<Function<DateTime, Matcher<RecurrenceRule>>> matcherFunctions) // { // return new AllOf<>(new Joined<>(new Seq<>(increasing(start)), new Mapped<>(f -> f.value(start), matcherFunctions))); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/DayOfMonthMatcher.java // public static Matcher<DateTime> onDayOfMonth(Matcher<Integer> dayMatcher) // { // return new DayOfMonthMatcher(dayMatcher); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/DayOfYearMatcher.java // public static Matcher<DateTime> onDayOfYear(Matcher<Integer> dayMatcher) // { // return new DayOfYearMatcher(dayMatcher); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/MonthMatcher.java // public static Matcher<DateTime> inMonth(Matcher<Integer> monthMatcher) // { // return new MonthMatcher(monthMatcher); // } // // Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/WeekOfYearMatcher.java // public static Matcher<DateTime> inWeekOfYear(Matcher<Integer> weekOfYearMatcher) // { // return new WeekOfYearMatcher(weekOfYearMatcher); // } // Path: src/test/java/org/dmfs/rfc5545/recur/RScaleTest.java import org.dmfs.rfc5545.DateTime; import org.junit.Test; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.are; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.instances; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.startingWith; import static org.dmfs.rfc5545.hamcrest.RecurrenceRuleMatcher.validRule; import static org.dmfs.rfc5545.hamcrest.datetime.DayOfMonthMatcher.onDayOfMonth; import static org.dmfs.rfc5545.hamcrest.datetime.DayOfYearMatcher.onDayOfYear; import static org.dmfs.rfc5545.hamcrest.datetime.MonthMatcher.inMonth; import static org.dmfs.rfc5545.hamcrest.datetime.WeekOfYearMatcher.inWeekOfYear; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; startingWith("20121231", "20140101", "20150101", "20160101", "20161231", "20180101", "20190101", "20200101", "20201231")))); assertThat(new RecurrenceRule("FREQ=YEARLY;RSCALE=GREGORIAN;BYYEARDAY=366;SKIP=BACKWARD"), is(validRule(DateTime.parse("20121231"), instances(are(onDayOfMonth(31), inMonth(12))), startingWith("20121231", "20131231", "20141231", "20151231", "20161231", "20171231", "20181231", "20191231", "20201231")))); assertThat(new RecurrenceRule("FREQ=YEARLY;RSCALE=GREGORIAN;BYYEARDAY=-366"), is(validRule(DateTime.parse("20120101"), instances(are(onDayOfMonth(1), inMonth(1))), startingWith("20120101", "20160101", "20200101")))); assertThat(new RecurrenceRule("FREQ=YEARLY;RSCALE=GREGORIAN;BYYEARDAY=-366;SKIP=OMIT"), is(validRule(DateTime.parse("20120101"), instances(are(onDayOfMonth(1), inMonth(1))), startingWith("20120101", "20160101", "20200101")))); assertThat(new RecurrenceRule("FREQ=YEARLY;RSCALE=GREGORIAN;BYYEARDAY=-366;SKIP=FORWARD"), is(validRule(DateTime.parse("20120101"), instances(are(onDayOfMonth(1), inMonth(1), onDayOfYear(1))), startingWith("20120101", "20130101", "20140101", "20150101", "20160101", "20170101", "20180101", "20190101", "20200101")))); assertThat(new RecurrenceRule("FREQ=YEARLY;RSCALE=GREGORIAN;BYYEARDAY=-366;SKIP=BACKWARD"), is(validRule(DateTime.parse("20120101"), instances(are(onDayOfMonth(1, 31), inMonth(1, 12))), startingWith("20120101", "20121231", "20131231", "20141231", "20160101", "20161231", "20171231", "20181231", "20200101")))); } @Test public void testByWeekNoSkip() throws InvalidRecurrenceRuleException { assertThat(new RecurrenceRule("FREQ=YEARLY;RSCALE=GREGORIAN;BYWEEKNO=53"), is(validRule(DateTime.parse("20151229"),
instances(are(onDayOfMonth(28, 29), inMonth(12), inWeekOfYear(53))),
dmfs/lib-recur
src/main/java/org/dmfs/rfc5545/recur/ByDayYearlyExpander.java
// Path: src/main/java/org/dmfs/rfc5545/recur/RecurrenceRule.java // public static class WeekdayNum // { // /** // * The position of this weekday in the interval. This value is <code>0</code> if this instance means every occurrence of {@link #weekday} in the // * interval. // */ // public final int pos; // // /** // * The {@link Weekday}. // */ // public final Weekday weekday; // // // /** // * Create a new WeekdayNum instance. // * <p> // * TODO: update range check // * // * @param pos // * The position of the weekday in the Interval or <code>0</code> for every occurrence of the weekday. // * @param weekday // * The {@link Weekday}. // */ // public WeekdayNum(int pos, Weekday weekday) // { // if (pos < -53 || pos > 53) // { // throw new IllegalArgumentException("position " + pos + " of week day out of range"); // } // this.pos = pos; // this.weekday = weekday; // } // // // /** // * Parse a weekdaynum String as defined in <a href="http://tools.ietf.org/html/rfc5545#section-3.3.10">RFC 5545</a> (this definition equals the // * definition in RFC 2445). // * // * @param value // * The weekdaynum String to parse. // * @param tolerant // * Set to <code>true</code> to be tolerant and accept values outside of the allowed range. // * // * @return A new {@link WeekdayNum} instance. // * // * @throws InvalidRecurrenceRuleException // * If the weekdaynum string is invalid. // */ // public static WeekdayNum valueOf(String value, boolean tolerant) throws InvalidRecurrenceRuleException // { // try // { // int len = value.length(); // if (len > 2) // { // // includes a position // int pos = Integer.parseInt(value.substring(value.charAt(0) == '+' ? 1 : 0, len - 2)); // if (!tolerant && (pos == 0 || pos < -53 || pos > 53)) // { // throw new InvalidRecurrenceRuleException("invalid weeknum: '" + value + "'"); // } // return new WeekdayNum(pos, Weekday.valueOf(value.substring(len - 2))); // } // else // { // return new WeekdayNum(0, Weekday.valueOf(value)); // } // } // catch (Exception e) // { // throw new InvalidRecurrenceRuleException("invalid weeknum: '" + value + "'", e); // } // } // // // /** // * Parse a weekdaynum String as defined in <a href="http://tools.ietf.org/html/rfc5545#section-3.3.10">RFC 5545</a> (this definition equals the // * definition in RFC 2445). In contrast to {@link #valueOf(String, boolean)} this method is always strict and throws on every invalid value. // * // * @param value // * The weekdaynum String to parse. // * // * @return A new {@link WeekdayNum} instance. // * // * @throws InvalidRecurrenceRuleException // * If the weekdaynum string is invalid. // */ // public static WeekdayNum valueOf(String value) throws InvalidRecurrenceRuleException // { // return valueOf(value, false); // } // // // @Override // public String toString() // { // return pos == 0 ? weekday.name() : Integer.valueOf(pos) + weekday.name(); // } // }
import org.dmfs.rfc5545.Instance; import org.dmfs.rfc5545.calendarmetrics.CalendarMetrics; import org.dmfs.rfc5545.recur.RecurrenceRule.WeekdayNum; import java.util.List;
/* * Copyright 2018 Marten Gajda <marten@dmfs.org> * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dmfs.rfc5545.recur; /** * An expander that expands recurrence rules by day of week in a yearly scope. * * @author Marten Gajda */ final class ByDayYearlyExpander extends ByExpander { /** * The list of week days to expand. */ private final int[] mByDay; /** * Get a packed representation of a {@link WeekdayNum}. * * @param pos * The position of the day or <code>0</code>. * @param day * The number of the weekday. * * @return An int that contains the position and the weekday. */ private static int packWeekday(int pos, int day) { return (pos << 8) + day; } /** * Get the weekday part of a packed day. * * @param packedDay * The packed day int. * * @return The weekday. */ private static int unpackWeekday(int packedDay) { return packedDay & 0xff; } /** * Get the positional part of a packed day. * * @param packedDay * The packed day int. * * @return The position. */ private static int unpackPos(int packedDay) { return packedDay >> 8; } public ByDayYearlyExpander(RecurrenceRule rule, RuleIterator previous, CalendarMetrics calendarTools, long start) { super(previous, calendarTools, start); // get the list of WeekDayNums and convert it into an array
// Path: src/main/java/org/dmfs/rfc5545/recur/RecurrenceRule.java // public static class WeekdayNum // { // /** // * The position of this weekday in the interval. This value is <code>0</code> if this instance means every occurrence of {@link #weekday} in the // * interval. // */ // public final int pos; // // /** // * The {@link Weekday}. // */ // public final Weekday weekday; // // // /** // * Create a new WeekdayNum instance. // * <p> // * TODO: update range check // * // * @param pos // * The position of the weekday in the Interval or <code>0</code> for every occurrence of the weekday. // * @param weekday // * The {@link Weekday}. // */ // public WeekdayNum(int pos, Weekday weekday) // { // if (pos < -53 || pos > 53) // { // throw new IllegalArgumentException("position " + pos + " of week day out of range"); // } // this.pos = pos; // this.weekday = weekday; // } // // // /** // * Parse a weekdaynum String as defined in <a href="http://tools.ietf.org/html/rfc5545#section-3.3.10">RFC 5545</a> (this definition equals the // * definition in RFC 2445). // * // * @param value // * The weekdaynum String to parse. // * @param tolerant // * Set to <code>true</code> to be tolerant and accept values outside of the allowed range. // * // * @return A new {@link WeekdayNum} instance. // * // * @throws InvalidRecurrenceRuleException // * If the weekdaynum string is invalid. // */ // public static WeekdayNum valueOf(String value, boolean tolerant) throws InvalidRecurrenceRuleException // { // try // { // int len = value.length(); // if (len > 2) // { // // includes a position // int pos = Integer.parseInt(value.substring(value.charAt(0) == '+' ? 1 : 0, len - 2)); // if (!tolerant && (pos == 0 || pos < -53 || pos > 53)) // { // throw new InvalidRecurrenceRuleException("invalid weeknum: '" + value + "'"); // } // return new WeekdayNum(pos, Weekday.valueOf(value.substring(len - 2))); // } // else // { // return new WeekdayNum(0, Weekday.valueOf(value)); // } // } // catch (Exception e) // { // throw new InvalidRecurrenceRuleException("invalid weeknum: '" + value + "'", e); // } // } // // // /** // * Parse a weekdaynum String as defined in <a href="http://tools.ietf.org/html/rfc5545#section-3.3.10">RFC 5545</a> (this definition equals the // * definition in RFC 2445). In contrast to {@link #valueOf(String, boolean)} this method is always strict and throws on every invalid value. // * // * @param value // * The weekdaynum String to parse. // * // * @return A new {@link WeekdayNum} instance. // * // * @throws InvalidRecurrenceRuleException // * If the weekdaynum string is invalid. // */ // public static WeekdayNum valueOf(String value) throws InvalidRecurrenceRuleException // { // return valueOf(value, false); // } // // // @Override // public String toString() // { // return pos == 0 ? weekday.name() : Integer.valueOf(pos) + weekday.name(); // } // } // Path: src/main/java/org/dmfs/rfc5545/recur/ByDayYearlyExpander.java import org.dmfs.rfc5545.Instance; import org.dmfs.rfc5545.calendarmetrics.CalendarMetrics; import org.dmfs.rfc5545.recur.RecurrenceRule.WeekdayNum; import java.util.List; /* * Copyright 2018 Marten Gajda <marten@dmfs.org> * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dmfs.rfc5545.recur; /** * An expander that expands recurrence rules by day of week in a yearly scope. * * @author Marten Gajda */ final class ByDayYearlyExpander extends ByExpander { /** * The list of week days to expand. */ private final int[] mByDay; /** * Get a packed representation of a {@link WeekdayNum}. * * @param pos * The position of the day or <code>0</code>. * @param day * The number of the weekday. * * @return An int that contains the position and the weekday. */ private static int packWeekday(int pos, int day) { return (pos << 8) + day; } /** * Get the weekday part of a packed day. * * @param packedDay * The packed day int. * * @return The weekday. */ private static int unpackWeekday(int packedDay) { return packedDay & 0xff; } /** * Get the positional part of a packed day. * * @param packedDay * The packed day int. * * @return The position. */ private static int unpackPos(int packedDay) { return packedDay >> 8; } public ByDayYearlyExpander(RecurrenceRule rule, RuleIterator previous, CalendarMetrics calendarTools, long start) { super(previous, calendarTools, start); // get the list of WeekDayNums and convert it into an array
List<WeekdayNum> byDay = rule.getByDayPart();
dmfs/lib-recur
lib-recur-hamcrest/src/test/java/org/dmfs/rfc5545/hamcrest/datetime/MonthMatcherTest.java
// Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/MonthMatcher.java // public static Matcher<DateTime> inMonth(Matcher<Integer> monthMatcher) // { // return new MonthMatcher(monthMatcher); // }
import org.dmfs.rfc5545.DateTime; import org.hamcrest.Matcher; import org.hamcrest.core.AllOf; import org.junit.Test; import static org.dmfs.jems.hamcrest.matchers.matcher.MatcherMatcher.describesAs; import static org.dmfs.jems.hamcrest.matchers.matcher.MatcherMatcher.matches; import static org.dmfs.jems.hamcrest.matchers.matcher.MatcherMatcher.mismatches; import static org.dmfs.rfc5545.hamcrest.datetime.MonthMatcher.inMonth; import static org.junit.Assert.assertThat;
/* * Copyright 2018 Marten Gajda <marten@dmfs.org> * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dmfs.rfc5545.hamcrest.datetime; /** * Unit test for {@link MonthMatcher}. * * @author Marten Gajda */ public class MonthMatcherTest { @Test public void test() throws Exception {
// Path: lib-recur-hamcrest/src/main/java/org/dmfs/rfc5545/hamcrest/datetime/MonthMatcher.java // public static Matcher<DateTime> inMonth(Matcher<Integer> monthMatcher) // { // return new MonthMatcher(monthMatcher); // } // Path: lib-recur-hamcrest/src/test/java/org/dmfs/rfc5545/hamcrest/datetime/MonthMatcherTest.java import org.dmfs.rfc5545.DateTime; import org.hamcrest.Matcher; import org.hamcrest.core.AllOf; import org.junit.Test; import static org.dmfs.jems.hamcrest.matchers.matcher.MatcherMatcher.describesAs; import static org.dmfs.jems.hamcrest.matchers.matcher.MatcherMatcher.matches; import static org.dmfs.jems.hamcrest.matchers.matcher.MatcherMatcher.mismatches; import static org.dmfs.rfc5545.hamcrest.datetime.MonthMatcher.inMonth; import static org.junit.Assert.assertThat; /* * Copyright 2018 Marten Gajda <marten@dmfs.org> * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dmfs.rfc5545.hamcrest.datetime; /** * Unit test for {@link MonthMatcher}. * * @author Marten Gajda */ public class MonthMatcherTest { @Test public void test() throws Exception {
assertThat(inMonth(10),
rctoris/jrosbridge
src/main/java/edu/wpi/rail/jrosbridge/messages/geometry/TwistWithCovarianceStamped.java
// Path: src/main/java/edu/wpi/rail/jrosbridge/messages/std/Header.java // public class Header extends Message { // // /** // * The name of the sequence field for the message. // */ // public static final java.lang.String FIELD_SEQ = "seq"; // // /** // * The name of the timestamp field for the message. // */ // public static final java.lang.String FIELD_STAMP = "stamp"; // // /** // * The name of the frame ID field for the message. // */ // public static final java.lang.String FIELD_FRAME_ID = "frame_id"; // // /** // * The message type. // */ // public static final java.lang.String TYPE = "std_msgs/Header"; // // private final int seq; // private final edu.wpi.rail.jrosbridge.primitives.Time stamp; // private final java.lang.String frameID; // // /** // * Create a new Header with all empty values. // */ // public Header() { // this(0, new edu.wpi.rail.jrosbridge.primitives.Time(), ""); // } // // /** // * Create a new Header with the given values. // * // * @param seq // * The sequence number treated as an unsigned 32-bit integer. // * @param stamp // * The timestamp. // * @param frameID // * The frame ID. // */ // public Header(int seq, edu.wpi.rail.jrosbridge.primitives.Time stamp, // java.lang.String frameID) { // // build the JSON object // super(Json.createObjectBuilder() // .add(Header.FIELD_SEQ, Primitive.fromUInt32(seq)) // .add(Header.FIELD_STAMP, stamp.toJsonObject()) // .add(Header.FIELD_FRAME_ID, frameID).build(), Header.TYPE); // this.seq = seq; // this.stamp = stamp; // this.frameID = frameID; // } // // /** // * Get the sequence value of this header which should be treated as an // * unsigned 32-bit integer. // * // * @return The sequence value of this header. // */ // public int getSeq() { // return this.seq; // } // // /** // * Get the timestamp value of this header. // * // * @return The timestamp value of this header. // */ // public edu.wpi.rail.jrosbridge.primitives.Time getStamp() { // return this.stamp; // } // // /** // * Get the frame ID value of this header. // * // * @return The frame ID value of this header. // */ // public java.lang.String getFrameID() { // return this.frameID; // } // // /** // * Create a clone of this Header. // */ // @Override // public Header clone() { // // time primitives are mutable, create a clone // return new Header(this.seq, this.stamp.clone(), this.frameID); // } // // /** // * Create a new Header based on the given JSON string. Any missing values // * will be set to their defaults. // * // * @param jsonString // * The JSON string to parse. // * @return A Header message based on the given JSON string. // */ // public static Header fromJsonString(java.lang.String jsonString) { // // convert to a message // return Header.fromMessage(new Message(jsonString)); // } // // /** // * Create a new Header based on the given Message. Any missing values will // * be set to their defaults. // * // * @param m // * The Message to parse. // * @return A Header message based on the given Message. // */ // public static Header fromMessage(Message m) { // // get it from the JSON object // return Header.fromJsonObject(m.toJsonObject()); // } // // /** // * Create a new Header based on the given JSON object. Any missing values // * will be set to their defaults. // * // * @param jsonObject // * The JSON object to parse. // * @return A Header message based on the given JSON object. // */ // public static Header fromJsonObject(JsonObject jsonObject) { // // check the fields // long seq64 = jsonObject.containsKey(Header.FIELD_SEQ) ? jsonObject // .getJsonNumber(Header.FIELD_SEQ).longValue() : 0; // edu.wpi.rail.jrosbridge.primitives.Time stamp = jsonObject // .containsKey(Header.FIELD_STAMP) ? edu.wpi.rail.jrosbridge.primitives.Time // .fromJsonObject(jsonObject.getJsonObject(Header.FIELD_STAMP)) // : new edu.wpi.rail.jrosbridge.primitives.Time(); // java.lang.String frameID = jsonObject // .containsKey(Header.FIELD_FRAME_ID) ? jsonObject // .getString(Header.FIELD_FRAME_ID) : ""; // // // convert to a 32-bit number // int seq32 = Primitive.toUInt32(seq64); // return new Header(seq32, stamp, frameID); // } // }
import javax.json.Json; import javax.json.JsonObject; import edu.wpi.rail.jrosbridge.messages.Message; import edu.wpi.rail.jrosbridge.messages.std.Header;
package edu.wpi.rail.jrosbridge.messages.geometry; /** * The geometry_msgs/TwistWithCovarianceStamped message. This represents an * estimated twist with reference coordinate frame and timestamp. * * @author Russell Toris -- russell.toris@gmail.com * @version April 1, 2014 */ public class TwistWithCovarianceStamped extends Message { /** * The name of the header field for the message. */ public static final String FIELD_HEADER = "header"; /** * The name of the twist field for the message. */ public static final String FIELD_TWIST = "twist"; /** * The message type. */ public static final String TYPE = "geometry_msgs/TwistWithCovarianceStamped";
// Path: src/main/java/edu/wpi/rail/jrosbridge/messages/std/Header.java // public class Header extends Message { // // /** // * The name of the sequence field for the message. // */ // public static final java.lang.String FIELD_SEQ = "seq"; // // /** // * The name of the timestamp field for the message. // */ // public static final java.lang.String FIELD_STAMP = "stamp"; // // /** // * The name of the frame ID field for the message. // */ // public static final java.lang.String FIELD_FRAME_ID = "frame_id"; // // /** // * The message type. // */ // public static final java.lang.String TYPE = "std_msgs/Header"; // // private final int seq; // private final edu.wpi.rail.jrosbridge.primitives.Time stamp; // private final java.lang.String frameID; // // /** // * Create a new Header with all empty values. // */ // public Header() { // this(0, new edu.wpi.rail.jrosbridge.primitives.Time(), ""); // } // // /** // * Create a new Header with the given values. // * // * @param seq // * The sequence number treated as an unsigned 32-bit integer. // * @param stamp // * The timestamp. // * @param frameID // * The frame ID. // */ // public Header(int seq, edu.wpi.rail.jrosbridge.primitives.Time stamp, // java.lang.String frameID) { // // build the JSON object // super(Json.createObjectBuilder() // .add(Header.FIELD_SEQ, Primitive.fromUInt32(seq)) // .add(Header.FIELD_STAMP, stamp.toJsonObject()) // .add(Header.FIELD_FRAME_ID, frameID).build(), Header.TYPE); // this.seq = seq; // this.stamp = stamp; // this.frameID = frameID; // } // // /** // * Get the sequence value of this header which should be treated as an // * unsigned 32-bit integer. // * // * @return The sequence value of this header. // */ // public int getSeq() { // return this.seq; // } // // /** // * Get the timestamp value of this header. // * // * @return The timestamp value of this header. // */ // public edu.wpi.rail.jrosbridge.primitives.Time getStamp() { // return this.stamp; // } // // /** // * Get the frame ID value of this header. // * // * @return The frame ID value of this header. // */ // public java.lang.String getFrameID() { // return this.frameID; // } // // /** // * Create a clone of this Header. // */ // @Override // public Header clone() { // // time primitives are mutable, create a clone // return new Header(this.seq, this.stamp.clone(), this.frameID); // } // // /** // * Create a new Header based on the given JSON string. Any missing values // * will be set to their defaults. // * // * @param jsonString // * The JSON string to parse. // * @return A Header message based on the given JSON string. // */ // public static Header fromJsonString(java.lang.String jsonString) { // // convert to a message // return Header.fromMessage(new Message(jsonString)); // } // // /** // * Create a new Header based on the given Message. Any missing values will // * be set to their defaults. // * // * @param m // * The Message to parse. // * @return A Header message based on the given Message. // */ // public static Header fromMessage(Message m) { // // get it from the JSON object // return Header.fromJsonObject(m.toJsonObject()); // } // // /** // * Create a new Header based on the given JSON object. Any missing values // * will be set to their defaults. // * // * @param jsonObject // * The JSON object to parse. // * @return A Header message based on the given JSON object. // */ // public static Header fromJsonObject(JsonObject jsonObject) { // // check the fields // long seq64 = jsonObject.containsKey(Header.FIELD_SEQ) ? jsonObject // .getJsonNumber(Header.FIELD_SEQ).longValue() : 0; // edu.wpi.rail.jrosbridge.primitives.Time stamp = jsonObject // .containsKey(Header.FIELD_STAMP) ? edu.wpi.rail.jrosbridge.primitives.Time // .fromJsonObject(jsonObject.getJsonObject(Header.FIELD_STAMP)) // : new edu.wpi.rail.jrosbridge.primitives.Time(); // java.lang.String frameID = jsonObject // .containsKey(Header.FIELD_FRAME_ID) ? jsonObject // .getString(Header.FIELD_FRAME_ID) : ""; // // // convert to a 32-bit number // int seq32 = Primitive.toUInt32(seq64); // return new Header(seq32, stamp, frameID); // } // } // Path: src/main/java/edu/wpi/rail/jrosbridge/messages/geometry/TwistWithCovarianceStamped.java import javax.json.Json; import javax.json.JsonObject; import edu.wpi.rail.jrosbridge.messages.Message; import edu.wpi.rail.jrosbridge.messages.std.Header; package edu.wpi.rail.jrosbridge.messages.geometry; /** * The geometry_msgs/TwistWithCovarianceStamped message. This represents an * estimated twist with reference coordinate frame and timestamp. * * @author Russell Toris -- russell.toris@gmail.com * @version April 1, 2014 */ public class TwistWithCovarianceStamped extends Message { /** * The name of the header field for the message. */ public static final String FIELD_HEADER = "header"; /** * The name of the twist field for the message. */ public static final String FIELD_TWIST = "twist"; /** * The message type. */ public static final String TYPE = "geometry_msgs/TwistWithCovarianceStamped";
private final Header header;
rctoris/jrosbridge
src/main/java/edu/wpi/rail/jrosbridge/messages/geometry/QuaternionStamped.java
// Path: src/main/java/edu/wpi/rail/jrosbridge/messages/std/Header.java // public class Header extends Message { // // /** // * The name of the sequence field for the message. // */ // public static final java.lang.String FIELD_SEQ = "seq"; // // /** // * The name of the timestamp field for the message. // */ // public static final java.lang.String FIELD_STAMP = "stamp"; // // /** // * The name of the frame ID field for the message. // */ // public static final java.lang.String FIELD_FRAME_ID = "frame_id"; // // /** // * The message type. // */ // public static final java.lang.String TYPE = "std_msgs/Header"; // // private final int seq; // private final edu.wpi.rail.jrosbridge.primitives.Time stamp; // private final java.lang.String frameID; // // /** // * Create a new Header with all empty values. // */ // public Header() { // this(0, new edu.wpi.rail.jrosbridge.primitives.Time(), ""); // } // // /** // * Create a new Header with the given values. // * // * @param seq // * The sequence number treated as an unsigned 32-bit integer. // * @param stamp // * The timestamp. // * @param frameID // * The frame ID. // */ // public Header(int seq, edu.wpi.rail.jrosbridge.primitives.Time stamp, // java.lang.String frameID) { // // build the JSON object // super(Json.createObjectBuilder() // .add(Header.FIELD_SEQ, Primitive.fromUInt32(seq)) // .add(Header.FIELD_STAMP, stamp.toJsonObject()) // .add(Header.FIELD_FRAME_ID, frameID).build(), Header.TYPE); // this.seq = seq; // this.stamp = stamp; // this.frameID = frameID; // } // // /** // * Get the sequence value of this header which should be treated as an // * unsigned 32-bit integer. // * // * @return The sequence value of this header. // */ // public int getSeq() { // return this.seq; // } // // /** // * Get the timestamp value of this header. // * // * @return The timestamp value of this header. // */ // public edu.wpi.rail.jrosbridge.primitives.Time getStamp() { // return this.stamp; // } // // /** // * Get the frame ID value of this header. // * // * @return The frame ID value of this header. // */ // public java.lang.String getFrameID() { // return this.frameID; // } // // /** // * Create a clone of this Header. // */ // @Override // public Header clone() { // // time primitives are mutable, create a clone // return new Header(this.seq, this.stamp.clone(), this.frameID); // } // // /** // * Create a new Header based on the given JSON string. Any missing values // * will be set to their defaults. // * // * @param jsonString // * The JSON string to parse. // * @return A Header message based on the given JSON string. // */ // public static Header fromJsonString(java.lang.String jsonString) { // // convert to a message // return Header.fromMessage(new Message(jsonString)); // } // // /** // * Create a new Header based on the given Message. Any missing values will // * be set to their defaults. // * // * @param m // * The Message to parse. // * @return A Header message based on the given Message. // */ // public static Header fromMessage(Message m) { // // get it from the JSON object // return Header.fromJsonObject(m.toJsonObject()); // } // // /** // * Create a new Header based on the given JSON object. Any missing values // * will be set to their defaults. // * // * @param jsonObject // * The JSON object to parse. // * @return A Header message based on the given JSON object. // */ // public static Header fromJsonObject(JsonObject jsonObject) { // // check the fields // long seq64 = jsonObject.containsKey(Header.FIELD_SEQ) ? jsonObject // .getJsonNumber(Header.FIELD_SEQ).longValue() : 0; // edu.wpi.rail.jrosbridge.primitives.Time stamp = jsonObject // .containsKey(Header.FIELD_STAMP) ? edu.wpi.rail.jrosbridge.primitives.Time // .fromJsonObject(jsonObject.getJsonObject(Header.FIELD_STAMP)) // : new edu.wpi.rail.jrosbridge.primitives.Time(); // java.lang.String frameID = jsonObject // .containsKey(Header.FIELD_FRAME_ID) ? jsonObject // .getString(Header.FIELD_FRAME_ID) : ""; // // // convert to a 32-bit number // int seq32 = Primitive.toUInt32(seq64); // return new Header(seq32, stamp, frameID); // } // }
import javax.json.Json; import javax.json.JsonObject; import edu.wpi.rail.jrosbridge.messages.Message; import edu.wpi.rail.jrosbridge.messages.std.Header;
package edu.wpi.rail.jrosbridge.messages.geometry; /** * The geometry_msgs/QuaternionStamped message. This represents a Quaternion * with reference coordinate frame and timestamp. * * @author Russell Toris -- russell.toris@gmail.com * @version April 1, 2014 */ public class QuaternionStamped extends Message { /** * The name of the header field for the message. */ public static final String FIELD_HEADER = "header"; /** * The name of the quaternion field for the message. */ public static final String FIELD_QUATERNION = "quaternion"; /** * The message type. */ public static final String TYPE = "geometry_msgs/QuaternionStamped";
// Path: src/main/java/edu/wpi/rail/jrosbridge/messages/std/Header.java // public class Header extends Message { // // /** // * The name of the sequence field for the message. // */ // public static final java.lang.String FIELD_SEQ = "seq"; // // /** // * The name of the timestamp field for the message. // */ // public static final java.lang.String FIELD_STAMP = "stamp"; // // /** // * The name of the frame ID field for the message. // */ // public static final java.lang.String FIELD_FRAME_ID = "frame_id"; // // /** // * The message type. // */ // public static final java.lang.String TYPE = "std_msgs/Header"; // // private final int seq; // private final edu.wpi.rail.jrosbridge.primitives.Time stamp; // private final java.lang.String frameID; // // /** // * Create a new Header with all empty values. // */ // public Header() { // this(0, new edu.wpi.rail.jrosbridge.primitives.Time(), ""); // } // // /** // * Create a new Header with the given values. // * // * @param seq // * The sequence number treated as an unsigned 32-bit integer. // * @param stamp // * The timestamp. // * @param frameID // * The frame ID. // */ // public Header(int seq, edu.wpi.rail.jrosbridge.primitives.Time stamp, // java.lang.String frameID) { // // build the JSON object // super(Json.createObjectBuilder() // .add(Header.FIELD_SEQ, Primitive.fromUInt32(seq)) // .add(Header.FIELD_STAMP, stamp.toJsonObject()) // .add(Header.FIELD_FRAME_ID, frameID).build(), Header.TYPE); // this.seq = seq; // this.stamp = stamp; // this.frameID = frameID; // } // // /** // * Get the sequence value of this header which should be treated as an // * unsigned 32-bit integer. // * // * @return The sequence value of this header. // */ // public int getSeq() { // return this.seq; // } // // /** // * Get the timestamp value of this header. // * // * @return The timestamp value of this header. // */ // public edu.wpi.rail.jrosbridge.primitives.Time getStamp() { // return this.stamp; // } // // /** // * Get the frame ID value of this header. // * // * @return The frame ID value of this header. // */ // public java.lang.String getFrameID() { // return this.frameID; // } // // /** // * Create a clone of this Header. // */ // @Override // public Header clone() { // // time primitives are mutable, create a clone // return new Header(this.seq, this.stamp.clone(), this.frameID); // } // // /** // * Create a new Header based on the given JSON string. Any missing values // * will be set to their defaults. // * // * @param jsonString // * The JSON string to parse. // * @return A Header message based on the given JSON string. // */ // public static Header fromJsonString(java.lang.String jsonString) { // // convert to a message // return Header.fromMessage(new Message(jsonString)); // } // // /** // * Create a new Header based on the given Message. Any missing values will // * be set to their defaults. // * // * @param m // * The Message to parse. // * @return A Header message based on the given Message. // */ // public static Header fromMessage(Message m) { // // get it from the JSON object // return Header.fromJsonObject(m.toJsonObject()); // } // // /** // * Create a new Header based on the given JSON object. Any missing values // * will be set to their defaults. // * // * @param jsonObject // * The JSON object to parse. // * @return A Header message based on the given JSON object. // */ // public static Header fromJsonObject(JsonObject jsonObject) { // // check the fields // long seq64 = jsonObject.containsKey(Header.FIELD_SEQ) ? jsonObject // .getJsonNumber(Header.FIELD_SEQ).longValue() : 0; // edu.wpi.rail.jrosbridge.primitives.Time stamp = jsonObject // .containsKey(Header.FIELD_STAMP) ? edu.wpi.rail.jrosbridge.primitives.Time // .fromJsonObject(jsonObject.getJsonObject(Header.FIELD_STAMP)) // : new edu.wpi.rail.jrosbridge.primitives.Time(); // java.lang.String frameID = jsonObject // .containsKey(Header.FIELD_FRAME_ID) ? jsonObject // .getString(Header.FIELD_FRAME_ID) : ""; // // // convert to a 32-bit number // int seq32 = Primitive.toUInt32(seq64); // return new Header(seq32, stamp, frameID); // } // } // Path: src/main/java/edu/wpi/rail/jrosbridge/messages/geometry/QuaternionStamped.java import javax.json.Json; import javax.json.JsonObject; import edu.wpi.rail.jrosbridge.messages.Message; import edu.wpi.rail.jrosbridge.messages.std.Header; package edu.wpi.rail.jrosbridge.messages.geometry; /** * The geometry_msgs/QuaternionStamped message. This represents a Quaternion * with reference coordinate frame and timestamp. * * @author Russell Toris -- russell.toris@gmail.com * @version April 1, 2014 */ public class QuaternionStamped extends Message { /** * The name of the header field for the message. */ public static final String FIELD_HEADER = "header"; /** * The name of the quaternion field for the message. */ public static final String FIELD_QUATERNION = "quaternion"; /** * The message type. */ public static final String TYPE = "geometry_msgs/QuaternionStamped";
private final Header header;
rctoris/jrosbridge
src/main/java/edu/wpi/rail/jrosbridge/messages/geometry/PoseWithCovarianceStamped.java
// Path: src/main/java/edu/wpi/rail/jrosbridge/messages/std/Header.java // public class Header extends Message { // // /** // * The name of the sequence field for the message. // */ // public static final java.lang.String FIELD_SEQ = "seq"; // // /** // * The name of the timestamp field for the message. // */ // public static final java.lang.String FIELD_STAMP = "stamp"; // // /** // * The name of the frame ID field for the message. // */ // public static final java.lang.String FIELD_FRAME_ID = "frame_id"; // // /** // * The message type. // */ // public static final java.lang.String TYPE = "std_msgs/Header"; // // private final int seq; // private final edu.wpi.rail.jrosbridge.primitives.Time stamp; // private final java.lang.String frameID; // // /** // * Create a new Header with all empty values. // */ // public Header() { // this(0, new edu.wpi.rail.jrosbridge.primitives.Time(), ""); // } // // /** // * Create a new Header with the given values. // * // * @param seq // * The sequence number treated as an unsigned 32-bit integer. // * @param stamp // * The timestamp. // * @param frameID // * The frame ID. // */ // public Header(int seq, edu.wpi.rail.jrosbridge.primitives.Time stamp, // java.lang.String frameID) { // // build the JSON object // super(Json.createObjectBuilder() // .add(Header.FIELD_SEQ, Primitive.fromUInt32(seq)) // .add(Header.FIELD_STAMP, stamp.toJsonObject()) // .add(Header.FIELD_FRAME_ID, frameID).build(), Header.TYPE); // this.seq = seq; // this.stamp = stamp; // this.frameID = frameID; // } // // /** // * Get the sequence value of this header which should be treated as an // * unsigned 32-bit integer. // * // * @return The sequence value of this header. // */ // public int getSeq() { // return this.seq; // } // // /** // * Get the timestamp value of this header. // * // * @return The timestamp value of this header. // */ // public edu.wpi.rail.jrosbridge.primitives.Time getStamp() { // return this.stamp; // } // // /** // * Get the frame ID value of this header. // * // * @return The frame ID value of this header. // */ // public java.lang.String getFrameID() { // return this.frameID; // } // // /** // * Create a clone of this Header. // */ // @Override // public Header clone() { // // time primitives are mutable, create a clone // return new Header(this.seq, this.stamp.clone(), this.frameID); // } // // /** // * Create a new Header based on the given JSON string. Any missing values // * will be set to their defaults. // * // * @param jsonString // * The JSON string to parse. // * @return A Header message based on the given JSON string. // */ // public static Header fromJsonString(java.lang.String jsonString) { // // convert to a message // return Header.fromMessage(new Message(jsonString)); // } // // /** // * Create a new Header based on the given Message. Any missing values will // * be set to their defaults. // * // * @param m // * The Message to parse. // * @return A Header message based on the given Message. // */ // public static Header fromMessage(Message m) { // // get it from the JSON object // return Header.fromJsonObject(m.toJsonObject()); // } // // /** // * Create a new Header based on the given JSON object. Any missing values // * will be set to their defaults. // * // * @param jsonObject // * The JSON object to parse. // * @return A Header message based on the given JSON object. // */ // public static Header fromJsonObject(JsonObject jsonObject) { // // check the fields // long seq64 = jsonObject.containsKey(Header.FIELD_SEQ) ? jsonObject // .getJsonNumber(Header.FIELD_SEQ).longValue() : 0; // edu.wpi.rail.jrosbridge.primitives.Time stamp = jsonObject // .containsKey(Header.FIELD_STAMP) ? edu.wpi.rail.jrosbridge.primitives.Time // .fromJsonObject(jsonObject.getJsonObject(Header.FIELD_STAMP)) // : new edu.wpi.rail.jrosbridge.primitives.Time(); // java.lang.String frameID = jsonObject // .containsKey(Header.FIELD_FRAME_ID) ? jsonObject // .getString(Header.FIELD_FRAME_ID) : ""; // // // convert to a 32-bit number // int seq32 = Primitive.toUInt32(seq64); // return new Header(seq32, stamp, frameID); // } // }
import javax.json.Json; import javax.json.JsonObject; import edu.wpi.rail.jrosbridge.messages.Message; import edu.wpi.rail.jrosbridge.messages.std.Header;
package edu.wpi.rail.jrosbridge.messages.geometry; /** * The geometry_msgs/PoseWithCovarianceStamped message. This expresses an * estimated pose with a reference coordinate frame and timestamp. * * @author Russell Toris -- russell.toris@gmail.com * @version April 1, 2014 */ public class PoseWithCovarianceStamped extends Message { /** * The name of the header field for the message. */ public static final String FIELD_HEADER = "header"; /** * The name of the pose field for the message. */ public static final String FIELD_POSE = "pose"; /** * The message type. */ public static final String TYPE = "geometry_msgs/PoseWithCovarianceStamped";
// Path: src/main/java/edu/wpi/rail/jrosbridge/messages/std/Header.java // public class Header extends Message { // // /** // * The name of the sequence field for the message. // */ // public static final java.lang.String FIELD_SEQ = "seq"; // // /** // * The name of the timestamp field for the message. // */ // public static final java.lang.String FIELD_STAMP = "stamp"; // // /** // * The name of the frame ID field for the message. // */ // public static final java.lang.String FIELD_FRAME_ID = "frame_id"; // // /** // * The message type. // */ // public static final java.lang.String TYPE = "std_msgs/Header"; // // private final int seq; // private final edu.wpi.rail.jrosbridge.primitives.Time stamp; // private final java.lang.String frameID; // // /** // * Create a new Header with all empty values. // */ // public Header() { // this(0, new edu.wpi.rail.jrosbridge.primitives.Time(), ""); // } // // /** // * Create a new Header with the given values. // * // * @param seq // * The sequence number treated as an unsigned 32-bit integer. // * @param stamp // * The timestamp. // * @param frameID // * The frame ID. // */ // public Header(int seq, edu.wpi.rail.jrosbridge.primitives.Time stamp, // java.lang.String frameID) { // // build the JSON object // super(Json.createObjectBuilder() // .add(Header.FIELD_SEQ, Primitive.fromUInt32(seq)) // .add(Header.FIELD_STAMP, stamp.toJsonObject()) // .add(Header.FIELD_FRAME_ID, frameID).build(), Header.TYPE); // this.seq = seq; // this.stamp = stamp; // this.frameID = frameID; // } // // /** // * Get the sequence value of this header which should be treated as an // * unsigned 32-bit integer. // * // * @return The sequence value of this header. // */ // public int getSeq() { // return this.seq; // } // // /** // * Get the timestamp value of this header. // * // * @return The timestamp value of this header. // */ // public edu.wpi.rail.jrosbridge.primitives.Time getStamp() { // return this.stamp; // } // // /** // * Get the frame ID value of this header. // * // * @return The frame ID value of this header. // */ // public java.lang.String getFrameID() { // return this.frameID; // } // // /** // * Create a clone of this Header. // */ // @Override // public Header clone() { // // time primitives are mutable, create a clone // return new Header(this.seq, this.stamp.clone(), this.frameID); // } // // /** // * Create a new Header based on the given JSON string. Any missing values // * will be set to their defaults. // * // * @param jsonString // * The JSON string to parse. // * @return A Header message based on the given JSON string. // */ // public static Header fromJsonString(java.lang.String jsonString) { // // convert to a message // return Header.fromMessage(new Message(jsonString)); // } // // /** // * Create a new Header based on the given Message. Any missing values will // * be set to their defaults. // * // * @param m // * The Message to parse. // * @return A Header message based on the given Message. // */ // public static Header fromMessage(Message m) { // // get it from the JSON object // return Header.fromJsonObject(m.toJsonObject()); // } // // /** // * Create a new Header based on the given JSON object. Any missing values // * will be set to their defaults. // * // * @param jsonObject // * The JSON object to parse. // * @return A Header message based on the given JSON object. // */ // public static Header fromJsonObject(JsonObject jsonObject) { // // check the fields // long seq64 = jsonObject.containsKey(Header.FIELD_SEQ) ? jsonObject // .getJsonNumber(Header.FIELD_SEQ).longValue() : 0; // edu.wpi.rail.jrosbridge.primitives.Time stamp = jsonObject // .containsKey(Header.FIELD_STAMP) ? edu.wpi.rail.jrosbridge.primitives.Time // .fromJsonObject(jsonObject.getJsonObject(Header.FIELD_STAMP)) // : new edu.wpi.rail.jrosbridge.primitives.Time(); // java.lang.String frameID = jsonObject // .containsKey(Header.FIELD_FRAME_ID) ? jsonObject // .getString(Header.FIELD_FRAME_ID) : ""; // // // convert to a 32-bit number // int seq32 = Primitive.toUInt32(seq64); // return new Header(seq32, stamp, frameID); // } // } // Path: src/main/java/edu/wpi/rail/jrosbridge/messages/geometry/PoseWithCovarianceStamped.java import javax.json.Json; import javax.json.JsonObject; import edu.wpi.rail.jrosbridge.messages.Message; import edu.wpi.rail.jrosbridge.messages.std.Header; package edu.wpi.rail.jrosbridge.messages.geometry; /** * The geometry_msgs/PoseWithCovarianceStamped message. This expresses an * estimated pose with a reference coordinate frame and timestamp. * * @author Russell Toris -- russell.toris@gmail.com * @version April 1, 2014 */ public class PoseWithCovarianceStamped extends Message { /** * The name of the header field for the message. */ public static final String FIELD_HEADER = "header"; /** * The name of the pose field for the message. */ public static final String FIELD_POSE = "pose"; /** * The message type. */ public static final String TYPE = "geometry_msgs/PoseWithCovarianceStamped";
private final Header header;
rctoris/jrosbridge
src/test/java/edu/wpi/rail/jrosbridge/messages/geometry/TestTwistWithCovarianceStamped.java
// Path: src/main/java/edu/wpi/rail/jrosbridge/messages/std/Header.java // public class Header extends Message { // // /** // * The name of the sequence field for the message. // */ // public static final java.lang.String FIELD_SEQ = "seq"; // // /** // * The name of the timestamp field for the message. // */ // public static final java.lang.String FIELD_STAMP = "stamp"; // // /** // * The name of the frame ID field for the message. // */ // public static final java.lang.String FIELD_FRAME_ID = "frame_id"; // // /** // * The message type. // */ // public static final java.lang.String TYPE = "std_msgs/Header"; // // private final int seq; // private final edu.wpi.rail.jrosbridge.primitives.Time stamp; // private final java.lang.String frameID; // // /** // * Create a new Header with all empty values. // */ // public Header() { // this(0, new edu.wpi.rail.jrosbridge.primitives.Time(), ""); // } // // /** // * Create a new Header with the given values. // * // * @param seq // * The sequence number treated as an unsigned 32-bit integer. // * @param stamp // * The timestamp. // * @param frameID // * The frame ID. // */ // public Header(int seq, edu.wpi.rail.jrosbridge.primitives.Time stamp, // java.lang.String frameID) { // // build the JSON object // super(Json.createObjectBuilder() // .add(Header.FIELD_SEQ, Primitive.fromUInt32(seq)) // .add(Header.FIELD_STAMP, stamp.toJsonObject()) // .add(Header.FIELD_FRAME_ID, frameID).build(), Header.TYPE); // this.seq = seq; // this.stamp = stamp; // this.frameID = frameID; // } // // /** // * Get the sequence value of this header which should be treated as an // * unsigned 32-bit integer. // * // * @return The sequence value of this header. // */ // public int getSeq() { // return this.seq; // } // // /** // * Get the timestamp value of this header. // * // * @return The timestamp value of this header. // */ // public edu.wpi.rail.jrosbridge.primitives.Time getStamp() { // return this.stamp; // } // // /** // * Get the frame ID value of this header. // * // * @return The frame ID value of this header. // */ // public java.lang.String getFrameID() { // return this.frameID; // } // // /** // * Create a clone of this Header. // */ // @Override // public Header clone() { // // time primitives are mutable, create a clone // return new Header(this.seq, this.stamp.clone(), this.frameID); // } // // /** // * Create a new Header based on the given JSON string. Any missing values // * will be set to their defaults. // * // * @param jsonString // * The JSON string to parse. // * @return A Header message based on the given JSON string. // */ // public static Header fromJsonString(java.lang.String jsonString) { // // convert to a message // return Header.fromMessage(new Message(jsonString)); // } // // /** // * Create a new Header based on the given Message. Any missing values will // * be set to their defaults. // * // * @param m // * The Message to parse. // * @return A Header message based on the given Message. // */ // public static Header fromMessage(Message m) { // // get it from the JSON object // return Header.fromJsonObject(m.toJsonObject()); // } // // /** // * Create a new Header based on the given JSON object. Any missing values // * will be set to their defaults. // * // * @param jsonObject // * The JSON object to parse. // * @return A Header message based on the given JSON object. // */ // public static Header fromJsonObject(JsonObject jsonObject) { // // check the fields // long seq64 = jsonObject.containsKey(Header.FIELD_SEQ) ? jsonObject // .getJsonNumber(Header.FIELD_SEQ).longValue() : 0; // edu.wpi.rail.jrosbridge.primitives.Time stamp = jsonObject // .containsKey(Header.FIELD_STAMP) ? edu.wpi.rail.jrosbridge.primitives.Time // .fromJsonObject(jsonObject.getJsonObject(Header.FIELD_STAMP)) // : new edu.wpi.rail.jrosbridge.primitives.Time(); // java.lang.String frameID = jsonObject // .containsKey(Header.FIELD_FRAME_ID) ? jsonObject // .getString(Header.FIELD_FRAME_ID) : ""; // // // convert to a 32-bit number // int seq32 = Primitive.toUInt32(seq64); // return new Header(seq32, stamp, frameID); // } // }
import static org.junit.Assert.*; import javax.json.Json; import javax.json.JsonObject; import org.junit.Before; import org.junit.Test; import edu.wpi.rail.jrosbridge.messages.Message; import edu.wpi.rail.jrosbridge.messages.std.Header; import edu.wpi.rail.jrosbridge.primitives.Time;
package edu.wpi.rail.jrosbridge.messages.geometry; public class TestTwistWithCovarianceStamped { private TwistWithCovarianceStamped empty, t1; @Before public void setUp() { empty = new TwistWithCovarianceStamped();
// Path: src/main/java/edu/wpi/rail/jrosbridge/messages/std/Header.java // public class Header extends Message { // // /** // * The name of the sequence field for the message. // */ // public static final java.lang.String FIELD_SEQ = "seq"; // // /** // * The name of the timestamp field for the message. // */ // public static final java.lang.String FIELD_STAMP = "stamp"; // // /** // * The name of the frame ID field for the message. // */ // public static final java.lang.String FIELD_FRAME_ID = "frame_id"; // // /** // * The message type. // */ // public static final java.lang.String TYPE = "std_msgs/Header"; // // private final int seq; // private final edu.wpi.rail.jrosbridge.primitives.Time stamp; // private final java.lang.String frameID; // // /** // * Create a new Header with all empty values. // */ // public Header() { // this(0, new edu.wpi.rail.jrosbridge.primitives.Time(), ""); // } // // /** // * Create a new Header with the given values. // * // * @param seq // * The sequence number treated as an unsigned 32-bit integer. // * @param stamp // * The timestamp. // * @param frameID // * The frame ID. // */ // public Header(int seq, edu.wpi.rail.jrosbridge.primitives.Time stamp, // java.lang.String frameID) { // // build the JSON object // super(Json.createObjectBuilder() // .add(Header.FIELD_SEQ, Primitive.fromUInt32(seq)) // .add(Header.FIELD_STAMP, stamp.toJsonObject()) // .add(Header.FIELD_FRAME_ID, frameID).build(), Header.TYPE); // this.seq = seq; // this.stamp = stamp; // this.frameID = frameID; // } // // /** // * Get the sequence value of this header which should be treated as an // * unsigned 32-bit integer. // * // * @return The sequence value of this header. // */ // public int getSeq() { // return this.seq; // } // // /** // * Get the timestamp value of this header. // * // * @return The timestamp value of this header. // */ // public edu.wpi.rail.jrosbridge.primitives.Time getStamp() { // return this.stamp; // } // // /** // * Get the frame ID value of this header. // * // * @return The frame ID value of this header. // */ // public java.lang.String getFrameID() { // return this.frameID; // } // // /** // * Create a clone of this Header. // */ // @Override // public Header clone() { // // time primitives are mutable, create a clone // return new Header(this.seq, this.stamp.clone(), this.frameID); // } // // /** // * Create a new Header based on the given JSON string. Any missing values // * will be set to their defaults. // * // * @param jsonString // * The JSON string to parse. // * @return A Header message based on the given JSON string. // */ // public static Header fromJsonString(java.lang.String jsonString) { // // convert to a message // return Header.fromMessage(new Message(jsonString)); // } // // /** // * Create a new Header based on the given Message. Any missing values will // * be set to their defaults. // * // * @param m // * The Message to parse. // * @return A Header message based on the given Message. // */ // public static Header fromMessage(Message m) { // // get it from the JSON object // return Header.fromJsonObject(m.toJsonObject()); // } // // /** // * Create a new Header based on the given JSON object. Any missing values // * will be set to their defaults. // * // * @param jsonObject // * The JSON object to parse. // * @return A Header message based on the given JSON object. // */ // public static Header fromJsonObject(JsonObject jsonObject) { // // check the fields // long seq64 = jsonObject.containsKey(Header.FIELD_SEQ) ? jsonObject // .getJsonNumber(Header.FIELD_SEQ).longValue() : 0; // edu.wpi.rail.jrosbridge.primitives.Time stamp = jsonObject // .containsKey(Header.FIELD_STAMP) ? edu.wpi.rail.jrosbridge.primitives.Time // .fromJsonObject(jsonObject.getJsonObject(Header.FIELD_STAMP)) // : new edu.wpi.rail.jrosbridge.primitives.Time(); // java.lang.String frameID = jsonObject // .containsKey(Header.FIELD_FRAME_ID) ? jsonObject // .getString(Header.FIELD_FRAME_ID) : ""; // // // convert to a 32-bit number // int seq32 = Primitive.toUInt32(seq64); // return new Header(seq32, stamp, frameID); // } // } // Path: src/test/java/edu/wpi/rail/jrosbridge/messages/geometry/TestTwistWithCovarianceStamped.java import static org.junit.Assert.*; import javax.json.Json; import javax.json.JsonObject; import org.junit.Before; import org.junit.Test; import edu.wpi.rail.jrosbridge.messages.Message; import edu.wpi.rail.jrosbridge.messages.std.Header; import edu.wpi.rail.jrosbridge.primitives.Time; package edu.wpi.rail.jrosbridge.messages.geometry; public class TestTwistWithCovarianceStamped { private TwistWithCovarianceStamped empty, t1; @Before public void setUp() { empty = new TwistWithCovarianceStamped();
t1 = new TwistWithCovarianceStamped(new Header(123, new Time(10, 20),
rctoris/jrosbridge
src/main/java/edu/wpi/rail/jrosbridge/messages/geometry/Vector3Stamped.java
// Path: src/main/java/edu/wpi/rail/jrosbridge/messages/std/Header.java // public class Header extends Message { // // /** // * The name of the sequence field for the message. // */ // public static final java.lang.String FIELD_SEQ = "seq"; // // /** // * The name of the timestamp field for the message. // */ // public static final java.lang.String FIELD_STAMP = "stamp"; // // /** // * The name of the frame ID field for the message. // */ // public static final java.lang.String FIELD_FRAME_ID = "frame_id"; // // /** // * The message type. // */ // public static final java.lang.String TYPE = "std_msgs/Header"; // // private final int seq; // private final edu.wpi.rail.jrosbridge.primitives.Time stamp; // private final java.lang.String frameID; // // /** // * Create a new Header with all empty values. // */ // public Header() { // this(0, new edu.wpi.rail.jrosbridge.primitives.Time(), ""); // } // // /** // * Create a new Header with the given values. // * // * @param seq // * The sequence number treated as an unsigned 32-bit integer. // * @param stamp // * The timestamp. // * @param frameID // * The frame ID. // */ // public Header(int seq, edu.wpi.rail.jrosbridge.primitives.Time stamp, // java.lang.String frameID) { // // build the JSON object // super(Json.createObjectBuilder() // .add(Header.FIELD_SEQ, Primitive.fromUInt32(seq)) // .add(Header.FIELD_STAMP, stamp.toJsonObject()) // .add(Header.FIELD_FRAME_ID, frameID).build(), Header.TYPE); // this.seq = seq; // this.stamp = stamp; // this.frameID = frameID; // } // // /** // * Get the sequence value of this header which should be treated as an // * unsigned 32-bit integer. // * // * @return The sequence value of this header. // */ // public int getSeq() { // return this.seq; // } // // /** // * Get the timestamp value of this header. // * // * @return The timestamp value of this header. // */ // public edu.wpi.rail.jrosbridge.primitives.Time getStamp() { // return this.stamp; // } // // /** // * Get the frame ID value of this header. // * // * @return The frame ID value of this header. // */ // public java.lang.String getFrameID() { // return this.frameID; // } // // /** // * Create a clone of this Header. // */ // @Override // public Header clone() { // // time primitives are mutable, create a clone // return new Header(this.seq, this.stamp.clone(), this.frameID); // } // // /** // * Create a new Header based on the given JSON string. Any missing values // * will be set to their defaults. // * // * @param jsonString // * The JSON string to parse. // * @return A Header message based on the given JSON string. // */ // public static Header fromJsonString(java.lang.String jsonString) { // // convert to a message // return Header.fromMessage(new Message(jsonString)); // } // // /** // * Create a new Header based on the given Message. Any missing values will // * be set to their defaults. // * // * @param m // * The Message to parse. // * @return A Header message based on the given Message. // */ // public static Header fromMessage(Message m) { // // get it from the JSON object // return Header.fromJsonObject(m.toJsonObject()); // } // // /** // * Create a new Header based on the given JSON object. Any missing values // * will be set to their defaults. // * // * @param jsonObject // * The JSON object to parse. // * @return A Header message based on the given JSON object. // */ // public static Header fromJsonObject(JsonObject jsonObject) { // // check the fields // long seq64 = jsonObject.containsKey(Header.FIELD_SEQ) ? jsonObject // .getJsonNumber(Header.FIELD_SEQ).longValue() : 0; // edu.wpi.rail.jrosbridge.primitives.Time stamp = jsonObject // .containsKey(Header.FIELD_STAMP) ? edu.wpi.rail.jrosbridge.primitives.Time // .fromJsonObject(jsonObject.getJsonObject(Header.FIELD_STAMP)) // : new edu.wpi.rail.jrosbridge.primitives.Time(); // java.lang.String frameID = jsonObject // .containsKey(Header.FIELD_FRAME_ID) ? jsonObject // .getString(Header.FIELD_FRAME_ID) : ""; // // // convert to a 32-bit number // int seq32 = Primitive.toUInt32(seq64); // return new Header(seq32, stamp, frameID); // } // }
import javax.json.Json; import javax.json.JsonObject; import edu.wpi.rail.jrosbridge.messages.Message; import edu.wpi.rail.jrosbridge.messages.std.Header;
package edu.wpi.rail.jrosbridge.messages.geometry; /** * The geometry_msgs/Vector3Stamped message. This represents a Vector3 with * reference coordinate frame and timestamp. * * @author Russell Toris -- russell.toris@gmail.com * @version April 1, 2014 */ public class Vector3Stamped extends Message { /** * The name of the header field for the message. */ public static final String FIELD_HEADER = "header"; /** * The name of the vector field for the message. */ public static final String FIELD_VECTOR = "vector"; /** * The message type. */ public static final String TYPE = "geometry_msgs/Vector3Stamped";
// Path: src/main/java/edu/wpi/rail/jrosbridge/messages/std/Header.java // public class Header extends Message { // // /** // * The name of the sequence field for the message. // */ // public static final java.lang.String FIELD_SEQ = "seq"; // // /** // * The name of the timestamp field for the message. // */ // public static final java.lang.String FIELD_STAMP = "stamp"; // // /** // * The name of the frame ID field for the message. // */ // public static final java.lang.String FIELD_FRAME_ID = "frame_id"; // // /** // * The message type. // */ // public static final java.lang.String TYPE = "std_msgs/Header"; // // private final int seq; // private final edu.wpi.rail.jrosbridge.primitives.Time stamp; // private final java.lang.String frameID; // // /** // * Create a new Header with all empty values. // */ // public Header() { // this(0, new edu.wpi.rail.jrosbridge.primitives.Time(), ""); // } // // /** // * Create a new Header with the given values. // * // * @param seq // * The sequence number treated as an unsigned 32-bit integer. // * @param stamp // * The timestamp. // * @param frameID // * The frame ID. // */ // public Header(int seq, edu.wpi.rail.jrosbridge.primitives.Time stamp, // java.lang.String frameID) { // // build the JSON object // super(Json.createObjectBuilder() // .add(Header.FIELD_SEQ, Primitive.fromUInt32(seq)) // .add(Header.FIELD_STAMP, stamp.toJsonObject()) // .add(Header.FIELD_FRAME_ID, frameID).build(), Header.TYPE); // this.seq = seq; // this.stamp = stamp; // this.frameID = frameID; // } // // /** // * Get the sequence value of this header which should be treated as an // * unsigned 32-bit integer. // * // * @return The sequence value of this header. // */ // public int getSeq() { // return this.seq; // } // // /** // * Get the timestamp value of this header. // * // * @return The timestamp value of this header. // */ // public edu.wpi.rail.jrosbridge.primitives.Time getStamp() { // return this.stamp; // } // // /** // * Get the frame ID value of this header. // * // * @return The frame ID value of this header. // */ // public java.lang.String getFrameID() { // return this.frameID; // } // // /** // * Create a clone of this Header. // */ // @Override // public Header clone() { // // time primitives are mutable, create a clone // return new Header(this.seq, this.stamp.clone(), this.frameID); // } // // /** // * Create a new Header based on the given JSON string. Any missing values // * will be set to their defaults. // * // * @param jsonString // * The JSON string to parse. // * @return A Header message based on the given JSON string. // */ // public static Header fromJsonString(java.lang.String jsonString) { // // convert to a message // return Header.fromMessage(new Message(jsonString)); // } // // /** // * Create a new Header based on the given Message. Any missing values will // * be set to their defaults. // * // * @param m // * The Message to parse. // * @return A Header message based on the given Message. // */ // public static Header fromMessage(Message m) { // // get it from the JSON object // return Header.fromJsonObject(m.toJsonObject()); // } // // /** // * Create a new Header based on the given JSON object. Any missing values // * will be set to their defaults. // * // * @param jsonObject // * The JSON object to parse. // * @return A Header message based on the given JSON object. // */ // public static Header fromJsonObject(JsonObject jsonObject) { // // check the fields // long seq64 = jsonObject.containsKey(Header.FIELD_SEQ) ? jsonObject // .getJsonNumber(Header.FIELD_SEQ).longValue() : 0; // edu.wpi.rail.jrosbridge.primitives.Time stamp = jsonObject // .containsKey(Header.FIELD_STAMP) ? edu.wpi.rail.jrosbridge.primitives.Time // .fromJsonObject(jsonObject.getJsonObject(Header.FIELD_STAMP)) // : new edu.wpi.rail.jrosbridge.primitives.Time(); // java.lang.String frameID = jsonObject // .containsKey(Header.FIELD_FRAME_ID) ? jsonObject // .getString(Header.FIELD_FRAME_ID) : ""; // // // convert to a 32-bit number // int seq32 = Primitive.toUInt32(seq64); // return new Header(seq32, stamp, frameID); // } // } // Path: src/main/java/edu/wpi/rail/jrosbridge/messages/geometry/Vector3Stamped.java import javax.json.Json; import javax.json.JsonObject; import edu.wpi.rail.jrosbridge.messages.Message; import edu.wpi.rail.jrosbridge.messages.std.Header; package edu.wpi.rail.jrosbridge.messages.geometry; /** * The geometry_msgs/Vector3Stamped message. This represents a Vector3 with * reference coordinate frame and timestamp. * * @author Russell Toris -- russell.toris@gmail.com * @version April 1, 2014 */ public class Vector3Stamped extends Message { /** * The name of the header field for the message. */ public static final String FIELD_HEADER = "header"; /** * The name of the vector field for the message. */ public static final String FIELD_VECTOR = "vector"; /** * The message type. */ public static final String TYPE = "geometry_msgs/Vector3Stamped";
private final Header header;
kihira/Tails
src/main/java/uk/kihira/tails/common/network/PlayerDataMessage.java
// Path: src/main/java/uk/kihira/tails/client/outfit/Outfit.java // public final class Outfit // { // public final UUID id; // public String name; // public String description; // public ArrayList<OutfitPart> parts; // // public Outfit() // { // id = UUID.randomUUID(); // parts = new ArrayList<>(); // } // // // todo make a client only multimap of mountpoint <-> outfitpart? // } // // Path: src/main/java/uk/kihira/tails/common/Tails.java // @Mod(Tails.MOD_ID) // public class Tails // { // public static final String MOD_ID = "tails"; // public static final Logger LOGGER = LogManager.getLogger(MOD_ID); // public static final Gson GSON = new GsonBuilder().create(); // public static final boolean DEBUG = true; // // public static boolean hasRemote; // // public static CommonProxy proxy = DistExecutor.safeRunForDist(() -> ClientProxy::new, () -> CommonProxy::new); // // public Tails() // { // FMLJavaModLoadingContext.get().getModEventBus().addListener(this::setup); // FMLJavaModLoadingContext.get().getModEventBus().addListener(this::onConfigChange); // MinecraftForge.EVENT_BUS.addListener(this::addReloadListener); // } // // private void setup(final FMLCommonSetupEvent event) // { // proxy.preInit(); // Config.loadConfig(); // // PartRegistry.loadAllPartsFromResources(); // } // // private void addReloadListener(final AddReloadListenerEvent event) // { // event.addListener((stage, resourceManager, preparationsProfiler, reloadProfiler, backgroundExecutor, gameExecutor) -> // CompletableFuture.runAsync(() -> proxy.onResourceManagerReload())); // } // // public void onConfigChange(final ModConfigEvent event) // { // if (event.getConfig().getModId().equals(Tails.MOD_ID)) // { // Config.loadConfig(); // } // } // // public static void setLocalOutfit(final Outfit outfit) // { // Config.localOutfit.set(outfit); // Config.configuration.save(); // } // }
import com.google.common.base.Strings; import com.google.gson.JsonSyntaxException; import net.minecraft.network.PacketBuffer; import net.minecraftforge.fml.network.NetworkDirection; import net.minecraftforge.fml.network.PacketDistributor; import net.minecraftforge.fml.network.NetworkEvent.Context; import uk.kihira.tails.client.outfit.Outfit; import uk.kihira.tails.common.Tails; import java.util.UUID; import java.util.function.Supplier;
package uk.kihira.tails.common.network; public final class PlayerDataMessage { private UUID uuid;
// Path: src/main/java/uk/kihira/tails/client/outfit/Outfit.java // public final class Outfit // { // public final UUID id; // public String name; // public String description; // public ArrayList<OutfitPart> parts; // // public Outfit() // { // id = UUID.randomUUID(); // parts = new ArrayList<>(); // } // // // todo make a client only multimap of mountpoint <-> outfitpart? // } // // Path: src/main/java/uk/kihira/tails/common/Tails.java // @Mod(Tails.MOD_ID) // public class Tails // { // public static final String MOD_ID = "tails"; // public static final Logger LOGGER = LogManager.getLogger(MOD_ID); // public static final Gson GSON = new GsonBuilder().create(); // public static final boolean DEBUG = true; // // public static boolean hasRemote; // // public static CommonProxy proxy = DistExecutor.safeRunForDist(() -> ClientProxy::new, () -> CommonProxy::new); // // public Tails() // { // FMLJavaModLoadingContext.get().getModEventBus().addListener(this::setup); // FMLJavaModLoadingContext.get().getModEventBus().addListener(this::onConfigChange); // MinecraftForge.EVENT_BUS.addListener(this::addReloadListener); // } // // private void setup(final FMLCommonSetupEvent event) // { // proxy.preInit(); // Config.loadConfig(); // // PartRegistry.loadAllPartsFromResources(); // } // // private void addReloadListener(final AddReloadListenerEvent event) // { // event.addListener((stage, resourceManager, preparationsProfiler, reloadProfiler, backgroundExecutor, gameExecutor) -> // CompletableFuture.runAsync(() -> proxy.onResourceManagerReload())); // } // // public void onConfigChange(final ModConfigEvent event) // { // if (event.getConfig().getModId().equals(Tails.MOD_ID)) // { // Config.loadConfig(); // } // } // // public static void setLocalOutfit(final Outfit outfit) // { // Config.localOutfit.set(outfit); // Config.configuration.save(); // } // } // Path: src/main/java/uk/kihira/tails/common/network/PlayerDataMessage.java import com.google.common.base.Strings; import com.google.gson.JsonSyntaxException; import net.minecraft.network.PacketBuffer; import net.minecraftforge.fml.network.NetworkDirection; import net.minecraftforge.fml.network.PacketDistributor; import net.minecraftforge.fml.network.NetworkEvent.Context; import uk.kihira.tails.client.outfit.Outfit; import uk.kihira.tails.common.Tails; import java.util.UUID; import java.util.function.Supplier; package uk.kihira.tails.common.network; public final class PlayerDataMessage { private UUID uuid;
private Outfit outfit;
kihira/Tails
src/main/java/uk/kihira/tails/common/network/PlayerDataMessage.java
// Path: src/main/java/uk/kihira/tails/client/outfit/Outfit.java // public final class Outfit // { // public final UUID id; // public String name; // public String description; // public ArrayList<OutfitPart> parts; // // public Outfit() // { // id = UUID.randomUUID(); // parts = new ArrayList<>(); // } // // // todo make a client only multimap of mountpoint <-> outfitpart? // } // // Path: src/main/java/uk/kihira/tails/common/Tails.java // @Mod(Tails.MOD_ID) // public class Tails // { // public static final String MOD_ID = "tails"; // public static final Logger LOGGER = LogManager.getLogger(MOD_ID); // public static final Gson GSON = new GsonBuilder().create(); // public static final boolean DEBUG = true; // // public static boolean hasRemote; // // public static CommonProxy proxy = DistExecutor.safeRunForDist(() -> ClientProxy::new, () -> CommonProxy::new); // // public Tails() // { // FMLJavaModLoadingContext.get().getModEventBus().addListener(this::setup); // FMLJavaModLoadingContext.get().getModEventBus().addListener(this::onConfigChange); // MinecraftForge.EVENT_BUS.addListener(this::addReloadListener); // } // // private void setup(final FMLCommonSetupEvent event) // { // proxy.preInit(); // Config.loadConfig(); // // PartRegistry.loadAllPartsFromResources(); // } // // private void addReloadListener(final AddReloadListenerEvent event) // { // event.addListener((stage, resourceManager, preparationsProfiler, reloadProfiler, backgroundExecutor, gameExecutor) -> // CompletableFuture.runAsync(() -> proxy.onResourceManagerReload())); // } // // public void onConfigChange(final ModConfigEvent event) // { // if (event.getConfig().getModId().equals(Tails.MOD_ID)) // { // Config.loadConfig(); // } // } // // public static void setLocalOutfit(final Outfit outfit) // { // Config.localOutfit.set(outfit); // Config.configuration.save(); // } // }
import com.google.common.base.Strings; import com.google.gson.JsonSyntaxException; import net.minecraft.network.PacketBuffer; import net.minecraftforge.fml.network.NetworkDirection; import net.minecraftforge.fml.network.PacketDistributor; import net.minecraftforge.fml.network.NetworkEvent.Context; import uk.kihira.tails.client.outfit.Outfit; import uk.kihira.tails.common.Tails; import java.util.UUID; import java.util.function.Supplier;
package uk.kihira.tails.common.network; public final class PlayerDataMessage { private UUID uuid; private Outfit outfit; private boolean shouldRemove; public PlayerDataMessage() {} public PlayerDataMessage(UUID uuid, Outfit outfit, boolean shouldRemove) { this.uuid = uuid; this.outfit = outfit; this.shouldRemove = shouldRemove; } public PlayerDataMessage(PacketBuffer buf) { this.uuid = buf.readUniqueId(); String tailInfoJson = buf.readString(); if (!Strings.isNullOrEmpty(tailInfoJson)) { try {
// Path: src/main/java/uk/kihira/tails/client/outfit/Outfit.java // public final class Outfit // { // public final UUID id; // public String name; // public String description; // public ArrayList<OutfitPart> parts; // // public Outfit() // { // id = UUID.randomUUID(); // parts = new ArrayList<>(); // } // // // todo make a client only multimap of mountpoint <-> outfitpart? // } // // Path: src/main/java/uk/kihira/tails/common/Tails.java // @Mod(Tails.MOD_ID) // public class Tails // { // public static final String MOD_ID = "tails"; // public static final Logger LOGGER = LogManager.getLogger(MOD_ID); // public static final Gson GSON = new GsonBuilder().create(); // public static final boolean DEBUG = true; // // public static boolean hasRemote; // // public static CommonProxy proxy = DistExecutor.safeRunForDist(() -> ClientProxy::new, () -> CommonProxy::new); // // public Tails() // { // FMLJavaModLoadingContext.get().getModEventBus().addListener(this::setup); // FMLJavaModLoadingContext.get().getModEventBus().addListener(this::onConfigChange); // MinecraftForge.EVENT_BUS.addListener(this::addReloadListener); // } // // private void setup(final FMLCommonSetupEvent event) // { // proxy.preInit(); // Config.loadConfig(); // // PartRegistry.loadAllPartsFromResources(); // } // // private void addReloadListener(final AddReloadListenerEvent event) // { // event.addListener((stage, resourceManager, preparationsProfiler, reloadProfiler, backgroundExecutor, gameExecutor) -> // CompletableFuture.runAsync(() -> proxy.onResourceManagerReload())); // } // // public void onConfigChange(final ModConfigEvent event) // { // if (event.getConfig().getModId().equals(Tails.MOD_ID)) // { // Config.loadConfig(); // } // } // // public static void setLocalOutfit(final Outfit outfit) // { // Config.localOutfit.set(outfit); // Config.configuration.save(); // } // } // Path: src/main/java/uk/kihira/tails/common/network/PlayerDataMessage.java import com.google.common.base.Strings; import com.google.gson.JsonSyntaxException; import net.minecraft.network.PacketBuffer; import net.minecraftforge.fml.network.NetworkDirection; import net.minecraftforge.fml.network.PacketDistributor; import net.minecraftforge.fml.network.NetworkEvent.Context; import uk.kihira.tails.client.outfit.Outfit; import uk.kihira.tails.common.Tails; import java.util.UUID; import java.util.function.Supplier; package uk.kihira.tails.common.network; public final class PlayerDataMessage { private UUID uuid; private Outfit outfit; private boolean shouldRemove; public PlayerDataMessage() {} public PlayerDataMessage(UUID uuid, Outfit outfit, boolean shouldRemove) { this.uuid = uuid; this.outfit = outfit; this.shouldRemove = shouldRemove; } public PlayerDataMessage(PacketBuffer buf) { this.uuid = buf.readUniqueId(); String tailInfoJson = buf.readString(); if (!Strings.isNullOrEmpty(tailInfoJson)) { try {
this.outfit = Tails.GSON.fromJson(tailInfoJson, Outfit.class);
kihira/Tails
src/main/java/uk/kihira/tails/common/network/ServerCapabilitiesMessage.java
// Path: src/main/java/uk/kihira/tails/common/Config.java // public final class Config // { // public static BooleanValue forceLegacyRendering; // public static BooleanValue libraryEnabled; // public static ConfigValue<Outfit> localOutfit; // // public static ForgeConfigSpec configuration; // // public static void loadConfig() // { // ForgeConfigSpec.Builder builder = new ForgeConfigSpec.Builder(); // // forceLegacyRendering = builder // .comment("Forces the legacy renderer which may have better compatibility with other mods") // .define("forceLegacyRenderer", false); // // libraryEnabled = builder // .comment("Whether to enable the library system for sharing tails. This mostly matters on servers.") // .define("enableLibrary", true); // // localOutfit = builder // .comment("Local Players outfit. Delete to remove all customisation data. Do not try to edit manually") // .define("localPlayerOutfit", new Outfit()); // // //Load default if none exists // if (localOutfit == null) // { // Tails.setLocalOutfit(new Outfit()); // } // // todo // /* try // { // localOutfit = Gson.fromJson(Tails.configuration.getString("Local Player Outfit", // Configuration.CATEGORY_GENERAL, "{}", "Local Players outfit. Delete to remove all customisation data. Do not try to edit manually"), Outfit.class); // // } catch (JsonSyntaxException e) { // Tails.configuration.getCategory(Configuration.CATEGORY_GENERAL).remove("Local Player Data"); // Tails.LOGGER.error("Failed to load local player data: Invalid JSON syntax! Invalid data being removed"); // }*/ // // configuration = builder.build(); // //configuration.save(); // } // } // // Path: src/main/java/uk/kihira/tails/common/Tails.java // @Mod(Tails.MOD_ID) // public class Tails // { // public static final String MOD_ID = "tails"; // public static final Logger LOGGER = LogManager.getLogger(MOD_ID); // public static final Gson GSON = new GsonBuilder().create(); // public static final boolean DEBUG = true; // // public static boolean hasRemote; // // public static CommonProxy proxy = DistExecutor.safeRunForDist(() -> ClientProxy::new, () -> CommonProxy::new); // // public Tails() // { // FMLJavaModLoadingContext.get().getModEventBus().addListener(this::setup); // FMLJavaModLoadingContext.get().getModEventBus().addListener(this::onConfigChange); // MinecraftForge.EVENT_BUS.addListener(this::addReloadListener); // } // // private void setup(final FMLCommonSetupEvent event) // { // proxy.preInit(); // Config.loadConfig(); // // PartRegistry.loadAllPartsFromResources(); // } // // private void addReloadListener(final AddReloadListenerEvent event) // { // event.addListener((stage, resourceManager, preparationsProfiler, reloadProfiler, backgroundExecutor, gameExecutor) -> // CompletableFuture.runAsync(() -> proxy.onResourceManagerReload())); // } // // public void onConfigChange(final ModConfigEvent event) // { // if (event.getConfig().getModId().equals(Tails.MOD_ID)) // { // Config.loadConfig(); // } // } // // public static void setLocalOutfit(final Outfit outfit) // { // Config.localOutfit.set(outfit); // Config.configuration.save(); // } // }
import java.util.function.Supplier; import net.minecraft.network.PacketBuffer; import net.minecraftforge.fml.network.NetworkEvent.Context; import uk.kihira.tails.common.Config; import uk.kihira.tails.common.Tails;
package uk.kihira.tails.common.network; public class ServerCapabilitiesMessage { private final boolean library; public ServerCapabilitiesMessage(boolean library) { this.library = library; } public ServerCapabilitiesMessage(PacketBuffer buf) { library = buf.readBoolean(); } public void encode(PacketBuffer buf) { buf.writeBoolean(library); } public void handle(Supplier<Context> ctx) {
// Path: src/main/java/uk/kihira/tails/common/Config.java // public final class Config // { // public static BooleanValue forceLegacyRendering; // public static BooleanValue libraryEnabled; // public static ConfigValue<Outfit> localOutfit; // // public static ForgeConfigSpec configuration; // // public static void loadConfig() // { // ForgeConfigSpec.Builder builder = new ForgeConfigSpec.Builder(); // // forceLegacyRendering = builder // .comment("Forces the legacy renderer which may have better compatibility with other mods") // .define("forceLegacyRenderer", false); // // libraryEnabled = builder // .comment("Whether to enable the library system for sharing tails. This mostly matters on servers.") // .define("enableLibrary", true); // // localOutfit = builder // .comment("Local Players outfit. Delete to remove all customisation data. Do not try to edit manually") // .define("localPlayerOutfit", new Outfit()); // // //Load default if none exists // if (localOutfit == null) // { // Tails.setLocalOutfit(new Outfit()); // } // // todo // /* try // { // localOutfit = Gson.fromJson(Tails.configuration.getString("Local Player Outfit", // Configuration.CATEGORY_GENERAL, "{}", "Local Players outfit. Delete to remove all customisation data. Do not try to edit manually"), Outfit.class); // // } catch (JsonSyntaxException e) { // Tails.configuration.getCategory(Configuration.CATEGORY_GENERAL).remove("Local Player Data"); // Tails.LOGGER.error("Failed to load local player data: Invalid JSON syntax! Invalid data being removed"); // }*/ // // configuration = builder.build(); // //configuration.save(); // } // } // // Path: src/main/java/uk/kihira/tails/common/Tails.java // @Mod(Tails.MOD_ID) // public class Tails // { // public static final String MOD_ID = "tails"; // public static final Logger LOGGER = LogManager.getLogger(MOD_ID); // public static final Gson GSON = new GsonBuilder().create(); // public static final boolean DEBUG = true; // // public static boolean hasRemote; // // public static CommonProxy proxy = DistExecutor.safeRunForDist(() -> ClientProxy::new, () -> CommonProxy::new); // // public Tails() // { // FMLJavaModLoadingContext.get().getModEventBus().addListener(this::setup); // FMLJavaModLoadingContext.get().getModEventBus().addListener(this::onConfigChange); // MinecraftForge.EVENT_BUS.addListener(this::addReloadListener); // } // // private void setup(final FMLCommonSetupEvent event) // { // proxy.preInit(); // Config.loadConfig(); // // PartRegistry.loadAllPartsFromResources(); // } // // private void addReloadListener(final AddReloadListenerEvent event) // { // event.addListener((stage, resourceManager, preparationsProfiler, reloadProfiler, backgroundExecutor, gameExecutor) -> // CompletableFuture.runAsync(() -> proxy.onResourceManagerReload())); // } // // public void onConfigChange(final ModConfigEvent event) // { // if (event.getConfig().getModId().equals(Tails.MOD_ID)) // { // Config.loadConfig(); // } // } // // public static void setLocalOutfit(final Outfit outfit) // { // Config.localOutfit.set(outfit); // Config.configuration.save(); // } // } // Path: src/main/java/uk/kihira/tails/common/network/ServerCapabilitiesMessage.java import java.util.function.Supplier; import net.minecraft.network.PacketBuffer; import net.minecraftforge.fml.network.NetworkEvent.Context; import uk.kihira.tails.common.Config; import uk.kihira.tails.common.Tails; package uk.kihira.tails.common.network; public class ServerCapabilitiesMessage { private final boolean library; public ServerCapabilitiesMessage(boolean library) { this.library = library; } public ServerCapabilitiesMessage(PacketBuffer buf) { library = buf.readBoolean(); } public void encode(PacketBuffer buf) { buf.writeBoolean(library); } public void handle(Supplier<Context> ctx) {
ctx.get().enqueueWork(() -> Config.libraryEnabled.set(this.library));
kihira/Tails
src/main/java/uk/kihira/tails/common/network/LibraryRequestMessage.java
// Path: src/main/java/uk/kihira/tails/common/Tails.java // @Mod(Tails.MOD_ID) // public class Tails // { // public static final String MOD_ID = "tails"; // public static final Logger LOGGER = LogManager.getLogger(MOD_ID); // public static final Gson GSON = new GsonBuilder().create(); // public static final boolean DEBUG = true; // // public static boolean hasRemote; // // public static CommonProxy proxy = DistExecutor.safeRunForDist(() -> ClientProxy::new, () -> CommonProxy::new); // // public Tails() // { // FMLJavaModLoadingContext.get().getModEventBus().addListener(this::setup); // FMLJavaModLoadingContext.get().getModEventBus().addListener(this::onConfigChange); // MinecraftForge.EVENT_BUS.addListener(this::addReloadListener); // } // // private void setup(final FMLCommonSetupEvent event) // { // proxy.preInit(); // Config.loadConfig(); // // PartRegistry.loadAllPartsFromResources(); // } // // private void addReloadListener(final AddReloadListenerEvent event) // { // event.addListener((stage, resourceManager, preparationsProfiler, reloadProfiler, backgroundExecutor, gameExecutor) -> // CompletableFuture.runAsync(() -> proxy.onResourceManagerReload())); // } // // public void onConfigChange(final ModConfigEvent event) // { // if (event.getConfig().getModId().equals(Tails.MOD_ID)) // { // Config.loadConfig(); // } // } // // public static void setLocalOutfit(final Outfit outfit) // { // Config.localOutfit.set(outfit); // Config.configuration.save(); // } // }
import java.util.function.Supplier; import net.minecraft.network.PacketBuffer; import net.minecraftforge.fml.network.NetworkEvent.Context; import uk.kihira.tails.common.Tails;
package uk.kihira.tails.common.network; // TODO Is this still needed? public class LibraryRequestMessage { public LibraryRequestMessage() {} public LibraryRequestMessage(PacketBuffer buf) {} public void encode(PacketBuffer buf) {} public void handle(Supplier<Context> ctx) { ctx.get().enqueueWork(() -> {
// Path: src/main/java/uk/kihira/tails/common/Tails.java // @Mod(Tails.MOD_ID) // public class Tails // { // public static final String MOD_ID = "tails"; // public static final Logger LOGGER = LogManager.getLogger(MOD_ID); // public static final Gson GSON = new GsonBuilder().create(); // public static final boolean DEBUG = true; // // public static boolean hasRemote; // // public static CommonProxy proxy = DistExecutor.safeRunForDist(() -> ClientProxy::new, () -> CommonProxy::new); // // public Tails() // { // FMLJavaModLoadingContext.get().getModEventBus().addListener(this::setup); // FMLJavaModLoadingContext.get().getModEventBus().addListener(this::onConfigChange); // MinecraftForge.EVENT_BUS.addListener(this::addReloadListener); // } // // private void setup(final FMLCommonSetupEvent event) // { // proxy.preInit(); // Config.loadConfig(); // // PartRegistry.loadAllPartsFromResources(); // } // // private void addReloadListener(final AddReloadListenerEvent event) // { // event.addListener((stage, resourceManager, preparationsProfiler, reloadProfiler, backgroundExecutor, gameExecutor) -> // CompletableFuture.runAsync(() -> proxy.onResourceManagerReload())); // } // // public void onConfigChange(final ModConfigEvent event) // { // if (event.getConfig().getModId().equals(Tails.MOD_ID)) // { // Config.loadConfig(); // } // } // // public static void setLocalOutfit(final Outfit outfit) // { // Config.localOutfit.set(outfit); // Config.configuration.save(); // } // } // Path: src/main/java/uk/kihira/tails/common/network/LibraryRequestMessage.java import java.util.function.Supplier; import net.minecraft.network.PacketBuffer; import net.minecraftforge.fml.network.NetworkEvent.Context; import uk.kihira.tails.common.Tails; package uk.kihira.tails.common.network; // TODO Is this still needed? public class LibraryRequestMessage { public LibraryRequestMessage() {} public LibraryRequestMessage(PacketBuffer buf) {} public void encode(PacketBuffer buf) {} public void handle(Supplier<Context> ctx) { ctx.get().enqueueWork(() -> {
TailsPacketHandler.networkWrapper.reply(new LibraryEntriesMessage(Tails.proxy.getLibraryManager().libraryEntries, false), ctx.get());
kihira/Tails
src/main/java/uk/kihira/tails/client/gui/GuiList.java
// Path: src/main/java/uk/kihira/tails/client/RenderHelper.java // public class RenderHelper // { // public static void startGlScissor(int x, int y, int width, int height) // { // // TODO // // Minecraft mc = Minecraft.getInstance(); // // ScaledResolution reso = new ScaledResolution(mc); // // // // double scaleW = (double)mc.displayWidth / reso.getScaledWidth_double(); // // double scaleH = (double)mc.displayHeight / reso.getScaledHeight_double(); // // // // GL11.glEnable(GL11.GL_SCISSOR_TEST); // // GL11.glScissor((int)Math.floor((double)x * scaleW), (int)Math.floor((double)mc.displayHeight - ((double)(y + height) * scaleH)), (int)Math.floor((double)(x + width) * scaleW) - (int)Math.floor((double)x * scaleW), (int)Math.floor((double)mc.displayHeight - ((double)y * scaleH)) - (int)Math.floor((double)mc.displayHeight - ((double)(y + height) * scaleH))); //starts from lower left corner (minecraft starts from upper left) // } // // public static void endGlScissor() // { // GL11.glDisable(GL11.GL_SCISSOR_TEST); // } // }
import com.mojang.blaze3d.matrix.MatrixStack; import net.minecraft.client.gui.widget.list.AbstractList; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import uk.kihira.tails.client.RenderHelper; import net.minecraft.client.Minecraft; import java.util.List;
package uk.kihira.tails.client.gui; @OnlyIn(Dist.CLIENT) public class GuiList<T extends AbstractList.AbstractListEntry<T>> extends AbstractList<T> { private final IListCallback<T> parent; public GuiList(IListCallback<T> parent, int width, int height, int top, int bottom, int slotHeight, List<T> entries) { super(Minecraft.getInstance(), width, height, top, bottom, slotHeight); this.parent = parent; this.x0 = -3; entries.forEach(this::addEntry); } @Override public void render(MatrixStack matrixStack, int mouseX, int mouseY, float partialTicks) {
// Path: src/main/java/uk/kihira/tails/client/RenderHelper.java // public class RenderHelper // { // public static void startGlScissor(int x, int y, int width, int height) // { // // TODO // // Minecraft mc = Minecraft.getInstance(); // // ScaledResolution reso = new ScaledResolution(mc); // // // // double scaleW = (double)mc.displayWidth / reso.getScaledWidth_double(); // // double scaleH = (double)mc.displayHeight / reso.getScaledHeight_double(); // // // // GL11.glEnable(GL11.GL_SCISSOR_TEST); // // GL11.glScissor((int)Math.floor((double)x * scaleW), (int)Math.floor((double)mc.displayHeight - ((double)(y + height) * scaleH)), (int)Math.floor((double)(x + width) * scaleW) - (int)Math.floor((double)x * scaleW), (int)Math.floor((double)mc.displayHeight - ((double)y * scaleH)) - (int)Math.floor((double)mc.displayHeight - ((double)(y + height) * scaleH))); //starts from lower left corner (minecraft starts from upper left) // } // // public static void endGlScissor() // { // GL11.glDisable(GL11.GL_SCISSOR_TEST); // } // } // Path: src/main/java/uk/kihira/tails/client/gui/GuiList.java import com.mojang.blaze3d.matrix.MatrixStack; import net.minecraft.client.gui.widget.list.AbstractList; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import uk.kihira.tails.client.RenderHelper; import net.minecraft.client.Minecraft; import java.util.List; package uk.kihira.tails.client.gui; @OnlyIn(Dist.CLIENT) public class GuiList<T extends AbstractList.AbstractListEntry<T>> extends AbstractList<T> { private final IListCallback<T> parent; public GuiList(IListCallback<T> parent, int width, int height, int top, int bottom, int slotHeight, List<T> entries) { super(Minecraft.getInstance(), width, height, top, bottom, slotHeight); this.parent = parent; this.x0 = -3; entries.forEach(this::addEntry); } @Override public void render(MatrixStack matrixStack, int mouseX, int mouseY, float partialTicks) {
RenderHelper.startGlScissor(this.x0, this.y0, this.width + 3, this.height);
kihira/Tails
src/main/java/uk/kihira/gltf/animation/Channel.java
// Path: src/main/java/uk/kihira/gltf/Node.java // public final class Node implements IDisposable // { // private Matrix4f matrix; // private boolean isStatic; // This is set to true if there is no animation (ie a matrix is present in the gltf file) // private Mesh mesh; // private final ArrayList<Node> children; // // // These must be defined if we have an animation // public Vector3f translation; // public Quaternion rotation; // public Vector3f scale; // // private Node(@Nullable ArrayList<Node> children) // { // this.matrix = new Matrix4f(); // this.children = children; // } // // Node(@Nullable ArrayList<Node> children, float[] matrix) // { // this(children); // this.isStatic = true; // this.matrix = new Matrix4f(matrix); // } // // Node(@Nullable ArrayList<Node> children, float[] translation, float[] rotation, float[] scale) // { // this(children); // this.translation = new Vector3f(translation[0], translation[1], translation[2]); // this.rotation = new Quaternion(rotation[0], rotation[1], rotation[2], rotation[3]); // this.scale = new Vector3f(scale[0], scale[1], scale[2]); // } // // public void render(MatrixStack matrixStack) // { // // Generate matrix if this is not static // if (!this.isStatic) // { // this.matrix.setIdentity(); // this.matrix.translate(this.translation); // this.matrix.mul(this.rotation); // // todo this.matrix.scale(this.scale); // } // // matrixStack.push(); // matrixStack.getLast().getMatrix().mul(matrix); // // if (mesh != null) // { // mesh.render(); // } // // if (children != null) // { // for (Node child: children) // { // child.render(matrixStack); // } // } // // matrixStack.pop(); // } // // public void setMesh(Mesh mesh) // { // this.mesh = mesh; // } // // @Override // public void dispose() // { // mesh.dispose(); // } // } // // Path: src/main/java/uk/kihira/gltf/spec/Accessor.java // public enum Type { // SCALAR(1), // VEC2(2), // VEC3(3), // VEC4(4), // MAT2(4), // MAT3(9), // MAT4(16); // // public final int size; // // Type(final int size) { // this.size = size; // } // }
import java.nio.FloatBuffer; import uk.kihira.gltf.Node; import uk.kihira.gltf.spec.Accessor.Type;
package uk.kihira.gltf.animation; public class Channel { public final Sampler sampler;
// Path: src/main/java/uk/kihira/gltf/Node.java // public final class Node implements IDisposable // { // private Matrix4f matrix; // private boolean isStatic; // This is set to true if there is no animation (ie a matrix is present in the gltf file) // private Mesh mesh; // private final ArrayList<Node> children; // // // These must be defined if we have an animation // public Vector3f translation; // public Quaternion rotation; // public Vector3f scale; // // private Node(@Nullable ArrayList<Node> children) // { // this.matrix = new Matrix4f(); // this.children = children; // } // // Node(@Nullable ArrayList<Node> children, float[] matrix) // { // this(children); // this.isStatic = true; // this.matrix = new Matrix4f(matrix); // } // // Node(@Nullable ArrayList<Node> children, float[] translation, float[] rotation, float[] scale) // { // this(children); // this.translation = new Vector3f(translation[0], translation[1], translation[2]); // this.rotation = new Quaternion(rotation[0], rotation[1], rotation[2], rotation[3]); // this.scale = new Vector3f(scale[0], scale[1], scale[2]); // } // // public void render(MatrixStack matrixStack) // { // // Generate matrix if this is not static // if (!this.isStatic) // { // this.matrix.setIdentity(); // this.matrix.translate(this.translation); // this.matrix.mul(this.rotation); // // todo this.matrix.scale(this.scale); // } // // matrixStack.push(); // matrixStack.getLast().getMatrix().mul(matrix); // // if (mesh != null) // { // mesh.render(); // } // // if (children != null) // { // for (Node child: children) // { // child.render(matrixStack); // } // } // // matrixStack.pop(); // } // // public void setMesh(Mesh mesh) // { // this.mesh = mesh; // } // // @Override // public void dispose() // { // mesh.dispose(); // } // } // // Path: src/main/java/uk/kihira/gltf/spec/Accessor.java // public enum Type { // SCALAR(1), // VEC2(2), // VEC3(3), // VEC4(4), // MAT2(4), // MAT3(9), // MAT4(16); // // public final int size; // // Type(final int size) { // this.size = size; // } // } // Path: src/main/java/uk/kihira/gltf/animation/Channel.java import java.nio.FloatBuffer; import uk.kihira.gltf.Node; import uk.kihira.gltf.spec.Accessor.Type; package uk.kihira.gltf.animation; public class Channel { public final Sampler sampler;
public final Type outputType;
kihira/Tails
src/main/java/uk/kihira/gltf/animation/Channel.java
// Path: src/main/java/uk/kihira/gltf/Node.java // public final class Node implements IDisposable // { // private Matrix4f matrix; // private boolean isStatic; // This is set to true if there is no animation (ie a matrix is present in the gltf file) // private Mesh mesh; // private final ArrayList<Node> children; // // // These must be defined if we have an animation // public Vector3f translation; // public Quaternion rotation; // public Vector3f scale; // // private Node(@Nullable ArrayList<Node> children) // { // this.matrix = new Matrix4f(); // this.children = children; // } // // Node(@Nullable ArrayList<Node> children, float[] matrix) // { // this(children); // this.isStatic = true; // this.matrix = new Matrix4f(matrix); // } // // Node(@Nullable ArrayList<Node> children, float[] translation, float[] rotation, float[] scale) // { // this(children); // this.translation = new Vector3f(translation[0], translation[1], translation[2]); // this.rotation = new Quaternion(rotation[0], rotation[1], rotation[2], rotation[3]); // this.scale = new Vector3f(scale[0], scale[1], scale[2]); // } // // public void render(MatrixStack matrixStack) // { // // Generate matrix if this is not static // if (!this.isStatic) // { // this.matrix.setIdentity(); // this.matrix.translate(this.translation); // this.matrix.mul(this.rotation); // // todo this.matrix.scale(this.scale); // } // // matrixStack.push(); // matrixStack.getLast().getMatrix().mul(matrix); // // if (mesh != null) // { // mesh.render(); // } // // if (children != null) // { // for (Node child: children) // { // child.render(matrixStack); // } // } // // matrixStack.pop(); // } // // public void setMesh(Mesh mesh) // { // this.mesh = mesh; // } // // @Override // public void dispose() // { // mesh.dispose(); // } // } // // Path: src/main/java/uk/kihira/gltf/spec/Accessor.java // public enum Type { // SCALAR(1), // VEC2(2), // VEC3(3), // VEC4(4), // MAT2(4), // MAT3(9), // MAT4(16); // // public final int size; // // Type(final int size) { // this.size = size; // } // }
import java.nio.FloatBuffer; import uk.kihira.gltf.Node; import uk.kihira.gltf.spec.Accessor.Type;
package uk.kihira.gltf.animation; public class Channel { public final Sampler sampler; public final Type outputType; public final FloatBuffer inputData; public final FloatBuffer outputData;
// Path: src/main/java/uk/kihira/gltf/Node.java // public final class Node implements IDisposable // { // private Matrix4f matrix; // private boolean isStatic; // This is set to true if there is no animation (ie a matrix is present in the gltf file) // private Mesh mesh; // private final ArrayList<Node> children; // // // These must be defined if we have an animation // public Vector3f translation; // public Quaternion rotation; // public Vector3f scale; // // private Node(@Nullable ArrayList<Node> children) // { // this.matrix = new Matrix4f(); // this.children = children; // } // // Node(@Nullable ArrayList<Node> children, float[] matrix) // { // this(children); // this.isStatic = true; // this.matrix = new Matrix4f(matrix); // } // // Node(@Nullable ArrayList<Node> children, float[] translation, float[] rotation, float[] scale) // { // this(children); // this.translation = new Vector3f(translation[0], translation[1], translation[2]); // this.rotation = new Quaternion(rotation[0], rotation[1], rotation[2], rotation[3]); // this.scale = new Vector3f(scale[0], scale[1], scale[2]); // } // // public void render(MatrixStack matrixStack) // { // // Generate matrix if this is not static // if (!this.isStatic) // { // this.matrix.setIdentity(); // this.matrix.translate(this.translation); // this.matrix.mul(this.rotation); // // todo this.matrix.scale(this.scale); // } // // matrixStack.push(); // matrixStack.getLast().getMatrix().mul(matrix); // // if (mesh != null) // { // mesh.render(); // } // // if (children != null) // { // for (Node child: children) // { // child.render(matrixStack); // } // } // // matrixStack.pop(); // } // // public void setMesh(Mesh mesh) // { // this.mesh = mesh; // } // // @Override // public void dispose() // { // mesh.dispose(); // } // } // // Path: src/main/java/uk/kihira/gltf/spec/Accessor.java // public enum Type { // SCALAR(1), // VEC2(2), // VEC3(3), // VEC4(4), // MAT2(4), // MAT3(9), // MAT4(16); // // public final int size; // // Type(final int size) { // this.size = size; // } // } // Path: src/main/java/uk/kihira/gltf/animation/Channel.java import java.nio.FloatBuffer; import uk.kihira.gltf.Node; import uk.kihira.gltf.spec.Accessor.Type; package uk.kihira.gltf.animation; public class Channel { public final Sampler sampler; public final Type outputType; public final FloatBuffer inputData; public final FloatBuffer outputData;
public final Node node;
kihira/Tails
src/main/java/uk/kihira/tails/client/gui/IOutfitPartSelected.java
// Path: src/main/java/uk/kihira/tails/client/outfit/OutfitPart.java // public class OutfitPart { // public final UUID basePart; // public MountPoint mountPoint; // public float[] mountOffset; // [x,y,z] // public float[] rotation; // [x,y,z] // public float[] scale; // [x,y,z] // public float[][] tint; // [[r,g,b],[r,g,b]] // public UUID texture; // // // Client only fields // private transient Part part; // public transient ResourceLocation textureLoc; // // public OutfitPart(Part part) { // this.basePart = part.id; // this.mountPoint = part.mountPoint; // this.mountOffset = part.mountOffset; // this.rotation = part.rotation; // this.scale = part.scale; // this.tint = part.tint; // this.texture = part.textures[0]; // // this.textureLoc = new ResourceLocation(Tails.MOD_ID, this.texture.toString()); // } // // /** // * Gets the {@link Part} that has the ID for {@link #basePart} // * @return The part // */ // @Nullable // public Part getPart() // { // if (part == null) // { // part = PartRegistry.getPart(basePart).orElse(null); // } // return part; // } // }
import uk.kihira.tails.client.outfit.OutfitPart; import javax.annotation.Nullable;
package uk.kihira.tails.client.gui; public interface IOutfitPartSelected { /** * This method is called when the player selects a part that exists on the current outfit * This can also include if the part was just added. It is guaranteed that the part is in the outfit at this stage * * @param part The part that was just selected */
// Path: src/main/java/uk/kihira/tails/client/outfit/OutfitPart.java // public class OutfitPart { // public final UUID basePart; // public MountPoint mountPoint; // public float[] mountOffset; // [x,y,z] // public float[] rotation; // [x,y,z] // public float[] scale; // [x,y,z] // public float[][] tint; // [[r,g,b],[r,g,b]] // public UUID texture; // // // Client only fields // private transient Part part; // public transient ResourceLocation textureLoc; // // public OutfitPart(Part part) { // this.basePart = part.id; // this.mountPoint = part.mountPoint; // this.mountOffset = part.mountOffset; // this.rotation = part.rotation; // this.scale = part.scale; // this.tint = part.tint; // this.texture = part.textures[0]; // // this.textureLoc = new ResourceLocation(Tails.MOD_ID, this.texture.toString()); // } // // /** // * Gets the {@link Part} that has the ID for {@link #basePart} // * @return The part // */ // @Nullable // public Part getPart() // { // if (part == null) // { // part = PartRegistry.getPart(basePart).orElse(null); // } // return part; // } // } // Path: src/main/java/uk/kihira/tails/client/gui/IOutfitPartSelected.java import uk.kihira.tails.client.outfit.OutfitPart; import javax.annotation.Nullable; package uk.kihira.tails.client.gui; public interface IOutfitPartSelected { /** * This method is called when the player selects a part that exists on the current outfit * This can also include if the part was just added. It is guaranteed that the part is in the outfit at this stage * * @param part The part that was just selected */
void OnOutfitPartSelected(@Nullable final OutfitPart part);
kihira/Tails
src/main/java/uk/kihira/tails/client/gui/controls/NumberInput.java
// Path: src/main/java/uk/kihira/tails/client/gui/GuiBaseScreen.java // @OnlyIn(Dist.CLIENT) // public abstract class GuiBaseScreen extends Screen // { // private int prevMouseX; // private int prevMouseY; // private float mouseIdleTicks; // // protected GuiBaseScreen(ITextComponent titleIn) // { // super(titleIn); // } // // @Override // public void render(MatrixStack matrixStack, int mouseX, int mouseY, float partialTicks) // { // super.render(matrixStack, mouseX, mouseY, partialTicks); // // // Tooltips // for (Widget btn : buttons) // { // if (btn instanceof ITooltip && btn.isMouseOver(mouseX, mouseY)) // { // if (prevMouseX == mouseX && prevMouseY == mouseY) mouseIdleTicks += partialTicks; // else if (mouseIdleTicks > 0f) mouseIdleTicks = 0f; // // todo drawHoveringText(((ITooltip) btn).getTooltip(mouseX, mouseY, mouseIdleTicks), mouseX, mouseY); // prevMouseX = mouseX; // prevMouseY = mouseY; // break; // } // } // } // // public static class GuiButtonToggle extends Button // { // public GuiButtonToggle(int x, int y, int width, int height, ITextComponent text, int maxTextWidth, String... tooltips) // { // super(x, y, width, height, text, (a) -> {}, (button, matrixStack, mouseX, mouseY) -> // { // if (!button.active) // { // // todo Screen.renderTooltip(matrixStack, Minecraft.getInstance().fontRenderer.trimStringToWidth(new StringTextComponent(tooltips), Math.max(this.width / 2 - 43, 170)), mouseX, mouseY); // } // }); // } // // @Override // public boolean mouseClicked(double mouseX, double mouseY, int button) // { // if (this.visible && GuiBaseScreen.isMouseOver(mouseX, mouseY, x, y, width, height)) // { // this.active = !this.active; // return true; // } // return false; // } // // // TODO // /* @Override // public void drawButtonForegroundLayer(int x, int y) // { // ArrayList<String> list = new ArrayList<>(this.tooltip); // list.add((!this.enabled ? TextFormatting.GREEN + TextFormatting.ITALIC.toString() + "Enabled" : TextFormatting.RED + TextFormatting.ITALIC.toString() + "Disabled")); // drawHoveringText(list, x, y); // }*/ // } // // public static boolean isMouseOver(double mouseX, double mouseY, double x, double y, double width, double height) // { // return mouseX >= x && mouseY >= y && mouseX < x + width && mouseY < y + height; // } // } // // Path: src/main/java/uk/kihira/tails/client/gui/IControl.java // public interface IControl<V> { // // void setValue(V newValue); // // V getValue(); // } // // Path: src/main/java/uk/kihira/tails/client/gui/IControlCallback.java // public interface IControlCallback<T extends IControl<V>, V> { // // boolean onValueChange(T slider, V oldValue, V newValue); // } // // Path: src/main/java/uk/kihira/tails/client/gui/ITooltip.java // @Nonnull // public interface ITooltip { // List<String> getTooltip(int mouseX, int mouseY, float mouseIdleTime); // }
import com.google.common.base.Strings; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.widget.TextFieldWidget; import net.minecraft.client.gui.widget.Widget; import net.minecraft.util.math.MathHelper; import net.minecraft.util.text.StringTextComponent; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import uk.kihira.tails.client.gui.GuiBaseScreen; import uk.kihira.tails.client.gui.IControl; import uk.kihira.tails.client.gui.IControlCallback; import uk.kihira.tails.client.gui.ITooltip; import javax.annotation.Nullable; import java.math.RoundingMode; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.List;
package uk.kihira.tails.client.gui.controls; // todo tooltips only work for guibuttons @OnlyIn(Dist.CLIENT) public class NumberInput extends Widget implements IControl<Float>, ITooltip { private static final char[] VALID_CHARS = new char[]{'-', '.', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0'}; private static final float SHIFT_MOD = 10f; private static final float CTRL_MOD = 0.1f; private final int xPos; private final int yPos; private final float min; private final float max; private final float increment; private final int btnWidth = 10; private final int btnXPos; private final int btnHeight; private final DecimalFormat df = new DecimalFormat("###.##"); private final TextFieldWidget numInput; private float num = 0f;
// Path: src/main/java/uk/kihira/tails/client/gui/GuiBaseScreen.java // @OnlyIn(Dist.CLIENT) // public abstract class GuiBaseScreen extends Screen // { // private int prevMouseX; // private int prevMouseY; // private float mouseIdleTicks; // // protected GuiBaseScreen(ITextComponent titleIn) // { // super(titleIn); // } // // @Override // public void render(MatrixStack matrixStack, int mouseX, int mouseY, float partialTicks) // { // super.render(matrixStack, mouseX, mouseY, partialTicks); // // // Tooltips // for (Widget btn : buttons) // { // if (btn instanceof ITooltip && btn.isMouseOver(mouseX, mouseY)) // { // if (prevMouseX == mouseX && prevMouseY == mouseY) mouseIdleTicks += partialTicks; // else if (mouseIdleTicks > 0f) mouseIdleTicks = 0f; // // todo drawHoveringText(((ITooltip) btn).getTooltip(mouseX, mouseY, mouseIdleTicks), mouseX, mouseY); // prevMouseX = mouseX; // prevMouseY = mouseY; // break; // } // } // } // // public static class GuiButtonToggle extends Button // { // public GuiButtonToggle(int x, int y, int width, int height, ITextComponent text, int maxTextWidth, String... tooltips) // { // super(x, y, width, height, text, (a) -> {}, (button, matrixStack, mouseX, mouseY) -> // { // if (!button.active) // { // // todo Screen.renderTooltip(matrixStack, Minecraft.getInstance().fontRenderer.trimStringToWidth(new StringTextComponent(tooltips), Math.max(this.width / 2 - 43, 170)), mouseX, mouseY); // } // }); // } // // @Override // public boolean mouseClicked(double mouseX, double mouseY, int button) // { // if (this.visible && GuiBaseScreen.isMouseOver(mouseX, mouseY, x, y, width, height)) // { // this.active = !this.active; // return true; // } // return false; // } // // // TODO // /* @Override // public void drawButtonForegroundLayer(int x, int y) // { // ArrayList<String> list = new ArrayList<>(this.tooltip); // list.add((!this.enabled ? TextFormatting.GREEN + TextFormatting.ITALIC.toString() + "Enabled" : TextFormatting.RED + TextFormatting.ITALIC.toString() + "Disabled")); // drawHoveringText(list, x, y); // }*/ // } // // public static boolean isMouseOver(double mouseX, double mouseY, double x, double y, double width, double height) // { // return mouseX >= x && mouseY >= y && mouseX < x + width && mouseY < y + height; // } // } // // Path: src/main/java/uk/kihira/tails/client/gui/IControl.java // public interface IControl<V> { // // void setValue(V newValue); // // V getValue(); // } // // Path: src/main/java/uk/kihira/tails/client/gui/IControlCallback.java // public interface IControlCallback<T extends IControl<V>, V> { // // boolean onValueChange(T slider, V oldValue, V newValue); // } // // Path: src/main/java/uk/kihira/tails/client/gui/ITooltip.java // @Nonnull // public interface ITooltip { // List<String> getTooltip(int mouseX, int mouseY, float mouseIdleTime); // } // Path: src/main/java/uk/kihira/tails/client/gui/controls/NumberInput.java import com.google.common.base.Strings; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.widget.TextFieldWidget; import net.minecraft.client.gui.widget.Widget; import net.minecraft.util.math.MathHelper; import net.minecraft.util.text.StringTextComponent; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import uk.kihira.tails.client.gui.GuiBaseScreen; import uk.kihira.tails.client.gui.IControl; import uk.kihira.tails.client.gui.IControlCallback; import uk.kihira.tails.client.gui.ITooltip; import javax.annotation.Nullable; import java.math.RoundingMode; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.List; package uk.kihira.tails.client.gui.controls; // todo tooltips only work for guibuttons @OnlyIn(Dist.CLIENT) public class NumberInput extends Widget implements IControl<Float>, ITooltip { private static final char[] VALID_CHARS = new char[]{'-', '.', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0'}; private static final float SHIFT_MOD = 10f; private static final float CTRL_MOD = 0.1f; private final int xPos; private final int yPos; private final float min; private final float max; private final float increment; private final int btnWidth = 10; private final int btnXPos; private final int btnHeight; private final DecimalFormat df = new DecimalFormat("###.##"); private final TextFieldWidget numInput; private float num = 0f;
private IControlCallback<IControl<Float>, Float> callback;
kihira/Tails
src/main/java/uk/kihira/tails/client/gui/controls/NumberInput.java
// Path: src/main/java/uk/kihira/tails/client/gui/GuiBaseScreen.java // @OnlyIn(Dist.CLIENT) // public abstract class GuiBaseScreen extends Screen // { // private int prevMouseX; // private int prevMouseY; // private float mouseIdleTicks; // // protected GuiBaseScreen(ITextComponent titleIn) // { // super(titleIn); // } // // @Override // public void render(MatrixStack matrixStack, int mouseX, int mouseY, float partialTicks) // { // super.render(matrixStack, mouseX, mouseY, partialTicks); // // // Tooltips // for (Widget btn : buttons) // { // if (btn instanceof ITooltip && btn.isMouseOver(mouseX, mouseY)) // { // if (prevMouseX == mouseX && prevMouseY == mouseY) mouseIdleTicks += partialTicks; // else if (mouseIdleTicks > 0f) mouseIdleTicks = 0f; // // todo drawHoveringText(((ITooltip) btn).getTooltip(mouseX, mouseY, mouseIdleTicks), mouseX, mouseY); // prevMouseX = mouseX; // prevMouseY = mouseY; // break; // } // } // } // // public static class GuiButtonToggle extends Button // { // public GuiButtonToggle(int x, int y, int width, int height, ITextComponent text, int maxTextWidth, String... tooltips) // { // super(x, y, width, height, text, (a) -> {}, (button, matrixStack, mouseX, mouseY) -> // { // if (!button.active) // { // // todo Screen.renderTooltip(matrixStack, Minecraft.getInstance().fontRenderer.trimStringToWidth(new StringTextComponent(tooltips), Math.max(this.width / 2 - 43, 170)), mouseX, mouseY); // } // }); // } // // @Override // public boolean mouseClicked(double mouseX, double mouseY, int button) // { // if (this.visible && GuiBaseScreen.isMouseOver(mouseX, mouseY, x, y, width, height)) // { // this.active = !this.active; // return true; // } // return false; // } // // // TODO // /* @Override // public void drawButtonForegroundLayer(int x, int y) // { // ArrayList<String> list = new ArrayList<>(this.tooltip); // list.add((!this.enabled ? TextFormatting.GREEN + TextFormatting.ITALIC.toString() + "Enabled" : TextFormatting.RED + TextFormatting.ITALIC.toString() + "Disabled")); // drawHoveringText(list, x, y); // }*/ // } // // public static boolean isMouseOver(double mouseX, double mouseY, double x, double y, double width, double height) // { // return mouseX >= x && mouseY >= y && mouseX < x + width && mouseY < y + height; // } // } // // Path: src/main/java/uk/kihira/tails/client/gui/IControl.java // public interface IControl<V> { // // void setValue(V newValue); // // V getValue(); // } // // Path: src/main/java/uk/kihira/tails/client/gui/IControlCallback.java // public interface IControlCallback<T extends IControl<V>, V> { // // boolean onValueChange(T slider, V oldValue, V newValue); // } // // Path: src/main/java/uk/kihira/tails/client/gui/ITooltip.java // @Nonnull // public interface ITooltip { // List<String> getTooltip(int mouseX, int mouseY, float mouseIdleTime); // }
import com.google.common.base.Strings; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.widget.TextFieldWidget; import net.minecraft.client.gui.widget.Widget; import net.minecraft.util.math.MathHelper; import net.minecraft.util.text.StringTextComponent; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import uk.kihira.tails.client.gui.GuiBaseScreen; import uk.kihira.tails.client.gui.IControl; import uk.kihira.tails.client.gui.IControlCallback; import uk.kihira.tails.client.gui.ITooltip; import javax.annotation.Nullable; import java.math.RoundingMode; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.List;
this.btnXPos = xPos + numInput.getWidth() + 2; this.btnHeight = height / 2; } public void draw(int mouseX, int mouseY) { // todo //numInput.drawTextBox(); //drawRect(btnXPos, yPos, btnXPos + btnWidth, yPos + btnHeight, 0xFFFFFFFF); // Increment //drawRect(btnXPos, yPos + btnHeight, btnXPos + btnWidth, yPos + height, 0xAAAAAAFF); // Decrement } public void mouseClicked(int mouseX, int mouseY, int mouseButton) { boolean focused = numInput.isFocused(); numInput.mouseClicked(mouseX, mouseY, mouseButton); // Only update num when input loses focus if (focused && !numInput.isFocused()) { if (!Strings.isNullOrEmpty(numInput.getText())) setValue(Float.valueOf(numInput.getText())); else setValue(0f); numInput.setCursorPosition(0); } float inc = increment; // todo // if (Keyboard.isKeyDown(Keyboard.KEY_LSHIFT)) inc *= SHIFT_MOD; // else if (Keyboard.isKeyDown(Keyboard.KEY_LCONTROL)) inc *= CTRL_MOD; // Increase
// Path: src/main/java/uk/kihira/tails/client/gui/GuiBaseScreen.java // @OnlyIn(Dist.CLIENT) // public abstract class GuiBaseScreen extends Screen // { // private int prevMouseX; // private int prevMouseY; // private float mouseIdleTicks; // // protected GuiBaseScreen(ITextComponent titleIn) // { // super(titleIn); // } // // @Override // public void render(MatrixStack matrixStack, int mouseX, int mouseY, float partialTicks) // { // super.render(matrixStack, mouseX, mouseY, partialTicks); // // // Tooltips // for (Widget btn : buttons) // { // if (btn instanceof ITooltip && btn.isMouseOver(mouseX, mouseY)) // { // if (prevMouseX == mouseX && prevMouseY == mouseY) mouseIdleTicks += partialTicks; // else if (mouseIdleTicks > 0f) mouseIdleTicks = 0f; // // todo drawHoveringText(((ITooltip) btn).getTooltip(mouseX, mouseY, mouseIdleTicks), mouseX, mouseY); // prevMouseX = mouseX; // prevMouseY = mouseY; // break; // } // } // } // // public static class GuiButtonToggle extends Button // { // public GuiButtonToggle(int x, int y, int width, int height, ITextComponent text, int maxTextWidth, String... tooltips) // { // super(x, y, width, height, text, (a) -> {}, (button, matrixStack, mouseX, mouseY) -> // { // if (!button.active) // { // // todo Screen.renderTooltip(matrixStack, Minecraft.getInstance().fontRenderer.trimStringToWidth(new StringTextComponent(tooltips), Math.max(this.width / 2 - 43, 170)), mouseX, mouseY); // } // }); // } // // @Override // public boolean mouseClicked(double mouseX, double mouseY, int button) // { // if (this.visible && GuiBaseScreen.isMouseOver(mouseX, mouseY, x, y, width, height)) // { // this.active = !this.active; // return true; // } // return false; // } // // // TODO // /* @Override // public void drawButtonForegroundLayer(int x, int y) // { // ArrayList<String> list = new ArrayList<>(this.tooltip); // list.add((!this.enabled ? TextFormatting.GREEN + TextFormatting.ITALIC.toString() + "Enabled" : TextFormatting.RED + TextFormatting.ITALIC.toString() + "Disabled")); // drawHoveringText(list, x, y); // }*/ // } // // public static boolean isMouseOver(double mouseX, double mouseY, double x, double y, double width, double height) // { // return mouseX >= x && mouseY >= y && mouseX < x + width && mouseY < y + height; // } // } // // Path: src/main/java/uk/kihira/tails/client/gui/IControl.java // public interface IControl<V> { // // void setValue(V newValue); // // V getValue(); // } // // Path: src/main/java/uk/kihira/tails/client/gui/IControlCallback.java // public interface IControlCallback<T extends IControl<V>, V> { // // boolean onValueChange(T slider, V oldValue, V newValue); // } // // Path: src/main/java/uk/kihira/tails/client/gui/ITooltip.java // @Nonnull // public interface ITooltip { // List<String> getTooltip(int mouseX, int mouseY, float mouseIdleTime); // } // Path: src/main/java/uk/kihira/tails/client/gui/controls/NumberInput.java import com.google.common.base.Strings; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.widget.TextFieldWidget; import net.minecraft.client.gui.widget.Widget; import net.minecraft.util.math.MathHelper; import net.minecraft.util.text.StringTextComponent; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import uk.kihira.tails.client.gui.GuiBaseScreen; import uk.kihira.tails.client.gui.IControl; import uk.kihira.tails.client.gui.IControlCallback; import uk.kihira.tails.client.gui.ITooltip; import javax.annotation.Nullable; import java.math.RoundingMode; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.List; this.btnXPos = xPos + numInput.getWidth() + 2; this.btnHeight = height / 2; } public void draw(int mouseX, int mouseY) { // todo //numInput.drawTextBox(); //drawRect(btnXPos, yPos, btnXPos + btnWidth, yPos + btnHeight, 0xFFFFFFFF); // Increment //drawRect(btnXPos, yPos + btnHeight, btnXPos + btnWidth, yPos + height, 0xAAAAAAFF); // Decrement } public void mouseClicked(int mouseX, int mouseY, int mouseButton) { boolean focused = numInput.isFocused(); numInput.mouseClicked(mouseX, mouseY, mouseButton); // Only update num when input loses focus if (focused && !numInput.isFocused()) { if (!Strings.isNullOrEmpty(numInput.getText())) setValue(Float.valueOf(numInput.getText())); else setValue(0f); numInput.setCursorPosition(0); } float inc = increment; // todo // if (Keyboard.isKeyDown(Keyboard.KEY_LSHIFT)) inc *= SHIFT_MOD; // else if (Keyboard.isKeyDown(Keyboard.KEY_LCONTROL)) inc *= CTRL_MOD; // Increase
if (GuiBaseScreen.isMouseOver(mouseX, mouseY, xPos + numInput.getWidth(), yPos, btnWidth, btnHeight)) {
kihira/Tails
src/main/java/uk/kihira/tails/client/gui/IconButton.java
// Path: src/main/java/uk/kihira/tails/common/Tails.java // @Mod(Tails.MOD_ID) // public class Tails // { // public static final String MOD_ID = "tails"; // public static final Logger LOGGER = LogManager.getLogger(MOD_ID); // public static final Gson GSON = new GsonBuilder().create(); // public static final boolean DEBUG = true; // // public static boolean hasRemote; // // public static CommonProxy proxy = DistExecutor.safeRunForDist(() -> ClientProxy::new, () -> CommonProxy::new); // // public Tails() // { // FMLJavaModLoadingContext.get().getModEventBus().addListener(this::setup); // FMLJavaModLoadingContext.get().getModEventBus().addListener(this::onConfigChange); // MinecraftForge.EVENT_BUS.addListener(this::addReloadListener); // } // // private void setup(final FMLCommonSetupEvent event) // { // proxy.preInit(); // Config.loadConfig(); // // PartRegistry.loadAllPartsFromResources(); // } // // private void addReloadListener(final AddReloadListenerEvent event) // { // event.addListener((stage, resourceManager, preparationsProfiler, reloadProfiler, backgroundExecutor, gameExecutor) -> // CompletableFuture.runAsync(() -> proxy.onResourceManagerReload())); // } // // public void onConfigChange(final ModConfigEvent event) // { // if (event.getConfig().getModId().equals(Tails.MOD_ID)) // { // Config.loadConfig(); // } // } // // public static void setLocalOutfit(final Outfit outfit) // { // Config.localOutfit.set(outfit); // Config.configuration.save(); // } // }
import com.mojang.blaze3d.matrix.MatrixStack; import com.mojang.blaze3d.platform.GlStateManager; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.widget.button.Button; import net.minecraft.util.ResourceLocation; import net.minecraft.util.text.StringTextComponent; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.fml.client.gui.GuiUtils; import org.lwjgl.opengl.GL11; import uk.kihira.tails.common.Tails; import java.util.Arrays; import java.util.List;
package uk.kihira.tails.client.gui; @OnlyIn(Dist.CLIENT) public class IconButton extends Button {
// Path: src/main/java/uk/kihira/tails/common/Tails.java // @Mod(Tails.MOD_ID) // public class Tails // { // public static final String MOD_ID = "tails"; // public static final Logger LOGGER = LogManager.getLogger(MOD_ID); // public static final Gson GSON = new GsonBuilder().create(); // public static final boolean DEBUG = true; // // public static boolean hasRemote; // // public static CommonProxy proxy = DistExecutor.safeRunForDist(() -> ClientProxy::new, () -> CommonProxy::new); // // public Tails() // { // FMLJavaModLoadingContext.get().getModEventBus().addListener(this::setup); // FMLJavaModLoadingContext.get().getModEventBus().addListener(this::onConfigChange); // MinecraftForge.EVENT_BUS.addListener(this::addReloadListener); // } // // private void setup(final FMLCommonSetupEvent event) // { // proxy.preInit(); // Config.loadConfig(); // // PartRegistry.loadAllPartsFromResources(); // } // // private void addReloadListener(final AddReloadListenerEvent event) // { // event.addListener((stage, resourceManager, preparationsProfiler, reloadProfiler, backgroundExecutor, gameExecutor) -> // CompletableFuture.runAsync(() -> proxy.onResourceManagerReload())); // } // // public void onConfigChange(final ModConfigEvent event) // { // if (event.getConfig().getModId().equals(Tails.MOD_ID)) // { // Config.loadConfig(); // } // } // // public static void setLocalOutfit(final Outfit outfit) // { // Config.localOutfit.set(outfit); // Config.configuration.save(); // } // } // Path: src/main/java/uk/kihira/tails/client/gui/IconButton.java import com.mojang.blaze3d.matrix.MatrixStack; import com.mojang.blaze3d.platform.GlStateManager; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.widget.button.Button; import net.minecraft.util.ResourceLocation; import net.minecraft.util.text.StringTextComponent; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.fml.client.gui.GuiUtils; import org.lwjgl.opengl.GL11; import uk.kihira.tails.common.Tails; import java.util.Arrays; import java.util.List; package uk.kihira.tails.client.gui; @OnlyIn(Dist.CLIENT) public class IconButton extends Button {
static final ResourceLocation ICONS_TEXTURES = new ResourceLocation(Tails.MOD_ID, "texture/gui/icons.png");
kihira/Tails
src/main/java/uk/kihira/tails/client/gui/LibraryPanel.java
// Path: src/main/java/uk/kihira/tails/common/LibraryEntryData.java // public class LibraryEntryData { // @Expose public final Outfit outfit; // @Expose public String entryName = ""; // @Expose public final String comment = ""; // @Expose public boolean favourite; // @Expose public final long creationDate; // @Expose public final UUID creatorUUID; // /** // * Name is used purely for display purposes. // */ // @Expose public String creatorName; // public boolean remoteEntry = false; // // public LibraryEntryData(UUID creatorUUID, String creatorName, String name, Outfit outfit) { // this.entryName = name; // this.outfit = outfit; // this.creationDate = Calendar.getInstance().getTimeInMillis(); // this.creatorUUID = creatorUUID; // this.creatorName = creatorName; // } // // @SuppressWarnings("RedundantIfStatement") // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // LibraryEntryData data = (LibraryEntryData) o; // // if (creationDate != data.creationDate) return false; // if (favourite != data.favourite) return false; // if (!comment.equals(data.comment)) return false; // if (!creatorUUID.equals(data.creatorUUID)) return false; // if (entryName != null ? !entryName.equals(data.entryName) : data.entryName != null) return false; // if (outfit != null ? !outfit.equals(data.outfit) : data.outfit != null) return false; // // return true; // } // // @Override // public int hashCode() { // int result = outfit != null ? outfit.hashCode() : 0; // result = 31 * result + (entryName != null ? entryName.hashCode() : 0); // result = 31 * result + comment.hashCode(); // result = 31 * result + creatorUUID.hashCode(); // result = 31 * result + (favourite ? 1 : 0); // result = 31 * result + (int) (creationDate ^ (creationDate >>> 32)); // return result; // } // } // // Path: src/main/java/uk/kihira/tails/common/Tails.java // @Mod(Tails.MOD_ID) // public class Tails // { // public static final String MOD_ID = "tails"; // public static final Logger LOGGER = LogManager.getLogger(MOD_ID); // public static final Gson GSON = new GsonBuilder().create(); // public static final boolean DEBUG = true; // // public static boolean hasRemote; // // public static CommonProxy proxy = DistExecutor.safeRunForDist(() -> ClientProxy::new, () -> CommonProxy::new); // // public Tails() // { // FMLJavaModLoadingContext.get().getModEventBus().addListener(this::setup); // FMLJavaModLoadingContext.get().getModEventBus().addListener(this::onConfigChange); // MinecraftForge.EVENT_BUS.addListener(this::addReloadListener); // } // // private void setup(final FMLCommonSetupEvent event) // { // proxy.preInit(); // Config.loadConfig(); // // PartRegistry.loadAllPartsFromResources(); // } // // private void addReloadListener(final AddReloadListenerEvent event) // { // event.addListener((stage, resourceManager, preparationsProfiler, reloadProfiler, backgroundExecutor, gameExecutor) -> // CompletableFuture.runAsync(() -> proxy.onResourceManagerReload())); // } // // public void onConfigChange(final ModConfigEvent event) // { // if (event.getConfig().getModId().equals(Tails.MOD_ID)) // { // Config.loadConfig(); // } // } // // public static void setLocalOutfit(final Outfit outfit) // { // Config.localOutfit.set(outfit); // Config.configuration.save(); // } // }
import com.mojang.blaze3d.matrix.MatrixStack; import com.mojang.blaze3d.platform.GlStateManager; import net.minecraft.client.gui.widget.TextFieldWidget; import net.minecraft.client.gui.widget.button.Button; import net.minecraft.util.text.StringTextComponent; import net.minecraft.util.text.TranslationTextComponent; import net.minecraftforge.fml.client.gui.GuiUtils; import net.minecraftforge.fml.client.gui.widget.ExtendedButton; import uk.kihira.tails.common.LibraryEntryData; import uk.kihira.tails.common.Tails; import net.minecraft.client.Minecraft; import net.minecraft.client.resources.I18n; import java.io.IOException; import java.util.ArrayList; import java.util.Comparator; import java.util.List;
@Override public boolean charTyped(char codePoint, int modifiers) { this.searchField.charTyped(codePoint, codePoint); if (this.searchField.getVisible() && this.searchField.isFocused()) { List<LibraryListEntry> newEntries = filterListEntries(this.searchField.getText().toLowerCase()); newEntries.add(0, new LibraryListEntry.NewLibraryListEntry(this, null)); // todo ///this.list.getEntries().clear(); //this.list.getEntries().addAll(newEntries); } return super.charTyped(codePoint, modifiers); } @Override public boolean onEntrySelected(GuiList<LibraryListEntry> guiList, int index, LibraryListEntry entry) { if (!(entry instanceof LibraryListEntry.NewLibraryListEntry)) { this.parent.libraryInfoPanel.setEntry(entry); this.parent.setOutfit(entry.data.outfit); } return true; } public void initList() { List<LibraryListEntry> libraryEntries = new ArrayList<>();
// Path: src/main/java/uk/kihira/tails/common/LibraryEntryData.java // public class LibraryEntryData { // @Expose public final Outfit outfit; // @Expose public String entryName = ""; // @Expose public final String comment = ""; // @Expose public boolean favourite; // @Expose public final long creationDate; // @Expose public final UUID creatorUUID; // /** // * Name is used purely for display purposes. // */ // @Expose public String creatorName; // public boolean remoteEntry = false; // // public LibraryEntryData(UUID creatorUUID, String creatorName, String name, Outfit outfit) { // this.entryName = name; // this.outfit = outfit; // this.creationDate = Calendar.getInstance().getTimeInMillis(); // this.creatorUUID = creatorUUID; // this.creatorName = creatorName; // } // // @SuppressWarnings("RedundantIfStatement") // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // LibraryEntryData data = (LibraryEntryData) o; // // if (creationDate != data.creationDate) return false; // if (favourite != data.favourite) return false; // if (!comment.equals(data.comment)) return false; // if (!creatorUUID.equals(data.creatorUUID)) return false; // if (entryName != null ? !entryName.equals(data.entryName) : data.entryName != null) return false; // if (outfit != null ? !outfit.equals(data.outfit) : data.outfit != null) return false; // // return true; // } // // @Override // public int hashCode() { // int result = outfit != null ? outfit.hashCode() : 0; // result = 31 * result + (entryName != null ? entryName.hashCode() : 0); // result = 31 * result + comment.hashCode(); // result = 31 * result + creatorUUID.hashCode(); // result = 31 * result + (favourite ? 1 : 0); // result = 31 * result + (int) (creationDate ^ (creationDate >>> 32)); // return result; // } // } // // Path: src/main/java/uk/kihira/tails/common/Tails.java // @Mod(Tails.MOD_ID) // public class Tails // { // public static final String MOD_ID = "tails"; // public static final Logger LOGGER = LogManager.getLogger(MOD_ID); // public static final Gson GSON = new GsonBuilder().create(); // public static final boolean DEBUG = true; // // public static boolean hasRemote; // // public static CommonProxy proxy = DistExecutor.safeRunForDist(() -> ClientProxy::new, () -> CommonProxy::new); // // public Tails() // { // FMLJavaModLoadingContext.get().getModEventBus().addListener(this::setup); // FMLJavaModLoadingContext.get().getModEventBus().addListener(this::onConfigChange); // MinecraftForge.EVENT_BUS.addListener(this::addReloadListener); // } // // private void setup(final FMLCommonSetupEvent event) // { // proxy.preInit(); // Config.loadConfig(); // // PartRegistry.loadAllPartsFromResources(); // } // // private void addReloadListener(final AddReloadListenerEvent event) // { // event.addListener((stage, resourceManager, preparationsProfiler, reloadProfiler, backgroundExecutor, gameExecutor) -> // CompletableFuture.runAsync(() -> proxy.onResourceManagerReload())); // } // // public void onConfigChange(final ModConfigEvent event) // { // if (event.getConfig().getModId().equals(Tails.MOD_ID)) // { // Config.loadConfig(); // } // } // // public static void setLocalOutfit(final Outfit outfit) // { // Config.localOutfit.set(outfit); // Config.configuration.save(); // } // } // Path: src/main/java/uk/kihira/tails/client/gui/LibraryPanel.java import com.mojang.blaze3d.matrix.MatrixStack; import com.mojang.blaze3d.platform.GlStateManager; import net.minecraft.client.gui.widget.TextFieldWidget; import net.minecraft.client.gui.widget.button.Button; import net.minecraft.util.text.StringTextComponent; import net.minecraft.util.text.TranslationTextComponent; import net.minecraftforge.fml.client.gui.GuiUtils; import net.minecraftforge.fml.client.gui.widget.ExtendedButton; import uk.kihira.tails.common.LibraryEntryData; import uk.kihira.tails.common.Tails; import net.minecraft.client.Minecraft; import net.minecraft.client.resources.I18n; import java.io.IOException; import java.util.ArrayList; import java.util.Comparator; import java.util.List; @Override public boolean charTyped(char codePoint, int modifiers) { this.searchField.charTyped(codePoint, codePoint); if (this.searchField.getVisible() && this.searchField.isFocused()) { List<LibraryListEntry> newEntries = filterListEntries(this.searchField.getText().toLowerCase()); newEntries.add(0, new LibraryListEntry.NewLibraryListEntry(this, null)); // todo ///this.list.getEntries().clear(); //this.list.getEntries().addAll(newEntries); } return super.charTyped(codePoint, modifiers); } @Override public boolean onEntrySelected(GuiList<LibraryListEntry> guiList, int index, LibraryListEntry entry) { if (!(entry instanceof LibraryListEntry.NewLibraryListEntry)) { this.parent.libraryInfoPanel.setEntry(entry); this.parent.setOutfit(entry.data.outfit); } return true; } public void initList() { List<LibraryListEntry> libraryEntries = new ArrayList<>();
for (LibraryEntryData data : Tails.proxy.getLibraryManager().libraryEntries)
kihira/Tails
src/main/java/uk/kihira/tails/client/gui/LibraryPanel.java
// Path: src/main/java/uk/kihira/tails/common/LibraryEntryData.java // public class LibraryEntryData { // @Expose public final Outfit outfit; // @Expose public String entryName = ""; // @Expose public final String comment = ""; // @Expose public boolean favourite; // @Expose public final long creationDate; // @Expose public final UUID creatorUUID; // /** // * Name is used purely for display purposes. // */ // @Expose public String creatorName; // public boolean remoteEntry = false; // // public LibraryEntryData(UUID creatorUUID, String creatorName, String name, Outfit outfit) { // this.entryName = name; // this.outfit = outfit; // this.creationDate = Calendar.getInstance().getTimeInMillis(); // this.creatorUUID = creatorUUID; // this.creatorName = creatorName; // } // // @SuppressWarnings("RedundantIfStatement") // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // LibraryEntryData data = (LibraryEntryData) o; // // if (creationDate != data.creationDate) return false; // if (favourite != data.favourite) return false; // if (!comment.equals(data.comment)) return false; // if (!creatorUUID.equals(data.creatorUUID)) return false; // if (entryName != null ? !entryName.equals(data.entryName) : data.entryName != null) return false; // if (outfit != null ? !outfit.equals(data.outfit) : data.outfit != null) return false; // // return true; // } // // @Override // public int hashCode() { // int result = outfit != null ? outfit.hashCode() : 0; // result = 31 * result + (entryName != null ? entryName.hashCode() : 0); // result = 31 * result + comment.hashCode(); // result = 31 * result + creatorUUID.hashCode(); // result = 31 * result + (favourite ? 1 : 0); // result = 31 * result + (int) (creationDate ^ (creationDate >>> 32)); // return result; // } // } // // Path: src/main/java/uk/kihira/tails/common/Tails.java // @Mod(Tails.MOD_ID) // public class Tails // { // public static final String MOD_ID = "tails"; // public static final Logger LOGGER = LogManager.getLogger(MOD_ID); // public static final Gson GSON = new GsonBuilder().create(); // public static final boolean DEBUG = true; // // public static boolean hasRemote; // // public static CommonProxy proxy = DistExecutor.safeRunForDist(() -> ClientProxy::new, () -> CommonProxy::new); // // public Tails() // { // FMLJavaModLoadingContext.get().getModEventBus().addListener(this::setup); // FMLJavaModLoadingContext.get().getModEventBus().addListener(this::onConfigChange); // MinecraftForge.EVENT_BUS.addListener(this::addReloadListener); // } // // private void setup(final FMLCommonSetupEvent event) // { // proxy.preInit(); // Config.loadConfig(); // // PartRegistry.loadAllPartsFromResources(); // } // // private void addReloadListener(final AddReloadListenerEvent event) // { // event.addListener((stage, resourceManager, preparationsProfiler, reloadProfiler, backgroundExecutor, gameExecutor) -> // CompletableFuture.runAsync(() -> proxy.onResourceManagerReload())); // } // // public void onConfigChange(final ModConfigEvent event) // { // if (event.getConfig().getModId().equals(Tails.MOD_ID)) // { // Config.loadConfig(); // } // } // // public static void setLocalOutfit(final Outfit outfit) // { // Config.localOutfit.set(outfit); // Config.configuration.save(); // } // }
import com.mojang.blaze3d.matrix.MatrixStack; import com.mojang.blaze3d.platform.GlStateManager; import net.minecraft.client.gui.widget.TextFieldWidget; import net.minecraft.client.gui.widget.button.Button; import net.minecraft.util.text.StringTextComponent; import net.minecraft.util.text.TranslationTextComponent; import net.minecraftforge.fml.client.gui.GuiUtils; import net.minecraftforge.fml.client.gui.widget.ExtendedButton; import uk.kihira.tails.common.LibraryEntryData; import uk.kihira.tails.common.Tails; import net.minecraft.client.Minecraft; import net.minecraft.client.resources.I18n; import java.io.IOException; import java.util.ArrayList; import java.util.Comparator; import java.util.List;
@Override public boolean charTyped(char codePoint, int modifiers) { this.searchField.charTyped(codePoint, codePoint); if (this.searchField.getVisible() && this.searchField.isFocused()) { List<LibraryListEntry> newEntries = filterListEntries(this.searchField.getText().toLowerCase()); newEntries.add(0, new LibraryListEntry.NewLibraryListEntry(this, null)); // todo ///this.list.getEntries().clear(); //this.list.getEntries().addAll(newEntries); } return super.charTyped(codePoint, modifiers); } @Override public boolean onEntrySelected(GuiList<LibraryListEntry> guiList, int index, LibraryListEntry entry) { if (!(entry instanceof LibraryListEntry.NewLibraryListEntry)) { this.parent.libraryInfoPanel.setEntry(entry); this.parent.setOutfit(entry.data.outfit); } return true; } public void initList() { List<LibraryListEntry> libraryEntries = new ArrayList<>();
// Path: src/main/java/uk/kihira/tails/common/LibraryEntryData.java // public class LibraryEntryData { // @Expose public final Outfit outfit; // @Expose public String entryName = ""; // @Expose public final String comment = ""; // @Expose public boolean favourite; // @Expose public final long creationDate; // @Expose public final UUID creatorUUID; // /** // * Name is used purely for display purposes. // */ // @Expose public String creatorName; // public boolean remoteEntry = false; // // public LibraryEntryData(UUID creatorUUID, String creatorName, String name, Outfit outfit) { // this.entryName = name; // this.outfit = outfit; // this.creationDate = Calendar.getInstance().getTimeInMillis(); // this.creatorUUID = creatorUUID; // this.creatorName = creatorName; // } // // @SuppressWarnings("RedundantIfStatement") // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // LibraryEntryData data = (LibraryEntryData) o; // // if (creationDate != data.creationDate) return false; // if (favourite != data.favourite) return false; // if (!comment.equals(data.comment)) return false; // if (!creatorUUID.equals(data.creatorUUID)) return false; // if (entryName != null ? !entryName.equals(data.entryName) : data.entryName != null) return false; // if (outfit != null ? !outfit.equals(data.outfit) : data.outfit != null) return false; // // return true; // } // // @Override // public int hashCode() { // int result = outfit != null ? outfit.hashCode() : 0; // result = 31 * result + (entryName != null ? entryName.hashCode() : 0); // result = 31 * result + comment.hashCode(); // result = 31 * result + creatorUUID.hashCode(); // result = 31 * result + (favourite ? 1 : 0); // result = 31 * result + (int) (creationDate ^ (creationDate >>> 32)); // return result; // } // } // // Path: src/main/java/uk/kihira/tails/common/Tails.java // @Mod(Tails.MOD_ID) // public class Tails // { // public static final String MOD_ID = "tails"; // public static final Logger LOGGER = LogManager.getLogger(MOD_ID); // public static final Gson GSON = new GsonBuilder().create(); // public static final boolean DEBUG = true; // // public static boolean hasRemote; // // public static CommonProxy proxy = DistExecutor.safeRunForDist(() -> ClientProxy::new, () -> CommonProxy::new); // // public Tails() // { // FMLJavaModLoadingContext.get().getModEventBus().addListener(this::setup); // FMLJavaModLoadingContext.get().getModEventBus().addListener(this::onConfigChange); // MinecraftForge.EVENT_BUS.addListener(this::addReloadListener); // } // // private void setup(final FMLCommonSetupEvent event) // { // proxy.preInit(); // Config.loadConfig(); // // PartRegistry.loadAllPartsFromResources(); // } // // private void addReloadListener(final AddReloadListenerEvent event) // { // event.addListener((stage, resourceManager, preparationsProfiler, reloadProfiler, backgroundExecutor, gameExecutor) -> // CompletableFuture.runAsync(() -> proxy.onResourceManagerReload())); // } // // public void onConfigChange(final ModConfigEvent event) // { // if (event.getConfig().getModId().equals(Tails.MOD_ID)) // { // Config.loadConfig(); // } // } // // public static void setLocalOutfit(final Outfit outfit) // { // Config.localOutfit.set(outfit); // Config.configuration.save(); // } // } // Path: src/main/java/uk/kihira/tails/client/gui/LibraryPanel.java import com.mojang.blaze3d.matrix.MatrixStack; import com.mojang.blaze3d.platform.GlStateManager; import net.minecraft.client.gui.widget.TextFieldWidget; import net.minecraft.client.gui.widget.button.Button; import net.minecraft.util.text.StringTextComponent; import net.minecraft.util.text.TranslationTextComponent; import net.minecraftforge.fml.client.gui.GuiUtils; import net.minecraftforge.fml.client.gui.widget.ExtendedButton; import uk.kihira.tails.common.LibraryEntryData; import uk.kihira.tails.common.Tails; import net.minecraft.client.Minecraft; import net.minecraft.client.resources.I18n; import java.io.IOException; import java.util.ArrayList; import java.util.Comparator; import java.util.List; @Override public boolean charTyped(char codePoint, int modifiers) { this.searchField.charTyped(codePoint, codePoint); if (this.searchField.getVisible() && this.searchField.isFocused()) { List<LibraryListEntry> newEntries = filterListEntries(this.searchField.getText().toLowerCase()); newEntries.add(0, new LibraryListEntry.NewLibraryListEntry(this, null)); // todo ///this.list.getEntries().clear(); //this.list.getEntries().addAll(newEntries); } return super.charTyped(codePoint, modifiers); } @Override public boolean onEntrySelected(GuiList<LibraryListEntry> guiList, int index, LibraryListEntry entry) { if (!(entry instanceof LibraryListEntry.NewLibraryListEntry)) { this.parent.libraryInfoPanel.setEntry(entry); this.parent.setOutfit(entry.data.outfit); } return true; } public void initList() { List<LibraryListEntry> libraryEntries = new ArrayList<>();
for (LibraryEntryData data : Tails.proxy.getLibraryManager().libraryEntries)
kihira/Tails
src/main/java/uk/kihira/gltf/Geometry.java
// Path: src/main/java/uk/kihira/gltf/spec/MeshPrimitive.java // public enum Attribute { // POSITION(0), // NORMAL(1), // TEXCOORD_0(2), // TANGENT(3), // COLOR_0(4); // // public final int index; // // Attribute(final int index) { // this.index = index; // } // } // // Path: src/main/java/uk/kihira/tails/client/PartRenderer.java // public class PartRenderer // { // private final Shader shader; // private final FloatBuffer modelViewMatrixWorld; // private final FloatBuffer tintBuffer; // private final ArrayDeque<FloatBuffer> bufferPool; // private final HashMap<OutfitPart, FloatBuffer> renders; // // public PartRenderer() // { // modelViewMatrixWorld = BufferUtils.createFloatBuffer(16); // tintBuffer = BufferUtils.createFloatBuffer(9); // bufferPool = new ArrayDeque<>(); // renders = new HashMap<>(16); // shader = new Shader("threetint_vert", "threetint_frag"); // shader.registerUniform("tints"); // } // // /** // * Gets a {@link FloatBuffer} from the pool. If there is none left, creates a new one // * // * @return // */ // private FloatBuffer getFloatBuffer() // { // if (bufferPool.size() == 0) { // return BufferUtils.createFloatBuffer(16); // } else return bufferPool.pop(); // } // // /** // * Returns a {@link FloatBuffer} back to the pool // */ // private void freeFloatBuffer(FloatBuffer buffer) // { // bufferPool.add(buffer); // } // // /** // * Queues up a part to be rendered // */ // public void render(MatrixStack matrixStack, OutfitPart part) // { // GL11.glPushMatrix(); // matrixStack.push(); // matrixStack.translate(part.mountOffset[0], part.mountOffset[1], part.mountOffset[2]); // matrixStack.rotate(Vector3f.XP.rotationDegrees(part.rotation[0])); // matrixStack.rotate(Vector3f.YP.rotationDegrees(part.rotation[1])); // matrixStack.rotate(Vector3f.YP.rotationDegrees(part.rotation[2] + 180f)); // todo need to find out why its being rotated 180 degrees so this fix is no longer required // matrixStack.scale(part.scale[0], part.scale[1], part.scale[2]); // // FloatBuffer fb = getFloatBuffer(); // GL11.glGetFloatv(GL11.GL_MODELVIEW_MATRIX, fb); // GL11.glPopMatrix(); // // renders.put(part, fb); // } // // /** // * Renders the entire queue of parts // */ // public void doRender(MatrixStack matrixStack) // { // if (renders.size() == 0) return; // // // Prepare OpenGL for rendering // RenderHelper.enableStandardItemLighting(); // GlStateManager.enableDepthTest(); // GlStateManager.color4f(1f, 1f, 1f, 1f); // GL11.glGetFloatv(GL11.GL_MODELVIEW_MATRIX, modelViewMatrixWorld); // shader.use(); // // for (HashMap.Entry<OutfitPart, FloatBuffer> entry : renders.entrySet()) // { // OutfitPart outfitPart = entry.getKey(); // Part basePart = outfitPart.getPart(); // if (basePart == null) continue; // Model model = basePart.getModel(); // if (model == null) continue; // // // Set tint colors // tintBuffer.put(outfitPart.tint[0]); // tintBuffer.put(outfitPart.tint[1]); // tintBuffer.put(outfitPart.tint[2]); // tintBuffer.flip(); // GlStateManager.uniform3f(shader.getUniform("tints"), tintBuffer); // // // Load texture and model matrix // Minecraft.getInstance().getTextureManager().bindTexture(outfitPart.textureLoc); // GL11.glLoadMatrixf(entry.getValue()); // model.render(matrixStack); // // if (Tails.DEBUG) // { // renderDebugGizmo(); // } // // freeFloatBuffer(entry.getValue()); // tintBuffer.clear(); // } // renders.clear(); // // unbindBuffersAndShader(); // // GlStateManager.disableDepthTest(); // RenderHelper.disableStandardItemLighting(); // GL11.glLoadMatrixf(modelViewMatrixWorld); // } // // private void renderDebugGizmo() // { // unbindBuffersAndShader(); // // final int scale = 1; // // TODO OpenGlHelper.renderDirections(scale); // } // // /** // * Helper method to clear OpenGL state related to VBOs and Shader programs // */ // private void unbindBuffersAndShader() // { // GlStateManager.useProgram(0); // glBindVertexArray(0); // GlStateManager.bindBuffer(GL15.GL_ARRAY_BUFFER, 0); // } // // /* // Caching for vertex array binding // */ // private static int vertexArray = 0; // // public static void glBindVertexArray(int vao) // { // if (vao != vertexArray) { // GL30.glBindVertexArray(vao); // vertexArray = vao; // } // } // } // // Path: src/main/java/uk/kihira/tails/common/IDisposable.java // public interface IDisposable { // /** // * This method handles cleaning up any resources that are not removed by normal GC means. // * This can include OpenGL buffers and textures // */ // void dispose(); // }
import org.lwjgl.opengl.*; import uk.kihira.gltf.spec.MeshPrimitive.Attribute; import uk.kihira.tails.client.PartRenderer; import uk.kihira.tails.common.IDisposable; import javax.annotation.Nullable; import javax.annotation.ParametersAreNonnullByDefault; import java.util.HashMap; import java.util.Map.Entry;
package uk.kihira.gltf; @ParametersAreNonnullByDefault public final class Geometry implements IDisposable { private final int drawMode; private int vao = -1; private int vertexCount;
// Path: src/main/java/uk/kihira/gltf/spec/MeshPrimitive.java // public enum Attribute { // POSITION(0), // NORMAL(1), // TEXCOORD_0(2), // TANGENT(3), // COLOR_0(4); // // public final int index; // // Attribute(final int index) { // this.index = index; // } // } // // Path: src/main/java/uk/kihira/tails/client/PartRenderer.java // public class PartRenderer // { // private final Shader shader; // private final FloatBuffer modelViewMatrixWorld; // private final FloatBuffer tintBuffer; // private final ArrayDeque<FloatBuffer> bufferPool; // private final HashMap<OutfitPart, FloatBuffer> renders; // // public PartRenderer() // { // modelViewMatrixWorld = BufferUtils.createFloatBuffer(16); // tintBuffer = BufferUtils.createFloatBuffer(9); // bufferPool = new ArrayDeque<>(); // renders = new HashMap<>(16); // shader = new Shader("threetint_vert", "threetint_frag"); // shader.registerUniform("tints"); // } // // /** // * Gets a {@link FloatBuffer} from the pool. If there is none left, creates a new one // * // * @return // */ // private FloatBuffer getFloatBuffer() // { // if (bufferPool.size() == 0) { // return BufferUtils.createFloatBuffer(16); // } else return bufferPool.pop(); // } // // /** // * Returns a {@link FloatBuffer} back to the pool // */ // private void freeFloatBuffer(FloatBuffer buffer) // { // bufferPool.add(buffer); // } // // /** // * Queues up a part to be rendered // */ // public void render(MatrixStack matrixStack, OutfitPart part) // { // GL11.glPushMatrix(); // matrixStack.push(); // matrixStack.translate(part.mountOffset[0], part.mountOffset[1], part.mountOffset[2]); // matrixStack.rotate(Vector3f.XP.rotationDegrees(part.rotation[0])); // matrixStack.rotate(Vector3f.YP.rotationDegrees(part.rotation[1])); // matrixStack.rotate(Vector3f.YP.rotationDegrees(part.rotation[2] + 180f)); // todo need to find out why its being rotated 180 degrees so this fix is no longer required // matrixStack.scale(part.scale[0], part.scale[1], part.scale[2]); // // FloatBuffer fb = getFloatBuffer(); // GL11.glGetFloatv(GL11.GL_MODELVIEW_MATRIX, fb); // GL11.glPopMatrix(); // // renders.put(part, fb); // } // // /** // * Renders the entire queue of parts // */ // public void doRender(MatrixStack matrixStack) // { // if (renders.size() == 0) return; // // // Prepare OpenGL for rendering // RenderHelper.enableStandardItemLighting(); // GlStateManager.enableDepthTest(); // GlStateManager.color4f(1f, 1f, 1f, 1f); // GL11.glGetFloatv(GL11.GL_MODELVIEW_MATRIX, modelViewMatrixWorld); // shader.use(); // // for (HashMap.Entry<OutfitPart, FloatBuffer> entry : renders.entrySet()) // { // OutfitPart outfitPart = entry.getKey(); // Part basePart = outfitPart.getPart(); // if (basePart == null) continue; // Model model = basePart.getModel(); // if (model == null) continue; // // // Set tint colors // tintBuffer.put(outfitPart.tint[0]); // tintBuffer.put(outfitPart.tint[1]); // tintBuffer.put(outfitPart.tint[2]); // tintBuffer.flip(); // GlStateManager.uniform3f(shader.getUniform("tints"), tintBuffer); // // // Load texture and model matrix // Minecraft.getInstance().getTextureManager().bindTexture(outfitPart.textureLoc); // GL11.glLoadMatrixf(entry.getValue()); // model.render(matrixStack); // // if (Tails.DEBUG) // { // renderDebugGizmo(); // } // // freeFloatBuffer(entry.getValue()); // tintBuffer.clear(); // } // renders.clear(); // // unbindBuffersAndShader(); // // GlStateManager.disableDepthTest(); // RenderHelper.disableStandardItemLighting(); // GL11.glLoadMatrixf(modelViewMatrixWorld); // } // // private void renderDebugGizmo() // { // unbindBuffersAndShader(); // // final int scale = 1; // // TODO OpenGlHelper.renderDirections(scale); // } // // /** // * Helper method to clear OpenGL state related to VBOs and Shader programs // */ // private void unbindBuffersAndShader() // { // GlStateManager.useProgram(0); // glBindVertexArray(0); // GlStateManager.bindBuffer(GL15.GL_ARRAY_BUFFER, 0); // } // // /* // Caching for vertex array binding // */ // private static int vertexArray = 0; // // public static void glBindVertexArray(int vao) // { // if (vao != vertexArray) { // GL30.glBindVertexArray(vao); // vertexArray = vao; // } // } // } // // Path: src/main/java/uk/kihira/tails/common/IDisposable.java // public interface IDisposable { // /** // * This method handles cleaning up any resources that are not removed by normal GC means. // * This can include OpenGL buffers and textures // */ // void dispose(); // } // Path: src/main/java/uk/kihira/gltf/Geometry.java import org.lwjgl.opengl.*; import uk.kihira.gltf.spec.MeshPrimitive.Attribute; import uk.kihira.tails.client.PartRenderer; import uk.kihira.tails.common.IDisposable; import javax.annotation.Nullable; import javax.annotation.ParametersAreNonnullByDefault; import java.util.HashMap; import java.util.Map.Entry; package uk.kihira.gltf; @ParametersAreNonnullByDefault public final class Geometry implements IDisposable { private final int drawMode; private int vao = -1; private int vertexCount;
private final HashMap<Attribute, VertexBuffer> buffers = new HashMap<>();
kihira/Tails
src/main/java/uk/kihira/tails/common/network/PlayerDataMapMessage.java
// Path: src/main/java/uk/kihira/tails/client/outfit/Outfit.java // public final class Outfit // { // public final UUID id; // public String name; // public String description; // public ArrayList<OutfitPart> parts; // // public Outfit() // { // id = UUID.randomUUID(); // parts = new ArrayList<>(); // } // // // todo make a client only multimap of mountpoint <-> outfitpart? // } // // Path: src/main/java/uk/kihira/tails/common/Tails.java // @Mod(Tails.MOD_ID) // public class Tails // { // public static final String MOD_ID = "tails"; // public static final Logger LOGGER = LogManager.getLogger(MOD_ID); // public static final Gson GSON = new GsonBuilder().create(); // public static final boolean DEBUG = true; // // public static boolean hasRemote; // // public static CommonProxy proxy = DistExecutor.safeRunForDist(() -> ClientProxy::new, () -> CommonProxy::new); // // public Tails() // { // FMLJavaModLoadingContext.get().getModEventBus().addListener(this::setup); // FMLJavaModLoadingContext.get().getModEventBus().addListener(this::onConfigChange); // MinecraftForge.EVENT_BUS.addListener(this::addReloadListener); // } // // private void setup(final FMLCommonSetupEvent event) // { // proxy.preInit(); // Config.loadConfig(); // // PartRegistry.loadAllPartsFromResources(); // } // // private void addReloadListener(final AddReloadListenerEvent event) // { // event.addListener((stage, resourceManager, preparationsProfiler, reloadProfiler, backgroundExecutor, gameExecutor) -> // CompletableFuture.runAsync(() -> proxy.onResourceManagerReload())); // } // // public void onConfigChange(final ModConfigEvent event) // { // if (event.getConfig().getModId().equals(Tails.MOD_ID)) // { // Config.loadConfig(); // } // } // // public static void setLocalOutfit(final Outfit outfit) // { // Config.localOutfit.set(outfit); // Config.configuration.save(); // } // }
import com.google.common.reflect.TypeToken; import com.google.gson.JsonSyntaxException; import net.minecraft.network.PacketBuffer; import net.minecraftforge.fml.network.NetworkEvent.Context; import uk.kihira.tails.client.outfit.Outfit; import uk.kihira.tails.common.Tails; import java.util.Map; import java.util.UUID; import java.util.function.Supplier;
package uk.kihira.tails.common.network; public class PlayerDataMapMessage {
// Path: src/main/java/uk/kihira/tails/client/outfit/Outfit.java // public final class Outfit // { // public final UUID id; // public String name; // public String description; // public ArrayList<OutfitPart> parts; // // public Outfit() // { // id = UUID.randomUUID(); // parts = new ArrayList<>(); // } // // // todo make a client only multimap of mountpoint <-> outfitpart? // } // // Path: src/main/java/uk/kihira/tails/common/Tails.java // @Mod(Tails.MOD_ID) // public class Tails // { // public static final String MOD_ID = "tails"; // public static final Logger LOGGER = LogManager.getLogger(MOD_ID); // public static final Gson GSON = new GsonBuilder().create(); // public static final boolean DEBUG = true; // // public static boolean hasRemote; // // public static CommonProxy proxy = DistExecutor.safeRunForDist(() -> ClientProxy::new, () -> CommonProxy::new); // // public Tails() // { // FMLJavaModLoadingContext.get().getModEventBus().addListener(this::setup); // FMLJavaModLoadingContext.get().getModEventBus().addListener(this::onConfigChange); // MinecraftForge.EVENT_BUS.addListener(this::addReloadListener); // } // // private void setup(final FMLCommonSetupEvent event) // { // proxy.preInit(); // Config.loadConfig(); // // PartRegistry.loadAllPartsFromResources(); // } // // private void addReloadListener(final AddReloadListenerEvent event) // { // event.addListener((stage, resourceManager, preparationsProfiler, reloadProfiler, backgroundExecutor, gameExecutor) -> // CompletableFuture.runAsync(() -> proxy.onResourceManagerReload())); // } // // public void onConfigChange(final ModConfigEvent event) // { // if (event.getConfig().getModId().equals(Tails.MOD_ID)) // { // Config.loadConfig(); // } // } // // public static void setLocalOutfit(final Outfit outfit) // { // Config.localOutfit.set(outfit); // Config.configuration.save(); // } // } // Path: src/main/java/uk/kihira/tails/common/network/PlayerDataMapMessage.java import com.google.common.reflect.TypeToken; import com.google.gson.JsonSyntaxException; import net.minecraft.network.PacketBuffer; import net.minecraftforge.fml.network.NetworkEvent.Context; import uk.kihira.tails.client.outfit.Outfit; import uk.kihira.tails.common.Tails; import java.util.Map; import java.util.UUID; import java.util.function.Supplier; package uk.kihira.tails.common.network; public class PlayerDataMapMessage {
private Map<UUID, Outfit> outfitMap;
kihira/Tails
src/main/java/uk/kihira/tails/common/network/PlayerDataMapMessage.java
// Path: src/main/java/uk/kihira/tails/client/outfit/Outfit.java // public final class Outfit // { // public final UUID id; // public String name; // public String description; // public ArrayList<OutfitPart> parts; // // public Outfit() // { // id = UUID.randomUUID(); // parts = new ArrayList<>(); // } // // // todo make a client only multimap of mountpoint <-> outfitpart? // } // // Path: src/main/java/uk/kihira/tails/common/Tails.java // @Mod(Tails.MOD_ID) // public class Tails // { // public static final String MOD_ID = "tails"; // public static final Logger LOGGER = LogManager.getLogger(MOD_ID); // public static final Gson GSON = new GsonBuilder().create(); // public static final boolean DEBUG = true; // // public static boolean hasRemote; // // public static CommonProxy proxy = DistExecutor.safeRunForDist(() -> ClientProxy::new, () -> CommonProxy::new); // // public Tails() // { // FMLJavaModLoadingContext.get().getModEventBus().addListener(this::setup); // FMLJavaModLoadingContext.get().getModEventBus().addListener(this::onConfigChange); // MinecraftForge.EVENT_BUS.addListener(this::addReloadListener); // } // // private void setup(final FMLCommonSetupEvent event) // { // proxy.preInit(); // Config.loadConfig(); // // PartRegistry.loadAllPartsFromResources(); // } // // private void addReloadListener(final AddReloadListenerEvent event) // { // event.addListener((stage, resourceManager, preparationsProfiler, reloadProfiler, backgroundExecutor, gameExecutor) -> // CompletableFuture.runAsync(() -> proxy.onResourceManagerReload())); // } // // public void onConfigChange(final ModConfigEvent event) // { // if (event.getConfig().getModId().equals(Tails.MOD_ID)) // { // Config.loadConfig(); // } // } // // public static void setLocalOutfit(final Outfit outfit) // { // Config.localOutfit.set(outfit); // Config.configuration.save(); // } // }
import com.google.common.reflect.TypeToken; import com.google.gson.JsonSyntaxException; import net.minecraft.network.PacketBuffer; import net.minecraftforge.fml.network.NetworkEvent.Context; import uk.kihira.tails.client.outfit.Outfit; import uk.kihira.tails.common.Tails; import java.util.Map; import java.util.UUID; import java.util.function.Supplier;
package uk.kihira.tails.common.network; public class PlayerDataMapMessage { private Map<UUID, Outfit> outfitMap; public PlayerDataMapMessage() {} public PlayerDataMapMessage(Map<UUID, Outfit> outfitMap) { this.outfitMap = outfitMap; } public PlayerDataMapMessage(PacketBuffer buf) { String tailInfoJson = buf.readString(); try {
// Path: src/main/java/uk/kihira/tails/client/outfit/Outfit.java // public final class Outfit // { // public final UUID id; // public String name; // public String description; // public ArrayList<OutfitPart> parts; // // public Outfit() // { // id = UUID.randomUUID(); // parts = new ArrayList<>(); // } // // // todo make a client only multimap of mountpoint <-> outfitpart? // } // // Path: src/main/java/uk/kihira/tails/common/Tails.java // @Mod(Tails.MOD_ID) // public class Tails // { // public static final String MOD_ID = "tails"; // public static final Logger LOGGER = LogManager.getLogger(MOD_ID); // public static final Gson GSON = new GsonBuilder().create(); // public static final boolean DEBUG = true; // // public static boolean hasRemote; // // public static CommonProxy proxy = DistExecutor.safeRunForDist(() -> ClientProxy::new, () -> CommonProxy::new); // // public Tails() // { // FMLJavaModLoadingContext.get().getModEventBus().addListener(this::setup); // FMLJavaModLoadingContext.get().getModEventBus().addListener(this::onConfigChange); // MinecraftForge.EVENT_BUS.addListener(this::addReloadListener); // } // // private void setup(final FMLCommonSetupEvent event) // { // proxy.preInit(); // Config.loadConfig(); // // PartRegistry.loadAllPartsFromResources(); // } // // private void addReloadListener(final AddReloadListenerEvent event) // { // event.addListener((stage, resourceManager, preparationsProfiler, reloadProfiler, backgroundExecutor, gameExecutor) -> // CompletableFuture.runAsync(() -> proxy.onResourceManagerReload())); // } // // public void onConfigChange(final ModConfigEvent event) // { // if (event.getConfig().getModId().equals(Tails.MOD_ID)) // { // Config.loadConfig(); // } // } // // public static void setLocalOutfit(final Outfit outfit) // { // Config.localOutfit.set(outfit); // Config.configuration.save(); // } // } // Path: src/main/java/uk/kihira/tails/common/network/PlayerDataMapMessage.java import com.google.common.reflect.TypeToken; import com.google.gson.JsonSyntaxException; import net.minecraft.network.PacketBuffer; import net.minecraftforge.fml.network.NetworkEvent.Context; import uk.kihira.tails.client.outfit.Outfit; import uk.kihira.tails.common.Tails; import java.util.Map; import java.util.UUID; import java.util.function.Supplier; package uk.kihira.tails.common.network; public class PlayerDataMapMessage { private Map<UUID, Outfit> outfitMap; public PlayerDataMapMessage() {} public PlayerDataMapMessage(Map<UUID, Outfit> outfitMap) { this.outfitMap = outfitMap; } public PlayerDataMapMessage(PacketBuffer buf) { String tailInfoJson = buf.readString(); try {
this.outfitMap = Tails.GSON.fromJson(tailInfoJson, new TypeToken<Map<UUID, Outfit>>() {}.getType());
kihira/Tails
src/test/java/uk/kihira/tails/LazyLoadAssetRegistryTests.java
// Path: src/main/java/uk/kihira/tails/client/LazyLoadAssetRegistry.java // public final class LazyLoadAssetRegistry<K, V> // { // private final HashMap<K, V> items = new HashMap<>(); // private final HashMap<K, CompletableFuture<V>> itemsLoading = new HashMap<>(); // private final Logger logger; // private final V defaultValue; // private final V errorValue; // // private final Function<K, CompletableFuture<V>> getter; // // /** // * Creates an asset registry that will asynchronously load items when they are requested. // * @param logger The logger that will be used to output information // * @param getter The function that will be invoked when requesting an item // * @param defaultValue The value to return whilst an item is loading // * @param errorValue The value to store and return if an item fails to load // */ // public LazyLoadAssetRegistry(Logger logger, Function<K, CompletableFuture<V>> getter, @Nullable V defaultValue, @Nullable V errorValue) // { // this.logger = logger; // this.getter = getter; // this.defaultValue = defaultValue; // this.errorValue = errorValue; // } // // public Optional<V> get(K key) // { // if (items.containsKey(key)) { return Optional.of(items.get(key)); } // if (itemsLoading.containsKey(key)) // { // CompletableFuture<V> future = itemsLoading.get(key); // if (future.isDone()) // { // V result; // try // { // result = future.get(); // } // catch (InterruptedException | ExecutionException e) // { // result = errorValue; // logger.error(String.format("Failed to load item %s", key.toString()), e); // } // items.put(key, result); // itemsLoading.remove(key); // // return Optional.ofNullable(result); // } // // return Optional.ofNullable(defaultValue); // } // // // Start lazy loading the item // CompletableFuture<V> future = getter.apply(key); // if (future.isDone()) // { // return safePut(key, future); // } // else // { // itemsLoading.put(key, future); // } // // return Optional.empty(); // } // // /** // * Removes a value from {@link #items} if it exists, and optionally from the cache as well. // * If the item is still loading ({@link #itemsLoading}) then it cancels the operation. // * @param key The key // */ // public void remove(K key) // { // if (items.remove(key) != null) { return; } // if (itemsLoading.containsKey(key)) // { // CompletableFuture<V> future = itemsLoading.get(key); // future.cancel(true); // itemsLoading.remove(key); // } // } // // public void put(K key, V value) // { // items.put(key, value); // } // // /** // * Returns a {@link Collection} of values for all items that have been fully loaded, including items that are error // * values // * @return // */ // public Collection<V> values() // { // return items.values(); // } // // /** // * Attempts to store the result of a CompletableFuture into {@link #items} and returns the result. // * If an error occurs, returns an empty {@link Optional} and stores {@link #errorValue} instead. // * @param key The key // * @param future The {@link CompletableFuture} that contains the result // */ // private Optional<V> safePut(K key, CompletableFuture<V> future) // { // V result; // try // { // result = future.get(); // } // catch (InterruptedException | ExecutionException e) // { // result = errorValue; // logger.error(String.format("Failed to load item %s", key.toString()), e); // } // items.put(key, result); // // return Optional.ofNullable(result); // } // }
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.junit.jupiter.api.Test; import uk.kihira.tails.client.LazyLoadAssetRegistry; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.function.Function; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue;
package uk.kihira.tails; class LazyLoadAssetRegistryTests { @Test void Get_ErrorOccursDuringLoading_StoresAndReturnsErrorValue() { Logger logger = LogManager.getLogger(); Function<String, CompletableFuture<String>> getter = (input) -> { CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "VALID_VALUE"); future.completeExceptionally(new ExecutionException(new RuntimeException())); return future; };
// Path: src/main/java/uk/kihira/tails/client/LazyLoadAssetRegistry.java // public final class LazyLoadAssetRegistry<K, V> // { // private final HashMap<K, V> items = new HashMap<>(); // private final HashMap<K, CompletableFuture<V>> itemsLoading = new HashMap<>(); // private final Logger logger; // private final V defaultValue; // private final V errorValue; // // private final Function<K, CompletableFuture<V>> getter; // // /** // * Creates an asset registry that will asynchronously load items when they are requested. // * @param logger The logger that will be used to output information // * @param getter The function that will be invoked when requesting an item // * @param defaultValue The value to return whilst an item is loading // * @param errorValue The value to store and return if an item fails to load // */ // public LazyLoadAssetRegistry(Logger logger, Function<K, CompletableFuture<V>> getter, @Nullable V defaultValue, @Nullable V errorValue) // { // this.logger = logger; // this.getter = getter; // this.defaultValue = defaultValue; // this.errorValue = errorValue; // } // // public Optional<V> get(K key) // { // if (items.containsKey(key)) { return Optional.of(items.get(key)); } // if (itemsLoading.containsKey(key)) // { // CompletableFuture<V> future = itemsLoading.get(key); // if (future.isDone()) // { // V result; // try // { // result = future.get(); // } // catch (InterruptedException | ExecutionException e) // { // result = errorValue; // logger.error(String.format("Failed to load item %s", key.toString()), e); // } // items.put(key, result); // itemsLoading.remove(key); // // return Optional.ofNullable(result); // } // // return Optional.ofNullable(defaultValue); // } // // // Start lazy loading the item // CompletableFuture<V> future = getter.apply(key); // if (future.isDone()) // { // return safePut(key, future); // } // else // { // itemsLoading.put(key, future); // } // // return Optional.empty(); // } // // /** // * Removes a value from {@link #items} if it exists, and optionally from the cache as well. // * If the item is still loading ({@link #itemsLoading}) then it cancels the operation. // * @param key The key // */ // public void remove(K key) // { // if (items.remove(key) != null) { return; } // if (itemsLoading.containsKey(key)) // { // CompletableFuture<V> future = itemsLoading.get(key); // future.cancel(true); // itemsLoading.remove(key); // } // } // // public void put(K key, V value) // { // items.put(key, value); // } // // /** // * Returns a {@link Collection} of values for all items that have been fully loaded, including items that are error // * values // * @return // */ // public Collection<V> values() // { // return items.values(); // } // // /** // * Attempts to store the result of a CompletableFuture into {@link #items} and returns the result. // * If an error occurs, returns an empty {@link Optional} and stores {@link #errorValue} instead. // * @param key The key // * @param future The {@link CompletableFuture} that contains the result // */ // private Optional<V> safePut(K key, CompletableFuture<V> future) // { // V result; // try // { // result = future.get(); // } // catch (InterruptedException | ExecutionException e) // { // result = errorValue; // logger.error(String.format("Failed to load item %s", key.toString()), e); // } // items.put(key, result); // // return Optional.ofNullable(result); // } // } // Path: src/test/java/uk/kihira/tails/LazyLoadAssetRegistryTests.java import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.junit.jupiter.api.Test; import uk.kihira.tails.client.LazyLoadAssetRegistry; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.function.Function; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; package uk.kihira.tails; class LazyLoadAssetRegistryTests { @Test void Get_ErrorOccursDuringLoading_StoresAndReturnsErrorValue() { Logger logger = LogManager.getLogger(); Function<String, CompletableFuture<String>> getter = (input) -> { CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "VALID_VALUE"); future.completeExceptionally(new ExecutionException(new RuntimeException())); return future; };
LazyLoadAssetRegistry<String, String> registry = new LazyLoadAssetRegistry<>(logger, getter, "DEFAULT", "ERROR");
kihira/Tails
src/main/java/uk/kihira/tails/common/ServerEventHandler.java
// Path: src/main/java/uk/kihira/tails/common/network/PlayerDataMapMessage.java // public class PlayerDataMapMessage // { // private Map<UUID, Outfit> outfitMap; // // public PlayerDataMapMessage() {} // public PlayerDataMapMessage(Map<UUID, Outfit> outfitMap) // { // this.outfitMap = outfitMap; // } // // public PlayerDataMapMessage(PacketBuffer buf) // { // String tailInfoJson = buf.readString(); // try // { // this.outfitMap = Tails.GSON.fromJson(tailInfoJson, new TypeToken<Map<UUID, Outfit>>() {}.getType()); // } catch (JsonSyntaxException e) // { // Tails.LOGGER.catching(e); // } // } // // public void encode(PacketBuffer buf) // { // String tailInfoJson = Tails.GSON.toJson(this.outfitMap); // buf.writeString(tailInfoJson); // } // // public void handle(Supplier<Context> ctx) // { // ctx.get().enqueueWork(() -> // { // for (Map.Entry<UUID, Outfit> entry : outfitMap.entrySet()) // { // Tails.proxy.setActiveOutfit(entry.getKey(), entry.getValue()); // } // }); // ctx.get().setPacketHandled(true); // } // } // // Path: src/main/java/uk/kihira/tails/common/network/ServerCapabilitiesMessage.java // public class ServerCapabilitiesMessage // { // private final boolean library; // // public ServerCapabilitiesMessage(boolean library) // { // this.library = library; // } // // public ServerCapabilitiesMessage(PacketBuffer buf) // { // library = buf.readBoolean(); // } // // public void encode(PacketBuffer buf) // { // buf.writeBoolean(library); // } // // public void handle(Supplier<Context> ctx) // { // ctx.get().enqueueWork(() -> Config.libraryEnabled.set(this.library)); // ctx.get().setPacketHandled(true); // } // } // // Path: src/main/java/uk/kihira/tails/common/network/TailsPacketHandler.java // public final class TailsPacketHandler // { // private static final String PROTOCOL_VERSION = "1"; // // public static final SimpleChannel networkWrapper = NetworkRegistry.newSimpleChannel( // new ResourceLocation(Tails.MOD_ID, "main"), // () -> PROTOCOL_VERSION, // PROTOCOL_VERSION::equals, // TailsPacketHandler::versionCheck); // // private static boolean versionCheck(String serverVersion) // { // if (serverVersion.equals(NetworkRegistry.ABSENT) || serverVersion.equals(NetworkRegistry.ACCEPTVANILLA)) // { // Tails.LOGGER.info("Connecting to vanilla server, or mod is missing from server"); // Tails.hasRemote = false; // TODO better pattern // } // else if (serverVersion.equals(PROTOCOL_VERSION)) // { // Tails.LOGGER.info("Connecting to server that has Tails mod installed and acceptable version"); // Tails.hasRemote = true; // } // else // { // Tails.LOGGER.warn("Unknown server version %s!", serverVersion); // } // // return true; // } // }
import net.minecraft.entity.player.PlayerEntity; import net.minecraft.entity.player.ServerPlayerEntity; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.event.entity.player.PlayerEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.network.PacketDistributor; import uk.kihira.tails.common.network.PlayerDataMapMessage; import uk.kihira.tails.common.network.ServerCapabilitiesMessage; import uk.kihira.tails.common.network.TailsPacketHandler;
package uk.kihira.tails.common; public class ServerEventHandler { @SubscribeEvent public void onPlayerLogin(PlayerEvent.PlayerLoggedInEvent event) { //Send current known tails to client
// Path: src/main/java/uk/kihira/tails/common/network/PlayerDataMapMessage.java // public class PlayerDataMapMessage // { // private Map<UUID, Outfit> outfitMap; // // public PlayerDataMapMessage() {} // public PlayerDataMapMessage(Map<UUID, Outfit> outfitMap) // { // this.outfitMap = outfitMap; // } // // public PlayerDataMapMessage(PacketBuffer buf) // { // String tailInfoJson = buf.readString(); // try // { // this.outfitMap = Tails.GSON.fromJson(tailInfoJson, new TypeToken<Map<UUID, Outfit>>() {}.getType()); // } catch (JsonSyntaxException e) // { // Tails.LOGGER.catching(e); // } // } // // public void encode(PacketBuffer buf) // { // String tailInfoJson = Tails.GSON.toJson(this.outfitMap); // buf.writeString(tailInfoJson); // } // // public void handle(Supplier<Context> ctx) // { // ctx.get().enqueueWork(() -> // { // for (Map.Entry<UUID, Outfit> entry : outfitMap.entrySet()) // { // Tails.proxy.setActiveOutfit(entry.getKey(), entry.getValue()); // } // }); // ctx.get().setPacketHandled(true); // } // } // // Path: src/main/java/uk/kihira/tails/common/network/ServerCapabilitiesMessage.java // public class ServerCapabilitiesMessage // { // private final boolean library; // // public ServerCapabilitiesMessage(boolean library) // { // this.library = library; // } // // public ServerCapabilitiesMessage(PacketBuffer buf) // { // library = buf.readBoolean(); // } // // public void encode(PacketBuffer buf) // { // buf.writeBoolean(library); // } // // public void handle(Supplier<Context> ctx) // { // ctx.get().enqueueWork(() -> Config.libraryEnabled.set(this.library)); // ctx.get().setPacketHandled(true); // } // } // // Path: src/main/java/uk/kihira/tails/common/network/TailsPacketHandler.java // public final class TailsPacketHandler // { // private static final String PROTOCOL_VERSION = "1"; // // public static final SimpleChannel networkWrapper = NetworkRegistry.newSimpleChannel( // new ResourceLocation(Tails.MOD_ID, "main"), // () -> PROTOCOL_VERSION, // PROTOCOL_VERSION::equals, // TailsPacketHandler::versionCheck); // // private static boolean versionCheck(String serverVersion) // { // if (serverVersion.equals(NetworkRegistry.ABSENT) || serverVersion.equals(NetworkRegistry.ACCEPTVANILLA)) // { // Tails.LOGGER.info("Connecting to vanilla server, or mod is missing from server"); // Tails.hasRemote = false; // TODO better pattern // } // else if (serverVersion.equals(PROTOCOL_VERSION)) // { // Tails.LOGGER.info("Connecting to server that has Tails mod installed and acceptable version"); // Tails.hasRemote = true; // } // else // { // Tails.LOGGER.warn("Unknown server version %s!", serverVersion); // } // // return true; // } // } // Path: src/main/java/uk/kihira/tails/common/ServerEventHandler.java import net.minecraft.entity.player.PlayerEntity; import net.minecraft.entity.player.ServerPlayerEntity; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.event.entity.player.PlayerEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.network.PacketDistributor; import uk.kihira.tails.common.network.PlayerDataMapMessage; import uk.kihira.tails.common.network.ServerCapabilitiesMessage; import uk.kihira.tails.common.network.TailsPacketHandler; package uk.kihira.tails.common; public class ServerEventHandler { @SubscribeEvent public void onPlayerLogin(PlayerEvent.PlayerLoggedInEvent event) { //Send current known tails to client
TailsPacketHandler.networkWrapper.send(PacketDistributor.PLAYER.with(() -> (ServerPlayerEntity) event.getPlayer()), new PlayerDataMapMessage(Tails.proxy.getActiveOutfits()));
kihira/Tails
src/main/java/uk/kihira/tails/common/ServerEventHandler.java
// Path: src/main/java/uk/kihira/tails/common/network/PlayerDataMapMessage.java // public class PlayerDataMapMessage // { // private Map<UUID, Outfit> outfitMap; // // public PlayerDataMapMessage() {} // public PlayerDataMapMessage(Map<UUID, Outfit> outfitMap) // { // this.outfitMap = outfitMap; // } // // public PlayerDataMapMessage(PacketBuffer buf) // { // String tailInfoJson = buf.readString(); // try // { // this.outfitMap = Tails.GSON.fromJson(tailInfoJson, new TypeToken<Map<UUID, Outfit>>() {}.getType()); // } catch (JsonSyntaxException e) // { // Tails.LOGGER.catching(e); // } // } // // public void encode(PacketBuffer buf) // { // String tailInfoJson = Tails.GSON.toJson(this.outfitMap); // buf.writeString(tailInfoJson); // } // // public void handle(Supplier<Context> ctx) // { // ctx.get().enqueueWork(() -> // { // for (Map.Entry<UUID, Outfit> entry : outfitMap.entrySet()) // { // Tails.proxy.setActiveOutfit(entry.getKey(), entry.getValue()); // } // }); // ctx.get().setPacketHandled(true); // } // } // // Path: src/main/java/uk/kihira/tails/common/network/ServerCapabilitiesMessage.java // public class ServerCapabilitiesMessage // { // private final boolean library; // // public ServerCapabilitiesMessage(boolean library) // { // this.library = library; // } // // public ServerCapabilitiesMessage(PacketBuffer buf) // { // library = buf.readBoolean(); // } // // public void encode(PacketBuffer buf) // { // buf.writeBoolean(library); // } // // public void handle(Supplier<Context> ctx) // { // ctx.get().enqueueWork(() -> Config.libraryEnabled.set(this.library)); // ctx.get().setPacketHandled(true); // } // } // // Path: src/main/java/uk/kihira/tails/common/network/TailsPacketHandler.java // public final class TailsPacketHandler // { // private static final String PROTOCOL_VERSION = "1"; // // public static final SimpleChannel networkWrapper = NetworkRegistry.newSimpleChannel( // new ResourceLocation(Tails.MOD_ID, "main"), // () -> PROTOCOL_VERSION, // PROTOCOL_VERSION::equals, // TailsPacketHandler::versionCheck); // // private static boolean versionCheck(String serverVersion) // { // if (serverVersion.equals(NetworkRegistry.ABSENT) || serverVersion.equals(NetworkRegistry.ACCEPTVANILLA)) // { // Tails.LOGGER.info("Connecting to vanilla server, or mod is missing from server"); // Tails.hasRemote = false; // TODO better pattern // } // else if (serverVersion.equals(PROTOCOL_VERSION)) // { // Tails.LOGGER.info("Connecting to server that has Tails mod installed and acceptable version"); // Tails.hasRemote = true; // } // else // { // Tails.LOGGER.warn("Unknown server version %s!", serverVersion); // } // // return true; // } // }
import net.minecraft.entity.player.PlayerEntity; import net.minecraft.entity.player.ServerPlayerEntity; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.event.entity.player.PlayerEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.network.PacketDistributor; import uk.kihira.tails.common.network.PlayerDataMapMessage; import uk.kihira.tails.common.network.ServerCapabilitiesMessage; import uk.kihira.tails.common.network.TailsPacketHandler;
package uk.kihira.tails.common; public class ServerEventHandler { @SubscribeEvent public void onPlayerLogin(PlayerEvent.PlayerLoggedInEvent event) { //Send current known tails to client
// Path: src/main/java/uk/kihira/tails/common/network/PlayerDataMapMessage.java // public class PlayerDataMapMessage // { // private Map<UUID, Outfit> outfitMap; // // public PlayerDataMapMessage() {} // public PlayerDataMapMessage(Map<UUID, Outfit> outfitMap) // { // this.outfitMap = outfitMap; // } // // public PlayerDataMapMessage(PacketBuffer buf) // { // String tailInfoJson = buf.readString(); // try // { // this.outfitMap = Tails.GSON.fromJson(tailInfoJson, new TypeToken<Map<UUID, Outfit>>() {}.getType()); // } catch (JsonSyntaxException e) // { // Tails.LOGGER.catching(e); // } // } // // public void encode(PacketBuffer buf) // { // String tailInfoJson = Tails.GSON.toJson(this.outfitMap); // buf.writeString(tailInfoJson); // } // // public void handle(Supplier<Context> ctx) // { // ctx.get().enqueueWork(() -> // { // for (Map.Entry<UUID, Outfit> entry : outfitMap.entrySet()) // { // Tails.proxy.setActiveOutfit(entry.getKey(), entry.getValue()); // } // }); // ctx.get().setPacketHandled(true); // } // } // // Path: src/main/java/uk/kihira/tails/common/network/ServerCapabilitiesMessage.java // public class ServerCapabilitiesMessage // { // private final boolean library; // // public ServerCapabilitiesMessage(boolean library) // { // this.library = library; // } // // public ServerCapabilitiesMessage(PacketBuffer buf) // { // library = buf.readBoolean(); // } // // public void encode(PacketBuffer buf) // { // buf.writeBoolean(library); // } // // public void handle(Supplier<Context> ctx) // { // ctx.get().enqueueWork(() -> Config.libraryEnabled.set(this.library)); // ctx.get().setPacketHandled(true); // } // } // // Path: src/main/java/uk/kihira/tails/common/network/TailsPacketHandler.java // public final class TailsPacketHandler // { // private static final String PROTOCOL_VERSION = "1"; // // public static final SimpleChannel networkWrapper = NetworkRegistry.newSimpleChannel( // new ResourceLocation(Tails.MOD_ID, "main"), // () -> PROTOCOL_VERSION, // PROTOCOL_VERSION::equals, // TailsPacketHandler::versionCheck); // // private static boolean versionCheck(String serverVersion) // { // if (serverVersion.equals(NetworkRegistry.ABSENT) || serverVersion.equals(NetworkRegistry.ACCEPTVANILLA)) // { // Tails.LOGGER.info("Connecting to vanilla server, or mod is missing from server"); // Tails.hasRemote = false; // TODO better pattern // } // else if (serverVersion.equals(PROTOCOL_VERSION)) // { // Tails.LOGGER.info("Connecting to server that has Tails mod installed and acceptable version"); // Tails.hasRemote = true; // } // else // { // Tails.LOGGER.warn("Unknown server version %s!", serverVersion); // } // // return true; // } // } // Path: src/main/java/uk/kihira/tails/common/ServerEventHandler.java import net.minecraft.entity.player.PlayerEntity; import net.minecraft.entity.player.ServerPlayerEntity; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.event.entity.player.PlayerEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.network.PacketDistributor; import uk.kihira.tails.common.network.PlayerDataMapMessage; import uk.kihira.tails.common.network.ServerCapabilitiesMessage; import uk.kihira.tails.common.network.TailsPacketHandler; package uk.kihira.tails.common; public class ServerEventHandler { @SubscribeEvent public void onPlayerLogin(PlayerEvent.PlayerLoggedInEvent event) { //Send current known tails to client
TailsPacketHandler.networkWrapper.send(PacketDistributor.PLAYER.with(() -> (ServerPlayerEntity) event.getPlayer()), new PlayerDataMapMessage(Tails.proxy.getActiveOutfits()));
kihira/Tails
src/main/java/uk/kihira/tails/common/ServerEventHandler.java
// Path: src/main/java/uk/kihira/tails/common/network/PlayerDataMapMessage.java // public class PlayerDataMapMessage // { // private Map<UUID, Outfit> outfitMap; // // public PlayerDataMapMessage() {} // public PlayerDataMapMessage(Map<UUID, Outfit> outfitMap) // { // this.outfitMap = outfitMap; // } // // public PlayerDataMapMessage(PacketBuffer buf) // { // String tailInfoJson = buf.readString(); // try // { // this.outfitMap = Tails.GSON.fromJson(tailInfoJson, new TypeToken<Map<UUID, Outfit>>() {}.getType()); // } catch (JsonSyntaxException e) // { // Tails.LOGGER.catching(e); // } // } // // public void encode(PacketBuffer buf) // { // String tailInfoJson = Tails.GSON.toJson(this.outfitMap); // buf.writeString(tailInfoJson); // } // // public void handle(Supplier<Context> ctx) // { // ctx.get().enqueueWork(() -> // { // for (Map.Entry<UUID, Outfit> entry : outfitMap.entrySet()) // { // Tails.proxy.setActiveOutfit(entry.getKey(), entry.getValue()); // } // }); // ctx.get().setPacketHandled(true); // } // } // // Path: src/main/java/uk/kihira/tails/common/network/ServerCapabilitiesMessage.java // public class ServerCapabilitiesMessage // { // private final boolean library; // // public ServerCapabilitiesMessage(boolean library) // { // this.library = library; // } // // public ServerCapabilitiesMessage(PacketBuffer buf) // { // library = buf.readBoolean(); // } // // public void encode(PacketBuffer buf) // { // buf.writeBoolean(library); // } // // public void handle(Supplier<Context> ctx) // { // ctx.get().enqueueWork(() -> Config.libraryEnabled.set(this.library)); // ctx.get().setPacketHandled(true); // } // } // // Path: src/main/java/uk/kihira/tails/common/network/TailsPacketHandler.java // public final class TailsPacketHandler // { // private static final String PROTOCOL_VERSION = "1"; // // public static final SimpleChannel networkWrapper = NetworkRegistry.newSimpleChannel( // new ResourceLocation(Tails.MOD_ID, "main"), // () -> PROTOCOL_VERSION, // PROTOCOL_VERSION::equals, // TailsPacketHandler::versionCheck); // // private static boolean versionCheck(String serverVersion) // { // if (serverVersion.equals(NetworkRegistry.ABSENT) || serverVersion.equals(NetworkRegistry.ACCEPTVANILLA)) // { // Tails.LOGGER.info("Connecting to vanilla server, or mod is missing from server"); // Tails.hasRemote = false; // TODO better pattern // } // else if (serverVersion.equals(PROTOCOL_VERSION)) // { // Tails.LOGGER.info("Connecting to server that has Tails mod installed and acceptable version"); // Tails.hasRemote = true; // } // else // { // Tails.LOGGER.warn("Unknown server version %s!", serverVersion); // } // // return true; // } // }
import net.minecraft.entity.player.PlayerEntity; import net.minecraft.entity.player.ServerPlayerEntity; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.event.entity.player.PlayerEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.network.PacketDistributor; import uk.kihira.tails.common.network.PlayerDataMapMessage; import uk.kihira.tails.common.network.ServerCapabilitiesMessage; import uk.kihira.tails.common.network.TailsPacketHandler;
package uk.kihira.tails.common; public class ServerEventHandler { @SubscribeEvent public void onPlayerLogin(PlayerEvent.PlayerLoggedInEvent event) { //Send current known tails to client TailsPacketHandler.networkWrapper.send(PacketDistributor.PLAYER.with(() -> (ServerPlayerEntity) event.getPlayer()), new PlayerDataMapMessage(Tails.proxy.getActiveOutfits()));
// Path: src/main/java/uk/kihira/tails/common/network/PlayerDataMapMessage.java // public class PlayerDataMapMessage // { // private Map<UUID, Outfit> outfitMap; // // public PlayerDataMapMessage() {} // public PlayerDataMapMessage(Map<UUID, Outfit> outfitMap) // { // this.outfitMap = outfitMap; // } // // public PlayerDataMapMessage(PacketBuffer buf) // { // String tailInfoJson = buf.readString(); // try // { // this.outfitMap = Tails.GSON.fromJson(tailInfoJson, new TypeToken<Map<UUID, Outfit>>() {}.getType()); // } catch (JsonSyntaxException e) // { // Tails.LOGGER.catching(e); // } // } // // public void encode(PacketBuffer buf) // { // String tailInfoJson = Tails.GSON.toJson(this.outfitMap); // buf.writeString(tailInfoJson); // } // // public void handle(Supplier<Context> ctx) // { // ctx.get().enqueueWork(() -> // { // for (Map.Entry<UUID, Outfit> entry : outfitMap.entrySet()) // { // Tails.proxy.setActiveOutfit(entry.getKey(), entry.getValue()); // } // }); // ctx.get().setPacketHandled(true); // } // } // // Path: src/main/java/uk/kihira/tails/common/network/ServerCapabilitiesMessage.java // public class ServerCapabilitiesMessage // { // private final boolean library; // // public ServerCapabilitiesMessage(boolean library) // { // this.library = library; // } // // public ServerCapabilitiesMessage(PacketBuffer buf) // { // library = buf.readBoolean(); // } // // public void encode(PacketBuffer buf) // { // buf.writeBoolean(library); // } // // public void handle(Supplier<Context> ctx) // { // ctx.get().enqueueWork(() -> Config.libraryEnabled.set(this.library)); // ctx.get().setPacketHandled(true); // } // } // // Path: src/main/java/uk/kihira/tails/common/network/TailsPacketHandler.java // public final class TailsPacketHandler // { // private static final String PROTOCOL_VERSION = "1"; // // public static final SimpleChannel networkWrapper = NetworkRegistry.newSimpleChannel( // new ResourceLocation(Tails.MOD_ID, "main"), // () -> PROTOCOL_VERSION, // PROTOCOL_VERSION::equals, // TailsPacketHandler::versionCheck); // // private static boolean versionCheck(String serverVersion) // { // if (serverVersion.equals(NetworkRegistry.ABSENT) || serverVersion.equals(NetworkRegistry.ACCEPTVANILLA)) // { // Tails.LOGGER.info("Connecting to vanilla server, or mod is missing from server"); // Tails.hasRemote = false; // TODO better pattern // } // else if (serverVersion.equals(PROTOCOL_VERSION)) // { // Tails.LOGGER.info("Connecting to server that has Tails mod installed and acceptable version"); // Tails.hasRemote = true; // } // else // { // Tails.LOGGER.warn("Unknown server version %s!", serverVersion); // } // // return true; // } // } // Path: src/main/java/uk/kihira/tails/common/ServerEventHandler.java import net.minecraft.entity.player.PlayerEntity; import net.minecraft.entity.player.ServerPlayerEntity; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.event.entity.player.PlayerEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.network.PacketDistributor; import uk.kihira.tails.common.network.PlayerDataMapMessage; import uk.kihira.tails.common.network.ServerCapabilitiesMessage; import uk.kihira.tails.common.network.TailsPacketHandler; package uk.kihira.tails.common; public class ServerEventHandler { @SubscribeEvent public void onPlayerLogin(PlayerEvent.PlayerLoggedInEvent event) { //Send current known tails to client TailsPacketHandler.networkWrapper.send(PacketDistributor.PLAYER.with(() -> (ServerPlayerEntity) event.getPlayer()), new PlayerDataMapMessage(Tails.proxy.getActiveOutfits()));
TailsPacketHandler.networkWrapper.send(PacketDistributor.PLAYER.with(() -> (ServerPlayerEntity) event.getPlayer()), new ServerCapabilitiesMessage(Config.libraryEnabled.get()));
kihira/Tails
src/main/java/uk/kihira/tails/client/Part.java
// Path: src/main/java/uk/kihira/gltf/Model.java // public class Model implements IDisposable // { // private final ArrayList<Node> allNodes; // private final ArrayList<Node> rootNodes; // private final HashMap<String, Animation> animations; // private final ArrayList<ResourceLocation> textures; // // public Model(ArrayList<Node> allNodes, ArrayList<Node> rootNodes, HashMap<String, Animation> animations, ArrayList<ResourceLocation> textures) { // this.allNodes = allNodes; // this.rootNodes = rootNodes; // this.animations = animations; // this.textures = textures; // } // // public void render(MatrixStack matrixStack) // { // for (Node node : rootNodes) // { // node.render(matrixStack); // } // } // // public void dispose() // { // allNodes.forEach(Node::dispose); // // // Textures // textures.forEach(texture -> Minecraft.getInstance().getTextureManager().deleteTexture(texture)); // textures.clear(); // } // }
import uk.kihira.gltf.Model; import javax.annotation.Nullable; import java.util.UUID;
package uk.kihira.tails.client; /** * Represents a Part that has a name, author, model and various details about how it should render */ @Nullable public final class Part { // Non render details public final UUID id; // A UUID for a file that contains the model and texture. Also the UUID for the part public final String author; public final String name; public final String[] tags = new String[]{}; public final int category = 0; public final MountPoint mountPoint; public final float[] mountOffset; public final float[] rotation; public final float[] scale; public final float[][] tint; public final UUID[] textures;
// Path: src/main/java/uk/kihira/gltf/Model.java // public class Model implements IDisposable // { // private final ArrayList<Node> allNodes; // private final ArrayList<Node> rootNodes; // private final HashMap<String, Animation> animations; // private final ArrayList<ResourceLocation> textures; // // public Model(ArrayList<Node> allNodes, ArrayList<Node> rootNodes, HashMap<String, Animation> animations, ArrayList<ResourceLocation> textures) { // this.allNodes = allNodes; // this.rootNodes = rootNodes; // this.animations = animations; // this.textures = textures; // } // // public void render(MatrixStack matrixStack) // { // for (Node node : rootNodes) // { // node.render(matrixStack); // } // } // // public void dispose() // { // allNodes.forEach(Node::dispose); // // // Textures // textures.forEach(texture -> Minecraft.getInstance().getTextureManager().deleteTexture(texture)); // textures.clear(); // } // } // Path: src/main/java/uk/kihira/tails/client/Part.java import uk.kihira.gltf.Model; import javax.annotation.Nullable; import java.util.UUID; package uk.kihira.tails.client; /** * Represents a Part that has a name, author, model and various details about how it should render */ @Nullable public final class Part { // Non render details public final UUID id; // A UUID for a file that contains the model and texture. Also the UUID for the part public final String author; public final String name; public final String[] tags = new String[]{}; public final int category = 0; public final MountPoint mountPoint; public final float[] mountOffset; public final float[] rotation; public final float[] scale; public final float[][] tint; public final UUID[] textures;
private transient Model model;
kihira/Tails
src/main/java/uk/kihira/tails/common/network/TailsPacketHandler.java
// Path: src/main/java/uk/kihira/tails/common/Tails.java // @Mod(Tails.MOD_ID) // public class Tails // { // public static final String MOD_ID = "tails"; // public static final Logger LOGGER = LogManager.getLogger(MOD_ID); // public static final Gson GSON = new GsonBuilder().create(); // public static final boolean DEBUG = true; // // public static boolean hasRemote; // // public static CommonProxy proxy = DistExecutor.safeRunForDist(() -> ClientProxy::new, () -> CommonProxy::new); // // public Tails() // { // FMLJavaModLoadingContext.get().getModEventBus().addListener(this::setup); // FMLJavaModLoadingContext.get().getModEventBus().addListener(this::onConfigChange); // MinecraftForge.EVENT_BUS.addListener(this::addReloadListener); // } // // private void setup(final FMLCommonSetupEvent event) // { // proxy.preInit(); // Config.loadConfig(); // // PartRegistry.loadAllPartsFromResources(); // } // // private void addReloadListener(final AddReloadListenerEvent event) // { // event.addListener((stage, resourceManager, preparationsProfiler, reloadProfiler, backgroundExecutor, gameExecutor) -> // CompletableFuture.runAsync(() -> proxy.onResourceManagerReload())); // } // // public void onConfigChange(final ModConfigEvent event) // { // if (event.getConfig().getModId().equals(Tails.MOD_ID)) // { // Config.loadConfig(); // } // } // // public static void setLocalOutfit(final Outfit outfit) // { // Config.localOutfit.set(outfit); // Config.configuration.save(); // } // }
import net.minecraft.util.ResourceLocation; import net.minecraftforge.fml.network.NetworkRegistry; import net.minecraftforge.fml.network.simple.SimpleChannel; import uk.kihira.tails.common.Tails;
package uk.kihira.tails.common.network; public final class TailsPacketHandler { private static final String PROTOCOL_VERSION = "1"; public static final SimpleChannel networkWrapper = NetworkRegistry.newSimpleChannel(
// Path: src/main/java/uk/kihira/tails/common/Tails.java // @Mod(Tails.MOD_ID) // public class Tails // { // public static final String MOD_ID = "tails"; // public static final Logger LOGGER = LogManager.getLogger(MOD_ID); // public static final Gson GSON = new GsonBuilder().create(); // public static final boolean DEBUG = true; // // public static boolean hasRemote; // // public static CommonProxy proxy = DistExecutor.safeRunForDist(() -> ClientProxy::new, () -> CommonProxy::new); // // public Tails() // { // FMLJavaModLoadingContext.get().getModEventBus().addListener(this::setup); // FMLJavaModLoadingContext.get().getModEventBus().addListener(this::onConfigChange); // MinecraftForge.EVENT_BUS.addListener(this::addReloadListener); // } // // private void setup(final FMLCommonSetupEvent event) // { // proxy.preInit(); // Config.loadConfig(); // // PartRegistry.loadAllPartsFromResources(); // } // // private void addReloadListener(final AddReloadListenerEvent event) // { // event.addListener((stage, resourceManager, preparationsProfiler, reloadProfiler, backgroundExecutor, gameExecutor) -> // CompletableFuture.runAsync(() -> proxy.onResourceManagerReload())); // } // // public void onConfigChange(final ModConfigEvent event) // { // if (event.getConfig().getModId().equals(Tails.MOD_ID)) // { // Config.loadConfig(); // } // } // // public static void setLocalOutfit(final Outfit outfit) // { // Config.localOutfit.set(outfit); // Config.configuration.save(); // } // } // Path: src/main/java/uk/kihira/tails/common/network/TailsPacketHandler.java import net.minecraft.util.ResourceLocation; import net.minecraftforge.fml.network.NetworkRegistry; import net.minecraftforge.fml.network.simple.SimpleChannel; import uk.kihira.tails.common.Tails; package uk.kihira.tails.common.network; public final class TailsPacketHandler { private static final String PROTOCOL_VERSION = "1"; public static final SimpleChannel networkWrapper = NetworkRegistry.newSimpleChannel(
new ResourceLocation(Tails.MOD_ID, "main"),
kihira/Tails
src/main/java/uk/kihira/tails/client/render/FakeEntityRenderHelper.java
// Path: src/main/java/uk/kihira/tails/api/IRenderHelper.java // public interface IRenderHelper { // void onPreRenderPart(LivingEntity entity, OutfitPart outfitPart); // } // // Path: src/main/java/uk/kihira/tails/client/outfit/OutfitPart.java // public class OutfitPart { // public final UUID basePart; // public MountPoint mountPoint; // public float[] mountOffset; // [x,y,z] // public float[] rotation; // [x,y,z] // public float[] scale; // [x,y,z] // public float[][] tint; // [[r,g,b],[r,g,b]] // public UUID texture; // // // Client only fields // private transient Part part; // public transient ResourceLocation textureLoc; // // public OutfitPart(Part part) { // this.basePart = part.id; // this.mountPoint = part.mountPoint; // this.mountOffset = part.mountOffset; // this.rotation = part.rotation; // this.scale = part.scale; // this.tint = part.tint; // this.texture = part.textures[0]; // // this.textureLoc = new ResourceLocation(Tails.MOD_ID, this.texture.toString()); // } // // /** // * Gets the {@link Part} that has the ID for {@link #basePart} // * @return The part // */ // @Nullable // public Part getPart() // { // if (part == null) // { // part = PartRegistry.getPart(basePart).orElse(null); // } // return part; // } // }
import com.mojang.blaze3d.platform.GlStateManager; import net.minecraft.entity.LivingEntity; import uk.kihira.tails.api.IRenderHelper; import uk.kihira.tails.client.outfit.OutfitPart;
package uk.kihira.tails.client.render; public class FakeEntityRenderHelper implements IRenderHelper { @Override
// Path: src/main/java/uk/kihira/tails/api/IRenderHelper.java // public interface IRenderHelper { // void onPreRenderPart(LivingEntity entity, OutfitPart outfitPart); // } // // Path: src/main/java/uk/kihira/tails/client/outfit/OutfitPart.java // public class OutfitPart { // public final UUID basePart; // public MountPoint mountPoint; // public float[] mountOffset; // [x,y,z] // public float[] rotation; // [x,y,z] // public float[] scale; // [x,y,z] // public float[][] tint; // [[r,g,b],[r,g,b]] // public UUID texture; // // // Client only fields // private transient Part part; // public transient ResourceLocation textureLoc; // // public OutfitPart(Part part) { // this.basePart = part.id; // this.mountPoint = part.mountPoint; // this.mountOffset = part.mountOffset; // this.rotation = part.rotation; // this.scale = part.scale; // this.tint = part.tint; // this.texture = part.textures[0]; // // this.textureLoc = new ResourceLocation(Tails.MOD_ID, this.texture.toString()); // } // // /** // * Gets the {@link Part} that has the ID for {@link #basePart} // * @return The part // */ // @Nullable // public Part getPart() // { // if (part == null) // { // part = PartRegistry.getPart(basePart).orElse(null); // } // return part; // } // } // Path: src/main/java/uk/kihira/tails/client/render/FakeEntityRenderHelper.java import com.mojang.blaze3d.platform.GlStateManager; import net.minecraft.entity.LivingEntity; import uk.kihira.tails.api.IRenderHelper; import uk.kihira.tails.client.outfit.OutfitPart; package uk.kihira.tails.client.render; public class FakeEntityRenderHelper implements IRenderHelper { @Override
public void onPreRenderPart(LivingEntity entity, OutfitPart outfitPart) {
kihira/Tails
src/main/java/uk/kihira/tails/common/network/LibraryEntriesMessage.java
// Path: src/main/java/uk/kihira/tails/common/LibraryEntryData.java // public class LibraryEntryData { // @Expose public final Outfit outfit; // @Expose public String entryName = ""; // @Expose public final String comment = ""; // @Expose public boolean favourite; // @Expose public final long creationDate; // @Expose public final UUID creatorUUID; // /** // * Name is used purely for display purposes. // */ // @Expose public String creatorName; // public boolean remoteEntry = false; // // public LibraryEntryData(UUID creatorUUID, String creatorName, String name, Outfit outfit) { // this.entryName = name; // this.outfit = outfit; // this.creationDate = Calendar.getInstance().getTimeInMillis(); // this.creatorUUID = creatorUUID; // this.creatorName = creatorName; // } // // @SuppressWarnings("RedundantIfStatement") // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // LibraryEntryData data = (LibraryEntryData) o; // // if (creationDate != data.creationDate) return false; // if (favourite != data.favourite) return false; // if (!comment.equals(data.comment)) return false; // if (!creatorUUID.equals(data.creatorUUID)) return false; // if (entryName != null ? !entryName.equals(data.entryName) : data.entryName != null) return false; // if (outfit != null ? !outfit.equals(data.outfit) : data.outfit != null) return false; // // return true; // } // // @Override // public int hashCode() { // int result = outfit != null ? outfit.hashCode() : 0; // result = 31 * result + (entryName != null ? entryName.hashCode() : 0); // result = 31 * result + comment.hashCode(); // result = 31 * result + creatorUUID.hashCode(); // result = 31 * result + (favourite ? 1 : 0); // result = 31 * result + (int) (creationDate ^ (creationDate >>> 32)); // return result; // } // } // // Path: src/main/java/uk/kihira/tails/common/Tails.java // @Mod(Tails.MOD_ID) // public class Tails // { // public static final String MOD_ID = "tails"; // public static final Logger LOGGER = LogManager.getLogger(MOD_ID); // public static final Gson GSON = new GsonBuilder().create(); // public static final boolean DEBUG = true; // // public static boolean hasRemote; // // public static CommonProxy proxy = DistExecutor.safeRunForDist(() -> ClientProxy::new, () -> CommonProxy::new); // // public Tails() // { // FMLJavaModLoadingContext.get().getModEventBus().addListener(this::setup); // FMLJavaModLoadingContext.get().getModEventBus().addListener(this::onConfigChange); // MinecraftForge.EVENT_BUS.addListener(this::addReloadListener); // } // // private void setup(final FMLCommonSetupEvent event) // { // proxy.preInit(); // Config.loadConfig(); // // PartRegistry.loadAllPartsFromResources(); // } // // private void addReloadListener(final AddReloadListenerEvent event) // { // event.addListener((stage, resourceManager, preparationsProfiler, reloadProfiler, backgroundExecutor, gameExecutor) -> // CompletableFuture.runAsync(() -> proxy.onResourceManagerReload())); // } // // public void onConfigChange(final ModConfigEvent event) // { // if (event.getConfig().getModId().equals(Tails.MOD_ID)) // { // Config.loadConfig(); // } // } // // public static void setLocalOutfit(final Outfit outfit) // { // Config.localOutfit.set(outfit); // Config.configuration.save(); // } // }
import com.google.gson.JsonParseException; import com.google.gson.reflect.TypeToken; import uk.kihira.tails.common.LibraryEntryData; import uk.kihira.tails.common.Tails; import net.minecraft.network.PacketBuffer; import net.minecraftforge.fml.network.NetworkDirection; import net.minecraftforge.fml.network.NetworkEvent.Context; import java.util.List; import java.util.function.Supplier;
package uk.kihira.tails.common.network; public class LibraryEntriesMessage { private List<LibraryEntryData> entries; private boolean delete; //Only used when sending to server public LibraryEntriesMessage() {} public LibraryEntriesMessage(List<LibraryEntryData> entries, boolean delete) { this.entries = entries; this.delete = delete; } public LibraryEntriesMessage(PacketBuffer buf) { try {
// Path: src/main/java/uk/kihira/tails/common/LibraryEntryData.java // public class LibraryEntryData { // @Expose public final Outfit outfit; // @Expose public String entryName = ""; // @Expose public final String comment = ""; // @Expose public boolean favourite; // @Expose public final long creationDate; // @Expose public final UUID creatorUUID; // /** // * Name is used purely for display purposes. // */ // @Expose public String creatorName; // public boolean remoteEntry = false; // // public LibraryEntryData(UUID creatorUUID, String creatorName, String name, Outfit outfit) { // this.entryName = name; // this.outfit = outfit; // this.creationDate = Calendar.getInstance().getTimeInMillis(); // this.creatorUUID = creatorUUID; // this.creatorName = creatorName; // } // // @SuppressWarnings("RedundantIfStatement") // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // LibraryEntryData data = (LibraryEntryData) o; // // if (creationDate != data.creationDate) return false; // if (favourite != data.favourite) return false; // if (!comment.equals(data.comment)) return false; // if (!creatorUUID.equals(data.creatorUUID)) return false; // if (entryName != null ? !entryName.equals(data.entryName) : data.entryName != null) return false; // if (outfit != null ? !outfit.equals(data.outfit) : data.outfit != null) return false; // // return true; // } // // @Override // public int hashCode() { // int result = outfit != null ? outfit.hashCode() : 0; // result = 31 * result + (entryName != null ? entryName.hashCode() : 0); // result = 31 * result + comment.hashCode(); // result = 31 * result + creatorUUID.hashCode(); // result = 31 * result + (favourite ? 1 : 0); // result = 31 * result + (int) (creationDate ^ (creationDate >>> 32)); // return result; // } // } // // Path: src/main/java/uk/kihira/tails/common/Tails.java // @Mod(Tails.MOD_ID) // public class Tails // { // public static final String MOD_ID = "tails"; // public static final Logger LOGGER = LogManager.getLogger(MOD_ID); // public static final Gson GSON = new GsonBuilder().create(); // public static final boolean DEBUG = true; // // public static boolean hasRemote; // // public static CommonProxy proxy = DistExecutor.safeRunForDist(() -> ClientProxy::new, () -> CommonProxy::new); // // public Tails() // { // FMLJavaModLoadingContext.get().getModEventBus().addListener(this::setup); // FMLJavaModLoadingContext.get().getModEventBus().addListener(this::onConfigChange); // MinecraftForge.EVENT_BUS.addListener(this::addReloadListener); // } // // private void setup(final FMLCommonSetupEvent event) // { // proxy.preInit(); // Config.loadConfig(); // // PartRegistry.loadAllPartsFromResources(); // } // // private void addReloadListener(final AddReloadListenerEvent event) // { // event.addListener((stage, resourceManager, preparationsProfiler, reloadProfiler, backgroundExecutor, gameExecutor) -> // CompletableFuture.runAsync(() -> proxy.onResourceManagerReload())); // } // // public void onConfigChange(final ModConfigEvent event) // { // if (event.getConfig().getModId().equals(Tails.MOD_ID)) // { // Config.loadConfig(); // } // } // // public static void setLocalOutfit(final Outfit outfit) // { // Config.localOutfit.set(outfit); // Config.configuration.save(); // } // } // Path: src/main/java/uk/kihira/tails/common/network/LibraryEntriesMessage.java import com.google.gson.JsonParseException; import com.google.gson.reflect.TypeToken; import uk.kihira.tails.common.LibraryEntryData; import uk.kihira.tails.common.Tails; import net.minecraft.network.PacketBuffer; import net.minecraftforge.fml.network.NetworkDirection; import net.minecraftforge.fml.network.NetworkEvent.Context; import java.util.List; import java.util.function.Supplier; package uk.kihira.tails.common.network; public class LibraryEntriesMessage { private List<LibraryEntryData> entries; private boolean delete; //Only used when sending to server public LibraryEntriesMessage() {} public LibraryEntriesMessage(List<LibraryEntryData> entries, boolean delete) { this.entries = entries; this.delete = delete; } public LibraryEntriesMessage(PacketBuffer buf) { try {
this.entries = Tails.GSON.fromJson(buf.readString(), new TypeToken<List<LibraryEntryData>>() {}.getType());
kihira/Tails
src/main/java/uk/kihira/tails/common/Config.java
// Path: src/main/java/uk/kihira/tails/client/outfit/Outfit.java // public final class Outfit // { // public final UUID id; // public String name; // public String description; // public ArrayList<OutfitPart> parts; // // public Outfit() // { // id = UUID.randomUUID(); // parts = new ArrayList<>(); // } // // // todo make a client only multimap of mountpoint <-> outfitpart? // }
import com.google.gson.Gson; import net.minecraftforge.common.ForgeConfigSpec; import net.minecraftforge.common.ForgeConfigSpec.BooleanValue; import net.minecraftforge.common.ForgeConfigSpec.ConfigValue; import uk.kihira.tails.client.outfit.Outfit;
package uk.kihira.tails.common; public final class Config { public static BooleanValue forceLegacyRendering; public static BooleanValue libraryEnabled;
// Path: src/main/java/uk/kihira/tails/client/outfit/Outfit.java // public final class Outfit // { // public final UUID id; // public String name; // public String description; // public ArrayList<OutfitPart> parts; // // public Outfit() // { // id = UUID.randomUUID(); // parts = new ArrayList<>(); // } // // // todo make a client only multimap of mountpoint <-> outfitpart? // } // Path: src/main/java/uk/kihira/tails/common/Config.java import com.google.gson.Gson; import net.minecraftforge.common.ForgeConfigSpec; import net.minecraftforge.common.ForgeConfigSpec.BooleanValue; import net.minecraftforge.common.ForgeConfigSpec.ConfigValue; import uk.kihira.tails.client.outfit.Outfit; package uk.kihira.tails.common; public final class Config { public static BooleanValue forceLegacyRendering; public static BooleanValue libraryEnabled;
public static ConfigValue<Outfit> localOutfit;
kihira/Tails
src/main/java/uk/kihira/gltf/Model.java
// Path: src/main/java/uk/kihira/gltf/animation/Animation.java // public class Animation { // private final ArrayList<Channel> channels; // // private FloatBuffer interpolatedValues; // todo per channel instead? // private float currentAnimTime; // // public Animation(ArrayList<Channel> channels) { // this.channels = channels; // interpolatedValues = BufferUtils.createFloatBuffer(4); // } // // public void run() { // for (Channel channel : channels) { // int prevKeyFrameIndex = 0, nextKeyFrameIndex = 1; // float deltaTime; // // // Find where we are on the track (prev and next keyframe positions) // for (int i = 0; i < channel.inputData.limit() - 1; i++) { // if (currentAnimTime > channel.inputData.get(i) && currentAnimTime < channel.inputData.get(i + 1)) { // prevKeyFrameIndex = i; // nextKeyFrameIndex = i + 1; // break; // } // } // deltaTime = (channel.inputData.get(nextKeyFrameIndex) - channel.inputData.get(prevKeyFrameIndex)) / (currentAnimTime - channel.inputData.get(prevKeyFrameIndex)); // // // note: BufferViews referenced by Accessor's won't have byteStride as per spec // FloatBuffer prevFrameData = (FloatBuffer) channel.outputData.slice().position(prevKeyFrameIndex * channel.outputType.size).limit(channel.outputType.size); // FloatBuffer nextFrameData = (FloatBuffer) channel.outputData.slice().position(nextKeyFrameIndex * channel.outputType.size).limit(channel.outputType.size); // // // Do the interpolation // switch (channel.sampler.interpolation) { // case CUBICSPLINE: // Interpolators.CUBIC.evaluate(prevFrameData, nextFrameData, interpolatedValues, deltaTime); // break; // case STEP: // Interpolators.STEP.evaluate(prevFrameData, nextFrameData, interpolatedValues, deltaTime); // break; // case LINEAR: // if (channel.path == AnimationPath.ROTATION) { // Interpolators.SLERP.evaluate(prevFrameData, nextFrameData, interpolatedValues, deltaTime); // } else { // Interpolators.LINEAR.evaluate(prevFrameData, nextFrameData, interpolatedValues, deltaTime); // } // break; // default: // throw new RuntimeException("Unknown interpolation method"); // } // // // Apply the interpolated values to the node // switch (channel.path) { // case TRANSLATION: // channel.node.translation.set(interpolatedValues.get(0), interpolatedValues.get(1), interpolatedValues.get(2)); // break; // case ROTATION: // channel.node.rotation.set(interpolatedValues.get(0), interpolatedValues.get(1), interpolatedValues.get(2), interpolatedValues.get(3)); // break; // case SCALE: // channel.node.scale.set(interpolatedValues.get(0), interpolatedValues.get(1), interpolatedValues.get(2)); // break; // default: // break; // } // } // } // } // // Path: src/main/java/uk/kihira/tails/common/IDisposable.java // public interface IDisposable { // /** // * This method handles cleaning up any resources that are not removed by normal GC means. // * This can include OpenGL buffers and textures // */ // void dispose(); // }
import com.mojang.blaze3d.matrix.MatrixStack; import net.minecraft.client.Minecraft; import net.minecraft.util.ResourceLocation; import uk.kihira.gltf.animation.Animation; import uk.kihira.tails.common.IDisposable; import java.util.ArrayList; import java.util.HashMap;
package uk.kihira.gltf; public class Model implements IDisposable { private final ArrayList<Node> allNodes; private final ArrayList<Node> rootNodes;
// Path: src/main/java/uk/kihira/gltf/animation/Animation.java // public class Animation { // private final ArrayList<Channel> channels; // // private FloatBuffer interpolatedValues; // todo per channel instead? // private float currentAnimTime; // // public Animation(ArrayList<Channel> channels) { // this.channels = channels; // interpolatedValues = BufferUtils.createFloatBuffer(4); // } // // public void run() { // for (Channel channel : channels) { // int prevKeyFrameIndex = 0, nextKeyFrameIndex = 1; // float deltaTime; // // // Find where we are on the track (prev and next keyframe positions) // for (int i = 0; i < channel.inputData.limit() - 1; i++) { // if (currentAnimTime > channel.inputData.get(i) && currentAnimTime < channel.inputData.get(i + 1)) { // prevKeyFrameIndex = i; // nextKeyFrameIndex = i + 1; // break; // } // } // deltaTime = (channel.inputData.get(nextKeyFrameIndex) - channel.inputData.get(prevKeyFrameIndex)) / (currentAnimTime - channel.inputData.get(prevKeyFrameIndex)); // // // note: BufferViews referenced by Accessor's won't have byteStride as per spec // FloatBuffer prevFrameData = (FloatBuffer) channel.outputData.slice().position(prevKeyFrameIndex * channel.outputType.size).limit(channel.outputType.size); // FloatBuffer nextFrameData = (FloatBuffer) channel.outputData.slice().position(nextKeyFrameIndex * channel.outputType.size).limit(channel.outputType.size); // // // Do the interpolation // switch (channel.sampler.interpolation) { // case CUBICSPLINE: // Interpolators.CUBIC.evaluate(prevFrameData, nextFrameData, interpolatedValues, deltaTime); // break; // case STEP: // Interpolators.STEP.evaluate(prevFrameData, nextFrameData, interpolatedValues, deltaTime); // break; // case LINEAR: // if (channel.path == AnimationPath.ROTATION) { // Interpolators.SLERP.evaluate(prevFrameData, nextFrameData, interpolatedValues, deltaTime); // } else { // Interpolators.LINEAR.evaluate(prevFrameData, nextFrameData, interpolatedValues, deltaTime); // } // break; // default: // throw new RuntimeException("Unknown interpolation method"); // } // // // Apply the interpolated values to the node // switch (channel.path) { // case TRANSLATION: // channel.node.translation.set(interpolatedValues.get(0), interpolatedValues.get(1), interpolatedValues.get(2)); // break; // case ROTATION: // channel.node.rotation.set(interpolatedValues.get(0), interpolatedValues.get(1), interpolatedValues.get(2), interpolatedValues.get(3)); // break; // case SCALE: // channel.node.scale.set(interpolatedValues.get(0), interpolatedValues.get(1), interpolatedValues.get(2)); // break; // default: // break; // } // } // } // } // // Path: src/main/java/uk/kihira/tails/common/IDisposable.java // public interface IDisposable { // /** // * This method handles cleaning up any resources that are not removed by normal GC means. // * This can include OpenGL buffers and textures // */ // void dispose(); // } // Path: src/main/java/uk/kihira/gltf/Model.java import com.mojang.blaze3d.matrix.MatrixStack; import net.minecraft.client.Minecraft; import net.minecraft.util.ResourceLocation; import uk.kihira.gltf.animation.Animation; import uk.kihira.tails.common.IDisposable; import java.util.ArrayList; import java.util.HashMap; package uk.kihira.gltf; public class Model implements IDisposable { private final ArrayList<Node> allNodes; private final ArrayList<Node> rootNodes;
private final HashMap<String, Animation> animations;
kihira/Tails
src/main/java/uk/kihira/tails/client/Shader.java
// Path: src/main/java/uk/kihira/tails/common/Tails.java // @Mod(Tails.MOD_ID) // public class Tails // { // public static final String MOD_ID = "tails"; // public static final Logger LOGGER = LogManager.getLogger(MOD_ID); // public static final Gson GSON = new GsonBuilder().create(); // public static final boolean DEBUG = true; // // public static boolean hasRemote; // // public static CommonProxy proxy = DistExecutor.safeRunForDist(() -> ClientProxy::new, () -> CommonProxy::new); // // public Tails() // { // FMLJavaModLoadingContext.get().getModEventBus().addListener(this::setup); // FMLJavaModLoadingContext.get().getModEventBus().addListener(this::onConfigChange); // MinecraftForge.EVENT_BUS.addListener(this::addReloadListener); // } // // private void setup(final FMLCommonSetupEvent event) // { // proxy.preInit(); // Config.loadConfig(); // // PartRegistry.loadAllPartsFromResources(); // } // // private void addReloadListener(final AddReloadListenerEvent event) // { // event.addListener((stage, resourceManager, preparationsProfiler, reloadProfiler, backgroundExecutor, gameExecutor) -> // CompletableFuture.runAsync(() -> proxy.onResourceManagerReload())); // } // // public void onConfigChange(final ModConfigEvent event) // { // if (event.getConfig().getModId().equals(Tails.MOD_ID)) // { // Config.loadConfig(); // } // } // // public static void setLocalOutfit(final Outfit outfit) // { // Config.localOutfit.set(outfit); // Config.configuration.save(); // } // }
import com.google.common.base.Strings; import com.mojang.blaze3d.platform.GlStateManager; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.texture.TextureUtil; import net.minecraft.util.ResourceLocation; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL20; import uk.kihira.tails.common.Tails; import javax.annotation.ParametersAreNonnullByDefault; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map;
package uk.kihira.tails.client; @OnlyIn(Dist.CLIENT) @ParametersAreNonnullByDefault public class Shader { private final Map<String, Integer> uniforms; private int program; public Shader(String vertShader, String fragShader) { Minecraft mc = Minecraft.getInstance();
// Path: src/main/java/uk/kihira/tails/common/Tails.java // @Mod(Tails.MOD_ID) // public class Tails // { // public static final String MOD_ID = "tails"; // public static final Logger LOGGER = LogManager.getLogger(MOD_ID); // public static final Gson GSON = new GsonBuilder().create(); // public static final boolean DEBUG = true; // // public static boolean hasRemote; // // public static CommonProxy proxy = DistExecutor.safeRunForDist(() -> ClientProxy::new, () -> CommonProxy::new); // // public Tails() // { // FMLJavaModLoadingContext.get().getModEventBus().addListener(this::setup); // FMLJavaModLoadingContext.get().getModEventBus().addListener(this::onConfigChange); // MinecraftForge.EVENT_BUS.addListener(this::addReloadListener); // } // // private void setup(final FMLCommonSetupEvent event) // { // proxy.preInit(); // Config.loadConfig(); // // PartRegistry.loadAllPartsFromResources(); // } // // private void addReloadListener(final AddReloadListenerEvent event) // { // event.addListener((stage, resourceManager, preparationsProfiler, reloadProfiler, backgroundExecutor, gameExecutor) -> // CompletableFuture.runAsync(() -> proxy.onResourceManagerReload())); // } // // public void onConfigChange(final ModConfigEvent event) // { // if (event.getConfig().getModId().equals(Tails.MOD_ID)) // { // Config.loadConfig(); // } // } // // public static void setLocalOutfit(final Outfit outfit) // { // Config.localOutfit.set(outfit); // Config.configuration.save(); // } // } // Path: src/main/java/uk/kihira/tails/client/Shader.java import com.google.common.base.Strings; import com.mojang.blaze3d.platform.GlStateManager; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.texture.TextureUtil; import net.minecraft.util.ResourceLocation; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL20; import uk.kihira.tails.common.Tails; import javax.annotation.ParametersAreNonnullByDefault; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map; package uk.kihira.tails.client; @OnlyIn(Dist.CLIENT) @ParametersAreNonnullByDefault public class Shader { private final Map<String, Integer> uniforms; private int program; public Shader(String vertShader, String fragShader) { Minecraft mc = Minecraft.getInstance();
ResourceLocation vertRes = new ResourceLocation(Tails.MOD_ID, "shader/" + vertShader + ".glsl");
kihira/Tails
src/main/java/uk/kihira/tails/client/gui/controls/GuiHSBSlider.java
// Path: src/main/java/uk/kihira/tails/client/gui/ITooltip.java // @Nonnull // public interface ITooltip { // List<String> getTooltip(int mouseX, int mouseY, float mouseIdleTime); // } // // Path: src/main/java/uk/kihira/tails/common/Tails.java // @Mod(Tails.MOD_ID) // public class Tails // { // public static final String MOD_ID = "tails"; // public static final Logger LOGGER = LogManager.getLogger(MOD_ID); // public static final Gson GSON = new GsonBuilder().create(); // public static final boolean DEBUG = true; // // public static boolean hasRemote; // // public static CommonProxy proxy = DistExecutor.safeRunForDist(() -> ClientProxy::new, () -> CommonProxy::new); // // public Tails() // { // FMLJavaModLoadingContext.get().getModEventBus().addListener(this::setup); // FMLJavaModLoadingContext.get().getModEventBus().addListener(this::onConfigChange); // MinecraftForge.EVENT_BUS.addListener(this::addReloadListener); // } // // private void setup(final FMLCommonSetupEvent event) // { // proxy.preInit(); // Config.loadConfig(); // // PartRegistry.loadAllPartsFromResources(); // } // // private void addReloadListener(final AddReloadListenerEvent event) // { // event.addListener((stage, resourceManager, preparationsProfiler, reloadProfiler, backgroundExecutor, gameExecutor) -> // CompletableFuture.runAsync(() -> proxy.onResourceManagerReload())); // } // // public void onConfigChange(final ModConfigEvent event) // { // if (event.getConfig().getModId().equals(Tails.MOD_ID)) // { // Config.loadConfig(); // } // } // // public static void setLocalOutfit(final Outfit outfit) // { // Config.localOutfit.set(outfit); // Config.configuration.save(); // } // }
import net.minecraft.client.renderer.BufferBuilder; import net.minecraft.client.renderer.vertex.DefaultVertexFormats; import net.minecraft.util.text.StringTextComponent; import net.minecraftforge.fml.client.gui.GuiUtils; import uk.kihira.tails.client.gui.ITooltip; import uk.kihira.tails.common.Tails; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.Tessellator; import net.minecraft.util.ResourceLocation; import net.minecraftforge.fml.client.gui.widget.Slider; import javax.annotation.ParametersAreNonnullByDefault; import com.mojang.blaze3d.matrix.MatrixStack; import com.mojang.blaze3d.platform.GlStateManager; import java.awt.*; import java.util.Arrays; import java.util.List;
package uk.kihira.tails.client.gui.controls; @ParametersAreNonnullByDefault public class GuiHSBSlider extends Slider implements ITooltip {
// Path: src/main/java/uk/kihira/tails/client/gui/ITooltip.java // @Nonnull // public interface ITooltip { // List<String> getTooltip(int mouseX, int mouseY, float mouseIdleTime); // } // // Path: src/main/java/uk/kihira/tails/common/Tails.java // @Mod(Tails.MOD_ID) // public class Tails // { // public static final String MOD_ID = "tails"; // public static final Logger LOGGER = LogManager.getLogger(MOD_ID); // public static final Gson GSON = new GsonBuilder().create(); // public static final boolean DEBUG = true; // // public static boolean hasRemote; // // public static CommonProxy proxy = DistExecutor.safeRunForDist(() -> ClientProxy::new, () -> CommonProxy::new); // // public Tails() // { // FMLJavaModLoadingContext.get().getModEventBus().addListener(this::setup); // FMLJavaModLoadingContext.get().getModEventBus().addListener(this::onConfigChange); // MinecraftForge.EVENT_BUS.addListener(this::addReloadListener); // } // // private void setup(final FMLCommonSetupEvent event) // { // proxy.preInit(); // Config.loadConfig(); // // PartRegistry.loadAllPartsFromResources(); // } // // private void addReloadListener(final AddReloadListenerEvent event) // { // event.addListener((stage, resourceManager, preparationsProfiler, reloadProfiler, backgroundExecutor, gameExecutor) -> // CompletableFuture.runAsync(() -> proxy.onResourceManagerReload())); // } // // public void onConfigChange(final ModConfigEvent event) // { // if (event.getConfig().getModId().equals(Tails.MOD_ID)) // { // Config.loadConfig(); // } // } // // public static void setLocalOutfit(final Outfit outfit) // { // Config.localOutfit.set(outfit); // Config.configuration.save(); // } // } // Path: src/main/java/uk/kihira/tails/client/gui/controls/GuiHSBSlider.java import net.minecraft.client.renderer.BufferBuilder; import net.minecraft.client.renderer.vertex.DefaultVertexFormats; import net.minecraft.util.text.StringTextComponent; import net.minecraftforge.fml.client.gui.GuiUtils; import uk.kihira.tails.client.gui.ITooltip; import uk.kihira.tails.common.Tails; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.Tessellator; import net.minecraft.util.ResourceLocation; import net.minecraftforge.fml.client.gui.widget.Slider; import javax.annotation.ParametersAreNonnullByDefault; import com.mojang.blaze3d.matrix.MatrixStack; import com.mojang.blaze3d.platform.GlStateManager; import java.awt.*; import java.util.Arrays; import java.util.List; package uk.kihira.tails.client.gui.controls; @ParametersAreNonnullByDefault public class GuiHSBSlider extends Slider implements ITooltip {
private static final ResourceLocation SLIDER_TEXTURE = new ResourceLocation(Tails.MOD_ID, "texture/gui/controls/slider_hue.png");
kihira/Tails
src/main/java/uk/kihira/tails/client/PartRenderer.java
// Path: src/main/java/uk/kihira/gltf/Model.java // public class Model implements IDisposable // { // private final ArrayList<Node> allNodes; // private final ArrayList<Node> rootNodes; // private final HashMap<String, Animation> animations; // private final ArrayList<ResourceLocation> textures; // // public Model(ArrayList<Node> allNodes, ArrayList<Node> rootNodes, HashMap<String, Animation> animations, ArrayList<ResourceLocation> textures) { // this.allNodes = allNodes; // this.rootNodes = rootNodes; // this.animations = animations; // this.textures = textures; // } // // public void render(MatrixStack matrixStack) // { // for (Node node : rootNodes) // { // node.render(matrixStack); // } // } // // public void dispose() // { // allNodes.forEach(Node::dispose); // // // Textures // textures.forEach(texture -> Minecraft.getInstance().getTextureManager().deleteTexture(texture)); // textures.clear(); // } // } // // Path: src/main/java/uk/kihira/tails/client/outfit/OutfitPart.java // public class OutfitPart { // public final UUID basePart; // public MountPoint mountPoint; // public float[] mountOffset; // [x,y,z] // public float[] rotation; // [x,y,z] // public float[] scale; // [x,y,z] // public float[][] tint; // [[r,g,b],[r,g,b]] // public UUID texture; // // // Client only fields // private transient Part part; // public transient ResourceLocation textureLoc; // // public OutfitPart(Part part) { // this.basePart = part.id; // this.mountPoint = part.mountPoint; // this.mountOffset = part.mountOffset; // this.rotation = part.rotation; // this.scale = part.scale; // this.tint = part.tint; // this.texture = part.textures[0]; // // this.textureLoc = new ResourceLocation(Tails.MOD_ID, this.texture.toString()); // } // // /** // * Gets the {@link Part} that has the ID for {@link #basePart} // * @return The part // */ // @Nullable // public Part getPart() // { // if (part == null) // { // part = PartRegistry.getPart(basePart).orElse(null); // } // return part; // } // } // // Path: src/main/java/uk/kihira/tails/common/Tails.java // @Mod(Tails.MOD_ID) // public class Tails // { // public static final String MOD_ID = "tails"; // public static final Logger LOGGER = LogManager.getLogger(MOD_ID); // public static final Gson GSON = new GsonBuilder().create(); // public static final boolean DEBUG = true; // // public static boolean hasRemote; // // public static CommonProxy proxy = DistExecutor.safeRunForDist(() -> ClientProxy::new, () -> CommonProxy::new); // // public Tails() // { // FMLJavaModLoadingContext.get().getModEventBus().addListener(this::setup); // FMLJavaModLoadingContext.get().getModEventBus().addListener(this::onConfigChange); // MinecraftForge.EVENT_BUS.addListener(this::addReloadListener); // } // // private void setup(final FMLCommonSetupEvent event) // { // proxy.preInit(); // Config.loadConfig(); // // PartRegistry.loadAllPartsFromResources(); // } // // private void addReloadListener(final AddReloadListenerEvent event) // { // event.addListener((stage, resourceManager, preparationsProfiler, reloadProfiler, backgroundExecutor, gameExecutor) -> // CompletableFuture.runAsync(() -> proxy.onResourceManagerReload())); // } // // public void onConfigChange(final ModConfigEvent event) // { // if (event.getConfig().getModId().equals(Tails.MOD_ID)) // { // Config.loadConfig(); // } // } // // public static void setLocalOutfit(final Outfit outfit) // { // Config.localOutfit.set(outfit); // Config.configuration.save(); // } // }
import com.mojang.blaze3d.matrix.MatrixStack; import com.mojang.blaze3d.platform.GlStateManager; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.RenderHelper; import net.minecraft.util.math.vector.Vector3f; import org.lwjgl.BufferUtils; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL15; import org.lwjgl.opengl.GL30; import uk.kihira.gltf.Model; import uk.kihira.tails.client.outfit.OutfitPart; import uk.kihira.tails.common.Tails; import java.nio.FloatBuffer; import java.util.ArrayDeque; import java.util.HashMap;
package uk.kihira.tails.client; /** * The main class for handling rendering of parts */ public class PartRenderer { private final Shader shader; private final FloatBuffer modelViewMatrixWorld; private final FloatBuffer tintBuffer; private final ArrayDeque<FloatBuffer> bufferPool;
// Path: src/main/java/uk/kihira/gltf/Model.java // public class Model implements IDisposable // { // private final ArrayList<Node> allNodes; // private final ArrayList<Node> rootNodes; // private final HashMap<String, Animation> animations; // private final ArrayList<ResourceLocation> textures; // // public Model(ArrayList<Node> allNodes, ArrayList<Node> rootNodes, HashMap<String, Animation> animations, ArrayList<ResourceLocation> textures) { // this.allNodes = allNodes; // this.rootNodes = rootNodes; // this.animations = animations; // this.textures = textures; // } // // public void render(MatrixStack matrixStack) // { // for (Node node : rootNodes) // { // node.render(matrixStack); // } // } // // public void dispose() // { // allNodes.forEach(Node::dispose); // // // Textures // textures.forEach(texture -> Minecraft.getInstance().getTextureManager().deleteTexture(texture)); // textures.clear(); // } // } // // Path: src/main/java/uk/kihira/tails/client/outfit/OutfitPart.java // public class OutfitPart { // public final UUID basePart; // public MountPoint mountPoint; // public float[] mountOffset; // [x,y,z] // public float[] rotation; // [x,y,z] // public float[] scale; // [x,y,z] // public float[][] tint; // [[r,g,b],[r,g,b]] // public UUID texture; // // // Client only fields // private transient Part part; // public transient ResourceLocation textureLoc; // // public OutfitPart(Part part) { // this.basePart = part.id; // this.mountPoint = part.mountPoint; // this.mountOffset = part.mountOffset; // this.rotation = part.rotation; // this.scale = part.scale; // this.tint = part.tint; // this.texture = part.textures[0]; // // this.textureLoc = new ResourceLocation(Tails.MOD_ID, this.texture.toString()); // } // // /** // * Gets the {@link Part} that has the ID for {@link #basePart} // * @return The part // */ // @Nullable // public Part getPart() // { // if (part == null) // { // part = PartRegistry.getPart(basePart).orElse(null); // } // return part; // } // } // // Path: src/main/java/uk/kihira/tails/common/Tails.java // @Mod(Tails.MOD_ID) // public class Tails // { // public static final String MOD_ID = "tails"; // public static final Logger LOGGER = LogManager.getLogger(MOD_ID); // public static final Gson GSON = new GsonBuilder().create(); // public static final boolean DEBUG = true; // // public static boolean hasRemote; // // public static CommonProxy proxy = DistExecutor.safeRunForDist(() -> ClientProxy::new, () -> CommonProxy::new); // // public Tails() // { // FMLJavaModLoadingContext.get().getModEventBus().addListener(this::setup); // FMLJavaModLoadingContext.get().getModEventBus().addListener(this::onConfigChange); // MinecraftForge.EVENT_BUS.addListener(this::addReloadListener); // } // // private void setup(final FMLCommonSetupEvent event) // { // proxy.preInit(); // Config.loadConfig(); // // PartRegistry.loadAllPartsFromResources(); // } // // private void addReloadListener(final AddReloadListenerEvent event) // { // event.addListener((stage, resourceManager, preparationsProfiler, reloadProfiler, backgroundExecutor, gameExecutor) -> // CompletableFuture.runAsync(() -> proxy.onResourceManagerReload())); // } // // public void onConfigChange(final ModConfigEvent event) // { // if (event.getConfig().getModId().equals(Tails.MOD_ID)) // { // Config.loadConfig(); // } // } // // public static void setLocalOutfit(final Outfit outfit) // { // Config.localOutfit.set(outfit); // Config.configuration.save(); // } // } // Path: src/main/java/uk/kihira/tails/client/PartRenderer.java import com.mojang.blaze3d.matrix.MatrixStack; import com.mojang.blaze3d.platform.GlStateManager; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.RenderHelper; import net.minecraft.util.math.vector.Vector3f; import org.lwjgl.BufferUtils; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL15; import org.lwjgl.opengl.GL30; import uk.kihira.gltf.Model; import uk.kihira.tails.client.outfit.OutfitPart; import uk.kihira.tails.common.Tails; import java.nio.FloatBuffer; import java.util.ArrayDeque; import java.util.HashMap; package uk.kihira.tails.client; /** * The main class for handling rendering of parts */ public class PartRenderer { private final Shader shader; private final FloatBuffer modelViewMatrixWorld; private final FloatBuffer tintBuffer; private final ArrayDeque<FloatBuffer> bufferPool;
private final HashMap<OutfitPart, FloatBuffer> renders;
kihira/Tails
src/main/java/uk/kihira/tails/client/PartRenderer.java
// Path: src/main/java/uk/kihira/gltf/Model.java // public class Model implements IDisposable // { // private final ArrayList<Node> allNodes; // private final ArrayList<Node> rootNodes; // private final HashMap<String, Animation> animations; // private final ArrayList<ResourceLocation> textures; // // public Model(ArrayList<Node> allNodes, ArrayList<Node> rootNodes, HashMap<String, Animation> animations, ArrayList<ResourceLocation> textures) { // this.allNodes = allNodes; // this.rootNodes = rootNodes; // this.animations = animations; // this.textures = textures; // } // // public void render(MatrixStack matrixStack) // { // for (Node node : rootNodes) // { // node.render(matrixStack); // } // } // // public void dispose() // { // allNodes.forEach(Node::dispose); // // // Textures // textures.forEach(texture -> Minecraft.getInstance().getTextureManager().deleteTexture(texture)); // textures.clear(); // } // } // // Path: src/main/java/uk/kihira/tails/client/outfit/OutfitPart.java // public class OutfitPart { // public final UUID basePart; // public MountPoint mountPoint; // public float[] mountOffset; // [x,y,z] // public float[] rotation; // [x,y,z] // public float[] scale; // [x,y,z] // public float[][] tint; // [[r,g,b],[r,g,b]] // public UUID texture; // // // Client only fields // private transient Part part; // public transient ResourceLocation textureLoc; // // public OutfitPart(Part part) { // this.basePart = part.id; // this.mountPoint = part.mountPoint; // this.mountOffset = part.mountOffset; // this.rotation = part.rotation; // this.scale = part.scale; // this.tint = part.tint; // this.texture = part.textures[0]; // // this.textureLoc = new ResourceLocation(Tails.MOD_ID, this.texture.toString()); // } // // /** // * Gets the {@link Part} that has the ID for {@link #basePart} // * @return The part // */ // @Nullable // public Part getPart() // { // if (part == null) // { // part = PartRegistry.getPart(basePart).orElse(null); // } // return part; // } // } // // Path: src/main/java/uk/kihira/tails/common/Tails.java // @Mod(Tails.MOD_ID) // public class Tails // { // public static final String MOD_ID = "tails"; // public static final Logger LOGGER = LogManager.getLogger(MOD_ID); // public static final Gson GSON = new GsonBuilder().create(); // public static final boolean DEBUG = true; // // public static boolean hasRemote; // // public static CommonProxy proxy = DistExecutor.safeRunForDist(() -> ClientProxy::new, () -> CommonProxy::new); // // public Tails() // { // FMLJavaModLoadingContext.get().getModEventBus().addListener(this::setup); // FMLJavaModLoadingContext.get().getModEventBus().addListener(this::onConfigChange); // MinecraftForge.EVENT_BUS.addListener(this::addReloadListener); // } // // private void setup(final FMLCommonSetupEvent event) // { // proxy.preInit(); // Config.loadConfig(); // // PartRegistry.loadAllPartsFromResources(); // } // // private void addReloadListener(final AddReloadListenerEvent event) // { // event.addListener((stage, resourceManager, preparationsProfiler, reloadProfiler, backgroundExecutor, gameExecutor) -> // CompletableFuture.runAsync(() -> proxy.onResourceManagerReload())); // } // // public void onConfigChange(final ModConfigEvent event) // { // if (event.getConfig().getModId().equals(Tails.MOD_ID)) // { // Config.loadConfig(); // } // } // // public static void setLocalOutfit(final Outfit outfit) // { // Config.localOutfit.set(outfit); // Config.configuration.save(); // } // }
import com.mojang.blaze3d.matrix.MatrixStack; import com.mojang.blaze3d.platform.GlStateManager; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.RenderHelper; import net.minecraft.util.math.vector.Vector3f; import org.lwjgl.BufferUtils; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL15; import org.lwjgl.opengl.GL30; import uk.kihira.gltf.Model; import uk.kihira.tails.client.outfit.OutfitPart; import uk.kihira.tails.common.Tails; import java.nio.FloatBuffer; import java.util.ArrayDeque; import java.util.HashMap;
matrixStack.rotate(Vector3f.YP.rotationDegrees(part.rotation[1])); matrixStack.rotate(Vector3f.YP.rotationDegrees(part.rotation[2] + 180f)); // todo need to find out why its being rotated 180 degrees so this fix is no longer required matrixStack.scale(part.scale[0], part.scale[1], part.scale[2]); FloatBuffer fb = getFloatBuffer(); GL11.glGetFloatv(GL11.GL_MODELVIEW_MATRIX, fb); GL11.glPopMatrix(); renders.put(part, fb); } /** * Renders the entire queue of parts */ public void doRender(MatrixStack matrixStack) { if (renders.size() == 0) return; // Prepare OpenGL for rendering RenderHelper.enableStandardItemLighting(); GlStateManager.enableDepthTest(); GlStateManager.color4f(1f, 1f, 1f, 1f); GL11.glGetFloatv(GL11.GL_MODELVIEW_MATRIX, modelViewMatrixWorld); shader.use(); for (HashMap.Entry<OutfitPart, FloatBuffer> entry : renders.entrySet()) { OutfitPart outfitPart = entry.getKey(); Part basePart = outfitPart.getPart(); if (basePart == null) continue;
// Path: src/main/java/uk/kihira/gltf/Model.java // public class Model implements IDisposable // { // private final ArrayList<Node> allNodes; // private final ArrayList<Node> rootNodes; // private final HashMap<String, Animation> animations; // private final ArrayList<ResourceLocation> textures; // // public Model(ArrayList<Node> allNodes, ArrayList<Node> rootNodes, HashMap<String, Animation> animations, ArrayList<ResourceLocation> textures) { // this.allNodes = allNodes; // this.rootNodes = rootNodes; // this.animations = animations; // this.textures = textures; // } // // public void render(MatrixStack matrixStack) // { // for (Node node : rootNodes) // { // node.render(matrixStack); // } // } // // public void dispose() // { // allNodes.forEach(Node::dispose); // // // Textures // textures.forEach(texture -> Minecraft.getInstance().getTextureManager().deleteTexture(texture)); // textures.clear(); // } // } // // Path: src/main/java/uk/kihira/tails/client/outfit/OutfitPart.java // public class OutfitPart { // public final UUID basePart; // public MountPoint mountPoint; // public float[] mountOffset; // [x,y,z] // public float[] rotation; // [x,y,z] // public float[] scale; // [x,y,z] // public float[][] tint; // [[r,g,b],[r,g,b]] // public UUID texture; // // // Client only fields // private transient Part part; // public transient ResourceLocation textureLoc; // // public OutfitPart(Part part) { // this.basePart = part.id; // this.mountPoint = part.mountPoint; // this.mountOffset = part.mountOffset; // this.rotation = part.rotation; // this.scale = part.scale; // this.tint = part.tint; // this.texture = part.textures[0]; // // this.textureLoc = new ResourceLocation(Tails.MOD_ID, this.texture.toString()); // } // // /** // * Gets the {@link Part} that has the ID for {@link #basePart} // * @return The part // */ // @Nullable // public Part getPart() // { // if (part == null) // { // part = PartRegistry.getPart(basePart).orElse(null); // } // return part; // } // } // // Path: src/main/java/uk/kihira/tails/common/Tails.java // @Mod(Tails.MOD_ID) // public class Tails // { // public static final String MOD_ID = "tails"; // public static final Logger LOGGER = LogManager.getLogger(MOD_ID); // public static final Gson GSON = new GsonBuilder().create(); // public static final boolean DEBUG = true; // // public static boolean hasRemote; // // public static CommonProxy proxy = DistExecutor.safeRunForDist(() -> ClientProxy::new, () -> CommonProxy::new); // // public Tails() // { // FMLJavaModLoadingContext.get().getModEventBus().addListener(this::setup); // FMLJavaModLoadingContext.get().getModEventBus().addListener(this::onConfigChange); // MinecraftForge.EVENT_BUS.addListener(this::addReloadListener); // } // // private void setup(final FMLCommonSetupEvent event) // { // proxy.preInit(); // Config.loadConfig(); // // PartRegistry.loadAllPartsFromResources(); // } // // private void addReloadListener(final AddReloadListenerEvent event) // { // event.addListener((stage, resourceManager, preparationsProfiler, reloadProfiler, backgroundExecutor, gameExecutor) -> // CompletableFuture.runAsync(() -> proxy.onResourceManagerReload())); // } // // public void onConfigChange(final ModConfigEvent event) // { // if (event.getConfig().getModId().equals(Tails.MOD_ID)) // { // Config.loadConfig(); // } // } // // public static void setLocalOutfit(final Outfit outfit) // { // Config.localOutfit.set(outfit); // Config.configuration.save(); // } // } // Path: src/main/java/uk/kihira/tails/client/PartRenderer.java import com.mojang.blaze3d.matrix.MatrixStack; import com.mojang.blaze3d.platform.GlStateManager; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.RenderHelper; import net.minecraft.util.math.vector.Vector3f; import org.lwjgl.BufferUtils; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL15; import org.lwjgl.opengl.GL30; import uk.kihira.gltf.Model; import uk.kihira.tails.client.outfit.OutfitPart; import uk.kihira.tails.common.Tails; import java.nio.FloatBuffer; import java.util.ArrayDeque; import java.util.HashMap; matrixStack.rotate(Vector3f.YP.rotationDegrees(part.rotation[1])); matrixStack.rotate(Vector3f.YP.rotationDegrees(part.rotation[2] + 180f)); // todo need to find out why its being rotated 180 degrees so this fix is no longer required matrixStack.scale(part.scale[0], part.scale[1], part.scale[2]); FloatBuffer fb = getFloatBuffer(); GL11.glGetFloatv(GL11.GL_MODELVIEW_MATRIX, fb); GL11.glPopMatrix(); renders.put(part, fb); } /** * Renders the entire queue of parts */ public void doRender(MatrixStack matrixStack) { if (renders.size() == 0) return; // Prepare OpenGL for rendering RenderHelper.enableStandardItemLighting(); GlStateManager.enableDepthTest(); GlStateManager.color4f(1f, 1f, 1f, 1f); GL11.glGetFloatv(GL11.GL_MODELVIEW_MATRIX, modelViewMatrixWorld); shader.use(); for (HashMap.Entry<OutfitPart, FloatBuffer> entry : renders.entrySet()) { OutfitPart outfitPart = entry.getKey(); Part basePart = outfitPart.getPart(); if (basePart == null) continue;
Model model = basePart.getModel();
kihira/Tails
src/main/java/uk/kihira/tails/client/PartRenderer.java
// Path: src/main/java/uk/kihira/gltf/Model.java // public class Model implements IDisposable // { // private final ArrayList<Node> allNodes; // private final ArrayList<Node> rootNodes; // private final HashMap<String, Animation> animations; // private final ArrayList<ResourceLocation> textures; // // public Model(ArrayList<Node> allNodes, ArrayList<Node> rootNodes, HashMap<String, Animation> animations, ArrayList<ResourceLocation> textures) { // this.allNodes = allNodes; // this.rootNodes = rootNodes; // this.animations = animations; // this.textures = textures; // } // // public void render(MatrixStack matrixStack) // { // for (Node node : rootNodes) // { // node.render(matrixStack); // } // } // // public void dispose() // { // allNodes.forEach(Node::dispose); // // // Textures // textures.forEach(texture -> Minecraft.getInstance().getTextureManager().deleteTexture(texture)); // textures.clear(); // } // } // // Path: src/main/java/uk/kihira/tails/client/outfit/OutfitPart.java // public class OutfitPart { // public final UUID basePart; // public MountPoint mountPoint; // public float[] mountOffset; // [x,y,z] // public float[] rotation; // [x,y,z] // public float[] scale; // [x,y,z] // public float[][] tint; // [[r,g,b],[r,g,b]] // public UUID texture; // // // Client only fields // private transient Part part; // public transient ResourceLocation textureLoc; // // public OutfitPart(Part part) { // this.basePart = part.id; // this.mountPoint = part.mountPoint; // this.mountOffset = part.mountOffset; // this.rotation = part.rotation; // this.scale = part.scale; // this.tint = part.tint; // this.texture = part.textures[0]; // // this.textureLoc = new ResourceLocation(Tails.MOD_ID, this.texture.toString()); // } // // /** // * Gets the {@link Part} that has the ID for {@link #basePart} // * @return The part // */ // @Nullable // public Part getPart() // { // if (part == null) // { // part = PartRegistry.getPart(basePart).orElse(null); // } // return part; // } // } // // Path: src/main/java/uk/kihira/tails/common/Tails.java // @Mod(Tails.MOD_ID) // public class Tails // { // public static final String MOD_ID = "tails"; // public static final Logger LOGGER = LogManager.getLogger(MOD_ID); // public static final Gson GSON = new GsonBuilder().create(); // public static final boolean DEBUG = true; // // public static boolean hasRemote; // // public static CommonProxy proxy = DistExecutor.safeRunForDist(() -> ClientProxy::new, () -> CommonProxy::new); // // public Tails() // { // FMLJavaModLoadingContext.get().getModEventBus().addListener(this::setup); // FMLJavaModLoadingContext.get().getModEventBus().addListener(this::onConfigChange); // MinecraftForge.EVENT_BUS.addListener(this::addReloadListener); // } // // private void setup(final FMLCommonSetupEvent event) // { // proxy.preInit(); // Config.loadConfig(); // // PartRegistry.loadAllPartsFromResources(); // } // // private void addReloadListener(final AddReloadListenerEvent event) // { // event.addListener((stage, resourceManager, preparationsProfiler, reloadProfiler, backgroundExecutor, gameExecutor) -> // CompletableFuture.runAsync(() -> proxy.onResourceManagerReload())); // } // // public void onConfigChange(final ModConfigEvent event) // { // if (event.getConfig().getModId().equals(Tails.MOD_ID)) // { // Config.loadConfig(); // } // } // // public static void setLocalOutfit(final Outfit outfit) // { // Config.localOutfit.set(outfit); // Config.configuration.save(); // } // }
import com.mojang.blaze3d.matrix.MatrixStack; import com.mojang.blaze3d.platform.GlStateManager; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.RenderHelper; import net.minecraft.util.math.vector.Vector3f; import org.lwjgl.BufferUtils; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL15; import org.lwjgl.opengl.GL30; import uk.kihira.gltf.Model; import uk.kihira.tails.client.outfit.OutfitPart; import uk.kihira.tails.common.Tails; import java.nio.FloatBuffer; import java.util.ArrayDeque; import java.util.HashMap;
{ if (renders.size() == 0) return; // Prepare OpenGL for rendering RenderHelper.enableStandardItemLighting(); GlStateManager.enableDepthTest(); GlStateManager.color4f(1f, 1f, 1f, 1f); GL11.glGetFloatv(GL11.GL_MODELVIEW_MATRIX, modelViewMatrixWorld); shader.use(); for (HashMap.Entry<OutfitPart, FloatBuffer> entry : renders.entrySet()) { OutfitPart outfitPart = entry.getKey(); Part basePart = outfitPart.getPart(); if (basePart == null) continue; Model model = basePart.getModel(); if (model == null) continue; // Set tint colors tintBuffer.put(outfitPart.tint[0]); tintBuffer.put(outfitPart.tint[1]); tintBuffer.put(outfitPart.tint[2]); tintBuffer.flip(); GlStateManager.uniform3f(shader.getUniform("tints"), tintBuffer); // Load texture and model matrix Minecraft.getInstance().getTextureManager().bindTexture(outfitPart.textureLoc); GL11.glLoadMatrixf(entry.getValue()); model.render(matrixStack);
// Path: src/main/java/uk/kihira/gltf/Model.java // public class Model implements IDisposable // { // private final ArrayList<Node> allNodes; // private final ArrayList<Node> rootNodes; // private final HashMap<String, Animation> animations; // private final ArrayList<ResourceLocation> textures; // // public Model(ArrayList<Node> allNodes, ArrayList<Node> rootNodes, HashMap<String, Animation> animations, ArrayList<ResourceLocation> textures) { // this.allNodes = allNodes; // this.rootNodes = rootNodes; // this.animations = animations; // this.textures = textures; // } // // public void render(MatrixStack matrixStack) // { // for (Node node : rootNodes) // { // node.render(matrixStack); // } // } // // public void dispose() // { // allNodes.forEach(Node::dispose); // // // Textures // textures.forEach(texture -> Minecraft.getInstance().getTextureManager().deleteTexture(texture)); // textures.clear(); // } // } // // Path: src/main/java/uk/kihira/tails/client/outfit/OutfitPart.java // public class OutfitPart { // public final UUID basePart; // public MountPoint mountPoint; // public float[] mountOffset; // [x,y,z] // public float[] rotation; // [x,y,z] // public float[] scale; // [x,y,z] // public float[][] tint; // [[r,g,b],[r,g,b]] // public UUID texture; // // // Client only fields // private transient Part part; // public transient ResourceLocation textureLoc; // // public OutfitPart(Part part) { // this.basePart = part.id; // this.mountPoint = part.mountPoint; // this.mountOffset = part.mountOffset; // this.rotation = part.rotation; // this.scale = part.scale; // this.tint = part.tint; // this.texture = part.textures[0]; // // this.textureLoc = new ResourceLocation(Tails.MOD_ID, this.texture.toString()); // } // // /** // * Gets the {@link Part} that has the ID for {@link #basePart} // * @return The part // */ // @Nullable // public Part getPart() // { // if (part == null) // { // part = PartRegistry.getPart(basePart).orElse(null); // } // return part; // } // } // // Path: src/main/java/uk/kihira/tails/common/Tails.java // @Mod(Tails.MOD_ID) // public class Tails // { // public static final String MOD_ID = "tails"; // public static final Logger LOGGER = LogManager.getLogger(MOD_ID); // public static final Gson GSON = new GsonBuilder().create(); // public static final boolean DEBUG = true; // // public static boolean hasRemote; // // public static CommonProxy proxy = DistExecutor.safeRunForDist(() -> ClientProxy::new, () -> CommonProxy::new); // // public Tails() // { // FMLJavaModLoadingContext.get().getModEventBus().addListener(this::setup); // FMLJavaModLoadingContext.get().getModEventBus().addListener(this::onConfigChange); // MinecraftForge.EVENT_BUS.addListener(this::addReloadListener); // } // // private void setup(final FMLCommonSetupEvent event) // { // proxy.preInit(); // Config.loadConfig(); // // PartRegistry.loadAllPartsFromResources(); // } // // private void addReloadListener(final AddReloadListenerEvent event) // { // event.addListener((stage, resourceManager, preparationsProfiler, reloadProfiler, backgroundExecutor, gameExecutor) -> // CompletableFuture.runAsync(() -> proxy.onResourceManagerReload())); // } // // public void onConfigChange(final ModConfigEvent event) // { // if (event.getConfig().getModId().equals(Tails.MOD_ID)) // { // Config.loadConfig(); // } // } // // public static void setLocalOutfit(final Outfit outfit) // { // Config.localOutfit.set(outfit); // Config.configuration.save(); // } // } // Path: src/main/java/uk/kihira/tails/client/PartRenderer.java import com.mojang.blaze3d.matrix.MatrixStack; import com.mojang.blaze3d.platform.GlStateManager; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.RenderHelper; import net.minecraft.util.math.vector.Vector3f; import org.lwjgl.BufferUtils; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL15; import org.lwjgl.opengl.GL30; import uk.kihira.gltf.Model; import uk.kihira.tails.client.outfit.OutfitPart; import uk.kihira.tails.common.Tails; import java.nio.FloatBuffer; import java.util.ArrayDeque; import java.util.HashMap; { if (renders.size() == 0) return; // Prepare OpenGL for rendering RenderHelper.enableStandardItemLighting(); GlStateManager.enableDepthTest(); GlStateManager.color4f(1f, 1f, 1f, 1f); GL11.glGetFloatv(GL11.GL_MODELVIEW_MATRIX, modelViewMatrixWorld); shader.use(); for (HashMap.Entry<OutfitPart, FloatBuffer> entry : renders.entrySet()) { OutfitPart outfitPart = entry.getKey(); Part basePart = outfitPart.getPart(); if (basePart == null) continue; Model model = basePart.getModel(); if (model == null) continue; // Set tint colors tintBuffer.put(outfitPart.tint[0]); tintBuffer.put(outfitPart.tint[1]); tintBuffer.put(outfitPart.tint[2]); tintBuffer.flip(); GlStateManager.uniform3f(shader.getUniform("tints"), tintBuffer); // Load texture and model matrix Minecraft.getInstance().getTextureManager().bindTexture(outfitPart.textureLoc); GL11.glLoadMatrixf(entry.getValue()); model.render(matrixStack);
if (Tails.DEBUG)
M4thG33k/TombManyGraves2
src/main/java/com/m4thg33k/tombmanygraves/network/PacketProbeFiles.java
// Path: src/main/java/com/m4thg33k/tombmanygraves/TombManyGraves.java // @Mod(modid = Names.MODID, name = Names.MODNAME, version = Names.VERSION, dependencies = TombManyGraves.DEPENDENCIES) // public class TombManyGraves { // // public static final String DEPENDENCIES = "required-after:forge@[14.23.3.2655,)"; // private static Set<ASMData> moduleASM; // // @Mod.Instance // public static TombManyGraves INSTANCE = new TombManyGraves(); // // @SidedProxy(clientSide = "com.m4thg33k.tombmanygraves.proxy.ClientProxy", serverSide = "com.m4thg33k.tombmanygraves.proxy.ServerProxy") // public static CommonProxy proxy; // // @Mod.EventHandler // public void preInit(FMLPreInitializationEvent e) { // proxy.preinit(e); // moduleASM = e.getAsmData().getAll(GraveRegistry.class.getName()); // } // // @Mod.EventHandler // public void init(FMLInitializationEvent e) { // proxy.init(e); // for (ASMData data : moduleASM) { // try { // Class<?> c = Class.forName(data.getClassName()); // if (IGraveInventory.class.isAssignableFrom(c)) { // Map<String, Object> annotation = data.getAnnotationInfo(); // String reqMod = (String) annotation.get("reqMod"); // if (reqMod == null || Loader.isModLoaded(reqMod)){ // GraveInventoryManager.getInstance().registerListener((IGraveInventory) c.newInstance(), annotation); // } // } // } catch (Exception ex) { // ex.printStackTrace(); // } // } // } // // @Mod.EventHandler // public void postinit(FMLPostInitializationEvent e) { // proxy.postinit(e); // // // Make sure to finalize the listeners so the mod actually works... // GraveInventoryManager.getInstance().finalizeListeners(); // } // // @Mod.EventHandler // public void serverLoad(FMLServerStartingEvent event) { // ModCommands.initCommands(event); // } // }
import java.util.List; import java.util.UUID; import com.m4thg33k.tombmanygraves.TombManyGraves; import io.netty.buffer.ByteBuf; import net.minecraft.client.network.NetHandlerPlayClient; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.network.NetHandlerPlayServer; import net.minecraft.util.math.BlockPos; import net.minecraft.world.WorldServer; import net.minecraftforge.common.DimensionManager; import net.minecraftforge.fml.common.network.ByteBufUtils;
package com.m4thg33k.tombmanygraves.network; public class PacketProbeFiles extends BaseThreadsafePacket{ private BlockPos pos; private int dimension; private UUID uuid; public PacketProbeFiles() { } public PacketProbeFiles(int dimension, UUID playerUUID, BlockPos pos) { this.dimension = dimension; this.pos = pos; this.uuid = playerUUID; } @Override public void handleClientSafe(NetHandlerPlayClient netHandler) { throw new UnsupportedOperationException("Server-side only!"); } @Override public void handleServerSafe(NetHandlerPlayServer netHandler) {
// Path: src/main/java/com/m4thg33k/tombmanygraves/TombManyGraves.java // @Mod(modid = Names.MODID, name = Names.MODNAME, version = Names.VERSION, dependencies = TombManyGraves.DEPENDENCIES) // public class TombManyGraves { // // public static final String DEPENDENCIES = "required-after:forge@[14.23.3.2655,)"; // private static Set<ASMData> moduleASM; // // @Mod.Instance // public static TombManyGraves INSTANCE = new TombManyGraves(); // // @SidedProxy(clientSide = "com.m4thg33k.tombmanygraves.proxy.ClientProxy", serverSide = "com.m4thg33k.tombmanygraves.proxy.ServerProxy") // public static CommonProxy proxy; // // @Mod.EventHandler // public void preInit(FMLPreInitializationEvent e) { // proxy.preinit(e); // moduleASM = e.getAsmData().getAll(GraveRegistry.class.getName()); // } // // @Mod.EventHandler // public void init(FMLInitializationEvent e) { // proxy.init(e); // for (ASMData data : moduleASM) { // try { // Class<?> c = Class.forName(data.getClassName()); // if (IGraveInventory.class.isAssignableFrom(c)) { // Map<String, Object> annotation = data.getAnnotationInfo(); // String reqMod = (String) annotation.get("reqMod"); // if (reqMod == null || Loader.isModLoaded(reqMod)){ // GraveInventoryManager.getInstance().registerListener((IGraveInventory) c.newInstance(), annotation); // } // } // } catch (Exception ex) { // ex.printStackTrace(); // } // } // } // // @Mod.EventHandler // public void postinit(FMLPostInitializationEvent e) { // proxy.postinit(e); // // // Make sure to finalize the listeners so the mod actually works... // GraveInventoryManager.getInstance().finalizeListeners(); // } // // @Mod.EventHandler // public void serverLoad(FMLServerStartingEvent event) { // ModCommands.initCommands(event); // } // } // Path: src/main/java/com/m4thg33k/tombmanygraves/network/PacketProbeFiles.java import java.util.List; import java.util.UUID; import com.m4thg33k.tombmanygraves.TombManyGraves; import io.netty.buffer.ByteBuf; import net.minecraft.client.network.NetHandlerPlayClient; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.network.NetHandlerPlayServer; import net.minecraft.util.math.BlockPos; import net.minecraft.world.WorldServer; import net.minecraftforge.common.DimensionManager; import net.minecraftforge.fml.common.network.ByteBufUtils; package com.m4thg33k.tombmanygraves.network; public class PacketProbeFiles extends BaseThreadsafePacket{ private BlockPos pos; private int dimension; private UUID uuid; public PacketProbeFiles() { } public PacketProbeFiles(int dimension, UUID playerUUID, BlockPos pos) { this.dimension = dimension; this.pos = pos; this.uuid = playerUUID; } @Override public void handleClientSafe(NetHandlerPlayClient netHandler) { throw new UnsupportedOperationException("Server-side only!"); } @Override public void handleServerSafe(NetHandlerPlayServer netHandler) {
List<String> files = TombManyGraves.proxy.probeForFiles(pos);
M4thG33k/TombManyGraves2
src/main/java/com/m4thg33k/tombmanygraves/commands/CommandToggleRender.java
// Path: src/main/java/com/m4thg33k/tombmanygraves/network/GraveRenderTogglePacket.java // public class GraveRenderTogglePacket extends BaseThreadsafePacket { // // public GraveRenderTogglePacket() // { // // } // // @Override // public void handleClientSafe(NetHandlerPlayClient netHandler) { // TombManyGraves.proxy.toggleGraveRendering(); // } // // @Override // public void handleServerSafe(NetHandlerPlayServer netHandler) { // LogHelper.error("Attempting to handle rendering packet on server!"); // } // // @Override // public void fromBytes(ByteBuf buf) { // // } // // @Override // public void toBytes(ByteBuf buf) { // // } // } // // Path: src/main/java/com/m4thg33k/tombmanygraves/network/TMGNetwork.java // public class TMGNetwork { // // public static TMGNetwork instance = new TMGNetwork(); // // public final SimpleNetworkWrapper network; // protected final BasePacketHandler handler; // private int id = 0; // // public TMGNetwork(){ // network = NetworkRegistry.INSTANCE.newSimpleChannel(Names.MODID); // handler = new BasePacketHandler(); // } // // public void registerPacket(Class<? extends BasePacket> packetClass) // { // registerPacketClient(packetClass); // registerPacketServer(packetClass); // } // // public static void registerPacketClient(Class<? extends BasePacket> packetClass) // { // registerPacketImp(packetClass, Side.CLIENT); // } // // public static void registerPacketServer(Class<? extends BasePacket> packetClass) // { // registerPacketImp(packetClass, Side.SERVER); // } // // public static void registerPacketImp(Class<? extends BasePacket> packetClass, Side side) // { // instance.network.registerMessage(instance.handler, packetClass, instance.id++, side); // } // // public static void setup() // { // //register packets here // registerPacketServer(PacketProbeFiles.class); // registerPacketClient(GraveRenderTogglePacket.class); // registerPacketClient(GravePosTogglePacket.class); // } // // public static void sendToAll(BasePacket packet) // { // instance.network.sendToAll(packet); // } // // public static void sendTo(BasePacket packet, EntityPlayerMP player) // { // instance.network.sendTo(packet, player); // } // // public static void sendToAllAround(BasePacket packet, NetworkRegistry.TargetPoint point) // { // instance.network.sendToAllAround(packet, point); // } // // public static void sendToDimension(BasePacket packet, int dimensionID) // { // instance.network.sendToDimension(packet, dimensionID); // } // // public static void sendToServer(BasePacket packet) // { // instance.network.sendToServer(packet); // } // // public static void sendToClients(WorldServer world, BlockPos pos, BasePacket packet) // { // Chunk chunk = world.getChunkFromBlockCoords(pos); // for (EntityPlayer player : world.playerEntities) // { // if (!(player instanceof EntityPlayerMP)) // { // continue; // } // EntityPlayerMP playerMP = (EntityPlayerMP) player; // if (world.getPlayerChunkMap().isPlayerWatchingChunk(playerMP, chunk.x, chunk.z)) // { // // LogHelper.info("Sending packet to: " + player.getName()); // TMGNetwork.sendTo(packet, playerMP); // } // } // } // }
import java.util.ArrayList; import java.util.List; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.annotation.ParametersAreNonnullByDefault; import com.m4thg33k.tombmanygraves.network.GraveRenderTogglePacket; import com.m4thg33k.tombmanygraves.network.TMGNetwork; import net.minecraft.command.CommandException; import net.minecraft.command.ICommandSender; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.server.MinecraftServer; import net.minecraft.util.math.BlockPos;
package com.m4thg33k.tombmanygraves.commands; public class CommandToggleRender extends CommandBase { public CommandToggleRender() { super("tmg_toggle_render", 0, true); } @Override @Nonnull @ParametersAreNonnullByDefault public String getUsage(ICommandSender sender) { return COMMAND_NAME; } @Override @ParametersAreNonnullByDefault public void execute(MinecraftServer server, ICommandSender sender, String[] args) throws CommandException { if (!(sender instanceof EntityPlayerMP)) { return; }
// Path: src/main/java/com/m4thg33k/tombmanygraves/network/GraveRenderTogglePacket.java // public class GraveRenderTogglePacket extends BaseThreadsafePacket { // // public GraveRenderTogglePacket() // { // // } // // @Override // public void handleClientSafe(NetHandlerPlayClient netHandler) { // TombManyGraves.proxy.toggleGraveRendering(); // } // // @Override // public void handleServerSafe(NetHandlerPlayServer netHandler) { // LogHelper.error("Attempting to handle rendering packet on server!"); // } // // @Override // public void fromBytes(ByteBuf buf) { // // } // // @Override // public void toBytes(ByteBuf buf) { // // } // } // // Path: src/main/java/com/m4thg33k/tombmanygraves/network/TMGNetwork.java // public class TMGNetwork { // // public static TMGNetwork instance = new TMGNetwork(); // // public final SimpleNetworkWrapper network; // protected final BasePacketHandler handler; // private int id = 0; // // public TMGNetwork(){ // network = NetworkRegistry.INSTANCE.newSimpleChannel(Names.MODID); // handler = new BasePacketHandler(); // } // // public void registerPacket(Class<? extends BasePacket> packetClass) // { // registerPacketClient(packetClass); // registerPacketServer(packetClass); // } // // public static void registerPacketClient(Class<? extends BasePacket> packetClass) // { // registerPacketImp(packetClass, Side.CLIENT); // } // // public static void registerPacketServer(Class<? extends BasePacket> packetClass) // { // registerPacketImp(packetClass, Side.SERVER); // } // // public static void registerPacketImp(Class<? extends BasePacket> packetClass, Side side) // { // instance.network.registerMessage(instance.handler, packetClass, instance.id++, side); // } // // public static void setup() // { // //register packets here // registerPacketServer(PacketProbeFiles.class); // registerPacketClient(GraveRenderTogglePacket.class); // registerPacketClient(GravePosTogglePacket.class); // } // // public static void sendToAll(BasePacket packet) // { // instance.network.sendToAll(packet); // } // // public static void sendTo(BasePacket packet, EntityPlayerMP player) // { // instance.network.sendTo(packet, player); // } // // public static void sendToAllAround(BasePacket packet, NetworkRegistry.TargetPoint point) // { // instance.network.sendToAllAround(packet, point); // } // // public static void sendToDimension(BasePacket packet, int dimensionID) // { // instance.network.sendToDimension(packet, dimensionID); // } // // public static void sendToServer(BasePacket packet) // { // instance.network.sendToServer(packet); // } // // public static void sendToClients(WorldServer world, BlockPos pos, BasePacket packet) // { // Chunk chunk = world.getChunkFromBlockCoords(pos); // for (EntityPlayer player : world.playerEntities) // { // if (!(player instanceof EntityPlayerMP)) // { // continue; // } // EntityPlayerMP playerMP = (EntityPlayerMP) player; // if (world.getPlayerChunkMap().isPlayerWatchingChunk(playerMP, chunk.x, chunk.z)) // { // // LogHelper.info("Sending packet to: " + player.getName()); // TMGNetwork.sendTo(packet, playerMP); // } // } // } // } // Path: src/main/java/com/m4thg33k/tombmanygraves/commands/CommandToggleRender.java import java.util.ArrayList; import java.util.List; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.annotation.ParametersAreNonnullByDefault; import com.m4thg33k.tombmanygraves.network.GraveRenderTogglePacket; import com.m4thg33k.tombmanygraves.network.TMGNetwork; import net.minecraft.command.CommandException; import net.minecraft.command.ICommandSender; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.server.MinecraftServer; import net.minecraft.util.math.BlockPos; package com.m4thg33k.tombmanygraves.commands; public class CommandToggleRender extends CommandBase { public CommandToggleRender() { super("tmg_toggle_render", 0, true); } @Override @Nonnull @ParametersAreNonnullByDefault public String getUsage(ICommandSender sender) { return COMMAND_NAME; } @Override @ParametersAreNonnullByDefault public void execute(MinecraftServer server, ICommandSender sender, String[] args) throws CommandException { if (!(sender instanceof EntityPlayerMP)) { return; }
TMGNetwork.sendTo(new GraveRenderTogglePacket(), (EntityPlayerMP)sender);
M4thG33k/TombManyGraves2
src/main/java/com/m4thg33k/tombmanygraves/commands/CommandToggleRender.java
// Path: src/main/java/com/m4thg33k/tombmanygraves/network/GraveRenderTogglePacket.java // public class GraveRenderTogglePacket extends BaseThreadsafePacket { // // public GraveRenderTogglePacket() // { // // } // // @Override // public void handleClientSafe(NetHandlerPlayClient netHandler) { // TombManyGraves.proxy.toggleGraveRendering(); // } // // @Override // public void handleServerSafe(NetHandlerPlayServer netHandler) { // LogHelper.error("Attempting to handle rendering packet on server!"); // } // // @Override // public void fromBytes(ByteBuf buf) { // // } // // @Override // public void toBytes(ByteBuf buf) { // // } // } // // Path: src/main/java/com/m4thg33k/tombmanygraves/network/TMGNetwork.java // public class TMGNetwork { // // public static TMGNetwork instance = new TMGNetwork(); // // public final SimpleNetworkWrapper network; // protected final BasePacketHandler handler; // private int id = 0; // // public TMGNetwork(){ // network = NetworkRegistry.INSTANCE.newSimpleChannel(Names.MODID); // handler = new BasePacketHandler(); // } // // public void registerPacket(Class<? extends BasePacket> packetClass) // { // registerPacketClient(packetClass); // registerPacketServer(packetClass); // } // // public static void registerPacketClient(Class<? extends BasePacket> packetClass) // { // registerPacketImp(packetClass, Side.CLIENT); // } // // public static void registerPacketServer(Class<? extends BasePacket> packetClass) // { // registerPacketImp(packetClass, Side.SERVER); // } // // public static void registerPacketImp(Class<? extends BasePacket> packetClass, Side side) // { // instance.network.registerMessage(instance.handler, packetClass, instance.id++, side); // } // // public static void setup() // { // //register packets here // registerPacketServer(PacketProbeFiles.class); // registerPacketClient(GraveRenderTogglePacket.class); // registerPacketClient(GravePosTogglePacket.class); // } // // public static void sendToAll(BasePacket packet) // { // instance.network.sendToAll(packet); // } // // public static void sendTo(BasePacket packet, EntityPlayerMP player) // { // instance.network.sendTo(packet, player); // } // // public static void sendToAllAround(BasePacket packet, NetworkRegistry.TargetPoint point) // { // instance.network.sendToAllAround(packet, point); // } // // public static void sendToDimension(BasePacket packet, int dimensionID) // { // instance.network.sendToDimension(packet, dimensionID); // } // // public static void sendToServer(BasePacket packet) // { // instance.network.sendToServer(packet); // } // // public static void sendToClients(WorldServer world, BlockPos pos, BasePacket packet) // { // Chunk chunk = world.getChunkFromBlockCoords(pos); // for (EntityPlayer player : world.playerEntities) // { // if (!(player instanceof EntityPlayerMP)) // { // continue; // } // EntityPlayerMP playerMP = (EntityPlayerMP) player; // if (world.getPlayerChunkMap().isPlayerWatchingChunk(playerMP, chunk.x, chunk.z)) // { // // LogHelper.info("Sending packet to: " + player.getName()); // TMGNetwork.sendTo(packet, playerMP); // } // } // } // }
import java.util.ArrayList; import java.util.List; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.annotation.ParametersAreNonnullByDefault; import com.m4thg33k.tombmanygraves.network.GraveRenderTogglePacket; import com.m4thg33k.tombmanygraves.network.TMGNetwork; import net.minecraft.command.CommandException; import net.minecraft.command.ICommandSender; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.server.MinecraftServer; import net.minecraft.util.math.BlockPos;
package com.m4thg33k.tombmanygraves.commands; public class CommandToggleRender extends CommandBase { public CommandToggleRender() { super("tmg_toggle_render", 0, true); } @Override @Nonnull @ParametersAreNonnullByDefault public String getUsage(ICommandSender sender) { return COMMAND_NAME; } @Override @ParametersAreNonnullByDefault public void execute(MinecraftServer server, ICommandSender sender, String[] args) throws CommandException { if (!(sender instanceof EntityPlayerMP)) { return; }
// Path: src/main/java/com/m4thg33k/tombmanygraves/network/GraveRenderTogglePacket.java // public class GraveRenderTogglePacket extends BaseThreadsafePacket { // // public GraveRenderTogglePacket() // { // // } // // @Override // public void handleClientSafe(NetHandlerPlayClient netHandler) { // TombManyGraves.proxy.toggleGraveRendering(); // } // // @Override // public void handleServerSafe(NetHandlerPlayServer netHandler) { // LogHelper.error("Attempting to handle rendering packet on server!"); // } // // @Override // public void fromBytes(ByteBuf buf) { // // } // // @Override // public void toBytes(ByteBuf buf) { // // } // } // // Path: src/main/java/com/m4thg33k/tombmanygraves/network/TMGNetwork.java // public class TMGNetwork { // // public static TMGNetwork instance = new TMGNetwork(); // // public final SimpleNetworkWrapper network; // protected final BasePacketHandler handler; // private int id = 0; // // public TMGNetwork(){ // network = NetworkRegistry.INSTANCE.newSimpleChannel(Names.MODID); // handler = new BasePacketHandler(); // } // // public void registerPacket(Class<? extends BasePacket> packetClass) // { // registerPacketClient(packetClass); // registerPacketServer(packetClass); // } // // public static void registerPacketClient(Class<? extends BasePacket> packetClass) // { // registerPacketImp(packetClass, Side.CLIENT); // } // // public static void registerPacketServer(Class<? extends BasePacket> packetClass) // { // registerPacketImp(packetClass, Side.SERVER); // } // // public static void registerPacketImp(Class<? extends BasePacket> packetClass, Side side) // { // instance.network.registerMessage(instance.handler, packetClass, instance.id++, side); // } // // public static void setup() // { // //register packets here // registerPacketServer(PacketProbeFiles.class); // registerPacketClient(GraveRenderTogglePacket.class); // registerPacketClient(GravePosTogglePacket.class); // } // // public static void sendToAll(BasePacket packet) // { // instance.network.sendToAll(packet); // } // // public static void sendTo(BasePacket packet, EntityPlayerMP player) // { // instance.network.sendTo(packet, player); // } // // public static void sendToAllAround(BasePacket packet, NetworkRegistry.TargetPoint point) // { // instance.network.sendToAllAround(packet, point); // } // // public static void sendToDimension(BasePacket packet, int dimensionID) // { // instance.network.sendToDimension(packet, dimensionID); // } // // public static void sendToServer(BasePacket packet) // { // instance.network.sendToServer(packet); // } // // public static void sendToClients(WorldServer world, BlockPos pos, BasePacket packet) // { // Chunk chunk = world.getChunkFromBlockCoords(pos); // for (EntityPlayer player : world.playerEntities) // { // if (!(player instanceof EntityPlayerMP)) // { // continue; // } // EntityPlayerMP playerMP = (EntityPlayerMP) player; // if (world.getPlayerChunkMap().isPlayerWatchingChunk(playerMP, chunk.x, chunk.z)) // { // // LogHelper.info("Sending packet to: " + player.getName()); // TMGNetwork.sendTo(packet, playerMP); // } // } // } // } // Path: src/main/java/com/m4thg33k/tombmanygraves/commands/CommandToggleRender.java import java.util.ArrayList; import java.util.List; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.annotation.ParametersAreNonnullByDefault; import com.m4thg33k.tombmanygraves.network.GraveRenderTogglePacket; import com.m4thg33k.tombmanygraves.network.TMGNetwork; import net.minecraft.command.CommandException; import net.minecraft.command.ICommandSender; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.server.MinecraftServer; import net.minecraft.util.math.BlockPos; package com.m4thg33k.tombmanygraves.commands; public class CommandToggleRender extends CommandBase { public CommandToggleRender() { super("tmg_toggle_render", 0, true); } @Override @Nonnull @ParametersAreNonnullByDefault public String getUsage(ICommandSender sender) { return COMMAND_NAME; } @Override @ParametersAreNonnullByDefault public void execute(MinecraftServer server, ICommandSender sender, String[] args) throws CommandException { if (!(sender instanceof EntityPlayerMP)) { return; }
TMGNetwork.sendTo(new GraveRenderTogglePacket(), (EntityPlayerMP)sender);
M4thG33k/TombManyGraves2
src/main/java/com/m4thg33k/tombmanygraves/client/gui/ModBaseContainerGui.java
// Path: src/main/java/com/m4thg33k/tombmanygraves/Names.java // public class Names { // public static final String MODID = "tombmanygraves"; // public static final String VERSION = "999"; // public static final String MODNAME = "TombManyGraves"; // // public static final String GRAVE_BLOCK = "grave_block"; // public static final String ITEM_FILE_CONTROL = "item_file_control"; // public static final String DEATH_LIST = "death_list"; // // public static final String BLOCK_PATH = MODID + ":blocks/"; // public static final String BLOCK_MODEL_PATH = MODID + ":models/block/"; // // }
import com.m4thg33k.tombmanygraves.Names; import net.minecraft.client.gui.inventory.GuiContainer; import net.minecraft.inventory.Container; import net.minecraft.util.ResourceLocation;
package com.m4thg33k.tombmanygraves.client.gui; public class ModBaseContainerGui extends GuiContainer { public ModBaseContainerGui(int xSize, int ySize, Container container) { super(container); this.xSize = xSize; this.ySize = ySize; } @Override protected void drawGuiContainerBackgroundLayer(float partialTicks, int mouseX, int mouseY) { } public void bindTexture(String filename) {
// Path: src/main/java/com/m4thg33k/tombmanygraves/Names.java // public class Names { // public static final String MODID = "tombmanygraves"; // public static final String VERSION = "999"; // public static final String MODNAME = "TombManyGraves"; // // public static final String GRAVE_BLOCK = "grave_block"; // public static final String ITEM_FILE_CONTROL = "item_file_control"; // public static final String DEATH_LIST = "death_list"; // // public static final String BLOCK_PATH = MODID + ":blocks/"; // public static final String BLOCK_MODEL_PATH = MODID + ":models/block/"; // // } // Path: src/main/java/com/m4thg33k/tombmanygraves/client/gui/ModBaseContainerGui.java import com.m4thg33k.tombmanygraves.Names; import net.minecraft.client.gui.inventory.GuiContainer; import net.minecraft.inventory.Container; import net.minecraft.util.ResourceLocation; package com.m4thg33k.tombmanygraves.client.gui; public class ModBaseContainerGui extends GuiContainer { public ModBaseContainerGui(int xSize, int ySize, Container container) { super(container); this.xSize = xSize; this.ySize = ySize; } @Override protected void drawGuiContainerBackgroundLayer(float partialTicks, int mouseX, int mouseY) { } public void bindTexture(String filename) {
bindTexture(Names.MODID, filename);
M4thG33k/TombManyGraves2
src/main/java/com/m4thg33k/tombmanygraves/tiles/ModTiles.java
// Path: src/main/java/com/m4thg33k/tombmanygraves/Names.java // public class Names { // public static final String MODID = "tombmanygraves"; // public static final String VERSION = "999"; // public static final String MODNAME = "TombManyGraves"; // // public static final String GRAVE_BLOCK = "grave_block"; // public static final String ITEM_FILE_CONTROL = "item_file_control"; // public static final String DEATH_LIST = "death_list"; // // public static final String BLOCK_PATH = MODID + ":blocks/"; // public static final String BLOCK_MODEL_PATH = MODID + ":models/block/"; // // }
import com.m4thg33k.tombmanygraves.Names; import net.minecraftforge.fml.common.registry.GameRegistry;
package com.m4thg33k.tombmanygraves.tiles; public class ModTiles { @SuppressWarnings("deprecation") public static void init() {
// Path: src/main/java/com/m4thg33k/tombmanygraves/Names.java // public class Names { // public static final String MODID = "tombmanygraves"; // public static final String VERSION = "999"; // public static final String MODNAME = "TombManyGraves"; // // public static final String GRAVE_BLOCK = "grave_block"; // public static final String ITEM_FILE_CONTROL = "item_file_control"; // public static final String DEATH_LIST = "death_list"; // // public static final String BLOCK_PATH = MODID + ":blocks/"; // public static final String BLOCK_MODEL_PATH = MODID + ":models/block/"; // // } // Path: src/main/java/com/m4thg33k/tombmanygraves/tiles/ModTiles.java import com.m4thg33k.tombmanygraves.Names; import net.minecraftforge.fml.common.registry.GameRegistry; package com.m4thg33k.tombmanygraves.tiles; public class ModTiles { @SuppressWarnings("deprecation") public static void init() {
String prefix = "tile." + Names.MODID;
M4thG33k/TombManyGraves2
src/main/java/com/m4thg33k/tombmanygraves/network/GraveRenderTogglePacket.java
// Path: src/main/java/com/m4thg33k/tombmanygraves/TombManyGraves.java // @Mod(modid = Names.MODID, name = Names.MODNAME, version = Names.VERSION, dependencies = TombManyGraves.DEPENDENCIES) // public class TombManyGraves { // // public static final String DEPENDENCIES = "required-after:forge@[14.23.3.2655,)"; // private static Set<ASMData> moduleASM; // // @Mod.Instance // public static TombManyGraves INSTANCE = new TombManyGraves(); // // @SidedProxy(clientSide = "com.m4thg33k.tombmanygraves.proxy.ClientProxy", serverSide = "com.m4thg33k.tombmanygraves.proxy.ServerProxy") // public static CommonProxy proxy; // // @Mod.EventHandler // public void preInit(FMLPreInitializationEvent e) { // proxy.preinit(e); // moduleASM = e.getAsmData().getAll(GraveRegistry.class.getName()); // } // // @Mod.EventHandler // public void init(FMLInitializationEvent e) { // proxy.init(e); // for (ASMData data : moduleASM) { // try { // Class<?> c = Class.forName(data.getClassName()); // if (IGraveInventory.class.isAssignableFrom(c)) { // Map<String, Object> annotation = data.getAnnotationInfo(); // String reqMod = (String) annotation.get("reqMod"); // if (reqMod == null || Loader.isModLoaded(reqMod)){ // GraveInventoryManager.getInstance().registerListener((IGraveInventory) c.newInstance(), annotation); // } // } // } catch (Exception ex) { // ex.printStackTrace(); // } // } // } // // @Mod.EventHandler // public void postinit(FMLPostInitializationEvent e) { // proxy.postinit(e); // // // Make sure to finalize the listeners so the mod actually works... // GraveInventoryManager.getInstance().finalizeListeners(); // } // // @Mod.EventHandler // public void serverLoad(FMLServerStartingEvent event) { // ModCommands.initCommands(event); // } // } // // Path: src/main/java/com/m4thg33k/tombmanygraves/util/LogHelper.java // public class LogHelper { // // private static final Logger LOGGER = LogManager.getLogger(Names.MODID); // // public static void log(Level logLevel, Object object) // { // LOGGER.log(logLevel, "[" + Names.MODNAME + "]: " + String.valueOf(object)); // } // // public static void all(Object object) // { // log(Level.ALL, object); // } // // public static void debug(Object object) // { // log(Level.DEBUG, object); // } // // public static void error(Object object) // { // log(Level.ERROR, object); // } // // public static void fatal(Object object) // { // log(Level.FATAL, object); // } // // public static void info(Object object) // { // log(Level.INFO, object); // } // // public static void off(Object object) // { // log(Level.OFF, object); // } // // public static void trace(Object object) // { // log(Level.TRACE, object); // } // // public static void warn(Object object) // { // log(Level.WARN, object); // } // }
import com.m4thg33k.tombmanygraves.TombManyGraves; import com.m4thg33k.tombmanygraves.util.LogHelper; import io.netty.buffer.ByteBuf; import net.minecraft.client.network.NetHandlerPlayClient; import net.minecraft.network.NetHandlerPlayServer;
package com.m4thg33k.tombmanygraves.network; public class GraveRenderTogglePacket extends BaseThreadsafePacket { public GraveRenderTogglePacket() { } @Override public void handleClientSafe(NetHandlerPlayClient netHandler) {
// Path: src/main/java/com/m4thg33k/tombmanygraves/TombManyGraves.java // @Mod(modid = Names.MODID, name = Names.MODNAME, version = Names.VERSION, dependencies = TombManyGraves.DEPENDENCIES) // public class TombManyGraves { // // public static final String DEPENDENCIES = "required-after:forge@[14.23.3.2655,)"; // private static Set<ASMData> moduleASM; // // @Mod.Instance // public static TombManyGraves INSTANCE = new TombManyGraves(); // // @SidedProxy(clientSide = "com.m4thg33k.tombmanygraves.proxy.ClientProxy", serverSide = "com.m4thg33k.tombmanygraves.proxy.ServerProxy") // public static CommonProxy proxy; // // @Mod.EventHandler // public void preInit(FMLPreInitializationEvent e) { // proxy.preinit(e); // moduleASM = e.getAsmData().getAll(GraveRegistry.class.getName()); // } // // @Mod.EventHandler // public void init(FMLInitializationEvent e) { // proxy.init(e); // for (ASMData data : moduleASM) { // try { // Class<?> c = Class.forName(data.getClassName()); // if (IGraveInventory.class.isAssignableFrom(c)) { // Map<String, Object> annotation = data.getAnnotationInfo(); // String reqMod = (String) annotation.get("reqMod"); // if (reqMod == null || Loader.isModLoaded(reqMod)){ // GraveInventoryManager.getInstance().registerListener((IGraveInventory) c.newInstance(), annotation); // } // } // } catch (Exception ex) { // ex.printStackTrace(); // } // } // } // // @Mod.EventHandler // public void postinit(FMLPostInitializationEvent e) { // proxy.postinit(e); // // // Make sure to finalize the listeners so the mod actually works... // GraveInventoryManager.getInstance().finalizeListeners(); // } // // @Mod.EventHandler // public void serverLoad(FMLServerStartingEvent event) { // ModCommands.initCommands(event); // } // } // // Path: src/main/java/com/m4thg33k/tombmanygraves/util/LogHelper.java // public class LogHelper { // // private static final Logger LOGGER = LogManager.getLogger(Names.MODID); // // public static void log(Level logLevel, Object object) // { // LOGGER.log(logLevel, "[" + Names.MODNAME + "]: " + String.valueOf(object)); // } // // public static void all(Object object) // { // log(Level.ALL, object); // } // // public static void debug(Object object) // { // log(Level.DEBUG, object); // } // // public static void error(Object object) // { // log(Level.ERROR, object); // } // // public static void fatal(Object object) // { // log(Level.FATAL, object); // } // // public static void info(Object object) // { // log(Level.INFO, object); // } // // public static void off(Object object) // { // log(Level.OFF, object); // } // // public static void trace(Object object) // { // log(Level.TRACE, object); // } // // public static void warn(Object object) // { // log(Level.WARN, object); // } // } // Path: src/main/java/com/m4thg33k/tombmanygraves/network/GraveRenderTogglePacket.java import com.m4thg33k.tombmanygraves.TombManyGraves; import com.m4thg33k.tombmanygraves.util.LogHelper; import io.netty.buffer.ByteBuf; import net.minecraft.client.network.NetHandlerPlayClient; import net.minecraft.network.NetHandlerPlayServer; package com.m4thg33k.tombmanygraves.network; public class GraveRenderTogglePacket extends BaseThreadsafePacket { public GraveRenderTogglePacket() { } @Override public void handleClientSafe(NetHandlerPlayClient netHandler) {
TombManyGraves.proxy.toggleGraveRendering();
M4thG33k/TombManyGraves2
src/main/java/com/m4thg33k/tombmanygraves/network/GraveRenderTogglePacket.java
// Path: src/main/java/com/m4thg33k/tombmanygraves/TombManyGraves.java // @Mod(modid = Names.MODID, name = Names.MODNAME, version = Names.VERSION, dependencies = TombManyGraves.DEPENDENCIES) // public class TombManyGraves { // // public static final String DEPENDENCIES = "required-after:forge@[14.23.3.2655,)"; // private static Set<ASMData> moduleASM; // // @Mod.Instance // public static TombManyGraves INSTANCE = new TombManyGraves(); // // @SidedProxy(clientSide = "com.m4thg33k.tombmanygraves.proxy.ClientProxy", serverSide = "com.m4thg33k.tombmanygraves.proxy.ServerProxy") // public static CommonProxy proxy; // // @Mod.EventHandler // public void preInit(FMLPreInitializationEvent e) { // proxy.preinit(e); // moduleASM = e.getAsmData().getAll(GraveRegistry.class.getName()); // } // // @Mod.EventHandler // public void init(FMLInitializationEvent e) { // proxy.init(e); // for (ASMData data : moduleASM) { // try { // Class<?> c = Class.forName(data.getClassName()); // if (IGraveInventory.class.isAssignableFrom(c)) { // Map<String, Object> annotation = data.getAnnotationInfo(); // String reqMod = (String) annotation.get("reqMod"); // if (reqMod == null || Loader.isModLoaded(reqMod)){ // GraveInventoryManager.getInstance().registerListener((IGraveInventory) c.newInstance(), annotation); // } // } // } catch (Exception ex) { // ex.printStackTrace(); // } // } // } // // @Mod.EventHandler // public void postinit(FMLPostInitializationEvent e) { // proxy.postinit(e); // // // Make sure to finalize the listeners so the mod actually works... // GraveInventoryManager.getInstance().finalizeListeners(); // } // // @Mod.EventHandler // public void serverLoad(FMLServerStartingEvent event) { // ModCommands.initCommands(event); // } // } // // Path: src/main/java/com/m4thg33k/tombmanygraves/util/LogHelper.java // public class LogHelper { // // private static final Logger LOGGER = LogManager.getLogger(Names.MODID); // // public static void log(Level logLevel, Object object) // { // LOGGER.log(logLevel, "[" + Names.MODNAME + "]: " + String.valueOf(object)); // } // // public static void all(Object object) // { // log(Level.ALL, object); // } // // public static void debug(Object object) // { // log(Level.DEBUG, object); // } // // public static void error(Object object) // { // log(Level.ERROR, object); // } // // public static void fatal(Object object) // { // log(Level.FATAL, object); // } // // public static void info(Object object) // { // log(Level.INFO, object); // } // // public static void off(Object object) // { // log(Level.OFF, object); // } // // public static void trace(Object object) // { // log(Level.TRACE, object); // } // // public static void warn(Object object) // { // log(Level.WARN, object); // } // }
import com.m4thg33k.tombmanygraves.TombManyGraves; import com.m4thg33k.tombmanygraves.util.LogHelper; import io.netty.buffer.ByteBuf; import net.minecraft.client.network.NetHandlerPlayClient; import net.minecraft.network.NetHandlerPlayServer;
package com.m4thg33k.tombmanygraves.network; public class GraveRenderTogglePacket extends BaseThreadsafePacket { public GraveRenderTogglePacket() { } @Override public void handleClientSafe(NetHandlerPlayClient netHandler) { TombManyGraves.proxy.toggleGraveRendering(); } @Override public void handleServerSafe(NetHandlerPlayServer netHandler) {
// Path: src/main/java/com/m4thg33k/tombmanygraves/TombManyGraves.java // @Mod(modid = Names.MODID, name = Names.MODNAME, version = Names.VERSION, dependencies = TombManyGraves.DEPENDENCIES) // public class TombManyGraves { // // public static final String DEPENDENCIES = "required-after:forge@[14.23.3.2655,)"; // private static Set<ASMData> moduleASM; // // @Mod.Instance // public static TombManyGraves INSTANCE = new TombManyGraves(); // // @SidedProxy(clientSide = "com.m4thg33k.tombmanygraves.proxy.ClientProxy", serverSide = "com.m4thg33k.tombmanygraves.proxy.ServerProxy") // public static CommonProxy proxy; // // @Mod.EventHandler // public void preInit(FMLPreInitializationEvent e) { // proxy.preinit(e); // moduleASM = e.getAsmData().getAll(GraveRegistry.class.getName()); // } // // @Mod.EventHandler // public void init(FMLInitializationEvent e) { // proxy.init(e); // for (ASMData data : moduleASM) { // try { // Class<?> c = Class.forName(data.getClassName()); // if (IGraveInventory.class.isAssignableFrom(c)) { // Map<String, Object> annotation = data.getAnnotationInfo(); // String reqMod = (String) annotation.get("reqMod"); // if (reqMod == null || Loader.isModLoaded(reqMod)){ // GraveInventoryManager.getInstance().registerListener((IGraveInventory) c.newInstance(), annotation); // } // } // } catch (Exception ex) { // ex.printStackTrace(); // } // } // } // // @Mod.EventHandler // public void postinit(FMLPostInitializationEvent e) { // proxy.postinit(e); // // // Make sure to finalize the listeners so the mod actually works... // GraveInventoryManager.getInstance().finalizeListeners(); // } // // @Mod.EventHandler // public void serverLoad(FMLServerStartingEvent event) { // ModCommands.initCommands(event); // } // } // // Path: src/main/java/com/m4thg33k/tombmanygraves/util/LogHelper.java // public class LogHelper { // // private static final Logger LOGGER = LogManager.getLogger(Names.MODID); // // public static void log(Level logLevel, Object object) // { // LOGGER.log(logLevel, "[" + Names.MODNAME + "]: " + String.valueOf(object)); // } // // public static void all(Object object) // { // log(Level.ALL, object); // } // // public static void debug(Object object) // { // log(Level.DEBUG, object); // } // // public static void error(Object object) // { // log(Level.ERROR, object); // } // // public static void fatal(Object object) // { // log(Level.FATAL, object); // } // // public static void info(Object object) // { // log(Level.INFO, object); // } // // public static void off(Object object) // { // log(Level.OFF, object); // } // // public static void trace(Object object) // { // log(Level.TRACE, object); // } // // public static void warn(Object object) // { // log(Level.WARN, object); // } // } // Path: src/main/java/com/m4thg33k/tombmanygraves/network/GraveRenderTogglePacket.java import com.m4thg33k.tombmanygraves.TombManyGraves; import com.m4thg33k.tombmanygraves.util.LogHelper; import io.netty.buffer.ByteBuf; import net.minecraft.client.network.NetHandlerPlayClient; import net.minecraft.network.NetHandlerPlayServer; package com.m4thg33k.tombmanygraves.network; public class GraveRenderTogglePacket extends BaseThreadsafePacket { public GraveRenderTogglePacket() { } @Override public void handleClientSafe(NetHandlerPlayClient netHandler) { TombManyGraves.proxy.toggleGraveRendering(); } @Override public void handleServerSafe(NetHandlerPlayServer netHandler) {
LogHelper.error("Attempting to handle rendering packet on server!");
M4thG33k/TombManyGraves2
src/main/java/com/m4thg33k/tombmanygraves/network/GravePosTogglePacket.java
// Path: src/main/java/com/m4thg33k/tombmanygraves/TombManyGraves.java // @Mod(modid = Names.MODID, name = Names.MODNAME, version = Names.VERSION, dependencies = TombManyGraves.DEPENDENCIES) // public class TombManyGraves { // // public static final String DEPENDENCIES = "required-after:forge@[14.23.3.2655,)"; // private static Set<ASMData> moduleASM; // // @Mod.Instance // public static TombManyGraves INSTANCE = new TombManyGraves(); // // @SidedProxy(clientSide = "com.m4thg33k.tombmanygraves.proxy.ClientProxy", serverSide = "com.m4thg33k.tombmanygraves.proxy.ServerProxy") // public static CommonProxy proxy; // // @Mod.EventHandler // public void preInit(FMLPreInitializationEvent e) { // proxy.preinit(e); // moduleASM = e.getAsmData().getAll(GraveRegistry.class.getName()); // } // // @Mod.EventHandler // public void init(FMLInitializationEvent e) { // proxy.init(e); // for (ASMData data : moduleASM) { // try { // Class<?> c = Class.forName(data.getClassName()); // if (IGraveInventory.class.isAssignableFrom(c)) { // Map<String, Object> annotation = data.getAnnotationInfo(); // String reqMod = (String) annotation.get("reqMod"); // if (reqMod == null || Loader.isModLoaded(reqMod)){ // GraveInventoryManager.getInstance().registerListener((IGraveInventory) c.newInstance(), annotation); // } // } // } catch (Exception ex) { // ex.printStackTrace(); // } // } // } // // @Mod.EventHandler // public void postinit(FMLPostInitializationEvent e) { // proxy.postinit(e); // // // Make sure to finalize the listeners so the mod actually works... // GraveInventoryManager.getInstance().finalizeListeners(); // } // // @Mod.EventHandler // public void serverLoad(FMLServerStartingEvent event) { // ModCommands.initCommands(event); // } // } // // Path: src/main/java/com/m4thg33k/tombmanygraves/util/LogHelper.java // public class LogHelper { // // private static final Logger LOGGER = LogManager.getLogger(Names.MODID); // // public static void log(Level logLevel, Object object) // { // LOGGER.log(logLevel, "[" + Names.MODNAME + "]: " + String.valueOf(object)); // } // // public static void all(Object object) // { // log(Level.ALL, object); // } // // public static void debug(Object object) // { // log(Level.DEBUG, object); // } // // public static void error(Object object) // { // log(Level.ERROR, object); // } // // public static void fatal(Object object) // { // log(Level.FATAL, object); // } // // public static void info(Object object) // { // log(Level.INFO, object); // } // // public static void off(Object object) // { // log(Level.OFF, object); // } // // public static void trace(Object object) // { // log(Level.TRACE, object); // } // // public static void warn(Object object) // { // log(Level.WARN, object); // } // }
import com.m4thg33k.tombmanygraves.TombManyGraves; import com.m4thg33k.tombmanygraves.util.LogHelper; import io.netty.buffer.ByteBuf; import net.minecraft.client.network.NetHandlerPlayClient; import net.minecraft.network.NetHandlerPlayServer;
package com.m4thg33k.tombmanygraves.network; public class GravePosTogglePacket extends BaseThreadsafePacket{ public GravePosTogglePacket() { } @Override public void handleClientSafe(NetHandlerPlayClient netHandler) {
// Path: src/main/java/com/m4thg33k/tombmanygraves/TombManyGraves.java // @Mod(modid = Names.MODID, name = Names.MODNAME, version = Names.VERSION, dependencies = TombManyGraves.DEPENDENCIES) // public class TombManyGraves { // // public static final String DEPENDENCIES = "required-after:forge@[14.23.3.2655,)"; // private static Set<ASMData> moduleASM; // // @Mod.Instance // public static TombManyGraves INSTANCE = new TombManyGraves(); // // @SidedProxy(clientSide = "com.m4thg33k.tombmanygraves.proxy.ClientProxy", serverSide = "com.m4thg33k.tombmanygraves.proxy.ServerProxy") // public static CommonProxy proxy; // // @Mod.EventHandler // public void preInit(FMLPreInitializationEvent e) { // proxy.preinit(e); // moduleASM = e.getAsmData().getAll(GraveRegistry.class.getName()); // } // // @Mod.EventHandler // public void init(FMLInitializationEvent e) { // proxy.init(e); // for (ASMData data : moduleASM) { // try { // Class<?> c = Class.forName(data.getClassName()); // if (IGraveInventory.class.isAssignableFrom(c)) { // Map<String, Object> annotation = data.getAnnotationInfo(); // String reqMod = (String) annotation.get("reqMod"); // if (reqMod == null || Loader.isModLoaded(reqMod)){ // GraveInventoryManager.getInstance().registerListener((IGraveInventory) c.newInstance(), annotation); // } // } // } catch (Exception ex) { // ex.printStackTrace(); // } // } // } // // @Mod.EventHandler // public void postinit(FMLPostInitializationEvent e) { // proxy.postinit(e); // // // Make sure to finalize the listeners so the mod actually works... // GraveInventoryManager.getInstance().finalizeListeners(); // } // // @Mod.EventHandler // public void serverLoad(FMLServerStartingEvent event) { // ModCommands.initCommands(event); // } // } // // Path: src/main/java/com/m4thg33k/tombmanygraves/util/LogHelper.java // public class LogHelper { // // private static final Logger LOGGER = LogManager.getLogger(Names.MODID); // // public static void log(Level logLevel, Object object) // { // LOGGER.log(logLevel, "[" + Names.MODNAME + "]: " + String.valueOf(object)); // } // // public static void all(Object object) // { // log(Level.ALL, object); // } // // public static void debug(Object object) // { // log(Level.DEBUG, object); // } // // public static void error(Object object) // { // log(Level.ERROR, object); // } // // public static void fatal(Object object) // { // log(Level.FATAL, object); // } // // public static void info(Object object) // { // log(Level.INFO, object); // } // // public static void off(Object object) // { // log(Level.OFF, object); // } // // public static void trace(Object object) // { // log(Level.TRACE, object); // } // // public static void warn(Object object) // { // log(Level.WARN, object); // } // } // Path: src/main/java/com/m4thg33k/tombmanygraves/network/GravePosTogglePacket.java import com.m4thg33k.tombmanygraves.TombManyGraves; import com.m4thg33k.tombmanygraves.util.LogHelper; import io.netty.buffer.ByteBuf; import net.minecraft.client.network.NetHandlerPlayClient; import net.minecraft.network.NetHandlerPlayServer; package com.m4thg33k.tombmanygraves.network; public class GravePosTogglePacket extends BaseThreadsafePacket{ public GravePosTogglePacket() { } @Override public void handleClientSafe(NetHandlerPlayClient netHandler) {
TombManyGraves.proxy.toggleGravePositionRendering();
M4thG33k/TombManyGraves2
src/main/java/com/m4thg33k/tombmanygraves/network/GravePosTogglePacket.java
// Path: src/main/java/com/m4thg33k/tombmanygraves/TombManyGraves.java // @Mod(modid = Names.MODID, name = Names.MODNAME, version = Names.VERSION, dependencies = TombManyGraves.DEPENDENCIES) // public class TombManyGraves { // // public static final String DEPENDENCIES = "required-after:forge@[14.23.3.2655,)"; // private static Set<ASMData> moduleASM; // // @Mod.Instance // public static TombManyGraves INSTANCE = new TombManyGraves(); // // @SidedProxy(clientSide = "com.m4thg33k.tombmanygraves.proxy.ClientProxy", serverSide = "com.m4thg33k.tombmanygraves.proxy.ServerProxy") // public static CommonProxy proxy; // // @Mod.EventHandler // public void preInit(FMLPreInitializationEvent e) { // proxy.preinit(e); // moduleASM = e.getAsmData().getAll(GraveRegistry.class.getName()); // } // // @Mod.EventHandler // public void init(FMLInitializationEvent e) { // proxy.init(e); // for (ASMData data : moduleASM) { // try { // Class<?> c = Class.forName(data.getClassName()); // if (IGraveInventory.class.isAssignableFrom(c)) { // Map<String, Object> annotation = data.getAnnotationInfo(); // String reqMod = (String) annotation.get("reqMod"); // if (reqMod == null || Loader.isModLoaded(reqMod)){ // GraveInventoryManager.getInstance().registerListener((IGraveInventory) c.newInstance(), annotation); // } // } // } catch (Exception ex) { // ex.printStackTrace(); // } // } // } // // @Mod.EventHandler // public void postinit(FMLPostInitializationEvent e) { // proxy.postinit(e); // // // Make sure to finalize the listeners so the mod actually works... // GraveInventoryManager.getInstance().finalizeListeners(); // } // // @Mod.EventHandler // public void serverLoad(FMLServerStartingEvent event) { // ModCommands.initCommands(event); // } // } // // Path: src/main/java/com/m4thg33k/tombmanygraves/util/LogHelper.java // public class LogHelper { // // private static final Logger LOGGER = LogManager.getLogger(Names.MODID); // // public static void log(Level logLevel, Object object) // { // LOGGER.log(logLevel, "[" + Names.MODNAME + "]: " + String.valueOf(object)); // } // // public static void all(Object object) // { // log(Level.ALL, object); // } // // public static void debug(Object object) // { // log(Level.DEBUG, object); // } // // public static void error(Object object) // { // log(Level.ERROR, object); // } // // public static void fatal(Object object) // { // log(Level.FATAL, object); // } // // public static void info(Object object) // { // log(Level.INFO, object); // } // // public static void off(Object object) // { // log(Level.OFF, object); // } // // public static void trace(Object object) // { // log(Level.TRACE, object); // } // // public static void warn(Object object) // { // log(Level.WARN, object); // } // }
import com.m4thg33k.tombmanygraves.TombManyGraves; import com.m4thg33k.tombmanygraves.util.LogHelper; import io.netty.buffer.ByteBuf; import net.minecraft.client.network.NetHandlerPlayClient; import net.minecraft.network.NetHandlerPlayServer;
package com.m4thg33k.tombmanygraves.network; public class GravePosTogglePacket extends BaseThreadsafePacket{ public GravePosTogglePacket() { } @Override public void handleClientSafe(NetHandlerPlayClient netHandler) { TombManyGraves.proxy.toggleGravePositionRendering(); } @Override public void handleServerSafe(NetHandlerPlayServer netHandler) {
// Path: src/main/java/com/m4thg33k/tombmanygraves/TombManyGraves.java // @Mod(modid = Names.MODID, name = Names.MODNAME, version = Names.VERSION, dependencies = TombManyGraves.DEPENDENCIES) // public class TombManyGraves { // // public static final String DEPENDENCIES = "required-after:forge@[14.23.3.2655,)"; // private static Set<ASMData> moduleASM; // // @Mod.Instance // public static TombManyGraves INSTANCE = new TombManyGraves(); // // @SidedProxy(clientSide = "com.m4thg33k.tombmanygraves.proxy.ClientProxy", serverSide = "com.m4thg33k.tombmanygraves.proxy.ServerProxy") // public static CommonProxy proxy; // // @Mod.EventHandler // public void preInit(FMLPreInitializationEvent e) { // proxy.preinit(e); // moduleASM = e.getAsmData().getAll(GraveRegistry.class.getName()); // } // // @Mod.EventHandler // public void init(FMLInitializationEvent e) { // proxy.init(e); // for (ASMData data : moduleASM) { // try { // Class<?> c = Class.forName(data.getClassName()); // if (IGraveInventory.class.isAssignableFrom(c)) { // Map<String, Object> annotation = data.getAnnotationInfo(); // String reqMod = (String) annotation.get("reqMod"); // if (reqMod == null || Loader.isModLoaded(reqMod)){ // GraveInventoryManager.getInstance().registerListener((IGraveInventory) c.newInstance(), annotation); // } // } // } catch (Exception ex) { // ex.printStackTrace(); // } // } // } // // @Mod.EventHandler // public void postinit(FMLPostInitializationEvent e) { // proxy.postinit(e); // // // Make sure to finalize the listeners so the mod actually works... // GraveInventoryManager.getInstance().finalizeListeners(); // } // // @Mod.EventHandler // public void serverLoad(FMLServerStartingEvent event) { // ModCommands.initCommands(event); // } // } // // Path: src/main/java/com/m4thg33k/tombmanygraves/util/LogHelper.java // public class LogHelper { // // private static final Logger LOGGER = LogManager.getLogger(Names.MODID); // // public static void log(Level logLevel, Object object) // { // LOGGER.log(logLevel, "[" + Names.MODNAME + "]: " + String.valueOf(object)); // } // // public static void all(Object object) // { // log(Level.ALL, object); // } // // public static void debug(Object object) // { // log(Level.DEBUG, object); // } // // public static void error(Object object) // { // log(Level.ERROR, object); // } // // public static void fatal(Object object) // { // log(Level.FATAL, object); // } // // public static void info(Object object) // { // log(Level.INFO, object); // } // // public static void off(Object object) // { // log(Level.OFF, object); // } // // public static void trace(Object object) // { // log(Level.TRACE, object); // } // // public static void warn(Object object) // { // log(Level.WARN, object); // } // } // Path: src/main/java/com/m4thg33k/tombmanygraves/network/GravePosTogglePacket.java import com.m4thg33k.tombmanygraves.TombManyGraves; import com.m4thg33k.tombmanygraves.util.LogHelper; import io.netty.buffer.ByteBuf; import net.minecraft.client.network.NetHandlerPlayClient; import net.minecraft.network.NetHandlerPlayServer; package com.m4thg33k.tombmanygraves.network; public class GravePosTogglePacket extends BaseThreadsafePacket{ public GravePosTogglePacket() { } @Override public void handleClientSafe(NetHandlerPlayClient netHandler) { TombManyGraves.proxy.toggleGravePositionRendering(); } @Override public void handleServerSafe(NetHandlerPlayServer netHandler) {
LogHelper.error("Attempting to handle rendering packet on server!");
M4thG33k/TombManyGraves2
src/main/java/com/m4thg33k/tombmanygraves/client/render/ItemRenderRegister.java
// Path: src/main/java/com/m4thg33k/tombmanygraves/blocks/ModBlocks.java // public class ModBlocks { // // public static BlockGrave blockGrave = new BlockGrave(); // // public static void preInit() // { // ForgeRegistries.BLOCKS.register(blockGrave); // } // } // // Path: src/main/java/com/m4thg33k/tombmanygraves/items/ModItems.java // public class ModItems { // // // public static ItemFileControl itemFileControl = new ItemFileControl(); // public static ItemDeathList itemDeathList = new ItemDeathList(); // // public static void createItems() // { // // GameRegistry.register(itemFileControl); // ForgeRegistries.ITEMS.register(itemDeathList); // } // }
import com.m4thg33k.tombmanygraves.blocks.ModBlocks; import com.m4thg33k.tombmanygraves.items.ModItems; import net.minecraft.client.renderer.ItemModelMesher; import net.minecraft.client.renderer.block.model.ModelResourceLocation; import net.minecraft.item.Item; import net.minecraftforge.client.model.ModelLoader; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly;
package com.m4thg33k.tombmanygraves.client.render; public final class ItemRenderRegister { @SideOnly(Side.CLIENT) public static void initClient(ItemModelMesher mesher) {
// Path: src/main/java/com/m4thg33k/tombmanygraves/blocks/ModBlocks.java // public class ModBlocks { // // public static BlockGrave blockGrave = new BlockGrave(); // // public static void preInit() // { // ForgeRegistries.BLOCKS.register(blockGrave); // } // } // // Path: src/main/java/com/m4thg33k/tombmanygraves/items/ModItems.java // public class ModItems { // // // public static ItemFileControl itemFileControl = new ItemFileControl(); // public static ItemDeathList itemDeathList = new ItemDeathList(); // // public static void createItems() // { // // GameRegistry.register(itemFileControl); // ForgeRegistries.ITEMS.register(itemDeathList); // } // } // Path: src/main/java/com/m4thg33k/tombmanygraves/client/render/ItemRenderRegister.java import com.m4thg33k.tombmanygraves.blocks.ModBlocks; import com.m4thg33k.tombmanygraves.items.ModItems; import net.minecraft.client.renderer.ItemModelMesher; import net.minecraft.client.renderer.block.model.ModelResourceLocation; import net.minecraft.item.Item; import net.minecraftforge.client.model.ModelLoader; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; package com.m4thg33k.tombmanygraves.client.render; public final class ItemRenderRegister { @SideOnly(Side.CLIENT) public static void initClient(ItemModelMesher mesher) {
registerSingleModel(ModItems.itemDeathList, mesher);
M4thG33k/TombManyGraves2
src/main/java/com/m4thg33k/tombmanygraves/client/render/ItemRenderRegister.java
// Path: src/main/java/com/m4thg33k/tombmanygraves/blocks/ModBlocks.java // public class ModBlocks { // // public static BlockGrave blockGrave = new BlockGrave(); // // public static void preInit() // { // ForgeRegistries.BLOCKS.register(blockGrave); // } // } // // Path: src/main/java/com/m4thg33k/tombmanygraves/items/ModItems.java // public class ModItems { // // // public static ItemFileControl itemFileControl = new ItemFileControl(); // public static ItemDeathList itemDeathList = new ItemDeathList(); // // public static void createItems() // { // // GameRegistry.register(itemFileControl); // ForgeRegistries.ITEMS.register(itemDeathList); // } // }
import com.m4thg33k.tombmanygraves.blocks.ModBlocks; import com.m4thg33k.tombmanygraves.items.ModItems; import net.minecraft.client.renderer.ItemModelMesher; import net.minecraft.client.renderer.block.model.ModelResourceLocation; import net.minecraft.item.Item; import net.minecraftforge.client.model.ModelLoader; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly;
package com.m4thg33k.tombmanygraves.client.render; public final class ItemRenderRegister { @SideOnly(Side.CLIENT) public static void initClient(ItemModelMesher mesher) { registerSingleModel(ModItems.itemDeathList, mesher);
// Path: src/main/java/com/m4thg33k/tombmanygraves/blocks/ModBlocks.java // public class ModBlocks { // // public static BlockGrave blockGrave = new BlockGrave(); // // public static void preInit() // { // ForgeRegistries.BLOCKS.register(blockGrave); // } // } // // Path: src/main/java/com/m4thg33k/tombmanygraves/items/ModItems.java // public class ModItems { // // // public static ItemFileControl itemFileControl = new ItemFileControl(); // public static ItemDeathList itemDeathList = new ItemDeathList(); // // public static void createItems() // { // // GameRegistry.register(itemFileControl); // ForgeRegistries.ITEMS.register(itemDeathList); // } // } // Path: src/main/java/com/m4thg33k/tombmanygraves/client/render/ItemRenderRegister.java import com.m4thg33k.tombmanygraves.blocks.ModBlocks; import com.m4thg33k.tombmanygraves.items.ModItems; import net.minecraft.client.renderer.ItemModelMesher; import net.minecraft.client.renderer.block.model.ModelResourceLocation; import net.minecraft.item.Item; import net.minecraftforge.client.model.ModelLoader; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; package com.m4thg33k.tombmanygraves.client.render; public final class ItemRenderRegister { @SideOnly(Side.CLIENT) public static void initClient(ItemModelMesher mesher) { registerSingleModel(ModItems.itemDeathList, mesher);
registerSingleModel(Item.getItemFromBlock(ModBlocks.blockGrave), mesher);
M4thG33k/TombManyGraves2
src/main/java/com/m4thg33k/tombmanygraves/client/gui/ModBaseGui.java
// Path: src/main/java/com/m4thg33k/tombmanygraves/Names.java // public class Names { // public static final String MODID = "tombmanygraves"; // public static final String VERSION = "999"; // public static final String MODNAME = "TombManyGraves"; // // public static final String GRAVE_BLOCK = "grave_block"; // public static final String ITEM_FILE_CONTROL = "item_file_control"; // public static final String DEATH_LIST = "death_list"; // // public static final String BLOCK_PATH = MODID + ":blocks/"; // public static final String BLOCK_MODEL_PATH = MODID + ":models/block/"; // // }
import com.m4thg33k.tombmanygraves.Names; import net.minecraft.client.gui.GuiScreen; import net.minecraft.util.ResourceLocation;
package com.m4thg33k.tombmanygraves.client.gui; public class ModBaseGui extends GuiScreen{ protected int xSize; protected int ySize; public ModBaseGui(int xSize, int ySize) { this.xSize = xSize; this.ySize = ySize; } public void bindTexture(String filename) {
// Path: src/main/java/com/m4thg33k/tombmanygraves/Names.java // public class Names { // public static final String MODID = "tombmanygraves"; // public static final String VERSION = "999"; // public static final String MODNAME = "TombManyGraves"; // // public static final String GRAVE_BLOCK = "grave_block"; // public static final String ITEM_FILE_CONTROL = "item_file_control"; // public static final String DEATH_LIST = "death_list"; // // public static final String BLOCK_PATH = MODID + ":blocks/"; // public static final String BLOCK_MODEL_PATH = MODID + ":models/block/"; // // } // Path: src/main/java/com/m4thg33k/tombmanygraves/client/gui/ModBaseGui.java import com.m4thg33k.tombmanygraves.Names; import net.minecraft.client.gui.GuiScreen; import net.minecraft.util.ResourceLocation; package com.m4thg33k.tombmanygraves.client.gui; public class ModBaseGui extends GuiScreen{ protected int xSize; protected int ySize; public ModBaseGui(int xSize, int ySize) { this.xSize = xSize; this.ySize = ySize; } public void bindTexture(String filename) {
bindTexture(Names.MODID, filename);
M4thG33k/TombManyGraves2
src/main/java/com/m4thg33k/tombmanygraves/commands/CommandToggleGravePos.java
// Path: src/main/java/com/m4thg33k/tombmanygraves/network/GravePosTogglePacket.java // public class GravePosTogglePacket extends BaseThreadsafePacket{ // // public GravePosTogglePacket() // { // // } // // @Override // public void handleClientSafe(NetHandlerPlayClient netHandler) { // TombManyGraves.proxy.toggleGravePositionRendering(); // } // // @Override // public void handleServerSafe(NetHandlerPlayServer netHandler) { // // LogHelper.error("Attempting to handle rendering packet on server!"); // } // // @Override // public void fromBytes(ByteBuf buf) { // // } // // @Override // public void toBytes(ByteBuf buf) { // // } // } // // Path: src/main/java/com/m4thg33k/tombmanygraves/network/TMGNetwork.java // public class TMGNetwork { // // public static TMGNetwork instance = new TMGNetwork(); // // public final SimpleNetworkWrapper network; // protected final BasePacketHandler handler; // private int id = 0; // // public TMGNetwork(){ // network = NetworkRegistry.INSTANCE.newSimpleChannel(Names.MODID); // handler = new BasePacketHandler(); // } // // public void registerPacket(Class<? extends BasePacket> packetClass) // { // registerPacketClient(packetClass); // registerPacketServer(packetClass); // } // // public static void registerPacketClient(Class<? extends BasePacket> packetClass) // { // registerPacketImp(packetClass, Side.CLIENT); // } // // public static void registerPacketServer(Class<? extends BasePacket> packetClass) // { // registerPacketImp(packetClass, Side.SERVER); // } // // public static void registerPacketImp(Class<? extends BasePacket> packetClass, Side side) // { // instance.network.registerMessage(instance.handler, packetClass, instance.id++, side); // } // // public static void setup() // { // //register packets here // registerPacketServer(PacketProbeFiles.class); // registerPacketClient(GraveRenderTogglePacket.class); // registerPacketClient(GravePosTogglePacket.class); // } // // public static void sendToAll(BasePacket packet) // { // instance.network.sendToAll(packet); // } // // public static void sendTo(BasePacket packet, EntityPlayerMP player) // { // instance.network.sendTo(packet, player); // } // // public static void sendToAllAround(BasePacket packet, NetworkRegistry.TargetPoint point) // { // instance.network.sendToAllAround(packet, point); // } // // public static void sendToDimension(BasePacket packet, int dimensionID) // { // instance.network.sendToDimension(packet, dimensionID); // } // // public static void sendToServer(BasePacket packet) // { // instance.network.sendToServer(packet); // } // // public static void sendToClients(WorldServer world, BlockPos pos, BasePacket packet) // { // Chunk chunk = world.getChunkFromBlockCoords(pos); // for (EntityPlayer player : world.playerEntities) // { // if (!(player instanceof EntityPlayerMP)) // { // continue; // } // EntityPlayerMP playerMP = (EntityPlayerMP) player; // if (world.getPlayerChunkMap().isPlayerWatchingChunk(playerMP, chunk.x, chunk.z)) // { // // LogHelper.info("Sending packet to: " + player.getName()); // TMGNetwork.sendTo(packet, playerMP); // } // } // } // }
import java.util.ArrayList; import java.util.List; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.annotation.ParametersAreNonnullByDefault; import com.m4thg33k.tombmanygraves.network.GravePosTogglePacket; import com.m4thg33k.tombmanygraves.network.TMGNetwork; import net.minecraft.command.CommandException; import net.minecraft.command.ICommandSender; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.server.MinecraftServer; import net.minecraft.util.math.BlockPos;
package com.m4thg33k.tombmanygraves.commands; public class CommandToggleGravePos extends CommandBase { public CommandToggleGravePos() { super("tmg_toggle_grave_pos", 0, true); } @Override @Nonnull @ParametersAreNonnullByDefault public String getUsage(ICommandSender sender) { return COMMAND_NAME; } @Override @ParametersAreNonnullByDefault public void execute(MinecraftServer server, ICommandSender sender, String[] args) throws CommandException { if (!(sender instanceof EntityPlayerMP)) { return; }
// Path: src/main/java/com/m4thg33k/tombmanygraves/network/GravePosTogglePacket.java // public class GravePosTogglePacket extends BaseThreadsafePacket{ // // public GravePosTogglePacket() // { // // } // // @Override // public void handleClientSafe(NetHandlerPlayClient netHandler) { // TombManyGraves.proxy.toggleGravePositionRendering(); // } // // @Override // public void handleServerSafe(NetHandlerPlayServer netHandler) { // // LogHelper.error("Attempting to handle rendering packet on server!"); // } // // @Override // public void fromBytes(ByteBuf buf) { // // } // // @Override // public void toBytes(ByteBuf buf) { // // } // } // // Path: src/main/java/com/m4thg33k/tombmanygraves/network/TMGNetwork.java // public class TMGNetwork { // // public static TMGNetwork instance = new TMGNetwork(); // // public final SimpleNetworkWrapper network; // protected final BasePacketHandler handler; // private int id = 0; // // public TMGNetwork(){ // network = NetworkRegistry.INSTANCE.newSimpleChannel(Names.MODID); // handler = new BasePacketHandler(); // } // // public void registerPacket(Class<? extends BasePacket> packetClass) // { // registerPacketClient(packetClass); // registerPacketServer(packetClass); // } // // public static void registerPacketClient(Class<? extends BasePacket> packetClass) // { // registerPacketImp(packetClass, Side.CLIENT); // } // // public static void registerPacketServer(Class<? extends BasePacket> packetClass) // { // registerPacketImp(packetClass, Side.SERVER); // } // // public static void registerPacketImp(Class<? extends BasePacket> packetClass, Side side) // { // instance.network.registerMessage(instance.handler, packetClass, instance.id++, side); // } // // public static void setup() // { // //register packets here // registerPacketServer(PacketProbeFiles.class); // registerPacketClient(GraveRenderTogglePacket.class); // registerPacketClient(GravePosTogglePacket.class); // } // // public static void sendToAll(BasePacket packet) // { // instance.network.sendToAll(packet); // } // // public static void sendTo(BasePacket packet, EntityPlayerMP player) // { // instance.network.sendTo(packet, player); // } // // public static void sendToAllAround(BasePacket packet, NetworkRegistry.TargetPoint point) // { // instance.network.sendToAllAround(packet, point); // } // // public static void sendToDimension(BasePacket packet, int dimensionID) // { // instance.network.sendToDimension(packet, dimensionID); // } // // public static void sendToServer(BasePacket packet) // { // instance.network.sendToServer(packet); // } // // public static void sendToClients(WorldServer world, BlockPos pos, BasePacket packet) // { // Chunk chunk = world.getChunkFromBlockCoords(pos); // for (EntityPlayer player : world.playerEntities) // { // if (!(player instanceof EntityPlayerMP)) // { // continue; // } // EntityPlayerMP playerMP = (EntityPlayerMP) player; // if (world.getPlayerChunkMap().isPlayerWatchingChunk(playerMP, chunk.x, chunk.z)) // { // // LogHelper.info("Sending packet to: " + player.getName()); // TMGNetwork.sendTo(packet, playerMP); // } // } // } // } // Path: src/main/java/com/m4thg33k/tombmanygraves/commands/CommandToggleGravePos.java import java.util.ArrayList; import java.util.List; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.annotation.ParametersAreNonnullByDefault; import com.m4thg33k.tombmanygraves.network.GravePosTogglePacket; import com.m4thg33k.tombmanygraves.network.TMGNetwork; import net.minecraft.command.CommandException; import net.minecraft.command.ICommandSender; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.server.MinecraftServer; import net.minecraft.util.math.BlockPos; package com.m4thg33k.tombmanygraves.commands; public class CommandToggleGravePos extends CommandBase { public CommandToggleGravePos() { super("tmg_toggle_grave_pos", 0, true); } @Override @Nonnull @ParametersAreNonnullByDefault public String getUsage(ICommandSender sender) { return COMMAND_NAME; } @Override @ParametersAreNonnullByDefault public void execute(MinecraftServer server, ICommandSender sender, String[] args) throws CommandException { if (!(sender instanceof EntityPlayerMP)) { return; }
TMGNetwork.sendTo(new GravePosTogglePacket(), (EntityPlayerMP)sender);
M4thG33k/TombManyGraves2
src/main/java/com/m4thg33k/tombmanygraves/commands/CommandToggleGravePos.java
// Path: src/main/java/com/m4thg33k/tombmanygraves/network/GravePosTogglePacket.java // public class GravePosTogglePacket extends BaseThreadsafePacket{ // // public GravePosTogglePacket() // { // // } // // @Override // public void handleClientSafe(NetHandlerPlayClient netHandler) { // TombManyGraves.proxy.toggleGravePositionRendering(); // } // // @Override // public void handleServerSafe(NetHandlerPlayServer netHandler) { // // LogHelper.error("Attempting to handle rendering packet on server!"); // } // // @Override // public void fromBytes(ByteBuf buf) { // // } // // @Override // public void toBytes(ByteBuf buf) { // // } // } // // Path: src/main/java/com/m4thg33k/tombmanygraves/network/TMGNetwork.java // public class TMGNetwork { // // public static TMGNetwork instance = new TMGNetwork(); // // public final SimpleNetworkWrapper network; // protected final BasePacketHandler handler; // private int id = 0; // // public TMGNetwork(){ // network = NetworkRegistry.INSTANCE.newSimpleChannel(Names.MODID); // handler = new BasePacketHandler(); // } // // public void registerPacket(Class<? extends BasePacket> packetClass) // { // registerPacketClient(packetClass); // registerPacketServer(packetClass); // } // // public static void registerPacketClient(Class<? extends BasePacket> packetClass) // { // registerPacketImp(packetClass, Side.CLIENT); // } // // public static void registerPacketServer(Class<? extends BasePacket> packetClass) // { // registerPacketImp(packetClass, Side.SERVER); // } // // public static void registerPacketImp(Class<? extends BasePacket> packetClass, Side side) // { // instance.network.registerMessage(instance.handler, packetClass, instance.id++, side); // } // // public static void setup() // { // //register packets here // registerPacketServer(PacketProbeFiles.class); // registerPacketClient(GraveRenderTogglePacket.class); // registerPacketClient(GravePosTogglePacket.class); // } // // public static void sendToAll(BasePacket packet) // { // instance.network.sendToAll(packet); // } // // public static void sendTo(BasePacket packet, EntityPlayerMP player) // { // instance.network.sendTo(packet, player); // } // // public static void sendToAllAround(BasePacket packet, NetworkRegistry.TargetPoint point) // { // instance.network.sendToAllAround(packet, point); // } // // public static void sendToDimension(BasePacket packet, int dimensionID) // { // instance.network.sendToDimension(packet, dimensionID); // } // // public static void sendToServer(BasePacket packet) // { // instance.network.sendToServer(packet); // } // // public static void sendToClients(WorldServer world, BlockPos pos, BasePacket packet) // { // Chunk chunk = world.getChunkFromBlockCoords(pos); // for (EntityPlayer player : world.playerEntities) // { // if (!(player instanceof EntityPlayerMP)) // { // continue; // } // EntityPlayerMP playerMP = (EntityPlayerMP) player; // if (world.getPlayerChunkMap().isPlayerWatchingChunk(playerMP, chunk.x, chunk.z)) // { // // LogHelper.info("Sending packet to: " + player.getName()); // TMGNetwork.sendTo(packet, playerMP); // } // } // } // }
import java.util.ArrayList; import java.util.List; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.annotation.ParametersAreNonnullByDefault; import com.m4thg33k.tombmanygraves.network.GravePosTogglePacket; import com.m4thg33k.tombmanygraves.network.TMGNetwork; import net.minecraft.command.CommandException; import net.minecraft.command.ICommandSender; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.server.MinecraftServer; import net.minecraft.util.math.BlockPos;
package com.m4thg33k.tombmanygraves.commands; public class CommandToggleGravePos extends CommandBase { public CommandToggleGravePos() { super("tmg_toggle_grave_pos", 0, true); } @Override @Nonnull @ParametersAreNonnullByDefault public String getUsage(ICommandSender sender) { return COMMAND_NAME; } @Override @ParametersAreNonnullByDefault public void execute(MinecraftServer server, ICommandSender sender, String[] args) throws CommandException { if (!(sender instanceof EntityPlayerMP)) { return; }
// Path: src/main/java/com/m4thg33k/tombmanygraves/network/GravePosTogglePacket.java // public class GravePosTogglePacket extends BaseThreadsafePacket{ // // public GravePosTogglePacket() // { // // } // // @Override // public void handleClientSafe(NetHandlerPlayClient netHandler) { // TombManyGraves.proxy.toggleGravePositionRendering(); // } // // @Override // public void handleServerSafe(NetHandlerPlayServer netHandler) { // // LogHelper.error("Attempting to handle rendering packet on server!"); // } // // @Override // public void fromBytes(ByteBuf buf) { // // } // // @Override // public void toBytes(ByteBuf buf) { // // } // } // // Path: src/main/java/com/m4thg33k/tombmanygraves/network/TMGNetwork.java // public class TMGNetwork { // // public static TMGNetwork instance = new TMGNetwork(); // // public final SimpleNetworkWrapper network; // protected final BasePacketHandler handler; // private int id = 0; // // public TMGNetwork(){ // network = NetworkRegistry.INSTANCE.newSimpleChannel(Names.MODID); // handler = new BasePacketHandler(); // } // // public void registerPacket(Class<? extends BasePacket> packetClass) // { // registerPacketClient(packetClass); // registerPacketServer(packetClass); // } // // public static void registerPacketClient(Class<? extends BasePacket> packetClass) // { // registerPacketImp(packetClass, Side.CLIENT); // } // // public static void registerPacketServer(Class<? extends BasePacket> packetClass) // { // registerPacketImp(packetClass, Side.SERVER); // } // // public static void registerPacketImp(Class<? extends BasePacket> packetClass, Side side) // { // instance.network.registerMessage(instance.handler, packetClass, instance.id++, side); // } // // public static void setup() // { // //register packets here // registerPacketServer(PacketProbeFiles.class); // registerPacketClient(GraveRenderTogglePacket.class); // registerPacketClient(GravePosTogglePacket.class); // } // // public static void sendToAll(BasePacket packet) // { // instance.network.sendToAll(packet); // } // // public static void sendTo(BasePacket packet, EntityPlayerMP player) // { // instance.network.sendTo(packet, player); // } // // public static void sendToAllAround(BasePacket packet, NetworkRegistry.TargetPoint point) // { // instance.network.sendToAllAround(packet, point); // } // // public static void sendToDimension(BasePacket packet, int dimensionID) // { // instance.network.sendToDimension(packet, dimensionID); // } // // public static void sendToServer(BasePacket packet) // { // instance.network.sendToServer(packet); // } // // public static void sendToClients(WorldServer world, BlockPos pos, BasePacket packet) // { // Chunk chunk = world.getChunkFromBlockCoords(pos); // for (EntityPlayer player : world.playerEntities) // { // if (!(player instanceof EntityPlayerMP)) // { // continue; // } // EntityPlayerMP playerMP = (EntityPlayerMP) player; // if (world.getPlayerChunkMap().isPlayerWatchingChunk(playerMP, chunk.x, chunk.z)) // { // // LogHelper.info("Sending packet to: " + player.getName()); // TMGNetwork.sendTo(packet, playerMP); // } // } // } // } // Path: src/main/java/com/m4thg33k/tombmanygraves/commands/CommandToggleGravePos.java import java.util.ArrayList; import java.util.List; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.annotation.ParametersAreNonnullByDefault; import com.m4thg33k.tombmanygraves.network.GravePosTogglePacket; import com.m4thg33k.tombmanygraves.network.TMGNetwork; import net.minecraft.command.CommandException; import net.minecraft.command.ICommandSender; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.server.MinecraftServer; import net.minecraft.util.math.BlockPos; package com.m4thg33k.tombmanygraves.commands; public class CommandToggleGravePos extends CommandBase { public CommandToggleGravePos() { super("tmg_toggle_grave_pos", 0, true); } @Override @Nonnull @ParametersAreNonnullByDefault public String getUsage(ICommandSender sender) { return COMMAND_NAME; } @Override @ParametersAreNonnullByDefault public void execute(MinecraftServer server, ICommandSender sender, String[] args) throws CommandException { if (!(sender instanceof EntityPlayerMP)) { return; }
TMGNetwork.sendTo(new GravePosTogglePacket(), (EntityPlayerMP)sender);
M4thG33k/TombManyGraves2
src/main/java/com/m4thg33k/tombmanygraves/friends/FriendHandler.java
// Path: src/main/java/com/m4thg33k/tombmanygraves/util/LogHelper.java // public class LogHelper { // // private static final Logger LOGGER = LogManager.getLogger(Names.MODID); // // public static void log(Level logLevel, Object object) // { // LOGGER.log(logLevel, "[" + Names.MODNAME + "]: " + String.valueOf(object)); // } // // public static void all(Object object) // { // log(Level.ALL, object); // } // // public static void debug(Object object) // { // log(Level.DEBUG, object); // } // // public static void error(Object object) // { // log(Level.ERROR, object); // } // // public static void fatal(Object object) // { // log(Level.FATAL, object); // } // // public static void info(Object object) // { // log(Level.INFO, object); // } // // public static void off(Object object) // { // log(Level.OFF, object); // } // // public static void trace(Object object) // { // log(Level.TRACE, object); // } // // public static void warn(Object object) // { // log(Level.WARN, object); // } // }
import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.UUID; import com.m4thg33k.tombmanygraves.util.LogHelper; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.server.MinecraftServer; import net.minecraft.util.text.TextComponentString; import net.minecraftforge.event.entity.EntityJoinWorldEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
package com.m4thg33k.tombmanygraves.friends; public class FriendHandler { private static String PREFIX = "./TombManyGraves"; private static String FILE = "./TombManyGraves/friends.fdat"; private static HashMap<UUID, HashSet<UUID>> friendList; @SuppressWarnings("unchecked") public static void importFriendsList() { friendList = null; try { checkFilePath(); FileInputStream fileIn = new FileInputStream(FILE); ObjectInputStream in = new ObjectInputStream(fileIn); friendList = (HashMap<UUID, HashSet<UUID>>) in.readObject(); in.close(); fileIn.close();
// Path: src/main/java/com/m4thg33k/tombmanygraves/util/LogHelper.java // public class LogHelper { // // private static final Logger LOGGER = LogManager.getLogger(Names.MODID); // // public static void log(Level logLevel, Object object) // { // LOGGER.log(logLevel, "[" + Names.MODNAME + "]: " + String.valueOf(object)); // } // // public static void all(Object object) // { // log(Level.ALL, object); // } // // public static void debug(Object object) // { // log(Level.DEBUG, object); // } // // public static void error(Object object) // { // log(Level.ERROR, object); // } // // public static void fatal(Object object) // { // log(Level.FATAL, object); // } // // public static void info(Object object) // { // log(Level.INFO, object); // } // // public static void off(Object object) // { // log(Level.OFF, object); // } // // public static void trace(Object object) // { // log(Level.TRACE, object); // } // // public static void warn(Object object) // { // log(Level.WARN, object); // } // } // Path: src/main/java/com/m4thg33k/tombmanygraves/friends/FriendHandler.java import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.UUID; import com.m4thg33k.tombmanygraves.util.LogHelper; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.server.MinecraftServer; import net.minecraft.util.text.TextComponentString; import net.minecraftforge.event.entity.EntityJoinWorldEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; package com.m4thg33k.tombmanygraves.friends; public class FriendHandler { private static String PREFIX = "./TombManyGraves"; private static String FILE = "./TombManyGraves/friends.fdat"; private static HashMap<UUID, HashSet<UUID>> friendList; @SuppressWarnings("unchecked") public static void importFriendsList() { friendList = null; try { checkFilePath(); FileInputStream fileIn = new FileInputStream(FILE); ObjectInputStream in = new ObjectInputStream(fileIn); friendList = (HashMap<UUID, HashSet<UUID>>) in.readObject(); in.close(); fileIn.close();
LogHelper.info("Successfully loaded the friend list.");
M4thG33k/TombManyGraves2
src/main/java/com/m4thg33k/tombmanygraves/network/TMGNetwork.java
// Path: src/main/java/com/m4thg33k/tombmanygraves/Names.java // public class Names { // public static final String MODID = "tombmanygraves"; // public static final String VERSION = "999"; // public static final String MODNAME = "TombManyGraves"; // // public static final String GRAVE_BLOCK = "grave_block"; // public static final String ITEM_FILE_CONTROL = "item_file_control"; // public static final String DEATH_LIST = "death_list"; // // public static final String BLOCK_PATH = MODID + ":blocks/"; // public static final String BLOCK_MODEL_PATH = MODID + ":models/block/"; // // }
import com.m4thg33k.tombmanygraves.Names; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.util.math.BlockPos; import net.minecraft.world.WorldServer; import net.minecraft.world.chunk.Chunk; import net.minecraftforge.fml.common.network.NetworkRegistry; import net.minecraftforge.fml.common.network.simpleimpl.SimpleNetworkWrapper; import net.minecraftforge.fml.relauncher.Side;
package com.m4thg33k.tombmanygraves.network; public class TMGNetwork { public static TMGNetwork instance = new TMGNetwork(); public final SimpleNetworkWrapper network; protected final BasePacketHandler handler; private int id = 0; public TMGNetwork(){
// Path: src/main/java/com/m4thg33k/tombmanygraves/Names.java // public class Names { // public static final String MODID = "tombmanygraves"; // public static final String VERSION = "999"; // public static final String MODNAME = "TombManyGraves"; // // public static final String GRAVE_BLOCK = "grave_block"; // public static final String ITEM_FILE_CONTROL = "item_file_control"; // public static final String DEATH_LIST = "death_list"; // // public static final String BLOCK_PATH = MODID + ":blocks/"; // public static final String BLOCK_MODEL_PATH = MODID + ":models/block/"; // // } // Path: src/main/java/com/m4thg33k/tombmanygraves/network/TMGNetwork.java import com.m4thg33k.tombmanygraves.Names; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.util.math.BlockPos; import net.minecraft.world.WorldServer; import net.minecraft.world.chunk.Chunk; import net.minecraftforge.fml.common.network.NetworkRegistry; import net.minecraftforge.fml.common.network.simpleimpl.SimpleNetworkWrapper; import net.minecraftforge.fml.relauncher.Side; package com.m4thg33k.tombmanygraves.network; public class TMGNetwork { public static TMGNetwork instance = new TMGNetwork(); public final SimpleNetworkWrapper network; protected final BasePacketHandler handler; private int id = 0; public TMGNetwork(){
network = NetworkRegistry.INSTANCE.newSimpleChannel(Names.MODID);
M4thG33k/TombManyGraves2
src/main/java/com/m4thg33k/tombmanygraves/blocks/itemblocks/GraveItemBlock.java
// Path: src/main/java/com/m4thg33k/tombmanygraves/Names.java // public class Names { // public static final String MODID = "tombmanygraves"; // public static final String VERSION = "999"; // public static final String MODNAME = "TombManyGraves"; // // public static final String GRAVE_BLOCK = "grave_block"; // public static final String ITEM_FILE_CONTROL = "item_file_control"; // public static final String DEATH_LIST = "death_list"; // // public static final String BLOCK_PATH = MODID + ":blocks/"; // public static final String BLOCK_MODEL_PATH = MODID + ":models/block/"; // // }
import java.util.List; import javax.annotation.Nonnull; import javax.annotation.Nullable; import com.m4thg33k.tombmanygraves.Names; import net.minecraft.block.Block; import net.minecraft.client.util.ITooltipFlag; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; import net.minecraft.util.EnumActionResult; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumHand; import net.minecraft.util.math.BlockPos; import net.minecraft.util.text.TextFormatting; import net.minecraft.world.World;
package com.m4thg33k.tombmanygraves.blocks.itemblocks; public class GraveItemBlock extends ItemBlock{ public GraveItemBlock(Block block) { super(block); this.setMaxDamage(0);
// Path: src/main/java/com/m4thg33k/tombmanygraves/Names.java // public class Names { // public static final String MODID = "tombmanygraves"; // public static final String VERSION = "999"; // public static final String MODNAME = "TombManyGraves"; // // public static final String GRAVE_BLOCK = "grave_block"; // public static final String ITEM_FILE_CONTROL = "item_file_control"; // public static final String DEATH_LIST = "death_list"; // // public static final String BLOCK_PATH = MODID + ":blocks/"; // public static final String BLOCK_MODEL_PATH = MODID + ":models/block/"; // // } // Path: src/main/java/com/m4thg33k/tombmanygraves/blocks/itemblocks/GraveItemBlock.java import java.util.List; import javax.annotation.Nonnull; import javax.annotation.Nullable; import com.m4thg33k.tombmanygraves.Names; import net.minecraft.block.Block; import net.minecraft.client.util.ITooltipFlag; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; import net.minecraft.util.EnumActionResult; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumHand; import net.minecraft.util.math.BlockPos; import net.minecraft.util.text.TextFormatting; import net.minecraft.world.World; package com.m4thg33k.tombmanygraves.blocks.itemblocks; public class GraveItemBlock extends ItemBlock{ public GraveItemBlock(Block block) { super(block); this.setMaxDamage(0);
this.setRegistryName(Names.MODID, Names.GRAVE_BLOCK);
M4thG33k/TombManyGraves2
src/main/java/com/m4thg33k/tombmanygraves/client/gui/InventoryFileManagerGui.java
// Path: src/main/java/com/m4thg33k/tombmanygraves/gui/containers/ContainerInventoryFileManager.java // public class ContainerInventoryFileManager extends BaseContainer { // // protected EntityPlayer player; // // public ContainerInventoryFileManager(EntityPlayer player){ // this.player = player; // } // // public List<String> getFileNames() // { // // LogHelper.info("Getting file names inside container"); // return DeathInventoryHandler.getSavedInventories(); // } // } // // Path: src/main/java/com/m4thg33k/tombmanygraves/network/PacketProbeFiles.java // public class PacketProbeFiles extends BaseThreadsafePacket{ // // private BlockPos pos; // private int dimension; // private UUID uuid; // // public PacketProbeFiles() // { // // } // // public PacketProbeFiles(int dimension, UUID playerUUID, BlockPos pos) // { // this.dimension = dimension; // this.pos = pos; // this.uuid = playerUUID; // } // // @Override // public void handleClientSafe(NetHandlerPlayClient netHandler) { // throw new UnsupportedOperationException("Server-side only!"); // } // // @Override // public void handleServerSafe(NetHandlerPlayServer netHandler) { // List<String> files = TombManyGraves.proxy.probeForFiles(pos); // // LogHelper.info("I've received the files in PacketProbeFiles"); // WorldServer server = DimensionManager.getWorld(dimension); // TMGNetwork.sendTo(new PacketFileNames(pos, files), (EntityPlayerMP)server.getPlayerEntityByUUID(uuid)); // } // // @Override // public void toBytes(ByteBuf buf) { // writePos(pos, buf); // buf.writeInt(dimension); // ByteBufUtils.writeUTF8String(buf, uuid.toString()); // } // // @Override // public void fromBytes(ByteBuf buf) { // pos = readPos(buf); // dimension = buf.readInt(); // uuid = UUID.fromString(ByteBufUtils.readUTF8String(buf)); // } // } // // Path: src/main/java/com/m4thg33k/tombmanygraves/network/TMGNetwork.java // public class TMGNetwork { // // public static TMGNetwork instance = new TMGNetwork(); // // public final SimpleNetworkWrapper network; // protected final BasePacketHandler handler; // private int id = 0; // // public TMGNetwork(){ // network = NetworkRegistry.INSTANCE.newSimpleChannel(Names.MODID); // handler = new BasePacketHandler(); // } // // public void registerPacket(Class<? extends BasePacket> packetClass) // { // registerPacketClient(packetClass); // registerPacketServer(packetClass); // } // // public static void registerPacketClient(Class<? extends BasePacket> packetClass) // { // registerPacketImp(packetClass, Side.CLIENT); // } // // public static void registerPacketServer(Class<? extends BasePacket> packetClass) // { // registerPacketImp(packetClass, Side.SERVER); // } // // public static void registerPacketImp(Class<? extends BasePacket> packetClass, Side side) // { // instance.network.registerMessage(instance.handler, packetClass, instance.id++, side); // } // // public static void setup() // { // //register packets here // registerPacketServer(PacketProbeFiles.class); // registerPacketClient(GraveRenderTogglePacket.class); // registerPacketClient(GravePosTogglePacket.class); // } // // public static void sendToAll(BasePacket packet) // { // instance.network.sendToAll(packet); // } // // public static void sendTo(BasePacket packet, EntityPlayerMP player) // { // instance.network.sendTo(packet, player); // } // // public static void sendToAllAround(BasePacket packet, NetworkRegistry.TargetPoint point) // { // instance.network.sendToAllAround(packet, point); // } // // public static void sendToDimension(BasePacket packet, int dimensionID) // { // instance.network.sendToDimension(packet, dimensionID); // } // // public static void sendToServer(BasePacket packet) // { // instance.network.sendToServer(packet); // } // // public static void sendToClients(WorldServer world, BlockPos pos, BasePacket packet) // { // Chunk chunk = world.getChunkFromBlockCoords(pos); // for (EntityPlayer player : world.playerEntities) // { // if (!(player instanceof EntityPlayerMP)) // { // continue; // } // EntityPlayerMP playerMP = (EntityPlayerMP) player; // if (world.getPlayerChunkMap().isPlayerWatchingChunk(playerMP, chunk.x, chunk.z)) // { // // LogHelper.info("Sending packet to: " + player.getName()); // TMGNetwork.sendTo(packet, playerMP); // } // } // } // }
import java.util.ArrayList; import java.util.List; import com.m4thg33k.tombmanygraves.gui.containers.ContainerInventoryFileManager; import com.m4thg33k.tombmanygraves.network.PacketProbeFiles; import com.m4thg33k.tombmanygraves.network.TMGNetwork; import net.minecraft.client.gui.GuiButton; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.entity.player.EntityPlayer;
package com.m4thg33k.tombmanygraves.client.gui; public class InventoryFileManagerGui extends ModBaseContainerGui { protected EntityPlayer player; protected GuiButton testButton;
// Path: src/main/java/com/m4thg33k/tombmanygraves/gui/containers/ContainerInventoryFileManager.java // public class ContainerInventoryFileManager extends BaseContainer { // // protected EntityPlayer player; // // public ContainerInventoryFileManager(EntityPlayer player){ // this.player = player; // } // // public List<String> getFileNames() // { // // LogHelper.info("Getting file names inside container"); // return DeathInventoryHandler.getSavedInventories(); // } // } // // Path: src/main/java/com/m4thg33k/tombmanygraves/network/PacketProbeFiles.java // public class PacketProbeFiles extends BaseThreadsafePacket{ // // private BlockPos pos; // private int dimension; // private UUID uuid; // // public PacketProbeFiles() // { // // } // // public PacketProbeFiles(int dimension, UUID playerUUID, BlockPos pos) // { // this.dimension = dimension; // this.pos = pos; // this.uuid = playerUUID; // } // // @Override // public void handleClientSafe(NetHandlerPlayClient netHandler) { // throw new UnsupportedOperationException("Server-side only!"); // } // // @Override // public void handleServerSafe(NetHandlerPlayServer netHandler) { // List<String> files = TombManyGraves.proxy.probeForFiles(pos); // // LogHelper.info("I've received the files in PacketProbeFiles"); // WorldServer server = DimensionManager.getWorld(dimension); // TMGNetwork.sendTo(new PacketFileNames(pos, files), (EntityPlayerMP)server.getPlayerEntityByUUID(uuid)); // } // // @Override // public void toBytes(ByteBuf buf) { // writePos(pos, buf); // buf.writeInt(dimension); // ByteBufUtils.writeUTF8String(buf, uuid.toString()); // } // // @Override // public void fromBytes(ByteBuf buf) { // pos = readPos(buf); // dimension = buf.readInt(); // uuid = UUID.fromString(ByteBufUtils.readUTF8String(buf)); // } // } // // Path: src/main/java/com/m4thg33k/tombmanygraves/network/TMGNetwork.java // public class TMGNetwork { // // public static TMGNetwork instance = new TMGNetwork(); // // public final SimpleNetworkWrapper network; // protected final BasePacketHandler handler; // private int id = 0; // // public TMGNetwork(){ // network = NetworkRegistry.INSTANCE.newSimpleChannel(Names.MODID); // handler = new BasePacketHandler(); // } // // public void registerPacket(Class<? extends BasePacket> packetClass) // { // registerPacketClient(packetClass); // registerPacketServer(packetClass); // } // // public static void registerPacketClient(Class<? extends BasePacket> packetClass) // { // registerPacketImp(packetClass, Side.CLIENT); // } // // public static void registerPacketServer(Class<? extends BasePacket> packetClass) // { // registerPacketImp(packetClass, Side.SERVER); // } // // public static void registerPacketImp(Class<? extends BasePacket> packetClass, Side side) // { // instance.network.registerMessage(instance.handler, packetClass, instance.id++, side); // } // // public static void setup() // { // //register packets here // registerPacketServer(PacketProbeFiles.class); // registerPacketClient(GraveRenderTogglePacket.class); // registerPacketClient(GravePosTogglePacket.class); // } // // public static void sendToAll(BasePacket packet) // { // instance.network.sendToAll(packet); // } // // public static void sendTo(BasePacket packet, EntityPlayerMP player) // { // instance.network.sendTo(packet, player); // } // // public static void sendToAllAround(BasePacket packet, NetworkRegistry.TargetPoint point) // { // instance.network.sendToAllAround(packet, point); // } // // public static void sendToDimension(BasePacket packet, int dimensionID) // { // instance.network.sendToDimension(packet, dimensionID); // } // // public static void sendToServer(BasePacket packet) // { // instance.network.sendToServer(packet); // } // // public static void sendToClients(WorldServer world, BlockPos pos, BasePacket packet) // { // Chunk chunk = world.getChunkFromBlockCoords(pos); // for (EntityPlayer player : world.playerEntities) // { // if (!(player instanceof EntityPlayerMP)) // { // continue; // } // EntityPlayerMP playerMP = (EntityPlayerMP) player; // if (world.getPlayerChunkMap().isPlayerWatchingChunk(playerMP, chunk.x, chunk.z)) // { // // LogHelper.info("Sending packet to: " + player.getName()); // TMGNetwork.sendTo(packet, playerMP); // } // } // } // } // Path: src/main/java/com/m4thg33k/tombmanygraves/client/gui/InventoryFileManagerGui.java import java.util.ArrayList; import java.util.List; import com.m4thg33k.tombmanygraves.gui.containers.ContainerInventoryFileManager; import com.m4thg33k.tombmanygraves.network.PacketProbeFiles; import com.m4thg33k.tombmanygraves.network.TMGNetwork; import net.minecraft.client.gui.GuiButton; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.entity.player.EntityPlayer; package com.m4thg33k.tombmanygraves.client.gui; public class InventoryFileManagerGui extends ModBaseContainerGui { protected EntityPlayer player; protected GuiButton testButton;
protected ContainerInventoryFileManager container;
M4thG33k/TombManyGraves2
src/main/java/com/m4thg33k/tombmanygraves/client/gui/InventoryFileManagerGui.java
// Path: src/main/java/com/m4thg33k/tombmanygraves/gui/containers/ContainerInventoryFileManager.java // public class ContainerInventoryFileManager extends BaseContainer { // // protected EntityPlayer player; // // public ContainerInventoryFileManager(EntityPlayer player){ // this.player = player; // } // // public List<String> getFileNames() // { // // LogHelper.info("Getting file names inside container"); // return DeathInventoryHandler.getSavedInventories(); // } // } // // Path: src/main/java/com/m4thg33k/tombmanygraves/network/PacketProbeFiles.java // public class PacketProbeFiles extends BaseThreadsafePacket{ // // private BlockPos pos; // private int dimension; // private UUID uuid; // // public PacketProbeFiles() // { // // } // // public PacketProbeFiles(int dimension, UUID playerUUID, BlockPos pos) // { // this.dimension = dimension; // this.pos = pos; // this.uuid = playerUUID; // } // // @Override // public void handleClientSafe(NetHandlerPlayClient netHandler) { // throw new UnsupportedOperationException("Server-side only!"); // } // // @Override // public void handleServerSafe(NetHandlerPlayServer netHandler) { // List<String> files = TombManyGraves.proxy.probeForFiles(pos); // // LogHelper.info("I've received the files in PacketProbeFiles"); // WorldServer server = DimensionManager.getWorld(dimension); // TMGNetwork.sendTo(new PacketFileNames(pos, files), (EntityPlayerMP)server.getPlayerEntityByUUID(uuid)); // } // // @Override // public void toBytes(ByteBuf buf) { // writePos(pos, buf); // buf.writeInt(dimension); // ByteBufUtils.writeUTF8String(buf, uuid.toString()); // } // // @Override // public void fromBytes(ByteBuf buf) { // pos = readPos(buf); // dimension = buf.readInt(); // uuid = UUID.fromString(ByteBufUtils.readUTF8String(buf)); // } // } // // Path: src/main/java/com/m4thg33k/tombmanygraves/network/TMGNetwork.java // public class TMGNetwork { // // public static TMGNetwork instance = new TMGNetwork(); // // public final SimpleNetworkWrapper network; // protected final BasePacketHandler handler; // private int id = 0; // // public TMGNetwork(){ // network = NetworkRegistry.INSTANCE.newSimpleChannel(Names.MODID); // handler = new BasePacketHandler(); // } // // public void registerPacket(Class<? extends BasePacket> packetClass) // { // registerPacketClient(packetClass); // registerPacketServer(packetClass); // } // // public static void registerPacketClient(Class<? extends BasePacket> packetClass) // { // registerPacketImp(packetClass, Side.CLIENT); // } // // public static void registerPacketServer(Class<? extends BasePacket> packetClass) // { // registerPacketImp(packetClass, Side.SERVER); // } // // public static void registerPacketImp(Class<? extends BasePacket> packetClass, Side side) // { // instance.network.registerMessage(instance.handler, packetClass, instance.id++, side); // } // // public static void setup() // { // //register packets here // registerPacketServer(PacketProbeFiles.class); // registerPacketClient(GraveRenderTogglePacket.class); // registerPacketClient(GravePosTogglePacket.class); // } // // public static void sendToAll(BasePacket packet) // { // instance.network.sendToAll(packet); // } // // public static void sendTo(BasePacket packet, EntityPlayerMP player) // { // instance.network.sendTo(packet, player); // } // // public static void sendToAllAround(BasePacket packet, NetworkRegistry.TargetPoint point) // { // instance.network.sendToAllAround(packet, point); // } // // public static void sendToDimension(BasePacket packet, int dimensionID) // { // instance.network.sendToDimension(packet, dimensionID); // } // // public static void sendToServer(BasePacket packet) // { // instance.network.sendToServer(packet); // } // // public static void sendToClients(WorldServer world, BlockPos pos, BasePacket packet) // { // Chunk chunk = world.getChunkFromBlockCoords(pos); // for (EntityPlayer player : world.playerEntities) // { // if (!(player instanceof EntityPlayerMP)) // { // continue; // } // EntityPlayerMP playerMP = (EntityPlayerMP) player; // if (world.getPlayerChunkMap().isPlayerWatchingChunk(playerMP, chunk.x, chunk.z)) // { // // LogHelper.info("Sending packet to: " + player.getName()); // TMGNetwork.sendTo(packet, playerMP); // } // } // } // }
import java.util.ArrayList; import java.util.List; import com.m4thg33k.tombmanygraves.gui.containers.ContainerInventoryFileManager; import com.m4thg33k.tombmanygraves.network.PacketProbeFiles; import com.m4thg33k.tombmanygraves.network.TMGNetwork; import net.minecraft.client.gui.GuiButton; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.entity.player.EntityPlayer;
package com.m4thg33k.tombmanygraves.client.gui; public class InventoryFileManagerGui extends ModBaseContainerGui { protected EntityPlayer player; protected GuiButton testButton; protected ContainerInventoryFileManager container; protected List<String> files; public InventoryFileManagerGui(EntityPlayer player, ContainerInventoryFileManager container) { super(200, 150, container); this.player = player; this.container = container; // files = container.getFileNames(); files = new ArrayList<>(); // LogHelper.info("Sending packet to server");
// Path: src/main/java/com/m4thg33k/tombmanygraves/gui/containers/ContainerInventoryFileManager.java // public class ContainerInventoryFileManager extends BaseContainer { // // protected EntityPlayer player; // // public ContainerInventoryFileManager(EntityPlayer player){ // this.player = player; // } // // public List<String> getFileNames() // { // // LogHelper.info("Getting file names inside container"); // return DeathInventoryHandler.getSavedInventories(); // } // } // // Path: src/main/java/com/m4thg33k/tombmanygraves/network/PacketProbeFiles.java // public class PacketProbeFiles extends BaseThreadsafePacket{ // // private BlockPos pos; // private int dimension; // private UUID uuid; // // public PacketProbeFiles() // { // // } // // public PacketProbeFiles(int dimension, UUID playerUUID, BlockPos pos) // { // this.dimension = dimension; // this.pos = pos; // this.uuid = playerUUID; // } // // @Override // public void handleClientSafe(NetHandlerPlayClient netHandler) { // throw new UnsupportedOperationException("Server-side only!"); // } // // @Override // public void handleServerSafe(NetHandlerPlayServer netHandler) { // List<String> files = TombManyGraves.proxy.probeForFiles(pos); // // LogHelper.info("I've received the files in PacketProbeFiles"); // WorldServer server = DimensionManager.getWorld(dimension); // TMGNetwork.sendTo(new PacketFileNames(pos, files), (EntityPlayerMP)server.getPlayerEntityByUUID(uuid)); // } // // @Override // public void toBytes(ByteBuf buf) { // writePos(pos, buf); // buf.writeInt(dimension); // ByteBufUtils.writeUTF8String(buf, uuid.toString()); // } // // @Override // public void fromBytes(ByteBuf buf) { // pos = readPos(buf); // dimension = buf.readInt(); // uuid = UUID.fromString(ByteBufUtils.readUTF8String(buf)); // } // } // // Path: src/main/java/com/m4thg33k/tombmanygraves/network/TMGNetwork.java // public class TMGNetwork { // // public static TMGNetwork instance = new TMGNetwork(); // // public final SimpleNetworkWrapper network; // protected final BasePacketHandler handler; // private int id = 0; // // public TMGNetwork(){ // network = NetworkRegistry.INSTANCE.newSimpleChannel(Names.MODID); // handler = new BasePacketHandler(); // } // // public void registerPacket(Class<? extends BasePacket> packetClass) // { // registerPacketClient(packetClass); // registerPacketServer(packetClass); // } // // public static void registerPacketClient(Class<? extends BasePacket> packetClass) // { // registerPacketImp(packetClass, Side.CLIENT); // } // // public static void registerPacketServer(Class<? extends BasePacket> packetClass) // { // registerPacketImp(packetClass, Side.SERVER); // } // // public static void registerPacketImp(Class<? extends BasePacket> packetClass, Side side) // { // instance.network.registerMessage(instance.handler, packetClass, instance.id++, side); // } // // public static void setup() // { // //register packets here // registerPacketServer(PacketProbeFiles.class); // registerPacketClient(GraveRenderTogglePacket.class); // registerPacketClient(GravePosTogglePacket.class); // } // // public static void sendToAll(BasePacket packet) // { // instance.network.sendToAll(packet); // } // // public static void sendTo(BasePacket packet, EntityPlayerMP player) // { // instance.network.sendTo(packet, player); // } // // public static void sendToAllAround(BasePacket packet, NetworkRegistry.TargetPoint point) // { // instance.network.sendToAllAround(packet, point); // } // // public static void sendToDimension(BasePacket packet, int dimensionID) // { // instance.network.sendToDimension(packet, dimensionID); // } // // public static void sendToServer(BasePacket packet) // { // instance.network.sendToServer(packet); // } // // public static void sendToClients(WorldServer world, BlockPos pos, BasePacket packet) // { // Chunk chunk = world.getChunkFromBlockCoords(pos); // for (EntityPlayer player : world.playerEntities) // { // if (!(player instanceof EntityPlayerMP)) // { // continue; // } // EntityPlayerMP playerMP = (EntityPlayerMP) player; // if (world.getPlayerChunkMap().isPlayerWatchingChunk(playerMP, chunk.x, chunk.z)) // { // // LogHelper.info("Sending packet to: " + player.getName()); // TMGNetwork.sendTo(packet, playerMP); // } // } // } // } // Path: src/main/java/com/m4thg33k/tombmanygraves/client/gui/InventoryFileManagerGui.java import java.util.ArrayList; import java.util.List; import com.m4thg33k.tombmanygraves.gui.containers.ContainerInventoryFileManager; import com.m4thg33k.tombmanygraves.network.PacketProbeFiles; import com.m4thg33k.tombmanygraves.network.TMGNetwork; import net.minecraft.client.gui.GuiButton; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.entity.player.EntityPlayer; package com.m4thg33k.tombmanygraves.client.gui; public class InventoryFileManagerGui extends ModBaseContainerGui { protected EntityPlayer player; protected GuiButton testButton; protected ContainerInventoryFileManager container; protected List<String> files; public InventoryFileManagerGui(EntityPlayer player, ContainerInventoryFileManager container) { super(200, 150, container); this.player = player; this.container = container; // files = container.getFileNames(); files = new ArrayList<>(); // LogHelper.info("Sending packet to server");
TMGNetwork.sendToServer(new PacketProbeFiles(player.dimension, player.getUniqueID(), player.getPosition()));
M4thG33k/TombManyGraves2
src/main/java/com/m4thg33k/tombmanygraves/client/gui/InventoryFileManagerGui.java
// Path: src/main/java/com/m4thg33k/tombmanygraves/gui/containers/ContainerInventoryFileManager.java // public class ContainerInventoryFileManager extends BaseContainer { // // protected EntityPlayer player; // // public ContainerInventoryFileManager(EntityPlayer player){ // this.player = player; // } // // public List<String> getFileNames() // { // // LogHelper.info("Getting file names inside container"); // return DeathInventoryHandler.getSavedInventories(); // } // } // // Path: src/main/java/com/m4thg33k/tombmanygraves/network/PacketProbeFiles.java // public class PacketProbeFiles extends BaseThreadsafePacket{ // // private BlockPos pos; // private int dimension; // private UUID uuid; // // public PacketProbeFiles() // { // // } // // public PacketProbeFiles(int dimension, UUID playerUUID, BlockPos pos) // { // this.dimension = dimension; // this.pos = pos; // this.uuid = playerUUID; // } // // @Override // public void handleClientSafe(NetHandlerPlayClient netHandler) { // throw new UnsupportedOperationException("Server-side only!"); // } // // @Override // public void handleServerSafe(NetHandlerPlayServer netHandler) { // List<String> files = TombManyGraves.proxy.probeForFiles(pos); // // LogHelper.info("I've received the files in PacketProbeFiles"); // WorldServer server = DimensionManager.getWorld(dimension); // TMGNetwork.sendTo(new PacketFileNames(pos, files), (EntityPlayerMP)server.getPlayerEntityByUUID(uuid)); // } // // @Override // public void toBytes(ByteBuf buf) { // writePos(pos, buf); // buf.writeInt(dimension); // ByteBufUtils.writeUTF8String(buf, uuid.toString()); // } // // @Override // public void fromBytes(ByteBuf buf) { // pos = readPos(buf); // dimension = buf.readInt(); // uuid = UUID.fromString(ByteBufUtils.readUTF8String(buf)); // } // } // // Path: src/main/java/com/m4thg33k/tombmanygraves/network/TMGNetwork.java // public class TMGNetwork { // // public static TMGNetwork instance = new TMGNetwork(); // // public final SimpleNetworkWrapper network; // protected final BasePacketHandler handler; // private int id = 0; // // public TMGNetwork(){ // network = NetworkRegistry.INSTANCE.newSimpleChannel(Names.MODID); // handler = new BasePacketHandler(); // } // // public void registerPacket(Class<? extends BasePacket> packetClass) // { // registerPacketClient(packetClass); // registerPacketServer(packetClass); // } // // public static void registerPacketClient(Class<? extends BasePacket> packetClass) // { // registerPacketImp(packetClass, Side.CLIENT); // } // // public static void registerPacketServer(Class<? extends BasePacket> packetClass) // { // registerPacketImp(packetClass, Side.SERVER); // } // // public static void registerPacketImp(Class<? extends BasePacket> packetClass, Side side) // { // instance.network.registerMessage(instance.handler, packetClass, instance.id++, side); // } // // public static void setup() // { // //register packets here // registerPacketServer(PacketProbeFiles.class); // registerPacketClient(GraveRenderTogglePacket.class); // registerPacketClient(GravePosTogglePacket.class); // } // // public static void sendToAll(BasePacket packet) // { // instance.network.sendToAll(packet); // } // // public static void sendTo(BasePacket packet, EntityPlayerMP player) // { // instance.network.sendTo(packet, player); // } // // public static void sendToAllAround(BasePacket packet, NetworkRegistry.TargetPoint point) // { // instance.network.sendToAllAround(packet, point); // } // // public static void sendToDimension(BasePacket packet, int dimensionID) // { // instance.network.sendToDimension(packet, dimensionID); // } // // public static void sendToServer(BasePacket packet) // { // instance.network.sendToServer(packet); // } // // public static void sendToClients(WorldServer world, BlockPos pos, BasePacket packet) // { // Chunk chunk = world.getChunkFromBlockCoords(pos); // for (EntityPlayer player : world.playerEntities) // { // if (!(player instanceof EntityPlayerMP)) // { // continue; // } // EntityPlayerMP playerMP = (EntityPlayerMP) player; // if (world.getPlayerChunkMap().isPlayerWatchingChunk(playerMP, chunk.x, chunk.z)) // { // // LogHelper.info("Sending packet to: " + player.getName()); // TMGNetwork.sendTo(packet, playerMP); // } // } // } // }
import java.util.ArrayList; import java.util.List; import com.m4thg33k.tombmanygraves.gui.containers.ContainerInventoryFileManager; import com.m4thg33k.tombmanygraves.network.PacketProbeFiles; import com.m4thg33k.tombmanygraves.network.TMGNetwork; import net.minecraft.client.gui.GuiButton; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.entity.player.EntityPlayer;
package com.m4thg33k.tombmanygraves.client.gui; public class InventoryFileManagerGui extends ModBaseContainerGui { protected EntityPlayer player; protected GuiButton testButton; protected ContainerInventoryFileManager container; protected List<String> files; public InventoryFileManagerGui(EntityPlayer player, ContainerInventoryFileManager container) { super(200, 150, container); this.player = player; this.container = container; // files = container.getFileNames(); files = new ArrayList<>(); // LogHelper.info("Sending packet to server");
// Path: src/main/java/com/m4thg33k/tombmanygraves/gui/containers/ContainerInventoryFileManager.java // public class ContainerInventoryFileManager extends BaseContainer { // // protected EntityPlayer player; // // public ContainerInventoryFileManager(EntityPlayer player){ // this.player = player; // } // // public List<String> getFileNames() // { // // LogHelper.info("Getting file names inside container"); // return DeathInventoryHandler.getSavedInventories(); // } // } // // Path: src/main/java/com/m4thg33k/tombmanygraves/network/PacketProbeFiles.java // public class PacketProbeFiles extends BaseThreadsafePacket{ // // private BlockPos pos; // private int dimension; // private UUID uuid; // // public PacketProbeFiles() // { // // } // // public PacketProbeFiles(int dimension, UUID playerUUID, BlockPos pos) // { // this.dimension = dimension; // this.pos = pos; // this.uuid = playerUUID; // } // // @Override // public void handleClientSafe(NetHandlerPlayClient netHandler) { // throw new UnsupportedOperationException("Server-side only!"); // } // // @Override // public void handleServerSafe(NetHandlerPlayServer netHandler) { // List<String> files = TombManyGraves.proxy.probeForFiles(pos); // // LogHelper.info("I've received the files in PacketProbeFiles"); // WorldServer server = DimensionManager.getWorld(dimension); // TMGNetwork.sendTo(new PacketFileNames(pos, files), (EntityPlayerMP)server.getPlayerEntityByUUID(uuid)); // } // // @Override // public void toBytes(ByteBuf buf) { // writePos(pos, buf); // buf.writeInt(dimension); // ByteBufUtils.writeUTF8String(buf, uuid.toString()); // } // // @Override // public void fromBytes(ByteBuf buf) { // pos = readPos(buf); // dimension = buf.readInt(); // uuid = UUID.fromString(ByteBufUtils.readUTF8String(buf)); // } // } // // Path: src/main/java/com/m4thg33k/tombmanygraves/network/TMGNetwork.java // public class TMGNetwork { // // public static TMGNetwork instance = new TMGNetwork(); // // public final SimpleNetworkWrapper network; // protected final BasePacketHandler handler; // private int id = 0; // // public TMGNetwork(){ // network = NetworkRegistry.INSTANCE.newSimpleChannel(Names.MODID); // handler = new BasePacketHandler(); // } // // public void registerPacket(Class<? extends BasePacket> packetClass) // { // registerPacketClient(packetClass); // registerPacketServer(packetClass); // } // // public static void registerPacketClient(Class<? extends BasePacket> packetClass) // { // registerPacketImp(packetClass, Side.CLIENT); // } // // public static void registerPacketServer(Class<? extends BasePacket> packetClass) // { // registerPacketImp(packetClass, Side.SERVER); // } // // public static void registerPacketImp(Class<? extends BasePacket> packetClass, Side side) // { // instance.network.registerMessage(instance.handler, packetClass, instance.id++, side); // } // // public static void setup() // { // //register packets here // registerPacketServer(PacketProbeFiles.class); // registerPacketClient(GraveRenderTogglePacket.class); // registerPacketClient(GravePosTogglePacket.class); // } // // public static void sendToAll(BasePacket packet) // { // instance.network.sendToAll(packet); // } // // public static void sendTo(BasePacket packet, EntityPlayerMP player) // { // instance.network.sendTo(packet, player); // } // // public static void sendToAllAround(BasePacket packet, NetworkRegistry.TargetPoint point) // { // instance.network.sendToAllAround(packet, point); // } // // public static void sendToDimension(BasePacket packet, int dimensionID) // { // instance.network.sendToDimension(packet, dimensionID); // } // // public static void sendToServer(BasePacket packet) // { // instance.network.sendToServer(packet); // } // // public static void sendToClients(WorldServer world, BlockPos pos, BasePacket packet) // { // Chunk chunk = world.getChunkFromBlockCoords(pos); // for (EntityPlayer player : world.playerEntities) // { // if (!(player instanceof EntityPlayerMP)) // { // continue; // } // EntityPlayerMP playerMP = (EntityPlayerMP) player; // if (world.getPlayerChunkMap().isPlayerWatchingChunk(playerMP, chunk.x, chunk.z)) // { // // LogHelper.info("Sending packet to: " + player.getName()); // TMGNetwork.sendTo(packet, playerMP); // } // } // } // } // Path: src/main/java/com/m4thg33k/tombmanygraves/client/gui/InventoryFileManagerGui.java import java.util.ArrayList; import java.util.List; import com.m4thg33k.tombmanygraves.gui.containers.ContainerInventoryFileManager; import com.m4thg33k.tombmanygraves.network.PacketProbeFiles; import com.m4thg33k.tombmanygraves.network.TMGNetwork; import net.minecraft.client.gui.GuiButton; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.entity.player.EntityPlayer; package com.m4thg33k.tombmanygraves.client.gui; public class InventoryFileManagerGui extends ModBaseContainerGui { protected EntityPlayer player; protected GuiButton testButton; protected ContainerInventoryFileManager container; protected List<String> files; public InventoryFileManagerGui(EntityPlayer player, ContainerInventoryFileManager container) { super(200, 150, container); this.player = player; this.container = container; // files = container.getFileNames(); files = new ArrayList<>(); // LogHelper.info("Sending packet to server");
TMGNetwork.sendToServer(new PacketProbeFiles(player.dimension, player.getUniqueID(), player.getPosition()));
M4thG33k/TombManyGraves2
src/main/java/com/m4thg33k/tombmanygraves/items/ItemFileControl.java
// Path: src/main/java/com/m4thg33k/tombmanygraves/Names.java // public class Names { // public static final String MODID = "tombmanygraves"; // public static final String VERSION = "999"; // public static final String MODNAME = "TombManyGraves"; // // public static final String GRAVE_BLOCK = "grave_block"; // public static final String ITEM_FILE_CONTROL = "item_file_control"; // public static final String DEATH_LIST = "death_list"; // // public static final String BLOCK_PATH = MODID + ":blocks/"; // public static final String BLOCK_MODEL_PATH = MODID + ":models/block/"; // // }
import com.m4thg33k.tombmanygraves.Names; import net.minecraft.item.Item;
package com.m4thg33k.tombmanygraves.items; public class ItemFileControl extends Item { public ItemFileControl() { super();
// Path: src/main/java/com/m4thg33k/tombmanygraves/Names.java // public class Names { // public static final String MODID = "tombmanygraves"; // public static final String VERSION = "999"; // public static final String MODNAME = "TombManyGraves"; // // public static final String GRAVE_BLOCK = "grave_block"; // public static final String ITEM_FILE_CONTROL = "item_file_control"; // public static final String DEATH_LIST = "death_list"; // // public static final String BLOCK_PATH = MODID + ":blocks/"; // public static final String BLOCK_MODEL_PATH = MODID + ":models/block/"; // // } // Path: src/main/java/com/m4thg33k/tombmanygraves/items/ItemFileControl.java import com.m4thg33k.tombmanygraves.Names; import net.minecraft.item.Item; package com.m4thg33k.tombmanygraves.items; public class ItemFileControl extends Item { public ItemFileControl() { super();
this.setUnlocalizedName(Names.ITEM_FILE_CONTROL);
readen/Relay
src/main/java/cn/readen/relay/ApiGenerator.java
// Path: src/main/java/cn/readen/relay/common/JsonParser.java // public class JsonParser { // private ObjectMapper objectMapper = new ObjectMapper(); // private ObjectReader objectReader=objectMapper.reader(); // private static JsonParser instance; // // private JsonParser(){} // // public static JsonParser me(){ // if(instance==null){ // synchronized (JsonParser.class){ // instance=new JsonParser(); // } // } // return instance; // } // // public static ObjectMapper getObjectMapper(){ // return me().objectMapper; // } // // public static ObjectReader getObjectReader(){ // return me().objectReader; // } // // public String toJson(Object obj){ // try { // // return objectMapper.writeValueAsString(obj); // } catch (Exception e) { // throw e instanceof RuntimeException ? (RuntimeException)e : new RuntimeException(e); // } // } // // } // // Path: src/main/java/cn/readen/relay/model/ApiConfig.java // public class ApiConfig { // private String apiName; // private String host; // private String basePath; // private String localPath; // private String appKey; // private String appSecret; // private ApiMethod[] apiMethods; // // public String getApiName() { // return apiName; // } // // public void setApiName(String apiName) { // this.apiName = apiName; // } // // public String getHost() { // return host; // } // // public void setHost(String host) { // this.host = host; // } // // public String getBasePath() { // return basePath; // } // // public void setBasePath(String basePath) { // this.basePath = basePath; // } // // public String getLocalPath() { // return localPath; // } // // public void setLocalPath(String localPath) { // this.localPath = localPath; // } // // public String getAppKey() { // return appKey; // } // // public void setAppKey(String appKey) { // this.appKey = appKey; // } // // public String getAppSecret() { // return appSecret; // } // // public void setAppSecret(String appSecret) { // this.appSecret = appSecret; // } // // public ApiMethod[] getApiMethods() { // return apiMethods; // } // // public void setApiMethods(ApiMethod[] apiMethods) { // this.apiMethods = apiMethods; // } // } // // Path: src/main/java/cn/readen/relay/model/ApiMethod.java // public class ApiMethod { // private String name; // private String httpMethod; // private ApiParam[] urlParams; // private ApiParam[] headerParams; // private int cacheExpireTime; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getHttpMethod() { // return httpMethod; // } // // public void setHttpMethod(String httpMethod) { // this.httpMethod = httpMethod; // } // // public ApiParam[] getUrlParams() { // return urlParams; // } // // public void setUrlParams(ApiParam[] urlParams) { // this.urlParams = urlParams; // } // // public ApiParam[] getHeaderParams() { // return headerParams; // } // // public void setHeaderParams(ApiParam[] headerParams) { // this.headerParams = headerParams; // } // // public int getCacheExpireTime() { // return cacheExpireTime; // } // // public void setCacheExpireTime(int cacheExpireTime) { // this.cacheExpireTime = cacheExpireTime; // } // }
import cn.readen.relay.common.JsonParser; import cn.readen.relay.generator.*; import cn.readen.relay.model.ApiConfig; import cn.readen.relay.model.ApiMethod; import com.jfinal.config.Routes; import java.io.*; import java.util.HashMap; import java.util.Map;
package cn.readen.relay; /** * Created by readen on 2017/2/15. */ public class ApiGenerator implements SourceGenerator { private static String[] apiNames = {"weather", "amapWeather"}; //生成代码所在packageName private static final String packageName = "cn.readen.relay.api"; //代码根目录 private static final String baseDir = "/Users/readen/Documents/web/Relay/src/main/java"; private static final String srcDir = baseDir + File.separator + packageName.replace(".", "/");
// Path: src/main/java/cn/readen/relay/common/JsonParser.java // public class JsonParser { // private ObjectMapper objectMapper = new ObjectMapper(); // private ObjectReader objectReader=objectMapper.reader(); // private static JsonParser instance; // // private JsonParser(){} // // public static JsonParser me(){ // if(instance==null){ // synchronized (JsonParser.class){ // instance=new JsonParser(); // } // } // return instance; // } // // public static ObjectMapper getObjectMapper(){ // return me().objectMapper; // } // // public static ObjectReader getObjectReader(){ // return me().objectReader; // } // // public String toJson(Object obj){ // try { // // return objectMapper.writeValueAsString(obj); // } catch (Exception e) { // throw e instanceof RuntimeException ? (RuntimeException)e : new RuntimeException(e); // } // } // // } // // Path: src/main/java/cn/readen/relay/model/ApiConfig.java // public class ApiConfig { // private String apiName; // private String host; // private String basePath; // private String localPath; // private String appKey; // private String appSecret; // private ApiMethod[] apiMethods; // // public String getApiName() { // return apiName; // } // // public void setApiName(String apiName) { // this.apiName = apiName; // } // // public String getHost() { // return host; // } // // public void setHost(String host) { // this.host = host; // } // // public String getBasePath() { // return basePath; // } // // public void setBasePath(String basePath) { // this.basePath = basePath; // } // // public String getLocalPath() { // return localPath; // } // // public void setLocalPath(String localPath) { // this.localPath = localPath; // } // // public String getAppKey() { // return appKey; // } // // public void setAppKey(String appKey) { // this.appKey = appKey; // } // // public String getAppSecret() { // return appSecret; // } // // public void setAppSecret(String appSecret) { // this.appSecret = appSecret; // } // // public ApiMethod[] getApiMethods() { // return apiMethods; // } // // public void setApiMethods(ApiMethod[] apiMethods) { // this.apiMethods = apiMethods; // } // } // // Path: src/main/java/cn/readen/relay/model/ApiMethod.java // public class ApiMethod { // private String name; // private String httpMethod; // private ApiParam[] urlParams; // private ApiParam[] headerParams; // private int cacheExpireTime; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getHttpMethod() { // return httpMethod; // } // // public void setHttpMethod(String httpMethod) { // this.httpMethod = httpMethod; // } // // public ApiParam[] getUrlParams() { // return urlParams; // } // // public void setUrlParams(ApiParam[] urlParams) { // this.urlParams = urlParams; // } // // public ApiParam[] getHeaderParams() { // return headerParams; // } // // public void setHeaderParams(ApiParam[] headerParams) { // this.headerParams = headerParams; // } // // public int getCacheExpireTime() { // return cacheExpireTime; // } // // public void setCacheExpireTime(int cacheExpireTime) { // this.cacheExpireTime = cacheExpireTime; // } // } // Path: src/main/java/cn/readen/relay/ApiGenerator.java import cn.readen.relay.common.JsonParser; import cn.readen.relay.generator.*; import cn.readen.relay.model.ApiConfig; import cn.readen.relay.model.ApiMethod; import com.jfinal.config.Routes; import java.io.*; import java.util.HashMap; import java.util.Map; package cn.readen.relay; /** * Created by readen on 2017/2/15. */ public class ApiGenerator implements SourceGenerator { private static String[] apiNames = {"weather", "amapWeather"}; //生成代码所在packageName private static final String packageName = "cn.readen.relay.api"; //代码根目录 private static final String baseDir = "/Users/readen/Documents/web/Relay/src/main/java"; private static final String srcDir = baseDir + File.separator + packageName.replace(".", "/");
private Map<String, ApiConfig> apiConfigs;
readen/Relay
src/main/java/cn/readen/relay/ApiGenerator.java
// Path: src/main/java/cn/readen/relay/common/JsonParser.java // public class JsonParser { // private ObjectMapper objectMapper = new ObjectMapper(); // private ObjectReader objectReader=objectMapper.reader(); // private static JsonParser instance; // // private JsonParser(){} // // public static JsonParser me(){ // if(instance==null){ // synchronized (JsonParser.class){ // instance=new JsonParser(); // } // } // return instance; // } // // public static ObjectMapper getObjectMapper(){ // return me().objectMapper; // } // // public static ObjectReader getObjectReader(){ // return me().objectReader; // } // // public String toJson(Object obj){ // try { // // return objectMapper.writeValueAsString(obj); // } catch (Exception e) { // throw e instanceof RuntimeException ? (RuntimeException)e : new RuntimeException(e); // } // } // // } // // Path: src/main/java/cn/readen/relay/model/ApiConfig.java // public class ApiConfig { // private String apiName; // private String host; // private String basePath; // private String localPath; // private String appKey; // private String appSecret; // private ApiMethod[] apiMethods; // // public String getApiName() { // return apiName; // } // // public void setApiName(String apiName) { // this.apiName = apiName; // } // // public String getHost() { // return host; // } // // public void setHost(String host) { // this.host = host; // } // // public String getBasePath() { // return basePath; // } // // public void setBasePath(String basePath) { // this.basePath = basePath; // } // // public String getLocalPath() { // return localPath; // } // // public void setLocalPath(String localPath) { // this.localPath = localPath; // } // // public String getAppKey() { // return appKey; // } // // public void setAppKey(String appKey) { // this.appKey = appKey; // } // // public String getAppSecret() { // return appSecret; // } // // public void setAppSecret(String appSecret) { // this.appSecret = appSecret; // } // // public ApiMethod[] getApiMethods() { // return apiMethods; // } // // public void setApiMethods(ApiMethod[] apiMethods) { // this.apiMethods = apiMethods; // } // } // // Path: src/main/java/cn/readen/relay/model/ApiMethod.java // public class ApiMethod { // private String name; // private String httpMethod; // private ApiParam[] urlParams; // private ApiParam[] headerParams; // private int cacheExpireTime; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getHttpMethod() { // return httpMethod; // } // // public void setHttpMethod(String httpMethod) { // this.httpMethod = httpMethod; // } // // public ApiParam[] getUrlParams() { // return urlParams; // } // // public void setUrlParams(ApiParam[] urlParams) { // this.urlParams = urlParams; // } // // public ApiParam[] getHeaderParams() { // return headerParams; // } // // public void setHeaderParams(ApiParam[] headerParams) { // this.headerParams = headerParams; // } // // public int getCacheExpireTime() { // return cacheExpireTime; // } // // public void setCacheExpireTime(int cacheExpireTime) { // this.cacheExpireTime = cacheExpireTime; // } // }
import cn.readen.relay.common.JsonParser; import cn.readen.relay.generator.*; import cn.readen.relay.model.ApiConfig; import cn.readen.relay.model.ApiMethod; import com.jfinal.config.Routes; import java.io.*; import java.util.HashMap; import java.util.Map;
package cn.readen.relay; /** * Created by readen on 2017/2/15. */ public class ApiGenerator implements SourceGenerator { private static String[] apiNames = {"weather", "amapWeather"}; //生成代码所在packageName private static final String packageName = "cn.readen.relay.api"; //代码根目录 private static final String baseDir = "/Users/readen/Documents/web/Relay/src/main/java"; private static final String srcDir = baseDir + File.separator + packageName.replace(".", "/"); private Map<String, ApiConfig> apiConfigs; private Map<String, String> classNames; private static ApiGenerator instance; public static ApiGenerator me() { if (instance == null) { synchronized (ApiGenerator.class) { instance = new ApiGenerator(); } } return instance; } private ApiGenerator() { apiConfigs = new HashMap<>(); classNames = new HashMap<>(); } @Override public void generateSource(PrintStream out, String apiName) { ApiConfig config = getConfig(apiName); JClass jClass = new JClass(getClassName(apiName), packageName); jClass.setExtends(BaseController.class); jClass.add(new JImport(ApiGenerator.class)); jClass.add(new JImport(ApiConfig.class));
// Path: src/main/java/cn/readen/relay/common/JsonParser.java // public class JsonParser { // private ObjectMapper objectMapper = new ObjectMapper(); // private ObjectReader objectReader=objectMapper.reader(); // private static JsonParser instance; // // private JsonParser(){} // // public static JsonParser me(){ // if(instance==null){ // synchronized (JsonParser.class){ // instance=new JsonParser(); // } // } // return instance; // } // // public static ObjectMapper getObjectMapper(){ // return me().objectMapper; // } // // public static ObjectReader getObjectReader(){ // return me().objectReader; // } // // public String toJson(Object obj){ // try { // // return objectMapper.writeValueAsString(obj); // } catch (Exception e) { // throw e instanceof RuntimeException ? (RuntimeException)e : new RuntimeException(e); // } // } // // } // // Path: src/main/java/cn/readen/relay/model/ApiConfig.java // public class ApiConfig { // private String apiName; // private String host; // private String basePath; // private String localPath; // private String appKey; // private String appSecret; // private ApiMethod[] apiMethods; // // public String getApiName() { // return apiName; // } // // public void setApiName(String apiName) { // this.apiName = apiName; // } // // public String getHost() { // return host; // } // // public void setHost(String host) { // this.host = host; // } // // public String getBasePath() { // return basePath; // } // // public void setBasePath(String basePath) { // this.basePath = basePath; // } // // public String getLocalPath() { // return localPath; // } // // public void setLocalPath(String localPath) { // this.localPath = localPath; // } // // public String getAppKey() { // return appKey; // } // // public void setAppKey(String appKey) { // this.appKey = appKey; // } // // public String getAppSecret() { // return appSecret; // } // // public void setAppSecret(String appSecret) { // this.appSecret = appSecret; // } // // public ApiMethod[] getApiMethods() { // return apiMethods; // } // // public void setApiMethods(ApiMethod[] apiMethods) { // this.apiMethods = apiMethods; // } // } // // Path: src/main/java/cn/readen/relay/model/ApiMethod.java // public class ApiMethod { // private String name; // private String httpMethod; // private ApiParam[] urlParams; // private ApiParam[] headerParams; // private int cacheExpireTime; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getHttpMethod() { // return httpMethod; // } // // public void setHttpMethod(String httpMethod) { // this.httpMethod = httpMethod; // } // // public ApiParam[] getUrlParams() { // return urlParams; // } // // public void setUrlParams(ApiParam[] urlParams) { // this.urlParams = urlParams; // } // // public ApiParam[] getHeaderParams() { // return headerParams; // } // // public void setHeaderParams(ApiParam[] headerParams) { // this.headerParams = headerParams; // } // // public int getCacheExpireTime() { // return cacheExpireTime; // } // // public void setCacheExpireTime(int cacheExpireTime) { // this.cacheExpireTime = cacheExpireTime; // } // } // Path: src/main/java/cn/readen/relay/ApiGenerator.java import cn.readen.relay.common.JsonParser; import cn.readen.relay.generator.*; import cn.readen.relay.model.ApiConfig; import cn.readen.relay.model.ApiMethod; import com.jfinal.config.Routes; import java.io.*; import java.util.HashMap; import java.util.Map; package cn.readen.relay; /** * Created by readen on 2017/2/15. */ public class ApiGenerator implements SourceGenerator { private static String[] apiNames = {"weather", "amapWeather"}; //生成代码所在packageName private static final String packageName = "cn.readen.relay.api"; //代码根目录 private static final String baseDir = "/Users/readen/Documents/web/Relay/src/main/java"; private static final String srcDir = baseDir + File.separator + packageName.replace(".", "/"); private Map<String, ApiConfig> apiConfigs; private Map<String, String> classNames; private static ApiGenerator instance; public static ApiGenerator me() { if (instance == null) { synchronized (ApiGenerator.class) { instance = new ApiGenerator(); } } return instance; } private ApiGenerator() { apiConfigs = new HashMap<>(); classNames = new HashMap<>(); } @Override public void generateSource(PrintStream out, String apiName) { ApiConfig config = getConfig(apiName); JClass jClass = new JClass(getClassName(apiName), packageName); jClass.setExtends(BaseController.class); jClass.add(new JImport(ApiGenerator.class)); jClass.add(new JImport(ApiConfig.class));
jClass.add(new JImport(ApiMethod.class));
readen/Relay
src/main/java/cn/readen/relay/ApiGenerator.java
// Path: src/main/java/cn/readen/relay/common/JsonParser.java // public class JsonParser { // private ObjectMapper objectMapper = new ObjectMapper(); // private ObjectReader objectReader=objectMapper.reader(); // private static JsonParser instance; // // private JsonParser(){} // // public static JsonParser me(){ // if(instance==null){ // synchronized (JsonParser.class){ // instance=new JsonParser(); // } // } // return instance; // } // // public static ObjectMapper getObjectMapper(){ // return me().objectMapper; // } // // public static ObjectReader getObjectReader(){ // return me().objectReader; // } // // public String toJson(Object obj){ // try { // // return objectMapper.writeValueAsString(obj); // } catch (Exception e) { // throw e instanceof RuntimeException ? (RuntimeException)e : new RuntimeException(e); // } // } // // } // // Path: src/main/java/cn/readen/relay/model/ApiConfig.java // public class ApiConfig { // private String apiName; // private String host; // private String basePath; // private String localPath; // private String appKey; // private String appSecret; // private ApiMethod[] apiMethods; // // public String getApiName() { // return apiName; // } // // public void setApiName(String apiName) { // this.apiName = apiName; // } // // public String getHost() { // return host; // } // // public void setHost(String host) { // this.host = host; // } // // public String getBasePath() { // return basePath; // } // // public void setBasePath(String basePath) { // this.basePath = basePath; // } // // public String getLocalPath() { // return localPath; // } // // public void setLocalPath(String localPath) { // this.localPath = localPath; // } // // public String getAppKey() { // return appKey; // } // // public void setAppKey(String appKey) { // this.appKey = appKey; // } // // public String getAppSecret() { // return appSecret; // } // // public void setAppSecret(String appSecret) { // this.appSecret = appSecret; // } // // public ApiMethod[] getApiMethods() { // return apiMethods; // } // // public void setApiMethods(ApiMethod[] apiMethods) { // this.apiMethods = apiMethods; // } // } // // Path: src/main/java/cn/readen/relay/model/ApiMethod.java // public class ApiMethod { // private String name; // private String httpMethod; // private ApiParam[] urlParams; // private ApiParam[] headerParams; // private int cacheExpireTime; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getHttpMethod() { // return httpMethod; // } // // public void setHttpMethod(String httpMethod) { // this.httpMethod = httpMethod; // } // // public ApiParam[] getUrlParams() { // return urlParams; // } // // public void setUrlParams(ApiParam[] urlParams) { // this.urlParams = urlParams; // } // // public ApiParam[] getHeaderParams() { // return headerParams; // } // // public void setHeaderParams(ApiParam[] headerParams) { // this.headerParams = headerParams; // } // // public int getCacheExpireTime() { // return cacheExpireTime; // } // // public void setCacheExpireTime(int cacheExpireTime) { // this.cacheExpireTime = cacheExpireTime; // } // }
import cn.readen.relay.common.JsonParser; import cn.readen.relay.generator.*; import cn.readen.relay.model.ApiConfig; import cn.readen.relay.model.ApiMethod; import com.jfinal.config.Routes; import java.io.*; import java.util.HashMap; import java.util.Map;
public void generateSource(PrintStream out, String apiName) { ApiConfig config = getConfig(apiName); JClass jClass = new JClass(getClassName(apiName), packageName); jClass.setExtends(BaseController.class); jClass.add(new JImport(ApiGenerator.class)); jClass.add(new JImport(ApiConfig.class)); jClass.add(new JImport(ApiMethod.class)); ApiMethod[] apiMethods = config.getApiMethods(); for (int j = 0; j < apiMethods.length; j++) { JMethodBody methodBody = new JMethodBody(); methodBody.append("ApiConfig apiConfig= ApiGenerator.me().getConfig(\"" + apiName + "\");"); methodBody.append("ApiMethod method=apiConfig.getApiMethods()[" + j + "];"); methodBody.append("handle(apiConfig,method);"); JMethod method = new JMethod(Modifier.PUBLIC, false, apiMethods[j].getName(), "void", methodBody); jClass.add(method); } jClass.print(out, 0); } @Override public ApiConfig getConfig(String apiName) { if (apiConfigs.get(apiName) == null) { String fileName = apiName + ".json"; InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName); InputStreamReader inputStreamReader = new InputStreamReader(inputStream); String jsonConfig = CommentRemover.removeComments(inputStreamReader); // System.out.println(jsonConfig); try {
// Path: src/main/java/cn/readen/relay/common/JsonParser.java // public class JsonParser { // private ObjectMapper objectMapper = new ObjectMapper(); // private ObjectReader objectReader=objectMapper.reader(); // private static JsonParser instance; // // private JsonParser(){} // // public static JsonParser me(){ // if(instance==null){ // synchronized (JsonParser.class){ // instance=new JsonParser(); // } // } // return instance; // } // // public static ObjectMapper getObjectMapper(){ // return me().objectMapper; // } // // public static ObjectReader getObjectReader(){ // return me().objectReader; // } // // public String toJson(Object obj){ // try { // // return objectMapper.writeValueAsString(obj); // } catch (Exception e) { // throw e instanceof RuntimeException ? (RuntimeException)e : new RuntimeException(e); // } // } // // } // // Path: src/main/java/cn/readen/relay/model/ApiConfig.java // public class ApiConfig { // private String apiName; // private String host; // private String basePath; // private String localPath; // private String appKey; // private String appSecret; // private ApiMethod[] apiMethods; // // public String getApiName() { // return apiName; // } // // public void setApiName(String apiName) { // this.apiName = apiName; // } // // public String getHost() { // return host; // } // // public void setHost(String host) { // this.host = host; // } // // public String getBasePath() { // return basePath; // } // // public void setBasePath(String basePath) { // this.basePath = basePath; // } // // public String getLocalPath() { // return localPath; // } // // public void setLocalPath(String localPath) { // this.localPath = localPath; // } // // public String getAppKey() { // return appKey; // } // // public void setAppKey(String appKey) { // this.appKey = appKey; // } // // public String getAppSecret() { // return appSecret; // } // // public void setAppSecret(String appSecret) { // this.appSecret = appSecret; // } // // public ApiMethod[] getApiMethods() { // return apiMethods; // } // // public void setApiMethods(ApiMethod[] apiMethods) { // this.apiMethods = apiMethods; // } // } // // Path: src/main/java/cn/readen/relay/model/ApiMethod.java // public class ApiMethod { // private String name; // private String httpMethod; // private ApiParam[] urlParams; // private ApiParam[] headerParams; // private int cacheExpireTime; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getHttpMethod() { // return httpMethod; // } // // public void setHttpMethod(String httpMethod) { // this.httpMethod = httpMethod; // } // // public ApiParam[] getUrlParams() { // return urlParams; // } // // public void setUrlParams(ApiParam[] urlParams) { // this.urlParams = urlParams; // } // // public ApiParam[] getHeaderParams() { // return headerParams; // } // // public void setHeaderParams(ApiParam[] headerParams) { // this.headerParams = headerParams; // } // // public int getCacheExpireTime() { // return cacheExpireTime; // } // // public void setCacheExpireTime(int cacheExpireTime) { // this.cacheExpireTime = cacheExpireTime; // } // } // Path: src/main/java/cn/readen/relay/ApiGenerator.java import cn.readen.relay.common.JsonParser; import cn.readen.relay.generator.*; import cn.readen.relay.model.ApiConfig; import cn.readen.relay.model.ApiMethod; import com.jfinal.config.Routes; import java.io.*; import java.util.HashMap; import java.util.Map; public void generateSource(PrintStream out, String apiName) { ApiConfig config = getConfig(apiName); JClass jClass = new JClass(getClassName(apiName), packageName); jClass.setExtends(BaseController.class); jClass.add(new JImport(ApiGenerator.class)); jClass.add(new JImport(ApiConfig.class)); jClass.add(new JImport(ApiMethod.class)); ApiMethod[] apiMethods = config.getApiMethods(); for (int j = 0; j < apiMethods.length; j++) { JMethodBody methodBody = new JMethodBody(); methodBody.append("ApiConfig apiConfig= ApiGenerator.me().getConfig(\"" + apiName + "\");"); methodBody.append("ApiMethod method=apiConfig.getApiMethods()[" + j + "];"); methodBody.append("handle(apiConfig,method);"); JMethod method = new JMethod(Modifier.PUBLIC, false, apiMethods[j].getName(), "void", methodBody); jClass.add(method); } jClass.print(out, 0); } @Override public ApiConfig getConfig(String apiName) { if (apiConfigs.get(apiName) == null) { String fileName = apiName + ".json"; InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName); InputStreamReader inputStreamReader = new InputStreamReader(inputStream); String jsonConfig = CommentRemover.removeComments(inputStreamReader); // System.out.println(jsonConfig); try {
ApiConfig config = JsonParser.getObjectReader().forType(ApiConfig.class).readValue(jsonConfig);
readen/Relay
src/main/java/cn/readen/relay/AppConfig.java
// Path: src/main/java/cn/readen/relay/api/ApiRouter.java // public class ApiRouter extends Routes { // // // public void config() { // add("/weather",WeatherController.class); // add("/amap/weather",AmapWeatherController.class); // } // // }
import cn.readen.relay.api.ApiRouter; import com.jfinal.config.*; import com.jfinal.json.JacksonFactory; import com.jfinal.kit.PropKit; import com.jfinal.plugin.redis.IKeyNamingPolicy; import com.jfinal.plugin.redis.RedisPlugin; import com.jfinal.render.ViewType; import com.jfinal.template.Engine;
package cn.readen.relay; /** * Created by hnair20160706 on 2016/9/13. */ public class AppConfig extends JFinalConfig{ @Override public void configConstant(Constants me) { PropKit.use("config.txt"); me.setViewType(ViewType.JSP); //根据gt可以添加扩展函数,格式化函数,共享变量等, me.setDevMode(true); me.setJsonFactory(new JacksonFactory()); } @Override public void configRoute(Routes me) {
// Path: src/main/java/cn/readen/relay/api/ApiRouter.java // public class ApiRouter extends Routes { // // // public void config() { // add("/weather",WeatherController.class); // add("/amap/weather",AmapWeatherController.class); // } // // } // Path: src/main/java/cn/readen/relay/AppConfig.java import cn.readen.relay.api.ApiRouter; import com.jfinal.config.*; import com.jfinal.json.JacksonFactory; import com.jfinal.kit.PropKit; import com.jfinal.plugin.redis.IKeyNamingPolicy; import com.jfinal.plugin.redis.RedisPlugin; import com.jfinal.render.ViewType; import com.jfinal.template.Engine; package cn.readen.relay; /** * Created by hnair20160706 on 2016/9/13. */ public class AppConfig extends JFinalConfig{ @Override public void configConstant(Constants me) { PropKit.use("config.txt"); me.setViewType(ViewType.JSP); //根据gt可以添加扩展函数,格式化函数,共享变量等, me.setDevMode(true); me.setJsonFactory(new JacksonFactory()); } @Override public void configRoute(Routes me) {
me.add(new ApiRouter());
readen/Relay
src/main/java/cn/readen/relay/SourceGenerator.java
// Path: src/main/java/cn/readen/relay/model/ApiConfig.java // public class ApiConfig { // private String apiName; // private String host; // private String basePath; // private String localPath; // private String appKey; // private String appSecret; // private ApiMethod[] apiMethods; // // public String getApiName() { // return apiName; // } // // public void setApiName(String apiName) { // this.apiName = apiName; // } // // public String getHost() { // return host; // } // // public void setHost(String host) { // this.host = host; // } // // public String getBasePath() { // return basePath; // } // // public void setBasePath(String basePath) { // this.basePath = basePath; // } // // public String getLocalPath() { // return localPath; // } // // public void setLocalPath(String localPath) { // this.localPath = localPath; // } // // public String getAppKey() { // return appKey; // } // // public void setAppKey(String appKey) { // this.appKey = appKey; // } // // public String getAppSecret() { // return appSecret; // } // // public void setAppSecret(String appSecret) { // this.appSecret = appSecret; // } // // public ApiMethod[] getApiMethods() { // return apiMethods; // } // // public void setApiMethods(ApiMethod[] apiMethods) { // this.apiMethods = apiMethods; // } // }
import cn.readen.relay.model.ApiConfig; import java.io.PrintStream;
package cn.readen.relay; /** * Created by readen on 2017/2/15. */ public interface SourceGenerator { void generateSource(PrintStream out,String apiName);
// Path: src/main/java/cn/readen/relay/model/ApiConfig.java // public class ApiConfig { // private String apiName; // private String host; // private String basePath; // private String localPath; // private String appKey; // private String appSecret; // private ApiMethod[] apiMethods; // // public String getApiName() { // return apiName; // } // // public void setApiName(String apiName) { // this.apiName = apiName; // } // // public String getHost() { // return host; // } // // public void setHost(String host) { // this.host = host; // } // // public String getBasePath() { // return basePath; // } // // public void setBasePath(String basePath) { // this.basePath = basePath; // } // // public String getLocalPath() { // return localPath; // } // // public void setLocalPath(String localPath) { // this.localPath = localPath; // } // // public String getAppKey() { // return appKey; // } // // public void setAppKey(String appKey) { // this.appKey = appKey; // } // // public String getAppSecret() { // return appSecret; // } // // public void setAppSecret(String appSecret) { // this.appSecret = appSecret; // } // // public ApiMethod[] getApiMethods() { // return apiMethods; // } // // public void setApiMethods(ApiMethod[] apiMethods) { // this.apiMethods = apiMethods; // } // } // Path: src/main/java/cn/readen/relay/SourceGenerator.java import cn.readen.relay.model.ApiConfig; import java.io.PrintStream; package cn.readen.relay; /** * Created by readen on 2017/2/15. */ public interface SourceGenerator { void generateSource(PrintStream out,String apiName);
ApiConfig getConfig(String apiName);
w9jds/MarketBot
app/src/main/java/com/w9jds/marketbot/ui/adapters/bindings/MarginAdapters.java
// Path: app/src/main/java/com/w9jds/marketbot/classes/models/StationMargin.java // public final class StationMargin { // // double maxBuyPrice; // double maxSellPrice; // double margin; // double percentage; // // String station; // // public double getMargin() { // return margin; // } // // public double getPercentage() { // return percentage; // } // // public double getMaxBuyPrice() { // return maxBuyPrice; // } // // public double getMaxSellPrice() { // return maxSellPrice; // } // // public String getStation() { // return station; // } // // public static class Builder { // // double maxBuyPrice; // double maxSellPrice; // String station; // // public Builder setMaxBuyPrice(double maxBuyPrice) { // this.maxBuyPrice = maxBuyPrice; // return this; // } // // public Builder setMaxSellPrice(double maxSellPrice) { // this.maxSellPrice = maxSellPrice; // return this; // } // // public Builder setStation(String station) { // this.station = station; // return this; // } // // public StationMargin build() { // StationMargin margin = new StationMargin(); // margin.maxBuyPrice = maxBuyPrice; // margin.maxSellPrice = maxSellPrice; // margin.margin = maxSellPrice - maxBuyPrice; // margin.percentage = margin.margin / maxBuyPrice; // margin.station = station; // // return margin; // } // } // // }
import android.databinding.BindingAdapter; import android.widget.TextView; import com.w9jds.marketbot.classes.models.StationMargin; import java.text.DecimalFormat;
package com.w9jds.marketbot.ui.adapters.bindings; public class MarginAdapters { @BindingAdapter("bind:marginPercentage")
// Path: app/src/main/java/com/w9jds/marketbot/classes/models/StationMargin.java // public final class StationMargin { // // double maxBuyPrice; // double maxSellPrice; // double margin; // double percentage; // // String station; // // public double getMargin() { // return margin; // } // // public double getPercentage() { // return percentage; // } // // public double getMaxBuyPrice() { // return maxBuyPrice; // } // // public double getMaxSellPrice() { // return maxSellPrice; // } // // public String getStation() { // return station; // } // // public static class Builder { // // double maxBuyPrice; // double maxSellPrice; // String station; // // public Builder setMaxBuyPrice(double maxBuyPrice) { // this.maxBuyPrice = maxBuyPrice; // return this; // } // // public Builder setMaxSellPrice(double maxSellPrice) { // this.maxSellPrice = maxSellPrice; // return this; // } // // public Builder setStation(String station) { // this.station = station; // return this; // } // // public StationMargin build() { // StationMargin margin = new StationMargin(); // margin.maxBuyPrice = maxBuyPrice; // margin.maxSellPrice = maxSellPrice; // margin.margin = maxSellPrice - maxBuyPrice; // margin.percentage = margin.margin / maxBuyPrice; // margin.station = station; // // return margin; // } // } // // } // Path: app/src/main/java/com/w9jds/marketbot/ui/adapters/bindings/MarginAdapters.java import android.databinding.BindingAdapter; import android.widget.TextView; import com.w9jds.marketbot.classes.models.StationMargin; import java.text.DecimalFormat; package com.w9jds.marketbot.ui.adapters.bindings; public class MarginAdapters { @BindingAdapter("bind:marginPercentage")
public static void setMarginPercentage(TextView textView, StationMargin margin) {
w9jds/MarketBot
app/src/main/java/com/w9jds/marketbot/ui/InfoActivity.java
// Path: app/src/main/java/com/w9jds/marketbot/classes/MarketBot.java // public class MarketBot extends Application { // // private static BaseComponent baseComponent; // // @Override // public void onCreate() { // super.onCreate(); // FlowManager.init(this); // // baseComponent = DaggerBaseComponent.builder() // .applicationModule(new ApplicationModule(this)) // .netModule(new NetModule(NetModule.TRANQUILITY)) // .build(); // // } // // public static StorageComponent createNewStorageSession() { // return DaggerStorageComponent.builder() // .baseComponent(baseComponent) // .storageModule(new StorageModule()) // .build(); // } // // }
import android.content.Intent; import android.content.pm.PackageInfo; import android.net.Uri; import android.support.design.widget.CoordinatorLayout; import android.support.design.widget.Snackbar; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.w9jds.marketbot.R; import com.w9jds.marketbot.classes.MarketBot; import javax.inject.Inject; import butterknife.Bind; import butterknife.ButterKnife; import butterknife.OnClick;
package com.w9jds.marketbot.ui; public class InfoActivity extends AppCompatActivity { @Bind(R.id.rix_icon) ImageView rixxIcon; @Bind(R.id.me_icon) ImageView jeremyIcon; @Bind(R.id.crest_version) TextView crestVersionView; @Bind(R.id.application_version) TextView appVersionView; @Bind(R.id.base_view) CoordinatorLayout baseView; @Bind(R.id.toolbar) Toolbar toolbar; @Inject String crestVersion; private ActionBar actionBar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_info); ButterKnife.bind(this);
// Path: app/src/main/java/com/w9jds/marketbot/classes/MarketBot.java // public class MarketBot extends Application { // // private static BaseComponent baseComponent; // // @Override // public void onCreate() { // super.onCreate(); // FlowManager.init(this); // // baseComponent = DaggerBaseComponent.builder() // .applicationModule(new ApplicationModule(this)) // .netModule(new NetModule(NetModule.TRANQUILITY)) // .build(); // // } // // public static StorageComponent createNewStorageSession() { // return DaggerStorageComponent.builder() // .baseComponent(baseComponent) // .storageModule(new StorageModule()) // .build(); // } // // } // Path: app/src/main/java/com/w9jds/marketbot/ui/InfoActivity.java import android.content.Intent; import android.content.pm.PackageInfo; import android.net.Uri; import android.support.design.widget.CoordinatorLayout; import android.support.design.widget.Snackbar; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.w9jds.marketbot.R; import com.w9jds.marketbot.classes.MarketBot; import javax.inject.Inject; import butterknife.Bind; import butterknife.ButterKnife; import butterknife.OnClick; package com.w9jds.marketbot.ui; public class InfoActivity extends AppCompatActivity { @Bind(R.id.rix_icon) ImageView rixxIcon; @Bind(R.id.me_icon) ImageView jeremyIcon; @Bind(R.id.crest_version) TextView crestVersionView; @Bind(R.id.application_version) TextView appVersionView; @Bind(R.id.base_view) CoordinatorLayout baseView; @Bind(R.id.toolbar) Toolbar toolbar; @Inject String crestVersion; private ActionBar actionBar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_info); ButterKnife.bind(this);
MarketBot.createNewStorageSession().inject(this);
w9jds/MarketBot
app/src/main/java/com/w9jds/marketbot/classes/modules/NetModule.java
// Path: app/src/main/java/com/w9jds/marketbot/classes/CrestService.java // public interface CrestService { // // @GET("/") // Observable<Response<CrestServerStatus>> getServer(); // // @GET("/market/types/") // Call<CrestDictionary<CrestMarketType>> getMarketTypes(@Query("page") int page); // // @GET("/inventory/types/{typeId}/") // Call<CrestType> getTypeInfo(@Path("typeId") long id); // // @GET("/market/groups/") // Observable<Response<CrestDictionary<CrestMarketGroup>>> getMarketGroups(); // // @GET("/regions/") // Observable<Response<CrestDictionary<CrestItem>>> getRegions(); // // @GET("/market/{regionId}/orders/{orderType}/") // Observable<Response<CrestDictionary<CrestMarketOrder>>> getMarketOrders(@Path("regionId") long regionId, // @Path("orderType") String orderType, // @Query(value = "type", encoded = true) String typeId); // // @GET("/market/{regionId}/orders/") // Observable<Response<CrestDictionary<CrestMarketOrder>>> getMarketOrders(@Path("regionId") long regionId, // @Query(value = "type", encoded = true) String typeId); // // @GET("/market/{regionId}/history/") // Call<CrestDictionary<CrestMarketHistory>> getMarketHistory(@Path("regionId") final long regionId, // @Query("type") final String typeRef); // // }
import android.app.Application; import com.w9jds.marketbot.classes.CrestService; import java.io.IOException; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import okhttp3.Cache; import okhttp3.Interceptor; import okhttp3.OkHttpClient; import okhttp3.Request; import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.jackson.JacksonConverterFactory;
@Provides @Singleton Cache provideOkHttpCache(Application application) { int cacheSize = 10 * 1024 * 1024; return new Cache(application.getCacheDir(), cacheSize); } @Provides @Singleton OkHttpClient provideOkHttpClient(Cache cache, Interceptor interceptor) { return new OkHttpClient.Builder() .cache(cache) .addInterceptor(interceptor) .build(); } @Provides @Singleton Retrofit providePublicRetrofit(OkHttpClient okHttpClient) { return new Retrofit.Builder() .baseUrl(TRANQUILITY) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .addConverterFactory(JacksonConverterFactory.create()) .client(okHttpClient) .build(); } @Provides @Singleton
// Path: app/src/main/java/com/w9jds/marketbot/classes/CrestService.java // public interface CrestService { // // @GET("/") // Observable<Response<CrestServerStatus>> getServer(); // // @GET("/market/types/") // Call<CrestDictionary<CrestMarketType>> getMarketTypes(@Query("page") int page); // // @GET("/inventory/types/{typeId}/") // Call<CrestType> getTypeInfo(@Path("typeId") long id); // // @GET("/market/groups/") // Observable<Response<CrestDictionary<CrestMarketGroup>>> getMarketGroups(); // // @GET("/regions/") // Observable<Response<CrestDictionary<CrestItem>>> getRegions(); // // @GET("/market/{regionId}/orders/{orderType}/") // Observable<Response<CrestDictionary<CrestMarketOrder>>> getMarketOrders(@Path("regionId") long regionId, // @Path("orderType") String orderType, // @Query(value = "type", encoded = true) String typeId); // // @GET("/market/{regionId}/orders/") // Observable<Response<CrestDictionary<CrestMarketOrder>>> getMarketOrders(@Path("regionId") long regionId, // @Query(value = "type", encoded = true) String typeId); // // @GET("/market/{regionId}/history/") // Call<CrestDictionary<CrestMarketHistory>> getMarketHistory(@Path("regionId") final long regionId, // @Query("type") final String typeRef); // // } // Path: app/src/main/java/com/w9jds/marketbot/classes/modules/NetModule.java import android.app.Application; import com.w9jds.marketbot.classes.CrestService; import java.io.IOException; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import okhttp3.Cache; import okhttp3.Interceptor; import okhttp3.OkHttpClient; import okhttp3.Request; import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.jackson.JacksonConverterFactory; @Provides @Singleton Cache provideOkHttpCache(Application application) { int cacheSize = 10 * 1024 * 1024; return new Cache(application.getCacheDir(), cacheSize); } @Provides @Singleton OkHttpClient provideOkHttpClient(Cache cache, Interceptor interceptor) { return new OkHttpClient.Builder() .cache(cache) .addInterceptor(interceptor) .build(); } @Provides @Singleton Retrofit providePublicRetrofit(OkHttpClient okHttpClient) { return new Retrofit.Builder() .baseUrl(TRANQUILITY) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .addConverterFactory(JacksonConverterFactory.create()) .client(okHttpClient) .build(); } @Provides @Singleton
public CrestService providePublicCrest(Retrofit retrofit) {
w9jds/MarketBot
app/src/main/java/com/w9jds/marketbot/ui/fragments/MarketHistoryTab.java
// Path: app/src/main/java/com/w9jds/marketbot/classes/models/MarketHistory.java // public final class MarketHistory { // // private int orderCount; // private double lowPrice; // private double highPrice; // private double averagePrice; // private long volume; // private long recordDate; // // public int getOrderCount() { // return orderCount; // } // // public double getAveragePrice() { // return averagePrice; // } // // public double getHighPrice() { // return highPrice; // } // // public double getLowPrice() { // return lowPrice; // } // // public long getVolume() { // return volume; // } // // public long getRecordDate() { // return recordDate; // } // // public static class Builder { // // private int orderCount; // private double lowPrice; // private double highPrice; // private double averagePrice; // private long volume; // private long recordDate; // // public Builder setOrderCount(int orderCount) { // this.orderCount = orderCount; // return this; // } // // public Builder setAveragePrice(double averagePrice) { // this.averagePrice = averagePrice; // return this; // } // // public Builder setHighPrice(double highPrice) { // this.highPrice = highPrice; // return this; // } // // public Builder setLowPrice(double lowPrice) { // this.lowPrice = lowPrice; // return this; // } // // public Builder setRecordDate(long recordDate) { // this.recordDate = recordDate; // return this; // } // // public Builder setVolume(long volume) { // this.volume = volume; // return this; // } // // public MarketHistory build() { // MarketHistory history = new MarketHistory(); // history.orderCount = orderCount; // history.lowPrice = lowPrice; // history.highPrice = highPrice; // history.averagePrice = averagePrice; // history.volume = volume; // history.recordDate = recordDate; // // return history; // } // } // } // // Path: app/src/main/java/com/w9jds/marketbot/utils/NumberUtils.java // public class NumberUtils { // // private static char[] c = new char[]{'k', 'M', 'B', 'T', 'P', 'E', 'Z', 'Y'}; // // public static String shortened(double n, int iteration) { // double d = ((long) n / 100) / 10.0; // boolean isRound = (d * 10) % 10 == 0; // return (d < 1000 ? ((d > 99.9 || isRound || (!isRound && d > 9.99) ? // (int) d * 10 / 10 : d + "") + "" + c[iteration]) : shortened(d, iteration + 1)); // } // }
import android.content.Context; import android.graphics.Color; import android.graphics.Paint; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.github.mikephil.charting.charts.CombinedChart; import com.github.mikephil.charting.components.XAxis; import com.github.mikephil.charting.components.YAxis; import com.github.mikephil.charting.data.BarData; import com.github.mikephil.charting.data.BarDataSet; import com.github.mikephil.charting.data.BarEntry; import com.github.mikephil.charting.data.CandleData; import com.github.mikephil.charting.data.CandleDataSet; import com.github.mikephil.charting.data.CandleEntry; import com.github.mikephil.charting.data.CombinedData; import com.github.mikephil.charting.data.Entry; import com.github.mikephil.charting.data.LineData; import com.github.mikephil.charting.data.LineDataSet; import com.w9jds.marketbot.R; import com.w9jds.marketbot.classes.models.MarketHistory; import com.w9jds.marketbot.utils.NumberUtils; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.Map; import butterknife.Bind; import butterknife.ButterKnife; import rx.functions.Action1; import rx.subjects.BehaviorSubject; import rx.subscriptions.CompositeSubscription;
package com.w9jds.marketbot.ui.fragments; public class MarketHistoryTab extends Fragment { static final String ARG_PAGE = "ARG_PAGE"; @Bind(R.id.combine_chart) CombinedChart chart; private YAxis rightAxis; private YAxis leftAxis; private XAxis xAxis; private CompositeSubscription subscriptions; private int position; public static MarketHistoryTab create(int page, BehaviorSubject<Map.Entry<Integer, List<?>>> behaviorSubject) { Bundle args = new Bundle(); args.putInt(ARG_PAGE, page); MarketHistoryTab fragment = new MarketHistoryTab(); fragment.setArguments(args); fragment.setRetainInstance(true); fragment.getSubscriptions().add(behaviorSubject .doOnError(Throwable::printStackTrace) .doOnNext(fragment.updateTab) .subscribe()); return fragment; } public MarketHistoryTab() { subscriptions = new CompositeSubscription(); } public Action1<Map.Entry<Integer, List<?>>> updateTab = historyEntries -> { if (historyEntries.getKey() == position && historyEntries.getValue().size() > 0) { SimpleDateFormat format = new SimpleDateFormat("MMM dd", Locale.getDefault()); int size = historyEntries.getValue().size();
// Path: app/src/main/java/com/w9jds/marketbot/classes/models/MarketHistory.java // public final class MarketHistory { // // private int orderCount; // private double lowPrice; // private double highPrice; // private double averagePrice; // private long volume; // private long recordDate; // // public int getOrderCount() { // return orderCount; // } // // public double getAveragePrice() { // return averagePrice; // } // // public double getHighPrice() { // return highPrice; // } // // public double getLowPrice() { // return lowPrice; // } // // public long getVolume() { // return volume; // } // // public long getRecordDate() { // return recordDate; // } // // public static class Builder { // // private int orderCount; // private double lowPrice; // private double highPrice; // private double averagePrice; // private long volume; // private long recordDate; // // public Builder setOrderCount(int orderCount) { // this.orderCount = orderCount; // return this; // } // // public Builder setAveragePrice(double averagePrice) { // this.averagePrice = averagePrice; // return this; // } // // public Builder setHighPrice(double highPrice) { // this.highPrice = highPrice; // return this; // } // // public Builder setLowPrice(double lowPrice) { // this.lowPrice = lowPrice; // return this; // } // // public Builder setRecordDate(long recordDate) { // this.recordDate = recordDate; // return this; // } // // public Builder setVolume(long volume) { // this.volume = volume; // return this; // } // // public MarketHistory build() { // MarketHistory history = new MarketHistory(); // history.orderCount = orderCount; // history.lowPrice = lowPrice; // history.highPrice = highPrice; // history.averagePrice = averagePrice; // history.volume = volume; // history.recordDate = recordDate; // // return history; // } // } // } // // Path: app/src/main/java/com/w9jds/marketbot/utils/NumberUtils.java // public class NumberUtils { // // private static char[] c = new char[]{'k', 'M', 'B', 'T', 'P', 'E', 'Z', 'Y'}; // // public static String shortened(double n, int iteration) { // double d = ((long) n / 100) / 10.0; // boolean isRound = (d * 10) % 10 == 0; // return (d < 1000 ? ((d > 99.9 || isRound || (!isRound && d > 9.99) ? // (int) d * 10 / 10 : d + "") + "" + c[iteration]) : shortened(d, iteration + 1)); // } // } // Path: app/src/main/java/com/w9jds/marketbot/ui/fragments/MarketHistoryTab.java import android.content.Context; import android.graphics.Color; import android.graphics.Paint; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.github.mikephil.charting.charts.CombinedChart; import com.github.mikephil.charting.components.XAxis; import com.github.mikephil.charting.components.YAxis; import com.github.mikephil.charting.data.BarData; import com.github.mikephil.charting.data.BarDataSet; import com.github.mikephil.charting.data.BarEntry; import com.github.mikephil.charting.data.CandleData; import com.github.mikephil.charting.data.CandleDataSet; import com.github.mikephil.charting.data.CandleEntry; import com.github.mikephil.charting.data.CombinedData; import com.github.mikephil.charting.data.Entry; import com.github.mikephil.charting.data.LineData; import com.github.mikephil.charting.data.LineDataSet; import com.w9jds.marketbot.R; import com.w9jds.marketbot.classes.models.MarketHistory; import com.w9jds.marketbot.utils.NumberUtils; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.Map; import butterknife.Bind; import butterknife.ButterKnife; import rx.functions.Action1; import rx.subjects.BehaviorSubject; import rx.subscriptions.CompositeSubscription; package com.w9jds.marketbot.ui.fragments; public class MarketHistoryTab extends Fragment { static final String ARG_PAGE = "ARG_PAGE"; @Bind(R.id.combine_chart) CombinedChart chart; private YAxis rightAxis; private YAxis leftAxis; private XAxis xAxis; private CompositeSubscription subscriptions; private int position; public static MarketHistoryTab create(int page, BehaviorSubject<Map.Entry<Integer, List<?>>> behaviorSubject) { Bundle args = new Bundle(); args.putInt(ARG_PAGE, page); MarketHistoryTab fragment = new MarketHistoryTab(); fragment.setArguments(args); fragment.setRetainInstance(true); fragment.getSubscriptions().add(behaviorSubject .doOnError(Throwable::printStackTrace) .doOnNext(fragment.updateTab) .subscribe()); return fragment; } public MarketHistoryTab() { subscriptions = new CompositeSubscription(); } public Action1<Map.Entry<Integer, List<?>>> updateTab = historyEntries -> { if (historyEntries.getKey() == position && historyEntries.getValue().size() > 0) { SimpleDateFormat format = new SimpleDateFormat("MMM dd", Locale.getDefault()); int size = historyEntries.getValue().size();
List<MarketHistory> histories = new ArrayList<>(size);
w9jds/MarketBot
app/src/main/java/com/w9jds/marketbot/ui/fragments/MarketHistoryTab.java
// Path: app/src/main/java/com/w9jds/marketbot/classes/models/MarketHistory.java // public final class MarketHistory { // // private int orderCount; // private double lowPrice; // private double highPrice; // private double averagePrice; // private long volume; // private long recordDate; // // public int getOrderCount() { // return orderCount; // } // // public double getAveragePrice() { // return averagePrice; // } // // public double getHighPrice() { // return highPrice; // } // // public double getLowPrice() { // return lowPrice; // } // // public long getVolume() { // return volume; // } // // public long getRecordDate() { // return recordDate; // } // // public static class Builder { // // private int orderCount; // private double lowPrice; // private double highPrice; // private double averagePrice; // private long volume; // private long recordDate; // // public Builder setOrderCount(int orderCount) { // this.orderCount = orderCount; // return this; // } // // public Builder setAveragePrice(double averagePrice) { // this.averagePrice = averagePrice; // return this; // } // // public Builder setHighPrice(double highPrice) { // this.highPrice = highPrice; // return this; // } // // public Builder setLowPrice(double lowPrice) { // this.lowPrice = lowPrice; // return this; // } // // public Builder setRecordDate(long recordDate) { // this.recordDate = recordDate; // return this; // } // // public Builder setVolume(long volume) { // this.volume = volume; // return this; // } // // public MarketHistory build() { // MarketHistory history = new MarketHistory(); // history.orderCount = orderCount; // history.lowPrice = lowPrice; // history.highPrice = highPrice; // history.averagePrice = averagePrice; // history.volume = volume; // history.recordDate = recordDate; // // return history; // } // } // } // // Path: app/src/main/java/com/w9jds/marketbot/utils/NumberUtils.java // public class NumberUtils { // // private static char[] c = new char[]{'k', 'M', 'B', 'T', 'P', 'E', 'Z', 'Y'}; // // public static String shortened(double n, int iteration) { // double d = ((long) n / 100) / 10.0; // boolean isRound = (d * 10) % 10 == 0; // return (d < 1000 ? ((d > 99.9 || isRound || (!isRound && d > 9.99) ? // (int) d * 10 / 10 : d + "") + "" + c[iteration]) : shortened(d, iteration + 1)); // } // }
import android.content.Context; import android.graphics.Color; import android.graphics.Paint; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.github.mikephil.charting.charts.CombinedChart; import com.github.mikephil.charting.components.XAxis; import com.github.mikephil.charting.components.YAxis; import com.github.mikephil.charting.data.BarData; import com.github.mikephil.charting.data.BarDataSet; import com.github.mikephil.charting.data.BarEntry; import com.github.mikephil.charting.data.CandleData; import com.github.mikephil.charting.data.CandleDataSet; import com.github.mikephil.charting.data.CandleEntry; import com.github.mikephil.charting.data.CombinedData; import com.github.mikephil.charting.data.Entry; import com.github.mikephil.charting.data.LineData; import com.github.mikephil.charting.data.LineDataSet; import com.w9jds.marketbot.R; import com.w9jds.marketbot.classes.models.MarketHistory; import com.w9jds.marketbot.utils.NumberUtils; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.Map; import butterknife.Bind; import butterknife.ButterKnife; import rx.functions.Action1; import rx.subjects.BehaviorSubject; import rx.subscriptions.CompositeSubscription;
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle args = getArguments(); position = args.getInt(ARG_PAGE); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_market_history, container, false); ButterKnife.bind(this, view); chart.setDescription(""); chart.setDrawGridBackground(true); chart.setGridBackgroundColor(Color.WHITE); chart.setMaxVisibleValueCount(40); chart.setDrawOrder(new CombinedChart.DrawOrder[] { CombinedChart.DrawOrder.BAR, CombinedChart.DrawOrder.CANDLE, CombinedChart.DrawOrder.LINE }); rightAxis = chart.getAxisRight(); rightAxis.setDrawGridLines(false); rightAxis.setAxisMinValue(0f); leftAxis = chart.getAxisLeft(); leftAxis.setDrawGridLines(false); leftAxis.setAxisMinValue(0f); leftAxis.setValueFormatter((value, yAxis) ->
// Path: app/src/main/java/com/w9jds/marketbot/classes/models/MarketHistory.java // public final class MarketHistory { // // private int orderCount; // private double lowPrice; // private double highPrice; // private double averagePrice; // private long volume; // private long recordDate; // // public int getOrderCount() { // return orderCount; // } // // public double getAveragePrice() { // return averagePrice; // } // // public double getHighPrice() { // return highPrice; // } // // public double getLowPrice() { // return lowPrice; // } // // public long getVolume() { // return volume; // } // // public long getRecordDate() { // return recordDate; // } // // public static class Builder { // // private int orderCount; // private double lowPrice; // private double highPrice; // private double averagePrice; // private long volume; // private long recordDate; // // public Builder setOrderCount(int orderCount) { // this.orderCount = orderCount; // return this; // } // // public Builder setAveragePrice(double averagePrice) { // this.averagePrice = averagePrice; // return this; // } // // public Builder setHighPrice(double highPrice) { // this.highPrice = highPrice; // return this; // } // // public Builder setLowPrice(double lowPrice) { // this.lowPrice = lowPrice; // return this; // } // // public Builder setRecordDate(long recordDate) { // this.recordDate = recordDate; // return this; // } // // public Builder setVolume(long volume) { // this.volume = volume; // return this; // } // // public MarketHistory build() { // MarketHistory history = new MarketHistory(); // history.orderCount = orderCount; // history.lowPrice = lowPrice; // history.highPrice = highPrice; // history.averagePrice = averagePrice; // history.volume = volume; // history.recordDate = recordDate; // // return history; // } // } // } // // Path: app/src/main/java/com/w9jds/marketbot/utils/NumberUtils.java // public class NumberUtils { // // private static char[] c = new char[]{'k', 'M', 'B', 'T', 'P', 'E', 'Z', 'Y'}; // // public static String shortened(double n, int iteration) { // double d = ((long) n / 100) / 10.0; // boolean isRound = (d * 10) % 10 == 0; // return (d < 1000 ? ((d > 99.9 || isRound || (!isRound && d > 9.99) ? // (int) d * 10 / 10 : d + "") + "" + c[iteration]) : shortened(d, iteration + 1)); // } // } // Path: app/src/main/java/com/w9jds/marketbot/ui/fragments/MarketHistoryTab.java import android.content.Context; import android.graphics.Color; import android.graphics.Paint; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.github.mikephil.charting.charts.CombinedChart; import com.github.mikephil.charting.components.XAxis; import com.github.mikephil.charting.components.YAxis; import com.github.mikephil.charting.data.BarData; import com.github.mikephil.charting.data.BarDataSet; import com.github.mikephil.charting.data.BarEntry; import com.github.mikephil.charting.data.CandleData; import com.github.mikephil.charting.data.CandleDataSet; import com.github.mikephil.charting.data.CandleEntry; import com.github.mikephil.charting.data.CombinedData; import com.github.mikephil.charting.data.Entry; import com.github.mikephil.charting.data.LineData; import com.github.mikephil.charting.data.LineDataSet; import com.w9jds.marketbot.R; import com.w9jds.marketbot.classes.models.MarketHistory; import com.w9jds.marketbot.utils.NumberUtils; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.Map; import butterknife.Bind; import butterknife.ButterKnife; import rx.functions.Action1; import rx.subjects.BehaviorSubject; import rx.subscriptions.CompositeSubscription; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle args = getArguments(); position = args.getInt(ARG_PAGE); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_market_history, container, false); ButterKnife.bind(this, view); chart.setDescription(""); chart.setDrawGridBackground(true); chart.setGridBackgroundColor(Color.WHITE); chart.setMaxVisibleValueCount(40); chart.setDrawOrder(new CombinedChart.DrawOrder[] { CombinedChart.DrawOrder.BAR, CombinedChart.DrawOrder.CANDLE, CombinedChart.DrawOrder.LINE }); rightAxis = chart.getAxisRight(); rightAxis.setDrawGridLines(false); rightAxis.setAxisMinValue(0f); leftAxis = chart.getAxisLeft(); leftAxis.setDrawGridLines(false); leftAxis.setAxisMinValue(0f); leftAxis.setValueFormatter((value, yAxis) ->
value < 1000 ? String.valueOf(value) : NumberUtils.shortened(value, 0));
w9jds/MarketBot
app/src/main/java/com/w9jds/marketbot/classes/MarketBot.java
// Path: app/src/main/java/com/w9jds/marketbot/classes/modules/ApplicationModule.java // @Module // public class ApplicationModule { // // private Application application; // // public ApplicationModule(Application application) { // this.application = application; // } // // @Provides // @Singleton // Application provideApplication() { // return application; // } // // @Provides // @Singleton // SharedPreferences provideSharedPreferences(Application application) { // return PreferenceManager.getDefaultSharedPreferences(application); // } // // } // // Path: app/src/main/java/com/w9jds/marketbot/classes/modules/NetModule.java // @Module // public class NetModule { // // public static final String SINGULARITY = "https://api-sisi.testeveonline.com/"; // public static final String TRANQUILITY = "https://crest-tq.eveonline.com/"; // // String mBaseUrl; // // public NetModule(String baseUrl) { // this.mBaseUrl = baseUrl; // } // // @Provides // @Singleton // Interceptor provideInterceptor() { // return chain -> { // Request request = chain.request(); // // request = request.newBuilder() // .addHeader("User-Agent", "MarketBot by Jeremy Shore") // .build(); // // return chain.proceed(request); // }; // } // // @Provides // @Singleton // Cache provideOkHttpCache(Application application) { // int cacheSize = 10 * 1024 * 1024; // return new Cache(application.getCacheDir(), cacheSize); // } // // @Provides // @Singleton // OkHttpClient provideOkHttpClient(Cache cache, Interceptor interceptor) { // return new OkHttpClient.Builder() // .cache(cache) // .addInterceptor(interceptor) // .build(); // } // // @Provides // @Singleton // Retrofit providePublicRetrofit(OkHttpClient okHttpClient) { // return new Retrofit.Builder() // .baseUrl(TRANQUILITY) // .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // .addConverterFactory(JacksonConverterFactory.create()) // .client(okHttpClient) // .build(); // } // // @Provides // @Singleton // public CrestService providePublicCrest(Retrofit retrofit) { // return retrofit.create(CrestService.class); // } // } // // Path: app/src/main/java/com/w9jds/marketbot/classes/modules/StorageModule.java // @Module // public class StorageModule { // // public StorageModule() { // // } // // @Provides // @StorageScope // String provideServerVersion(SharedPreferences sharedPreferences) { // return sharedPreferences.getString("serverVersion", ""); // } // // @Provides // @StorageScope // boolean provideFirstRun(SharedPreferences sharedPreferences) { // return sharedPreferences.getBoolean("isFirstRun", true); // } // // @Provides // @StorageScope // long provideRegionId(SharedPreferences sharedPreferences) { // return sharedPreferences.getLong("regionId", 10000002); // } // // }
import android.app.Application; import com.raizlabs.android.dbflow.config.FlowManager; import com.w9jds.marketbot.classes.components.*; import com.w9jds.marketbot.classes.modules.ApplicationModule; import com.w9jds.marketbot.classes.modules.NetModule; import com.w9jds.marketbot.classes.modules.StorageModule;
package com.w9jds.marketbot.classes; public class MarketBot extends Application { private static BaseComponent baseComponent; @Override public void onCreate() { super.onCreate(); FlowManager.init(this); baseComponent = DaggerBaseComponent.builder()
// Path: app/src/main/java/com/w9jds/marketbot/classes/modules/ApplicationModule.java // @Module // public class ApplicationModule { // // private Application application; // // public ApplicationModule(Application application) { // this.application = application; // } // // @Provides // @Singleton // Application provideApplication() { // return application; // } // // @Provides // @Singleton // SharedPreferences provideSharedPreferences(Application application) { // return PreferenceManager.getDefaultSharedPreferences(application); // } // // } // // Path: app/src/main/java/com/w9jds/marketbot/classes/modules/NetModule.java // @Module // public class NetModule { // // public static final String SINGULARITY = "https://api-sisi.testeveonline.com/"; // public static final String TRANQUILITY = "https://crest-tq.eveonline.com/"; // // String mBaseUrl; // // public NetModule(String baseUrl) { // this.mBaseUrl = baseUrl; // } // // @Provides // @Singleton // Interceptor provideInterceptor() { // return chain -> { // Request request = chain.request(); // // request = request.newBuilder() // .addHeader("User-Agent", "MarketBot by Jeremy Shore") // .build(); // // return chain.proceed(request); // }; // } // // @Provides // @Singleton // Cache provideOkHttpCache(Application application) { // int cacheSize = 10 * 1024 * 1024; // return new Cache(application.getCacheDir(), cacheSize); // } // // @Provides // @Singleton // OkHttpClient provideOkHttpClient(Cache cache, Interceptor interceptor) { // return new OkHttpClient.Builder() // .cache(cache) // .addInterceptor(interceptor) // .build(); // } // // @Provides // @Singleton // Retrofit providePublicRetrofit(OkHttpClient okHttpClient) { // return new Retrofit.Builder() // .baseUrl(TRANQUILITY) // .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // .addConverterFactory(JacksonConverterFactory.create()) // .client(okHttpClient) // .build(); // } // // @Provides // @Singleton // public CrestService providePublicCrest(Retrofit retrofit) { // return retrofit.create(CrestService.class); // } // } // // Path: app/src/main/java/com/w9jds/marketbot/classes/modules/StorageModule.java // @Module // public class StorageModule { // // public StorageModule() { // // } // // @Provides // @StorageScope // String provideServerVersion(SharedPreferences sharedPreferences) { // return sharedPreferences.getString("serverVersion", ""); // } // // @Provides // @StorageScope // boolean provideFirstRun(SharedPreferences sharedPreferences) { // return sharedPreferences.getBoolean("isFirstRun", true); // } // // @Provides // @StorageScope // long provideRegionId(SharedPreferences sharedPreferences) { // return sharedPreferences.getLong("regionId", 10000002); // } // // } // Path: app/src/main/java/com/w9jds/marketbot/classes/MarketBot.java import android.app.Application; import com.raizlabs.android.dbflow.config.FlowManager; import com.w9jds.marketbot.classes.components.*; import com.w9jds.marketbot.classes.modules.ApplicationModule; import com.w9jds.marketbot.classes.modules.NetModule; import com.w9jds.marketbot.classes.modules.StorageModule; package com.w9jds.marketbot.classes; public class MarketBot extends Application { private static BaseComponent baseComponent; @Override public void onCreate() { super.onCreate(); FlowManager.init(this); baseComponent = DaggerBaseComponent.builder()
.applicationModule(new ApplicationModule(this))
w9jds/MarketBot
app/src/main/java/com/w9jds/marketbot/classes/MarketBot.java
// Path: app/src/main/java/com/w9jds/marketbot/classes/modules/ApplicationModule.java // @Module // public class ApplicationModule { // // private Application application; // // public ApplicationModule(Application application) { // this.application = application; // } // // @Provides // @Singleton // Application provideApplication() { // return application; // } // // @Provides // @Singleton // SharedPreferences provideSharedPreferences(Application application) { // return PreferenceManager.getDefaultSharedPreferences(application); // } // // } // // Path: app/src/main/java/com/w9jds/marketbot/classes/modules/NetModule.java // @Module // public class NetModule { // // public static final String SINGULARITY = "https://api-sisi.testeveonline.com/"; // public static final String TRANQUILITY = "https://crest-tq.eveonline.com/"; // // String mBaseUrl; // // public NetModule(String baseUrl) { // this.mBaseUrl = baseUrl; // } // // @Provides // @Singleton // Interceptor provideInterceptor() { // return chain -> { // Request request = chain.request(); // // request = request.newBuilder() // .addHeader("User-Agent", "MarketBot by Jeremy Shore") // .build(); // // return chain.proceed(request); // }; // } // // @Provides // @Singleton // Cache provideOkHttpCache(Application application) { // int cacheSize = 10 * 1024 * 1024; // return new Cache(application.getCacheDir(), cacheSize); // } // // @Provides // @Singleton // OkHttpClient provideOkHttpClient(Cache cache, Interceptor interceptor) { // return new OkHttpClient.Builder() // .cache(cache) // .addInterceptor(interceptor) // .build(); // } // // @Provides // @Singleton // Retrofit providePublicRetrofit(OkHttpClient okHttpClient) { // return new Retrofit.Builder() // .baseUrl(TRANQUILITY) // .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // .addConverterFactory(JacksonConverterFactory.create()) // .client(okHttpClient) // .build(); // } // // @Provides // @Singleton // public CrestService providePublicCrest(Retrofit retrofit) { // return retrofit.create(CrestService.class); // } // } // // Path: app/src/main/java/com/w9jds/marketbot/classes/modules/StorageModule.java // @Module // public class StorageModule { // // public StorageModule() { // // } // // @Provides // @StorageScope // String provideServerVersion(SharedPreferences sharedPreferences) { // return sharedPreferences.getString("serverVersion", ""); // } // // @Provides // @StorageScope // boolean provideFirstRun(SharedPreferences sharedPreferences) { // return sharedPreferences.getBoolean("isFirstRun", true); // } // // @Provides // @StorageScope // long provideRegionId(SharedPreferences sharedPreferences) { // return sharedPreferences.getLong("regionId", 10000002); // } // // }
import android.app.Application; import com.raizlabs.android.dbflow.config.FlowManager; import com.w9jds.marketbot.classes.components.*; import com.w9jds.marketbot.classes.modules.ApplicationModule; import com.w9jds.marketbot.classes.modules.NetModule; import com.w9jds.marketbot.classes.modules.StorageModule;
package com.w9jds.marketbot.classes; public class MarketBot extends Application { private static BaseComponent baseComponent; @Override public void onCreate() { super.onCreate(); FlowManager.init(this); baseComponent = DaggerBaseComponent.builder() .applicationModule(new ApplicationModule(this))
// Path: app/src/main/java/com/w9jds/marketbot/classes/modules/ApplicationModule.java // @Module // public class ApplicationModule { // // private Application application; // // public ApplicationModule(Application application) { // this.application = application; // } // // @Provides // @Singleton // Application provideApplication() { // return application; // } // // @Provides // @Singleton // SharedPreferences provideSharedPreferences(Application application) { // return PreferenceManager.getDefaultSharedPreferences(application); // } // // } // // Path: app/src/main/java/com/w9jds/marketbot/classes/modules/NetModule.java // @Module // public class NetModule { // // public static final String SINGULARITY = "https://api-sisi.testeveonline.com/"; // public static final String TRANQUILITY = "https://crest-tq.eveonline.com/"; // // String mBaseUrl; // // public NetModule(String baseUrl) { // this.mBaseUrl = baseUrl; // } // // @Provides // @Singleton // Interceptor provideInterceptor() { // return chain -> { // Request request = chain.request(); // // request = request.newBuilder() // .addHeader("User-Agent", "MarketBot by Jeremy Shore") // .build(); // // return chain.proceed(request); // }; // } // // @Provides // @Singleton // Cache provideOkHttpCache(Application application) { // int cacheSize = 10 * 1024 * 1024; // return new Cache(application.getCacheDir(), cacheSize); // } // // @Provides // @Singleton // OkHttpClient provideOkHttpClient(Cache cache, Interceptor interceptor) { // return new OkHttpClient.Builder() // .cache(cache) // .addInterceptor(interceptor) // .build(); // } // // @Provides // @Singleton // Retrofit providePublicRetrofit(OkHttpClient okHttpClient) { // return new Retrofit.Builder() // .baseUrl(TRANQUILITY) // .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // .addConverterFactory(JacksonConverterFactory.create()) // .client(okHttpClient) // .build(); // } // // @Provides // @Singleton // public CrestService providePublicCrest(Retrofit retrofit) { // return retrofit.create(CrestService.class); // } // } // // Path: app/src/main/java/com/w9jds/marketbot/classes/modules/StorageModule.java // @Module // public class StorageModule { // // public StorageModule() { // // } // // @Provides // @StorageScope // String provideServerVersion(SharedPreferences sharedPreferences) { // return sharedPreferences.getString("serverVersion", ""); // } // // @Provides // @StorageScope // boolean provideFirstRun(SharedPreferences sharedPreferences) { // return sharedPreferences.getBoolean("isFirstRun", true); // } // // @Provides // @StorageScope // long provideRegionId(SharedPreferences sharedPreferences) { // return sharedPreferences.getLong("regionId", 10000002); // } // // } // Path: app/src/main/java/com/w9jds/marketbot/classes/MarketBot.java import android.app.Application; import com.raizlabs.android.dbflow.config.FlowManager; import com.w9jds.marketbot.classes.components.*; import com.w9jds.marketbot.classes.modules.ApplicationModule; import com.w9jds.marketbot.classes.modules.NetModule; import com.w9jds.marketbot.classes.modules.StorageModule; package com.w9jds.marketbot.classes; public class MarketBot extends Application { private static BaseComponent baseComponent; @Override public void onCreate() { super.onCreate(); FlowManager.init(this); baseComponent = DaggerBaseComponent.builder() .applicationModule(new ApplicationModule(this))
.netModule(new NetModule(NetModule.TRANQUILITY))
w9jds/MarketBot
app/src/main/java/com/w9jds/marketbot/classes/MarketBot.java
// Path: app/src/main/java/com/w9jds/marketbot/classes/modules/ApplicationModule.java // @Module // public class ApplicationModule { // // private Application application; // // public ApplicationModule(Application application) { // this.application = application; // } // // @Provides // @Singleton // Application provideApplication() { // return application; // } // // @Provides // @Singleton // SharedPreferences provideSharedPreferences(Application application) { // return PreferenceManager.getDefaultSharedPreferences(application); // } // // } // // Path: app/src/main/java/com/w9jds/marketbot/classes/modules/NetModule.java // @Module // public class NetModule { // // public static final String SINGULARITY = "https://api-sisi.testeveonline.com/"; // public static final String TRANQUILITY = "https://crest-tq.eveonline.com/"; // // String mBaseUrl; // // public NetModule(String baseUrl) { // this.mBaseUrl = baseUrl; // } // // @Provides // @Singleton // Interceptor provideInterceptor() { // return chain -> { // Request request = chain.request(); // // request = request.newBuilder() // .addHeader("User-Agent", "MarketBot by Jeremy Shore") // .build(); // // return chain.proceed(request); // }; // } // // @Provides // @Singleton // Cache provideOkHttpCache(Application application) { // int cacheSize = 10 * 1024 * 1024; // return new Cache(application.getCacheDir(), cacheSize); // } // // @Provides // @Singleton // OkHttpClient provideOkHttpClient(Cache cache, Interceptor interceptor) { // return new OkHttpClient.Builder() // .cache(cache) // .addInterceptor(interceptor) // .build(); // } // // @Provides // @Singleton // Retrofit providePublicRetrofit(OkHttpClient okHttpClient) { // return new Retrofit.Builder() // .baseUrl(TRANQUILITY) // .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // .addConverterFactory(JacksonConverterFactory.create()) // .client(okHttpClient) // .build(); // } // // @Provides // @Singleton // public CrestService providePublicCrest(Retrofit retrofit) { // return retrofit.create(CrestService.class); // } // } // // Path: app/src/main/java/com/w9jds/marketbot/classes/modules/StorageModule.java // @Module // public class StorageModule { // // public StorageModule() { // // } // // @Provides // @StorageScope // String provideServerVersion(SharedPreferences sharedPreferences) { // return sharedPreferences.getString("serverVersion", ""); // } // // @Provides // @StorageScope // boolean provideFirstRun(SharedPreferences sharedPreferences) { // return sharedPreferences.getBoolean("isFirstRun", true); // } // // @Provides // @StorageScope // long provideRegionId(SharedPreferences sharedPreferences) { // return sharedPreferences.getLong("regionId", 10000002); // } // // }
import android.app.Application; import com.raizlabs.android.dbflow.config.FlowManager; import com.w9jds.marketbot.classes.components.*; import com.w9jds.marketbot.classes.modules.ApplicationModule; import com.w9jds.marketbot.classes.modules.NetModule; import com.w9jds.marketbot.classes.modules.StorageModule;
package com.w9jds.marketbot.classes; public class MarketBot extends Application { private static BaseComponent baseComponent; @Override public void onCreate() { super.onCreate(); FlowManager.init(this); baseComponent = DaggerBaseComponent.builder() .applicationModule(new ApplicationModule(this)) .netModule(new NetModule(NetModule.TRANQUILITY)) .build(); } public static StorageComponent createNewStorageSession() { return DaggerStorageComponent.builder() .baseComponent(baseComponent)
// Path: app/src/main/java/com/w9jds/marketbot/classes/modules/ApplicationModule.java // @Module // public class ApplicationModule { // // private Application application; // // public ApplicationModule(Application application) { // this.application = application; // } // // @Provides // @Singleton // Application provideApplication() { // return application; // } // // @Provides // @Singleton // SharedPreferences provideSharedPreferences(Application application) { // return PreferenceManager.getDefaultSharedPreferences(application); // } // // } // // Path: app/src/main/java/com/w9jds/marketbot/classes/modules/NetModule.java // @Module // public class NetModule { // // public static final String SINGULARITY = "https://api-sisi.testeveonline.com/"; // public static final String TRANQUILITY = "https://crest-tq.eveonline.com/"; // // String mBaseUrl; // // public NetModule(String baseUrl) { // this.mBaseUrl = baseUrl; // } // // @Provides // @Singleton // Interceptor provideInterceptor() { // return chain -> { // Request request = chain.request(); // // request = request.newBuilder() // .addHeader("User-Agent", "MarketBot by Jeremy Shore") // .build(); // // return chain.proceed(request); // }; // } // // @Provides // @Singleton // Cache provideOkHttpCache(Application application) { // int cacheSize = 10 * 1024 * 1024; // return new Cache(application.getCacheDir(), cacheSize); // } // // @Provides // @Singleton // OkHttpClient provideOkHttpClient(Cache cache, Interceptor interceptor) { // return new OkHttpClient.Builder() // .cache(cache) // .addInterceptor(interceptor) // .build(); // } // // @Provides // @Singleton // Retrofit providePublicRetrofit(OkHttpClient okHttpClient) { // return new Retrofit.Builder() // .baseUrl(TRANQUILITY) // .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // .addConverterFactory(JacksonConverterFactory.create()) // .client(okHttpClient) // .build(); // } // // @Provides // @Singleton // public CrestService providePublicCrest(Retrofit retrofit) { // return retrofit.create(CrestService.class); // } // } // // Path: app/src/main/java/com/w9jds/marketbot/classes/modules/StorageModule.java // @Module // public class StorageModule { // // public StorageModule() { // // } // // @Provides // @StorageScope // String provideServerVersion(SharedPreferences sharedPreferences) { // return sharedPreferences.getString("serverVersion", ""); // } // // @Provides // @StorageScope // boolean provideFirstRun(SharedPreferences sharedPreferences) { // return sharedPreferences.getBoolean("isFirstRun", true); // } // // @Provides // @StorageScope // long provideRegionId(SharedPreferences sharedPreferences) { // return sharedPreferences.getLong("regionId", 10000002); // } // // } // Path: app/src/main/java/com/w9jds/marketbot/classes/MarketBot.java import android.app.Application; import com.raizlabs.android.dbflow.config.FlowManager; import com.w9jds.marketbot.classes.components.*; import com.w9jds.marketbot.classes.modules.ApplicationModule; import com.w9jds.marketbot.classes.modules.NetModule; import com.w9jds.marketbot.classes.modules.StorageModule; package com.w9jds.marketbot.classes; public class MarketBot extends Application { private static BaseComponent baseComponent; @Override public void onCreate() { super.onCreate(); FlowManager.init(this); baseComponent = DaggerBaseComponent.builder() .applicationModule(new ApplicationModule(this)) .netModule(new NetModule(NetModule.TRANQUILITY)) .build(); } public static StorageComponent createNewStorageSession() { return DaggerStorageComponent.builder() .baseComponent(baseComponent)
.storageModule(new StorageModule())
w9jds/MarketBot
app/src/main/java/com/w9jds/marketbot/data/storage/MarketGroupEntry.java
// Path: app/src/main/java/com/w9jds/marketbot/classes/models/MarketGroup.java // public final class MarketGroup extends MarketItemBase { // // private String parentGroupRef; // private long parentId; // private String href; // private String description; // private String types; // // public MarketGroup() { // // } // // public String getDescription() { // return description; // } // // public String getHref() { // return href; // } // // public String getTypesLocation() { // return types; // } // // public String getParentGroup() { // return parentGroupRef; // } // // public long getParentId() { // return this.parentId; // } // // public boolean hasParent() { // return this.parentGroupRef != null && !this.parentGroupRef.equals(""); // } // // public static class Builder { // // private long id; // private String name; // private String parentGroup; // private long parentId; // private String href; // private String description; // private String types; // // public Builder setParentGroup(String parentGroup) { // this.parentGroup = parentGroup; // return this; // } // // public Builder setHref(String href) { // this.href = href; // return this; // } // // public Builder setDescription(String description) { // this.description = description; // return this; // } // // public Builder setTypes(String types) { // this.types = types; // return this; // } // // public Builder setName(String name) { // this.name = name; // return this; // } // // public Builder setId(long id) { // this.id = id; // return this; // } // // public Builder setParentId(long id) { // this.parentId = id; // return this; // } // // public MarketGroup build() { // MarketGroup group = new MarketGroup(); // group.id = id; // group.name = name; // // if (parentGroup != null) { // group.parentGroupRef = this.parentGroup; // group.parentId = this.parentId; // } // // group.href = this.href; // group.description = this.description; // group.types = this.types; // // return group; // } // } // // } // // Path: app/src/main/java/com/w9jds/marketbot/data/MarketDatabase.java // @Database(name = MarketDatabase.NAME, version = MarketDatabase.VERSION) // public class MarketDatabase { // // public static final String NAME = "MarketBotDb"; // public static final int VERSION = 3; // // // public interface TransactionListener { // void onTransactionProgressUpdate(int progress, int max); // } // }
import com.raizlabs.android.dbflow.annotation.Column; import com.raizlabs.android.dbflow.annotation.PrimaryKey; import com.raizlabs.android.dbflow.annotation.Table; import com.raizlabs.android.dbflow.runtime.DBTransactionQueue; import com.raizlabs.android.dbflow.runtime.TransactionManager; import com.raizlabs.android.dbflow.runtime.transaction.process.ProcessModelInfo; import com.raizlabs.android.dbflow.runtime.transaction.process.SaveModelTransaction; import com.raizlabs.android.dbflow.sql.language.Condition; import com.raizlabs.android.dbflow.sql.language.OrderBy; import com.raizlabs.android.dbflow.sql.language.Select; import com.raizlabs.android.dbflow.structure.BaseModel; import com.w9jds.marketbot.classes.models.MarketGroup; import com.w9jds.marketbot.data.MarketDatabase; import org.devfleet.crest.model.CrestMarketGroup; import java.util.ArrayList; import java.util.List;
@Column Long parentId; @Column String parent; @Column String types; public static void addNewMarketGroups(List<CrestMarketGroup> groups) { int count = groups.size(); List<MarketGroupEntry> entries = new ArrayList<>(count); for (int i = 0; i < count; i++) { CrestMarketGroup group = groups.get(i); MarketGroupEntry entry = new MarketGroupEntry(); entry.id = group.getId(); entry.description = group.getDescription(); entry.name = group.getName(); entry.href = group.getHref(); entry.parent = group.hasParent() ? group.getParentRef() : null; entry.parentId = group.hasParent() ? group.getParentId() : null; entry.types = group.getTypeRef(); entries.add(entry); } TransactionManager.getInstance().addTransaction(new SaveModelTransaction<>( ProcessModelInfo.withModels(entries))); }
// Path: app/src/main/java/com/w9jds/marketbot/classes/models/MarketGroup.java // public final class MarketGroup extends MarketItemBase { // // private String parentGroupRef; // private long parentId; // private String href; // private String description; // private String types; // // public MarketGroup() { // // } // // public String getDescription() { // return description; // } // // public String getHref() { // return href; // } // // public String getTypesLocation() { // return types; // } // // public String getParentGroup() { // return parentGroupRef; // } // // public long getParentId() { // return this.parentId; // } // // public boolean hasParent() { // return this.parentGroupRef != null && !this.parentGroupRef.equals(""); // } // // public static class Builder { // // private long id; // private String name; // private String parentGroup; // private long parentId; // private String href; // private String description; // private String types; // // public Builder setParentGroup(String parentGroup) { // this.parentGroup = parentGroup; // return this; // } // // public Builder setHref(String href) { // this.href = href; // return this; // } // // public Builder setDescription(String description) { // this.description = description; // return this; // } // // public Builder setTypes(String types) { // this.types = types; // return this; // } // // public Builder setName(String name) { // this.name = name; // return this; // } // // public Builder setId(long id) { // this.id = id; // return this; // } // // public Builder setParentId(long id) { // this.parentId = id; // return this; // } // // public MarketGroup build() { // MarketGroup group = new MarketGroup(); // group.id = id; // group.name = name; // // if (parentGroup != null) { // group.parentGroupRef = this.parentGroup; // group.parentId = this.parentId; // } // // group.href = this.href; // group.description = this.description; // group.types = this.types; // // return group; // } // } // // } // // Path: app/src/main/java/com/w9jds/marketbot/data/MarketDatabase.java // @Database(name = MarketDatabase.NAME, version = MarketDatabase.VERSION) // public class MarketDatabase { // // public static final String NAME = "MarketBotDb"; // public static final int VERSION = 3; // // // public interface TransactionListener { // void onTransactionProgressUpdate(int progress, int max); // } // } // Path: app/src/main/java/com/w9jds/marketbot/data/storage/MarketGroupEntry.java import com.raizlabs.android.dbflow.annotation.Column; import com.raizlabs.android.dbflow.annotation.PrimaryKey; import com.raizlabs.android.dbflow.annotation.Table; import com.raizlabs.android.dbflow.runtime.DBTransactionQueue; import com.raizlabs.android.dbflow.runtime.TransactionManager; import com.raizlabs.android.dbflow.runtime.transaction.process.ProcessModelInfo; import com.raizlabs.android.dbflow.runtime.transaction.process.SaveModelTransaction; import com.raizlabs.android.dbflow.sql.language.Condition; import com.raizlabs.android.dbflow.sql.language.OrderBy; import com.raizlabs.android.dbflow.sql.language.Select; import com.raizlabs.android.dbflow.structure.BaseModel; import com.w9jds.marketbot.classes.models.MarketGroup; import com.w9jds.marketbot.data.MarketDatabase; import org.devfleet.crest.model.CrestMarketGroup; import java.util.ArrayList; import java.util.List; @Column Long parentId; @Column String parent; @Column String types; public static void addNewMarketGroups(List<CrestMarketGroup> groups) { int count = groups.size(); List<MarketGroupEntry> entries = new ArrayList<>(count); for (int i = 0; i < count; i++) { CrestMarketGroup group = groups.get(i); MarketGroupEntry entry = new MarketGroupEntry(); entry.id = group.getId(); entry.description = group.getDescription(); entry.name = group.getName(); entry.href = group.getHref(); entry.parent = group.hasParent() ? group.getParentRef() : null; entry.parentId = group.hasParent() ? group.getParentId() : null; entry.types = group.getTypeRef(); entries.add(entry); } TransactionManager.getInstance().addTransaction(new SaveModelTransaction<>( ProcessModelInfo.withModels(entries))); }
public static ArrayList<MarketGroup> getMarketGroupsForParent(Long parentId) {
w9jds/MarketBot
app/src/main/java/com/w9jds/marketbot/data/storage/RegionEntry.java
// Path: app/src/main/java/com/w9jds/marketbot/classes/models/Region.java // public final class Region extends MarketItemBase { // // private String href; // // public String getHref() { // return href; // } // // public static class Builder { // // private long id; // private String name; // private String href; // // public Builder setId(long id) { // this.id = id; // return this; // } // // public Builder setHref(String href) { // this.href = href; // return this; // } // // public Builder setName(String name) { // this.name = name; // return this; // } // // public Region build() { // Region region = new Region(); // region.id = this.id; // region.name = this.name; // region.href = this.href; // // return region; // } // } // // } // // Path: app/src/main/java/com/w9jds/marketbot/data/MarketDatabase.java // @Database(name = MarketDatabase.NAME, version = MarketDatabase.VERSION) // public class MarketDatabase { // // public static final String NAME = "MarketBotDb"; // public static final int VERSION = 3; // // // public interface TransactionListener { // void onTransactionProgressUpdate(int progress, int max); // } // }
import com.raizlabs.android.dbflow.annotation.Column; import com.raizlabs.android.dbflow.annotation.PrimaryKey; import com.raizlabs.android.dbflow.annotation.Table; import com.raizlabs.android.dbflow.runtime.TransactionManager; import com.raizlabs.android.dbflow.runtime.transaction.process.ProcessModelInfo; import com.raizlabs.android.dbflow.runtime.transaction.process.SaveModelTransaction; import com.raizlabs.android.dbflow.sql.language.OrderBy; import com.raizlabs.android.dbflow.sql.language.Select; import com.raizlabs.android.dbflow.structure.BaseModel; import com.w9jds.marketbot.classes.models.Region; import com.w9jds.marketbot.data.MarketDatabase; import org.devfleet.crest.model.CrestItem; import java.util.ArrayList; import java.util.List;
package com.w9jds.marketbot.data.storage; @Table(database = MarketDatabase.class, name = "Regions") public final class RegionEntry extends BaseModel { @PrimaryKey long id; @Column String name; @Column String href; public static void addRegions(List<CrestItem> regions) { int size = regions.size(); List<RegionEntry> entries = new ArrayList<>(size); for (int i = 0; i < size; i++) { CrestItem region = regions.get(i); RegionEntry entry = new RegionEntry(); entry.id = region.getId(); entry.name = region.getName(); entry.href = region.getHref(); entries.add(entry); } TransactionManager.getInstance().addTransaction(new SaveModelTransaction<>( ProcessModelInfo.withModels(entries))); }
// Path: app/src/main/java/com/w9jds/marketbot/classes/models/Region.java // public final class Region extends MarketItemBase { // // private String href; // // public String getHref() { // return href; // } // // public static class Builder { // // private long id; // private String name; // private String href; // // public Builder setId(long id) { // this.id = id; // return this; // } // // public Builder setHref(String href) { // this.href = href; // return this; // } // // public Builder setName(String name) { // this.name = name; // return this; // } // // public Region build() { // Region region = new Region(); // region.id = this.id; // region.name = this.name; // region.href = this.href; // // return region; // } // } // // } // // Path: app/src/main/java/com/w9jds/marketbot/data/MarketDatabase.java // @Database(name = MarketDatabase.NAME, version = MarketDatabase.VERSION) // public class MarketDatabase { // // public static final String NAME = "MarketBotDb"; // public static final int VERSION = 3; // // // public interface TransactionListener { // void onTransactionProgressUpdate(int progress, int max); // } // } // Path: app/src/main/java/com/w9jds/marketbot/data/storage/RegionEntry.java import com.raizlabs.android.dbflow.annotation.Column; import com.raizlabs.android.dbflow.annotation.PrimaryKey; import com.raizlabs.android.dbflow.annotation.Table; import com.raizlabs.android.dbflow.runtime.TransactionManager; import com.raizlabs.android.dbflow.runtime.transaction.process.ProcessModelInfo; import com.raizlabs.android.dbflow.runtime.transaction.process.SaveModelTransaction; import com.raizlabs.android.dbflow.sql.language.OrderBy; import com.raizlabs.android.dbflow.sql.language.Select; import com.raizlabs.android.dbflow.structure.BaseModel; import com.w9jds.marketbot.classes.models.Region; import com.w9jds.marketbot.data.MarketDatabase; import org.devfleet.crest.model.CrestItem; import java.util.ArrayList; import java.util.List; package com.w9jds.marketbot.data.storage; @Table(database = MarketDatabase.class, name = "Regions") public final class RegionEntry extends BaseModel { @PrimaryKey long id; @Column String name; @Column String href; public static void addRegions(List<CrestItem> regions) { int size = regions.size(); List<RegionEntry> entries = new ArrayList<>(size); for (int i = 0; i < size; i++) { CrestItem region = regions.get(i); RegionEntry entry = new RegionEntry(); entry.id = region.getId(); entry.name = region.getName(); entry.href = region.getHref(); entries.add(entry); } TransactionManager.getInstance().addTransaction(new SaveModelTransaction<>( ProcessModelInfo.withModels(entries))); }
private static List<Region> buildRegions(List<RegionEntry> entries) {
w9jds/MarketBot
app/src/main/java/com/w9jds/marketbot/services/BotJobService.java
// Path: app/src/main/java/com/w9jds/marketbot/classes/CrestService.java // public interface CrestService { // // @GET("/") // Observable<Response<CrestServerStatus>> getServer(); // // @GET("/market/types/") // Call<CrestDictionary<CrestMarketType>> getMarketTypes(@Query("page") int page); // // @GET("/inventory/types/{typeId}/") // Call<CrestType> getTypeInfo(@Path("typeId") long id); // // @GET("/market/groups/") // Observable<Response<CrestDictionary<CrestMarketGroup>>> getMarketGroups(); // // @GET("/regions/") // Observable<Response<CrestDictionary<CrestItem>>> getRegions(); // // @GET("/market/{regionId}/orders/{orderType}/") // Observable<Response<CrestDictionary<CrestMarketOrder>>> getMarketOrders(@Path("regionId") long regionId, // @Path("orderType") String orderType, // @Query(value = "type", encoded = true) String typeId); // // @GET("/market/{regionId}/orders/") // Observable<Response<CrestDictionary<CrestMarketOrder>>> getMarketOrders(@Path("regionId") long regionId, // @Query(value = "type", encoded = true) String typeId); // // @GET("/market/{regionId}/history/") // Call<CrestDictionary<CrestMarketHistory>> getMarketHistory(@Path("regionId") final long regionId, // @Query("type") final String typeRef); // // }
import android.annotation.TargetApi; import android.app.job.JobParameters; import android.app.job.JobService; import android.content.Context; import android.os.AsyncTask; import android.os.Build; import com.w9jds.marketbot.classes.CrestService;
package com.w9jds.marketbot.services; @TargetApi(Build.VERSION_CODES.LOLLIPOP) public final class BotJobService extends JobService { private static final String TAG = "MailService"; @Override public void onCreate() { super.onCreate(); } @Override public void onDestroy() { super.onDestroy(); } @Override public boolean onStartJob(JobParameters params) { new CheckMarketOrders(this) .executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params); return true; } @Override public boolean onStopJob(JobParameters params) { return false; } private class CheckMarketOrders extends AsyncTask<JobParameters, Void, JobParameters[]> { private Context context; private JobParameters params;
// Path: app/src/main/java/com/w9jds/marketbot/classes/CrestService.java // public interface CrestService { // // @GET("/") // Observable<Response<CrestServerStatus>> getServer(); // // @GET("/market/types/") // Call<CrestDictionary<CrestMarketType>> getMarketTypes(@Query("page") int page); // // @GET("/inventory/types/{typeId}/") // Call<CrestType> getTypeInfo(@Path("typeId") long id); // // @GET("/market/groups/") // Observable<Response<CrestDictionary<CrestMarketGroup>>> getMarketGroups(); // // @GET("/regions/") // Observable<Response<CrestDictionary<CrestItem>>> getRegions(); // // @GET("/market/{regionId}/orders/{orderType}/") // Observable<Response<CrestDictionary<CrestMarketOrder>>> getMarketOrders(@Path("regionId") long regionId, // @Path("orderType") String orderType, // @Query(value = "type", encoded = true) String typeId); // // @GET("/market/{regionId}/orders/") // Observable<Response<CrestDictionary<CrestMarketOrder>>> getMarketOrders(@Path("regionId") long regionId, // @Query(value = "type", encoded = true) String typeId); // // @GET("/market/{regionId}/history/") // Call<CrestDictionary<CrestMarketHistory>> getMarketHistory(@Path("regionId") final long regionId, // @Query("type") final String typeRef); // // } // Path: app/src/main/java/com/w9jds/marketbot/services/BotJobService.java import android.annotation.TargetApi; import android.app.job.JobParameters; import android.app.job.JobService; import android.content.Context; import android.os.AsyncTask; import android.os.Build; import com.w9jds.marketbot.classes.CrestService; package com.w9jds.marketbot.services; @TargetApi(Build.VERSION_CODES.LOLLIPOP) public final class BotJobService extends JobService { private static final String TAG = "MailService"; @Override public void onCreate() { super.onCreate(); } @Override public void onDestroy() { super.onDestroy(); } @Override public boolean onStartJob(JobParameters params) { new CheckMarketOrders(this) .executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params); return true; } @Override public boolean onStopJob(JobParameters params) { return false; } private class CheckMarketOrders extends AsyncTask<JobParameters, Void, JobParameters[]> { private Context context; private JobParameters params;
private CrestService publicCrestApi;
w9jds/MarketBot
app/src/main/java/com/w9jds/marketbot/ui/adapters/RegionAdapter.java
// Path: app/src/main/java/com/w9jds/marketbot/classes/models/MarketItemBase.java // public class MarketItemBase { // // protected long id; // protected String name; // // public long getId() { // return id; // } // // public String getName() { // return name; // } // // } // // Path: app/src/main/java/com/w9jds/marketbot/classes/models/Region.java // public final class Region extends MarketItemBase { // // private String href; // // public String getHref() { // return href; // } // // public static class Builder { // // private long id; // private String name; // private String href; // // public Builder setId(long id) { // this.id = id; // return this; // } // // public Builder setHref(String href) { // this.href = href; // return this; // } // // public Builder setName(String name) { // this.name = name; // return this; // } // // public Region build() { // Region region = new Region(); // region.id = this.id; // region.name = this.name; // region.href = this.href; // // return region; // } // } // // }
import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.SpinnerAdapter; import android.widget.TextView; import com.w9jds.marketbot.R; import com.w9jds.marketbot.classes.models.MarketItemBase; import com.w9jds.marketbot.classes.models.Region; import java.util.ArrayList; import java.util.Collection; import java.util.List; import butterknife.ButterKnife;
package com.w9jds.marketbot.ui.adapters; public final class RegionAdapter extends BaseAdapter implements SpinnerAdapter { private Context context;
// Path: app/src/main/java/com/w9jds/marketbot/classes/models/MarketItemBase.java // public class MarketItemBase { // // protected long id; // protected String name; // // public long getId() { // return id; // } // // public String getName() { // return name; // } // // } // // Path: app/src/main/java/com/w9jds/marketbot/classes/models/Region.java // public final class Region extends MarketItemBase { // // private String href; // // public String getHref() { // return href; // } // // public static class Builder { // // private long id; // private String name; // private String href; // // public Builder setId(long id) { // this.id = id; // return this; // } // // public Builder setHref(String href) { // this.href = href; // return this; // } // // public Builder setName(String name) { // this.name = name; // return this; // } // // public Region build() { // Region region = new Region(); // region.id = this.id; // region.name = this.name; // region.href = this.href; // // return region; // } // } // // } // Path: app/src/main/java/com/w9jds/marketbot/ui/adapters/RegionAdapter.java import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.SpinnerAdapter; import android.widget.TextView; import com.w9jds.marketbot.R; import com.w9jds.marketbot.classes.models.MarketItemBase; import com.w9jds.marketbot.classes.models.Region; import java.util.ArrayList; import java.util.Collection; import java.util.List; import butterknife.ButterKnife; package com.w9jds.marketbot.ui.adapters; public final class RegionAdapter extends BaseAdapter implements SpinnerAdapter { private Context context;
private List<Region> regions = new ArrayList<>();
w9jds/MarketBot
app/src/main/java/com/w9jds/marketbot/ui/adapters/RegionAdapter.java
// Path: app/src/main/java/com/w9jds/marketbot/classes/models/MarketItemBase.java // public class MarketItemBase { // // protected long id; // protected String name; // // public long getId() { // return id; // } // // public String getName() { // return name; // } // // } // // Path: app/src/main/java/com/w9jds/marketbot/classes/models/Region.java // public final class Region extends MarketItemBase { // // private String href; // // public String getHref() { // return href; // } // // public static class Builder { // // private long id; // private String name; // private String href; // // public Builder setId(long id) { // this.id = id; // return this; // } // // public Builder setHref(String href) { // this.href = href; // return this; // } // // public Builder setName(String name) { // this.name = name; // return this; // } // // public Region build() { // Region region = new Region(); // region.id = this.id; // region.name = this.name; // region.href = this.href; // // return region; // } // } // // }
import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.SpinnerAdapter; import android.widget.TextView; import com.w9jds.marketbot.R; import com.w9jds.marketbot.classes.models.MarketItemBase; import com.w9jds.marketbot.classes.models.Region; import java.util.ArrayList; import java.util.Collection; import java.util.List; import butterknife.ButterKnife;
static class RegionViewHolder { TextView name; public RegionViewHolder(View view) { name = ButterKnife.findById(view, R.id.region_name); } } @Override public View getView(int position, View convertView, ViewGroup parent) { RegionViewHolder holder; final Region region = (Region) getItem(position); if (convertView == null) { convertView = LayoutInflater.from(context).inflate(R.layout.toolbar_spinner_item_actionbar, parent, false); holder = new RegionViewHolder(convertView); convertView.setTag(holder); } else { holder = (RegionViewHolder) convertView.getTag(); } holder.name.setText(region.getName()); return convertView; }
// Path: app/src/main/java/com/w9jds/marketbot/classes/models/MarketItemBase.java // public class MarketItemBase { // // protected long id; // protected String name; // // public long getId() { // return id; // } // // public String getName() { // return name; // } // // } // // Path: app/src/main/java/com/w9jds/marketbot/classes/models/Region.java // public final class Region extends MarketItemBase { // // private String href; // // public String getHref() { // return href; // } // // public static class Builder { // // private long id; // private String name; // private String href; // // public Builder setId(long id) { // this.id = id; // return this; // } // // public Builder setHref(String href) { // this.href = href; // return this; // } // // public Builder setName(String name) { // this.name = name; // return this; // } // // public Region build() { // Region region = new Region(); // region.id = this.id; // region.name = this.name; // region.href = this.href; // // return region; // } // } // // } // Path: app/src/main/java/com/w9jds/marketbot/ui/adapters/RegionAdapter.java import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.SpinnerAdapter; import android.widget.TextView; import com.w9jds.marketbot.R; import com.w9jds.marketbot.classes.models.MarketItemBase; import com.w9jds.marketbot.classes.models.Region; import java.util.ArrayList; import java.util.Collection; import java.util.List; import butterknife.ButterKnife; static class RegionViewHolder { TextView name; public RegionViewHolder(View view) { name = ButterKnife.findById(view, R.id.region_name); } } @Override public View getView(int position, View convertView, ViewGroup parent) { RegionViewHolder holder; final Region region = (Region) getItem(position); if (convertView == null) { convertView = LayoutInflater.from(context).inflate(R.layout.toolbar_spinner_item_actionbar, parent, false); holder = new RegionViewHolder(convertView); convertView.setTag(holder); } else { holder = (RegionViewHolder) convertView.getTag(); } holder.name.setText(region.getName()); return convertView; }
public void addAllItems(Collection<? extends MarketItemBase> regions) {
w9jds/MarketBot
app/src/main/java/com/w9jds/marketbot/classes/components/BaseComponent.java
// Path: app/src/main/java/com/w9jds/marketbot/classes/CrestService.java // public interface CrestService { // // @GET("/") // Observable<Response<CrestServerStatus>> getServer(); // // @GET("/market/types/") // Call<CrestDictionary<CrestMarketType>> getMarketTypes(@Query("page") int page); // // @GET("/inventory/types/{typeId}/") // Call<CrestType> getTypeInfo(@Path("typeId") long id); // // @GET("/market/groups/") // Observable<Response<CrestDictionary<CrestMarketGroup>>> getMarketGroups(); // // @GET("/regions/") // Observable<Response<CrestDictionary<CrestItem>>> getRegions(); // // @GET("/market/{regionId}/orders/{orderType}/") // Observable<Response<CrestDictionary<CrestMarketOrder>>> getMarketOrders(@Path("regionId") long regionId, // @Path("orderType") String orderType, // @Query(value = "type", encoded = true) String typeId); // // @GET("/market/{regionId}/orders/") // Observable<Response<CrestDictionary<CrestMarketOrder>>> getMarketOrders(@Path("regionId") long regionId, // @Query(value = "type", encoded = true) String typeId); // // @GET("/market/{regionId}/history/") // Call<CrestDictionary<CrestMarketHistory>> getMarketHistory(@Path("regionId") final long regionId, // @Query("type") final String typeRef); // // } // // Path: app/src/main/java/com/w9jds/marketbot/classes/modules/ApplicationModule.java // @Module // public class ApplicationModule { // // private Application application; // // public ApplicationModule(Application application) { // this.application = application; // } // // @Provides // @Singleton // Application provideApplication() { // return application; // } // // @Provides // @Singleton // SharedPreferences provideSharedPreferences(Application application) { // return PreferenceManager.getDefaultSharedPreferences(application); // } // // } // // Path: app/src/main/java/com/w9jds/marketbot/classes/modules/NetModule.java // @Module // public class NetModule { // // public static final String SINGULARITY = "https://api-sisi.testeveonline.com/"; // public static final String TRANQUILITY = "https://crest-tq.eveonline.com/"; // // String mBaseUrl; // // public NetModule(String baseUrl) { // this.mBaseUrl = baseUrl; // } // // @Provides // @Singleton // Interceptor provideInterceptor() { // return chain -> { // Request request = chain.request(); // // request = request.newBuilder() // .addHeader("User-Agent", "MarketBot by Jeremy Shore") // .build(); // // return chain.proceed(request); // }; // } // // @Provides // @Singleton // Cache provideOkHttpCache(Application application) { // int cacheSize = 10 * 1024 * 1024; // return new Cache(application.getCacheDir(), cacheSize); // } // // @Provides // @Singleton // OkHttpClient provideOkHttpClient(Cache cache, Interceptor interceptor) { // return new OkHttpClient.Builder() // .cache(cache) // .addInterceptor(interceptor) // .build(); // } // // @Provides // @Singleton // Retrofit providePublicRetrofit(OkHttpClient okHttpClient) { // return new Retrofit.Builder() // .baseUrl(TRANQUILITY) // .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // .addConverterFactory(JacksonConverterFactory.create()) // .client(okHttpClient) // .build(); // } // // @Provides // @Singleton // public CrestService providePublicCrest(Retrofit retrofit) { // return retrofit.create(CrestService.class); // } // }
import android.app.Application; import android.content.SharedPreferences; import com.w9jds.marketbot.classes.CrestService; import com.w9jds.marketbot.classes.modules.ApplicationModule; import com.w9jds.marketbot.classes.modules.NetModule; import javax.inject.Singleton; import dagger.Component;
package com.w9jds.marketbot.classes.components; @Singleton @Component(modules = { ApplicationModule.class, NetModule.class }) public interface BaseComponent { Application application(); SharedPreferences sharedPreferences();
// Path: app/src/main/java/com/w9jds/marketbot/classes/CrestService.java // public interface CrestService { // // @GET("/") // Observable<Response<CrestServerStatus>> getServer(); // // @GET("/market/types/") // Call<CrestDictionary<CrestMarketType>> getMarketTypes(@Query("page") int page); // // @GET("/inventory/types/{typeId}/") // Call<CrestType> getTypeInfo(@Path("typeId") long id); // // @GET("/market/groups/") // Observable<Response<CrestDictionary<CrestMarketGroup>>> getMarketGroups(); // // @GET("/regions/") // Observable<Response<CrestDictionary<CrestItem>>> getRegions(); // // @GET("/market/{regionId}/orders/{orderType}/") // Observable<Response<CrestDictionary<CrestMarketOrder>>> getMarketOrders(@Path("regionId") long regionId, // @Path("orderType") String orderType, // @Query(value = "type", encoded = true) String typeId); // // @GET("/market/{regionId}/orders/") // Observable<Response<CrestDictionary<CrestMarketOrder>>> getMarketOrders(@Path("regionId") long regionId, // @Query(value = "type", encoded = true) String typeId); // // @GET("/market/{regionId}/history/") // Call<CrestDictionary<CrestMarketHistory>> getMarketHistory(@Path("regionId") final long regionId, // @Query("type") final String typeRef); // // } // // Path: app/src/main/java/com/w9jds/marketbot/classes/modules/ApplicationModule.java // @Module // public class ApplicationModule { // // private Application application; // // public ApplicationModule(Application application) { // this.application = application; // } // // @Provides // @Singleton // Application provideApplication() { // return application; // } // // @Provides // @Singleton // SharedPreferences provideSharedPreferences(Application application) { // return PreferenceManager.getDefaultSharedPreferences(application); // } // // } // // Path: app/src/main/java/com/w9jds/marketbot/classes/modules/NetModule.java // @Module // public class NetModule { // // public static final String SINGULARITY = "https://api-sisi.testeveonline.com/"; // public static final String TRANQUILITY = "https://crest-tq.eveonline.com/"; // // String mBaseUrl; // // public NetModule(String baseUrl) { // this.mBaseUrl = baseUrl; // } // // @Provides // @Singleton // Interceptor provideInterceptor() { // return chain -> { // Request request = chain.request(); // // request = request.newBuilder() // .addHeader("User-Agent", "MarketBot by Jeremy Shore") // .build(); // // return chain.proceed(request); // }; // } // // @Provides // @Singleton // Cache provideOkHttpCache(Application application) { // int cacheSize = 10 * 1024 * 1024; // return new Cache(application.getCacheDir(), cacheSize); // } // // @Provides // @Singleton // OkHttpClient provideOkHttpClient(Cache cache, Interceptor interceptor) { // return new OkHttpClient.Builder() // .cache(cache) // .addInterceptor(interceptor) // .build(); // } // // @Provides // @Singleton // Retrofit providePublicRetrofit(OkHttpClient okHttpClient) { // return new Retrofit.Builder() // .baseUrl(TRANQUILITY) // .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // .addConverterFactory(JacksonConverterFactory.create()) // .client(okHttpClient) // .build(); // } // // @Provides // @Singleton // public CrestService providePublicCrest(Retrofit retrofit) { // return retrofit.create(CrestService.class); // } // } // Path: app/src/main/java/com/w9jds/marketbot/classes/components/BaseComponent.java import android.app.Application; import android.content.SharedPreferences; import com.w9jds.marketbot.classes.CrestService; import com.w9jds.marketbot.classes.modules.ApplicationModule; import com.w9jds.marketbot.classes.modules.NetModule; import javax.inject.Singleton; import dagger.Component; package com.w9jds.marketbot.classes.components; @Singleton @Component(modules = { ApplicationModule.class, NetModule.class }) public interface BaseComponent { Application application(); SharedPreferences sharedPreferences();
CrestService crest();
w9jds/MarketBot
app/src/main/java/com/w9jds/marketbot/data/storage/MarketTypeEntry.java
// Path: app/src/main/java/com/w9jds/marketbot/classes/models/Type.java // public final class Type extends MarketItemBase implements Parcelable { // // private String href; // private String icon; // private String marketGroup; // private long groupId; // // public String getHref() { // return href; // } // // public String getIcon() { // return icon; // } // // public long getGroupId() { // return groupId; // } // // public String getMarketGroup() { // return marketGroup; // } // // public static class Builder { // // private long id; // private String name; // private String href; // private String icon; // private String marketGroup; // private long groupId; // // public Builder setId(long id) { // this.id = id; // return this; // } // // public Builder setName(String name) { // this.name = name; // return this; // } // // public Builder setHref(String href) { // this.href = href; // return this; // } // // public Builder setIcon(String icon) { // this.icon = icon; // return this; // } // // public Builder setMarketGroup(String marketGroup) { // this.marketGroup = marketGroup; // return this; // } // // public Builder setGroupId(long groupId) { // this.groupId = groupId; // return this; // } // // public Type build() { // Type type = new Type(); // type.id = this.id; // type.name = this.name; // type.href = this.href; // type.icon = this.icon; // type.marketGroup = this.marketGroup; // type.groupId = this.groupId; // // return type; // } // // // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(this.href); // dest.writeString(this.icon); // dest.writeString(this.marketGroup); // dest.writeString(this.name); // dest.writeLong(this.id); // dest.writeLong(this.groupId); // } // // public Type() { // // } // // protected Type(Parcel in) { // this.href = in.readString(); // this.icon = in.readString(); // this.marketGroup = in.readString(); // this.name = in.readString(); // this.id = in.readLong(); // this.groupId = in.readLong(); // } // // public static final Parcelable.Creator<Type> CREATOR = new Parcelable.Creator<Type>() { // @Override // public Type createFromParcel(Parcel source) { // return new Type(source); // } // // @Override // public Type[] newArray(int size) { // return new Type[size]; // } // }; // } // // Path: app/src/main/java/com/w9jds/marketbot/data/MarketDatabase.java // @Database(name = MarketDatabase.NAME, version = MarketDatabase.VERSION) // public class MarketDatabase { // // public static final String NAME = "MarketBotDb"; // public static final int VERSION = 3; // // // public interface TransactionListener { // void onTransactionProgressUpdate(int progress, int max); // } // }
import com.raizlabs.android.dbflow.annotation.Column; import com.raizlabs.android.dbflow.annotation.PrimaryKey; import com.raizlabs.android.dbflow.annotation.Table; import com.raizlabs.android.dbflow.runtime.TransactionManager; import com.raizlabs.android.dbflow.runtime.transaction.process.ProcessModelInfo; import com.raizlabs.android.dbflow.runtime.transaction.process.ProcessModelTransaction; import com.raizlabs.android.dbflow.runtime.transaction.process.SaveModelTransaction; import com.raizlabs.android.dbflow.sql.language.OrderBy; import com.raizlabs.android.dbflow.sql.language.Select; import com.raizlabs.android.dbflow.structure.BaseModel; import com.w9jds.marketbot.classes.models.Type; import com.w9jds.marketbot.data.MarketDatabase; import org.devfleet.crest.model.CrestMarketType; import java.util.AbstractMap; import java.util.ArrayList; import java.util.List; import java.util.Map; import rx.subjects.BehaviorSubject;
@Column String name; public static void addNewMarketTypes(List<CrestMarketType> types, BehaviorSubject<Map.Entry<Integer, Integer>> subject) { int size = types.size(); List<MarketTypeEntry> entries = new ArrayList<>(size); for (int i = 0; i < size; i++) { CrestMarketType type = types.get(i); MarketTypeEntry entry = new MarketTypeEntry(); entry.id = type.getTypeId(); entry.groupId = type.getGroupId(); entry.href = type.getTypeHref(); entry.icon = type.getTypeIcon(); entry.name = type.getTypeName(); entries.add(entry); } TransactionManager manager = TransactionManager.getInstance(); ProcessModelTransaction transaction = new SaveModelTransaction<>(ProcessModelInfo.withModels(entries)); transaction.setChangeListener((current, maxProgress, modifiedModel) -> { if (current % 25 == 0 || current == maxProgress) { subject.onNext(new AbstractMap.SimpleEntry<>((int) current, (int) maxProgress)); } }); manager.addTransaction(transaction); }
// Path: app/src/main/java/com/w9jds/marketbot/classes/models/Type.java // public final class Type extends MarketItemBase implements Parcelable { // // private String href; // private String icon; // private String marketGroup; // private long groupId; // // public String getHref() { // return href; // } // // public String getIcon() { // return icon; // } // // public long getGroupId() { // return groupId; // } // // public String getMarketGroup() { // return marketGroup; // } // // public static class Builder { // // private long id; // private String name; // private String href; // private String icon; // private String marketGroup; // private long groupId; // // public Builder setId(long id) { // this.id = id; // return this; // } // // public Builder setName(String name) { // this.name = name; // return this; // } // // public Builder setHref(String href) { // this.href = href; // return this; // } // // public Builder setIcon(String icon) { // this.icon = icon; // return this; // } // // public Builder setMarketGroup(String marketGroup) { // this.marketGroup = marketGroup; // return this; // } // // public Builder setGroupId(long groupId) { // this.groupId = groupId; // return this; // } // // public Type build() { // Type type = new Type(); // type.id = this.id; // type.name = this.name; // type.href = this.href; // type.icon = this.icon; // type.marketGroup = this.marketGroup; // type.groupId = this.groupId; // // return type; // } // // // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(this.href); // dest.writeString(this.icon); // dest.writeString(this.marketGroup); // dest.writeString(this.name); // dest.writeLong(this.id); // dest.writeLong(this.groupId); // } // // public Type() { // // } // // protected Type(Parcel in) { // this.href = in.readString(); // this.icon = in.readString(); // this.marketGroup = in.readString(); // this.name = in.readString(); // this.id = in.readLong(); // this.groupId = in.readLong(); // } // // public static final Parcelable.Creator<Type> CREATOR = new Parcelable.Creator<Type>() { // @Override // public Type createFromParcel(Parcel source) { // return new Type(source); // } // // @Override // public Type[] newArray(int size) { // return new Type[size]; // } // }; // } // // Path: app/src/main/java/com/w9jds/marketbot/data/MarketDatabase.java // @Database(name = MarketDatabase.NAME, version = MarketDatabase.VERSION) // public class MarketDatabase { // // public static final String NAME = "MarketBotDb"; // public static final int VERSION = 3; // // // public interface TransactionListener { // void onTransactionProgressUpdate(int progress, int max); // } // } // Path: app/src/main/java/com/w9jds/marketbot/data/storage/MarketTypeEntry.java import com.raizlabs.android.dbflow.annotation.Column; import com.raizlabs.android.dbflow.annotation.PrimaryKey; import com.raizlabs.android.dbflow.annotation.Table; import com.raizlabs.android.dbflow.runtime.TransactionManager; import com.raizlabs.android.dbflow.runtime.transaction.process.ProcessModelInfo; import com.raizlabs.android.dbflow.runtime.transaction.process.ProcessModelTransaction; import com.raizlabs.android.dbflow.runtime.transaction.process.SaveModelTransaction; import com.raizlabs.android.dbflow.sql.language.OrderBy; import com.raizlabs.android.dbflow.sql.language.Select; import com.raizlabs.android.dbflow.structure.BaseModel; import com.w9jds.marketbot.classes.models.Type; import com.w9jds.marketbot.data.MarketDatabase; import org.devfleet.crest.model.CrestMarketType; import java.util.AbstractMap; import java.util.ArrayList; import java.util.List; import java.util.Map; import rx.subjects.BehaviorSubject; @Column String name; public static void addNewMarketTypes(List<CrestMarketType> types, BehaviorSubject<Map.Entry<Integer, Integer>> subject) { int size = types.size(); List<MarketTypeEntry> entries = new ArrayList<>(size); for (int i = 0; i < size; i++) { CrestMarketType type = types.get(i); MarketTypeEntry entry = new MarketTypeEntry(); entry.id = type.getTypeId(); entry.groupId = type.getGroupId(); entry.href = type.getTypeHref(); entry.icon = type.getTypeIcon(); entry.name = type.getTypeName(); entries.add(entry); } TransactionManager manager = TransactionManager.getInstance(); ProcessModelTransaction transaction = new SaveModelTransaction<>(ProcessModelInfo.withModels(entries)); transaction.setChangeListener((current, maxProgress, modifiedModel) -> { if (current % 25 == 0 || current == maxProgress) { subject.onNext(new AbstractMap.SimpleEntry<>((int) current, (int) maxProgress)); } }); manager.addTransaction(transaction); }
private static Type buildMarketType(MarketTypeEntry entry) {
xqbase/chess
AjaxChess/src/Startup.java
// Path: AjaxChess/src/ajaxchess/util/ClassPath.java // public class ClassPath extends File { // private static final long serialVersionUID = 1L; // // private static ClassPath instance = new ClassPath(); // // private static String getPath(Class<? extends ClassPath> cls) { // try { // String path = URLDecoder.decode(cls.getProtectionDomain().getCodeSource().getLocation().getPath(), "UTF-8"); // if (path.endsWith(".jar")) { // path += separator + ".."; // } else if (path.endsWith(".class")) { // int nParent = ClassPath.class.getPackage().getName().split("\\.").length + 1; // for (int i = 0; i < nParent; i ++) { // path += separator + ".."; // } // } // return new File(path).getCanonicalPath(); // } catch (Exception e) { // throw new RuntimeException(e); // } // } // // private ClassPath(String strFile) { // super(strFile); // } // // private ClassPath() { // this(ClassPath.class); // } // // public ClassPath(Class<? extends ClassPath> cls) { // super(getPath(cls)); // } // // public ClassPath append(String strPath) { // try { // return new ClassPath(new File(getPath() + separator + strPath).getCanonicalPath()); // } catch (Exception e) { // throw new RuntimeException(e); // } // } // // public static ClassPath getInstance() { // return instance; // } // // public static ClassPath getInstance(String strPath) { // return instance.append(strPath); // } // } // // Path: AjaxChess/src/ajaxchess/util/Integers.java // public class Integers { // public static int parse(String s) { // return parse(s, 0); // } // // public static int parse(String s, int i) { // int n = i; // try { // n = Integer.parseInt(s); // } catch (Exception e) { // // Ignored // } // return n; // } // // public static int minMax(int min, int mid, int max) { // return mid < min ? min : mid > max ? max : mid; // } // } // // Path: AjaxChess/src/ajaxchess/util/server/JettyServer.java // public class JettyServer extends Server { // public JettyServer(File home) throws Exception { // this(home, 80); // } // // public JettyServer(File home, int port) throws Exception { // SocketConnector connector = new SocketConnector(); // connector.setPort(port); // addConnector(connector); // initWebApp(home); // } // // public JettyServer(File home, File filePfx, String password) throws Exception { // this(home, 443, filePfx, password); // } // // public JettyServer(File home, int nPort, File filePfx, String password) throws Exception { // SslSocketConnector connector = new SslSocketConnector(); // connector.setPassword(password); // connector.setKeystoreType("PKCS12"); // connector.setKeystore(filePfx.getPath()); // connector.setKeyPassword(password); // connector.setTruststoreType("PKCS12"); // connector.setTruststore(filePfx.getPath()); // connector.setTrustPassword(password); // connector.setWantClientAuth(true); // connector.setPort(nPort); // addConnector(connector); // initWebApp(home); // } // // private void initWebApp(File home) throws Exception { // HandlerCollection handler = new HandlerCollection(); // setHandler(handler); // WebAppDeployer webapp = new WebAppDeployer(); // webapp.setContexts(handler); // webapp.setWebAppDir(home + File.separator + "webapps"); // webapp.start(); // } // }
import java.io.File; import ajaxchess.util.ClassPath; import ajaxchess.util.Integers; import ajaxchess.util.server.JettyServer;
public class Startup { private static final File DEFAULT_HOME = ClassPath.getInstance("../../../.."); public static void main(String[] args) throws Exception {
// Path: AjaxChess/src/ajaxchess/util/ClassPath.java // public class ClassPath extends File { // private static final long serialVersionUID = 1L; // // private static ClassPath instance = new ClassPath(); // // private static String getPath(Class<? extends ClassPath> cls) { // try { // String path = URLDecoder.decode(cls.getProtectionDomain().getCodeSource().getLocation().getPath(), "UTF-8"); // if (path.endsWith(".jar")) { // path += separator + ".."; // } else if (path.endsWith(".class")) { // int nParent = ClassPath.class.getPackage().getName().split("\\.").length + 1; // for (int i = 0; i < nParent; i ++) { // path += separator + ".."; // } // } // return new File(path).getCanonicalPath(); // } catch (Exception e) { // throw new RuntimeException(e); // } // } // // private ClassPath(String strFile) { // super(strFile); // } // // private ClassPath() { // this(ClassPath.class); // } // // public ClassPath(Class<? extends ClassPath> cls) { // super(getPath(cls)); // } // // public ClassPath append(String strPath) { // try { // return new ClassPath(new File(getPath() + separator + strPath).getCanonicalPath()); // } catch (Exception e) { // throw new RuntimeException(e); // } // } // // public static ClassPath getInstance() { // return instance; // } // // public static ClassPath getInstance(String strPath) { // return instance.append(strPath); // } // } // // Path: AjaxChess/src/ajaxchess/util/Integers.java // public class Integers { // public static int parse(String s) { // return parse(s, 0); // } // // public static int parse(String s, int i) { // int n = i; // try { // n = Integer.parseInt(s); // } catch (Exception e) { // // Ignored // } // return n; // } // // public static int minMax(int min, int mid, int max) { // return mid < min ? min : mid > max ? max : mid; // } // } // // Path: AjaxChess/src/ajaxchess/util/server/JettyServer.java // public class JettyServer extends Server { // public JettyServer(File home) throws Exception { // this(home, 80); // } // // public JettyServer(File home, int port) throws Exception { // SocketConnector connector = new SocketConnector(); // connector.setPort(port); // addConnector(connector); // initWebApp(home); // } // // public JettyServer(File home, File filePfx, String password) throws Exception { // this(home, 443, filePfx, password); // } // // public JettyServer(File home, int nPort, File filePfx, String password) throws Exception { // SslSocketConnector connector = new SslSocketConnector(); // connector.setPassword(password); // connector.setKeystoreType("PKCS12"); // connector.setKeystore(filePfx.getPath()); // connector.setKeyPassword(password); // connector.setTruststoreType("PKCS12"); // connector.setTruststore(filePfx.getPath()); // connector.setTrustPassword(password); // connector.setWantClientAuth(true); // connector.setPort(nPort); // addConnector(connector); // initWebApp(home); // } // // private void initWebApp(File home) throws Exception { // HandlerCollection handler = new HandlerCollection(); // setHandler(handler); // WebAppDeployer webapp = new WebAppDeployer(); // webapp.setContexts(handler); // webapp.setWebAppDir(home + File.separator + "webapps"); // webapp.start(); // } // } // Path: AjaxChess/src/Startup.java import java.io.File; import ajaxchess.util.ClassPath; import ajaxchess.util.Integers; import ajaxchess.util.server.JettyServer; public class Startup { private static final File DEFAULT_HOME = ClassPath.getInstance("../../../.."); public static void main(String[] args) throws Exception {
int port = (args.length == 0 ? 80 : Integers.parse(args[0], 80));
xqbase/chess
AjaxChess/src/Startup.java
// Path: AjaxChess/src/ajaxchess/util/ClassPath.java // public class ClassPath extends File { // private static final long serialVersionUID = 1L; // // private static ClassPath instance = new ClassPath(); // // private static String getPath(Class<? extends ClassPath> cls) { // try { // String path = URLDecoder.decode(cls.getProtectionDomain().getCodeSource().getLocation().getPath(), "UTF-8"); // if (path.endsWith(".jar")) { // path += separator + ".."; // } else if (path.endsWith(".class")) { // int nParent = ClassPath.class.getPackage().getName().split("\\.").length + 1; // for (int i = 0; i < nParent; i ++) { // path += separator + ".."; // } // } // return new File(path).getCanonicalPath(); // } catch (Exception e) { // throw new RuntimeException(e); // } // } // // private ClassPath(String strFile) { // super(strFile); // } // // private ClassPath() { // this(ClassPath.class); // } // // public ClassPath(Class<? extends ClassPath> cls) { // super(getPath(cls)); // } // // public ClassPath append(String strPath) { // try { // return new ClassPath(new File(getPath() + separator + strPath).getCanonicalPath()); // } catch (Exception e) { // throw new RuntimeException(e); // } // } // // public static ClassPath getInstance() { // return instance; // } // // public static ClassPath getInstance(String strPath) { // return instance.append(strPath); // } // } // // Path: AjaxChess/src/ajaxchess/util/Integers.java // public class Integers { // public static int parse(String s) { // return parse(s, 0); // } // // public static int parse(String s, int i) { // int n = i; // try { // n = Integer.parseInt(s); // } catch (Exception e) { // // Ignored // } // return n; // } // // public static int minMax(int min, int mid, int max) { // return mid < min ? min : mid > max ? max : mid; // } // } // // Path: AjaxChess/src/ajaxchess/util/server/JettyServer.java // public class JettyServer extends Server { // public JettyServer(File home) throws Exception { // this(home, 80); // } // // public JettyServer(File home, int port) throws Exception { // SocketConnector connector = new SocketConnector(); // connector.setPort(port); // addConnector(connector); // initWebApp(home); // } // // public JettyServer(File home, File filePfx, String password) throws Exception { // this(home, 443, filePfx, password); // } // // public JettyServer(File home, int nPort, File filePfx, String password) throws Exception { // SslSocketConnector connector = new SslSocketConnector(); // connector.setPassword(password); // connector.setKeystoreType("PKCS12"); // connector.setKeystore(filePfx.getPath()); // connector.setKeyPassword(password); // connector.setTruststoreType("PKCS12"); // connector.setTruststore(filePfx.getPath()); // connector.setTrustPassword(password); // connector.setWantClientAuth(true); // connector.setPort(nPort); // addConnector(connector); // initWebApp(home); // } // // private void initWebApp(File home) throws Exception { // HandlerCollection handler = new HandlerCollection(); // setHandler(handler); // WebAppDeployer webapp = new WebAppDeployer(); // webapp.setContexts(handler); // webapp.setWebAppDir(home + File.separator + "webapps"); // webapp.start(); // } // }
import java.io.File; import ajaxchess.util.ClassPath; import ajaxchess.util.Integers; import ajaxchess.util.server.JettyServer;
public class Startup { private static final File DEFAULT_HOME = ClassPath.getInstance("../../../.."); public static void main(String[] args) throws Exception { int port = (args.length == 0 ? 80 : Integers.parse(args[0], 80));
// Path: AjaxChess/src/ajaxchess/util/ClassPath.java // public class ClassPath extends File { // private static final long serialVersionUID = 1L; // // private static ClassPath instance = new ClassPath(); // // private static String getPath(Class<? extends ClassPath> cls) { // try { // String path = URLDecoder.decode(cls.getProtectionDomain().getCodeSource().getLocation().getPath(), "UTF-8"); // if (path.endsWith(".jar")) { // path += separator + ".."; // } else if (path.endsWith(".class")) { // int nParent = ClassPath.class.getPackage().getName().split("\\.").length + 1; // for (int i = 0; i < nParent; i ++) { // path += separator + ".."; // } // } // return new File(path).getCanonicalPath(); // } catch (Exception e) { // throw new RuntimeException(e); // } // } // // private ClassPath(String strFile) { // super(strFile); // } // // private ClassPath() { // this(ClassPath.class); // } // // public ClassPath(Class<? extends ClassPath> cls) { // super(getPath(cls)); // } // // public ClassPath append(String strPath) { // try { // return new ClassPath(new File(getPath() + separator + strPath).getCanonicalPath()); // } catch (Exception e) { // throw new RuntimeException(e); // } // } // // public static ClassPath getInstance() { // return instance; // } // // public static ClassPath getInstance(String strPath) { // return instance.append(strPath); // } // } // // Path: AjaxChess/src/ajaxchess/util/Integers.java // public class Integers { // public static int parse(String s) { // return parse(s, 0); // } // // public static int parse(String s, int i) { // int n = i; // try { // n = Integer.parseInt(s); // } catch (Exception e) { // // Ignored // } // return n; // } // // public static int minMax(int min, int mid, int max) { // return mid < min ? min : mid > max ? max : mid; // } // } // // Path: AjaxChess/src/ajaxchess/util/server/JettyServer.java // public class JettyServer extends Server { // public JettyServer(File home) throws Exception { // this(home, 80); // } // // public JettyServer(File home, int port) throws Exception { // SocketConnector connector = new SocketConnector(); // connector.setPort(port); // addConnector(connector); // initWebApp(home); // } // // public JettyServer(File home, File filePfx, String password) throws Exception { // this(home, 443, filePfx, password); // } // // public JettyServer(File home, int nPort, File filePfx, String password) throws Exception { // SslSocketConnector connector = new SslSocketConnector(); // connector.setPassword(password); // connector.setKeystoreType("PKCS12"); // connector.setKeystore(filePfx.getPath()); // connector.setKeyPassword(password); // connector.setTruststoreType("PKCS12"); // connector.setTruststore(filePfx.getPath()); // connector.setTrustPassword(password); // connector.setWantClientAuth(true); // connector.setPort(nPort); // addConnector(connector); // initWebApp(home); // } // // private void initWebApp(File home) throws Exception { // HandlerCollection handler = new HandlerCollection(); // setHandler(handler); // WebAppDeployer webapp = new WebAppDeployer(); // webapp.setContexts(handler); // webapp.setWebAppDir(home + File.separator + "webapps"); // webapp.start(); // } // } // Path: AjaxChess/src/Startup.java import java.io.File; import ajaxchess.util.ClassPath; import ajaxchess.util.Integers; import ajaxchess.util.server.JettyServer; public class Startup { private static final File DEFAULT_HOME = ClassPath.getInstance("../../../.."); public static void main(String[] args) throws Exception { int port = (args.length == 0 ? 80 : Integers.parse(args[0], 80));
JettyServer server = new JettyServer(DEFAULT_HOME, port);