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
universal-automata/liblevenshtein-java
src/test/java/com/github/liblevenshtein/transducer/StandardPositionTransitionFunctionTest.java
// Path: src/main/java/com/github/liblevenshtein/transducer/factory/PositionFactory.java // @NoArgsConstructor // public class PositionFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds a dummy position. // * @return Dummy position. // */ // public Position build() { // return new Position(-1, -1); // } // // /** // * Builds a position vector for the standard, Levenshtein algorihtm. // * @param termIndex Current index of the spelling candidate. // * @param numErrors Number of accumulated errors at index {@code termIndex}. // * @return New position vector having index {@code termIndex} and error // * {@code numErrors}. // */ // public Position build(final int termIndex, final int numErrors) { // return new Position(termIndex, numErrors); // } // // /** // * Builds a position vector for the transposition and merge-and-split, // * Levenshtein algorihtms. // * @param termIndex Current index of the spelling candidate. // * @param numErrors Number of accumulated errors at index {@code termIndex}. // * @param isSpecial Either {@code 1} or {@code 0}, depending on whether the // * position is a special case (numErrors.g. a transposition position). // * @return New position vector having index {@code termIndex}, error // * {@code numErrors}, and special marker {@code isSpecial}. // */ // public Position build(final int termIndex, final int numErrors, final boolean isSpecial) { // if (isSpecial) { // return new SpecialPosition(termIndex, numErrors); // } // // return new Position(termIndex, numErrors); // } // } // // Path: src/main/java/com/github/liblevenshtein/transducer/factory/StateFactory.java // public class StateFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds a new, Levenshtein state with the given position vectors. // * @param positions Array of position vectors to link into the state. // * @return New state having the position vectors. // */ // public State build(final Position... positions) { // final State state = new State(); // // Position prev = null; // for (final Position curr : positions) { // state.insertAfter(prev, curr); // prev = curr; // } // // return state; // } // } // // Path: src/test/java/com/github/liblevenshtein/assertion/StandardPositionTransitionFunctionAssertions.java // public static StandardPositionTransitionFunctionAssertions assertThat( // final StandardPositionTransitionFunction actual) { // return new StandardPositionTransitionFunctionAssertions(actual); // }
import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import com.github.liblevenshtein.transducer.factory.PositionFactory; import com.github.liblevenshtein.transducer.factory.StateFactory; import static com.github.liblevenshtein.assertion.StandardPositionTransitionFunctionAssertions.assertThat;
@BeforeTest public void setUp() { transition.stateFactory(stateFactory); transition.positionFactory(positionFactory); } @Test public void testOf() { i = 0; e = 0; check(1 + i, e, true, false, true, false); check(i, 1 + e, 1 + i, 1 + e, 1 + 1 + i, 1 + e, false, true, false, true); check(i, 1 + e, 1 + i, 1 + e, false, false, false, false); i = W - 1; check(1 + i, e, true, true, true, true); check(i, 1 + e, 1 + i, 1 + e, false, false, false, false); i = W; check(W, 1 + e, true, true, true, true); i = 2; e = N; check(1 + i, N, true, true, true, true); check(false, false, false, false); i = W; check(true, true, true, true); } private void check(final boolean... characteristicVector) {
// Path: src/main/java/com/github/liblevenshtein/transducer/factory/PositionFactory.java // @NoArgsConstructor // public class PositionFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds a dummy position. // * @return Dummy position. // */ // public Position build() { // return new Position(-1, -1); // } // // /** // * Builds a position vector for the standard, Levenshtein algorihtm. // * @param termIndex Current index of the spelling candidate. // * @param numErrors Number of accumulated errors at index {@code termIndex}. // * @return New position vector having index {@code termIndex} and error // * {@code numErrors}. // */ // public Position build(final int termIndex, final int numErrors) { // return new Position(termIndex, numErrors); // } // // /** // * Builds a position vector for the transposition and merge-and-split, // * Levenshtein algorihtms. // * @param termIndex Current index of the spelling candidate. // * @param numErrors Number of accumulated errors at index {@code termIndex}. // * @param isSpecial Either {@code 1} or {@code 0}, depending on whether the // * position is a special case (numErrors.g. a transposition position). // * @return New position vector having index {@code termIndex}, error // * {@code numErrors}, and special marker {@code isSpecial}. // */ // public Position build(final int termIndex, final int numErrors, final boolean isSpecial) { // if (isSpecial) { // return new SpecialPosition(termIndex, numErrors); // } // // return new Position(termIndex, numErrors); // } // } // // Path: src/main/java/com/github/liblevenshtein/transducer/factory/StateFactory.java // public class StateFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds a new, Levenshtein state with the given position vectors. // * @param positions Array of position vectors to link into the state. // * @return New state having the position vectors. // */ // public State build(final Position... positions) { // final State state = new State(); // // Position prev = null; // for (final Position curr : positions) { // state.insertAfter(prev, curr); // prev = curr; // } // // return state; // } // } // // Path: src/test/java/com/github/liblevenshtein/assertion/StandardPositionTransitionFunctionAssertions.java // public static StandardPositionTransitionFunctionAssertions assertThat( // final StandardPositionTransitionFunction actual) { // return new StandardPositionTransitionFunctionAssertions(actual); // } // Path: src/test/java/com/github/liblevenshtein/transducer/StandardPositionTransitionFunctionTest.java import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import com.github.liblevenshtein.transducer.factory.PositionFactory; import com.github.liblevenshtein.transducer.factory.StateFactory; import static com.github.liblevenshtein.assertion.StandardPositionTransitionFunctionAssertions.assertThat; @BeforeTest public void setUp() { transition.stateFactory(stateFactory); transition.positionFactory(positionFactory); } @Test public void testOf() { i = 0; e = 0; check(1 + i, e, true, false, true, false); check(i, 1 + e, 1 + i, 1 + e, 1 + 1 + i, 1 + e, false, true, false, true); check(i, 1 + e, 1 + i, 1 + e, false, false, false, false); i = W - 1; check(1 + i, e, true, true, true, true); check(i, 1 + e, 1 + i, 1 + e, false, false, false, false); i = W; check(W, 1 + e, true, true, true, true); i = 2; e = N; check(1 + i, N, true, true, true, true); check(false, false, false, false); i = W; check(true, true, true, true); } private void check(final boolean... characteristicVector) {
assertThat(transition)
universal-automata/liblevenshtein-java
src/test/java/com/github/liblevenshtein/distance/factory/MemoizedDistanceFactoryTest.java
// Path: src/main/java/com/github/liblevenshtein/distance/IDistance.java // public interface IDistance<Term> extends Serializable { // // /** // * Finds the distance between two terms, {@code v} and {@code w}. The distance // * between two terms is complemented by their similarity, which is determined // * by subtracting their distance from the maximum distance they may be apart. // * @param v Term to compare with {@code w} // * @param w Term to compare with {@code v} // * @return Distance between {@code v} and {@code w} // */ // int between(Term v, Term w); // } // // Path: src/main/java/com/github/liblevenshtein/transducer/Algorithm.java // public enum Algorithm { // // /** // * This is the standard, textbook version of Levenshtein distance. It includes // * support for the elementary operations of insertion, deletion and // * substitution. // */ // STANDARD, // // /** // * Sometimes known as Damerau–Levenshtein distance, this includes the // * elementary operations described by the standard algorithm, as well as the // * elementary operation, transposition, which would incur a penalty of two // * units of error in the standard algorithm (whether it be an insertion and // * deletion, a deletion and insertion, or two substitutions). This algorithm // * is particularly useful in typed spelling-correction, where most spelling // * errors occur when a user transposes two characters. // */ // TRANSPOSITION, // // /** // * This algorithm includes the elementary operations described by the basic // * algorithm, as well as the elementary operations, merge and split. A merge // * occurs when two characters are joined together, and a split occurs when a // * single character is exploded into two characters. This algorithm is // * particularly useful in OCR applications, where one may read a "cl" when one // * should have read a "d" (i.e. merge), or when one may have read a "d" when // * one should have read a "cl" (i.e. split). // */ // MERGE_AND_SPLIT; // } // // Path: src/test/java/com/github/liblevenshtein/assertion/DistanceAssertions.java // public static <Type> DistanceAssertions<Type> assertThat( // final IDistance<Type> actual) { // return new DistanceAssertions<>(actual); // }
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.testng.annotations.BeforeClass; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import com.github.liblevenshtein.distance.IDistance; import com.github.liblevenshtein.transducer.Algorithm; import static com.github.liblevenshtein.assertion.DistanceAssertions.assertThat;
} this.terms = termsList; this.factory = new MemoizedDistanceFactory(); } } @DataProvider(name = "equalSelfSimilarityData") public Iterator<Object[]> equalSelfSimilarityData() { return new EqualSelfSimilarityDataIterator(factory, terms); } @DataProvider(name = "minimalityData") public Iterator<Object[]> minimalityData() { return new MinimalityDataIterator(factory, terms); } @DataProvider(name = "symmetryData") public Iterator<Object[]> symmetryData() { return new SymmetryDataIterator(factory, terms); } @DataProvider(name = "triangleInequalityData") public Iterator<Object[]> triangleInequalityData() { return new TriangleInequalityDataIterator(factory, terms); } @DataProvider(name = "penaltyData") public Object[][] penaltyData() { return new Object[][] {
// Path: src/main/java/com/github/liblevenshtein/distance/IDistance.java // public interface IDistance<Term> extends Serializable { // // /** // * Finds the distance between two terms, {@code v} and {@code w}. The distance // * between two terms is complemented by their similarity, which is determined // * by subtracting their distance from the maximum distance they may be apart. // * @param v Term to compare with {@code w} // * @param w Term to compare with {@code v} // * @return Distance between {@code v} and {@code w} // */ // int between(Term v, Term w); // } // // Path: src/main/java/com/github/liblevenshtein/transducer/Algorithm.java // public enum Algorithm { // // /** // * This is the standard, textbook version of Levenshtein distance. It includes // * support for the elementary operations of insertion, deletion and // * substitution. // */ // STANDARD, // // /** // * Sometimes known as Damerau–Levenshtein distance, this includes the // * elementary operations described by the standard algorithm, as well as the // * elementary operation, transposition, which would incur a penalty of two // * units of error in the standard algorithm (whether it be an insertion and // * deletion, a deletion and insertion, or two substitutions). This algorithm // * is particularly useful in typed spelling-correction, where most spelling // * errors occur when a user transposes two characters. // */ // TRANSPOSITION, // // /** // * This algorithm includes the elementary operations described by the basic // * algorithm, as well as the elementary operations, merge and split. A merge // * occurs when two characters are joined together, and a split occurs when a // * single character is exploded into two characters. This algorithm is // * particularly useful in OCR applications, where one may read a "cl" when one // * should have read a "d" (i.e. merge), or when one may have read a "d" when // * one should have read a "cl" (i.e. split). // */ // MERGE_AND_SPLIT; // } // // Path: src/test/java/com/github/liblevenshtein/assertion/DistanceAssertions.java // public static <Type> DistanceAssertions<Type> assertThat( // final IDistance<Type> actual) { // return new DistanceAssertions<>(actual); // } // Path: src/test/java/com/github/liblevenshtein/distance/factory/MemoizedDistanceFactoryTest.java import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.testng.annotations.BeforeClass; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import com.github.liblevenshtein.distance.IDistance; import com.github.liblevenshtein.transducer.Algorithm; import static com.github.liblevenshtein.assertion.DistanceAssertions.assertThat; } this.terms = termsList; this.factory = new MemoizedDistanceFactory(); } } @DataProvider(name = "equalSelfSimilarityData") public Iterator<Object[]> equalSelfSimilarityData() { return new EqualSelfSimilarityDataIterator(factory, terms); } @DataProvider(name = "minimalityData") public Iterator<Object[]> minimalityData() { return new MinimalityDataIterator(factory, terms); } @DataProvider(name = "symmetryData") public Iterator<Object[]> symmetryData() { return new SymmetryDataIterator(factory, terms); } @DataProvider(name = "triangleInequalityData") public Iterator<Object[]> triangleInequalityData() { return new TriangleInequalityDataIterator(factory, terms); } @DataProvider(name = "penaltyData") public Object[][] penaltyData() { return new Object[][] {
{Algorithm.STANDARD, factory.build(Algorithm.STANDARD), 2, 2, 2},
universal-automata/liblevenshtein-java
src/test/java/com/github/liblevenshtein/distance/factory/MemoizedDistanceFactoryTest.java
// Path: src/main/java/com/github/liblevenshtein/distance/IDistance.java // public interface IDistance<Term> extends Serializable { // // /** // * Finds the distance between two terms, {@code v} and {@code w}. The distance // * between two terms is complemented by their similarity, which is determined // * by subtracting their distance from the maximum distance they may be apart. // * @param v Term to compare with {@code w} // * @param w Term to compare with {@code v} // * @return Distance between {@code v} and {@code w} // */ // int between(Term v, Term w); // } // // Path: src/main/java/com/github/liblevenshtein/transducer/Algorithm.java // public enum Algorithm { // // /** // * This is the standard, textbook version of Levenshtein distance. It includes // * support for the elementary operations of insertion, deletion and // * substitution. // */ // STANDARD, // // /** // * Sometimes known as Damerau–Levenshtein distance, this includes the // * elementary operations described by the standard algorithm, as well as the // * elementary operation, transposition, which would incur a penalty of two // * units of error in the standard algorithm (whether it be an insertion and // * deletion, a deletion and insertion, or two substitutions). This algorithm // * is particularly useful in typed spelling-correction, where most spelling // * errors occur when a user transposes two characters. // */ // TRANSPOSITION, // // /** // * This algorithm includes the elementary operations described by the basic // * algorithm, as well as the elementary operations, merge and split. A merge // * occurs when two characters are joined together, and a split occurs when a // * single character is exploded into two characters. This algorithm is // * particularly useful in OCR applications, where one may read a "cl" when one // * should have read a "d" (i.e. merge), or when one may have read a "d" when // * one should have read a "cl" (i.e. split). // */ // MERGE_AND_SPLIT; // } // // Path: src/test/java/com/github/liblevenshtein/assertion/DistanceAssertions.java // public static <Type> DistanceAssertions<Type> assertThat( // final IDistance<Type> actual) { // return new DistanceAssertions<>(actual); // }
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.testng.annotations.BeforeClass; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import com.github.liblevenshtein.distance.IDistance; import com.github.liblevenshtein.transducer.Algorithm; import static com.github.liblevenshtein.assertion.DistanceAssertions.assertThat;
return new EqualSelfSimilarityDataIterator(factory, terms); } @DataProvider(name = "minimalityData") public Iterator<Object[]> minimalityData() { return new MinimalityDataIterator(factory, terms); } @DataProvider(name = "symmetryData") public Iterator<Object[]> symmetryData() { return new SymmetryDataIterator(factory, terms); } @DataProvider(name = "triangleInequalityData") public Iterator<Object[]> triangleInequalityData() { return new TriangleInequalityDataIterator(factory, terms); } @DataProvider(name = "penaltyData") public Object[][] penaltyData() { return new Object[][] { {Algorithm.STANDARD, factory.build(Algorithm.STANDARD), 2, 2, 2}, {Algorithm.TRANSPOSITION, factory.build(Algorithm.TRANSPOSITION), 1, 2, 2}, {Algorithm.MERGE_AND_SPLIT, factory.build(Algorithm.MERGE_AND_SPLIT), 2, 1, 1}, }; } @Test(dataProvider = "equalSelfSimilarityData") public void testEqualSelfSimilarity( final Algorithm algorithm,
// Path: src/main/java/com/github/liblevenshtein/distance/IDistance.java // public interface IDistance<Term> extends Serializable { // // /** // * Finds the distance between two terms, {@code v} and {@code w}. The distance // * between two terms is complemented by their similarity, which is determined // * by subtracting their distance from the maximum distance they may be apart. // * @param v Term to compare with {@code w} // * @param w Term to compare with {@code v} // * @return Distance between {@code v} and {@code w} // */ // int between(Term v, Term w); // } // // Path: src/main/java/com/github/liblevenshtein/transducer/Algorithm.java // public enum Algorithm { // // /** // * This is the standard, textbook version of Levenshtein distance. It includes // * support for the elementary operations of insertion, deletion and // * substitution. // */ // STANDARD, // // /** // * Sometimes known as Damerau–Levenshtein distance, this includes the // * elementary operations described by the standard algorithm, as well as the // * elementary operation, transposition, which would incur a penalty of two // * units of error in the standard algorithm (whether it be an insertion and // * deletion, a deletion and insertion, or two substitutions). This algorithm // * is particularly useful in typed spelling-correction, where most spelling // * errors occur when a user transposes two characters. // */ // TRANSPOSITION, // // /** // * This algorithm includes the elementary operations described by the basic // * algorithm, as well as the elementary operations, merge and split. A merge // * occurs when two characters are joined together, and a split occurs when a // * single character is exploded into two characters. This algorithm is // * particularly useful in OCR applications, where one may read a "cl" when one // * should have read a "d" (i.e. merge), or when one may have read a "d" when // * one should have read a "cl" (i.e. split). // */ // MERGE_AND_SPLIT; // } // // Path: src/test/java/com/github/liblevenshtein/assertion/DistanceAssertions.java // public static <Type> DistanceAssertions<Type> assertThat( // final IDistance<Type> actual) { // return new DistanceAssertions<>(actual); // } // Path: src/test/java/com/github/liblevenshtein/distance/factory/MemoizedDistanceFactoryTest.java import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.testng.annotations.BeforeClass; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import com.github.liblevenshtein.distance.IDistance; import com.github.liblevenshtein.transducer.Algorithm; import static com.github.liblevenshtein.assertion.DistanceAssertions.assertThat; return new EqualSelfSimilarityDataIterator(factory, terms); } @DataProvider(name = "minimalityData") public Iterator<Object[]> minimalityData() { return new MinimalityDataIterator(factory, terms); } @DataProvider(name = "symmetryData") public Iterator<Object[]> symmetryData() { return new SymmetryDataIterator(factory, terms); } @DataProvider(name = "triangleInequalityData") public Iterator<Object[]> triangleInequalityData() { return new TriangleInequalityDataIterator(factory, terms); } @DataProvider(name = "penaltyData") public Object[][] penaltyData() { return new Object[][] { {Algorithm.STANDARD, factory.build(Algorithm.STANDARD), 2, 2, 2}, {Algorithm.TRANSPOSITION, factory.build(Algorithm.TRANSPOSITION), 1, 2, 2}, {Algorithm.MERGE_AND_SPLIT, factory.build(Algorithm.MERGE_AND_SPLIT), 2, 1, 1}, }; } @Test(dataProvider = "equalSelfSimilarityData") public void testEqualSelfSimilarity( final Algorithm algorithm,
final IDistance<String> distance,
universal-automata/liblevenshtein-java
src/test/java/com/github/liblevenshtein/distance/factory/MemoizedDistanceFactoryTest.java
// Path: src/main/java/com/github/liblevenshtein/distance/IDistance.java // public interface IDistance<Term> extends Serializable { // // /** // * Finds the distance between two terms, {@code v} and {@code w}. The distance // * between two terms is complemented by their similarity, which is determined // * by subtracting their distance from the maximum distance they may be apart. // * @param v Term to compare with {@code w} // * @param w Term to compare with {@code v} // * @return Distance between {@code v} and {@code w} // */ // int between(Term v, Term w); // } // // Path: src/main/java/com/github/liblevenshtein/transducer/Algorithm.java // public enum Algorithm { // // /** // * This is the standard, textbook version of Levenshtein distance. It includes // * support for the elementary operations of insertion, deletion and // * substitution. // */ // STANDARD, // // /** // * Sometimes known as Damerau–Levenshtein distance, this includes the // * elementary operations described by the standard algorithm, as well as the // * elementary operation, transposition, which would incur a penalty of two // * units of error in the standard algorithm (whether it be an insertion and // * deletion, a deletion and insertion, or two substitutions). This algorithm // * is particularly useful in typed spelling-correction, where most spelling // * errors occur when a user transposes two characters. // */ // TRANSPOSITION, // // /** // * This algorithm includes the elementary operations described by the basic // * algorithm, as well as the elementary operations, merge and split. A merge // * occurs when two characters are joined together, and a split occurs when a // * single character is exploded into two characters. This algorithm is // * particularly useful in OCR applications, where one may read a "cl" when one // * should have read a "d" (i.e. merge), or when one may have read a "d" when // * one should have read a "cl" (i.e. split). // */ // MERGE_AND_SPLIT; // } // // Path: src/test/java/com/github/liblevenshtein/assertion/DistanceAssertions.java // public static <Type> DistanceAssertions<Type> assertThat( // final IDistance<Type> actual) { // return new DistanceAssertions<>(actual); // }
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.testng.annotations.BeforeClass; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import com.github.liblevenshtein.distance.IDistance; import com.github.liblevenshtein.transducer.Algorithm; import static com.github.liblevenshtein.assertion.DistanceAssertions.assertThat;
@DataProvider(name = "minimalityData") public Iterator<Object[]> minimalityData() { return new MinimalityDataIterator(factory, terms); } @DataProvider(name = "symmetryData") public Iterator<Object[]> symmetryData() { return new SymmetryDataIterator(factory, terms); } @DataProvider(name = "triangleInequalityData") public Iterator<Object[]> triangleInequalityData() { return new TriangleInequalityDataIterator(factory, terms); } @DataProvider(name = "penaltyData") public Object[][] penaltyData() { return new Object[][] { {Algorithm.STANDARD, factory.build(Algorithm.STANDARD), 2, 2, 2}, {Algorithm.TRANSPOSITION, factory.build(Algorithm.TRANSPOSITION), 1, 2, 2}, {Algorithm.MERGE_AND_SPLIT, factory.build(Algorithm.MERGE_AND_SPLIT), 2, 1, 1}, }; } @Test(dataProvider = "equalSelfSimilarityData") public void testEqualSelfSimilarity( final Algorithm algorithm, final IDistance<String> distance, final String term1, final String term2) {
// Path: src/main/java/com/github/liblevenshtein/distance/IDistance.java // public interface IDistance<Term> extends Serializable { // // /** // * Finds the distance between two terms, {@code v} and {@code w}. The distance // * between two terms is complemented by their similarity, which is determined // * by subtracting their distance from the maximum distance they may be apart. // * @param v Term to compare with {@code w} // * @param w Term to compare with {@code v} // * @return Distance between {@code v} and {@code w} // */ // int between(Term v, Term w); // } // // Path: src/main/java/com/github/liblevenshtein/transducer/Algorithm.java // public enum Algorithm { // // /** // * This is the standard, textbook version of Levenshtein distance. It includes // * support for the elementary operations of insertion, deletion and // * substitution. // */ // STANDARD, // // /** // * Sometimes known as Damerau–Levenshtein distance, this includes the // * elementary operations described by the standard algorithm, as well as the // * elementary operation, transposition, which would incur a penalty of two // * units of error in the standard algorithm (whether it be an insertion and // * deletion, a deletion and insertion, or two substitutions). This algorithm // * is particularly useful in typed spelling-correction, where most spelling // * errors occur when a user transposes two characters. // */ // TRANSPOSITION, // // /** // * This algorithm includes the elementary operations described by the basic // * algorithm, as well as the elementary operations, merge and split. A merge // * occurs when two characters are joined together, and a split occurs when a // * single character is exploded into two characters. This algorithm is // * particularly useful in OCR applications, where one may read a "cl" when one // * should have read a "d" (i.e. merge), or when one may have read a "d" when // * one should have read a "cl" (i.e. split). // */ // MERGE_AND_SPLIT; // } // // Path: src/test/java/com/github/liblevenshtein/assertion/DistanceAssertions.java // public static <Type> DistanceAssertions<Type> assertThat( // final IDistance<Type> actual) { // return new DistanceAssertions<>(actual); // } // Path: src/test/java/com/github/liblevenshtein/distance/factory/MemoizedDistanceFactoryTest.java import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.testng.annotations.BeforeClass; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import com.github.liblevenshtein.distance.IDistance; import com.github.liblevenshtein.transducer.Algorithm; import static com.github.liblevenshtein.assertion.DistanceAssertions.assertThat; @DataProvider(name = "minimalityData") public Iterator<Object[]> minimalityData() { return new MinimalityDataIterator(factory, terms); } @DataProvider(name = "symmetryData") public Iterator<Object[]> symmetryData() { return new SymmetryDataIterator(factory, terms); } @DataProvider(name = "triangleInequalityData") public Iterator<Object[]> triangleInequalityData() { return new TriangleInequalityDataIterator(factory, terms); } @DataProvider(name = "penaltyData") public Object[][] penaltyData() { return new Object[][] { {Algorithm.STANDARD, factory.build(Algorithm.STANDARD), 2, 2, 2}, {Algorithm.TRANSPOSITION, factory.build(Algorithm.TRANSPOSITION), 1, 2, 2}, {Algorithm.MERGE_AND_SPLIT, factory.build(Algorithm.MERGE_AND_SPLIT), 2, 1, 1}, }; } @Test(dataProvider = "equalSelfSimilarityData") public void testEqualSelfSimilarity( final Algorithm algorithm, final IDistance<String> distance, final String term1, final String term2) {
assertThat(distance).satisfiesEqualSelfSimilarity(term1, term2);
universal-automata/liblevenshtein-java
src/main/java/com/github/liblevenshtein/distance/MemoizedMergeAndSplit.java
// Path: src/main/java/com/github/liblevenshtein/collection/SymmetricImmutablePair.java // @Value // public class SymmetricImmutablePair<Type extends Comparable<Type>> // implements Comparable<SymmetricImmutablePair<Type>>, Serializable { // // private static final long serialVersionUID = 1L; // // /** // * First element of this pair. // */ // private final Type first; // // /** // * Second element of this pair. // */ // private final Type second; // // /** // * Returned from {@link #hashCode()}. // */ // private final int hashCode; // // /** // * Constructs a new symmetric, immutable pair on the given parameters. The // * hashCode is determined upon construction, so the assumption is made that // * first and second are immutable or will not be mutated. If they or any of // * their hashable components are mutated post-construction, the hashCode will // * be incorrect and the behavior of instances of this pair in such structures // * as hash maps will be undefined (e.g. this pair may seem to "disappear" from // * the hash map, even though it's still there). // * @param first First element of this pair // * @param second Second element of this pair // */ // public SymmetricImmutablePair( // @NonNull final Type first, // @NonNull final Type second) { // // if (first.compareTo(second) < 0) { // this.first = first; // this.second = second; // } // else { // this.first = second; // this.second = first; // } // // this.hashCode = new HashCodeBuilder(541, 7873) // .append(this.first) // .append(this.second) // .toHashCode(); // } // // /** // * {@inheritDoc} // */ // @Override // public int compareTo(final SymmetricImmutablePair<Type> other) { // final int c = first.compareTo(other.first()); // if (0 == c) { // return second.compareTo(other.second()); // } // return c; // } // // /** // * {@inheritDoc} // */ // @Override // public boolean equals(final Object o) { // if (!(o instanceof SymmetricImmutablePair)) { // return false; // } // // @SuppressWarnings("unchecked") // final SymmetricImmutablePair<Type> other = (SymmetricImmutablePair<Type>) o; // return 0 == compareTo(other); // } // // /** // * {@inheritDoc} // */ // @Override // public int hashCode() { // return hashCode; // } // }
import lombok.val; import com.github.liblevenshtein.collection.SymmetricImmutablePair;
package com.github.liblevenshtein.distance; /** * Memoizes the distance between two terms, where the distance is calculated * using the standard Levenshtein distance extended with merge and split. * @author Dylon Edwards * @since 2.1.0 */ public class MemoizedMergeAndSplit extends AbstractMemoized { private static final long serialVersionUID = 1L; /** * {@inheritDoc} */ @Override @SuppressWarnings("checkstyle:finalparameters") public int memoizedDistance(String v, String w) {
// Path: src/main/java/com/github/liblevenshtein/collection/SymmetricImmutablePair.java // @Value // public class SymmetricImmutablePair<Type extends Comparable<Type>> // implements Comparable<SymmetricImmutablePair<Type>>, Serializable { // // private static final long serialVersionUID = 1L; // // /** // * First element of this pair. // */ // private final Type first; // // /** // * Second element of this pair. // */ // private final Type second; // // /** // * Returned from {@link #hashCode()}. // */ // private final int hashCode; // // /** // * Constructs a new symmetric, immutable pair on the given parameters. The // * hashCode is determined upon construction, so the assumption is made that // * first and second are immutable or will not be mutated. If they or any of // * their hashable components are mutated post-construction, the hashCode will // * be incorrect and the behavior of instances of this pair in such structures // * as hash maps will be undefined (e.g. this pair may seem to "disappear" from // * the hash map, even though it's still there). // * @param first First element of this pair // * @param second Second element of this pair // */ // public SymmetricImmutablePair( // @NonNull final Type first, // @NonNull final Type second) { // // if (first.compareTo(second) < 0) { // this.first = first; // this.second = second; // } // else { // this.first = second; // this.second = first; // } // // this.hashCode = new HashCodeBuilder(541, 7873) // .append(this.first) // .append(this.second) // .toHashCode(); // } // // /** // * {@inheritDoc} // */ // @Override // public int compareTo(final SymmetricImmutablePair<Type> other) { // final int c = first.compareTo(other.first()); // if (0 == c) { // return second.compareTo(other.second()); // } // return c; // } // // /** // * {@inheritDoc} // */ // @Override // public boolean equals(final Object o) { // if (!(o instanceof SymmetricImmutablePair)) { // return false; // } // // @SuppressWarnings("unchecked") // final SymmetricImmutablePair<Type> other = (SymmetricImmutablePair<Type>) o; // return 0 == compareTo(other); // } // // /** // * {@inheritDoc} // */ // @Override // public int hashCode() { // return hashCode; // } // } // Path: src/main/java/com/github/liblevenshtein/distance/MemoizedMergeAndSplit.java import lombok.val; import com.github.liblevenshtein.collection.SymmetricImmutablePair; package com.github.liblevenshtein.distance; /** * Memoizes the distance between two terms, where the distance is calculated * using the standard Levenshtein distance extended with merge and split. * @author Dylon Edwards * @since 2.1.0 */ public class MemoizedMergeAndSplit extends AbstractMemoized { private static final long serialVersionUID = 1L; /** * {@inheritDoc} */ @Override @SuppressWarnings("checkstyle:finalparameters") public int memoizedDistance(String v, String w) {
val key = new SymmetricImmutablePair<String>(v, w);
universal-automata/liblevenshtein-java
src/test/java/com/github/liblevenshtein/transducer/StateIteratorTest.java
// Path: src/test/java/com/github/liblevenshtein/assertion/StateAssertions.java // public static StateAssertions assertThat(final State actual) { // return new StateAssertions(actual); // }
import org.testng.annotations.Test; import static com.github.liblevenshtein.assertion.StateAssertions.assertThat;
package com.github.liblevenshtein.transducer; public class StateIteratorTest { @Test public void emptyStateIteratorShouldNotHaveNextElement() { final State state = new State();
// Path: src/test/java/com/github/liblevenshtein/assertion/StateAssertions.java // public static StateAssertions assertThat(final State actual) { // return new StateAssertions(actual); // } // Path: src/test/java/com/github/liblevenshtein/transducer/StateIteratorTest.java import org.testng.annotations.Test; import static com.github.liblevenshtein.assertion.StateAssertions.assertThat; package com.github.liblevenshtein.transducer; public class StateIteratorTest { @Test public void emptyStateIteratorShouldNotHaveNextElement() { final State state = new State();
assertThat(state).iterator()
universal-automata/liblevenshtein-java
src/test/java/com/github/liblevenshtein/assertion/ComparatorAssertionsTest.java
// Path: src/test/java/com/github/liblevenshtein/assertion/ComparatorAssertions.java // public static <Type> ComparatorAssertions<Type> assertThat( // final Comparator<Type> actual) { // return new ComparatorAssertions<>(actual); // }
import java.util.Comparator; import org.testng.annotations.Test; import static com.github.liblevenshtein.assertion.ComparatorAssertions.assertThat;
package com.github.liblevenshtein.assertion; public class ComparatorAssertionsTest { private final Comparator<Integer> comparator = (i, j) -> Integer.compare(i, j); @Test public void testEqualsTo() {
// Path: src/test/java/com/github/liblevenshtein/assertion/ComparatorAssertions.java // public static <Type> ComparatorAssertions<Type> assertThat( // final Comparator<Type> actual) { // return new ComparatorAssertions<>(actual); // } // Path: src/test/java/com/github/liblevenshtein/assertion/ComparatorAssertionsTest.java import java.util.Comparator; import org.testng.annotations.Test; import static com.github.liblevenshtein.assertion.ComparatorAssertions.assertThat; package com.github.liblevenshtein.assertion; public class ComparatorAssertionsTest { private final Comparator<Integer> comparator = (i, j) -> Integer.compare(i, j); @Test public void testEqualsTo() {
assertThat(comparator).comparesEqualTo(1, 1);
universal-automata/liblevenshtein-java
src/test/java/com/github/liblevenshtein/transducer/AbstractPositionTransitionFunctionTest.java
// Path: src/main/java/com/github/liblevenshtein/transducer/factory/PositionFactory.java // @NoArgsConstructor // public class PositionFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds a dummy position. // * @return Dummy position. // */ // public Position build() { // return new Position(-1, -1); // } // // /** // * Builds a position vector for the standard, Levenshtein algorihtm. // * @param termIndex Current index of the spelling candidate. // * @param numErrors Number of accumulated errors at index {@code termIndex}. // * @return New position vector having index {@code termIndex} and error // * {@code numErrors}. // */ // public Position build(final int termIndex, final int numErrors) { // return new Position(termIndex, numErrors); // } // // /** // * Builds a position vector for the transposition and merge-and-split, // * Levenshtein algorihtms. // * @param termIndex Current index of the spelling candidate. // * @param numErrors Number of accumulated errors at index {@code termIndex}. // * @param isSpecial Either {@code 1} or {@code 0}, depending on whether the // * position is a special case (numErrors.g. a transposition position). // * @return New position vector having index {@code termIndex}, error // * {@code numErrors}, and special marker {@code isSpecial}. // */ // public Position build(final int termIndex, final int numErrors, final boolean isSpecial) { // if (isSpecial) { // return new SpecialPosition(termIndex, numErrors); // } // // return new Position(termIndex, numErrors); // } // } // // Path: src/main/java/com/github/liblevenshtein/transducer/factory/StateFactory.java // public class StateFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds a new, Levenshtein state with the given position vectors. // * @param positions Array of position vectors to link into the state. // * @return New state having the position vectors. // */ // public State build(final Position... positions) { // final State state = new State(); // // Position prev = null; // for (final Position curr : positions) { // state.insertAfter(prev, curr); // prev = curr; // } // // return state; // } // }
import static org.assertj.core.api.Assertions.assertThat; import com.github.liblevenshtein.transducer.factory.PositionFactory; import com.github.liblevenshtein.transducer.factory.StateFactory;
package com.github.liblevenshtein.transducer; public abstract class AbstractPositionTransitionFunctionTest { protected static final int N = 3; // max number of errors protected static final int W = 4; // length of characteristic vector protected final PositionTransitionFunction transition = buildTransition();
// Path: src/main/java/com/github/liblevenshtein/transducer/factory/PositionFactory.java // @NoArgsConstructor // public class PositionFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds a dummy position. // * @return Dummy position. // */ // public Position build() { // return new Position(-1, -1); // } // // /** // * Builds a position vector for the standard, Levenshtein algorihtm. // * @param termIndex Current index of the spelling candidate. // * @param numErrors Number of accumulated errors at index {@code termIndex}. // * @return New position vector having index {@code termIndex} and error // * {@code numErrors}. // */ // public Position build(final int termIndex, final int numErrors) { // return new Position(termIndex, numErrors); // } // // /** // * Builds a position vector for the transposition and merge-and-split, // * Levenshtein algorihtms. // * @param termIndex Current index of the spelling candidate. // * @param numErrors Number of accumulated errors at index {@code termIndex}. // * @param isSpecial Either {@code 1} or {@code 0}, depending on whether the // * position is a special case (numErrors.g. a transposition position). // * @return New position vector having index {@code termIndex}, error // * {@code numErrors}, and special marker {@code isSpecial}. // */ // public Position build(final int termIndex, final int numErrors, final boolean isSpecial) { // if (isSpecial) { // return new SpecialPosition(termIndex, numErrors); // } // // return new Position(termIndex, numErrors); // } // } // // Path: src/main/java/com/github/liblevenshtein/transducer/factory/StateFactory.java // public class StateFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds a new, Levenshtein state with the given position vectors. // * @param positions Array of position vectors to link into the state. // * @return New state having the position vectors. // */ // public State build(final Position... positions) { // final State state = new State(); // // Position prev = null; // for (final Position curr : positions) { // state.insertAfter(prev, curr); // prev = curr; // } // // return state; // } // } // Path: src/test/java/com/github/liblevenshtein/transducer/AbstractPositionTransitionFunctionTest.java import static org.assertj.core.api.Assertions.assertThat; import com.github.liblevenshtein.transducer.factory.PositionFactory; import com.github.liblevenshtein.transducer.factory.StateFactory; package com.github.liblevenshtein.transducer; public abstract class AbstractPositionTransitionFunctionTest { protected static final int N = 3; // max number of errors protected static final int W = 4; // length of characteristic vector protected final PositionTransitionFunction transition = buildTransition();
protected final StateFactory stateFactory = new StateFactory();
universal-automata/liblevenshtein-java
src/test/java/com/github/liblevenshtein/transducer/AbstractPositionTransitionFunctionTest.java
// Path: src/main/java/com/github/liblevenshtein/transducer/factory/PositionFactory.java // @NoArgsConstructor // public class PositionFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds a dummy position. // * @return Dummy position. // */ // public Position build() { // return new Position(-1, -1); // } // // /** // * Builds a position vector for the standard, Levenshtein algorihtm. // * @param termIndex Current index of the spelling candidate. // * @param numErrors Number of accumulated errors at index {@code termIndex}. // * @return New position vector having index {@code termIndex} and error // * {@code numErrors}. // */ // public Position build(final int termIndex, final int numErrors) { // return new Position(termIndex, numErrors); // } // // /** // * Builds a position vector for the transposition and merge-and-split, // * Levenshtein algorihtms. // * @param termIndex Current index of the spelling candidate. // * @param numErrors Number of accumulated errors at index {@code termIndex}. // * @param isSpecial Either {@code 1} or {@code 0}, depending on whether the // * position is a special case (numErrors.g. a transposition position). // * @return New position vector having index {@code termIndex}, error // * {@code numErrors}, and special marker {@code isSpecial}. // */ // public Position build(final int termIndex, final int numErrors, final boolean isSpecial) { // if (isSpecial) { // return new SpecialPosition(termIndex, numErrors); // } // // return new Position(termIndex, numErrors); // } // } // // Path: src/main/java/com/github/liblevenshtein/transducer/factory/StateFactory.java // public class StateFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds a new, Levenshtein state with the given position vectors. // * @param positions Array of position vectors to link into the state. // * @return New state having the position vectors. // */ // public State build(final Position... positions) { // final State state = new State(); // // Position prev = null; // for (final Position curr : positions) { // state.insertAfter(prev, curr); // prev = curr; // } // // return state; // } // }
import static org.assertj.core.api.Assertions.assertThat; import com.github.liblevenshtein.transducer.factory.PositionFactory; import com.github.liblevenshtein.transducer.factory.StateFactory;
package com.github.liblevenshtein.transducer; public abstract class AbstractPositionTransitionFunctionTest { protected static final int N = 3; // max number of errors protected static final int W = 4; // length of characteristic vector protected final PositionTransitionFunction transition = buildTransition(); protected final StateFactory stateFactory = new StateFactory();
// Path: src/main/java/com/github/liblevenshtein/transducer/factory/PositionFactory.java // @NoArgsConstructor // public class PositionFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds a dummy position. // * @return Dummy position. // */ // public Position build() { // return new Position(-1, -1); // } // // /** // * Builds a position vector for the standard, Levenshtein algorihtm. // * @param termIndex Current index of the spelling candidate. // * @param numErrors Number of accumulated errors at index {@code termIndex}. // * @return New position vector having index {@code termIndex} and error // * {@code numErrors}. // */ // public Position build(final int termIndex, final int numErrors) { // return new Position(termIndex, numErrors); // } // // /** // * Builds a position vector for the transposition and merge-and-split, // * Levenshtein algorihtms. // * @param termIndex Current index of the spelling candidate. // * @param numErrors Number of accumulated errors at index {@code termIndex}. // * @param isSpecial Either {@code 1} or {@code 0}, depending on whether the // * position is a special case (numErrors.g. a transposition position). // * @return New position vector having index {@code termIndex}, error // * {@code numErrors}, and special marker {@code isSpecial}. // */ // public Position build(final int termIndex, final int numErrors, final boolean isSpecial) { // if (isSpecial) { // return new SpecialPosition(termIndex, numErrors); // } // // return new Position(termIndex, numErrors); // } // } // // Path: src/main/java/com/github/liblevenshtein/transducer/factory/StateFactory.java // public class StateFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds a new, Levenshtein state with the given position vectors. // * @param positions Array of position vectors to link into the state. // * @return New state having the position vectors. // */ // public State build(final Position... positions) { // final State state = new State(); // // Position prev = null; // for (final Position curr : positions) { // state.insertAfter(prev, curr); // prev = curr; // } // // return state; // } // } // Path: src/test/java/com/github/liblevenshtein/transducer/AbstractPositionTransitionFunctionTest.java import static org.assertj.core.api.Assertions.assertThat; import com.github.liblevenshtein.transducer.factory.PositionFactory; import com.github.liblevenshtein.transducer.factory.StateFactory; package com.github.liblevenshtein.transducer; public abstract class AbstractPositionTransitionFunctionTest { protected static final int N = 3; // max number of errors protected static final int W = 4; // length of characteristic vector protected final PositionTransitionFunction transition = buildTransition(); protected final StateFactory stateFactory = new StateFactory();
protected final PositionFactory positionFactory = new PositionFactory();
universal-automata/liblevenshtein-java
src/test/java/com/github/liblevenshtein/transducer/StandardPositionDistanceFunctionTest.java
// Path: src/main/java/com/github/liblevenshtein/transducer/factory/PositionFactory.java // @NoArgsConstructor // public class PositionFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds a dummy position. // * @return Dummy position. // */ // public Position build() { // return new Position(-1, -1); // } // // /** // * Builds a position vector for the standard, Levenshtein algorihtm. // * @param termIndex Current index of the spelling candidate. // * @param numErrors Number of accumulated errors at index {@code termIndex}. // * @return New position vector having index {@code termIndex} and error // * {@code numErrors}. // */ // public Position build(final int termIndex, final int numErrors) { // return new Position(termIndex, numErrors); // } // // /** // * Builds a position vector for the transposition and merge-and-split, // * Levenshtein algorihtms. // * @param termIndex Current index of the spelling candidate. // * @param numErrors Number of accumulated errors at index {@code termIndex}. // * @param isSpecial Either {@code 1} or {@code 0}, depending on whether the // * position is a special case (numErrors.g. a transposition position). // * @return New position vector having index {@code termIndex}, error // * {@code numErrors}, and special marker {@code isSpecial}. // */ // public Position build(final int termIndex, final int numErrors, final boolean isSpecial) { // if (isSpecial) { // return new SpecialPosition(termIndex, numErrors); // } // // return new Position(termIndex, numErrors); // } // } // // Path: src/main/java/com/github/liblevenshtein/transducer/factory/StateFactory.java // public class StateFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds a new, Levenshtein state with the given position vectors. // * @param positions Array of position vectors to link into the state. // * @return New state having the position vectors. // */ // public State build(final Position... positions) { // final State state = new State(); // // Position prev = null; // for (final Position curr : positions) { // state.insertAfter(prev, curr); // prev = curr; // } // // return state; // } // } // // Path: src/test/java/com/github/liblevenshtein/assertion/DistanceFunctionAssertions.java // public static DistanceFunctionAssertions assertThat(final DistanceFunction actual) { // return new DistanceFunctionAssertions(actual); // }
import org.testng.annotations.Test; import lombok.val; import com.github.liblevenshtein.transducer.factory.PositionFactory; import com.github.liblevenshtein.transducer.factory.StateFactory; import static com.github.liblevenshtein.assertion.DistanceFunctionAssertions.assertThat;
package com.github.liblevenshtein.transducer; public class StandardPositionDistanceFunctionTest { @Test public void testAt() {
// Path: src/main/java/com/github/liblevenshtein/transducer/factory/PositionFactory.java // @NoArgsConstructor // public class PositionFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds a dummy position. // * @return Dummy position. // */ // public Position build() { // return new Position(-1, -1); // } // // /** // * Builds a position vector for the standard, Levenshtein algorihtm. // * @param termIndex Current index of the spelling candidate. // * @param numErrors Number of accumulated errors at index {@code termIndex}. // * @return New position vector having index {@code termIndex} and error // * {@code numErrors}. // */ // public Position build(final int termIndex, final int numErrors) { // return new Position(termIndex, numErrors); // } // // /** // * Builds a position vector for the transposition and merge-and-split, // * Levenshtein algorihtms. // * @param termIndex Current index of the spelling candidate. // * @param numErrors Number of accumulated errors at index {@code termIndex}. // * @param isSpecial Either {@code 1} or {@code 0}, depending on whether the // * position is a special case (numErrors.g. a transposition position). // * @return New position vector having index {@code termIndex}, error // * {@code numErrors}, and special marker {@code isSpecial}. // */ // public Position build(final int termIndex, final int numErrors, final boolean isSpecial) { // if (isSpecial) { // return new SpecialPosition(termIndex, numErrors); // } // // return new Position(termIndex, numErrors); // } // } // // Path: src/main/java/com/github/liblevenshtein/transducer/factory/StateFactory.java // public class StateFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds a new, Levenshtein state with the given position vectors. // * @param positions Array of position vectors to link into the state. // * @return New state having the position vectors. // */ // public State build(final Position... positions) { // final State state = new State(); // // Position prev = null; // for (final Position curr : positions) { // state.insertAfter(prev, curr); // prev = curr; // } // // return state; // } // } // // Path: src/test/java/com/github/liblevenshtein/assertion/DistanceFunctionAssertions.java // public static DistanceFunctionAssertions assertThat(final DistanceFunction actual) { // return new DistanceFunctionAssertions(actual); // } // Path: src/test/java/com/github/liblevenshtein/transducer/StandardPositionDistanceFunctionTest.java import org.testng.annotations.Test; import lombok.val; import com.github.liblevenshtein.transducer.factory.PositionFactory; import com.github.liblevenshtein.transducer.factory.StateFactory; import static com.github.liblevenshtein.assertion.DistanceFunctionAssertions.assertThat; package com.github.liblevenshtein.transducer; public class StandardPositionDistanceFunctionTest { @Test public void testAt() {
val stateFactory = new StateFactory();
universal-automata/liblevenshtein-java
src/test/java/com/github/liblevenshtein/transducer/StandardPositionDistanceFunctionTest.java
// Path: src/main/java/com/github/liblevenshtein/transducer/factory/PositionFactory.java // @NoArgsConstructor // public class PositionFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds a dummy position. // * @return Dummy position. // */ // public Position build() { // return new Position(-1, -1); // } // // /** // * Builds a position vector for the standard, Levenshtein algorihtm. // * @param termIndex Current index of the spelling candidate. // * @param numErrors Number of accumulated errors at index {@code termIndex}. // * @return New position vector having index {@code termIndex} and error // * {@code numErrors}. // */ // public Position build(final int termIndex, final int numErrors) { // return new Position(termIndex, numErrors); // } // // /** // * Builds a position vector for the transposition and merge-and-split, // * Levenshtein algorihtms. // * @param termIndex Current index of the spelling candidate. // * @param numErrors Number of accumulated errors at index {@code termIndex}. // * @param isSpecial Either {@code 1} or {@code 0}, depending on whether the // * position is a special case (numErrors.g. a transposition position). // * @return New position vector having index {@code termIndex}, error // * {@code numErrors}, and special marker {@code isSpecial}. // */ // public Position build(final int termIndex, final int numErrors, final boolean isSpecial) { // if (isSpecial) { // return new SpecialPosition(termIndex, numErrors); // } // // return new Position(termIndex, numErrors); // } // } // // Path: src/main/java/com/github/liblevenshtein/transducer/factory/StateFactory.java // public class StateFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds a new, Levenshtein state with the given position vectors. // * @param positions Array of position vectors to link into the state. // * @return New state having the position vectors. // */ // public State build(final Position... positions) { // final State state = new State(); // // Position prev = null; // for (final Position curr : positions) { // state.insertAfter(prev, curr); // prev = curr; // } // // return state; // } // } // // Path: src/test/java/com/github/liblevenshtein/assertion/DistanceFunctionAssertions.java // public static DistanceFunctionAssertions assertThat(final DistanceFunction actual) { // return new DistanceFunctionAssertions(actual); // }
import org.testng.annotations.Test; import lombok.val; import com.github.liblevenshtein.transducer.factory.PositionFactory; import com.github.liblevenshtein.transducer.factory.StateFactory; import static com.github.liblevenshtein.assertion.DistanceFunctionAssertions.assertThat;
package com.github.liblevenshtein.transducer; public class StandardPositionDistanceFunctionTest { @Test public void testAt() { val stateFactory = new StateFactory();
// Path: src/main/java/com/github/liblevenshtein/transducer/factory/PositionFactory.java // @NoArgsConstructor // public class PositionFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds a dummy position. // * @return Dummy position. // */ // public Position build() { // return new Position(-1, -1); // } // // /** // * Builds a position vector for the standard, Levenshtein algorihtm. // * @param termIndex Current index of the spelling candidate. // * @param numErrors Number of accumulated errors at index {@code termIndex}. // * @return New position vector having index {@code termIndex} and error // * {@code numErrors}. // */ // public Position build(final int termIndex, final int numErrors) { // return new Position(termIndex, numErrors); // } // // /** // * Builds a position vector for the transposition and merge-and-split, // * Levenshtein algorihtms. // * @param termIndex Current index of the spelling candidate. // * @param numErrors Number of accumulated errors at index {@code termIndex}. // * @param isSpecial Either {@code 1} or {@code 0}, depending on whether the // * position is a special case (numErrors.g. a transposition position). // * @return New position vector having index {@code termIndex}, error // * {@code numErrors}, and special marker {@code isSpecial}. // */ // public Position build(final int termIndex, final int numErrors, final boolean isSpecial) { // if (isSpecial) { // return new SpecialPosition(termIndex, numErrors); // } // // return new Position(termIndex, numErrors); // } // } // // Path: src/main/java/com/github/liblevenshtein/transducer/factory/StateFactory.java // public class StateFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds a new, Levenshtein state with the given position vectors. // * @param positions Array of position vectors to link into the state. // * @return New state having the position vectors. // */ // public State build(final Position... positions) { // final State state = new State(); // // Position prev = null; // for (final Position curr : positions) { // state.insertAfter(prev, curr); // prev = curr; // } // // return state; // } // } // // Path: src/test/java/com/github/liblevenshtein/assertion/DistanceFunctionAssertions.java // public static DistanceFunctionAssertions assertThat(final DistanceFunction actual) { // return new DistanceFunctionAssertions(actual); // } // Path: src/test/java/com/github/liblevenshtein/transducer/StandardPositionDistanceFunctionTest.java import org.testng.annotations.Test; import lombok.val; import com.github.liblevenshtein.transducer.factory.PositionFactory; import com.github.liblevenshtein.transducer.factory.StateFactory; import static com.github.liblevenshtein.assertion.DistanceFunctionAssertions.assertThat; package com.github.liblevenshtein.transducer; public class StandardPositionDistanceFunctionTest { @Test public void testAt() { val stateFactory = new StateFactory();
val positionFactory = new PositionFactory();
universal-automata/liblevenshtein-java
src/test/java/com/github/liblevenshtein/transducer/StandardPositionDistanceFunctionTest.java
// Path: src/main/java/com/github/liblevenshtein/transducer/factory/PositionFactory.java // @NoArgsConstructor // public class PositionFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds a dummy position. // * @return Dummy position. // */ // public Position build() { // return new Position(-1, -1); // } // // /** // * Builds a position vector for the standard, Levenshtein algorihtm. // * @param termIndex Current index of the spelling candidate. // * @param numErrors Number of accumulated errors at index {@code termIndex}. // * @return New position vector having index {@code termIndex} and error // * {@code numErrors}. // */ // public Position build(final int termIndex, final int numErrors) { // return new Position(termIndex, numErrors); // } // // /** // * Builds a position vector for the transposition and merge-and-split, // * Levenshtein algorihtms. // * @param termIndex Current index of the spelling candidate. // * @param numErrors Number of accumulated errors at index {@code termIndex}. // * @param isSpecial Either {@code 1} or {@code 0}, depending on whether the // * position is a special case (numErrors.g. a transposition position). // * @return New position vector having index {@code termIndex}, error // * {@code numErrors}, and special marker {@code isSpecial}. // */ // public Position build(final int termIndex, final int numErrors, final boolean isSpecial) { // if (isSpecial) { // return new SpecialPosition(termIndex, numErrors); // } // // return new Position(termIndex, numErrors); // } // } // // Path: src/main/java/com/github/liblevenshtein/transducer/factory/StateFactory.java // public class StateFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds a new, Levenshtein state with the given position vectors. // * @param positions Array of position vectors to link into the state. // * @return New state having the position vectors. // */ // public State build(final Position... positions) { // final State state = new State(); // // Position prev = null; // for (final Position curr : positions) { // state.insertAfter(prev, curr); // prev = curr; // } // // return state; // } // } // // Path: src/test/java/com/github/liblevenshtein/assertion/DistanceFunctionAssertions.java // public static DistanceFunctionAssertions assertThat(final DistanceFunction actual) { // return new DistanceFunctionAssertions(actual); // }
import org.testng.annotations.Test; import lombok.val; import com.github.liblevenshtein.transducer.factory.PositionFactory; import com.github.liblevenshtein.transducer.factory.StateFactory; import static com.github.liblevenshtein.assertion.DistanceFunctionAssertions.assertThat;
package com.github.liblevenshtein.transducer; public class StandardPositionDistanceFunctionTest { @Test public void testAt() { val stateFactory = new StateFactory(); val positionFactory = new PositionFactory(); final State state = stateFactory.build( positionFactory.build(2, 3), positionFactory.build(1, 1), positionFactory.build(4, 2)); final DistanceFunction distance = new DistanceFunction.ForStandardPositions();
// Path: src/main/java/com/github/liblevenshtein/transducer/factory/PositionFactory.java // @NoArgsConstructor // public class PositionFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds a dummy position. // * @return Dummy position. // */ // public Position build() { // return new Position(-1, -1); // } // // /** // * Builds a position vector for the standard, Levenshtein algorihtm. // * @param termIndex Current index of the spelling candidate. // * @param numErrors Number of accumulated errors at index {@code termIndex}. // * @return New position vector having index {@code termIndex} and error // * {@code numErrors}. // */ // public Position build(final int termIndex, final int numErrors) { // return new Position(termIndex, numErrors); // } // // /** // * Builds a position vector for the transposition and merge-and-split, // * Levenshtein algorihtms. // * @param termIndex Current index of the spelling candidate. // * @param numErrors Number of accumulated errors at index {@code termIndex}. // * @param isSpecial Either {@code 1} or {@code 0}, depending on whether the // * position is a special case (numErrors.g. a transposition position). // * @return New position vector having index {@code termIndex}, error // * {@code numErrors}, and special marker {@code isSpecial}. // */ // public Position build(final int termIndex, final int numErrors, final boolean isSpecial) { // if (isSpecial) { // return new SpecialPosition(termIndex, numErrors); // } // // return new Position(termIndex, numErrors); // } // } // // Path: src/main/java/com/github/liblevenshtein/transducer/factory/StateFactory.java // public class StateFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds a new, Levenshtein state with the given position vectors. // * @param positions Array of position vectors to link into the state. // * @return New state having the position vectors. // */ // public State build(final Position... positions) { // final State state = new State(); // // Position prev = null; // for (final Position curr : positions) { // state.insertAfter(prev, curr); // prev = curr; // } // // return state; // } // } // // Path: src/test/java/com/github/liblevenshtein/assertion/DistanceFunctionAssertions.java // public static DistanceFunctionAssertions assertThat(final DistanceFunction actual) { // return new DistanceFunctionAssertions(actual); // } // Path: src/test/java/com/github/liblevenshtein/transducer/StandardPositionDistanceFunctionTest.java import org.testng.annotations.Test; import lombok.val; import com.github.liblevenshtein.transducer.factory.PositionFactory; import com.github.liblevenshtein.transducer.factory.StateFactory; import static com.github.liblevenshtein.assertion.DistanceFunctionAssertions.assertThat; package com.github.liblevenshtein.transducer; public class StandardPositionDistanceFunctionTest { @Test public void testAt() { val stateFactory = new StateFactory(); val positionFactory = new PositionFactory(); final State state = stateFactory.build( positionFactory.build(2, 3), positionFactory.build(1, 1), positionFactory.build(4, 2)); final DistanceFunction distance = new DistanceFunction.ForStandardPositions();
assertThat(distance).hasDistance(state, 4, 2);
universal-automata/liblevenshtein-java
src/main/java/com/github/liblevenshtein/transducer/factory/PositionFactory.java
// Path: src/main/java/com/github/liblevenshtein/transducer/Position.java // @Data // @RequiredArgsConstructor // public class Position implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Reference to the next node in this linked-list. The next node may be null // */ // private Position next = null; // // /** // * Index of the dictionary term represented by this coordinate. // */ // private final int termIndex; // // /** // * Number of accumulated errors at this coordinate. // */ // private final int numErrors; // // /** // * Whether this position should be treated specially, such as whether it // * represents a tranposition, merge, or split. // * @return Whether this position should be treated specially. // */ // public boolean isSpecial() { // return false; // } // } // // Path: src/main/java/com/github/liblevenshtein/transducer/SpecialPosition.java // @ToString(callSuper = true) // @EqualsAndHashCode(callSuper = true) // public class SpecialPosition extends Position implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds a new {@link Position}, extended with some special operation (e.g. // * transposition or merge-and-split). // * @param termIndex Index of the dictionary term represented by this coordinate. // * @param numErrors Number of accumulated errors at this coordinate. // */ // public SpecialPosition(final int termIndex, final int numErrors) { // super(termIndex, numErrors); // } // // /** // * {@inheritDoc} // */ // @Override // public boolean isSpecial() { // return true; // } // }
import java.io.Serializable; import lombok.NoArgsConstructor; import com.github.liblevenshtein.transducer.Position; import com.github.liblevenshtein.transducer.SpecialPosition;
package com.github.liblevenshtein.transducer.factory; /** * Builds position vectors for the given algorithm. * @author Dylon Edwards * @since 2.1.0 */ @NoArgsConstructor public class PositionFactory implements Serializable { private static final long serialVersionUID = 1L; /** * Builds a dummy position. * @return Dummy position. */
// Path: src/main/java/com/github/liblevenshtein/transducer/Position.java // @Data // @RequiredArgsConstructor // public class Position implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Reference to the next node in this linked-list. The next node may be null // */ // private Position next = null; // // /** // * Index of the dictionary term represented by this coordinate. // */ // private final int termIndex; // // /** // * Number of accumulated errors at this coordinate. // */ // private final int numErrors; // // /** // * Whether this position should be treated specially, such as whether it // * represents a tranposition, merge, or split. // * @return Whether this position should be treated specially. // */ // public boolean isSpecial() { // return false; // } // } // // Path: src/main/java/com/github/liblevenshtein/transducer/SpecialPosition.java // @ToString(callSuper = true) // @EqualsAndHashCode(callSuper = true) // public class SpecialPosition extends Position implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds a new {@link Position}, extended with some special operation (e.g. // * transposition or merge-and-split). // * @param termIndex Index of the dictionary term represented by this coordinate. // * @param numErrors Number of accumulated errors at this coordinate. // */ // public SpecialPosition(final int termIndex, final int numErrors) { // super(termIndex, numErrors); // } // // /** // * {@inheritDoc} // */ // @Override // public boolean isSpecial() { // return true; // } // } // Path: src/main/java/com/github/liblevenshtein/transducer/factory/PositionFactory.java import java.io.Serializable; import lombok.NoArgsConstructor; import com.github.liblevenshtein.transducer.Position; import com.github.liblevenshtein.transducer.SpecialPosition; package com.github.liblevenshtein.transducer.factory; /** * Builds position vectors for the given algorithm. * @author Dylon Edwards * @since 2.1.0 */ @NoArgsConstructor public class PositionFactory implements Serializable { private static final long serialVersionUID = 1L; /** * Builds a dummy position. * @return Dummy position. */
public Position build() {
universal-automata/liblevenshtein-java
src/main/java/com/github/liblevenshtein/transducer/factory/PositionFactory.java
// Path: src/main/java/com/github/liblevenshtein/transducer/Position.java // @Data // @RequiredArgsConstructor // public class Position implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Reference to the next node in this linked-list. The next node may be null // */ // private Position next = null; // // /** // * Index of the dictionary term represented by this coordinate. // */ // private final int termIndex; // // /** // * Number of accumulated errors at this coordinate. // */ // private final int numErrors; // // /** // * Whether this position should be treated specially, such as whether it // * represents a tranposition, merge, or split. // * @return Whether this position should be treated specially. // */ // public boolean isSpecial() { // return false; // } // } // // Path: src/main/java/com/github/liblevenshtein/transducer/SpecialPosition.java // @ToString(callSuper = true) // @EqualsAndHashCode(callSuper = true) // public class SpecialPosition extends Position implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds a new {@link Position}, extended with some special operation (e.g. // * transposition or merge-and-split). // * @param termIndex Index of the dictionary term represented by this coordinate. // * @param numErrors Number of accumulated errors at this coordinate. // */ // public SpecialPosition(final int termIndex, final int numErrors) { // super(termIndex, numErrors); // } // // /** // * {@inheritDoc} // */ // @Override // public boolean isSpecial() { // return true; // } // }
import java.io.Serializable; import lombok.NoArgsConstructor; import com.github.liblevenshtein.transducer.Position; import com.github.liblevenshtein.transducer.SpecialPosition;
package com.github.liblevenshtein.transducer.factory; /** * Builds position vectors for the given algorithm. * @author Dylon Edwards * @since 2.1.0 */ @NoArgsConstructor public class PositionFactory implements Serializable { private static final long serialVersionUID = 1L; /** * Builds a dummy position. * @return Dummy position. */ public Position build() { return new Position(-1, -1); } /** * Builds a position vector for the standard, Levenshtein algorihtm. * @param termIndex Current index of the spelling candidate. * @param numErrors Number of accumulated errors at index {@code termIndex}. * @return New position vector having index {@code termIndex} and error * {@code numErrors}. */ public Position build(final int termIndex, final int numErrors) { return new Position(termIndex, numErrors); } /** * Builds a position vector for the transposition and merge-and-split, * Levenshtein algorihtms. * @param termIndex Current index of the spelling candidate. * @param numErrors Number of accumulated errors at index {@code termIndex}. * @param isSpecial Either {@code 1} or {@code 0}, depending on whether the * position is a special case (numErrors.g. a transposition position). * @return New position vector having index {@code termIndex}, error * {@code numErrors}, and special marker {@code isSpecial}. */ public Position build(final int termIndex, final int numErrors, final boolean isSpecial) { if (isSpecial) {
// Path: src/main/java/com/github/liblevenshtein/transducer/Position.java // @Data // @RequiredArgsConstructor // public class Position implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Reference to the next node in this linked-list. The next node may be null // */ // private Position next = null; // // /** // * Index of the dictionary term represented by this coordinate. // */ // private final int termIndex; // // /** // * Number of accumulated errors at this coordinate. // */ // private final int numErrors; // // /** // * Whether this position should be treated specially, such as whether it // * represents a tranposition, merge, or split. // * @return Whether this position should be treated specially. // */ // public boolean isSpecial() { // return false; // } // } // // Path: src/main/java/com/github/liblevenshtein/transducer/SpecialPosition.java // @ToString(callSuper = true) // @EqualsAndHashCode(callSuper = true) // public class SpecialPosition extends Position implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds a new {@link Position}, extended with some special operation (e.g. // * transposition or merge-and-split). // * @param termIndex Index of the dictionary term represented by this coordinate. // * @param numErrors Number of accumulated errors at this coordinate. // */ // public SpecialPosition(final int termIndex, final int numErrors) { // super(termIndex, numErrors); // } // // /** // * {@inheritDoc} // */ // @Override // public boolean isSpecial() { // return true; // } // } // Path: src/main/java/com/github/liblevenshtein/transducer/factory/PositionFactory.java import java.io.Serializable; import lombok.NoArgsConstructor; import com.github.liblevenshtein.transducer.Position; import com.github.liblevenshtein.transducer.SpecialPosition; package com.github.liblevenshtein.transducer.factory; /** * Builds position vectors for the given algorithm. * @author Dylon Edwards * @since 2.1.0 */ @NoArgsConstructor public class PositionFactory implements Serializable { private static final long serialVersionUID = 1L; /** * Builds a dummy position. * @return Dummy position. */ public Position build() { return new Position(-1, -1); } /** * Builds a position vector for the standard, Levenshtein algorihtm. * @param termIndex Current index of the spelling candidate. * @param numErrors Number of accumulated errors at index {@code termIndex}. * @return New position vector having index {@code termIndex} and error * {@code numErrors}. */ public Position build(final int termIndex, final int numErrors) { return new Position(termIndex, numErrors); } /** * Builds a position vector for the transposition and merge-and-split, * Levenshtein algorihtms. * @param termIndex Current index of the spelling candidate. * @param numErrors Number of accumulated errors at index {@code termIndex}. * @param isSpecial Either {@code 1} or {@code 0}, depending on whether the * position is a special case (numErrors.g. a transposition position). * @return New position vector having index {@code termIndex}, error * {@code numErrors}, and special marker {@code isSpecial}. */ public Position build(final int termIndex, final int numErrors, final boolean isSpecial) { if (isSpecial) {
return new SpecialPosition(termIndex, numErrors);
universal-automata/liblevenshtein-java
src/test/java/com/github/liblevenshtein/assertion/DistanceAssertionsTest.java
// Path: src/main/java/com/github/liblevenshtein/distance/IDistance.java // public interface IDistance<Term> extends Serializable { // // /** // * Finds the distance between two terms, {@code v} and {@code w}. The distance // * between two terms is complemented by their similarity, which is determined // * by subtracting their distance from the maximum distance they may be apart. // * @param v Term to compare with {@code w} // * @param w Term to compare with {@code v} // * @return Distance between {@code v} and {@code w} // */ // int between(Term v, Term w); // } // // Path: src/test/java/com/github/liblevenshtein/assertion/DistanceAssertions.java // public static <Type> DistanceAssertions<Type> assertThat( // final IDistance<Type> actual) { // return new DistanceAssertions<>(actual); // }
import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import com.github.liblevenshtein.distance.IDistance; import static com.github.liblevenshtein.assertion.DistanceAssertions.assertThat;
package com.github.liblevenshtein.assertion; public class DistanceAssertionsTest { private static final String FOO = "foo"; private static final String BAR = "bar"; private static final String BAZ = "baz";
// Path: src/main/java/com/github/liblevenshtein/distance/IDistance.java // public interface IDistance<Term> extends Serializable { // // /** // * Finds the distance between two terms, {@code v} and {@code w}. The distance // * between two terms is complemented by their similarity, which is determined // * by subtracting their distance from the maximum distance they may be apart. // * @param v Term to compare with {@code w} // * @param w Term to compare with {@code v} // * @return Distance between {@code v} and {@code w} // */ // int between(Term v, Term w); // } // // Path: src/test/java/com/github/liblevenshtein/assertion/DistanceAssertions.java // public static <Type> DistanceAssertions<Type> assertThat( // final IDistance<Type> actual) { // return new DistanceAssertions<>(actual); // } // Path: src/test/java/com/github/liblevenshtein/assertion/DistanceAssertionsTest.java import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import com.github.liblevenshtein.distance.IDistance; import static com.github.liblevenshtein.assertion.DistanceAssertions.assertThat; package com.github.liblevenshtein.assertion; public class DistanceAssertionsTest { private static final String FOO = "foo"; private static final String BAR = "bar"; private static final String BAZ = "baz";
private final ThreadLocal<IDistance<String>> distance = new ThreadLocal<>();
universal-automata/liblevenshtein-java
src/test/java/com/github/liblevenshtein/assertion/DistanceAssertionsTest.java
// Path: src/main/java/com/github/liblevenshtein/distance/IDistance.java // public interface IDistance<Term> extends Serializable { // // /** // * Finds the distance between two terms, {@code v} and {@code w}. The distance // * between two terms is complemented by their similarity, which is determined // * by subtracting their distance from the maximum distance they may be apart. // * @param v Term to compare with {@code w} // * @param w Term to compare with {@code v} // * @return Distance between {@code v} and {@code w} // */ // int between(Term v, Term w); // } // // Path: src/test/java/com/github/liblevenshtein/assertion/DistanceAssertions.java // public static <Type> DistanceAssertions<Type> assertThat( // final IDistance<Type> actual) { // return new DistanceAssertions<>(actual); // }
import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import com.github.liblevenshtein.distance.IDistance; import static com.github.liblevenshtein.assertion.DistanceAssertions.assertThat;
package com.github.liblevenshtein.assertion; public class DistanceAssertionsTest { private static final String FOO = "foo"; private static final String BAR = "bar"; private static final String BAZ = "baz"; private final ThreadLocal<IDistance<String>> distance = new ThreadLocal<>(); @BeforeMethod @SuppressWarnings("unchecked") public void setUp() { distance.set(mock(IDistance.class)); } @Test public void testEqualSelfSimilarity() { when(distance.get().between(FOO, FOO)).thenReturn(0); when(distance.get().between(BAR, BAR)).thenReturn(0);
// Path: src/main/java/com/github/liblevenshtein/distance/IDistance.java // public interface IDistance<Term> extends Serializable { // // /** // * Finds the distance between two terms, {@code v} and {@code w}. The distance // * between two terms is complemented by their similarity, which is determined // * by subtracting their distance from the maximum distance they may be apart. // * @param v Term to compare with {@code w} // * @param w Term to compare with {@code v} // * @return Distance between {@code v} and {@code w} // */ // int between(Term v, Term w); // } // // Path: src/test/java/com/github/liblevenshtein/assertion/DistanceAssertions.java // public static <Type> DistanceAssertions<Type> assertThat( // final IDistance<Type> actual) { // return new DistanceAssertions<>(actual); // } // Path: src/test/java/com/github/liblevenshtein/assertion/DistanceAssertionsTest.java import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import com.github.liblevenshtein.distance.IDistance; import static com.github.liblevenshtein.assertion.DistanceAssertions.assertThat; package com.github.liblevenshtein.assertion; public class DistanceAssertionsTest { private static final String FOO = "foo"; private static final String BAR = "bar"; private static final String BAZ = "baz"; private final ThreadLocal<IDistance<String>> distance = new ThreadLocal<>(); @BeforeMethod @SuppressWarnings("unchecked") public void setUp() { distance.set(mock(IDistance.class)); } @Test public void testEqualSelfSimilarity() { when(distance.get().between(FOO, FOO)).thenReturn(0); when(distance.get().between(BAR, BAR)).thenReturn(0);
assertThat(distance.get()).satisfiesEqualSelfSimilarity(FOO, BAR);
universal-automata/liblevenshtein-java
src/integ/java/com/github/liblevenshtein/JDependIntegTest.java
// Path: src/test/java/com/github/liblevenshtein/assertion/IteratorAssertions.java // public static <Type> IteratorAssertions<Type> assertThat( // final Iterator<Type> actual) { // return new IteratorAssertions<>(actual); // }
import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import static org.assertj.core.api.Assertions.assertThat; import jdepend.framework.JDepend; import jdepend.framework.JavaPackage; import lombok.extern.slf4j.Slf4j; import static com.github.liblevenshtein.assertion.IteratorAssertions.assertThat;
package com.github.liblevenshtein; @Slf4j public class JDependIntegTest { private static final String BASE_PACKAGE = "com.github.liblevenshtein"; @SuppressWarnings("unchecked") private static final Set<String> EMPTY_DEPS = (Set<String>) Collections.EMPTY_SET; /** Valid, cyclic dependencies. */ private static final Map<String, Map<String, Set<String>>> VALID_DEPS = buildValidDeps(); @SuppressWarnings("checkstyle:multiplestringliterals") private static Map<String, Map<String, Set<String>>> buildValidDeps() { final Map<String, Set<String>> mainDeps = new ImmutableMap.Builder<String, Set<String>>() .put("com.github.liblevenshtein.transducer", new ImmutableSet.Builder<String>() .add("com.github.liblevenshtein.transducer.factory") .add("com.github.liblevenshtein.transducer") .build()) .put("com.github.liblevenshtein.transducer.factory", new ImmutableSet.Builder<String>() .add("com.github.liblevenshtein.transducer") .add("com.github.liblevenshtein.transducer.factory") .build()) .build(); // In the tests, pretty much every package is cyclic to every other through // their assertions, according to JDepend. In the future, it may be good to // refactor the tests such that their packages are not so coupled. final Set<String> assertionDeps = new ImmutableSet.Builder<String>() .add("com.github.liblevenshtein.assertion") .add("com.github.liblevenshtein.collection.dictionary") .add("com.github.liblevenshtein.collection.dictionary.factory") .add("com.github.liblevenshtein.distance") .add("com.github.liblevenshtein.distance.factory") .add("com.github.liblevenshtein.serialization") .add("com.github.liblevenshtein.transducer") .add("com.github.liblevenshtein.transducer.factory") .build(); final Map<String, Set<String>> testDeps = assertionDeps.stream() .reduce(new ImmutableMap.Builder<String, Set<String>>(), (builder, dep) -> builder.put(dep, assertionDeps), (lhs, rhs) -> lhs).build(); final Map<String, Set<String>> regrDeps = mainDeps; final Map<String, Set<String>> integDeps = mainDeps; return new ImmutableMap.Builder<String, Map<String, Set<String>>>() .put("main", mainDeps) .put("test", testDeps) .put("regr", regrDeps) .put("integ", integDeps) .build(); } @DataProvider(name = "jdependProvider") @SuppressWarnings("checkstyle:multiplestringliterals") public Object[][] jdependProvider() throws IOException { final String[] configs = {"main", "test", "regr", "integ", "task"}; final Object[][] jdepends = new Object[configs.length][2]; for (int i = 0; i < configs.length; i += 1) { final String config = configs[i]; try { final JDepend jdepend = new JDepend(); addConfigDir(jdepend, config); if (!"main".equals(config) && !"task".equals(config)) { addConfigDir(jdepend, "main"); } jdepend.analyze(); jdepends[i][0] = jdepend; jdepends[i][1] = config; } catch (final IOException exception) { log.error("Failed to initialize config [{}]", config, exception); throw exception; } } return jdepends; } private void addConfigDir(final JDepend jdepend, final String config) throws IOException { final String projectDir = System.getProperty("user.dir"); final String classesDir = String.format("%s/build/classes/%s", projectDir, config); jdepend.addDirectory(classesDir); } private Set<String> depsFor(final JavaPackage pkg, final String config) { if (!VALID_DEPS.containsKey(config)) { return EMPTY_DEPS; } final Map<String, Set<String>> validDeps = VALID_DEPS.get(config); if (!validDeps.containsKey(pkg.getName())) { return EMPTY_DEPS; } return validDeps.get(pkg.getName()); } @SuppressWarnings("unchecked") @Test(dataProvider = "jdependProvider") public void testNoUnexpectedCycles(final JDepend jdepend, final String config) { final List<JavaPackage> cycles = new ArrayList<>(); for (final JavaPackage pkg : (Collection<JavaPackage>) jdepend.getPackages()) { if (pkg.getName().startsWith(BASE_PACKAGE) && pkg.collectAllCycles(cycles) && isDirectCycle(cycles)) { final Iterator<JavaPackage> iter = cycles.iterator();
// Path: src/test/java/com/github/liblevenshtein/assertion/IteratorAssertions.java // public static <Type> IteratorAssertions<Type> assertThat( // final Iterator<Type> actual) { // return new IteratorAssertions<>(actual); // } // Path: src/integ/java/com/github/liblevenshtein/JDependIntegTest.java import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import static org.assertj.core.api.Assertions.assertThat; import jdepend.framework.JDepend; import jdepend.framework.JavaPackage; import lombok.extern.slf4j.Slf4j; import static com.github.liblevenshtein.assertion.IteratorAssertions.assertThat; package com.github.liblevenshtein; @Slf4j public class JDependIntegTest { private static final String BASE_PACKAGE = "com.github.liblevenshtein"; @SuppressWarnings("unchecked") private static final Set<String> EMPTY_DEPS = (Set<String>) Collections.EMPTY_SET; /** Valid, cyclic dependencies. */ private static final Map<String, Map<String, Set<String>>> VALID_DEPS = buildValidDeps(); @SuppressWarnings("checkstyle:multiplestringliterals") private static Map<String, Map<String, Set<String>>> buildValidDeps() { final Map<String, Set<String>> mainDeps = new ImmutableMap.Builder<String, Set<String>>() .put("com.github.liblevenshtein.transducer", new ImmutableSet.Builder<String>() .add("com.github.liblevenshtein.transducer.factory") .add("com.github.liblevenshtein.transducer") .build()) .put("com.github.liblevenshtein.transducer.factory", new ImmutableSet.Builder<String>() .add("com.github.liblevenshtein.transducer") .add("com.github.liblevenshtein.transducer.factory") .build()) .build(); // In the tests, pretty much every package is cyclic to every other through // their assertions, according to JDepend. In the future, it may be good to // refactor the tests such that their packages are not so coupled. final Set<String> assertionDeps = new ImmutableSet.Builder<String>() .add("com.github.liblevenshtein.assertion") .add("com.github.liblevenshtein.collection.dictionary") .add("com.github.liblevenshtein.collection.dictionary.factory") .add("com.github.liblevenshtein.distance") .add("com.github.liblevenshtein.distance.factory") .add("com.github.liblevenshtein.serialization") .add("com.github.liblevenshtein.transducer") .add("com.github.liblevenshtein.transducer.factory") .build(); final Map<String, Set<String>> testDeps = assertionDeps.stream() .reduce(new ImmutableMap.Builder<String, Set<String>>(), (builder, dep) -> builder.put(dep, assertionDeps), (lhs, rhs) -> lhs).build(); final Map<String, Set<String>> regrDeps = mainDeps; final Map<String, Set<String>> integDeps = mainDeps; return new ImmutableMap.Builder<String, Map<String, Set<String>>>() .put("main", mainDeps) .put("test", testDeps) .put("regr", regrDeps) .put("integ", integDeps) .build(); } @DataProvider(name = "jdependProvider") @SuppressWarnings("checkstyle:multiplestringliterals") public Object[][] jdependProvider() throws IOException { final String[] configs = {"main", "test", "regr", "integ", "task"}; final Object[][] jdepends = new Object[configs.length][2]; for (int i = 0; i < configs.length; i += 1) { final String config = configs[i]; try { final JDepend jdepend = new JDepend(); addConfigDir(jdepend, config); if (!"main".equals(config) && !"task".equals(config)) { addConfigDir(jdepend, "main"); } jdepend.analyze(); jdepends[i][0] = jdepend; jdepends[i][1] = config; } catch (final IOException exception) { log.error("Failed to initialize config [{}]", config, exception); throw exception; } } return jdepends; } private void addConfigDir(final JDepend jdepend, final String config) throws IOException { final String projectDir = System.getProperty("user.dir"); final String classesDir = String.format("%s/build/classes/%s", projectDir, config); jdepend.addDirectory(classesDir); } private Set<String> depsFor(final JavaPackage pkg, final String config) { if (!VALID_DEPS.containsKey(config)) { return EMPTY_DEPS; } final Map<String, Set<String>> validDeps = VALID_DEPS.get(config); if (!validDeps.containsKey(pkg.getName())) { return EMPTY_DEPS; } return validDeps.get(pkg.getName()); } @SuppressWarnings("unchecked") @Test(dataProvider = "jdependProvider") public void testNoUnexpectedCycles(final JDepend jdepend, final String config) { final List<JavaPackage> cycles = new ArrayList<>(); for (final JavaPackage pkg : (Collection<JavaPackage>) jdepend.getPackages()) { if (pkg.getName().startsWith(BASE_PACKAGE) && pkg.collectAllCycles(cycles) && isDirectCycle(cycles)) { final Iterator<JavaPackage> iter = cycles.iterator();
assertThat(iter).hasNext();
universal-automata/liblevenshtein-java
src/test/java/com/github/liblevenshtein/transducer/StandardPositionComparatorTest.java
// Path: src/test/java/com/github/liblevenshtein/assertion/ComparatorAssertions.java // public static <Type> ComparatorAssertions<Type> assertThat( // final Comparator<Type> actual) { // return new ComparatorAssertions<>(actual); // }
import org.testng.annotations.Test; import static com.github.liblevenshtein.assertion.ComparatorAssertions.assertThat;
package com.github.liblevenshtein.transducer; public class StandardPositionComparatorTest { private final StandardPositionComparator comparator = new StandardPositionComparator(); @Test public void testCompare() {
// Path: src/test/java/com/github/liblevenshtein/assertion/ComparatorAssertions.java // public static <Type> ComparatorAssertions<Type> assertThat( // final Comparator<Type> actual) { // return new ComparatorAssertions<>(actual); // } // Path: src/test/java/com/github/liblevenshtein/transducer/StandardPositionComparatorTest.java import org.testng.annotations.Test; import static com.github.liblevenshtein.assertion.ComparatorAssertions.assertThat; package com.github.liblevenshtein.transducer; public class StandardPositionComparatorTest { private final StandardPositionComparator comparator = new StandardPositionComparator(); @Test public void testCompare() {
assertThat(comparator)
legobmw99/Allomancy
src/main/java/com/legobmw99/allomancy/api/data/IAllomancerData.java
// Path: src/main/java/com/legobmw99/allomancy/api/enums/Metal.java // public enum Metal { // IRON(true), // STEEL, // TIN, // PEWTER, // ZINC, // BRASS, // COPPER(true), // BRONZE, // ALUMINUM, // DURALUMIN, // CHROMIUM, // NICROSIL, // GOLD(true), // ELECTRUM, // CADMIUM, // BENDALLOY; // // // private final boolean vanilla; // // Metal() { // this(false); // } // // Metal(boolean isVanilla) { // this.vanilla = isVanilla; // } // // public static Metal getMetal(int index) { // for (Metal metal : values()) { // if (metal.getIndex() == index) { // return metal; // } // } // throw new IllegalArgumentException("Allomancy: Bad Metal Index"); // } // // public boolean isVanilla() { // return this.vanilla; // } // // public String getName() { // return name().toLowerCase(Locale.ROOT); // } // // public int getIndex() { // return ordinal(); // } // // // }
import com.legobmw99.allomancy.api.enums.Metal; import net.minecraft.core.BlockPos; import net.minecraft.nbt.CompoundTag; import net.minecraft.resources.ResourceKey; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.level.Level;
package com.legobmw99.allomancy.api.data; public interface IAllomancerData { /** * Called each worldTick, checking the burn times, abilities, and metal * amounts. Then syncs to the client to make sure everyone is on the same * page * * @param player the player being checked */ void tickBurning(ServerPlayer player); /** * Get if the player has the supplied power * * @param metal the Metal to check * @return true if this capability has the power specified */
// Path: src/main/java/com/legobmw99/allomancy/api/enums/Metal.java // public enum Metal { // IRON(true), // STEEL, // TIN, // PEWTER, // ZINC, // BRASS, // COPPER(true), // BRONZE, // ALUMINUM, // DURALUMIN, // CHROMIUM, // NICROSIL, // GOLD(true), // ELECTRUM, // CADMIUM, // BENDALLOY; // // // private final boolean vanilla; // // Metal() { // this(false); // } // // Metal(boolean isVanilla) { // this.vanilla = isVanilla; // } // // public static Metal getMetal(int index) { // for (Metal metal : values()) { // if (metal.getIndex() == index) { // return metal; // } // } // throw new IllegalArgumentException("Allomancy: Bad Metal Index"); // } // // public boolean isVanilla() { // return this.vanilla; // } // // public String getName() { // return name().toLowerCase(Locale.ROOT); // } // // public int getIndex() { // return ordinal(); // } // // // } // Path: src/main/java/com/legobmw99/allomancy/api/data/IAllomancerData.java import com.legobmw99.allomancy.api.enums.Metal; import net.minecraft.core.BlockPos; import net.minecraft.nbt.CompoundTag; import net.minecraft.resources.ResourceKey; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.level.Level; package com.legobmw99.allomancy.api.data; public interface IAllomancerData { /** * Called each worldTick, checking the burn times, abilities, and metal * amounts. Then syncs to the client to make sure everyone is on the same * page * * @param player the player being checked */ void tickBurning(ServerPlayer player); /** * Get if the player has the supplied power * * @param metal the Metal to check * @return true if this capability has the power specified */
boolean hasPower(Metal metal);
legobmw99/Allomancy
src/main/java/com/legobmw99/allomancy/modules/powers/data/AllomancerDataProvider.java
// Path: src/main/java/com/legobmw99/allomancy/api/data/IAllomancerData.java // public interface IAllomancerData { // // /** // * Called each worldTick, checking the burn times, abilities, and metal // * amounts. Then syncs to the client to make sure everyone is on the same // * page // * // * @param player the player being checked // */ // void tickBurning(ServerPlayer player); // // /** // * Get if the player has the supplied power // * // * @param metal the Metal to check // * @return true if this capability has the power specified // */ // boolean hasPower(Metal metal); // // /** // * Get the number of powers the player has // * // * @return int between 0 and 16, inclusive // */ // int getPowerCount(); // // /** // * Returns an array of the player's metal abilities // * // * @return array of Metal // */ // Metal[] getPowers(); // // /** // * Sets the player as a Mistborn // */ // void setMistborn(); // // /** // * Check if the player is a Mistborn // * // * @return true if the player has ALL powers // */ // boolean isMistborn(); // // /** // * Check if the player is uninvested // * // * @return true if the player has NO powers // */ // boolean isUninvested(); // // /** // * Sets the player as uninvested // */ // void setUninvested(); // // /** // * Grant this player the given metal power // * // * @param metal the Metal to add // */ // void addPower(Metal metal); // // /** // * Remove the given metal power from this player // * // * @param metal the Metal to remove // */ // void revokePower(Metal metal); // // /** // * Checks if the player is burning the given metal // * // * @param metal the Metal to check // * @return true if the player is burning it // */ // boolean isBurning(Metal metal); // // /** // * Sets the player's burning flag for the given metal // * // * @param metal the Metal to set // * @param metalBurning the value to set it to // */ // void setBurning(Metal metal, boolean metalBurning); // // /** // * Sets the players amount of Metal to the given value // * // * @param metal the Metal to set // * @param amt the amount stored // */ // void setAmount(Metal metal, int amt); // // /** // * Gets the players stored amount of the given metal // * // * @param metal the Metal to check // * @return the amount stored // */ // int getAmount(Metal metal); // // /** // * Drain all specified metals // * // * @param metals all metals to drain // */ // void drainMetals(Metal... metals); // // /** // * Get how much damage has been accumulated // * // * @return the amount of damage // */ // int getDamageStored(); // // /** // * Set the amount of damage stored // * // * @param damageStored the amount of damage // */ // void setDamageStored(int damageStored); // // /** // * Set the death location and dimension // * // * @param pos BlockPos of the death location // * @param dim The RegistryKey representing the dimension the death occurred in // */ // void setDeathLoc(BlockPos pos, ResourceKey<Level> dim); // // void setDeathLoc(BlockPos pos, String dim_name); // // /** // * Returns the location of the most recent player's death, or null // * // * @return BlockPos of player's death, or null // */ // BlockPos getDeathLoc(); // // /** // * Returns the dimension of the most recent player's death, or null // * // * @return RegistryKey corresponding to the dimension, or null // */ // ResourceKey<Level> getDeathDim(); // // /** // * Set the spawn location and dimension // * // * @param pos BlockPos of the spawn point // * @param dim The RegistryKey representing the spawn dimension // */ // void setSpawnLoc(BlockPos pos, ResourceKey<Level> dim); // // void setSpawnLoc(BlockPos pos, String dim_name); // // /** // * Returns the location of the players spawn point if set, or null // * // * @return BlockPos of player's death, or null // */ // BlockPos getSpawnLoc(); // // /** // * Returns the dimension of the most player's spawn point, or null if unset. // * // * @return RegistryKey corresponding to the dimension, or null // */ // ResourceKey<Level> getSpawnDim(); // // void decEnhanced(); // // boolean isEnhanced(); // // void setEnhanced(int time); // // void load(CompoundTag nbt); // // CompoundTag save(); // // }
import com.legobmw99.allomancy.api.data.IAllomancerData; import net.minecraft.core.Direction; import net.minecraft.nbt.CompoundTag; import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.capabilities.ICapabilitySerializable; import net.minecraftforge.common.util.LazyOptional; import javax.annotation.Nonnull; import javax.annotation.Nullable;
package com.legobmw99.allomancy.modules.powers.data; public class AllomancerDataProvider implements ICapabilitySerializable<CompoundTag> { private final DefaultAllomancerData data = new DefaultAllomancerData();
// Path: src/main/java/com/legobmw99/allomancy/api/data/IAllomancerData.java // public interface IAllomancerData { // // /** // * Called each worldTick, checking the burn times, abilities, and metal // * amounts. Then syncs to the client to make sure everyone is on the same // * page // * // * @param player the player being checked // */ // void tickBurning(ServerPlayer player); // // /** // * Get if the player has the supplied power // * // * @param metal the Metal to check // * @return true if this capability has the power specified // */ // boolean hasPower(Metal metal); // // /** // * Get the number of powers the player has // * // * @return int between 0 and 16, inclusive // */ // int getPowerCount(); // // /** // * Returns an array of the player's metal abilities // * // * @return array of Metal // */ // Metal[] getPowers(); // // /** // * Sets the player as a Mistborn // */ // void setMistborn(); // // /** // * Check if the player is a Mistborn // * // * @return true if the player has ALL powers // */ // boolean isMistborn(); // // /** // * Check if the player is uninvested // * // * @return true if the player has NO powers // */ // boolean isUninvested(); // // /** // * Sets the player as uninvested // */ // void setUninvested(); // // /** // * Grant this player the given metal power // * // * @param metal the Metal to add // */ // void addPower(Metal metal); // // /** // * Remove the given metal power from this player // * // * @param metal the Metal to remove // */ // void revokePower(Metal metal); // // /** // * Checks if the player is burning the given metal // * // * @param metal the Metal to check // * @return true if the player is burning it // */ // boolean isBurning(Metal metal); // // /** // * Sets the player's burning flag for the given metal // * // * @param metal the Metal to set // * @param metalBurning the value to set it to // */ // void setBurning(Metal metal, boolean metalBurning); // // /** // * Sets the players amount of Metal to the given value // * // * @param metal the Metal to set // * @param amt the amount stored // */ // void setAmount(Metal metal, int amt); // // /** // * Gets the players stored amount of the given metal // * // * @param metal the Metal to check // * @return the amount stored // */ // int getAmount(Metal metal); // // /** // * Drain all specified metals // * // * @param metals all metals to drain // */ // void drainMetals(Metal... metals); // // /** // * Get how much damage has been accumulated // * // * @return the amount of damage // */ // int getDamageStored(); // // /** // * Set the amount of damage stored // * // * @param damageStored the amount of damage // */ // void setDamageStored(int damageStored); // // /** // * Set the death location and dimension // * // * @param pos BlockPos of the death location // * @param dim The RegistryKey representing the dimension the death occurred in // */ // void setDeathLoc(BlockPos pos, ResourceKey<Level> dim); // // void setDeathLoc(BlockPos pos, String dim_name); // // /** // * Returns the location of the most recent player's death, or null // * // * @return BlockPos of player's death, or null // */ // BlockPos getDeathLoc(); // // /** // * Returns the dimension of the most recent player's death, or null // * // * @return RegistryKey corresponding to the dimension, or null // */ // ResourceKey<Level> getDeathDim(); // // /** // * Set the spawn location and dimension // * // * @param pos BlockPos of the spawn point // * @param dim The RegistryKey representing the spawn dimension // */ // void setSpawnLoc(BlockPos pos, ResourceKey<Level> dim); // // void setSpawnLoc(BlockPos pos, String dim_name); // // /** // * Returns the location of the players spawn point if set, or null // * // * @return BlockPos of player's death, or null // */ // BlockPos getSpawnLoc(); // // /** // * Returns the dimension of the most player's spawn point, or null if unset. // * // * @return RegistryKey corresponding to the dimension, or null // */ // ResourceKey<Level> getSpawnDim(); // // void decEnhanced(); // // boolean isEnhanced(); // // void setEnhanced(int time); // // void load(CompoundTag nbt); // // CompoundTag save(); // // } // Path: src/main/java/com/legobmw99/allomancy/modules/powers/data/AllomancerDataProvider.java import com.legobmw99.allomancy.api.data.IAllomancerData; import net.minecraft.core.Direction; import net.minecraft.nbt.CompoundTag; import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.capabilities.ICapabilitySerializable; import net.minecraftforge.common.util.LazyOptional; import javax.annotation.Nonnull; import javax.annotation.Nullable; package com.legobmw99.allomancy.modules.powers.data; public class AllomancerDataProvider implements ICapabilitySerializable<CompoundTag> { private final DefaultAllomancerData data = new DefaultAllomancerData();
private final LazyOptional<IAllomancerData> dataOptional = LazyOptional.of(() -> this.data);
legobmw99/Allomancy
src/main/java/com/legobmw99/allomancy/datagen/DataGenerators.java
// Path: src/main/java/com/legobmw99/allomancy/Allomancy.java // @Mod(Allomancy.MODID) // public class Allomancy { // // public static final String MODID = "allomancy"; // public static final CreativeModeTab allomancy_group = new CreativeModeTab(MODID) { // @Override // public ItemStack makeIcon() { // return new ItemStack(CombatSetup.MISTCLOAK.get()); // } // }; // // public static final Logger LOGGER = LogManager.getLogger(); // // public static Allomancy instance; // // public Allomancy() { // instance = this; // // Register our setup events on the necessary buses // FMLJavaModLoadingContext.get().getModEventBus().addListener(Allomancy::init); // FMLJavaModLoadingContext.get().getModEventBus().addListener(Allomancy::clientInit); // FMLJavaModLoadingContext.get().getModEventBus().addListener(AllomancyConfig::onLoad); // FMLJavaModLoadingContext.get().getModEventBus().addListener(AllomancyConfig::onReload); // FMLJavaModLoadingContext.get().getModEventBus().addListener(PowersClientSetup::registerParticle); // FMLJavaModLoadingContext.get().getModEventBus().addListener(AllomancerCapability::registerCapability); // FMLJavaModLoadingContext.get().getModEventBus().addListener(CombatClientSetup::registerEntityRenders); // // MinecraftForge.EVENT_BUS.addListener(Allomancy::registerCommands); // MinecraftForge.EVENT_BUS.addListener(EventPriority.HIGH, OreGenerator::registerGeneration); // // // Register all Registries // PowersSetup.register(); // CombatSetup.register(); // ConsumeSetup.register(); // MaterialsSetup.register(); // ExtrasSetup.register(); // // AllomancyConfig.register(); // // } // // public static Item.Properties createStandardItemProperties() { // return new Item.Properties().tab(allomancy_group).stacksTo(64); // } // // public static Item createStandardItem() { // return new Item(createStandardItemProperties()); // } // // // public static MutableComponent addColorToText(String translationKey, ChatFormatting color) { // MutableComponent lore = new TranslatableComponent(translationKey); // return addColor(lore, color); // } // // public static MutableComponent addColorToText(String translationKey, ChatFormatting color, Object... fmting) { // MutableComponent lore = new TranslatableComponent(translationKey, fmting); // return addColor(lore, color); // } // // private static MutableComponent addColor(MutableComponent text, ChatFormatting color) { // text.setStyle(text.getStyle().withColor(TextColor.fromLegacyFormat(color))); // return text; // } // // public static void clientInit(final FMLClientSetupEvent e) { // PowersSetup.clientInit(e); // } // // public static void registerCommands(final RegisterCommandsEvent e) { // PowersSetup.registerCommands(e); // } // // public static void init(final FMLCommonSetupEvent e) { // PowersSetup.init(e); // MaterialsSetup.init(e); // Network.registerPackets(); // } // }
import com.legobmw99.allomancy.Allomancy; import net.minecraft.data.DataGenerator; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.forge.event.lifecycle.GatherDataEvent;
package com.legobmw99.allomancy.datagen; @Mod.EventBusSubscriber(bus = Mod.EventBusSubscriber.Bus.MOD) public class DataGenerators { @SubscribeEvent public static void gatherData(GatherDataEvent event) { DataGenerator generator = event.getGenerator(); if (event.includeServer()) { generator.addProvider(new Recipes(generator)); generator.addProvider(new LootTables(generator));
// Path: src/main/java/com/legobmw99/allomancy/Allomancy.java // @Mod(Allomancy.MODID) // public class Allomancy { // // public static final String MODID = "allomancy"; // public static final CreativeModeTab allomancy_group = new CreativeModeTab(MODID) { // @Override // public ItemStack makeIcon() { // return new ItemStack(CombatSetup.MISTCLOAK.get()); // } // }; // // public static final Logger LOGGER = LogManager.getLogger(); // // public static Allomancy instance; // // public Allomancy() { // instance = this; // // Register our setup events on the necessary buses // FMLJavaModLoadingContext.get().getModEventBus().addListener(Allomancy::init); // FMLJavaModLoadingContext.get().getModEventBus().addListener(Allomancy::clientInit); // FMLJavaModLoadingContext.get().getModEventBus().addListener(AllomancyConfig::onLoad); // FMLJavaModLoadingContext.get().getModEventBus().addListener(AllomancyConfig::onReload); // FMLJavaModLoadingContext.get().getModEventBus().addListener(PowersClientSetup::registerParticle); // FMLJavaModLoadingContext.get().getModEventBus().addListener(AllomancerCapability::registerCapability); // FMLJavaModLoadingContext.get().getModEventBus().addListener(CombatClientSetup::registerEntityRenders); // // MinecraftForge.EVENT_BUS.addListener(Allomancy::registerCommands); // MinecraftForge.EVENT_BUS.addListener(EventPriority.HIGH, OreGenerator::registerGeneration); // // // Register all Registries // PowersSetup.register(); // CombatSetup.register(); // ConsumeSetup.register(); // MaterialsSetup.register(); // ExtrasSetup.register(); // // AllomancyConfig.register(); // // } // // public static Item.Properties createStandardItemProperties() { // return new Item.Properties().tab(allomancy_group).stacksTo(64); // } // // public static Item createStandardItem() { // return new Item(createStandardItemProperties()); // } // // // public static MutableComponent addColorToText(String translationKey, ChatFormatting color) { // MutableComponent lore = new TranslatableComponent(translationKey); // return addColor(lore, color); // } // // public static MutableComponent addColorToText(String translationKey, ChatFormatting color, Object... fmting) { // MutableComponent lore = new TranslatableComponent(translationKey, fmting); // return addColor(lore, color); // } // // private static MutableComponent addColor(MutableComponent text, ChatFormatting color) { // text.setStyle(text.getStyle().withColor(TextColor.fromLegacyFormat(color))); // return text; // } // // public static void clientInit(final FMLClientSetupEvent e) { // PowersSetup.clientInit(e); // } // // public static void registerCommands(final RegisterCommandsEvent e) { // PowersSetup.registerCommands(e); // } // // public static void init(final FMLCommonSetupEvent e) { // PowersSetup.init(e); // MaterialsSetup.init(e); // Network.registerPackets(); // } // } // Path: src/main/java/com/legobmw99/allomancy/datagen/DataGenerators.java import com.legobmw99.allomancy.Allomancy; import net.minecraft.data.DataGenerator; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.forge.event.lifecycle.GatherDataEvent; package com.legobmw99.allomancy.datagen; @Mod.EventBusSubscriber(bus = Mod.EventBusSubscriber.Bus.MOD) public class DataGenerators { @SubscribeEvent public static void gatherData(GatherDataEvent event) { DataGenerator generator = event.getGenerator(); if (event.includeServer()) { generator.addProvider(new Recipes(generator)); generator.addProvider(new LootTables(generator));
BlockTags blocktags = new BlockTags(generator, Allomancy.MODID, event.getExistingFileHelper());
legobmw99/Allomancy
src/main/java/com/legobmw99/allomancy/modules/extras/block/IronButtonBlock.java
// Path: src/main/java/com/legobmw99/allomancy/Allomancy.java // @Mod(Allomancy.MODID) // public class Allomancy { // // public static final String MODID = "allomancy"; // public static final CreativeModeTab allomancy_group = new CreativeModeTab(MODID) { // @Override // public ItemStack makeIcon() { // return new ItemStack(CombatSetup.MISTCLOAK.get()); // } // }; // // public static final Logger LOGGER = LogManager.getLogger(); // // public static Allomancy instance; // // public Allomancy() { // instance = this; // // Register our setup events on the necessary buses // FMLJavaModLoadingContext.get().getModEventBus().addListener(Allomancy::init); // FMLJavaModLoadingContext.get().getModEventBus().addListener(Allomancy::clientInit); // FMLJavaModLoadingContext.get().getModEventBus().addListener(AllomancyConfig::onLoad); // FMLJavaModLoadingContext.get().getModEventBus().addListener(AllomancyConfig::onReload); // FMLJavaModLoadingContext.get().getModEventBus().addListener(PowersClientSetup::registerParticle); // FMLJavaModLoadingContext.get().getModEventBus().addListener(AllomancerCapability::registerCapability); // FMLJavaModLoadingContext.get().getModEventBus().addListener(CombatClientSetup::registerEntityRenders); // // MinecraftForge.EVENT_BUS.addListener(Allomancy::registerCommands); // MinecraftForge.EVENT_BUS.addListener(EventPriority.HIGH, OreGenerator::registerGeneration); // // // Register all Registries // PowersSetup.register(); // CombatSetup.register(); // ConsumeSetup.register(); // MaterialsSetup.register(); // ExtrasSetup.register(); // // AllomancyConfig.register(); // // } // // public static Item.Properties createStandardItemProperties() { // return new Item.Properties().tab(allomancy_group).stacksTo(64); // } // // public static Item createStandardItem() { // return new Item(createStandardItemProperties()); // } // // // public static MutableComponent addColorToText(String translationKey, ChatFormatting color) { // MutableComponent lore = new TranslatableComponent(translationKey); // return addColor(lore, color); // } // // public static MutableComponent addColorToText(String translationKey, ChatFormatting color, Object... fmting) { // MutableComponent lore = new TranslatableComponent(translationKey, fmting); // return addColor(lore, color); // } // // private static MutableComponent addColor(MutableComponent text, ChatFormatting color) { // text.setStyle(text.getStyle().withColor(TextColor.fromLegacyFormat(color))); // return text; // } // // public static void clientInit(final FMLClientSetupEvent e) { // PowersSetup.clientInit(e); // } // // public static void registerCommands(final RegisterCommandsEvent e) { // PowersSetup.registerCommands(e); // } // // public static void init(final FMLCommonSetupEvent e) { // PowersSetup.init(e); // MaterialsSetup.init(e); // Network.registerPackets(); // } // } // // Path: src/main/java/com/legobmw99/allomancy/api/block/IAllomanticallyUsableBlock.java // public interface IAllomanticallyUsableBlock { // // /** // * Called when the block is steelpushed or ironpulled // * // * @param isPush whether the activation is Steel // * @return whether the block was activated // */ // boolean useAllomantically(BlockState state, Level world, BlockPos pos, Player playerIn, boolean isPush); // }
import com.legobmw99.allomancy.Allomancy; import com.legobmw99.allomancy.api.block.IAllomanticallyUsableBlock; import net.minecraft.ChatFormatting; import net.minecraft.core.BlockPos; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.MutableComponent; import net.minecraft.sounds.SoundEvent; import net.minecraft.sounds.SoundEvents; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.TooltipFlag; import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.ButtonBlock; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.material.Material; import net.minecraft.world.phys.BlockHitResult; import javax.annotation.Nullable; import java.util.List;
package com.legobmw99.allomancy.modules.extras.block; public class IronButtonBlock extends ButtonBlock implements IAllomanticallyUsableBlock { public IronButtonBlock() { super(false, Block.Properties.of(Material.METAL).noCollission().strength(1.0F)); } @Override public boolean useAllomantically(BlockState state, Level level, BlockPos pos, Player player, boolean isPush) { if (state.getValue(POWERED) || level.isClientSide) { return true; } else if (isPush) { level.setBlock(pos, state.setValue(POWERED, true), 3); this.playSound(player, level, pos, true); this.updateNeighbors(state, level, pos); level.scheduleTick(pos, this, 20); return true; } else { return false; } } @Override public InteractionResult use(BlockState state, Level worldIn, BlockPos pos, Player player, InteractionHand handIn, BlockHitResult hit) { return InteractionResult.FAIL; } @Override protected SoundEvent getSound(boolean on) { return on ? SoundEvents.METAL_PRESSURE_PLATE_CLICK_ON : SoundEvents.METAL_PRESSURE_PLATE_CLICK_OFF; } @Override public void appendHoverText(ItemStack stack, @Nullable BlockGetter worldIn, List<Component> tooltip, TooltipFlag flagIn) { super.appendHoverText(stack, worldIn, tooltip, flagIn);
// Path: src/main/java/com/legobmw99/allomancy/Allomancy.java // @Mod(Allomancy.MODID) // public class Allomancy { // // public static final String MODID = "allomancy"; // public static final CreativeModeTab allomancy_group = new CreativeModeTab(MODID) { // @Override // public ItemStack makeIcon() { // return new ItemStack(CombatSetup.MISTCLOAK.get()); // } // }; // // public static final Logger LOGGER = LogManager.getLogger(); // // public static Allomancy instance; // // public Allomancy() { // instance = this; // // Register our setup events on the necessary buses // FMLJavaModLoadingContext.get().getModEventBus().addListener(Allomancy::init); // FMLJavaModLoadingContext.get().getModEventBus().addListener(Allomancy::clientInit); // FMLJavaModLoadingContext.get().getModEventBus().addListener(AllomancyConfig::onLoad); // FMLJavaModLoadingContext.get().getModEventBus().addListener(AllomancyConfig::onReload); // FMLJavaModLoadingContext.get().getModEventBus().addListener(PowersClientSetup::registerParticle); // FMLJavaModLoadingContext.get().getModEventBus().addListener(AllomancerCapability::registerCapability); // FMLJavaModLoadingContext.get().getModEventBus().addListener(CombatClientSetup::registerEntityRenders); // // MinecraftForge.EVENT_BUS.addListener(Allomancy::registerCommands); // MinecraftForge.EVENT_BUS.addListener(EventPriority.HIGH, OreGenerator::registerGeneration); // // // Register all Registries // PowersSetup.register(); // CombatSetup.register(); // ConsumeSetup.register(); // MaterialsSetup.register(); // ExtrasSetup.register(); // // AllomancyConfig.register(); // // } // // public static Item.Properties createStandardItemProperties() { // return new Item.Properties().tab(allomancy_group).stacksTo(64); // } // // public static Item createStandardItem() { // return new Item(createStandardItemProperties()); // } // // // public static MutableComponent addColorToText(String translationKey, ChatFormatting color) { // MutableComponent lore = new TranslatableComponent(translationKey); // return addColor(lore, color); // } // // public static MutableComponent addColorToText(String translationKey, ChatFormatting color, Object... fmting) { // MutableComponent lore = new TranslatableComponent(translationKey, fmting); // return addColor(lore, color); // } // // private static MutableComponent addColor(MutableComponent text, ChatFormatting color) { // text.setStyle(text.getStyle().withColor(TextColor.fromLegacyFormat(color))); // return text; // } // // public static void clientInit(final FMLClientSetupEvent e) { // PowersSetup.clientInit(e); // } // // public static void registerCommands(final RegisterCommandsEvent e) { // PowersSetup.registerCommands(e); // } // // public static void init(final FMLCommonSetupEvent e) { // PowersSetup.init(e); // MaterialsSetup.init(e); // Network.registerPackets(); // } // } // // Path: src/main/java/com/legobmw99/allomancy/api/block/IAllomanticallyUsableBlock.java // public interface IAllomanticallyUsableBlock { // // /** // * Called when the block is steelpushed or ironpulled // * // * @param isPush whether the activation is Steel // * @return whether the block was activated // */ // boolean useAllomantically(BlockState state, Level world, BlockPos pos, Player playerIn, boolean isPush); // } // Path: src/main/java/com/legobmw99/allomancy/modules/extras/block/IronButtonBlock.java import com.legobmw99.allomancy.Allomancy; import com.legobmw99.allomancy.api.block.IAllomanticallyUsableBlock; import net.minecraft.ChatFormatting; import net.minecraft.core.BlockPos; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.MutableComponent; import net.minecraft.sounds.SoundEvent; import net.minecraft.sounds.SoundEvents; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.TooltipFlag; import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.ButtonBlock; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.material.Material; import net.minecraft.world.phys.BlockHitResult; import javax.annotation.Nullable; import java.util.List; package com.legobmw99.allomancy.modules.extras.block; public class IronButtonBlock extends ButtonBlock implements IAllomanticallyUsableBlock { public IronButtonBlock() { super(false, Block.Properties.of(Material.METAL).noCollission().strength(1.0F)); } @Override public boolean useAllomantically(BlockState state, Level level, BlockPos pos, Player player, boolean isPush) { if (state.getValue(POWERED) || level.isClientSide) { return true; } else if (isPush) { level.setBlock(pos, state.setValue(POWERED, true), 3); this.playSound(player, level, pos, true); this.updateNeighbors(state, level, pos); level.scheduleTick(pos, this, 20); return true; } else { return false; } } @Override public InteractionResult use(BlockState state, Level worldIn, BlockPos pos, Player player, InteractionHand handIn, BlockHitResult hit) { return InteractionResult.FAIL; } @Override protected SoundEvent getSound(boolean on) { return on ? SoundEvents.METAL_PRESSURE_PLATE_CLICK_ON : SoundEvents.METAL_PRESSURE_PLATE_CLICK_OFF; } @Override public void appendHoverText(ItemStack stack, @Nullable BlockGetter worldIn, List<Component> tooltip, TooltipFlag flagIn) { super.appendHoverText(stack, worldIn, tooltip, flagIn);
MutableComponent lore = Allomancy.addColorToText("block.allomancy.iron_activation.lore", ChatFormatting.GRAY);
legobmw99/Allomancy
src/main/java/com/legobmw99/allomancy/modules/powers/command/AllomancyPowerType.java
// Path: src/main/java/com/legobmw99/allomancy/api/enums/Metal.java // public enum Metal { // IRON(true), // STEEL, // TIN, // PEWTER, // ZINC, // BRASS, // COPPER(true), // BRONZE, // ALUMINUM, // DURALUMIN, // CHROMIUM, // NICROSIL, // GOLD(true), // ELECTRUM, // CADMIUM, // BENDALLOY; // // // private final boolean vanilla; // // Metal() { // this(false); // } // // Metal(boolean isVanilla) { // this.vanilla = isVanilla; // } // // public static Metal getMetal(int index) { // for (Metal metal : values()) { // if (metal.getIndex() == index) { // return metal; // } // } // throw new IllegalArgumentException("Allomancy: Bad Metal Index"); // } // // public boolean isVanilla() { // return this.vanilla; // } // // public String getName() { // return name().toLowerCase(Locale.ROOT); // } // // public int getIndex() { // return ordinal(); // } // // // }
import com.legobmw99.allomancy.api.enums.Metal; import com.mojang.brigadier.StringReader; import com.mojang.brigadier.arguments.ArgumentType; import com.mojang.brigadier.context.CommandContext; import com.mojang.brigadier.exceptions.CommandSyntaxException; import com.mojang.brigadier.exceptions.DynamicCommandExceptionType; import com.mojang.brigadier.suggestion.Suggestions; import com.mojang.brigadier.suggestion.SuggestionsBuilder; import net.minecraft.commands.SharedSuggestionProvider; import net.minecraft.network.chat.TranslatableComponent; import java.util.Arrays; import java.util.Collection; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.stream.Collectors;
package com.legobmw99.allomancy.modules.powers.command; public class AllomancyPowerType implements ArgumentType<String> { public static final AllomancyPowerType INSTANCE = new AllomancyPowerType();
// Path: src/main/java/com/legobmw99/allomancy/api/enums/Metal.java // public enum Metal { // IRON(true), // STEEL, // TIN, // PEWTER, // ZINC, // BRASS, // COPPER(true), // BRONZE, // ALUMINUM, // DURALUMIN, // CHROMIUM, // NICROSIL, // GOLD(true), // ELECTRUM, // CADMIUM, // BENDALLOY; // // // private final boolean vanilla; // // Metal() { // this(false); // } // // Metal(boolean isVanilla) { // this.vanilla = isVanilla; // } // // public static Metal getMetal(int index) { // for (Metal metal : values()) { // if (metal.getIndex() == index) { // return metal; // } // } // throw new IllegalArgumentException("Allomancy: Bad Metal Index"); // } // // public boolean isVanilla() { // return this.vanilla; // } // // public String getName() { // return name().toLowerCase(Locale.ROOT); // } // // public int getIndex() { // return ordinal(); // } // // // } // Path: src/main/java/com/legobmw99/allomancy/modules/powers/command/AllomancyPowerType.java import com.legobmw99.allomancy.api.enums.Metal; import com.mojang.brigadier.StringReader; import com.mojang.brigadier.arguments.ArgumentType; import com.mojang.brigadier.context.CommandContext; import com.mojang.brigadier.exceptions.CommandSyntaxException; import com.mojang.brigadier.exceptions.DynamicCommandExceptionType; import com.mojang.brigadier.suggestion.Suggestions; import com.mojang.brigadier.suggestion.SuggestionsBuilder; import net.minecraft.commands.SharedSuggestionProvider; import net.minecraft.network.chat.TranslatableComponent; import java.util.Arrays; import java.util.Collection; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.stream.Collectors; package com.legobmw99.allomancy.modules.powers.command; public class AllomancyPowerType implements ArgumentType<String> { public static final AllomancyPowerType INSTANCE = new AllomancyPowerType();
private static final Set<String> types = Arrays.stream(Metal.values()).map(Metal::getName).collect(Collectors.toSet());
legobmw99/Allomancy
src/main/java/com/legobmw99/allomancy/modules/combat/item/MistcloakItem.java
// Path: src/main/java/com/legobmw99/allomancy/modules/combat/CombatSetup.java // public class CombatSetup { // public static final DeferredRegister<EntityType<?>> ENTITIES = DeferredRegister.create(ForgeRegistries.ENTITIES, Allomancy.MODID); // public static final DeferredRegister<Item> ITEMS = DeferredRegister.create(ForgeRegistries.ITEMS, Allomancy.MODID); // public static final RegistryObject<CoinBagItem> COIN_BAG = ITEMS.register("coin_bag", CoinBagItem::new); // public static final RegistryObject<ObsidianDaggerItem> OBSIDIAN_DAGGER = ITEMS.register("obsidian_dagger", ObsidianDaggerItem::new); // public static final RegistryObject<KolossBladeItem> KOLOSS_BLADE = ITEMS.register("koloss_blade", KolossBladeItem::new); // public static final ArmorMaterial WoolArmor = new ArmorMaterial() { // @Override // public int getDurabilityForSlot(EquipmentSlot slotIn) { // return 50; // } // // @Override // public int getDefenseForSlot(EquipmentSlot slotIn) { // return slotIn == EquipmentSlot.CHEST ? 4 : 0; // } // // @Override // public int getEnchantmentValue() { // return 15; // } // // @Override // public SoundEvent getEquipSound() { // return SoundEvents.ARMOR_EQUIP_LEATHER; // } // // @Override // public Ingredient getRepairIngredient() { // return Ingredient.of(Items.GRAY_WOOL); // } // // @Override // public String getName() { // return "allomancy:wool"; // } // // @Override // public float getToughness() { // return 0; // } // // @Override // public float getKnockbackResistance() { // return 0; // } // // }; // public static final RegistryObject<MistcloakItem> MISTCLOAK = ITEMS.register("mistcloak", MistcloakItem::new); // public static final RegistryObject<EntityType<ProjectileNuggetEntity>> NUGGET_PROJECTILE = ENTITIES.register("nugget_projectile", () -> EntityType.Builder // .<ProjectileNuggetEntity>of(ProjectileNuggetEntity::new, MobCategory.MISC) // .setShouldReceiveVelocityUpdates(true) // .setUpdateInterval(20) // .setCustomClientFactory((spawnEntity, world) -> new ProjectileNuggetEntity(world, spawnEntity.getEntity())) // .sized(0.25F, 0.25F) // .build("nugget_projectile")); // // public static void register() { // ENTITIES.register(FMLJavaModLoadingContext.get().getModEventBus()); // ITEMS.register(FMLJavaModLoadingContext.get().getModEventBus()); // } // // // }
import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.Multimap; import com.legobmw99.allomancy.modules.combat.CombatSetup; import net.minecraft.world.entity.EquipmentSlot; import net.minecraft.world.entity.ai.attributes.Attribute; import net.minecraft.world.entity.ai.attributes.AttributeModifier; import net.minecraft.world.entity.ai.attributes.Attributes; import net.minecraft.world.item.ArmorItem; import net.minecraft.world.item.CreativeModeTab; import net.minecraft.world.item.Item; import java.util.UUID;
package com.legobmw99.allomancy.modules.combat.item; public class MistcloakItem extends ArmorItem { private static final UUID[] ARMOR_MODIFIERS = new UUID[]{UUID.fromString("845DB27C-C624-495F-8C9F-6020A9A58B6B"), UUID.fromString("D8499B04-0E66-4726-AB29-64469D734E0D"), UUID.fromString("9F3D476D-C118-4544-8365-64846904B48E"), UUID.fromString("2AD3F246-FEE1-4E67-B886-69FD380BB150")}; private final Multimap<Attribute, AttributeModifier> attributes; public MistcloakItem() {
// Path: src/main/java/com/legobmw99/allomancy/modules/combat/CombatSetup.java // public class CombatSetup { // public static final DeferredRegister<EntityType<?>> ENTITIES = DeferredRegister.create(ForgeRegistries.ENTITIES, Allomancy.MODID); // public static final DeferredRegister<Item> ITEMS = DeferredRegister.create(ForgeRegistries.ITEMS, Allomancy.MODID); // public static final RegistryObject<CoinBagItem> COIN_BAG = ITEMS.register("coin_bag", CoinBagItem::new); // public static final RegistryObject<ObsidianDaggerItem> OBSIDIAN_DAGGER = ITEMS.register("obsidian_dagger", ObsidianDaggerItem::new); // public static final RegistryObject<KolossBladeItem> KOLOSS_BLADE = ITEMS.register("koloss_blade", KolossBladeItem::new); // public static final ArmorMaterial WoolArmor = new ArmorMaterial() { // @Override // public int getDurabilityForSlot(EquipmentSlot slotIn) { // return 50; // } // // @Override // public int getDefenseForSlot(EquipmentSlot slotIn) { // return slotIn == EquipmentSlot.CHEST ? 4 : 0; // } // // @Override // public int getEnchantmentValue() { // return 15; // } // // @Override // public SoundEvent getEquipSound() { // return SoundEvents.ARMOR_EQUIP_LEATHER; // } // // @Override // public Ingredient getRepairIngredient() { // return Ingredient.of(Items.GRAY_WOOL); // } // // @Override // public String getName() { // return "allomancy:wool"; // } // // @Override // public float getToughness() { // return 0; // } // // @Override // public float getKnockbackResistance() { // return 0; // } // // }; // public static final RegistryObject<MistcloakItem> MISTCLOAK = ITEMS.register("mistcloak", MistcloakItem::new); // public static final RegistryObject<EntityType<ProjectileNuggetEntity>> NUGGET_PROJECTILE = ENTITIES.register("nugget_projectile", () -> EntityType.Builder // .<ProjectileNuggetEntity>of(ProjectileNuggetEntity::new, MobCategory.MISC) // .setShouldReceiveVelocityUpdates(true) // .setUpdateInterval(20) // .setCustomClientFactory((spawnEntity, world) -> new ProjectileNuggetEntity(world, spawnEntity.getEntity())) // .sized(0.25F, 0.25F) // .build("nugget_projectile")); // // public static void register() { // ENTITIES.register(FMLJavaModLoadingContext.get().getModEventBus()); // ITEMS.register(FMLJavaModLoadingContext.get().getModEventBus()); // } // // // } // Path: src/main/java/com/legobmw99/allomancy/modules/combat/item/MistcloakItem.java import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.Multimap; import com.legobmw99.allomancy.modules.combat.CombatSetup; import net.minecraft.world.entity.EquipmentSlot; import net.minecraft.world.entity.ai.attributes.Attribute; import net.minecraft.world.entity.ai.attributes.AttributeModifier; import net.minecraft.world.entity.ai.attributes.Attributes; import net.minecraft.world.item.ArmorItem; import net.minecraft.world.item.CreativeModeTab; import net.minecraft.world.item.Item; import java.util.UUID; package com.legobmw99.allomancy.modules.combat.item; public class MistcloakItem extends ArmorItem { private static final UUID[] ARMOR_MODIFIERS = new UUID[]{UUID.fromString("845DB27C-C624-495F-8C9F-6020A9A58B6B"), UUID.fromString("D8499B04-0E66-4726-AB29-64469D734E0D"), UUID.fromString("9F3D476D-C118-4544-8365-64846904B48E"), UUID.fromString("2AD3F246-FEE1-4E67-B886-69FD380BB150")}; private final Multimap<Attribute, AttributeModifier> attributes; public MistcloakItem() {
super(CombatSetup.WoolArmor, EquipmentSlot.CHEST, new Item.Properties().tab(CreativeModeTab.TAB_COMBAT));
legobmw99/Allomancy
src/main/java/com/legobmw99/allomancy/modules/consumables/item/GrinderItem.java
// Path: src/main/java/com/legobmw99/allomancy/Allomancy.java // @Mod(Allomancy.MODID) // public class Allomancy { // // public static final String MODID = "allomancy"; // public static final CreativeModeTab allomancy_group = new CreativeModeTab(MODID) { // @Override // public ItemStack makeIcon() { // return new ItemStack(CombatSetup.MISTCLOAK.get()); // } // }; // // public static final Logger LOGGER = LogManager.getLogger(); // // public static Allomancy instance; // // public Allomancy() { // instance = this; // // Register our setup events on the necessary buses // FMLJavaModLoadingContext.get().getModEventBus().addListener(Allomancy::init); // FMLJavaModLoadingContext.get().getModEventBus().addListener(Allomancy::clientInit); // FMLJavaModLoadingContext.get().getModEventBus().addListener(AllomancyConfig::onLoad); // FMLJavaModLoadingContext.get().getModEventBus().addListener(AllomancyConfig::onReload); // FMLJavaModLoadingContext.get().getModEventBus().addListener(PowersClientSetup::registerParticle); // FMLJavaModLoadingContext.get().getModEventBus().addListener(AllomancerCapability::registerCapability); // FMLJavaModLoadingContext.get().getModEventBus().addListener(CombatClientSetup::registerEntityRenders); // // MinecraftForge.EVENT_BUS.addListener(Allomancy::registerCommands); // MinecraftForge.EVENT_BUS.addListener(EventPriority.HIGH, OreGenerator::registerGeneration); // // // Register all Registries // PowersSetup.register(); // CombatSetup.register(); // ConsumeSetup.register(); // MaterialsSetup.register(); // ExtrasSetup.register(); // // AllomancyConfig.register(); // // } // // public static Item.Properties createStandardItemProperties() { // return new Item.Properties().tab(allomancy_group).stacksTo(64); // } // // public static Item createStandardItem() { // return new Item(createStandardItemProperties()); // } // // // public static MutableComponent addColorToText(String translationKey, ChatFormatting color) { // MutableComponent lore = new TranslatableComponent(translationKey); // return addColor(lore, color); // } // // public static MutableComponent addColorToText(String translationKey, ChatFormatting color, Object... fmting) { // MutableComponent lore = new TranslatableComponent(translationKey, fmting); // return addColor(lore, color); // } // // private static MutableComponent addColor(MutableComponent text, ChatFormatting color) { // text.setStyle(text.getStyle().withColor(TextColor.fromLegacyFormat(color))); // return text; // } // // public static void clientInit(final FMLClientSetupEvent e) { // PowersSetup.clientInit(e); // } // // public static void registerCommands(final RegisterCommandsEvent e) { // PowersSetup.registerCommands(e); // } // // public static void init(final FMLCommonSetupEvent e) { // PowersSetup.init(e); // MaterialsSetup.init(e); // Network.registerPackets(); // } // }
import com.legobmw99.allomancy.Allomancy; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack;
package com.legobmw99.allomancy.modules.consumables.item; public class GrinderItem extends Item { public GrinderItem() {
// Path: src/main/java/com/legobmw99/allomancy/Allomancy.java // @Mod(Allomancy.MODID) // public class Allomancy { // // public static final String MODID = "allomancy"; // public static final CreativeModeTab allomancy_group = new CreativeModeTab(MODID) { // @Override // public ItemStack makeIcon() { // return new ItemStack(CombatSetup.MISTCLOAK.get()); // } // }; // // public static final Logger LOGGER = LogManager.getLogger(); // // public static Allomancy instance; // // public Allomancy() { // instance = this; // // Register our setup events on the necessary buses // FMLJavaModLoadingContext.get().getModEventBus().addListener(Allomancy::init); // FMLJavaModLoadingContext.get().getModEventBus().addListener(Allomancy::clientInit); // FMLJavaModLoadingContext.get().getModEventBus().addListener(AllomancyConfig::onLoad); // FMLJavaModLoadingContext.get().getModEventBus().addListener(AllomancyConfig::onReload); // FMLJavaModLoadingContext.get().getModEventBus().addListener(PowersClientSetup::registerParticle); // FMLJavaModLoadingContext.get().getModEventBus().addListener(AllomancerCapability::registerCapability); // FMLJavaModLoadingContext.get().getModEventBus().addListener(CombatClientSetup::registerEntityRenders); // // MinecraftForge.EVENT_BUS.addListener(Allomancy::registerCommands); // MinecraftForge.EVENT_BUS.addListener(EventPriority.HIGH, OreGenerator::registerGeneration); // // // Register all Registries // PowersSetup.register(); // CombatSetup.register(); // ConsumeSetup.register(); // MaterialsSetup.register(); // ExtrasSetup.register(); // // AllomancyConfig.register(); // // } // // public static Item.Properties createStandardItemProperties() { // return new Item.Properties().tab(allomancy_group).stacksTo(64); // } // // public static Item createStandardItem() { // return new Item(createStandardItemProperties()); // } // // // public static MutableComponent addColorToText(String translationKey, ChatFormatting color) { // MutableComponent lore = new TranslatableComponent(translationKey); // return addColor(lore, color); // } // // public static MutableComponent addColorToText(String translationKey, ChatFormatting color, Object... fmting) { // MutableComponent lore = new TranslatableComponent(translationKey, fmting); // return addColor(lore, color); // } // // private static MutableComponent addColor(MutableComponent text, ChatFormatting color) { // text.setStyle(text.getStyle().withColor(TextColor.fromLegacyFormat(color))); // return text; // } // // public static void clientInit(final FMLClientSetupEvent e) { // PowersSetup.clientInit(e); // } // // public static void registerCommands(final RegisterCommandsEvent e) { // PowersSetup.registerCommands(e); // } // // public static void init(final FMLCommonSetupEvent e) { // PowersSetup.init(e); // MaterialsSetup.init(e); // Network.registerPackets(); // } // } // Path: src/main/java/com/legobmw99/allomancy/modules/consumables/item/GrinderItem.java import com.legobmw99.allomancy.Allomancy; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; package com.legobmw99.allomancy.modules.consumables.item; public class GrinderItem extends Item { public GrinderItem() {
super(Allomancy.createStandardItemProperties().setNoRepair().defaultDurability(256));
legobmw99/Allomancy
src/main/java/com/legobmw99/allomancy/integration/AllomancyTooltip.java
// Path: src/main/java/com/legobmw99/allomancy/api/enums/Metal.java // public enum Metal { // IRON(true), // STEEL, // TIN, // PEWTER, // ZINC, // BRASS, // COPPER(true), // BRONZE, // ALUMINUM, // DURALUMIN, // CHROMIUM, // NICROSIL, // GOLD(true), // ELECTRUM, // CADMIUM, // BENDALLOY; // // // private final boolean vanilla; // // Metal() { // this(false); // } // // Metal(boolean isVanilla) { // this.vanilla = isVanilla; // } // // public static Metal getMetal(int index) { // for (Metal metal : values()) { // if (metal.getIndex() == index) { // return metal; // } // } // throw new IllegalArgumentException("Allomancy: Bad Metal Index"); // } // // public boolean isVanilla() { // return this.vanilla; // } // // public String getName() { // return name().toLowerCase(Locale.ROOT); // } // // public int getIndex() { // return ordinal(); // } // // // } // // Path: src/main/java/com/legobmw99/allomancy/modules/powers/data/AllomancerCapability.java // public class AllomancerCapability { // // public static final Capability<IAllomancerData> PLAYER_CAP = CapabilityManager.get(new CapabilityToken<>() { // }); // // public static final ResourceLocation IDENTIFIER = new ResourceLocation(Allomancy.MODID, "allomancy_data"); // // public static void registerCapability(final RegisterCapabilitiesEvent event) { // event.register(IAllomancerData.class); // } // // }
import com.legobmw99.allomancy.api.enums.Metal; import com.legobmw99.allomancy.modules.powers.data.AllomancerCapability; import mcp.mobius.waila.api.IEntityAccessor; import mcp.mobius.waila.api.IEntityComponentProvider; import mcp.mobius.waila.api.IPluginConfig; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.MutableComponent; import net.minecraft.network.chat.TranslatableComponent; import java.util.List;
package com.legobmw99.allomancy.integration; public class AllomancyTooltip implements IEntityComponentProvider { static final AllomancyTooltip INSTANCE = new AllomancyTooltip();
// Path: src/main/java/com/legobmw99/allomancy/api/enums/Metal.java // public enum Metal { // IRON(true), // STEEL, // TIN, // PEWTER, // ZINC, // BRASS, // COPPER(true), // BRONZE, // ALUMINUM, // DURALUMIN, // CHROMIUM, // NICROSIL, // GOLD(true), // ELECTRUM, // CADMIUM, // BENDALLOY; // // // private final boolean vanilla; // // Metal() { // this(false); // } // // Metal(boolean isVanilla) { // this.vanilla = isVanilla; // } // // public static Metal getMetal(int index) { // for (Metal metal : values()) { // if (metal.getIndex() == index) { // return metal; // } // } // throw new IllegalArgumentException("Allomancy: Bad Metal Index"); // } // // public boolean isVanilla() { // return this.vanilla; // } // // public String getName() { // return name().toLowerCase(Locale.ROOT); // } // // public int getIndex() { // return ordinal(); // } // // // } // // Path: src/main/java/com/legobmw99/allomancy/modules/powers/data/AllomancerCapability.java // public class AllomancerCapability { // // public static final Capability<IAllomancerData> PLAYER_CAP = CapabilityManager.get(new CapabilityToken<>() { // }); // // public static final ResourceLocation IDENTIFIER = new ResourceLocation(Allomancy.MODID, "allomancy_data"); // // public static void registerCapability(final RegisterCapabilitiesEvent event) { // event.register(IAllomancerData.class); // } // // } // Path: src/main/java/com/legobmw99/allomancy/integration/AllomancyTooltip.java import com.legobmw99.allomancy.api.enums.Metal; import com.legobmw99.allomancy.modules.powers.data.AllomancerCapability; import mcp.mobius.waila.api.IEntityAccessor; import mcp.mobius.waila.api.IEntityComponentProvider; import mcp.mobius.waila.api.IPluginConfig; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.MutableComponent; import net.minecraft.network.chat.TranslatableComponent; import java.util.List; package com.legobmw99.allomancy.integration; public class AllomancyTooltip implements IEntityComponentProvider { static final AllomancyTooltip INSTANCE = new AllomancyTooltip();
private static TranslatableComponent translateMetal(Metal mt) {
legobmw99/Allomancy
src/main/java/com/legobmw99/allomancy/integration/AllomancyTooltip.java
// Path: src/main/java/com/legobmw99/allomancy/api/enums/Metal.java // public enum Metal { // IRON(true), // STEEL, // TIN, // PEWTER, // ZINC, // BRASS, // COPPER(true), // BRONZE, // ALUMINUM, // DURALUMIN, // CHROMIUM, // NICROSIL, // GOLD(true), // ELECTRUM, // CADMIUM, // BENDALLOY; // // // private final boolean vanilla; // // Metal() { // this(false); // } // // Metal(boolean isVanilla) { // this.vanilla = isVanilla; // } // // public static Metal getMetal(int index) { // for (Metal metal : values()) { // if (metal.getIndex() == index) { // return metal; // } // } // throw new IllegalArgumentException("Allomancy: Bad Metal Index"); // } // // public boolean isVanilla() { // return this.vanilla; // } // // public String getName() { // return name().toLowerCase(Locale.ROOT); // } // // public int getIndex() { // return ordinal(); // } // // // } // // Path: src/main/java/com/legobmw99/allomancy/modules/powers/data/AllomancerCapability.java // public class AllomancerCapability { // // public static final Capability<IAllomancerData> PLAYER_CAP = CapabilityManager.get(new CapabilityToken<>() { // }); // // public static final ResourceLocation IDENTIFIER = new ResourceLocation(Allomancy.MODID, "allomancy_data"); // // public static void registerCapability(final RegisterCapabilitiesEvent event) { // event.register(IAllomancerData.class); // } // // }
import com.legobmw99.allomancy.api.enums.Metal; import com.legobmw99.allomancy.modules.powers.data.AllomancerCapability; import mcp.mobius.waila.api.IEntityAccessor; import mcp.mobius.waila.api.IEntityComponentProvider; import mcp.mobius.waila.api.IPluginConfig; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.MutableComponent; import net.minecraft.network.chat.TranslatableComponent; import java.util.List;
package com.legobmw99.allomancy.integration; public class AllomancyTooltip implements IEntityComponentProvider { static final AllomancyTooltip INSTANCE = new AllomancyTooltip(); private static TranslatableComponent translateMetal(Metal mt) { return new TranslatableComponent("metals." + mt.getName().toLowerCase()); } @Override public void appendBody(List<Component> tooltip, IEntityAccessor accessor, IPluginConfig config) {
// Path: src/main/java/com/legobmw99/allomancy/api/enums/Metal.java // public enum Metal { // IRON(true), // STEEL, // TIN, // PEWTER, // ZINC, // BRASS, // COPPER(true), // BRONZE, // ALUMINUM, // DURALUMIN, // CHROMIUM, // NICROSIL, // GOLD(true), // ELECTRUM, // CADMIUM, // BENDALLOY; // // // private final boolean vanilla; // // Metal() { // this(false); // } // // Metal(boolean isVanilla) { // this.vanilla = isVanilla; // } // // public static Metal getMetal(int index) { // for (Metal metal : values()) { // if (metal.getIndex() == index) { // return metal; // } // } // throw new IllegalArgumentException("Allomancy: Bad Metal Index"); // } // // public boolean isVanilla() { // return this.vanilla; // } // // public String getName() { // return name().toLowerCase(Locale.ROOT); // } // // public int getIndex() { // return ordinal(); // } // // // } // // Path: src/main/java/com/legobmw99/allomancy/modules/powers/data/AllomancerCapability.java // public class AllomancerCapability { // // public static final Capability<IAllomancerData> PLAYER_CAP = CapabilityManager.get(new CapabilityToken<>() { // }); // // public static final ResourceLocation IDENTIFIER = new ResourceLocation(Allomancy.MODID, "allomancy_data"); // // public static void registerCapability(final RegisterCapabilitiesEvent event) { // event.register(IAllomancerData.class); // } // // } // Path: src/main/java/com/legobmw99/allomancy/integration/AllomancyTooltip.java import com.legobmw99.allomancy.api.enums.Metal; import com.legobmw99.allomancy.modules.powers.data.AllomancerCapability; import mcp.mobius.waila.api.IEntityAccessor; import mcp.mobius.waila.api.IEntityComponentProvider; import mcp.mobius.waila.api.IPluginConfig; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.MutableComponent; import net.minecraft.network.chat.TranslatableComponent; import java.util.List; package com.legobmw99.allomancy.integration; public class AllomancyTooltip implements IEntityComponentProvider { static final AllomancyTooltip INSTANCE = new AllomancyTooltip(); private static TranslatableComponent translateMetal(Metal mt) { return new TranslatableComponent("metals." + mt.getName().toLowerCase()); } @Override public void appendBody(List<Component> tooltip, IEntityAccessor accessor, IPluginConfig config) {
accessor.getPlayer().getCapability(AllomancerCapability.PLAYER_CAP).ifPresent(cap -> {
legobmw99/Allomancy
src/main/java/com/legobmw99/allomancy/modules/combat/client/CombatClientSetup.java
// Path: src/main/java/com/legobmw99/allomancy/modules/combat/CombatSetup.java // public class CombatSetup { // public static final DeferredRegister<EntityType<?>> ENTITIES = DeferredRegister.create(ForgeRegistries.ENTITIES, Allomancy.MODID); // public static final DeferredRegister<Item> ITEMS = DeferredRegister.create(ForgeRegistries.ITEMS, Allomancy.MODID); // public static final RegistryObject<CoinBagItem> COIN_BAG = ITEMS.register("coin_bag", CoinBagItem::new); // public static final RegistryObject<ObsidianDaggerItem> OBSIDIAN_DAGGER = ITEMS.register("obsidian_dagger", ObsidianDaggerItem::new); // public static final RegistryObject<KolossBladeItem> KOLOSS_BLADE = ITEMS.register("koloss_blade", KolossBladeItem::new); // public static final ArmorMaterial WoolArmor = new ArmorMaterial() { // @Override // public int getDurabilityForSlot(EquipmentSlot slotIn) { // return 50; // } // // @Override // public int getDefenseForSlot(EquipmentSlot slotIn) { // return slotIn == EquipmentSlot.CHEST ? 4 : 0; // } // // @Override // public int getEnchantmentValue() { // return 15; // } // // @Override // public SoundEvent getEquipSound() { // return SoundEvents.ARMOR_EQUIP_LEATHER; // } // // @Override // public Ingredient getRepairIngredient() { // return Ingredient.of(Items.GRAY_WOOL); // } // // @Override // public String getName() { // return "allomancy:wool"; // } // // @Override // public float getToughness() { // return 0; // } // // @Override // public float getKnockbackResistance() { // return 0; // } // // }; // public static final RegistryObject<MistcloakItem> MISTCLOAK = ITEMS.register("mistcloak", MistcloakItem::new); // public static final RegistryObject<EntityType<ProjectileNuggetEntity>> NUGGET_PROJECTILE = ENTITIES.register("nugget_projectile", () -> EntityType.Builder // .<ProjectileNuggetEntity>of(ProjectileNuggetEntity::new, MobCategory.MISC) // .setShouldReceiveVelocityUpdates(true) // .setUpdateInterval(20) // .setCustomClientFactory((spawnEntity, world) -> new ProjectileNuggetEntity(world, spawnEntity.getEntity())) // .sized(0.25F, 0.25F) // .build("nugget_projectile")); // // public static void register() { // ENTITIES.register(FMLJavaModLoadingContext.get().getModEventBus()); // ITEMS.register(FMLJavaModLoadingContext.get().getModEventBus()); // } // // // }
import com.legobmw99.allomancy.modules.combat.CombatSetup; import net.minecraft.client.renderer.entity.ThrownItemRenderer; import net.minecraftforge.client.event.EntityRenderersEvent;
package com.legobmw99.allomancy.modules.combat.client; public class CombatClientSetup { public static void registerEntityRenders(final EntityRenderersEvent.RegisterRenderers e) {
// Path: src/main/java/com/legobmw99/allomancy/modules/combat/CombatSetup.java // public class CombatSetup { // public static final DeferredRegister<EntityType<?>> ENTITIES = DeferredRegister.create(ForgeRegistries.ENTITIES, Allomancy.MODID); // public static final DeferredRegister<Item> ITEMS = DeferredRegister.create(ForgeRegistries.ITEMS, Allomancy.MODID); // public static final RegistryObject<CoinBagItem> COIN_BAG = ITEMS.register("coin_bag", CoinBagItem::new); // public static final RegistryObject<ObsidianDaggerItem> OBSIDIAN_DAGGER = ITEMS.register("obsidian_dagger", ObsidianDaggerItem::new); // public static final RegistryObject<KolossBladeItem> KOLOSS_BLADE = ITEMS.register("koloss_blade", KolossBladeItem::new); // public static final ArmorMaterial WoolArmor = new ArmorMaterial() { // @Override // public int getDurabilityForSlot(EquipmentSlot slotIn) { // return 50; // } // // @Override // public int getDefenseForSlot(EquipmentSlot slotIn) { // return slotIn == EquipmentSlot.CHEST ? 4 : 0; // } // // @Override // public int getEnchantmentValue() { // return 15; // } // // @Override // public SoundEvent getEquipSound() { // return SoundEvents.ARMOR_EQUIP_LEATHER; // } // // @Override // public Ingredient getRepairIngredient() { // return Ingredient.of(Items.GRAY_WOOL); // } // // @Override // public String getName() { // return "allomancy:wool"; // } // // @Override // public float getToughness() { // return 0; // } // // @Override // public float getKnockbackResistance() { // return 0; // } // // }; // public static final RegistryObject<MistcloakItem> MISTCLOAK = ITEMS.register("mistcloak", MistcloakItem::new); // public static final RegistryObject<EntityType<ProjectileNuggetEntity>> NUGGET_PROJECTILE = ENTITIES.register("nugget_projectile", () -> EntityType.Builder // .<ProjectileNuggetEntity>of(ProjectileNuggetEntity::new, MobCategory.MISC) // .setShouldReceiveVelocityUpdates(true) // .setUpdateInterval(20) // .setCustomClientFactory((spawnEntity, world) -> new ProjectileNuggetEntity(world, spawnEntity.getEntity())) // .sized(0.25F, 0.25F) // .build("nugget_projectile")); // // public static void register() { // ENTITIES.register(FMLJavaModLoadingContext.get().getModEventBus()); // ITEMS.register(FMLJavaModLoadingContext.get().getModEventBus()); // } // // // } // Path: src/main/java/com/legobmw99/allomancy/modules/combat/client/CombatClientSetup.java import com.legobmw99.allomancy.modules.combat.CombatSetup; import net.minecraft.client.renderer.entity.ThrownItemRenderer; import net.minecraftforge.client.event.EntityRenderersEvent; package com.legobmw99.allomancy.modules.combat.client; public class CombatClientSetup { public static void registerEntityRenders(final EntityRenderersEvent.RegisterRenderers e) {
e.registerEntityRenderer(CombatSetup.NUGGET_PROJECTILE.get(), ThrownItemRenderer::new);
legobmw99/Allomancy
src/main/java/com/legobmw99/allomancy/modules/powers/network/UpdateBurnPacket.java
// Path: src/main/java/com/legobmw99/allomancy/api/enums/Metal.java // public enum Metal { // IRON(true), // STEEL, // TIN, // PEWTER, // ZINC, // BRASS, // COPPER(true), // BRONZE, // ALUMINUM, // DURALUMIN, // CHROMIUM, // NICROSIL, // GOLD(true), // ELECTRUM, // CADMIUM, // BENDALLOY; // // // private final boolean vanilla; // // Metal() { // this(false); // } // // Metal(boolean isVanilla) { // this.vanilla = isVanilla; // } // // public static Metal getMetal(int index) { // for (Metal metal : values()) { // if (metal.getIndex() == index) { // return metal; // } // } // throw new IllegalArgumentException("Allomancy: Bad Metal Index"); // } // // public boolean isVanilla() { // return this.vanilla; // } // // public String getName() { // return name().toLowerCase(Locale.ROOT); // } // // public int getIndex() { // return ordinal(); // } // // // } // // Path: src/main/java/com/legobmw99/allomancy/modules/powers/data/AllomancerCapability.java // public class AllomancerCapability { // // public static final Capability<IAllomancerData> PLAYER_CAP = CapabilityManager.get(new CapabilityToken<>() { // }); // // public static final ResourceLocation IDENTIFIER = new ResourceLocation(Allomancy.MODID, "allomancy_data"); // // public static void registerCapability(final RegisterCapabilitiesEvent event) { // event.register(IAllomancerData.class); // } // // } // // Path: src/main/java/com/legobmw99/allomancy/network/Network.java // public class Network { // // private static final String VERSION = "1.1"; // public static final SimpleChannel INSTANCE = NetworkRegistry.newSimpleChannel(new ResourceLocation(Allomancy.MODID, "networking"), () -> VERSION, VERSION::equals, // VERSION::equals); // // private static int index = 0; // // private static int nextIndex() { // return index++; // } // // public static void registerPackets() { // INSTANCE.registerMessage(nextIndex(), AllomancerDataPacket.class, AllomancerDataPacket::encode, AllomancerDataPacket::decode, AllomancerDataPacket::handle); // INSTANCE.registerMessage(nextIndex(), UpdateBurnPacket.class, UpdateBurnPacket::encode, UpdateBurnPacket::decode, UpdateBurnPacket::handle); // INSTANCE.registerMessage(nextIndex(), ChangeEmotionPacket.class, ChangeEmotionPacket::encode, ChangeEmotionPacket::decode, ChangeEmotionPacket::handle); // INSTANCE.registerMessage(nextIndex(), TryPushPullEntity.class, TryPushPullEntity::encode, TryPushPullEntity::decode, TryPushPullEntity::handle); // INSTANCE.registerMessage(nextIndex(), TryPushPullBlock.class, TryPushPullBlock::encode, TryPushPullBlock::decode, TryPushPullBlock::handle); // INSTANCE.registerMessage(nextIndex(), UpdateEnhancedPacket.class, UpdateEnhancedPacket::encode, UpdateEnhancedPacket::decode, UpdateEnhancedPacket::handle); // } // // public static void sendToServer(Object msg) { // INSTANCE.sendToServer(msg); // } // // public static void sendTo(Object msg, ServerPlayer player) { // if (!(player instanceof FakePlayer)) { // INSTANCE.sendTo(msg, player.connection.getConnection(), NetworkDirection.PLAY_TO_CLIENT); // } // } // // public static void sendTo(Object msg, PacketDistributor.PacketTarget target) { // INSTANCE.send(target, msg); // } // // public static void sync(Player player) { // player.getCapability(AllomancerCapability.PLAYER_CAP).ifPresent(data -> sync(data, player)); // } // // public static void sync(IAllomancerData cap, Player player) { // sync(new AllomancerDataPacket(cap, player), player); // } // // public static void sync(Object msg, Player player) { // sendTo(msg, PacketDistributor.TRACKING_ENTITY_AND_SELF.with(() -> player)); // } // // }
import com.legobmw99.allomancy.api.enums.Metal; import com.legobmw99.allomancy.modules.powers.data.AllomancerCapability; import com.legobmw99.allomancy.network.Network; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.server.level.ServerPlayer; import net.minecraftforge.network.NetworkEvent; import java.util.Arrays; import java.util.function.Supplier;
package com.legobmw99.allomancy.modules.powers.network; public class UpdateBurnPacket { private final Metal mt; private final boolean value; /** * Send request to the server to change the burning state of a metal * * @param mt the metal * @param value whether it is burning */ public UpdateBurnPacket(Metal mt, boolean value) { this.mt = mt; this.value = value; // Convert bool to int } public static UpdateBurnPacket decode(FriendlyByteBuf buf) { return new UpdateBurnPacket(buf.readEnum(Metal.class), buf.readBoolean()); } public void encode(FriendlyByteBuf buf) { buf.writeEnum(this.mt); buf.writeBoolean(this.value); } public void handle(Supplier<NetworkEvent.Context> ctx) { ctx.get().enqueueWork(() -> { ServerPlayer player = ctx.get().getSender();
// Path: src/main/java/com/legobmw99/allomancy/api/enums/Metal.java // public enum Metal { // IRON(true), // STEEL, // TIN, // PEWTER, // ZINC, // BRASS, // COPPER(true), // BRONZE, // ALUMINUM, // DURALUMIN, // CHROMIUM, // NICROSIL, // GOLD(true), // ELECTRUM, // CADMIUM, // BENDALLOY; // // // private final boolean vanilla; // // Metal() { // this(false); // } // // Metal(boolean isVanilla) { // this.vanilla = isVanilla; // } // // public static Metal getMetal(int index) { // for (Metal metal : values()) { // if (metal.getIndex() == index) { // return metal; // } // } // throw new IllegalArgumentException("Allomancy: Bad Metal Index"); // } // // public boolean isVanilla() { // return this.vanilla; // } // // public String getName() { // return name().toLowerCase(Locale.ROOT); // } // // public int getIndex() { // return ordinal(); // } // // // } // // Path: src/main/java/com/legobmw99/allomancy/modules/powers/data/AllomancerCapability.java // public class AllomancerCapability { // // public static final Capability<IAllomancerData> PLAYER_CAP = CapabilityManager.get(new CapabilityToken<>() { // }); // // public static final ResourceLocation IDENTIFIER = new ResourceLocation(Allomancy.MODID, "allomancy_data"); // // public static void registerCapability(final RegisterCapabilitiesEvent event) { // event.register(IAllomancerData.class); // } // // } // // Path: src/main/java/com/legobmw99/allomancy/network/Network.java // public class Network { // // private static final String VERSION = "1.1"; // public static final SimpleChannel INSTANCE = NetworkRegistry.newSimpleChannel(new ResourceLocation(Allomancy.MODID, "networking"), () -> VERSION, VERSION::equals, // VERSION::equals); // // private static int index = 0; // // private static int nextIndex() { // return index++; // } // // public static void registerPackets() { // INSTANCE.registerMessage(nextIndex(), AllomancerDataPacket.class, AllomancerDataPacket::encode, AllomancerDataPacket::decode, AllomancerDataPacket::handle); // INSTANCE.registerMessage(nextIndex(), UpdateBurnPacket.class, UpdateBurnPacket::encode, UpdateBurnPacket::decode, UpdateBurnPacket::handle); // INSTANCE.registerMessage(nextIndex(), ChangeEmotionPacket.class, ChangeEmotionPacket::encode, ChangeEmotionPacket::decode, ChangeEmotionPacket::handle); // INSTANCE.registerMessage(nextIndex(), TryPushPullEntity.class, TryPushPullEntity::encode, TryPushPullEntity::decode, TryPushPullEntity::handle); // INSTANCE.registerMessage(nextIndex(), TryPushPullBlock.class, TryPushPullBlock::encode, TryPushPullBlock::decode, TryPushPullBlock::handle); // INSTANCE.registerMessage(nextIndex(), UpdateEnhancedPacket.class, UpdateEnhancedPacket::encode, UpdateEnhancedPacket::decode, UpdateEnhancedPacket::handle); // } // // public static void sendToServer(Object msg) { // INSTANCE.sendToServer(msg); // } // // public static void sendTo(Object msg, ServerPlayer player) { // if (!(player instanceof FakePlayer)) { // INSTANCE.sendTo(msg, player.connection.getConnection(), NetworkDirection.PLAY_TO_CLIENT); // } // } // // public static void sendTo(Object msg, PacketDistributor.PacketTarget target) { // INSTANCE.send(target, msg); // } // // public static void sync(Player player) { // player.getCapability(AllomancerCapability.PLAYER_CAP).ifPresent(data -> sync(data, player)); // } // // public static void sync(IAllomancerData cap, Player player) { // sync(new AllomancerDataPacket(cap, player), player); // } // // public static void sync(Object msg, Player player) { // sendTo(msg, PacketDistributor.TRACKING_ENTITY_AND_SELF.with(() -> player)); // } // // } // Path: src/main/java/com/legobmw99/allomancy/modules/powers/network/UpdateBurnPacket.java import com.legobmw99.allomancy.api.enums.Metal; import com.legobmw99.allomancy.modules.powers.data.AllomancerCapability; import com.legobmw99.allomancy.network.Network; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.server.level.ServerPlayer; import net.minecraftforge.network.NetworkEvent; import java.util.Arrays; import java.util.function.Supplier; package com.legobmw99.allomancy.modules.powers.network; public class UpdateBurnPacket { private final Metal mt; private final boolean value; /** * Send request to the server to change the burning state of a metal * * @param mt the metal * @param value whether it is burning */ public UpdateBurnPacket(Metal mt, boolean value) { this.mt = mt; this.value = value; // Convert bool to int } public static UpdateBurnPacket decode(FriendlyByteBuf buf) { return new UpdateBurnPacket(buf.readEnum(Metal.class), buf.readBoolean()); } public void encode(FriendlyByteBuf buf) { buf.writeEnum(this.mt); buf.writeBoolean(this.value); } public void handle(Supplier<NetworkEvent.Context> ctx) { ctx.get().enqueueWork(() -> { ServerPlayer player = ctx.get().getSender();
player.getCapability(AllomancerCapability.PLAYER_CAP).ifPresent(data -> {
legobmw99/Allomancy
src/main/java/com/legobmw99/allomancy/modules/powers/network/UpdateBurnPacket.java
// Path: src/main/java/com/legobmw99/allomancy/api/enums/Metal.java // public enum Metal { // IRON(true), // STEEL, // TIN, // PEWTER, // ZINC, // BRASS, // COPPER(true), // BRONZE, // ALUMINUM, // DURALUMIN, // CHROMIUM, // NICROSIL, // GOLD(true), // ELECTRUM, // CADMIUM, // BENDALLOY; // // // private final boolean vanilla; // // Metal() { // this(false); // } // // Metal(boolean isVanilla) { // this.vanilla = isVanilla; // } // // public static Metal getMetal(int index) { // for (Metal metal : values()) { // if (metal.getIndex() == index) { // return metal; // } // } // throw new IllegalArgumentException("Allomancy: Bad Metal Index"); // } // // public boolean isVanilla() { // return this.vanilla; // } // // public String getName() { // return name().toLowerCase(Locale.ROOT); // } // // public int getIndex() { // return ordinal(); // } // // // } // // Path: src/main/java/com/legobmw99/allomancy/modules/powers/data/AllomancerCapability.java // public class AllomancerCapability { // // public static final Capability<IAllomancerData> PLAYER_CAP = CapabilityManager.get(new CapabilityToken<>() { // }); // // public static final ResourceLocation IDENTIFIER = new ResourceLocation(Allomancy.MODID, "allomancy_data"); // // public static void registerCapability(final RegisterCapabilitiesEvent event) { // event.register(IAllomancerData.class); // } // // } // // Path: src/main/java/com/legobmw99/allomancy/network/Network.java // public class Network { // // private static final String VERSION = "1.1"; // public static final SimpleChannel INSTANCE = NetworkRegistry.newSimpleChannel(new ResourceLocation(Allomancy.MODID, "networking"), () -> VERSION, VERSION::equals, // VERSION::equals); // // private static int index = 0; // // private static int nextIndex() { // return index++; // } // // public static void registerPackets() { // INSTANCE.registerMessage(nextIndex(), AllomancerDataPacket.class, AllomancerDataPacket::encode, AllomancerDataPacket::decode, AllomancerDataPacket::handle); // INSTANCE.registerMessage(nextIndex(), UpdateBurnPacket.class, UpdateBurnPacket::encode, UpdateBurnPacket::decode, UpdateBurnPacket::handle); // INSTANCE.registerMessage(nextIndex(), ChangeEmotionPacket.class, ChangeEmotionPacket::encode, ChangeEmotionPacket::decode, ChangeEmotionPacket::handle); // INSTANCE.registerMessage(nextIndex(), TryPushPullEntity.class, TryPushPullEntity::encode, TryPushPullEntity::decode, TryPushPullEntity::handle); // INSTANCE.registerMessage(nextIndex(), TryPushPullBlock.class, TryPushPullBlock::encode, TryPushPullBlock::decode, TryPushPullBlock::handle); // INSTANCE.registerMessage(nextIndex(), UpdateEnhancedPacket.class, UpdateEnhancedPacket::encode, UpdateEnhancedPacket::decode, UpdateEnhancedPacket::handle); // } // // public static void sendToServer(Object msg) { // INSTANCE.sendToServer(msg); // } // // public static void sendTo(Object msg, ServerPlayer player) { // if (!(player instanceof FakePlayer)) { // INSTANCE.sendTo(msg, player.connection.getConnection(), NetworkDirection.PLAY_TO_CLIENT); // } // } // // public static void sendTo(Object msg, PacketDistributor.PacketTarget target) { // INSTANCE.send(target, msg); // } // // public static void sync(Player player) { // player.getCapability(AllomancerCapability.PLAYER_CAP).ifPresent(data -> sync(data, player)); // } // // public static void sync(IAllomancerData cap, Player player) { // sync(new AllomancerDataPacket(cap, player), player); // } // // public static void sync(Object msg, Player player) { // sendTo(msg, PacketDistributor.TRACKING_ENTITY_AND_SELF.with(() -> player)); // } // // }
import com.legobmw99.allomancy.api.enums.Metal; import com.legobmw99.allomancy.modules.powers.data.AllomancerCapability; import com.legobmw99.allomancy.network.Network; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.server.level.ServerPlayer; import net.minecraftforge.network.NetworkEvent; import java.util.Arrays; import java.util.function.Supplier;
package com.legobmw99.allomancy.modules.powers.network; public class UpdateBurnPacket { private final Metal mt; private final boolean value; /** * Send request to the server to change the burning state of a metal * * @param mt the metal * @param value whether it is burning */ public UpdateBurnPacket(Metal mt, boolean value) { this.mt = mt; this.value = value; // Convert bool to int } public static UpdateBurnPacket decode(FriendlyByteBuf buf) { return new UpdateBurnPacket(buf.readEnum(Metal.class), buf.readBoolean()); } public void encode(FriendlyByteBuf buf) { buf.writeEnum(this.mt); buf.writeBoolean(this.value); } public void handle(Supplier<NetworkEvent.Context> ctx) { ctx.get().enqueueWork(() -> { ServerPlayer player = ctx.get().getSender(); player.getCapability(AllomancerCapability.PLAYER_CAP).ifPresent(data -> { if (data.hasPower(this.mt) && data.getAmount(this.mt) > 0) { data.setBurning(this.mt, this.value); if (!this.value && this.mt == Metal.DURALUMIN) { data.drainMetals(Arrays.stream(Metal.values()).filter(data::isBurning).toArray(Metal[]::new)); } if (!this.value && data.isEnhanced()) { data.drainMetals(this.mt); } } else { data.setBurning(this.mt, false); }
// Path: src/main/java/com/legobmw99/allomancy/api/enums/Metal.java // public enum Metal { // IRON(true), // STEEL, // TIN, // PEWTER, // ZINC, // BRASS, // COPPER(true), // BRONZE, // ALUMINUM, // DURALUMIN, // CHROMIUM, // NICROSIL, // GOLD(true), // ELECTRUM, // CADMIUM, // BENDALLOY; // // // private final boolean vanilla; // // Metal() { // this(false); // } // // Metal(boolean isVanilla) { // this.vanilla = isVanilla; // } // // public static Metal getMetal(int index) { // for (Metal metal : values()) { // if (metal.getIndex() == index) { // return metal; // } // } // throw new IllegalArgumentException("Allomancy: Bad Metal Index"); // } // // public boolean isVanilla() { // return this.vanilla; // } // // public String getName() { // return name().toLowerCase(Locale.ROOT); // } // // public int getIndex() { // return ordinal(); // } // // // } // // Path: src/main/java/com/legobmw99/allomancy/modules/powers/data/AllomancerCapability.java // public class AllomancerCapability { // // public static final Capability<IAllomancerData> PLAYER_CAP = CapabilityManager.get(new CapabilityToken<>() { // }); // // public static final ResourceLocation IDENTIFIER = new ResourceLocation(Allomancy.MODID, "allomancy_data"); // // public static void registerCapability(final RegisterCapabilitiesEvent event) { // event.register(IAllomancerData.class); // } // // } // // Path: src/main/java/com/legobmw99/allomancy/network/Network.java // public class Network { // // private static final String VERSION = "1.1"; // public static final SimpleChannel INSTANCE = NetworkRegistry.newSimpleChannel(new ResourceLocation(Allomancy.MODID, "networking"), () -> VERSION, VERSION::equals, // VERSION::equals); // // private static int index = 0; // // private static int nextIndex() { // return index++; // } // // public static void registerPackets() { // INSTANCE.registerMessage(nextIndex(), AllomancerDataPacket.class, AllomancerDataPacket::encode, AllomancerDataPacket::decode, AllomancerDataPacket::handle); // INSTANCE.registerMessage(nextIndex(), UpdateBurnPacket.class, UpdateBurnPacket::encode, UpdateBurnPacket::decode, UpdateBurnPacket::handle); // INSTANCE.registerMessage(nextIndex(), ChangeEmotionPacket.class, ChangeEmotionPacket::encode, ChangeEmotionPacket::decode, ChangeEmotionPacket::handle); // INSTANCE.registerMessage(nextIndex(), TryPushPullEntity.class, TryPushPullEntity::encode, TryPushPullEntity::decode, TryPushPullEntity::handle); // INSTANCE.registerMessage(nextIndex(), TryPushPullBlock.class, TryPushPullBlock::encode, TryPushPullBlock::decode, TryPushPullBlock::handle); // INSTANCE.registerMessage(nextIndex(), UpdateEnhancedPacket.class, UpdateEnhancedPacket::encode, UpdateEnhancedPacket::decode, UpdateEnhancedPacket::handle); // } // // public static void sendToServer(Object msg) { // INSTANCE.sendToServer(msg); // } // // public static void sendTo(Object msg, ServerPlayer player) { // if (!(player instanceof FakePlayer)) { // INSTANCE.sendTo(msg, player.connection.getConnection(), NetworkDirection.PLAY_TO_CLIENT); // } // } // // public static void sendTo(Object msg, PacketDistributor.PacketTarget target) { // INSTANCE.send(target, msg); // } // // public static void sync(Player player) { // player.getCapability(AllomancerCapability.PLAYER_CAP).ifPresent(data -> sync(data, player)); // } // // public static void sync(IAllomancerData cap, Player player) { // sync(new AllomancerDataPacket(cap, player), player); // } // // public static void sync(Object msg, Player player) { // sendTo(msg, PacketDistributor.TRACKING_ENTITY_AND_SELF.with(() -> player)); // } // // } // Path: src/main/java/com/legobmw99/allomancy/modules/powers/network/UpdateBurnPacket.java import com.legobmw99.allomancy.api.enums.Metal; import com.legobmw99.allomancy.modules.powers.data.AllomancerCapability; import com.legobmw99.allomancy.network.Network; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.server.level.ServerPlayer; import net.minecraftforge.network.NetworkEvent; import java.util.Arrays; import java.util.function.Supplier; package com.legobmw99.allomancy.modules.powers.network; public class UpdateBurnPacket { private final Metal mt; private final boolean value; /** * Send request to the server to change the burning state of a metal * * @param mt the metal * @param value whether it is burning */ public UpdateBurnPacket(Metal mt, boolean value) { this.mt = mt; this.value = value; // Convert bool to int } public static UpdateBurnPacket decode(FriendlyByteBuf buf) { return new UpdateBurnPacket(buf.readEnum(Metal.class), buf.readBoolean()); } public void encode(FriendlyByteBuf buf) { buf.writeEnum(this.mt); buf.writeBoolean(this.value); } public void handle(Supplier<NetworkEvent.Context> ctx) { ctx.get().enqueueWork(() -> { ServerPlayer player = ctx.get().getSender(); player.getCapability(AllomancerCapability.PLAYER_CAP).ifPresent(data -> { if (data.hasPower(this.mt) && data.getAmount(this.mt) > 0) { data.setBurning(this.mt, this.value); if (!this.value && this.mt == Metal.DURALUMIN) { data.drainMetals(Arrays.stream(Metal.values()).filter(data::isBurning).toArray(Metal[]::new)); } if (!this.value && data.isEnhanced()) { data.drainMetals(this.mt); } } else { data.setBurning(this.mt, false); }
Network.sync(data, player);
legobmw99/Allomancy
src/main/java/com/legobmw99/allomancy/modules/powers/client/particle/SoundParticleData.java
// Path: src/main/java/com/legobmw99/allomancy/modules/powers/client/PowersClientSetup.java // public class PowersClientSetup { // public static final DeferredRegister<ParticleType<?>> PARTICLES = DeferredRegister.create(ForgeRegistries.PARTICLE_TYPES, Allomancy.MODID); // public static final RegistryObject<ParticleType<SoundParticleData>> SOUND_PARTICLE_TYPE = PARTICLES.register("sound_particle", // () -> new ParticleType<>(true, SoundParticleData.DESERIALIZER) { // @Override // public Codec<SoundParticleData> codec() { // return null; // } // }); // @OnlyIn(Dist.CLIENT) // public static KeyMapping hud; // // @OnlyIn(Dist.CLIENT) // public static KeyMapping burn; // // public static boolean enable_more_keybinds; // // @OnlyIn(Dist.CLIENT) // public static KeyMapping[] powers; // // public static void initKeyBindings() { // burn = new KeyMapping("key.burn", GLFW.GLFW_KEY_V, "key.categories.allomancy"); // hud = new KeyMapping("key.hud", GLFW.GLFW_KEY_UNKNOWN, "key.categories.allomancy"); // ClientRegistry.registerKeyBinding(burn); // ClientRegistry.registerKeyBinding(hud); // // enable_more_keybinds = PowersConfig.enable_more_keybinds.get(); // // if (enable_more_keybinds) { // powers = new KeyMapping[Metal.values().length]; // for (int i = 0; i < powers.length; i++) { // powers[i] = new KeyMapping("metals." + Metal.getMetal(i).name().toLowerCase(), GLFW.GLFW_KEY_UNKNOWN, "key.categories.allomancy"); // ClientRegistry.registerKeyBinding(powers[i]); // } // } // // } // // public static void register() { // PARTICLES.register(FMLJavaModLoadingContext.get().getModEventBus()); // } // // @SubscribeEvent(priority = EventPriority.LOWEST) // public static void registerParticle(ParticleFactoryRegisterEvent event) { // Allomancy.LOGGER.info("Allomancy: Registering custom particles"); // Minecraft.getInstance().particleEngine.register(PowersClientSetup.SOUND_PARTICLE_TYPE.get(), SoundParticle.Factory::new); // } // // }
import com.legobmw99.allomancy.modules.powers.client.PowersClientSetup; import com.mojang.brigadier.StringReader; import net.minecraft.core.Registry; import net.minecraft.core.particles.ParticleOptions; import net.minecraft.core.particles.ParticleType; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.sounds.SoundSource;
package com.legobmw99.allomancy.modules.powers.client.particle; public class SoundParticleData implements ParticleOptions { public static final ParticleOptions.Deserializer<SoundParticleData> DESERIALIZER = new ParticleOptions.Deserializer<>() { @Override public SoundParticleData fromCommand(ParticleType<SoundParticleData> particleTypeIn, StringReader reader) { return new SoundParticleData(SoundSource.AMBIENT); } @Override public SoundParticleData fromNetwork(ParticleType<SoundParticleData> particleTypeIn, FriendlyByteBuf buffer) { return new SoundParticleData(buffer.readEnum(SoundSource.class)); } }; private final SoundSource type; public SoundParticleData(SoundSource type) { this.type = type; } protected SoundSource getSoundType() { return this.type; } @Override public ParticleType<?> getType() {
// Path: src/main/java/com/legobmw99/allomancy/modules/powers/client/PowersClientSetup.java // public class PowersClientSetup { // public static final DeferredRegister<ParticleType<?>> PARTICLES = DeferredRegister.create(ForgeRegistries.PARTICLE_TYPES, Allomancy.MODID); // public static final RegistryObject<ParticleType<SoundParticleData>> SOUND_PARTICLE_TYPE = PARTICLES.register("sound_particle", // () -> new ParticleType<>(true, SoundParticleData.DESERIALIZER) { // @Override // public Codec<SoundParticleData> codec() { // return null; // } // }); // @OnlyIn(Dist.CLIENT) // public static KeyMapping hud; // // @OnlyIn(Dist.CLIENT) // public static KeyMapping burn; // // public static boolean enable_more_keybinds; // // @OnlyIn(Dist.CLIENT) // public static KeyMapping[] powers; // // public static void initKeyBindings() { // burn = new KeyMapping("key.burn", GLFW.GLFW_KEY_V, "key.categories.allomancy"); // hud = new KeyMapping("key.hud", GLFW.GLFW_KEY_UNKNOWN, "key.categories.allomancy"); // ClientRegistry.registerKeyBinding(burn); // ClientRegistry.registerKeyBinding(hud); // // enable_more_keybinds = PowersConfig.enable_more_keybinds.get(); // // if (enable_more_keybinds) { // powers = new KeyMapping[Metal.values().length]; // for (int i = 0; i < powers.length; i++) { // powers[i] = new KeyMapping("metals." + Metal.getMetal(i).name().toLowerCase(), GLFW.GLFW_KEY_UNKNOWN, "key.categories.allomancy"); // ClientRegistry.registerKeyBinding(powers[i]); // } // } // // } // // public static void register() { // PARTICLES.register(FMLJavaModLoadingContext.get().getModEventBus()); // } // // @SubscribeEvent(priority = EventPriority.LOWEST) // public static void registerParticle(ParticleFactoryRegisterEvent event) { // Allomancy.LOGGER.info("Allomancy: Registering custom particles"); // Minecraft.getInstance().particleEngine.register(PowersClientSetup.SOUND_PARTICLE_TYPE.get(), SoundParticle.Factory::new); // } // // } // Path: src/main/java/com/legobmw99/allomancy/modules/powers/client/particle/SoundParticleData.java import com.legobmw99.allomancy.modules.powers.client.PowersClientSetup; import com.mojang.brigadier.StringReader; import net.minecraft.core.Registry; import net.minecraft.core.particles.ParticleOptions; import net.minecraft.core.particles.ParticleType; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.sounds.SoundSource; package com.legobmw99.allomancy.modules.powers.client.particle; public class SoundParticleData implements ParticleOptions { public static final ParticleOptions.Deserializer<SoundParticleData> DESERIALIZER = new ParticleOptions.Deserializer<>() { @Override public SoundParticleData fromCommand(ParticleType<SoundParticleData> particleTypeIn, StringReader reader) { return new SoundParticleData(SoundSource.AMBIENT); } @Override public SoundParticleData fromNetwork(ParticleType<SoundParticleData> particleTypeIn, FriendlyByteBuf buffer) { return new SoundParticleData(buffer.readEnum(SoundSource.class)); } }; private final SoundSource type; public SoundParticleData(SoundSource type) { this.type = type; } protected SoundSource getSoundType() { return this.type; } @Override public ParticleType<?> getType() {
return PowersClientSetup.SOUND_PARTICLE_TYPE.get();
legobmw99/Allomancy
src/main/java/com/legobmw99/allomancy/modules/combat/entity/ProjectileNuggetEntity.java
// Path: src/main/java/com/legobmw99/allomancy/modules/combat/CombatSetup.java // public class CombatSetup { // public static final DeferredRegister<EntityType<?>> ENTITIES = DeferredRegister.create(ForgeRegistries.ENTITIES, Allomancy.MODID); // public static final DeferredRegister<Item> ITEMS = DeferredRegister.create(ForgeRegistries.ITEMS, Allomancy.MODID); // public static final RegistryObject<CoinBagItem> COIN_BAG = ITEMS.register("coin_bag", CoinBagItem::new); // public static final RegistryObject<ObsidianDaggerItem> OBSIDIAN_DAGGER = ITEMS.register("obsidian_dagger", ObsidianDaggerItem::new); // public static final RegistryObject<KolossBladeItem> KOLOSS_BLADE = ITEMS.register("koloss_blade", KolossBladeItem::new); // public static final ArmorMaterial WoolArmor = new ArmorMaterial() { // @Override // public int getDurabilityForSlot(EquipmentSlot slotIn) { // return 50; // } // // @Override // public int getDefenseForSlot(EquipmentSlot slotIn) { // return slotIn == EquipmentSlot.CHEST ? 4 : 0; // } // // @Override // public int getEnchantmentValue() { // return 15; // } // // @Override // public SoundEvent getEquipSound() { // return SoundEvents.ARMOR_EQUIP_LEATHER; // } // // @Override // public Ingredient getRepairIngredient() { // return Ingredient.of(Items.GRAY_WOOL); // } // // @Override // public String getName() { // return "allomancy:wool"; // } // // @Override // public float getToughness() { // return 0; // } // // @Override // public float getKnockbackResistance() { // return 0; // } // // }; // public static final RegistryObject<MistcloakItem> MISTCLOAK = ITEMS.register("mistcloak", MistcloakItem::new); // public static final RegistryObject<EntityType<ProjectileNuggetEntity>> NUGGET_PROJECTILE = ENTITIES.register("nugget_projectile", () -> EntityType.Builder // .<ProjectileNuggetEntity>of(ProjectileNuggetEntity::new, MobCategory.MISC) // .setShouldReceiveVelocityUpdates(true) // .setUpdateInterval(20) // .setCustomClientFactory((spawnEntity, world) -> new ProjectileNuggetEntity(world, spawnEntity.getEntity())) // .sized(0.25F, 0.25F) // .build("nugget_projectile")); // // public static void register() { // ENTITIES.register(FMLJavaModLoadingContext.get().getModEventBus()); // ITEMS.register(FMLJavaModLoadingContext.get().getModEventBus()); // } // // // }
import com.legobmw99.allomancy.modules.combat.CombatSetup; import net.minecraft.network.protocol.Packet; import net.minecraft.network.syncher.EntityDataAccessor; import net.minecraft.network.syncher.EntityDataSerializers; import net.minecraft.network.syncher.SynchedEntityData; import net.minecraft.world.damagesource.DamageSource; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.item.ItemEntity; import net.minecraft.world.entity.player.Player; import net.minecraft.world.entity.projectile.ItemSupplier; import net.minecraft.world.entity.projectile.ThrowableItemProjectile; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; import net.minecraft.world.level.GameRules; import net.minecraft.world.level.Level; import net.minecraft.world.phys.EntityHitResult; import net.minecraft.world.phys.HitResult; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.network.NetworkHooks;
package com.legobmw99.allomancy.modules.combat.entity; @OnlyIn(value = Dist.CLIENT, _interface = ItemSupplier.class) public class ProjectileNuggetEntity extends ThrowableItemProjectile implements ItemSupplier { private static final EntityDataAccessor<ItemStack> ITEM = SynchedEntityData.defineId(ProjectileNuggetEntity.class, EntityDataSerializers.ITEM_STACK); private float damage; private boolean dropItem = true; public ProjectileNuggetEntity(double x, double y, double z, Level worldIn, ItemStack itemIn, float damageIn) {
// Path: src/main/java/com/legobmw99/allomancy/modules/combat/CombatSetup.java // public class CombatSetup { // public static final DeferredRegister<EntityType<?>> ENTITIES = DeferredRegister.create(ForgeRegistries.ENTITIES, Allomancy.MODID); // public static final DeferredRegister<Item> ITEMS = DeferredRegister.create(ForgeRegistries.ITEMS, Allomancy.MODID); // public static final RegistryObject<CoinBagItem> COIN_BAG = ITEMS.register("coin_bag", CoinBagItem::new); // public static final RegistryObject<ObsidianDaggerItem> OBSIDIAN_DAGGER = ITEMS.register("obsidian_dagger", ObsidianDaggerItem::new); // public static final RegistryObject<KolossBladeItem> KOLOSS_BLADE = ITEMS.register("koloss_blade", KolossBladeItem::new); // public static final ArmorMaterial WoolArmor = new ArmorMaterial() { // @Override // public int getDurabilityForSlot(EquipmentSlot slotIn) { // return 50; // } // // @Override // public int getDefenseForSlot(EquipmentSlot slotIn) { // return slotIn == EquipmentSlot.CHEST ? 4 : 0; // } // // @Override // public int getEnchantmentValue() { // return 15; // } // // @Override // public SoundEvent getEquipSound() { // return SoundEvents.ARMOR_EQUIP_LEATHER; // } // // @Override // public Ingredient getRepairIngredient() { // return Ingredient.of(Items.GRAY_WOOL); // } // // @Override // public String getName() { // return "allomancy:wool"; // } // // @Override // public float getToughness() { // return 0; // } // // @Override // public float getKnockbackResistance() { // return 0; // } // // }; // public static final RegistryObject<MistcloakItem> MISTCLOAK = ITEMS.register("mistcloak", MistcloakItem::new); // public static final RegistryObject<EntityType<ProjectileNuggetEntity>> NUGGET_PROJECTILE = ENTITIES.register("nugget_projectile", () -> EntityType.Builder // .<ProjectileNuggetEntity>of(ProjectileNuggetEntity::new, MobCategory.MISC) // .setShouldReceiveVelocityUpdates(true) // .setUpdateInterval(20) // .setCustomClientFactory((spawnEntity, world) -> new ProjectileNuggetEntity(world, spawnEntity.getEntity())) // .sized(0.25F, 0.25F) // .build("nugget_projectile")); // // public static void register() { // ENTITIES.register(FMLJavaModLoadingContext.get().getModEventBus()); // ITEMS.register(FMLJavaModLoadingContext.get().getModEventBus()); // } // // // } // Path: src/main/java/com/legobmw99/allomancy/modules/combat/entity/ProjectileNuggetEntity.java import com.legobmw99.allomancy.modules.combat.CombatSetup; import net.minecraft.network.protocol.Packet; import net.minecraft.network.syncher.EntityDataAccessor; import net.minecraft.network.syncher.EntityDataSerializers; import net.minecraft.network.syncher.SynchedEntityData; import net.minecraft.world.damagesource.DamageSource; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.item.ItemEntity; import net.minecraft.world.entity.player.Player; import net.minecraft.world.entity.projectile.ItemSupplier; import net.minecraft.world.entity.projectile.ThrowableItemProjectile; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; import net.minecraft.world.level.GameRules; import net.minecraft.world.level.Level; import net.minecraft.world.phys.EntityHitResult; import net.minecraft.world.phys.HitResult; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.network.NetworkHooks; package com.legobmw99.allomancy.modules.combat.entity; @OnlyIn(value = Dist.CLIENT, _interface = ItemSupplier.class) public class ProjectileNuggetEntity extends ThrowableItemProjectile implements ItemSupplier { private static final EntityDataAccessor<ItemStack> ITEM = SynchedEntityData.defineId(ProjectileNuggetEntity.class, EntityDataSerializers.ITEM_STACK); private float damage; private boolean dropItem = true; public ProjectileNuggetEntity(double x, double y, double z, Level worldIn, ItemStack itemIn, float damageIn) {
super(CombatSetup.NUGGET_PROJECTILE.get(), x, y, z, worldIn);
legobmw99/Allomancy
src/main/java/com/legobmw99/allomancy/modules/powers/network/AllomancerDataPacket.java
// Path: src/main/java/com/legobmw99/allomancy/api/data/IAllomancerData.java // public interface IAllomancerData { // // /** // * Called each worldTick, checking the burn times, abilities, and metal // * amounts. Then syncs to the client to make sure everyone is on the same // * page // * // * @param player the player being checked // */ // void tickBurning(ServerPlayer player); // // /** // * Get if the player has the supplied power // * // * @param metal the Metal to check // * @return true if this capability has the power specified // */ // boolean hasPower(Metal metal); // // /** // * Get the number of powers the player has // * // * @return int between 0 and 16, inclusive // */ // int getPowerCount(); // // /** // * Returns an array of the player's metal abilities // * // * @return array of Metal // */ // Metal[] getPowers(); // // /** // * Sets the player as a Mistborn // */ // void setMistborn(); // // /** // * Check if the player is a Mistborn // * // * @return true if the player has ALL powers // */ // boolean isMistborn(); // // /** // * Check if the player is uninvested // * // * @return true if the player has NO powers // */ // boolean isUninvested(); // // /** // * Sets the player as uninvested // */ // void setUninvested(); // // /** // * Grant this player the given metal power // * // * @param metal the Metal to add // */ // void addPower(Metal metal); // // /** // * Remove the given metal power from this player // * // * @param metal the Metal to remove // */ // void revokePower(Metal metal); // // /** // * Checks if the player is burning the given metal // * // * @param metal the Metal to check // * @return true if the player is burning it // */ // boolean isBurning(Metal metal); // // /** // * Sets the player's burning flag for the given metal // * // * @param metal the Metal to set // * @param metalBurning the value to set it to // */ // void setBurning(Metal metal, boolean metalBurning); // // /** // * Sets the players amount of Metal to the given value // * // * @param metal the Metal to set // * @param amt the amount stored // */ // void setAmount(Metal metal, int amt); // // /** // * Gets the players stored amount of the given metal // * // * @param metal the Metal to check // * @return the amount stored // */ // int getAmount(Metal metal); // // /** // * Drain all specified metals // * // * @param metals all metals to drain // */ // void drainMetals(Metal... metals); // // /** // * Get how much damage has been accumulated // * // * @return the amount of damage // */ // int getDamageStored(); // // /** // * Set the amount of damage stored // * // * @param damageStored the amount of damage // */ // void setDamageStored(int damageStored); // // /** // * Set the death location and dimension // * // * @param pos BlockPos of the death location // * @param dim The RegistryKey representing the dimension the death occurred in // */ // void setDeathLoc(BlockPos pos, ResourceKey<Level> dim); // // void setDeathLoc(BlockPos pos, String dim_name); // // /** // * Returns the location of the most recent player's death, or null // * // * @return BlockPos of player's death, or null // */ // BlockPos getDeathLoc(); // // /** // * Returns the dimension of the most recent player's death, or null // * // * @return RegistryKey corresponding to the dimension, or null // */ // ResourceKey<Level> getDeathDim(); // // /** // * Set the spawn location and dimension // * // * @param pos BlockPos of the spawn point // * @param dim The RegistryKey representing the spawn dimension // */ // void setSpawnLoc(BlockPos pos, ResourceKey<Level> dim); // // void setSpawnLoc(BlockPos pos, String dim_name); // // /** // * Returns the location of the players spawn point if set, or null // * // * @return BlockPos of player's death, or null // */ // BlockPos getSpawnLoc(); // // /** // * Returns the dimension of the most player's spawn point, or null if unset. // * // * @return RegistryKey corresponding to the dimension, or null // */ // ResourceKey<Level> getSpawnDim(); // // void decEnhanced(); // // boolean isEnhanced(); // // void setEnhanced(int time); // // void load(CompoundTag nbt); // // CompoundTag save(); // // } // // Path: src/main/java/com/legobmw99/allomancy/modules/powers/data/AllomancerCapability.java // public class AllomancerCapability { // // public static final Capability<IAllomancerData> PLAYER_CAP = CapabilityManager.get(new CapabilityToken<>() { // }); // // public static final ResourceLocation IDENTIFIER = new ResourceLocation(Allomancy.MODID, "allomancy_data"); // // public static void registerCapability(final RegisterCapabilitiesEvent event) { // event.register(IAllomancerData.class); // } // // }
import com.legobmw99.allomancy.api.data.IAllomancerData; import com.legobmw99.allomancy.modules.powers.data.AllomancerCapability; import net.minecraft.client.Minecraft; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.world.entity.player.Player; import net.minecraftforge.network.NetworkEvent; import java.util.UUID; import java.util.function.Supplier;
package com.legobmw99.allomancy.modules.powers.network; public class AllomancerDataPacket { private final CompoundTag nbt; private final UUID uuid; /** * Packet for sending Allomancy player data to a client * * @param data the IAllomancerData data for the player * @param player the player */
// Path: src/main/java/com/legobmw99/allomancy/api/data/IAllomancerData.java // public interface IAllomancerData { // // /** // * Called each worldTick, checking the burn times, abilities, and metal // * amounts. Then syncs to the client to make sure everyone is on the same // * page // * // * @param player the player being checked // */ // void tickBurning(ServerPlayer player); // // /** // * Get if the player has the supplied power // * // * @param metal the Metal to check // * @return true if this capability has the power specified // */ // boolean hasPower(Metal metal); // // /** // * Get the number of powers the player has // * // * @return int between 0 and 16, inclusive // */ // int getPowerCount(); // // /** // * Returns an array of the player's metal abilities // * // * @return array of Metal // */ // Metal[] getPowers(); // // /** // * Sets the player as a Mistborn // */ // void setMistborn(); // // /** // * Check if the player is a Mistborn // * // * @return true if the player has ALL powers // */ // boolean isMistborn(); // // /** // * Check if the player is uninvested // * // * @return true if the player has NO powers // */ // boolean isUninvested(); // // /** // * Sets the player as uninvested // */ // void setUninvested(); // // /** // * Grant this player the given metal power // * // * @param metal the Metal to add // */ // void addPower(Metal metal); // // /** // * Remove the given metal power from this player // * // * @param metal the Metal to remove // */ // void revokePower(Metal metal); // // /** // * Checks if the player is burning the given metal // * // * @param metal the Metal to check // * @return true if the player is burning it // */ // boolean isBurning(Metal metal); // // /** // * Sets the player's burning flag for the given metal // * // * @param metal the Metal to set // * @param metalBurning the value to set it to // */ // void setBurning(Metal metal, boolean metalBurning); // // /** // * Sets the players amount of Metal to the given value // * // * @param metal the Metal to set // * @param amt the amount stored // */ // void setAmount(Metal metal, int amt); // // /** // * Gets the players stored amount of the given metal // * // * @param metal the Metal to check // * @return the amount stored // */ // int getAmount(Metal metal); // // /** // * Drain all specified metals // * // * @param metals all metals to drain // */ // void drainMetals(Metal... metals); // // /** // * Get how much damage has been accumulated // * // * @return the amount of damage // */ // int getDamageStored(); // // /** // * Set the amount of damage stored // * // * @param damageStored the amount of damage // */ // void setDamageStored(int damageStored); // // /** // * Set the death location and dimension // * // * @param pos BlockPos of the death location // * @param dim The RegistryKey representing the dimension the death occurred in // */ // void setDeathLoc(BlockPos pos, ResourceKey<Level> dim); // // void setDeathLoc(BlockPos pos, String dim_name); // // /** // * Returns the location of the most recent player's death, or null // * // * @return BlockPos of player's death, or null // */ // BlockPos getDeathLoc(); // // /** // * Returns the dimension of the most recent player's death, or null // * // * @return RegistryKey corresponding to the dimension, or null // */ // ResourceKey<Level> getDeathDim(); // // /** // * Set the spawn location and dimension // * // * @param pos BlockPos of the spawn point // * @param dim The RegistryKey representing the spawn dimension // */ // void setSpawnLoc(BlockPos pos, ResourceKey<Level> dim); // // void setSpawnLoc(BlockPos pos, String dim_name); // // /** // * Returns the location of the players spawn point if set, or null // * // * @return BlockPos of player's death, or null // */ // BlockPos getSpawnLoc(); // // /** // * Returns the dimension of the most player's spawn point, or null if unset. // * // * @return RegistryKey corresponding to the dimension, or null // */ // ResourceKey<Level> getSpawnDim(); // // void decEnhanced(); // // boolean isEnhanced(); // // void setEnhanced(int time); // // void load(CompoundTag nbt); // // CompoundTag save(); // // } // // Path: src/main/java/com/legobmw99/allomancy/modules/powers/data/AllomancerCapability.java // public class AllomancerCapability { // // public static final Capability<IAllomancerData> PLAYER_CAP = CapabilityManager.get(new CapabilityToken<>() { // }); // // public static final ResourceLocation IDENTIFIER = new ResourceLocation(Allomancy.MODID, "allomancy_data"); // // public static void registerCapability(final RegisterCapabilitiesEvent event) { // event.register(IAllomancerData.class); // } // // } // Path: src/main/java/com/legobmw99/allomancy/modules/powers/network/AllomancerDataPacket.java import com.legobmw99.allomancy.api.data.IAllomancerData; import com.legobmw99.allomancy.modules.powers.data.AllomancerCapability; import net.minecraft.client.Minecraft; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.world.entity.player.Player; import net.minecraftforge.network.NetworkEvent; import java.util.UUID; import java.util.function.Supplier; package com.legobmw99.allomancy.modules.powers.network; public class AllomancerDataPacket { private final CompoundTag nbt; private final UUID uuid; /** * Packet for sending Allomancy player data to a client * * @param data the IAllomancerData data for the player * @param player the player */
public AllomancerDataPacket(IAllomancerData data, Player player) {
legobmw99/Allomancy
src/main/java/com/legobmw99/allomancy/modules/powers/network/AllomancerDataPacket.java
// Path: src/main/java/com/legobmw99/allomancy/api/data/IAllomancerData.java // public interface IAllomancerData { // // /** // * Called each worldTick, checking the burn times, abilities, and metal // * amounts. Then syncs to the client to make sure everyone is on the same // * page // * // * @param player the player being checked // */ // void tickBurning(ServerPlayer player); // // /** // * Get if the player has the supplied power // * // * @param metal the Metal to check // * @return true if this capability has the power specified // */ // boolean hasPower(Metal metal); // // /** // * Get the number of powers the player has // * // * @return int between 0 and 16, inclusive // */ // int getPowerCount(); // // /** // * Returns an array of the player's metal abilities // * // * @return array of Metal // */ // Metal[] getPowers(); // // /** // * Sets the player as a Mistborn // */ // void setMistborn(); // // /** // * Check if the player is a Mistborn // * // * @return true if the player has ALL powers // */ // boolean isMistborn(); // // /** // * Check if the player is uninvested // * // * @return true if the player has NO powers // */ // boolean isUninvested(); // // /** // * Sets the player as uninvested // */ // void setUninvested(); // // /** // * Grant this player the given metal power // * // * @param metal the Metal to add // */ // void addPower(Metal metal); // // /** // * Remove the given metal power from this player // * // * @param metal the Metal to remove // */ // void revokePower(Metal metal); // // /** // * Checks if the player is burning the given metal // * // * @param metal the Metal to check // * @return true if the player is burning it // */ // boolean isBurning(Metal metal); // // /** // * Sets the player's burning flag for the given metal // * // * @param metal the Metal to set // * @param metalBurning the value to set it to // */ // void setBurning(Metal metal, boolean metalBurning); // // /** // * Sets the players amount of Metal to the given value // * // * @param metal the Metal to set // * @param amt the amount stored // */ // void setAmount(Metal metal, int amt); // // /** // * Gets the players stored amount of the given metal // * // * @param metal the Metal to check // * @return the amount stored // */ // int getAmount(Metal metal); // // /** // * Drain all specified metals // * // * @param metals all metals to drain // */ // void drainMetals(Metal... metals); // // /** // * Get how much damage has been accumulated // * // * @return the amount of damage // */ // int getDamageStored(); // // /** // * Set the amount of damage stored // * // * @param damageStored the amount of damage // */ // void setDamageStored(int damageStored); // // /** // * Set the death location and dimension // * // * @param pos BlockPos of the death location // * @param dim The RegistryKey representing the dimension the death occurred in // */ // void setDeathLoc(BlockPos pos, ResourceKey<Level> dim); // // void setDeathLoc(BlockPos pos, String dim_name); // // /** // * Returns the location of the most recent player's death, or null // * // * @return BlockPos of player's death, or null // */ // BlockPos getDeathLoc(); // // /** // * Returns the dimension of the most recent player's death, or null // * // * @return RegistryKey corresponding to the dimension, or null // */ // ResourceKey<Level> getDeathDim(); // // /** // * Set the spawn location and dimension // * // * @param pos BlockPos of the spawn point // * @param dim The RegistryKey representing the spawn dimension // */ // void setSpawnLoc(BlockPos pos, ResourceKey<Level> dim); // // void setSpawnLoc(BlockPos pos, String dim_name); // // /** // * Returns the location of the players spawn point if set, or null // * // * @return BlockPos of player's death, or null // */ // BlockPos getSpawnLoc(); // // /** // * Returns the dimension of the most player's spawn point, or null if unset. // * // * @return RegistryKey corresponding to the dimension, or null // */ // ResourceKey<Level> getSpawnDim(); // // void decEnhanced(); // // boolean isEnhanced(); // // void setEnhanced(int time); // // void load(CompoundTag nbt); // // CompoundTag save(); // // } // // Path: src/main/java/com/legobmw99/allomancy/modules/powers/data/AllomancerCapability.java // public class AllomancerCapability { // // public static final Capability<IAllomancerData> PLAYER_CAP = CapabilityManager.get(new CapabilityToken<>() { // }); // // public static final ResourceLocation IDENTIFIER = new ResourceLocation(Allomancy.MODID, "allomancy_data"); // // public static void registerCapability(final RegisterCapabilitiesEvent event) { // event.register(IAllomancerData.class); // } // // }
import com.legobmw99.allomancy.api.data.IAllomancerData; import com.legobmw99.allomancy.modules.powers.data.AllomancerCapability; import net.minecraft.client.Minecraft; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.world.entity.player.Player; import net.minecraftforge.network.NetworkEvent; import java.util.UUID; import java.util.function.Supplier;
package com.legobmw99.allomancy.modules.powers.network; public class AllomancerDataPacket { private final CompoundTag nbt; private final UUID uuid; /** * Packet for sending Allomancy player data to a client * * @param data the IAllomancerData data for the player * @param player the player */ public AllomancerDataPacket(IAllomancerData data, Player player) { this.uuid = player.getUUID();
// Path: src/main/java/com/legobmw99/allomancy/api/data/IAllomancerData.java // public interface IAllomancerData { // // /** // * Called each worldTick, checking the burn times, abilities, and metal // * amounts. Then syncs to the client to make sure everyone is on the same // * page // * // * @param player the player being checked // */ // void tickBurning(ServerPlayer player); // // /** // * Get if the player has the supplied power // * // * @param metal the Metal to check // * @return true if this capability has the power specified // */ // boolean hasPower(Metal metal); // // /** // * Get the number of powers the player has // * // * @return int between 0 and 16, inclusive // */ // int getPowerCount(); // // /** // * Returns an array of the player's metal abilities // * // * @return array of Metal // */ // Metal[] getPowers(); // // /** // * Sets the player as a Mistborn // */ // void setMistborn(); // // /** // * Check if the player is a Mistborn // * // * @return true if the player has ALL powers // */ // boolean isMistborn(); // // /** // * Check if the player is uninvested // * // * @return true if the player has NO powers // */ // boolean isUninvested(); // // /** // * Sets the player as uninvested // */ // void setUninvested(); // // /** // * Grant this player the given metal power // * // * @param metal the Metal to add // */ // void addPower(Metal metal); // // /** // * Remove the given metal power from this player // * // * @param metal the Metal to remove // */ // void revokePower(Metal metal); // // /** // * Checks if the player is burning the given metal // * // * @param metal the Metal to check // * @return true if the player is burning it // */ // boolean isBurning(Metal metal); // // /** // * Sets the player's burning flag for the given metal // * // * @param metal the Metal to set // * @param metalBurning the value to set it to // */ // void setBurning(Metal metal, boolean metalBurning); // // /** // * Sets the players amount of Metal to the given value // * // * @param metal the Metal to set // * @param amt the amount stored // */ // void setAmount(Metal metal, int amt); // // /** // * Gets the players stored amount of the given metal // * // * @param metal the Metal to check // * @return the amount stored // */ // int getAmount(Metal metal); // // /** // * Drain all specified metals // * // * @param metals all metals to drain // */ // void drainMetals(Metal... metals); // // /** // * Get how much damage has been accumulated // * // * @return the amount of damage // */ // int getDamageStored(); // // /** // * Set the amount of damage stored // * // * @param damageStored the amount of damage // */ // void setDamageStored(int damageStored); // // /** // * Set the death location and dimension // * // * @param pos BlockPos of the death location // * @param dim The RegistryKey representing the dimension the death occurred in // */ // void setDeathLoc(BlockPos pos, ResourceKey<Level> dim); // // void setDeathLoc(BlockPos pos, String dim_name); // // /** // * Returns the location of the most recent player's death, or null // * // * @return BlockPos of player's death, or null // */ // BlockPos getDeathLoc(); // // /** // * Returns the dimension of the most recent player's death, or null // * // * @return RegistryKey corresponding to the dimension, or null // */ // ResourceKey<Level> getDeathDim(); // // /** // * Set the spawn location and dimension // * // * @param pos BlockPos of the spawn point // * @param dim The RegistryKey representing the spawn dimension // */ // void setSpawnLoc(BlockPos pos, ResourceKey<Level> dim); // // void setSpawnLoc(BlockPos pos, String dim_name); // // /** // * Returns the location of the players spawn point if set, or null // * // * @return BlockPos of player's death, or null // */ // BlockPos getSpawnLoc(); // // /** // * Returns the dimension of the most player's spawn point, or null if unset. // * // * @return RegistryKey corresponding to the dimension, or null // */ // ResourceKey<Level> getSpawnDim(); // // void decEnhanced(); // // boolean isEnhanced(); // // void setEnhanced(int time); // // void load(CompoundTag nbt); // // CompoundTag save(); // // } // // Path: src/main/java/com/legobmw99/allomancy/modules/powers/data/AllomancerCapability.java // public class AllomancerCapability { // // public static final Capability<IAllomancerData> PLAYER_CAP = CapabilityManager.get(new CapabilityToken<>() { // }); // // public static final ResourceLocation IDENTIFIER = new ResourceLocation(Allomancy.MODID, "allomancy_data"); // // public static void registerCapability(final RegisterCapabilitiesEvent event) { // event.register(IAllomancerData.class); // } // // } // Path: src/main/java/com/legobmw99/allomancy/modules/powers/network/AllomancerDataPacket.java import com.legobmw99.allomancy.api.data.IAllomancerData; import com.legobmw99.allomancy.modules.powers.data.AllomancerCapability; import net.minecraft.client.Minecraft; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.world.entity.player.Player; import net.minecraftforge.network.NetworkEvent; import java.util.UUID; import java.util.function.Supplier; package com.legobmw99.allomancy.modules.powers.network; public class AllomancerDataPacket { private final CompoundTag nbt; private final UUID uuid; /** * Packet for sending Allomancy player data to a client * * @param data the IAllomancerData data for the player * @param player the player */ public AllomancerDataPacket(IAllomancerData data, Player player) { this.uuid = player.getUUID();
this.nbt = (data != null && AllomancerCapability.PLAYER_CAP != null) ? data.save() : new CompoundTag();
legobmw99/Allomancy
src/main/java/com/legobmw99/allomancy/modules/powers/network/UpdateEnhancedPacket.java
// Path: src/main/java/com/legobmw99/allomancy/modules/powers/data/AllomancerCapability.java // public class AllomancerCapability { // // public static final Capability<IAllomancerData> PLAYER_CAP = CapabilityManager.get(new CapabilityToken<>() { // }); // // public static final ResourceLocation IDENTIFIER = new ResourceLocation(Allomancy.MODID, "allomancy_data"); // // public static void registerCapability(final RegisterCapabilitiesEvent event) { // event.register(IAllomancerData.class); // } // // } // // Path: src/main/java/com/legobmw99/allomancy/network/Network.java // public class Network { // // private static final String VERSION = "1.1"; // public static final SimpleChannel INSTANCE = NetworkRegistry.newSimpleChannel(new ResourceLocation(Allomancy.MODID, "networking"), () -> VERSION, VERSION::equals, // VERSION::equals); // // private static int index = 0; // // private static int nextIndex() { // return index++; // } // // public static void registerPackets() { // INSTANCE.registerMessage(nextIndex(), AllomancerDataPacket.class, AllomancerDataPacket::encode, AllomancerDataPacket::decode, AllomancerDataPacket::handle); // INSTANCE.registerMessage(nextIndex(), UpdateBurnPacket.class, UpdateBurnPacket::encode, UpdateBurnPacket::decode, UpdateBurnPacket::handle); // INSTANCE.registerMessage(nextIndex(), ChangeEmotionPacket.class, ChangeEmotionPacket::encode, ChangeEmotionPacket::decode, ChangeEmotionPacket::handle); // INSTANCE.registerMessage(nextIndex(), TryPushPullEntity.class, TryPushPullEntity::encode, TryPushPullEntity::decode, TryPushPullEntity::handle); // INSTANCE.registerMessage(nextIndex(), TryPushPullBlock.class, TryPushPullBlock::encode, TryPushPullBlock::decode, TryPushPullBlock::handle); // INSTANCE.registerMessage(nextIndex(), UpdateEnhancedPacket.class, UpdateEnhancedPacket::encode, UpdateEnhancedPacket::decode, UpdateEnhancedPacket::handle); // } // // public static void sendToServer(Object msg) { // INSTANCE.sendToServer(msg); // } // // public static void sendTo(Object msg, ServerPlayer player) { // if (!(player instanceof FakePlayer)) { // INSTANCE.sendTo(msg, player.connection.getConnection(), NetworkDirection.PLAY_TO_CLIENT); // } // } // // public static void sendTo(Object msg, PacketDistributor.PacketTarget target) { // INSTANCE.send(target, msg); // } // // public static void sync(Player player) { // player.getCapability(AllomancerCapability.PLAYER_CAP).ifPresent(data -> sync(data, player)); // } // // public static void sync(IAllomancerData cap, Player player) { // sync(new AllomancerDataPacket(cap, player), player); // } // // public static void sync(Object msg, Player player) { // sendTo(msg, PacketDistributor.TRACKING_ENTITY_AND_SELF.with(() -> player)); // } // // }
import com.legobmw99.allomancy.modules.powers.data.AllomancerCapability; import com.legobmw99.allomancy.network.Network; import net.minecraft.client.Minecraft; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.world.entity.player.Player; import net.minecraftforge.network.NetworkDirection; import net.minecraftforge.network.NetworkEvent; import java.util.function.Supplier;
package com.legobmw99.allomancy.modules.powers.network; public class UpdateEnhancedPacket { private final int enhance_time; private final int entityID; public UpdateEnhancedPacket(boolean enhanced, int entityID) { this.enhance_time = enhanced ? 100 : 0; this.entityID = entityID; } public UpdateEnhancedPacket(int enhance_time, int entityID) { this.enhance_time = enhance_time; this.entityID = entityID; } public static UpdateEnhancedPacket decode(FriendlyByteBuf buf) { return new UpdateEnhancedPacket(buf.readInt(), buf.readInt()); } public void encode(FriendlyByteBuf buf) { buf.writeInt(this.enhance_time); buf.writeInt(this.entityID); } public void handle(Supplier<NetworkEvent.Context> ctx) { ctx.get().enqueueWork(() -> { if (ctx.get().getDirection() == NetworkDirection.PLAY_TO_SERVER) { // Update player of own status Player player = (Player) ctx.get().getSender().level.getEntity(this.entityID); if (player != null) {
// Path: src/main/java/com/legobmw99/allomancy/modules/powers/data/AllomancerCapability.java // public class AllomancerCapability { // // public static final Capability<IAllomancerData> PLAYER_CAP = CapabilityManager.get(new CapabilityToken<>() { // }); // // public static final ResourceLocation IDENTIFIER = new ResourceLocation(Allomancy.MODID, "allomancy_data"); // // public static void registerCapability(final RegisterCapabilitiesEvent event) { // event.register(IAllomancerData.class); // } // // } // // Path: src/main/java/com/legobmw99/allomancy/network/Network.java // public class Network { // // private static final String VERSION = "1.1"; // public static final SimpleChannel INSTANCE = NetworkRegistry.newSimpleChannel(new ResourceLocation(Allomancy.MODID, "networking"), () -> VERSION, VERSION::equals, // VERSION::equals); // // private static int index = 0; // // private static int nextIndex() { // return index++; // } // // public static void registerPackets() { // INSTANCE.registerMessage(nextIndex(), AllomancerDataPacket.class, AllomancerDataPacket::encode, AllomancerDataPacket::decode, AllomancerDataPacket::handle); // INSTANCE.registerMessage(nextIndex(), UpdateBurnPacket.class, UpdateBurnPacket::encode, UpdateBurnPacket::decode, UpdateBurnPacket::handle); // INSTANCE.registerMessage(nextIndex(), ChangeEmotionPacket.class, ChangeEmotionPacket::encode, ChangeEmotionPacket::decode, ChangeEmotionPacket::handle); // INSTANCE.registerMessage(nextIndex(), TryPushPullEntity.class, TryPushPullEntity::encode, TryPushPullEntity::decode, TryPushPullEntity::handle); // INSTANCE.registerMessage(nextIndex(), TryPushPullBlock.class, TryPushPullBlock::encode, TryPushPullBlock::decode, TryPushPullBlock::handle); // INSTANCE.registerMessage(nextIndex(), UpdateEnhancedPacket.class, UpdateEnhancedPacket::encode, UpdateEnhancedPacket::decode, UpdateEnhancedPacket::handle); // } // // public static void sendToServer(Object msg) { // INSTANCE.sendToServer(msg); // } // // public static void sendTo(Object msg, ServerPlayer player) { // if (!(player instanceof FakePlayer)) { // INSTANCE.sendTo(msg, player.connection.getConnection(), NetworkDirection.PLAY_TO_CLIENT); // } // } // // public static void sendTo(Object msg, PacketDistributor.PacketTarget target) { // INSTANCE.send(target, msg); // } // // public static void sync(Player player) { // player.getCapability(AllomancerCapability.PLAYER_CAP).ifPresent(data -> sync(data, player)); // } // // public static void sync(IAllomancerData cap, Player player) { // sync(new AllomancerDataPacket(cap, player), player); // } // // public static void sync(Object msg, Player player) { // sendTo(msg, PacketDistributor.TRACKING_ENTITY_AND_SELF.with(() -> player)); // } // // } // Path: src/main/java/com/legobmw99/allomancy/modules/powers/network/UpdateEnhancedPacket.java import com.legobmw99.allomancy.modules.powers.data.AllomancerCapability; import com.legobmw99.allomancy.network.Network; import net.minecraft.client.Minecraft; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.world.entity.player.Player; import net.minecraftforge.network.NetworkDirection; import net.minecraftforge.network.NetworkEvent; import java.util.function.Supplier; package com.legobmw99.allomancy.modules.powers.network; public class UpdateEnhancedPacket { private final int enhance_time; private final int entityID; public UpdateEnhancedPacket(boolean enhanced, int entityID) { this.enhance_time = enhanced ? 100 : 0; this.entityID = entityID; } public UpdateEnhancedPacket(int enhance_time, int entityID) { this.enhance_time = enhance_time; this.entityID = entityID; } public static UpdateEnhancedPacket decode(FriendlyByteBuf buf) { return new UpdateEnhancedPacket(buf.readInt(), buf.readInt()); } public void encode(FriendlyByteBuf buf) { buf.writeInt(this.enhance_time); buf.writeInt(this.entityID); } public void handle(Supplier<NetworkEvent.Context> ctx) { ctx.get().enqueueWork(() -> { if (ctx.get().getDirection() == NetworkDirection.PLAY_TO_SERVER) { // Update player of own status Player player = (Player) ctx.get().getSender().level.getEntity(this.entityID); if (player != null) {
player.getCapability(AllomancerCapability.PLAYER_CAP).ifPresent(data -> {
legobmw99/Allomancy
src/main/java/com/legobmw99/allomancy/modules/powers/network/UpdateEnhancedPacket.java
// Path: src/main/java/com/legobmw99/allomancy/modules/powers/data/AllomancerCapability.java // public class AllomancerCapability { // // public static final Capability<IAllomancerData> PLAYER_CAP = CapabilityManager.get(new CapabilityToken<>() { // }); // // public static final ResourceLocation IDENTIFIER = new ResourceLocation(Allomancy.MODID, "allomancy_data"); // // public static void registerCapability(final RegisterCapabilitiesEvent event) { // event.register(IAllomancerData.class); // } // // } // // Path: src/main/java/com/legobmw99/allomancy/network/Network.java // public class Network { // // private static final String VERSION = "1.1"; // public static final SimpleChannel INSTANCE = NetworkRegistry.newSimpleChannel(new ResourceLocation(Allomancy.MODID, "networking"), () -> VERSION, VERSION::equals, // VERSION::equals); // // private static int index = 0; // // private static int nextIndex() { // return index++; // } // // public static void registerPackets() { // INSTANCE.registerMessage(nextIndex(), AllomancerDataPacket.class, AllomancerDataPacket::encode, AllomancerDataPacket::decode, AllomancerDataPacket::handle); // INSTANCE.registerMessage(nextIndex(), UpdateBurnPacket.class, UpdateBurnPacket::encode, UpdateBurnPacket::decode, UpdateBurnPacket::handle); // INSTANCE.registerMessage(nextIndex(), ChangeEmotionPacket.class, ChangeEmotionPacket::encode, ChangeEmotionPacket::decode, ChangeEmotionPacket::handle); // INSTANCE.registerMessage(nextIndex(), TryPushPullEntity.class, TryPushPullEntity::encode, TryPushPullEntity::decode, TryPushPullEntity::handle); // INSTANCE.registerMessage(nextIndex(), TryPushPullBlock.class, TryPushPullBlock::encode, TryPushPullBlock::decode, TryPushPullBlock::handle); // INSTANCE.registerMessage(nextIndex(), UpdateEnhancedPacket.class, UpdateEnhancedPacket::encode, UpdateEnhancedPacket::decode, UpdateEnhancedPacket::handle); // } // // public static void sendToServer(Object msg) { // INSTANCE.sendToServer(msg); // } // // public static void sendTo(Object msg, ServerPlayer player) { // if (!(player instanceof FakePlayer)) { // INSTANCE.sendTo(msg, player.connection.getConnection(), NetworkDirection.PLAY_TO_CLIENT); // } // } // // public static void sendTo(Object msg, PacketDistributor.PacketTarget target) { // INSTANCE.send(target, msg); // } // // public static void sync(Player player) { // player.getCapability(AllomancerCapability.PLAYER_CAP).ifPresent(data -> sync(data, player)); // } // // public static void sync(IAllomancerData cap, Player player) { // sync(new AllomancerDataPacket(cap, player), player); // } // // public static void sync(Object msg, Player player) { // sendTo(msg, PacketDistributor.TRACKING_ENTITY_AND_SELF.with(() -> player)); // } // // }
import com.legobmw99.allomancy.modules.powers.data.AllomancerCapability; import com.legobmw99.allomancy.network.Network; import net.minecraft.client.Minecraft; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.world.entity.player.Player; import net.minecraftforge.network.NetworkDirection; import net.minecraftforge.network.NetworkEvent; import java.util.function.Supplier;
package com.legobmw99.allomancy.modules.powers.network; public class UpdateEnhancedPacket { private final int enhance_time; private final int entityID; public UpdateEnhancedPacket(boolean enhanced, int entityID) { this.enhance_time = enhanced ? 100 : 0; this.entityID = entityID; } public UpdateEnhancedPacket(int enhance_time, int entityID) { this.enhance_time = enhance_time; this.entityID = entityID; } public static UpdateEnhancedPacket decode(FriendlyByteBuf buf) { return new UpdateEnhancedPacket(buf.readInt(), buf.readInt()); } public void encode(FriendlyByteBuf buf) { buf.writeInt(this.enhance_time); buf.writeInt(this.entityID); } public void handle(Supplier<NetworkEvent.Context> ctx) { ctx.get().enqueueWork(() -> { if (ctx.get().getDirection() == NetworkDirection.PLAY_TO_SERVER) { // Update player of own status Player player = (Player) ctx.get().getSender().level.getEntity(this.entityID); if (player != null) { player.getCapability(AllomancerCapability.PLAYER_CAP).ifPresent(data -> { data.setEnhanced(this.enhance_time);
// Path: src/main/java/com/legobmw99/allomancy/modules/powers/data/AllomancerCapability.java // public class AllomancerCapability { // // public static final Capability<IAllomancerData> PLAYER_CAP = CapabilityManager.get(new CapabilityToken<>() { // }); // // public static final ResourceLocation IDENTIFIER = new ResourceLocation(Allomancy.MODID, "allomancy_data"); // // public static void registerCapability(final RegisterCapabilitiesEvent event) { // event.register(IAllomancerData.class); // } // // } // // Path: src/main/java/com/legobmw99/allomancy/network/Network.java // public class Network { // // private static final String VERSION = "1.1"; // public static final SimpleChannel INSTANCE = NetworkRegistry.newSimpleChannel(new ResourceLocation(Allomancy.MODID, "networking"), () -> VERSION, VERSION::equals, // VERSION::equals); // // private static int index = 0; // // private static int nextIndex() { // return index++; // } // // public static void registerPackets() { // INSTANCE.registerMessage(nextIndex(), AllomancerDataPacket.class, AllomancerDataPacket::encode, AllomancerDataPacket::decode, AllomancerDataPacket::handle); // INSTANCE.registerMessage(nextIndex(), UpdateBurnPacket.class, UpdateBurnPacket::encode, UpdateBurnPacket::decode, UpdateBurnPacket::handle); // INSTANCE.registerMessage(nextIndex(), ChangeEmotionPacket.class, ChangeEmotionPacket::encode, ChangeEmotionPacket::decode, ChangeEmotionPacket::handle); // INSTANCE.registerMessage(nextIndex(), TryPushPullEntity.class, TryPushPullEntity::encode, TryPushPullEntity::decode, TryPushPullEntity::handle); // INSTANCE.registerMessage(nextIndex(), TryPushPullBlock.class, TryPushPullBlock::encode, TryPushPullBlock::decode, TryPushPullBlock::handle); // INSTANCE.registerMessage(nextIndex(), UpdateEnhancedPacket.class, UpdateEnhancedPacket::encode, UpdateEnhancedPacket::decode, UpdateEnhancedPacket::handle); // } // // public static void sendToServer(Object msg) { // INSTANCE.sendToServer(msg); // } // // public static void sendTo(Object msg, ServerPlayer player) { // if (!(player instanceof FakePlayer)) { // INSTANCE.sendTo(msg, player.connection.getConnection(), NetworkDirection.PLAY_TO_CLIENT); // } // } // // public static void sendTo(Object msg, PacketDistributor.PacketTarget target) { // INSTANCE.send(target, msg); // } // // public static void sync(Player player) { // player.getCapability(AllomancerCapability.PLAYER_CAP).ifPresent(data -> sync(data, player)); // } // // public static void sync(IAllomancerData cap, Player player) { // sync(new AllomancerDataPacket(cap, player), player); // } // // public static void sync(Object msg, Player player) { // sendTo(msg, PacketDistributor.TRACKING_ENTITY_AND_SELF.with(() -> player)); // } // // } // Path: src/main/java/com/legobmw99/allomancy/modules/powers/network/UpdateEnhancedPacket.java import com.legobmw99.allomancy.modules.powers.data.AllomancerCapability; import com.legobmw99.allomancy.network.Network; import net.minecraft.client.Minecraft; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.world.entity.player.Player; import net.minecraftforge.network.NetworkDirection; import net.minecraftforge.network.NetworkEvent; import java.util.function.Supplier; package com.legobmw99.allomancy.modules.powers.network; public class UpdateEnhancedPacket { private final int enhance_time; private final int entityID; public UpdateEnhancedPacket(boolean enhanced, int entityID) { this.enhance_time = enhanced ? 100 : 0; this.entityID = entityID; } public UpdateEnhancedPacket(int enhance_time, int entityID) { this.enhance_time = enhance_time; this.entityID = entityID; } public static UpdateEnhancedPacket decode(FriendlyByteBuf buf) { return new UpdateEnhancedPacket(buf.readInt(), buf.readInt()); } public void encode(FriendlyByteBuf buf) { buf.writeInt(this.enhance_time); buf.writeInt(this.entityID); } public void handle(Supplier<NetworkEvent.Context> ctx) { ctx.get().enqueueWork(() -> { if (ctx.get().getDirection() == NetworkDirection.PLAY_TO_SERVER) { // Update player of own status Player player = (Player) ctx.get().getSender().level.getEntity(this.entityID); if (player != null) { player.getCapability(AllomancerCapability.PLAYER_CAP).ifPresent(data -> { data.setEnhanced(this.enhance_time);
Network.sync(new UpdateEnhancedPacket(this.enhance_time, this.entityID), player);
legobmw99/Allomancy
src/main/java/com/legobmw99/allomancy/modules/extras/block/IronLeverBlock.java
// Path: src/main/java/com/legobmw99/allomancy/Allomancy.java // @Mod(Allomancy.MODID) // public class Allomancy { // // public static final String MODID = "allomancy"; // public static final CreativeModeTab allomancy_group = new CreativeModeTab(MODID) { // @Override // public ItemStack makeIcon() { // return new ItemStack(CombatSetup.MISTCLOAK.get()); // } // }; // // public static final Logger LOGGER = LogManager.getLogger(); // // public static Allomancy instance; // // public Allomancy() { // instance = this; // // Register our setup events on the necessary buses // FMLJavaModLoadingContext.get().getModEventBus().addListener(Allomancy::init); // FMLJavaModLoadingContext.get().getModEventBus().addListener(Allomancy::clientInit); // FMLJavaModLoadingContext.get().getModEventBus().addListener(AllomancyConfig::onLoad); // FMLJavaModLoadingContext.get().getModEventBus().addListener(AllomancyConfig::onReload); // FMLJavaModLoadingContext.get().getModEventBus().addListener(PowersClientSetup::registerParticle); // FMLJavaModLoadingContext.get().getModEventBus().addListener(AllomancerCapability::registerCapability); // FMLJavaModLoadingContext.get().getModEventBus().addListener(CombatClientSetup::registerEntityRenders); // // MinecraftForge.EVENT_BUS.addListener(Allomancy::registerCommands); // MinecraftForge.EVENT_BUS.addListener(EventPriority.HIGH, OreGenerator::registerGeneration); // // // Register all Registries // PowersSetup.register(); // CombatSetup.register(); // ConsumeSetup.register(); // MaterialsSetup.register(); // ExtrasSetup.register(); // // AllomancyConfig.register(); // // } // // public static Item.Properties createStandardItemProperties() { // return new Item.Properties().tab(allomancy_group).stacksTo(64); // } // // public static Item createStandardItem() { // return new Item(createStandardItemProperties()); // } // // // public static MutableComponent addColorToText(String translationKey, ChatFormatting color) { // MutableComponent lore = new TranslatableComponent(translationKey); // return addColor(lore, color); // } // // public static MutableComponent addColorToText(String translationKey, ChatFormatting color, Object... fmting) { // MutableComponent lore = new TranslatableComponent(translationKey, fmting); // return addColor(lore, color); // } // // private static MutableComponent addColor(MutableComponent text, ChatFormatting color) { // text.setStyle(text.getStyle().withColor(TextColor.fromLegacyFormat(color))); // return text; // } // // public static void clientInit(final FMLClientSetupEvent e) { // PowersSetup.clientInit(e); // } // // public static void registerCommands(final RegisterCommandsEvent e) { // PowersSetup.registerCommands(e); // } // // public static void init(final FMLCommonSetupEvent e) { // PowersSetup.init(e); // MaterialsSetup.init(e); // Network.registerPackets(); // } // } // // Path: src/main/java/com/legobmw99/allomancy/api/block/IAllomanticallyUsableBlock.java // public interface IAllomanticallyUsableBlock { // // /** // * Called when the block is steelpushed or ironpulled // * // * @param isPush whether the activation is Steel // * @return whether the block was activated // */ // boolean useAllomantically(BlockState state, Level world, BlockPos pos, Player playerIn, boolean isPush); // }
import com.legobmw99.allomancy.Allomancy; import com.legobmw99.allomancy.api.block.IAllomanticallyUsableBlock; import net.minecraft.ChatFormatting; import net.minecraft.core.BlockPos; import net.minecraft.network.chat.Component; import net.minecraft.sounds.SoundEvents; import net.minecraft.sounds.SoundSource; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.TooltipFlag; import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.LeverBlock; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.material.Material; import net.minecraft.world.phys.BlockHitResult; import javax.annotation.Nullable; import java.util.List;
package com.legobmw99.allomancy.modules.extras.block; public class IronLeverBlock extends LeverBlock implements IAllomanticallyUsableBlock { public IronLeverBlock() { super(Block.Properties.of(Material.METAL).noCollission().strength(1.0F)); } @Override public boolean useAllomantically(BlockState state, Level world, BlockPos pos, Player playerIn, boolean isPush) { state = state.cycle(POWERED); if (world.isClientSide) { return true; } if ((!isPush && state.getValue(POWERED)) || (isPush && !state.getValue(POWERED))) { world.setBlock(pos, state, 3); float f = state.getValue(POWERED) ? 0.6F : 0.5F; world.playSound(null, pos, SoundEvents.LEVER_CLICK, SoundSource.BLOCKS, 0.3F, f); this.updateNeighbors(state, world, pos); return true; } return false; } @Override public InteractionResult use(BlockState state, Level worldIn, BlockPos pos, Player player, InteractionHand handIn, BlockHitResult hit) { return InteractionResult.FAIL; } @Override public void appendHoverText(ItemStack stack, @Nullable BlockGetter worldIn, List<Component> tooltip, TooltipFlag flagIn) { super.appendHoverText(stack, worldIn, tooltip, flagIn);
// Path: src/main/java/com/legobmw99/allomancy/Allomancy.java // @Mod(Allomancy.MODID) // public class Allomancy { // // public static final String MODID = "allomancy"; // public static final CreativeModeTab allomancy_group = new CreativeModeTab(MODID) { // @Override // public ItemStack makeIcon() { // return new ItemStack(CombatSetup.MISTCLOAK.get()); // } // }; // // public static final Logger LOGGER = LogManager.getLogger(); // // public static Allomancy instance; // // public Allomancy() { // instance = this; // // Register our setup events on the necessary buses // FMLJavaModLoadingContext.get().getModEventBus().addListener(Allomancy::init); // FMLJavaModLoadingContext.get().getModEventBus().addListener(Allomancy::clientInit); // FMLJavaModLoadingContext.get().getModEventBus().addListener(AllomancyConfig::onLoad); // FMLJavaModLoadingContext.get().getModEventBus().addListener(AllomancyConfig::onReload); // FMLJavaModLoadingContext.get().getModEventBus().addListener(PowersClientSetup::registerParticle); // FMLJavaModLoadingContext.get().getModEventBus().addListener(AllomancerCapability::registerCapability); // FMLJavaModLoadingContext.get().getModEventBus().addListener(CombatClientSetup::registerEntityRenders); // // MinecraftForge.EVENT_BUS.addListener(Allomancy::registerCommands); // MinecraftForge.EVENT_BUS.addListener(EventPriority.HIGH, OreGenerator::registerGeneration); // // // Register all Registries // PowersSetup.register(); // CombatSetup.register(); // ConsumeSetup.register(); // MaterialsSetup.register(); // ExtrasSetup.register(); // // AllomancyConfig.register(); // // } // // public static Item.Properties createStandardItemProperties() { // return new Item.Properties().tab(allomancy_group).stacksTo(64); // } // // public static Item createStandardItem() { // return new Item(createStandardItemProperties()); // } // // // public static MutableComponent addColorToText(String translationKey, ChatFormatting color) { // MutableComponent lore = new TranslatableComponent(translationKey); // return addColor(lore, color); // } // // public static MutableComponent addColorToText(String translationKey, ChatFormatting color, Object... fmting) { // MutableComponent lore = new TranslatableComponent(translationKey, fmting); // return addColor(lore, color); // } // // private static MutableComponent addColor(MutableComponent text, ChatFormatting color) { // text.setStyle(text.getStyle().withColor(TextColor.fromLegacyFormat(color))); // return text; // } // // public static void clientInit(final FMLClientSetupEvent e) { // PowersSetup.clientInit(e); // } // // public static void registerCommands(final RegisterCommandsEvent e) { // PowersSetup.registerCommands(e); // } // // public static void init(final FMLCommonSetupEvent e) { // PowersSetup.init(e); // MaterialsSetup.init(e); // Network.registerPackets(); // } // } // // Path: src/main/java/com/legobmw99/allomancy/api/block/IAllomanticallyUsableBlock.java // public interface IAllomanticallyUsableBlock { // // /** // * Called when the block is steelpushed or ironpulled // * // * @param isPush whether the activation is Steel // * @return whether the block was activated // */ // boolean useAllomantically(BlockState state, Level world, BlockPos pos, Player playerIn, boolean isPush); // } // Path: src/main/java/com/legobmw99/allomancy/modules/extras/block/IronLeverBlock.java import com.legobmw99.allomancy.Allomancy; import com.legobmw99.allomancy.api.block.IAllomanticallyUsableBlock; import net.minecraft.ChatFormatting; import net.minecraft.core.BlockPos; import net.minecraft.network.chat.Component; import net.minecraft.sounds.SoundEvents; import net.minecraft.sounds.SoundSource; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.TooltipFlag; import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.LeverBlock; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.material.Material; import net.minecraft.world.phys.BlockHitResult; import javax.annotation.Nullable; import java.util.List; package com.legobmw99.allomancy.modules.extras.block; public class IronLeverBlock extends LeverBlock implements IAllomanticallyUsableBlock { public IronLeverBlock() { super(Block.Properties.of(Material.METAL).noCollission().strength(1.0F)); } @Override public boolean useAllomantically(BlockState state, Level world, BlockPos pos, Player playerIn, boolean isPush) { state = state.cycle(POWERED); if (world.isClientSide) { return true; } if ((!isPush && state.getValue(POWERED)) || (isPush && !state.getValue(POWERED))) { world.setBlock(pos, state, 3); float f = state.getValue(POWERED) ? 0.6F : 0.5F; world.playSound(null, pos, SoundEvents.LEVER_CLICK, SoundSource.BLOCKS, 0.3F, f); this.updateNeighbors(state, world, pos); return true; } return false; } @Override public InteractionResult use(BlockState state, Level worldIn, BlockPos pos, Player player, InteractionHand handIn, BlockHitResult hit) { return InteractionResult.FAIL; } @Override public void appendHoverText(ItemStack stack, @Nullable BlockGetter worldIn, List<Component> tooltip, TooltipFlag flagIn) { super.appendHoverText(stack, worldIn, tooltip, flagIn);
Component lore = Allomancy.addColorToText("block.allomancy.iron_activation.lore", ChatFormatting.GRAY);
PaNaVTEC/Katas
salary-slip/src/main/java/salaryslip/SalarySlipGenerator.java
// Path: salary-slip/src/main/java/salaryslip/SalarySlipBuilder.java // public static SalarySlipBuilder aSalarySlip() { // return new SalarySlipBuilder(); // }
import static salaryslip.SalarySlipBuilder.aSalarySlip;
package salaryslip; class SalarySlipGenerator { private final NationalInsuranceCalculation nationalInsuranceCalculation; private final GrossSalaryCalculation grossSalaryCalculation; private final TaxFreeAllowanceCalculation taxFreeAllowanceCalculation; private final TaxableIncomeCalculation taxableIncomeCalculation; private final TaxablePayableCalculation taxablePayableCalculation; SalarySlipGenerator(NationalInsuranceCalculation nationalInsuranceCalculation, GrossSalaryCalculation grossSalaryCalculation, TaxFreeAllowanceCalculation taxFreeAllowanceCalculation, TaxableIncomeCalculation taxableIncomeCalculation, TaxablePayableCalculation taxablePayableCalculation) { this.nationalInsuranceCalculation = nationalInsuranceCalculation; this.grossSalaryCalculation = grossSalaryCalculation; this.taxFreeAllowanceCalculation = taxFreeAllowanceCalculation; this.taxableIncomeCalculation = taxableIncomeCalculation; this.taxablePayableCalculation = taxablePayableCalculation; } SalarySlip generateFor(Employee employee) { AnnualAmount annualSalary = new AnnualAmount(employee.getAnnualSalary()); MonthlyAmount nationalInsuranceContribution = nationalInsuranceCalculation.execute(annualSalary); MonthlyAmount grossSalary = grossSalaryCalculation.execute(annualSalary); MonthlyAmount taxFreeAllowance = taxFreeAllowanceCalculation.execute(annualSalary); MonthlyAmount taxableIncome = taxableIncomeCalculation.execute(annualSalary); MonthlyAmount taxablePayable = taxablePayableCalculation.execute(annualSalary);
// Path: salary-slip/src/main/java/salaryslip/SalarySlipBuilder.java // public static SalarySlipBuilder aSalarySlip() { // return new SalarySlipBuilder(); // } // Path: salary-slip/src/main/java/salaryslip/SalarySlipGenerator.java import static salaryslip.SalarySlipBuilder.aSalarySlip; package salaryslip; class SalarySlipGenerator { private final NationalInsuranceCalculation nationalInsuranceCalculation; private final GrossSalaryCalculation grossSalaryCalculation; private final TaxFreeAllowanceCalculation taxFreeAllowanceCalculation; private final TaxableIncomeCalculation taxableIncomeCalculation; private final TaxablePayableCalculation taxablePayableCalculation; SalarySlipGenerator(NationalInsuranceCalculation nationalInsuranceCalculation, GrossSalaryCalculation grossSalaryCalculation, TaxFreeAllowanceCalculation taxFreeAllowanceCalculation, TaxableIncomeCalculation taxableIncomeCalculation, TaxablePayableCalculation taxablePayableCalculation) { this.nationalInsuranceCalculation = nationalInsuranceCalculation; this.grossSalaryCalculation = grossSalaryCalculation; this.taxFreeAllowanceCalculation = taxFreeAllowanceCalculation; this.taxableIncomeCalculation = taxableIncomeCalculation; this.taxablePayableCalculation = taxablePayableCalculation; } SalarySlip generateFor(Employee employee) { AnnualAmount annualSalary = new AnnualAmount(employee.getAnnualSalary()); MonthlyAmount nationalInsuranceContribution = nationalInsuranceCalculation.execute(annualSalary); MonthlyAmount grossSalary = grossSalaryCalculation.execute(annualSalary); MonthlyAmount taxFreeAllowance = taxFreeAllowanceCalculation.execute(annualSalary); MonthlyAmount taxableIncome = taxableIncomeCalculation.execute(annualSalary); MonthlyAmount taxablePayable = taxablePayableCalculation.execute(annualSalary);
return aSalarySlip()
PaNaVTEC/Katas
salary-slip/src/test/java/salaryslip/SalarySlipGeneratorShould.java
// Path: salary-slip/src/test/java/salaryslip/EmployeeBuilder.java // public static EmployeeBuilder anEmployee() { // return new EmployeeBuilder(); // } // // Path: salary-slip/src/main/java/salaryslip/SalarySlipBuilder.java // public static SalarySlipBuilder aSalarySlip() { // return new SalarySlipBuilder(); // }
import org.junit.Test; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static salaryslip.EmployeeBuilder.anEmployee; import static salaryslip.SalarySlipBuilder.aSalarySlip;
package salaryslip; public class SalarySlipGeneratorShould { private SalarySlipGenerator salarySlipGenerator = new SalarySlipGenerator( new NationalInsuranceCalculation(), new GrossSalaryCalculation(), new TaxFreeAllowanceCalculation(), new TaxableIncomeCalculation(), new TaxablePayableCalculation() ); @Test public void calculate_monthly_gross_salary() {
// Path: salary-slip/src/test/java/salaryslip/EmployeeBuilder.java // public static EmployeeBuilder anEmployee() { // return new EmployeeBuilder(); // } // // Path: salary-slip/src/main/java/salaryslip/SalarySlipBuilder.java // public static SalarySlipBuilder aSalarySlip() { // return new SalarySlipBuilder(); // } // Path: salary-slip/src/test/java/salaryslip/SalarySlipGeneratorShould.java import org.junit.Test; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static salaryslip.EmployeeBuilder.anEmployee; import static salaryslip.SalarySlipBuilder.aSalarySlip; package salaryslip; public class SalarySlipGeneratorShould { private SalarySlipGenerator salarySlipGenerator = new SalarySlipGenerator( new NationalInsuranceCalculation(), new GrossSalaryCalculation(), new TaxFreeAllowanceCalculation(), new TaxableIncomeCalculation(), new TaxablePayableCalculation() ); @Test public void calculate_monthly_gross_salary() {
Employee employee = anEmployee()
PaNaVTEC/Katas
salary-slip/src/test/java/salaryslip/SalarySlipGeneratorShould.java
// Path: salary-slip/src/test/java/salaryslip/EmployeeBuilder.java // public static EmployeeBuilder anEmployee() { // return new EmployeeBuilder(); // } // // Path: salary-slip/src/main/java/salaryslip/SalarySlipBuilder.java // public static SalarySlipBuilder aSalarySlip() { // return new SalarySlipBuilder(); // }
import org.junit.Test; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static salaryslip.EmployeeBuilder.anEmployee; import static salaryslip.SalarySlipBuilder.aSalarySlip;
package salaryslip; public class SalarySlipGeneratorShould { private SalarySlipGenerator salarySlipGenerator = new SalarySlipGenerator( new NationalInsuranceCalculation(), new GrossSalaryCalculation(), new TaxFreeAllowanceCalculation(), new TaxableIncomeCalculation(), new TaxablePayableCalculation() ); @Test public void calculate_monthly_gross_salary() { Employee employee = anEmployee() .withAnnualSalary(5000d) .withName("John J Doe") .withEmployeeID(new EmployeeID("12345")) .build(); SalarySlip calculatedPaySlip = salarySlipGenerator.generateFor(employee); assertThat(calculatedPaySlip, is(
// Path: salary-slip/src/test/java/salaryslip/EmployeeBuilder.java // public static EmployeeBuilder anEmployee() { // return new EmployeeBuilder(); // } // // Path: salary-slip/src/main/java/salaryslip/SalarySlipBuilder.java // public static SalarySlipBuilder aSalarySlip() { // return new SalarySlipBuilder(); // } // Path: salary-slip/src/test/java/salaryslip/SalarySlipGeneratorShould.java import org.junit.Test; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static salaryslip.EmployeeBuilder.anEmployee; import static salaryslip.SalarySlipBuilder.aSalarySlip; package salaryslip; public class SalarySlipGeneratorShould { private SalarySlipGenerator salarySlipGenerator = new SalarySlipGenerator( new NationalInsuranceCalculation(), new GrossSalaryCalculation(), new TaxFreeAllowanceCalculation(), new TaxableIncomeCalculation(), new TaxablePayableCalculation() ); @Test public void calculate_monthly_gross_salary() { Employee employee = anEmployee() .withAnnualSalary(5000d) .withName("John J Doe") .withEmployeeID(new EmployeeID("12345")) .build(); SalarySlip calculatedPaySlip = salarySlipGenerator.generateFor(employee); assertThat(calculatedPaySlip, is(
aSalarySlip()
Pesegato/MonkeySheet
src/main/java/com/pesegato/MonkeySheet/actions/MSFiniteStateMachine.java
// Path: src/main/java/com/pesegato/MonkeySheet/MonkeySheetAppState.java // public class MonkeySheetAppState extends BaseAppState { // // static Logger log = LoggerFactory.getLogger( MonkeySheetAppState.class ); // // private static float tickDuration=0.025f; // public static float tTPF = 0; // public static Timeable timeable=new SimpleTimeable(); // // @Override // protected void initialize(Application app) { // getStateManager().attach(new MSTimerAppState()); // logBuildInfo(); // } // // static HashMap<String, MTween> anis = new HashMap<>(); // // public static MTween getAnim(String name){ // return anis.get(name); // } // // public static int getCenterX(String name){ // return anis.get(name).centerX; // } // // public static int getCenterY(String name){ // return anis.get(name).centerY; // } // // public void addAnim(MSContainer msCont, String name, int ani[], int hitbox[], int centerX, int centerY) { // anis.put(name,new MTween(msCont, name, ani, hitbox, msCont.numTiles, centerX, centerY)); // } // // public MSContainer initializeContainer(String name) { // Container c = MonkeySheetAppState.getContainer(name); // MSContainer container = new MSContainer(c); // for (Animation anim : animationC.get(c)) { // loadAnim(container, anim.id); // } // return container; // } // // static HashMap<String, Container> containers; // static HashMap<Container, Animation[]> animationC; // // static Container getContainer(String id) { // if (containers == null) { // try { // containers = new HashMap<>(); // animations = new HashMap<>(); // animationC = new HashMap<>(); // Container[] data = new Gson().fromJson(GM.getJSON("MonkeySheet/Containers"), Container[].class); // for (Container obj : data) { // containers.put(obj.id, obj); // Animation[] aData = new Gson().fromJson(GM.getJSON("MonkeySheet/Animations/" + obj.id), Animation[].class); // for (Animation aniObj : aData) { // animations.put(aniObj.id, aniObj); // } // animationC.put(obj, aData); // } // } catch (FileNotFoundException ex) { // log.error(null, ex); // } // } // return containers.get(id); // } // static HashMap<String, Animation> animations; // // public void loadAnim(MSContainer container, String anim){ // addAnim(container,anim,animations.get(anim).frames,null,animations.get(anim).centerX,animations.get(anim).centerY); // } // // @Override // public void update(float tpf){ // tTPF += tpf*timeable.getClockspeed(); // if (tTPF > tickDuration) { // tTPF = 0; // } // } // // public static void setTickDuration(float tickDuration){ // MonkeySheetAppState.tickDuration=tickDuration; // } // // @Override // protected void cleanup(Application app) { // } // // @Override // protected void onEnable() { // } // // @Override // protected void onDisable() { // } // // private static final String LIBNAME="MonkeySheet"; // // protected void logBuildInfo() { // try { // java.net.URL u = Resources.getResource(LIBNAME+".build.date"); // String build = Resources.toString(u, Charsets.UTF_8); // log.info("MonkeySheet build date: " + build); // log.info("MonkeySheet build version: " + Resources.toString(Resources.getResource(LIBNAME+".build.version"), Charsets.UTF_8)); // } catch( java.io.IOException e ) { // log.error( "Error reading build info", e ); // } // } // }
import com.jme3.renderer.RenderManager; import com.jme3.renderer.ViewPort; import com.jme3.scene.control.AbstractControl; import com.pesegato.MonkeySheet.MonkeySheetAppState; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.pesegato.MonkeySheet.actions; /** * @author Pesegato */ public abstract class MSFiniteStateMachine extends AbstractControl { static Logger log = LoggerFactory.getLogger(MSFiniteStateMachine.class); MSAction[] actions; MSAction currentAction; MSTransitionAction transitionAction; boolean runInit = true; public MSFiniteStateMachine(MSAction... actions) { initActions(actions); } public void initActions(MSAction... actions) { this.actions = actions; } @Override protected void controlUpdate(float tpf) {
// Path: src/main/java/com/pesegato/MonkeySheet/MonkeySheetAppState.java // public class MonkeySheetAppState extends BaseAppState { // // static Logger log = LoggerFactory.getLogger( MonkeySheetAppState.class ); // // private static float tickDuration=0.025f; // public static float tTPF = 0; // public static Timeable timeable=new SimpleTimeable(); // // @Override // protected void initialize(Application app) { // getStateManager().attach(new MSTimerAppState()); // logBuildInfo(); // } // // static HashMap<String, MTween> anis = new HashMap<>(); // // public static MTween getAnim(String name){ // return anis.get(name); // } // // public static int getCenterX(String name){ // return anis.get(name).centerX; // } // // public static int getCenterY(String name){ // return anis.get(name).centerY; // } // // public void addAnim(MSContainer msCont, String name, int ani[], int hitbox[], int centerX, int centerY) { // anis.put(name,new MTween(msCont, name, ani, hitbox, msCont.numTiles, centerX, centerY)); // } // // public MSContainer initializeContainer(String name) { // Container c = MonkeySheetAppState.getContainer(name); // MSContainer container = new MSContainer(c); // for (Animation anim : animationC.get(c)) { // loadAnim(container, anim.id); // } // return container; // } // // static HashMap<String, Container> containers; // static HashMap<Container, Animation[]> animationC; // // static Container getContainer(String id) { // if (containers == null) { // try { // containers = new HashMap<>(); // animations = new HashMap<>(); // animationC = new HashMap<>(); // Container[] data = new Gson().fromJson(GM.getJSON("MonkeySheet/Containers"), Container[].class); // for (Container obj : data) { // containers.put(obj.id, obj); // Animation[] aData = new Gson().fromJson(GM.getJSON("MonkeySheet/Animations/" + obj.id), Animation[].class); // for (Animation aniObj : aData) { // animations.put(aniObj.id, aniObj); // } // animationC.put(obj, aData); // } // } catch (FileNotFoundException ex) { // log.error(null, ex); // } // } // return containers.get(id); // } // static HashMap<String, Animation> animations; // // public void loadAnim(MSContainer container, String anim){ // addAnim(container,anim,animations.get(anim).frames,null,animations.get(anim).centerX,animations.get(anim).centerY); // } // // @Override // public void update(float tpf){ // tTPF += tpf*timeable.getClockspeed(); // if (tTPF > tickDuration) { // tTPF = 0; // } // } // // public static void setTickDuration(float tickDuration){ // MonkeySheetAppState.tickDuration=tickDuration; // } // // @Override // protected void cleanup(Application app) { // } // // @Override // protected void onEnable() { // } // // @Override // protected void onDisable() { // } // // private static final String LIBNAME="MonkeySheet"; // // protected void logBuildInfo() { // try { // java.net.URL u = Resources.getResource(LIBNAME+".build.date"); // String build = Resources.toString(u, Charsets.UTF_8); // log.info("MonkeySheet build date: " + build); // log.info("MonkeySheet build version: " + Resources.toString(Resources.getResource(LIBNAME+".build.version"), Charsets.UTF_8)); // } catch( java.io.IOException e ) { // log.error( "Error reading build info", e ); // } // } // } // Path: src/main/java/com/pesegato/MonkeySheet/actions/MSFiniteStateMachine.java import com.jme3.renderer.RenderManager; import com.jme3.renderer.ViewPort; import com.jme3.scene.control.AbstractControl; import com.pesegato.MonkeySheet.MonkeySheetAppState; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.pesegato.MonkeySheet.actions; /** * @author Pesegato */ public abstract class MSFiniteStateMachine extends AbstractControl { static Logger log = LoggerFactory.getLogger(MSFiniteStateMachine.class); MSAction[] actions; MSAction currentAction; MSTransitionAction transitionAction; boolean runInit = true; public MSFiniteStateMachine(MSAction... actions) { initActions(actions); } public void initActions(MSAction... actions) { this.actions = actions; } @Override protected void controlUpdate(float tpf) {
tpf *= MonkeySheetAppState.timeable.getClockspeed();
Pesegato/MonkeySheet
src/main/java/com/pesegato/MonkeySheet/MonkeySheetAppState.java
// Path: src/main/java/com/pesegato/goldmonkey/Animation.java // public class Animation { // public String id; // public int[] frames; // public int centerX; // public int centerY; // public Animation(String id, int[] frames, int centerX, int centerY){ // this.id=id; // this.frames=frames; // this.centerX=centerX; // this.centerY=centerY; // } // } // // Path: src/main/java/com/pesegato/goldmonkey/Container.java // public class Container { // public String id; // public int size; // public Container(String id, int size){ // this.id=id; // this.size=size; // } // } // // Path: src/main/java/com/pesegato/timing/SimpleTimeable.java // public class SimpleTimeable implements Timeable{ // @Override // public float getClockspeed() { // return 1; // } // } // // Path: src/main/java/com/pesegato/timing/Timeable.java // public interface Timeable { // /** // * // * Implement this interface to have configurable timing. // * // * Time factor: // * 0: time stops // * 1: time runs normally // * &lt;1: time is faster // * &gt;1: time is slower // * // * @return time factor // */ // float getClockspeed(); // }
import com.google.common.base.Charsets; import com.google.common.io.Resources; import com.google.gson.Gson; import com.jme3.app.Application; import com.jme3.app.state.BaseAppState; import com.pesegato.goldmonkey.Animation; import com.pesegato.goldmonkey.Container; import com.pesegato.goldmonkey.GM; import com.pesegato.timing.SimpleTimeable; import com.pesegato.timing.Timeable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.FileNotFoundException; import java.util.HashMap;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.pesegato.MonkeySheet; /** * * @author Pesegato */ public class MonkeySheetAppState extends BaseAppState { static Logger log = LoggerFactory.getLogger( MonkeySheetAppState.class ); private static float tickDuration=0.025f; public static float tTPF = 0;
// Path: src/main/java/com/pesegato/goldmonkey/Animation.java // public class Animation { // public String id; // public int[] frames; // public int centerX; // public int centerY; // public Animation(String id, int[] frames, int centerX, int centerY){ // this.id=id; // this.frames=frames; // this.centerX=centerX; // this.centerY=centerY; // } // } // // Path: src/main/java/com/pesegato/goldmonkey/Container.java // public class Container { // public String id; // public int size; // public Container(String id, int size){ // this.id=id; // this.size=size; // } // } // // Path: src/main/java/com/pesegato/timing/SimpleTimeable.java // public class SimpleTimeable implements Timeable{ // @Override // public float getClockspeed() { // return 1; // } // } // // Path: src/main/java/com/pesegato/timing/Timeable.java // public interface Timeable { // /** // * // * Implement this interface to have configurable timing. // * // * Time factor: // * 0: time stops // * 1: time runs normally // * &lt;1: time is faster // * &gt;1: time is slower // * // * @return time factor // */ // float getClockspeed(); // } // Path: src/main/java/com/pesegato/MonkeySheet/MonkeySheetAppState.java import com.google.common.base.Charsets; import com.google.common.io.Resources; import com.google.gson.Gson; import com.jme3.app.Application; import com.jme3.app.state.BaseAppState; import com.pesegato.goldmonkey.Animation; import com.pesegato.goldmonkey.Container; import com.pesegato.goldmonkey.GM; import com.pesegato.timing.SimpleTimeable; import com.pesegato.timing.Timeable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.FileNotFoundException; import java.util.HashMap; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.pesegato.MonkeySheet; /** * * @author Pesegato */ public class MonkeySheetAppState extends BaseAppState { static Logger log = LoggerFactory.getLogger( MonkeySheetAppState.class ); private static float tickDuration=0.025f; public static float tTPF = 0;
public static Timeable timeable=new SimpleTimeable();
Pesegato/MonkeySheet
src/main/java/com/pesegato/MonkeySheet/MonkeySheetAppState.java
// Path: src/main/java/com/pesegato/goldmonkey/Animation.java // public class Animation { // public String id; // public int[] frames; // public int centerX; // public int centerY; // public Animation(String id, int[] frames, int centerX, int centerY){ // this.id=id; // this.frames=frames; // this.centerX=centerX; // this.centerY=centerY; // } // } // // Path: src/main/java/com/pesegato/goldmonkey/Container.java // public class Container { // public String id; // public int size; // public Container(String id, int size){ // this.id=id; // this.size=size; // } // } // // Path: src/main/java/com/pesegato/timing/SimpleTimeable.java // public class SimpleTimeable implements Timeable{ // @Override // public float getClockspeed() { // return 1; // } // } // // Path: src/main/java/com/pesegato/timing/Timeable.java // public interface Timeable { // /** // * // * Implement this interface to have configurable timing. // * // * Time factor: // * 0: time stops // * 1: time runs normally // * &lt;1: time is faster // * &gt;1: time is slower // * // * @return time factor // */ // float getClockspeed(); // }
import com.google.common.base.Charsets; import com.google.common.io.Resources; import com.google.gson.Gson; import com.jme3.app.Application; import com.jme3.app.state.BaseAppState; import com.pesegato.goldmonkey.Animation; import com.pesegato.goldmonkey.Container; import com.pesegato.goldmonkey.GM; import com.pesegato.timing.SimpleTimeable; import com.pesegato.timing.Timeable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.FileNotFoundException; import java.util.HashMap;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.pesegato.MonkeySheet; /** * * @author Pesegato */ public class MonkeySheetAppState extends BaseAppState { static Logger log = LoggerFactory.getLogger( MonkeySheetAppState.class ); private static float tickDuration=0.025f; public static float tTPF = 0;
// Path: src/main/java/com/pesegato/goldmonkey/Animation.java // public class Animation { // public String id; // public int[] frames; // public int centerX; // public int centerY; // public Animation(String id, int[] frames, int centerX, int centerY){ // this.id=id; // this.frames=frames; // this.centerX=centerX; // this.centerY=centerY; // } // } // // Path: src/main/java/com/pesegato/goldmonkey/Container.java // public class Container { // public String id; // public int size; // public Container(String id, int size){ // this.id=id; // this.size=size; // } // } // // Path: src/main/java/com/pesegato/timing/SimpleTimeable.java // public class SimpleTimeable implements Timeable{ // @Override // public float getClockspeed() { // return 1; // } // } // // Path: src/main/java/com/pesegato/timing/Timeable.java // public interface Timeable { // /** // * // * Implement this interface to have configurable timing. // * // * Time factor: // * 0: time stops // * 1: time runs normally // * &lt;1: time is faster // * &gt;1: time is slower // * // * @return time factor // */ // float getClockspeed(); // } // Path: src/main/java/com/pesegato/MonkeySheet/MonkeySheetAppState.java import com.google.common.base.Charsets; import com.google.common.io.Resources; import com.google.gson.Gson; import com.jme3.app.Application; import com.jme3.app.state.BaseAppState; import com.pesegato.goldmonkey.Animation; import com.pesegato.goldmonkey.Container; import com.pesegato.goldmonkey.GM; import com.pesegato.timing.SimpleTimeable; import com.pesegato.timing.Timeable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.FileNotFoundException; import java.util.HashMap; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.pesegato.MonkeySheet; /** * * @author Pesegato */ public class MonkeySheetAppState extends BaseAppState { static Logger log = LoggerFactory.getLogger( MonkeySheetAppState.class ); private static float tickDuration=0.025f; public static float tTPF = 0;
public static Timeable timeable=new SimpleTimeable();
Pesegato/MonkeySheet
src/main/java/com/pesegato/MonkeySheet/MonkeySheetAppState.java
// Path: src/main/java/com/pesegato/goldmonkey/Animation.java // public class Animation { // public String id; // public int[] frames; // public int centerX; // public int centerY; // public Animation(String id, int[] frames, int centerX, int centerY){ // this.id=id; // this.frames=frames; // this.centerX=centerX; // this.centerY=centerY; // } // } // // Path: src/main/java/com/pesegato/goldmonkey/Container.java // public class Container { // public String id; // public int size; // public Container(String id, int size){ // this.id=id; // this.size=size; // } // } // // Path: src/main/java/com/pesegato/timing/SimpleTimeable.java // public class SimpleTimeable implements Timeable{ // @Override // public float getClockspeed() { // return 1; // } // } // // Path: src/main/java/com/pesegato/timing/Timeable.java // public interface Timeable { // /** // * // * Implement this interface to have configurable timing. // * // * Time factor: // * 0: time stops // * 1: time runs normally // * &lt;1: time is faster // * &gt;1: time is slower // * // * @return time factor // */ // float getClockspeed(); // }
import com.google.common.base.Charsets; import com.google.common.io.Resources; import com.google.gson.Gson; import com.jme3.app.Application; import com.jme3.app.state.BaseAppState; import com.pesegato.goldmonkey.Animation; import com.pesegato.goldmonkey.Container; import com.pesegato.goldmonkey.GM; import com.pesegato.timing.SimpleTimeable; import com.pesegato.timing.Timeable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.FileNotFoundException; import java.util.HashMap;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.pesegato.MonkeySheet; /** * * @author Pesegato */ public class MonkeySheetAppState extends BaseAppState { static Logger log = LoggerFactory.getLogger( MonkeySheetAppState.class ); private static float tickDuration=0.025f; public static float tTPF = 0; public static Timeable timeable=new SimpleTimeable(); @Override protected void initialize(Application app) { getStateManager().attach(new MSTimerAppState()); logBuildInfo(); } static HashMap<String, MTween> anis = new HashMap<>(); public static MTween getAnim(String name){ return anis.get(name); } public static int getCenterX(String name){ return anis.get(name).centerX; } public static int getCenterY(String name){ return anis.get(name).centerY; } public void addAnim(MSContainer msCont, String name, int ani[], int hitbox[], int centerX, int centerY) { anis.put(name,new MTween(msCont, name, ani, hitbox, msCont.numTiles, centerX, centerY)); } public MSContainer initializeContainer(String name) {
// Path: src/main/java/com/pesegato/goldmonkey/Animation.java // public class Animation { // public String id; // public int[] frames; // public int centerX; // public int centerY; // public Animation(String id, int[] frames, int centerX, int centerY){ // this.id=id; // this.frames=frames; // this.centerX=centerX; // this.centerY=centerY; // } // } // // Path: src/main/java/com/pesegato/goldmonkey/Container.java // public class Container { // public String id; // public int size; // public Container(String id, int size){ // this.id=id; // this.size=size; // } // } // // Path: src/main/java/com/pesegato/timing/SimpleTimeable.java // public class SimpleTimeable implements Timeable{ // @Override // public float getClockspeed() { // return 1; // } // } // // Path: src/main/java/com/pesegato/timing/Timeable.java // public interface Timeable { // /** // * // * Implement this interface to have configurable timing. // * // * Time factor: // * 0: time stops // * 1: time runs normally // * &lt;1: time is faster // * &gt;1: time is slower // * // * @return time factor // */ // float getClockspeed(); // } // Path: src/main/java/com/pesegato/MonkeySheet/MonkeySheetAppState.java import com.google.common.base.Charsets; import com.google.common.io.Resources; import com.google.gson.Gson; import com.jme3.app.Application; import com.jme3.app.state.BaseAppState; import com.pesegato.goldmonkey.Animation; import com.pesegato.goldmonkey.Container; import com.pesegato.goldmonkey.GM; import com.pesegato.timing.SimpleTimeable; import com.pesegato.timing.Timeable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.FileNotFoundException; import java.util.HashMap; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.pesegato.MonkeySheet; /** * * @author Pesegato */ public class MonkeySheetAppState extends BaseAppState { static Logger log = LoggerFactory.getLogger( MonkeySheetAppState.class ); private static float tickDuration=0.025f; public static float tTPF = 0; public static Timeable timeable=new SimpleTimeable(); @Override protected void initialize(Application app) { getStateManager().attach(new MSTimerAppState()); logBuildInfo(); } static HashMap<String, MTween> anis = new HashMap<>(); public static MTween getAnim(String name){ return anis.get(name); } public static int getCenterX(String name){ return anis.get(name).centerX; } public static int getCenterY(String name){ return anis.get(name).centerY; } public void addAnim(MSContainer msCont, String name, int ani[], int hitbox[], int centerX, int centerY) { anis.put(name,new MTween(msCont, name, ani, hitbox, msCont.numTiles, centerX, centerY)); } public MSContainer initializeContainer(String name) {
Container c = MonkeySheetAppState.getContainer(name);
Pesegato/MonkeySheet
src/main/java/com/pesegato/MonkeySheet/MonkeySheetAppState.java
// Path: src/main/java/com/pesegato/goldmonkey/Animation.java // public class Animation { // public String id; // public int[] frames; // public int centerX; // public int centerY; // public Animation(String id, int[] frames, int centerX, int centerY){ // this.id=id; // this.frames=frames; // this.centerX=centerX; // this.centerY=centerY; // } // } // // Path: src/main/java/com/pesegato/goldmonkey/Container.java // public class Container { // public String id; // public int size; // public Container(String id, int size){ // this.id=id; // this.size=size; // } // } // // Path: src/main/java/com/pesegato/timing/SimpleTimeable.java // public class SimpleTimeable implements Timeable{ // @Override // public float getClockspeed() { // return 1; // } // } // // Path: src/main/java/com/pesegato/timing/Timeable.java // public interface Timeable { // /** // * // * Implement this interface to have configurable timing. // * // * Time factor: // * 0: time stops // * 1: time runs normally // * &lt;1: time is faster // * &gt;1: time is slower // * // * @return time factor // */ // float getClockspeed(); // }
import com.google.common.base.Charsets; import com.google.common.io.Resources; import com.google.gson.Gson; import com.jme3.app.Application; import com.jme3.app.state.BaseAppState; import com.pesegato.goldmonkey.Animation; import com.pesegato.goldmonkey.Container; import com.pesegato.goldmonkey.GM; import com.pesegato.timing.SimpleTimeable; import com.pesegato.timing.Timeable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.FileNotFoundException; import java.util.HashMap;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.pesegato.MonkeySheet; /** * * @author Pesegato */ public class MonkeySheetAppState extends BaseAppState { static Logger log = LoggerFactory.getLogger( MonkeySheetAppState.class ); private static float tickDuration=0.025f; public static float tTPF = 0; public static Timeable timeable=new SimpleTimeable(); @Override protected void initialize(Application app) { getStateManager().attach(new MSTimerAppState()); logBuildInfo(); } static HashMap<String, MTween> anis = new HashMap<>(); public static MTween getAnim(String name){ return anis.get(name); } public static int getCenterX(String name){ return anis.get(name).centerX; } public static int getCenterY(String name){ return anis.get(name).centerY; } public void addAnim(MSContainer msCont, String name, int ani[], int hitbox[], int centerX, int centerY) { anis.put(name,new MTween(msCont, name, ani, hitbox, msCont.numTiles, centerX, centerY)); } public MSContainer initializeContainer(String name) { Container c = MonkeySheetAppState.getContainer(name); MSContainer container = new MSContainer(c);
// Path: src/main/java/com/pesegato/goldmonkey/Animation.java // public class Animation { // public String id; // public int[] frames; // public int centerX; // public int centerY; // public Animation(String id, int[] frames, int centerX, int centerY){ // this.id=id; // this.frames=frames; // this.centerX=centerX; // this.centerY=centerY; // } // } // // Path: src/main/java/com/pesegato/goldmonkey/Container.java // public class Container { // public String id; // public int size; // public Container(String id, int size){ // this.id=id; // this.size=size; // } // } // // Path: src/main/java/com/pesegato/timing/SimpleTimeable.java // public class SimpleTimeable implements Timeable{ // @Override // public float getClockspeed() { // return 1; // } // } // // Path: src/main/java/com/pesegato/timing/Timeable.java // public interface Timeable { // /** // * // * Implement this interface to have configurable timing. // * // * Time factor: // * 0: time stops // * 1: time runs normally // * &lt;1: time is faster // * &gt;1: time is slower // * // * @return time factor // */ // float getClockspeed(); // } // Path: src/main/java/com/pesegato/MonkeySheet/MonkeySheetAppState.java import com.google.common.base.Charsets; import com.google.common.io.Resources; import com.google.gson.Gson; import com.jme3.app.Application; import com.jme3.app.state.BaseAppState; import com.pesegato.goldmonkey.Animation; import com.pesegato.goldmonkey.Container; import com.pesegato.goldmonkey.GM; import com.pesegato.timing.SimpleTimeable; import com.pesegato.timing.Timeable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.FileNotFoundException; import java.util.HashMap; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.pesegato.MonkeySheet; /** * * @author Pesegato */ public class MonkeySheetAppState extends BaseAppState { static Logger log = LoggerFactory.getLogger( MonkeySheetAppState.class ); private static float tickDuration=0.025f; public static float tTPF = 0; public static Timeable timeable=new SimpleTimeable(); @Override protected void initialize(Application app) { getStateManager().attach(new MSTimerAppState()); logBuildInfo(); } static HashMap<String, MTween> anis = new HashMap<>(); public static MTween getAnim(String name){ return anis.get(name); } public static int getCenterX(String name){ return anis.get(name).centerX; } public static int getCenterY(String name){ return anis.get(name).centerY; } public void addAnim(MSContainer msCont, String name, int ani[], int hitbox[], int centerX, int centerY) { anis.put(name,new MTween(msCont, name, ani, hitbox, msCont.numTiles, centerX, centerY)); } public MSContainer initializeContainer(String name) { Container c = MonkeySheetAppState.getContainer(name); MSContainer container = new MSContainer(c);
for (Animation anim : animationC.get(c)) {
Pesegato/MonkeySheet
src/main/java/com/pesegato/MonkeySheet/actions/MSBodyAction.java
// Path: src/main/java/com/pesegato/MonkeySheet/MSGlobals.java // public static final int SPRITE_SIZE = 256;
import org.dyn4j.dynamics.Body; import org.dyn4j.geometry.Transform; import static com.pesegato.MonkeySheet.MSGlobals.SPRITE_SIZE;
package com.pesegato.MonkeySheet.actions; @Deprecated abstract public class MSBodyAction extends MSAction{ protected Body body; public void setBody(Body body){ this.body=body; } /** * This method moves the body by x * SPRITE_SIZE and y * SPRITE_SIZE * * @param x movement on the X * @param y movement on the Y */ @Override protected void moveSprite(float x, float y) { Transform t=body.getTransform();
// Path: src/main/java/com/pesegato/MonkeySheet/MSGlobals.java // public static final int SPRITE_SIZE = 256; // Path: src/main/java/com/pesegato/MonkeySheet/actions/MSBodyAction.java import org.dyn4j.dynamics.Body; import org.dyn4j.geometry.Transform; import static com.pesegato.MonkeySheet.MSGlobals.SPRITE_SIZE; package com.pesegato.MonkeySheet.actions; @Deprecated abstract public class MSBodyAction extends MSAction{ protected Body body; public void setBody(Body body){ this.body=body; } /** * This method moves the body by x * SPRITE_SIZE and y * SPRITE_SIZE * * @param x movement on the X * @param y movement on the Y */ @Override protected void moveSprite(float x, float y) { Transform t=body.getTransform();
t.setTranslationX(t.getTranslationX()+(x * SPRITE_SIZE));
Pesegato/MonkeySheet
src/main/java/com/pesegato/MonkeySheet/actions/MSActionMachine.java
// Path: src/main/java/com/pesegato/MonkeySheet/MonkeySheetAppState.java // public class MonkeySheetAppState extends BaseAppState { // // static Logger log = LoggerFactory.getLogger( MonkeySheetAppState.class ); // // private static float tickDuration=0.025f; // public static float tTPF = 0; // public static Timeable timeable=new SimpleTimeable(); // // @Override // protected void initialize(Application app) { // getStateManager().attach(new MSTimerAppState()); // logBuildInfo(); // } // // static HashMap<String, MTween> anis = new HashMap<>(); // // public static MTween getAnim(String name){ // return anis.get(name); // } // // public static int getCenterX(String name){ // return anis.get(name).centerX; // } // // public static int getCenterY(String name){ // return anis.get(name).centerY; // } // // public void addAnim(MSContainer msCont, String name, int ani[], int hitbox[], int centerX, int centerY) { // anis.put(name,new MTween(msCont, name, ani, hitbox, msCont.numTiles, centerX, centerY)); // } // // public MSContainer initializeContainer(String name) { // Container c = MonkeySheetAppState.getContainer(name); // MSContainer container = new MSContainer(c); // for (Animation anim : animationC.get(c)) { // loadAnim(container, anim.id); // } // return container; // } // // static HashMap<String, Container> containers; // static HashMap<Container, Animation[]> animationC; // // static Container getContainer(String id) { // if (containers == null) { // try { // containers = new HashMap<>(); // animations = new HashMap<>(); // animationC = new HashMap<>(); // Container[] data = new Gson().fromJson(GM.getJSON("MonkeySheet/Containers"), Container[].class); // for (Container obj : data) { // containers.put(obj.id, obj); // Animation[] aData = new Gson().fromJson(GM.getJSON("MonkeySheet/Animations/" + obj.id), Animation[].class); // for (Animation aniObj : aData) { // animations.put(aniObj.id, aniObj); // } // animationC.put(obj, aData); // } // } catch (FileNotFoundException ex) { // log.error(null, ex); // } // } // return containers.get(id); // } // static HashMap<String, Animation> animations; // // public void loadAnim(MSContainer container, String anim){ // addAnim(container,anim,animations.get(anim).frames,null,animations.get(anim).centerX,animations.get(anim).centerY); // } // // @Override // public void update(float tpf){ // tTPF += tpf*timeable.getClockspeed(); // if (tTPF > tickDuration) { // tTPF = 0; // } // } // // public static void setTickDuration(float tickDuration){ // MonkeySheetAppState.tickDuration=tickDuration; // } // // @Override // protected void cleanup(Application app) { // } // // @Override // protected void onEnable() { // } // // @Override // protected void onDisable() { // } // // private static final String LIBNAME="MonkeySheet"; // // protected void logBuildInfo() { // try { // java.net.URL u = Resources.getResource(LIBNAME+".build.date"); // String build = Resources.toString(u, Charsets.UTF_8); // log.info("MonkeySheet build date: " + build); // log.info("MonkeySheet build version: " + Resources.toString(Resources.getResource(LIBNAME+".build.version"), Charsets.UTF_8)); // } catch( java.io.IOException e ) { // log.error( "Error reading build info", e ); // } // } // }
import com.jme3.renderer.RenderManager; import com.jme3.renderer.ViewPort; import com.jme3.scene.control.AbstractControl; import com.pesegato.MonkeySheet.MonkeySheetAppState; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.pesegato.MonkeySheet.actions; /** * * @author Pesegato * @deprecated use MSFiniteStateMachine instead */ public abstract class MSActionMachine extends AbstractControl { static Logger log = LoggerFactory.getLogger(MSActionMachine.class); MSAction[] actions; MSAction currentAction; public MSActionMachine(MSAction... actions) { initActions(actions); } public void initActions(MSAction... actions){ this.actions = actions; } @Override protected void controlUpdate(float tpf) { if (currentAction == null) { init(); nextAction(); }
// Path: src/main/java/com/pesegato/MonkeySheet/MonkeySheetAppState.java // public class MonkeySheetAppState extends BaseAppState { // // static Logger log = LoggerFactory.getLogger( MonkeySheetAppState.class ); // // private static float tickDuration=0.025f; // public static float tTPF = 0; // public static Timeable timeable=new SimpleTimeable(); // // @Override // protected void initialize(Application app) { // getStateManager().attach(new MSTimerAppState()); // logBuildInfo(); // } // // static HashMap<String, MTween> anis = new HashMap<>(); // // public static MTween getAnim(String name){ // return anis.get(name); // } // // public static int getCenterX(String name){ // return anis.get(name).centerX; // } // // public static int getCenterY(String name){ // return anis.get(name).centerY; // } // // public void addAnim(MSContainer msCont, String name, int ani[], int hitbox[], int centerX, int centerY) { // anis.put(name,new MTween(msCont, name, ani, hitbox, msCont.numTiles, centerX, centerY)); // } // // public MSContainer initializeContainer(String name) { // Container c = MonkeySheetAppState.getContainer(name); // MSContainer container = new MSContainer(c); // for (Animation anim : animationC.get(c)) { // loadAnim(container, anim.id); // } // return container; // } // // static HashMap<String, Container> containers; // static HashMap<Container, Animation[]> animationC; // // static Container getContainer(String id) { // if (containers == null) { // try { // containers = new HashMap<>(); // animations = new HashMap<>(); // animationC = new HashMap<>(); // Container[] data = new Gson().fromJson(GM.getJSON("MonkeySheet/Containers"), Container[].class); // for (Container obj : data) { // containers.put(obj.id, obj); // Animation[] aData = new Gson().fromJson(GM.getJSON("MonkeySheet/Animations/" + obj.id), Animation[].class); // for (Animation aniObj : aData) { // animations.put(aniObj.id, aniObj); // } // animationC.put(obj, aData); // } // } catch (FileNotFoundException ex) { // log.error(null, ex); // } // } // return containers.get(id); // } // static HashMap<String, Animation> animations; // // public void loadAnim(MSContainer container, String anim){ // addAnim(container,anim,animations.get(anim).frames,null,animations.get(anim).centerX,animations.get(anim).centerY); // } // // @Override // public void update(float tpf){ // tTPF += tpf*timeable.getClockspeed(); // if (tTPF > tickDuration) { // tTPF = 0; // } // } // // public static void setTickDuration(float tickDuration){ // MonkeySheetAppState.tickDuration=tickDuration; // } // // @Override // protected void cleanup(Application app) { // } // // @Override // protected void onEnable() { // } // // @Override // protected void onDisable() { // } // // private static final String LIBNAME="MonkeySheet"; // // protected void logBuildInfo() { // try { // java.net.URL u = Resources.getResource(LIBNAME+".build.date"); // String build = Resources.toString(u, Charsets.UTF_8); // log.info("MonkeySheet build date: " + build); // log.info("MonkeySheet build version: " + Resources.toString(Resources.getResource(LIBNAME+".build.version"), Charsets.UTF_8)); // } catch( java.io.IOException e ) { // log.error( "Error reading build info", e ); // } // } // } // Path: src/main/java/com/pesegato/MonkeySheet/actions/MSActionMachine.java import com.jme3.renderer.RenderManager; import com.jme3.renderer.ViewPort; import com.jme3.scene.control.AbstractControl; import com.pesegato.MonkeySheet.MonkeySheetAppState; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.pesegato.MonkeySheet.actions; /** * * @author Pesegato * @deprecated use MSFiniteStateMachine instead */ public abstract class MSActionMachine extends AbstractControl { static Logger log = LoggerFactory.getLogger(MSActionMachine.class); MSAction[] actions; MSAction currentAction; public MSActionMachine(MSAction... actions) { initActions(actions); } public void initActions(MSAction... actions){ this.actions = actions; } @Override protected void controlUpdate(float tpf) { if (currentAction == null) { init(); nextAction(); }
if (MonkeySheetAppState.tTPF == 0) {
Pesegato/MonkeySheet
src/main/java/com/pesegato/MonkeySheet/MSMaterialControl.java
// Path: src/main/java/com/pesegato/MonkeySheet/MonkeySheetAppState.java // static Logger log = LoggerFactory.getLogger( MonkeySheetAppState.class );
import com.jme3.asset.AssetManager; import com.jme3.material.Material; import com.jme3.material.RenderState; import com.jme3.math.ColorRGBA; import com.jme3.renderer.RenderManager; import com.jme3.renderer.ViewPort; import com.jme3.scene.Geometry; import com.jme3.scene.control.AbstractControl; import com.jme3.texture.Texture; import static com.pesegato.MonkeySheet.MonkeySheetAppState.log;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.pesegato.MonkeySheet; /** * @author Pesegato */ public class MSMaterialControl extends AbstractControl { Material material; public String animation; public int position; MSSpriteControl msc; private float alphaValue = 1; private boolean flipped = false; private boolean grayScale = false; private float hueShift = 0; private ColorRGBA fogColor = ColorRGBA.Pink; private float fogIntensity = 0; public MSMaterialControl(AssetManager assetManager, Geometry geo, MSContainer msCont, MSControl msc) { material = new Material(assetManager, "MonkeySheet/MatDefs/Anim.j3md"); Texture[] sheetsX = new Texture[msCont.sheets.length]; for (int i = 0; i < msCont.sheets.length; i++) { long start = System.currentTimeMillis(); long end; System.out.println("MonkeySheet: Now loading " + msCont.sheets[i]); sheetsX[i] = assetManager.loadTexture(msCont.sheets[i]); end = System.currentTimeMillis();
// Path: src/main/java/com/pesegato/MonkeySheet/MonkeySheetAppState.java // static Logger log = LoggerFactory.getLogger( MonkeySheetAppState.class ); // Path: src/main/java/com/pesegato/MonkeySheet/MSMaterialControl.java import com.jme3.asset.AssetManager; import com.jme3.material.Material; import com.jme3.material.RenderState; import com.jme3.math.ColorRGBA; import com.jme3.renderer.RenderManager; import com.jme3.renderer.ViewPort; import com.jme3.scene.Geometry; import com.jme3.scene.control.AbstractControl; import com.jme3.texture.Texture; import static com.pesegato.MonkeySheet.MonkeySheetAppState.log; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.pesegato.MonkeySheet; /** * @author Pesegato */ public class MSMaterialControl extends AbstractControl { Material material; public String animation; public int position; MSSpriteControl msc; private float alphaValue = 1; private boolean flipped = false; private boolean grayScale = false; private float hueShift = 0; private ColorRGBA fogColor = ColorRGBA.Pink; private float fogIntensity = 0; public MSMaterialControl(AssetManager assetManager, Geometry geo, MSContainer msCont, MSControl msc) { material = new Material(assetManager, "MonkeySheet/MatDefs/Anim.j3md"); Texture[] sheetsX = new Texture[msCont.sheets.length]; for (int i = 0; i < msCont.sheets.length; i++) { long start = System.currentTimeMillis(); long end; System.out.println("MonkeySheet: Now loading " + msCont.sheets[i]); sheetsX[i] = assetManager.loadTexture(msCont.sheets[i]); end = System.currentTimeMillis();
log.trace("loaded {}", (end - start));
Pesegato/MonkeySheet
src/main/java/com/pesegato/MonkeySheet/actions/MSAction.java
// Path: src/main/java/com/pesegato/MonkeySheet/MSControl.java // public class MSControl extends MSSpriteControl { // // boolean runOnce = false; // MSAnimationManager animManager; // public MSAction msAction; // // public MSControl() { // } // // public MSControl(String anim, Timeable timeable) { // playForever(anim); // MonkeySheetAppState.timeable = timeable; // } // // public MSControl(MSAnimationManager animManager) { // this.animManager = animManager; // } // // final public void playForever(String ani) { // anim = MonkeySheetAppState.getAnim(ani); // position = 0; // runOnce = false; // if (anim == null) { // log.warn("Running UNINITIALIZED animation {}, GOING TO CRASH VERY SOON!!!", ani); // return; // } // animation = ani; // log.debug("now playing FOREVER animation {}/{}", anim.msCont.name, ani); // } // // public void playOnce(String ani) { // anim = MonkeySheetAppState.getAnim(ani); // position = 0; // runOnce = true; // if (anim == null) { // log.warn("Running UNINITIALIZED animation {}, GOING TO CRASH VERY SOON!!!" + ani); // return; // } // animation = ani; // log.debug("now playing ONCE animation {}/{}", anim.msCont.name, ani); // } // // @Override // protected void controlUpdate(float tpf) { // if (MonkeySheetAppState.tTPF == 0) { // log.trace("position: {}/{} {} - {}", anim.msCont.name, animation, position, anim.anim[position].position); // if (position < anim.anim.length - 1) { // position++; // } else if (runOnce) { // if (animManager != null) { // log.trace("loading animManager {}", animManager); // animManager.whatPlay(this); // } // if (msAction != null) { // log.trace("end of MSAction {}", msAction); // msAction.terminatedAnim(); // msAction.whatPlay(this); // } // } else { // position = 0; // } // } // // } // // public int getCurrentHitbox() { // return anim.hitbox[position]; // } // // @Override // protected void controlRender(RenderManager rm, ViewPort vp) { // } // // } // // Path: src/main/java/com/pesegato/MonkeySheet/MSGlobals.java // public static final int SPRITE_SIZE = 256;
import com.jme3.math.Vector2f; import com.jme3.math.Vector3f; import com.jme3.scene.Geometry; import com.jme3.scene.Spatial; import com.jme3.scene.shape.Quad; import com.pesegato.MonkeySheet.MSControl; import static com.pesegato.MonkeySheet.MSGlobals.SPRITE_SIZE; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.pesegato.MonkeySheet.actions; /** * * @author Pesegato */ public abstract class MSAction { static Logger log = LoggerFactory.getLogger(MSAction.class); protected float msTimer;
// Path: src/main/java/com/pesegato/MonkeySheet/MSControl.java // public class MSControl extends MSSpriteControl { // // boolean runOnce = false; // MSAnimationManager animManager; // public MSAction msAction; // // public MSControl() { // } // // public MSControl(String anim, Timeable timeable) { // playForever(anim); // MonkeySheetAppState.timeable = timeable; // } // // public MSControl(MSAnimationManager animManager) { // this.animManager = animManager; // } // // final public void playForever(String ani) { // anim = MonkeySheetAppState.getAnim(ani); // position = 0; // runOnce = false; // if (anim == null) { // log.warn("Running UNINITIALIZED animation {}, GOING TO CRASH VERY SOON!!!", ani); // return; // } // animation = ani; // log.debug("now playing FOREVER animation {}/{}", anim.msCont.name, ani); // } // // public void playOnce(String ani) { // anim = MonkeySheetAppState.getAnim(ani); // position = 0; // runOnce = true; // if (anim == null) { // log.warn("Running UNINITIALIZED animation {}, GOING TO CRASH VERY SOON!!!" + ani); // return; // } // animation = ani; // log.debug("now playing ONCE animation {}/{}", anim.msCont.name, ani); // } // // @Override // protected void controlUpdate(float tpf) { // if (MonkeySheetAppState.tTPF == 0) { // log.trace("position: {}/{} {} - {}", anim.msCont.name, animation, position, anim.anim[position].position); // if (position < anim.anim.length - 1) { // position++; // } else if (runOnce) { // if (animManager != null) { // log.trace("loading animManager {}", animManager); // animManager.whatPlay(this); // } // if (msAction != null) { // log.trace("end of MSAction {}", msAction); // msAction.terminatedAnim(); // msAction.whatPlay(this); // } // } else { // position = 0; // } // } // // } // // public int getCurrentHitbox() { // return anim.hitbox[position]; // } // // @Override // protected void controlRender(RenderManager rm, ViewPort vp) { // } // // } // // Path: src/main/java/com/pesegato/MonkeySheet/MSGlobals.java // public static final int SPRITE_SIZE = 256; // Path: src/main/java/com/pesegato/MonkeySheet/actions/MSAction.java import com.jme3.math.Vector2f; import com.jme3.math.Vector3f; import com.jme3.scene.Geometry; import com.jme3.scene.Spatial; import com.jme3.scene.shape.Quad; import com.pesegato.MonkeySheet.MSControl; import static com.pesegato.MonkeySheet.MSGlobals.SPRITE_SIZE; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.pesegato.MonkeySheet.actions; /** * * @author Pesegato */ public abstract class MSAction { static Logger log = LoggerFactory.getLogger(MSAction.class); protected float msTimer;
protected MSControl msc;
Pesegato/MonkeySheet
src/main/java/com/pesegato/MonkeySheet/actions/MSAction.java
// Path: src/main/java/com/pesegato/MonkeySheet/MSControl.java // public class MSControl extends MSSpriteControl { // // boolean runOnce = false; // MSAnimationManager animManager; // public MSAction msAction; // // public MSControl() { // } // // public MSControl(String anim, Timeable timeable) { // playForever(anim); // MonkeySheetAppState.timeable = timeable; // } // // public MSControl(MSAnimationManager animManager) { // this.animManager = animManager; // } // // final public void playForever(String ani) { // anim = MonkeySheetAppState.getAnim(ani); // position = 0; // runOnce = false; // if (anim == null) { // log.warn("Running UNINITIALIZED animation {}, GOING TO CRASH VERY SOON!!!", ani); // return; // } // animation = ani; // log.debug("now playing FOREVER animation {}/{}", anim.msCont.name, ani); // } // // public void playOnce(String ani) { // anim = MonkeySheetAppState.getAnim(ani); // position = 0; // runOnce = true; // if (anim == null) { // log.warn("Running UNINITIALIZED animation {}, GOING TO CRASH VERY SOON!!!" + ani); // return; // } // animation = ani; // log.debug("now playing ONCE animation {}/{}", anim.msCont.name, ani); // } // // @Override // protected void controlUpdate(float tpf) { // if (MonkeySheetAppState.tTPF == 0) { // log.trace("position: {}/{} {} - {}", anim.msCont.name, animation, position, anim.anim[position].position); // if (position < anim.anim.length - 1) { // position++; // } else if (runOnce) { // if (animManager != null) { // log.trace("loading animManager {}", animManager); // animManager.whatPlay(this); // } // if (msAction != null) { // log.trace("end of MSAction {}", msAction); // msAction.terminatedAnim(); // msAction.whatPlay(this); // } // } else { // position = 0; // } // } // // } // // public int getCurrentHitbox() { // return anim.hitbox[position]; // } // // @Override // protected void controlRender(RenderManager rm, ViewPort vp) { // } // // } // // Path: src/main/java/com/pesegato/MonkeySheet/MSGlobals.java // public static final int SPRITE_SIZE = 256;
import com.jme3.math.Vector2f; import com.jme3.math.Vector3f; import com.jme3.scene.Geometry; import com.jme3.scene.Spatial; import com.jme3.scene.shape.Quad; import com.pesegato.MonkeySheet.MSControl; import static com.pesegato.MonkeySheet.MSGlobals.SPRITE_SIZE; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.pesegato.MonkeySheet.actions; /** * * @author Pesegato */ public abstract class MSAction { static Logger log = LoggerFactory.getLogger(MSAction.class); protected float msTimer; protected MSControl msc; protected Spatial spatial; public boolean hasEnded = false; public boolean uncalledFinish = true; public static Geometry createGeometry(String name, float scaleX, float scaleY) {
// Path: src/main/java/com/pesegato/MonkeySheet/MSControl.java // public class MSControl extends MSSpriteControl { // // boolean runOnce = false; // MSAnimationManager animManager; // public MSAction msAction; // // public MSControl() { // } // // public MSControl(String anim, Timeable timeable) { // playForever(anim); // MonkeySheetAppState.timeable = timeable; // } // // public MSControl(MSAnimationManager animManager) { // this.animManager = animManager; // } // // final public void playForever(String ani) { // anim = MonkeySheetAppState.getAnim(ani); // position = 0; // runOnce = false; // if (anim == null) { // log.warn("Running UNINITIALIZED animation {}, GOING TO CRASH VERY SOON!!!", ani); // return; // } // animation = ani; // log.debug("now playing FOREVER animation {}/{}", anim.msCont.name, ani); // } // // public void playOnce(String ani) { // anim = MonkeySheetAppState.getAnim(ani); // position = 0; // runOnce = true; // if (anim == null) { // log.warn("Running UNINITIALIZED animation {}, GOING TO CRASH VERY SOON!!!" + ani); // return; // } // animation = ani; // log.debug("now playing ONCE animation {}/{}", anim.msCont.name, ani); // } // // @Override // protected void controlUpdate(float tpf) { // if (MonkeySheetAppState.tTPF == 0) { // log.trace("position: {}/{} {} - {}", anim.msCont.name, animation, position, anim.anim[position].position); // if (position < anim.anim.length - 1) { // position++; // } else if (runOnce) { // if (animManager != null) { // log.trace("loading animManager {}", animManager); // animManager.whatPlay(this); // } // if (msAction != null) { // log.trace("end of MSAction {}", msAction); // msAction.terminatedAnim(); // msAction.whatPlay(this); // } // } else { // position = 0; // } // } // // } // // public int getCurrentHitbox() { // return anim.hitbox[position]; // } // // @Override // protected void controlRender(RenderManager rm, ViewPort vp) { // } // // } // // Path: src/main/java/com/pesegato/MonkeySheet/MSGlobals.java // public static final int SPRITE_SIZE = 256; // Path: src/main/java/com/pesegato/MonkeySheet/actions/MSAction.java import com.jme3.math.Vector2f; import com.jme3.math.Vector3f; import com.jme3.scene.Geometry; import com.jme3.scene.Spatial; import com.jme3.scene.shape.Quad; import com.pesegato.MonkeySheet.MSControl; import static com.pesegato.MonkeySheet.MSGlobals.SPRITE_SIZE; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.pesegato.MonkeySheet.actions; /** * * @author Pesegato */ public abstract class MSAction { static Logger log = LoggerFactory.getLogger(MSAction.class); protected float msTimer; protected MSControl msc; protected Spatial spatial; public boolean hasEnded = false; public boolean uncalledFinish = true; public static Geometry createGeometry(String name, float scaleX, float scaleY) {
return new Geometry(name, new Quad(SPRITE_SIZE * scaleX, SPRITE_SIZE * scaleY));
Pesegato/MonkeySheet
src/main/java/com/pesegato/MonkeySheet/MSContainer.java
// Path: src/main/java/com/pesegato/goldmonkey/Animation.java // public class Animation { // public String id; // public int[] frames; // public int centerX; // public int centerY; // public Animation(String id, int[] frames, int centerX, int centerY){ // this.id=id; // this.frames=frames; // this.centerX=centerX; // this.centerY=centerY; // } // } // // Path: src/main/java/com/pesegato/goldmonkey/Container.java // public class Container { // public String id; // public int size; // public Container(String id, int size){ // this.id=id; // this.size=size; // } // }
import com.pesegato.goldmonkey.Container; import com.pesegato.goldmonkey.Animation;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.pesegato.MonkeySheet; /** * @author Pesegato */ public class MSContainer { public int numTiles; String[] sheets; String name;
// Path: src/main/java/com/pesegato/goldmonkey/Animation.java // public class Animation { // public String id; // public int[] frames; // public int centerX; // public int centerY; // public Animation(String id, int[] frames, int centerX, int centerY){ // this.id=id; // this.frames=frames; // this.centerX=centerX; // this.centerY=centerY; // } // } // // Path: src/main/java/com/pesegato/goldmonkey/Container.java // public class Container { // public String id; // public int size; // public Container(String id, int size){ // this.id=id; // this.size=size; // } // } // Path: src/main/java/com/pesegato/MonkeySheet/MSContainer.java import com.pesegato.goldmonkey.Container; import com.pesegato.goldmonkey.Animation; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.pesegato.MonkeySheet; /** * @author Pesegato */ public class MSContainer { public int numTiles; String[] sheets; String name;
Container c;
Pesegato/MonkeySheet
src/main/java/com/pesegato/MonkeySheet/MSContainer.java
// Path: src/main/java/com/pesegato/goldmonkey/Animation.java // public class Animation { // public String id; // public int[] frames; // public int centerX; // public int centerY; // public Animation(String id, int[] frames, int centerX, int centerY){ // this.id=id; // this.frames=frames; // this.centerX=centerX; // this.centerY=centerY; // } // } // // Path: src/main/java/com/pesegato/goldmonkey/Container.java // public class Container { // public String id; // public int size; // public Container(String id, int size){ // this.id=id; // this.size=size; // } // }
import com.pesegato.goldmonkey.Container; import com.pesegato.goldmonkey.Animation;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.pesegato.MonkeySheet; /** * @author Pesegato */ public class MSContainer { public int numTiles; String[] sheets; String name; Container c; public MSContainer(Container c) { this.numTiles = c.size; this.name = c.id; setPath("Textures/MonkeySheet/"); this.c = c; }
// Path: src/main/java/com/pesegato/goldmonkey/Animation.java // public class Animation { // public String id; // public int[] frames; // public int centerX; // public int centerY; // public Animation(String id, int[] frames, int centerX, int centerY){ // this.id=id; // this.frames=frames; // this.centerX=centerX; // this.centerY=centerY; // } // } // // Path: src/main/java/com/pesegato/goldmonkey/Container.java // public class Container { // public String id; // public int size; // public Container(String id, int size){ // this.id=id; // this.size=size; // } // } // Path: src/main/java/com/pesegato/MonkeySheet/MSContainer.java import com.pesegato.goldmonkey.Container; import com.pesegato.goldmonkey.Animation; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.pesegato.MonkeySheet; /** * @author Pesegato */ public class MSContainer { public int numTiles; String[] sheets; String name; Container c; public MSContainer(Container c) { this.numTiles = c.size; this.name = c.id; setPath("Textures/MonkeySheet/"); this.c = c; }
public Animation[] getAnimList() {
Pesegato/MonkeySheet
src/main/java/com/pesegato/collision/Dyn4JShapeControl.java
// Path: src/main/java/com/pesegato/collision/hitbox/HBRect.java // public class HBRect extends DebuggableBody { // String name = ""; // float w, h; // public long id; // // public HBRect(long id, float wP, float hP) { // this.id = id; // this.w = wP * SPRITE_SIZE; // this.h = hP * SPRITE_SIZE; // addFixture(new BodyFixture(new Rectangle(new Float(w), new Float(h)))); // } // // public HBRect(String name, long id, float wP, float hP) { // this.name = name; // this.id = id; // this.w = wP * SPRITE_SIZE; // this.h = hP * SPRITE_SIZE; // addFixture(new BodyFixture(new Rectangle(new Float(w), new Float(h)))); // } // // public HBRect(long id, Filter filter, int w, int h) { // this.id = id; // this.w = w; // this.h = h; // BodyFixture bf=new BodyFixture(new Rectangle(new Float(w), new Float(h))); // bf.setFilter(filter); // addFixture(bf); // } // // @Deprecated // public Node getNode(AssetManager assetM, ColorRGBA color) { // Node n = new Node(); // if (SHOW_HITBOX) { // n.attachChild(makeHitboxMarker(assetM, n, color)); // } // return n; // } // // public Convex getConvex() { // return new Rectangle(new Float(w), new Float(h)); // } // // @Deprecated // public Dyn4JShapeControl getControl() { // return new Dyn4JShapeControl(getConvex(), MassType.INFINITE, this); // } // // @Override // public Geometry makeHitboxMarker(AssetManager assetManager, Node n, ColorRGBA color) { // Material mat = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md"); // ColorRGBA col = color.clone(); // col.a = .5f; // mat.setColor("Color", col); // mat.getAdditionalRenderState().setBlendMode(RenderState.BlendMode.Alpha); // Geometry geo = new Geometry(name, new Quad(w, h)); // geo.setMaterial(mat); // geo.setLocalTranslation(-w / 2, -h / 2, 0); // return geo; // } // }
import com.jme3.math.Quaternion; import com.jme3.math.Vector3f; import com.jme3.renderer.RenderManager; import com.jme3.renderer.ViewPort; import com.jme3.scene.Spatial; import com.pesegato.collision.hitbox.HBRect; import org.dyn4j.collision.CategoryFilter; import org.dyn4j.collision.broadphase.BroadphaseDetector; import org.dyn4j.dynamics.Body; import org.dyn4j.dynamics.BodyFixture; import org.dyn4j.geometry.Convex; import org.dyn4j.geometry.MassType; import org.dyn4j.geometry.Transform; import org.dyn4j.geometry.Vector2;
package com.pesegato.collision; @Deprecated public class Dyn4JShapeControl extends IDyn4JControl { protected Body body; BodyFixture fixture; //private World world; BroadphaseDetector broadphase;
// Path: src/main/java/com/pesegato/collision/hitbox/HBRect.java // public class HBRect extends DebuggableBody { // String name = ""; // float w, h; // public long id; // // public HBRect(long id, float wP, float hP) { // this.id = id; // this.w = wP * SPRITE_SIZE; // this.h = hP * SPRITE_SIZE; // addFixture(new BodyFixture(new Rectangle(new Float(w), new Float(h)))); // } // // public HBRect(String name, long id, float wP, float hP) { // this.name = name; // this.id = id; // this.w = wP * SPRITE_SIZE; // this.h = hP * SPRITE_SIZE; // addFixture(new BodyFixture(new Rectangle(new Float(w), new Float(h)))); // } // // public HBRect(long id, Filter filter, int w, int h) { // this.id = id; // this.w = w; // this.h = h; // BodyFixture bf=new BodyFixture(new Rectangle(new Float(w), new Float(h))); // bf.setFilter(filter); // addFixture(bf); // } // // @Deprecated // public Node getNode(AssetManager assetM, ColorRGBA color) { // Node n = new Node(); // if (SHOW_HITBOX) { // n.attachChild(makeHitboxMarker(assetM, n, color)); // } // return n; // } // // public Convex getConvex() { // return new Rectangle(new Float(w), new Float(h)); // } // // @Deprecated // public Dyn4JShapeControl getControl() { // return new Dyn4JShapeControl(getConvex(), MassType.INFINITE, this); // } // // @Override // public Geometry makeHitboxMarker(AssetManager assetManager, Node n, ColorRGBA color) { // Material mat = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md"); // ColorRGBA col = color.clone(); // col.a = .5f; // mat.setColor("Color", col); // mat.getAdditionalRenderState().setBlendMode(RenderState.BlendMode.Alpha); // Geometry geo = new Geometry(name, new Quad(w, h)); // geo.setMaterial(mat); // geo.setLocalTranslation(-w / 2, -h / 2, 0); // return geo; // } // } // Path: src/main/java/com/pesegato/collision/Dyn4JShapeControl.java import com.jme3.math.Quaternion; import com.jme3.math.Vector3f; import com.jme3.renderer.RenderManager; import com.jme3.renderer.ViewPort; import com.jme3.scene.Spatial; import com.pesegato.collision.hitbox.HBRect; import org.dyn4j.collision.CategoryFilter; import org.dyn4j.collision.broadphase.BroadphaseDetector; import org.dyn4j.dynamics.Body; import org.dyn4j.dynamics.BodyFixture; import org.dyn4j.geometry.Convex; import org.dyn4j.geometry.MassType; import org.dyn4j.geometry.Transform; import org.dyn4j.geometry.Vector2; package com.pesegato.collision; @Deprecated public class Dyn4JShapeControl extends IDyn4JControl { protected Body body; BodyFixture fixture; //private World world; BroadphaseDetector broadphase;
HBRect hbRect;
Pesegato/MonkeySheet
src/main/java/com/pesegato/collision/SampleD4J.java
// Path: src/main/java/com/pesegato/collision/hitbox/HBRect.java // public class HBRect extends DebuggableBody { // String name = ""; // float w, h; // public long id; // // public HBRect(long id, float wP, float hP) { // this.id = id; // this.w = wP * SPRITE_SIZE; // this.h = hP * SPRITE_SIZE; // addFixture(new BodyFixture(new Rectangle(new Float(w), new Float(h)))); // } // // public HBRect(String name, long id, float wP, float hP) { // this.name = name; // this.id = id; // this.w = wP * SPRITE_SIZE; // this.h = hP * SPRITE_SIZE; // addFixture(new BodyFixture(new Rectangle(new Float(w), new Float(h)))); // } // // public HBRect(long id, Filter filter, int w, int h) { // this.id = id; // this.w = w; // this.h = h; // BodyFixture bf=new BodyFixture(new Rectangle(new Float(w), new Float(h))); // bf.setFilter(filter); // addFixture(bf); // } // // @Deprecated // public Node getNode(AssetManager assetM, ColorRGBA color) { // Node n = new Node(); // if (SHOW_HITBOX) { // n.attachChild(makeHitboxMarker(assetM, n, color)); // } // return n; // } // // public Convex getConvex() { // return new Rectangle(new Float(w), new Float(h)); // } // // @Deprecated // public Dyn4JShapeControl getControl() { // return new Dyn4JShapeControl(getConvex(), MassType.INFINITE, this); // } // // @Override // public Geometry makeHitboxMarker(AssetManager assetManager, Node n, ColorRGBA color) { // Material mat = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md"); // ColorRGBA col = color.clone(); // col.a = .5f; // mat.setColor("Color", col); // mat.getAdditionalRenderState().setBlendMode(RenderState.BlendMode.Alpha); // Geometry geo = new Geometry(name, new Quad(w, h)); // geo.setMaterial(mat); // geo.setLocalTranslation(-w / 2, -h / 2, 0); // return geo; // } // }
import com.jme3.app.Application; import com.jme3.app.SimpleApplication; import com.jme3.app.state.BaseAppState; import com.jme3.math.ColorRGBA; import com.jme3.renderer.RenderManager; import com.jme3.renderer.ViewPort; import com.jme3.scene.Node; import com.jme3.scene.control.AbstractControl; import com.pesegato.collision.hitbox.HBRect; import org.dyn4j.dynamics.Body; import org.dyn4j.geometry.Vector2;
package com.pesegato.collision; public class SampleD4J extends SimpleApplication { public static void main(String[] args){ SampleD4J app = new SampleD4J(); //app.setShowSettings(false); app.start(); // start the game } Dyn4jMEAppState das; @Override public void simpleInitApp() { das = new Dyn4jMEAppState(); stateManager.attachAll(das,new MainAppState()); } class MainAppState extends BaseAppState{ @Override protected void initialize(Application app) { float boxSize = .5f;
// Path: src/main/java/com/pesegato/collision/hitbox/HBRect.java // public class HBRect extends DebuggableBody { // String name = ""; // float w, h; // public long id; // // public HBRect(long id, float wP, float hP) { // this.id = id; // this.w = wP * SPRITE_SIZE; // this.h = hP * SPRITE_SIZE; // addFixture(new BodyFixture(new Rectangle(new Float(w), new Float(h)))); // } // // public HBRect(String name, long id, float wP, float hP) { // this.name = name; // this.id = id; // this.w = wP * SPRITE_SIZE; // this.h = hP * SPRITE_SIZE; // addFixture(new BodyFixture(new Rectangle(new Float(w), new Float(h)))); // } // // public HBRect(long id, Filter filter, int w, int h) { // this.id = id; // this.w = w; // this.h = h; // BodyFixture bf=new BodyFixture(new Rectangle(new Float(w), new Float(h))); // bf.setFilter(filter); // addFixture(bf); // } // // @Deprecated // public Node getNode(AssetManager assetM, ColorRGBA color) { // Node n = new Node(); // if (SHOW_HITBOX) { // n.attachChild(makeHitboxMarker(assetM, n, color)); // } // return n; // } // // public Convex getConvex() { // return new Rectangle(new Float(w), new Float(h)); // } // // @Deprecated // public Dyn4JShapeControl getControl() { // return new Dyn4JShapeControl(getConvex(), MassType.INFINITE, this); // } // // @Override // public Geometry makeHitboxMarker(AssetManager assetManager, Node n, ColorRGBA color) { // Material mat = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md"); // ColorRGBA col = color.clone(); // col.a = .5f; // mat.setColor("Color", col); // mat.getAdditionalRenderState().setBlendMode(RenderState.BlendMode.Alpha); // Geometry geo = new Geometry(name, new Quad(w, h)); // geo.setMaterial(mat); // geo.setLocalTranslation(-w / 2, -h / 2, 0); // return geo; // } // } // Path: src/main/java/com/pesegato/collision/SampleD4J.java import com.jme3.app.Application; import com.jme3.app.SimpleApplication; import com.jme3.app.state.BaseAppState; import com.jme3.math.ColorRGBA; import com.jme3.renderer.RenderManager; import com.jme3.renderer.ViewPort; import com.jme3.scene.Node; import com.jme3.scene.control.AbstractControl; import com.pesegato.collision.hitbox.HBRect; import org.dyn4j.dynamics.Body; import org.dyn4j.geometry.Vector2; package com.pesegato.collision; public class SampleD4J extends SimpleApplication { public static void main(String[] args){ SampleD4J app = new SampleD4J(); //app.setShowSettings(false); app.start(); // start the game } Dyn4jMEAppState das; @Override public void simpleInitApp() { das = new Dyn4jMEAppState(); stateManager.attachAll(das,new MainAppState()); } class MainAppState extends BaseAppState{ @Override protected void initialize(Application app) { float boxSize = .5f;
HBRect hbRect=new HBRect(1,boxSize,.5f);
Pesegato/MonkeySheet
src/main/java/com/pesegato/collision/SampleD4J2.java
// Path: src/main/java/com/pesegato/collision/hitbox/HBCircle.java // public class HBCircle extends DebuggableBody { // String name = ""; // int radius; // public long id; // // public HBCircle(long id, int radius) { // this.id = id; // this.radius = radius; // addFixture(new BodyFixture(new Circle(radius))); // } // // public HBCircle(String name, long id, int radius) { // this.name = name; // this.id = id; // this.radius = radius; // addFixture(new BodyFixture(new Circle(radius))); // } // // public HBCircle(long id, Filter filter, int radius) { // this.id = id; // this.radius = radius; // BodyFixture bf=new BodyFixture(new Circle(radius)); // bf.setFilter(filter); // addFixture(bf); // } // // @Deprecated // public Node getNode(AssetManager assetM, ColorRGBA color) { // Node n = new Node(); // if (SHOW_HITBOX) { // n.attachChild(makeHitboxMarker(assetM, n, color)); // } // return n; // } // // public Convex getConvex() { // return new Circle(radius); // } // // @Override // public Geometry makeHitboxMarker(AssetManager assetManager, Node n, ColorRGBA color) { // Material mat = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md"); // ColorRGBA col = color.clone(); // col.a = .5f; // mat.setColor("Color", col); // mat.getAdditionalRenderState().setBlendMode(RenderState.BlendMode.Alpha); // Geometry geo = new Geometry(name, new Prism(radius , 5,12)); // geo.setMaterial(mat); // geo.rotate(FastMath.PI/2,0,0); // return geo; // } // } // // Path: src/main/java/com/pesegato/collision/hitbox/HBRect.java // public class HBRect extends DebuggableBody { // String name = ""; // float w, h; // public long id; // // public HBRect(long id, float wP, float hP) { // this.id = id; // this.w = wP * SPRITE_SIZE; // this.h = hP * SPRITE_SIZE; // addFixture(new BodyFixture(new Rectangle(new Float(w), new Float(h)))); // } // // public HBRect(String name, long id, float wP, float hP) { // this.name = name; // this.id = id; // this.w = wP * SPRITE_SIZE; // this.h = hP * SPRITE_SIZE; // addFixture(new BodyFixture(new Rectangle(new Float(w), new Float(h)))); // } // // public HBRect(long id, Filter filter, int w, int h) { // this.id = id; // this.w = w; // this.h = h; // BodyFixture bf=new BodyFixture(new Rectangle(new Float(w), new Float(h))); // bf.setFilter(filter); // addFixture(bf); // } // // @Deprecated // public Node getNode(AssetManager assetM, ColorRGBA color) { // Node n = new Node(); // if (SHOW_HITBOX) { // n.attachChild(makeHitboxMarker(assetM, n, color)); // } // return n; // } // // public Convex getConvex() { // return new Rectangle(new Float(w), new Float(h)); // } // // @Deprecated // public Dyn4JShapeControl getControl() { // return new Dyn4JShapeControl(getConvex(), MassType.INFINITE, this); // } // // @Override // public Geometry makeHitboxMarker(AssetManager assetManager, Node n, ColorRGBA color) { // Material mat = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md"); // ColorRGBA col = color.clone(); // col.a = .5f; // mat.setColor("Color", col); // mat.getAdditionalRenderState().setBlendMode(RenderState.BlendMode.Alpha); // Geometry geo = new Geometry(name, new Quad(w, h)); // geo.setMaterial(mat); // geo.setLocalTranslation(-w / 2, -h / 2, 0); // return geo; // } // }
import com.jme3.app.Application; import com.jme3.app.SimpleApplication; import com.jme3.app.state.BaseAppState; import com.jme3.math.ColorRGBA; import com.jme3.renderer.RenderManager; import com.jme3.renderer.ViewPort; import com.jme3.scene.Node; import com.jme3.scene.control.AbstractControl; import com.pesegato.collision.hitbox.HBCircle; import com.pesegato.collision.hitbox.HBRect; import org.dyn4j.dynamics.Body; import org.dyn4j.geometry.MassType; import org.dyn4j.geometry.Vector2;
package com.pesegato.collision; public class SampleD4J2 extends SimpleApplication { public static void main(String[] args) { SampleD4J2 app = new SampleD4J2(); //app.setShowSettings(false); app.start(); // start the game } D4JSpace2 d4j; @Override public void simpleInitApp() { d4j = new D4JSpace2(); stateManager.attachAll(d4j, new D4JSpaceDebugAppState(), new MainAppState()); }
// Path: src/main/java/com/pesegato/collision/hitbox/HBCircle.java // public class HBCircle extends DebuggableBody { // String name = ""; // int radius; // public long id; // // public HBCircle(long id, int radius) { // this.id = id; // this.radius = radius; // addFixture(new BodyFixture(new Circle(radius))); // } // // public HBCircle(String name, long id, int radius) { // this.name = name; // this.id = id; // this.radius = radius; // addFixture(new BodyFixture(new Circle(radius))); // } // // public HBCircle(long id, Filter filter, int radius) { // this.id = id; // this.radius = radius; // BodyFixture bf=new BodyFixture(new Circle(radius)); // bf.setFilter(filter); // addFixture(bf); // } // // @Deprecated // public Node getNode(AssetManager assetM, ColorRGBA color) { // Node n = new Node(); // if (SHOW_HITBOX) { // n.attachChild(makeHitboxMarker(assetM, n, color)); // } // return n; // } // // public Convex getConvex() { // return new Circle(radius); // } // // @Override // public Geometry makeHitboxMarker(AssetManager assetManager, Node n, ColorRGBA color) { // Material mat = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md"); // ColorRGBA col = color.clone(); // col.a = .5f; // mat.setColor("Color", col); // mat.getAdditionalRenderState().setBlendMode(RenderState.BlendMode.Alpha); // Geometry geo = new Geometry(name, new Prism(radius , 5,12)); // geo.setMaterial(mat); // geo.rotate(FastMath.PI/2,0,0); // return geo; // } // } // // Path: src/main/java/com/pesegato/collision/hitbox/HBRect.java // public class HBRect extends DebuggableBody { // String name = ""; // float w, h; // public long id; // // public HBRect(long id, float wP, float hP) { // this.id = id; // this.w = wP * SPRITE_SIZE; // this.h = hP * SPRITE_SIZE; // addFixture(new BodyFixture(new Rectangle(new Float(w), new Float(h)))); // } // // public HBRect(String name, long id, float wP, float hP) { // this.name = name; // this.id = id; // this.w = wP * SPRITE_SIZE; // this.h = hP * SPRITE_SIZE; // addFixture(new BodyFixture(new Rectangle(new Float(w), new Float(h)))); // } // // public HBRect(long id, Filter filter, int w, int h) { // this.id = id; // this.w = w; // this.h = h; // BodyFixture bf=new BodyFixture(new Rectangle(new Float(w), new Float(h))); // bf.setFilter(filter); // addFixture(bf); // } // // @Deprecated // public Node getNode(AssetManager assetM, ColorRGBA color) { // Node n = new Node(); // if (SHOW_HITBOX) { // n.attachChild(makeHitboxMarker(assetM, n, color)); // } // return n; // } // // public Convex getConvex() { // return new Rectangle(new Float(w), new Float(h)); // } // // @Deprecated // public Dyn4JShapeControl getControl() { // return new Dyn4JShapeControl(getConvex(), MassType.INFINITE, this); // } // // @Override // public Geometry makeHitboxMarker(AssetManager assetManager, Node n, ColorRGBA color) { // Material mat = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md"); // ColorRGBA col = color.clone(); // col.a = .5f; // mat.setColor("Color", col); // mat.getAdditionalRenderState().setBlendMode(RenderState.BlendMode.Alpha); // Geometry geo = new Geometry(name, new Quad(w, h)); // geo.setMaterial(mat); // geo.setLocalTranslation(-w / 2, -h / 2, 0); // return geo; // } // } // Path: src/main/java/com/pesegato/collision/SampleD4J2.java import com.jme3.app.Application; import com.jme3.app.SimpleApplication; import com.jme3.app.state.BaseAppState; import com.jme3.math.ColorRGBA; import com.jme3.renderer.RenderManager; import com.jme3.renderer.ViewPort; import com.jme3.scene.Node; import com.jme3.scene.control.AbstractControl; import com.pesegato.collision.hitbox.HBCircle; import com.pesegato.collision.hitbox.HBRect; import org.dyn4j.dynamics.Body; import org.dyn4j.geometry.MassType; import org.dyn4j.geometry.Vector2; package com.pesegato.collision; public class SampleD4J2 extends SimpleApplication { public static void main(String[] args) { SampleD4J2 app = new SampleD4J2(); //app.setShowSettings(false); app.start(); // start the game } D4JSpace2 d4j; @Override public void simpleInitApp() { d4j = new D4JSpace2(); stateManager.attachAll(d4j, new D4JSpaceDebugAppState(), new MainAppState()); }
HBRect hbRect;
Pesegato/MonkeySheet
src/main/java/com/pesegato/collision/SampleD4J2.java
// Path: src/main/java/com/pesegato/collision/hitbox/HBCircle.java // public class HBCircle extends DebuggableBody { // String name = ""; // int radius; // public long id; // // public HBCircle(long id, int radius) { // this.id = id; // this.radius = radius; // addFixture(new BodyFixture(new Circle(radius))); // } // // public HBCircle(String name, long id, int radius) { // this.name = name; // this.id = id; // this.radius = radius; // addFixture(new BodyFixture(new Circle(radius))); // } // // public HBCircle(long id, Filter filter, int radius) { // this.id = id; // this.radius = radius; // BodyFixture bf=new BodyFixture(new Circle(radius)); // bf.setFilter(filter); // addFixture(bf); // } // // @Deprecated // public Node getNode(AssetManager assetM, ColorRGBA color) { // Node n = new Node(); // if (SHOW_HITBOX) { // n.attachChild(makeHitboxMarker(assetM, n, color)); // } // return n; // } // // public Convex getConvex() { // return new Circle(radius); // } // // @Override // public Geometry makeHitboxMarker(AssetManager assetManager, Node n, ColorRGBA color) { // Material mat = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md"); // ColorRGBA col = color.clone(); // col.a = .5f; // mat.setColor("Color", col); // mat.getAdditionalRenderState().setBlendMode(RenderState.BlendMode.Alpha); // Geometry geo = new Geometry(name, new Prism(radius , 5,12)); // geo.setMaterial(mat); // geo.rotate(FastMath.PI/2,0,0); // return geo; // } // } // // Path: src/main/java/com/pesegato/collision/hitbox/HBRect.java // public class HBRect extends DebuggableBody { // String name = ""; // float w, h; // public long id; // // public HBRect(long id, float wP, float hP) { // this.id = id; // this.w = wP * SPRITE_SIZE; // this.h = hP * SPRITE_SIZE; // addFixture(new BodyFixture(new Rectangle(new Float(w), new Float(h)))); // } // // public HBRect(String name, long id, float wP, float hP) { // this.name = name; // this.id = id; // this.w = wP * SPRITE_SIZE; // this.h = hP * SPRITE_SIZE; // addFixture(new BodyFixture(new Rectangle(new Float(w), new Float(h)))); // } // // public HBRect(long id, Filter filter, int w, int h) { // this.id = id; // this.w = w; // this.h = h; // BodyFixture bf=new BodyFixture(new Rectangle(new Float(w), new Float(h))); // bf.setFilter(filter); // addFixture(bf); // } // // @Deprecated // public Node getNode(AssetManager assetM, ColorRGBA color) { // Node n = new Node(); // if (SHOW_HITBOX) { // n.attachChild(makeHitboxMarker(assetM, n, color)); // } // return n; // } // // public Convex getConvex() { // return new Rectangle(new Float(w), new Float(h)); // } // // @Deprecated // public Dyn4JShapeControl getControl() { // return new Dyn4JShapeControl(getConvex(), MassType.INFINITE, this); // } // // @Override // public Geometry makeHitboxMarker(AssetManager assetManager, Node n, ColorRGBA color) { // Material mat = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md"); // ColorRGBA col = color.clone(); // col.a = .5f; // mat.setColor("Color", col); // mat.getAdditionalRenderState().setBlendMode(RenderState.BlendMode.Alpha); // Geometry geo = new Geometry(name, new Quad(w, h)); // geo.setMaterial(mat); // geo.setLocalTranslation(-w / 2, -h / 2, 0); // return geo; // } // }
import com.jme3.app.Application; import com.jme3.app.SimpleApplication; import com.jme3.app.state.BaseAppState; import com.jme3.math.ColorRGBA; import com.jme3.renderer.RenderManager; import com.jme3.renderer.ViewPort; import com.jme3.scene.Node; import com.jme3.scene.control.AbstractControl; import com.pesegato.collision.hitbox.HBCircle; import com.pesegato.collision.hitbox.HBRect; import org.dyn4j.dynamics.Body; import org.dyn4j.geometry.MassType; import org.dyn4j.geometry.Vector2;
package com.pesegato.collision; public class SampleD4J2 extends SimpleApplication { public static void main(String[] args) { SampleD4J2 app = new SampleD4J2(); //app.setShowSettings(false); app.start(); // start the game } D4JSpace2 d4j; @Override public void simpleInitApp() { d4j = new D4JSpace2(); stateManager.attachAll(d4j, new D4JSpaceDebugAppState(), new MainAppState()); } HBRect hbRect; class MainAppState extends BaseAppState { @Override protected void initialize(Application app) { getState(D4JSpaceDebugAppState.class).setGuiNode(guiNode); float boxSize = .5f; hbRect = new HBRect(1, boxSize, .5f); hbRect.translate(200, 300); hbRect.setColor(ColorRGBA.Blue); d4j.add(hbRect, MassType.INFINITE, 2);
// Path: src/main/java/com/pesegato/collision/hitbox/HBCircle.java // public class HBCircle extends DebuggableBody { // String name = ""; // int radius; // public long id; // // public HBCircle(long id, int radius) { // this.id = id; // this.radius = radius; // addFixture(new BodyFixture(new Circle(radius))); // } // // public HBCircle(String name, long id, int radius) { // this.name = name; // this.id = id; // this.radius = radius; // addFixture(new BodyFixture(new Circle(radius))); // } // // public HBCircle(long id, Filter filter, int radius) { // this.id = id; // this.radius = radius; // BodyFixture bf=new BodyFixture(new Circle(radius)); // bf.setFilter(filter); // addFixture(bf); // } // // @Deprecated // public Node getNode(AssetManager assetM, ColorRGBA color) { // Node n = new Node(); // if (SHOW_HITBOX) { // n.attachChild(makeHitboxMarker(assetM, n, color)); // } // return n; // } // // public Convex getConvex() { // return new Circle(radius); // } // // @Override // public Geometry makeHitboxMarker(AssetManager assetManager, Node n, ColorRGBA color) { // Material mat = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md"); // ColorRGBA col = color.clone(); // col.a = .5f; // mat.setColor("Color", col); // mat.getAdditionalRenderState().setBlendMode(RenderState.BlendMode.Alpha); // Geometry geo = new Geometry(name, new Prism(radius , 5,12)); // geo.setMaterial(mat); // geo.rotate(FastMath.PI/2,0,0); // return geo; // } // } // // Path: src/main/java/com/pesegato/collision/hitbox/HBRect.java // public class HBRect extends DebuggableBody { // String name = ""; // float w, h; // public long id; // // public HBRect(long id, float wP, float hP) { // this.id = id; // this.w = wP * SPRITE_SIZE; // this.h = hP * SPRITE_SIZE; // addFixture(new BodyFixture(new Rectangle(new Float(w), new Float(h)))); // } // // public HBRect(String name, long id, float wP, float hP) { // this.name = name; // this.id = id; // this.w = wP * SPRITE_SIZE; // this.h = hP * SPRITE_SIZE; // addFixture(new BodyFixture(new Rectangle(new Float(w), new Float(h)))); // } // // public HBRect(long id, Filter filter, int w, int h) { // this.id = id; // this.w = w; // this.h = h; // BodyFixture bf=new BodyFixture(new Rectangle(new Float(w), new Float(h))); // bf.setFilter(filter); // addFixture(bf); // } // // @Deprecated // public Node getNode(AssetManager assetM, ColorRGBA color) { // Node n = new Node(); // if (SHOW_HITBOX) { // n.attachChild(makeHitboxMarker(assetM, n, color)); // } // return n; // } // // public Convex getConvex() { // return new Rectangle(new Float(w), new Float(h)); // } // // @Deprecated // public Dyn4JShapeControl getControl() { // return new Dyn4JShapeControl(getConvex(), MassType.INFINITE, this); // } // // @Override // public Geometry makeHitboxMarker(AssetManager assetManager, Node n, ColorRGBA color) { // Material mat = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md"); // ColorRGBA col = color.clone(); // col.a = .5f; // mat.setColor("Color", col); // mat.getAdditionalRenderState().setBlendMode(RenderState.BlendMode.Alpha); // Geometry geo = new Geometry(name, new Quad(w, h)); // geo.setMaterial(mat); // geo.setLocalTranslation(-w / 2, -h / 2, 0); // return geo; // } // } // Path: src/main/java/com/pesegato/collision/SampleD4J2.java import com.jme3.app.Application; import com.jme3.app.SimpleApplication; import com.jme3.app.state.BaseAppState; import com.jme3.math.ColorRGBA; import com.jme3.renderer.RenderManager; import com.jme3.renderer.ViewPort; import com.jme3.scene.Node; import com.jme3.scene.control.AbstractControl; import com.pesegato.collision.hitbox.HBCircle; import com.pesegato.collision.hitbox.HBRect; import org.dyn4j.dynamics.Body; import org.dyn4j.geometry.MassType; import org.dyn4j.geometry.Vector2; package com.pesegato.collision; public class SampleD4J2 extends SimpleApplication { public static void main(String[] args) { SampleD4J2 app = new SampleD4J2(); //app.setShowSettings(false); app.start(); // start the game } D4JSpace2 d4j; @Override public void simpleInitApp() { d4j = new D4JSpace2(); stateManager.attachAll(d4j, new D4JSpaceDebugAppState(), new MainAppState()); } HBRect hbRect; class MainAppState extends BaseAppState { @Override protected void initialize(Application app) { getState(D4JSpaceDebugAppState.class).setGuiNode(guiNode); float boxSize = .5f; hbRect = new HBRect(1, boxSize, .5f); hbRect.translate(200, 300); hbRect.setColor(ColorRGBA.Blue); d4j.add(hbRect, MassType.INFINITE, 2);
HBCircle hbRect2 = new HBCircle(3, 15);
NetHome/Coders
src/main/java/nu/nethome/coders/encoders/RollerTrolGEncoder.java
// Path: src/main/java/nu/nethome/coders/RollerTrolG.java // public class RollerTrolG { // public static final String ROLLER_TROL_G_PROTOCOL_NAME = "RollerTrolG"; // public static final int PROTOCOL_BIT_LENGTH = 40; // public static final ProtocolInfo ROLLERTROL_PROTOCOL_INFO = new ProtocolInfo(ROLLER_TROL_G_PROTOCOL_NAME, "Mark Length", "RollerTrol", PROTOCOL_BIT_LENGTH, 1); // // public static final int COMMAND_STOP = 0x55; // public static final int COMMAND_UP = 0x11; // public static final int COMMAND_UP_END = 0x1E; // public static final int COMMAND_DOWN = 0x33; // public static final int COMMAND_DOWN_END = 0x3C; // public static final int COMMAND_LEARN = 0xCC; // // public static final PulseLength LONG_PREAMBLE_MARK = // new PulseLength(RollerTrolGDecoder.class, "LONG_PREAMBLE_MARK", 5170, 4000, 5900); // public static final PulseLength LONG_PREAMBLE_SPACE = // new PulseLength(RollerTrolGDecoder.class, "LONG_PREAMBLE_SPACE", 1665, 1000, 2000); // public static final PulseLength SHORT = // new PulseLength(RollerTrolGDecoder.class, "SHORT", 360, 200, 500); // public static final PulseLength LONG = // new PulseLength(RollerTrolGDecoder.class, "LONG", 770, 600, 900); // public static final PulseLength REPEAT_SPACE = // new PulseLength(RollerTrolGDecoder.class, "REPEAT_SPACE", 7400, 7000, 11000); // // public static final BitString.Field COMMAND = new BitString.Field(0, 8); // public static final BitString.Field CHANNEL = new BitString.Field(8, 4); // public static final BitString.Field ADDRESS = new BitString.Field(12, 28); // public static final String COMMAND_NAME = "Command"; // public static final String CHANNEL_NAME = "Channel"; // public static final String ADDRESS_NAME = "Address"; // } // // Path: src/main/java/nu/nethome/coders/RollerTrolG.java // public class RollerTrolG { // public static final String ROLLER_TROL_G_PROTOCOL_NAME = "RollerTrolG"; // public static final int PROTOCOL_BIT_LENGTH = 40; // public static final ProtocolInfo ROLLERTROL_PROTOCOL_INFO = new ProtocolInfo(ROLLER_TROL_G_PROTOCOL_NAME, "Mark Length", "RollerTrol", PROTOCOL_BIT_LENGTH, 1); // // public static final int COMMAND_STOP = 0x55; // public static final int COMMAND_UP = 0x11; // public static final int COMMAND_UP_END = 0x1E; // public static final int COMMAND_DOWN = 0x33; // public static final int COMMAND_DOWN_END = 0x3C; // public static final int COMMAND_LEARN = 0xCC; // // public static final PulseLength LONG_PREAMBLE_MARK = // new PulseLength(RollerTrolGDecoder.class, "LONG_PREAMBLE_MARK", 5170, 4000, 5900); // public static final PulseLength LONG_PREAMBLE_SPACE = // new PulseLength(RollerTrolGDecoder.class, "LONG_PREAMBLE_SPACE", 1665, 1000, 2000); // public static final PulseLength SHORT = // new PulseLength(RollerTrolGDecoder.class, "SHORT", 360, 200, 500); // public static final PulseLength LONG = // new PulseLength(RollerTrolGDecoder.class, "LONG", 770, 600, 900); // public static final PulseLength REPEAT_SPACE = // new PulseLength(RollerTrolGDecoder.class, "REPEAT_SPACE", 7400, 7000, 11000); // // public static final BitString.Field COMMAND = new BitString.Field(0, 8); // public static final BitString.Field CHANNEL = new BitString.Field(8, 4); // public static final BitString.Field ADDRESS = new BitString.Field(12, 28); // public static final String COMMAND_NAME = "Command"; // public static final String CHANNEL_NAME = "Channel"; // public static final String ADDRESS_NAME = "Address"; // }
import nu.nethome.coders.RollerTrolG; import nu.nethome.util.ps.*; import static nu.nethome.coders.RollerTrolG.*;
package nu.nethome.coders.encoders; /** * */ public class RollerTrolGEncoder implements ProtocolEncoder { public static final int PREAMBLE_LENGTH = 2; public static final int CONSTANT_FIELD_VALUE = 1; @Override public ProtocolInfo getInfo() { return ROLLERTROL_PROTOCOL_INFO; } @Override public int[] encode(Message message, Phase phase) throws BadMessageException { int address = 0; int channel = 0; int command = 0; for (FieldValue f : message.getFields()) {
// Path: src/main/java/nu/nethome/coders/RollerTrolG.java // public class RollerTrolG { // public static final String ROLLER_TROL_G_PROTOCOL_NAME = "RollerTrolG"; // public static final int PROTOCOL_BIT_LENGTH = 40; // public static final ProtocolInfo ROLLERTROL_PROTOCOL_INFO = new ProtocolInfo(ROLLER_TROL_G_PROTOCOL_NAME, "Mark Length", "RollerTrol", PROTOCOL_BIT_LENGTH, 1); // // public static final int COMMAND_STOP = 0x55; // public static final int COMMAND_UP = 0x11; // public static final int COMMAND_UP_END = 0x1E; // public static final int COMMAND_DOWN = 0x33; // public static final int COMMAND_DOWN_END = 0x3C; // public static final int COMMAND_LEARN = 0xCC; // // public static final PulseLength LONG_PREAMBLE_MARK = // new PulseLength(RollerTrolGDecoder.class, "LONG_PREAMBLE_MARK", 5170, 4000, 5900); // public static final PulseLength LONG_PREAMBLE_SPACE = // new PulseLength(RollerTrolGDecoder.class, "LONG_PREAMBLE_SPACE", 1665, 1000, 2000); // public static final PulseLength SHORT = // new PulseLength(RollerTrolGDecoder.class, "SHORT", 360, 200, 500); // public static final PulseLength LONG = // new PulseLength(RollerTrolGDecoder.class, "LONG", 770, 600, 900); // public static final PulseLength REPEAT_SPACE = // new PulseLength(RollerTrolGDecoder.class, "REPEAT_SPACE", 7400, 7000, 11000); // // public static final BitString.Field COMMAND = new BitString.Field(0, 8); // public static final BitString.Field CHANNEL = new BitString.Field(8, 4); // public static final BitString.Field ADDRESS = new BitString.Field(12, 28); // public static final String COMMAND_NAME = "Command"; // public static final String CHANNEL_NAME = "Channel"; // public static final String ADDRESS_NAME = "Address"; // } // // Path: src/main/java/nu/nethome/coders/RollerTrolG.java // public class RollerTrolG { // public static final String ROLLER_TROL_G_PROTOCOL_NAME = "RollerTrolG"; // public static final int PROTOCOL_BIT_LENGTH = 40; // public static final ProtocolInfo ROLLERTROL_PROTOCOL_INFO = new ProtocolInfo(ROLLER_TROL_G_PROTOCOL_NAME, "Mark Length", "RollerTrol", PROTOCOL_BIT_LENGTH, 1); // // public static final int COMMAND_STOP = 0x55; // public static final int COMMAND_UP = 0x11; // public static final int COMMAND_UP_END = 0x1E; // public static final int COMMAND_DOWN = 0x33; // public static final int COMMAND_DOWN_END = 0x3C; // public static final int COMMAND_LEARN = 0xCC; // // public static final PulseLength LONG_PREAMBLE_MARK = // new PulseLength(RollerTrolGDecoder.class, "LONG_PREAMBLE_MARK", 5170, 4000, 5900); // public static final PulseLength LONG_PREAMBLE_SPACE = // new PulseLength(RollerTrolGDecoder.class, "LONG_PREAMBLE_SPACE", 1665, 1000, 2000); // public static final PulseLength SHORT = // new PulseLength(RollerTrolGDecoder.class, "SHORT", 360, 200, 500); // public static final PulseLength LONG = // new PulseLength(RollerTrolGDecoder.class, "LONG", 770, 600, 900); // public static final PulseLength REPEAT_SPACE = // new PulseLength(RollerTrolGDecoder.class, "REPEAT_SPACE", 7400, 7000, 11000); // // public static final BitString.Field COMMAND = new BitString.Field(0, 8); // public static final BitString.Field CHANNEL = new BitString.Field(8, 4); // public static final BitString.Field ADDRESS = new BitString.Field(12, 28); // public static final String COMMAND_NAME = "Command"; // public static final String CHANNEL_NAME = "Channel"; // public static final String ADDRESS_NAME = "Address"; // } // Path: src/main/java/nu/nethome/coders/encoders/RollerTrolGEncoder.java import nu.nethome.coders.RollerTrolG; import nu.nethome.util.ps.*; import static nu.nethome.coders.RollerTrolG.*; package nu.nethome.coders.encoders; /** * */ public class RollerTrolGEncoder implements ProtocolEncoder { public static final int PREAMBLE_LENGTH = 2; public static final int CONSTANT_FIELD_VALUE = 1; @Override public ProtocolInfo getInfo() { return ROLLERTROL_PROTOCOL_INFO; } @Override public int[] encode(Message message, Phase phase) throws BadMessageException { int address = 0; int channel = 0; int command = 0; for (FieldValue f : message.getFields()) {
if (RollerTrolG.ADDRESS_NAME.equals(f.getName())) {
NetHome/Coders
src/main/java/nu/nethome/coders/encoders/ZhejiangEncoder.java
// Path: src/main/java/nu/nethome/coders/decoders/ZhejiangDecoder.java // @Plugin // public class ZhejiangDecoder extends NexaDecoder implements ProtocolDecoder{ // // // This are the pulse length constants for the protocol. The default values may // // be overridden by system properties // public static final PulseLength ZHEJ_LONG_MARK = // new PulseLength(ZhejiangDecoder.class, "ZHEJ_LONG_MARK", 430, 370, 550); // public static final PulseLength ZHEJ_SHORT_MARK = // new PulseLength(ZhejiangDecoder.class, "ZHEJ_SHORT_MARK", 140, 100, 220); // public static final PulseLength ZHEJ_LONG_SPACE = // new PulseLength(ZhejiangDecoder.class, "ZHEJ_LONG_SPACE", 450, 370, 550); // public static final PulseLength ZHEJ_SHORT_SPACE = // new PulseLength(ZhejiangDecoder.class, "ZHEJ_SHORT_SPACE", 170, 100, 220); // public static final PulseLength ZHEJ_REPEAT = // new PulseLength(ZhejiangDecoder.class, "ZHEJ_REPEAT", 4560, 500); // // public void setup() { // m_ProtocolName = "Zhejiang"; // LONG_MARK = ZHEJ_LONG_MARK; // SHORT_MARK = ZHEJ_SHORT_MARK; // LONG_SPACE = ZHEJ_LONG_SPACE; // SHORT_SPACE = ZHEJ_SHORT_SPACE; // REPEAT = ZHEJ_REPEAT; // } // // protected int bytemap(int raw) { // return (raw & 1) + ((raw >> 1) & 2) + ((raw >> 2) & 4) + ((raw >> 3) & 8) + ((raw >> 4) & 0x10); // } // // protected void addBit(int b) { // // Shift in data // m_Data >>= 1; // m_Data |= (b << 24); // // Check if this is a complete message // if (m_BitCounter == 24) { // // It is, create the message // int command = ((m_Data >> 23) & 1) ^ 1; // int rawButton = bytemap(((m_Data >> 11) ^ 0x3FF) & 0x3FF); // int address = bytemap((m_Data ^ 0x3FF) & 0x3FF); // int button = bitPosToInt(rawButton); // // // Sender ends a message sequence by a signal saying "no button is pressed". // // We ignore that message. // if (rawButton == 0) { // m_State = IDLE; // m_RepeatCount = 0; // return; // } // // ProtocolMessage message = new ProtocolMessage(m_ProtocolName, command, (rawButton << 8) + address, 4); // message.setRawMessageByteAt(0, (m_Data >> 24) & 0x1); // message.setRawMessageByteAt(1, (m_Data >> 16) & 0xFF); // message.setRawMessageByteAt(2, (m_Data >> 8) & 0xFF); // message.setRawMessageByteAt(3, (m_Data) & 0xFF); // // message.addField(new FieldValue("Command", command)); // message.addField(new FieldValue("Button", button)); // message.addField(new FieldValue("Address", address)); // // // It is, check if this really is a repeat // if ((m_RepeatCount > 0) && (m_Data == m_LastData)) { // message.setRepeat(m_RepeatCount); // } else { // // It is not a repeat, reset counter // m_RepeatCount = 0; // } // // Report the parsed message // m_Sink.parsedMessage(message); // m_State = REPEAT_SCAN; // } // m_BitCounter++; // } // // private int bitPosToInt(int rawButton) { // int shift = rawButton; // for (int i = 0; i < 5; i++) { // if ((shift & 1) == 1) { // return i; // } // shift >>= 1; // } // return 5; // } // }
import java.util.ArrayList; import nu.nethome.coders.decoders.ZhejiangDecoder; import nu.nethome.util.plugin.Plugin; import nu.nethome.util.ps.*;
public static Message buildMessage(int command, int button, int address) { ProtocolMessage result = new ProtocolMessage("Zhejiang", command, address, 0); result.addField(new FieldValue("Command", command)); result.addField(new FieldValue("Address", address)); result.addField(new FieldValue("Button", button)); return result; } private int[] encode(int command, int button, int address) { ArrayList<Integer> result = new ArrayList<Integer>(); long message = 0x2003FF; message = copyBit(command, 0, message, 21, false); message = copyBit(command, 0, message, 23, true); int buttonBit = 1 << button; message = copyBit(buttonBit, 0, message, 11, true); message = copyBit(buttonBit, 1, message, 13, true); message = copyBit(buttonBit, 2, message, 15, true); message = copyBit(buttonBit, 3, message, 17, true); message = copyBit(buttonBit, 4, message, 19, true); message = copyBit(address, 0, message, 0, true); message = copyBit(address, 1, message, 2, true); message = copyBit(address, 2, message, 4, true); message = copyBit(address, 3, message, 6, true); message = copyBit(address, 4, message, 8, true); // Encode message bits for (int j = 0; j < (ZHEJIANG_RAW_MESSAGE_LENGTH); j++) { if ((message & 1) == 1) {
// Path: src/main/java/nu/nethome/coders/decoders/ZhejiangDecoder.java // @Plugin // public class ZhejiangDecoder extends NexaDecoder implements ProtocolDecoder{ // // // This are the pulse length constants for the protocol. The default values may // // be overridden by system properties // public static final PulseLength ZHEJ_LONG_MARK = // new PulseLength(ZhejiangDecoder.class, "ZHEJ_LONG_MARK", 430, 370, 550); // public static final PulseLength ZHEJ_SHORT_MARK = // new PulseLength(ZhejiangDecoder.class, "ZHEJ_SHORT_MARK", 140, 100, 220); // public static final PulseLength ZHEJ_LONG_SPACE = // new PulseLength(ZhejiangDecoder.class, "ZHEJ_LONG_SPACE", 450, 370, 550); // public static final PulseLength ZHEJ_SHORT_SPACE = // new PulseLength(ZhejiangDecoder.class, "ZHEJ_SHORT_SPACE", 170, 100, 220); // public static final PulseLength ZHEJ_REPEAT = // new PulseLength(ZhejiangDecoder.class, "ZHEJ_REPEAT", 4560, 500); // // public void setup() { // m_ProtocolName = "Zhejiang"; // LONG_MARK = ZHEJ_LONG_MARK; // SHORT_MARK = ZHEJ_SHORT_MARK; // LONG_SPACE = ZHEJ_LONG_SPACE; // SHORT_SPACE = ZHEJ_SHORT_SPACE; // REPEAT = ZHEJ_REPEAT; // } // // protected int bytemap(int raw) { // return (raw & 1) + ((raw >> 1) & 2) + ((raw >> 2) & 4) + ((raw >> 3) & 8) + ((raw >> 4) & 0x10); // } // // protected void addBit(int b) { // // Shift in data // m_Data >>= 1; // m_Data |= (b << 24); // // Check if this is a complete message // if (m_BitCounter == 24) { // // It is, create the message // int command = ((m_Data >> 23) & 1) ^ 1; // int rawButton = bytemap(((m_Data >> 11) ^ 0x3FF) & 0x3FF); // int address = bytemap((m_Data ^ 0x3FF) & 0x3FF); // int button = bitPosToInt(rawButton); // // // Sender ends a message sequence by a signal saying "no button is pressed". // // We ignore that message. // if (rawButton == 0) { // m_State = IDLE; // m_RepeatCount = 0; // return; // } // // ProtocolMessage message = new ProtocolMessage(m_ProtocolName, command, (rawButton << 8) + address, 4); // message.setRawMessageByteAt(0, (m_Data >> 24) & 0x1); // message.setRawMessageByteAt(1, (m_Data >> 16) & 0xFF); // message.setRawMessageByteAt(2, (m_Data >> 8) & 0xFF); // message.setRawMessageByteAt(3, (m_Data) & 0xFF); // // message.addField(new FieldValue("Command", command)); // message.addField(new FieldValue("Button", button)); // message.addField(new FieldValue("Address", address)); // // // It is, check if this really is a repeat // if ((m_RepeatCount > 0) && (m_Data == m_LastData)) { // message.setRepeat(m_RepeatCount); // } else { // // It is not a repeat, reset counter // m_RepeatCount = 0; // } // // Report the parsed message // m_Sink.parsedMessage(message); // m_State = REPEAT_SCAN; // } // m_BitCounter++; // } // // private int bitPosToInt(int rawButton) { // int shift = rawButton; // for (int i = 0; i < 5; i++) { // if ((shift & 1) == 1) { // return i; // } // shift >>= 1; // } // return 5; // } // } // Path: src/main/java/nu/nethome/coders/encoders/ZhejiangEncoder.java import java.util.ArrayList; import nu.nethome.coders.decoders.ZhejiangDecoder; import nu.nethome.util.plugin.Plugin; import nu.nethome.util.ps.*; public static Message buildMessage(int command, int button, int address) { ProtocolMessage result = new ProtocolMessage("Zhejiang", command, address, 0); result.addField(new FieldValue("Command", command)); result.addField(new FieldValue("Address", address)); result.addField(new FieldValue("Button", button)); return result; } private int[] encode(int command, int button, int address) { ArrayList<Integer> result = new ArrayList<Integer>(); long message = 0x2003FF; message = copyBit(command, 0, message, 21, false); message = copyBit(command, 0, message, 23, true); int buttonBit = 1 << button; message = copyBit(buttonBit, 0, message, 11, true); message = copyBit(buttonBit, 1, message, 13, true); message = copyBit(buttonBit, 2, message, 15, true); message = copyBit(buttonBit, 3, message, 17, true); message = copyBit(buttonBit, 4, message, 19, true); message = copyBit(address, 0, message, 0, true); message = copyBit(address, 1, message, 2, true); message = copyBit(address, 2, message, 4, true); message = copyBit(address, 3, message, 6, true); message = copyBit(address, 4, message, 8, true); // Encode message bits for (int j = 0; j < (ZHEJIANG_RAW_MESSAGE_LENGTH); j++) { if ((message & 1) == 1) {
result.add(ZhejiangDecoder.ZHEJ_LONG_MARK.length());
NetHome/Coders
src/main/java/nu/nethome/coders/encoders/RisingSunEncoder.java
// Path: src/main/java/nu/nethome/coders/decoders/RisingSunDecoder.java // @Plugin // public class RisingSunDecoder extends NexaDecoder{ // // protected final static int buttonmapping[] = {10,11,12,13,14,15,16,4,18,19,10,3,22,2,1,0}; // // // This are the pulse length constants for the protocol. The default values may // // be overridden by system properties // public static final PulseLength RISING_SUN_LONG_MARK = // new PulseLength(RisingSunDecoder.class,"RISING_SUN_LONG_MARK", 1300, 200); // public static final PulseLength RISING_SUN_SHORT_MARK = // new PulseLength(RisingSunDecoder.class,"RISING_SUN_SHORT_MARK", 450, 200); // public static final PulseLength RISING_SUN_LONG_SPACE = // new PulseLength(RisingSunDecoder.class,"RISING_SUN_LONG_SPACE", 1280, 200); // public static final PulseLength RISING_SUN_SHORT_SPACE = // new PulseLength(RisingSunDecoder.class,"RISING_SUN_SHORT_SPACE", 420, 150); // public static final PulseLength RISING_SUN_REPEAT = // new PulseLength(RisingSunDecoder.class,"RISING_SUN_REPEAT", 13400, 500); // // public void setup() { // m_ProtocolName = "RisingSun"; // LONG_MARK = RISING_SUN_LONG_MARK; // SHORT_MARK = RISING_SUN_SHORT_MARK; // LONG_SPACE = RISING_SUN_LONG_SPACE; // SHORT_SPACE = RISING_SUN_SHORT_SPACE; // REPEAT = RISING_SUN_REPEAT; // } // // protected int bytemap(int raw) { // return buttonmapping[(raw & 1) + ((raw >> 1) & 2) + ((raw >> 2) & 4) + ((raw >> 3) & 8)]; // } // // protected void addBit(int b) { // // Shift in data // m_Data >>= 1; // m_Data |= (b << 24); // // Check if this is a complete message // if (m_BitCounter == 24){ // // It is, create the message // int command = (m_Data >> 23) & 1; // int button = bytemap((m_Data >> 9) & 0xFF); // int address = bytemap((m_Data >> 1) & 0xFF); // // // Sender ends a message sequence by a signal saying "no button is pressed". // // We ignore that message. // if (button == 0) { // m_State = IDLE; // m_RepeatCount = 0; // return; // } // // ProtocolMessage message = new ProtocolMessage(m_ProtocolName, command, (button << 4) + address, 4); // message.setRawMessageByteAt(3, m_Data & 0x1); // message.setRawMessageByteAt(0, (m_Data >> 17) & 0xFF); // message.setRawMessageByteAt(1, (m_Data >> 9) & 0xFF); // message.setRawMessageByteAt(2, (m_Data >> 1) & 0xFF); // // message.addField(new FieldValue("Command", command)); // message.addField(new FieldValue("Button", button)); // message.addField(new FieldValue("Channel", address)); // // // It is, check if this really is a repeat // if ((m_RepeatCount > 0) && (m_Data == m_LastData)) { // message.setRepeat(m_RepeatCount); // } // else { // // It is not a repeat, reset counter // m_RepeatCount = 0; // } // // Report the parsed message // m_Sink.parsedMessage(message); // m_State = REPEAT_SCAN; // } // m_BitCounter++; // } // }
import java.util.ArrayList; import nu.nethome.coders.decoders.RisingSunDecoder; import nu.nethome.util.plugin.Plugin; import nu.nethome.util.ps.*;
/** * Copyright (C) 2005-2013, Stefan Strömberg <[email protected]> * * This file is part of OpenNetHome (http://www.nethome.nu). * * OpenNetHome is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenNetHome is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package nu.nethome.coders.encoders; @Plugin public class RisingSunEncoder implements ProtocolEncoder{ public int repeatCount = 5; private int channel = 1; private int button = 1; private int command = 1; protected int onCommandValue; protected int offCommandValue; // Get the pulse lengths from the decoder
// Path: src/main/java/nu/nethome/coders/decoders/RisingSunDecoder.java // @Plugin // public class RisingSunDecoder extends NexaDecoder{ // // protected final static int buttonmapping[] = {10,11,12,13,14,15,16,4,18,19,10,3,22,2,1,0}; // // // This are the pulse length constants for the protocol. The default values may // // be overridden by system properties // public static final PulseLength RISING_SUN_LONG_MARK = // new PulseLength(RisingSunDecoder.class,"RISING_SUN_LONG_MARK", 1300, 200); // public static final PulseLength RISING_SUN_SHORT_MARK = // new PulseLength(RisingSunDecoder.class,"RISING_SUN_SHORT_MARK", 450, 200); // public static final PulseLength RISING_SUN_LONG_SPACE = // new PulseLength(RisingSunDecoder.class,"RISING_SUN_LONG_SPACE", 1280, 200); // public static final PulseLength RISING_SUN_SHORT_SPACE = // new PulseLength(RisingSunDecoder.class,"RISING_SUN_SHORT_SPACE", 420, 150); // public static final PulseLength RISING_SUN_REPEAT = // new PulseLength(RisingSunDecoder.class,"RISING_SUN_REPEAT", 13400, 500); // // public void setup() { // m_ProtocolName = "RisingSun"; // LONG_MARK = RISING_SUN_LONG_MARK; // SHORT_MARK = RISING_SUN_SHORT_MARK; // LONG_SPACE = RISING_SUN_LONG_SPACE; // SHORT_SPACE = RISING_SUN_SHORT_SPACE; // REPEAT = RISING_SUN_REPEAT; // } // // protected int bytemap(int raw) { // return buttonmapping[(raw & 1) + ((raw >> 1) & 2) + ((raw >> 2) & 4) + ((raw >> 3) & 8)]; // } // // protected void addBit(int b) { // // Shift in data // m_Data >>= 1; // m_Data |= (b << 24); // // Check if this is a complete message // if (m_BitCounter == 24){ // // It is, create the message // int command = (m_Data >> 23) & 1; // int button = bytemap((m_Data >> 9) & 0xFF); // int address = bytemap((m_Data >> 1) & 0xFF); // // // Sender ends a message sequence by a signal saying "no button is pressed". // // We ignore that message. // if (button == 0) { // m_State = IDLE; // m_RepeatCount = 0; // return; // } // // ProtocolMessage message = new ProtocolMessage(m_ProtocolName, command, (button << 4) + address, 4); // message.setRawMessageByteAt(3, m_Data & 0x1); // message.setRawMessageByteAt(0, (m_Data >> 17) & 0xFF); // message.setRawMessageByteAt(1, (m_Data >> 9) & 0xFF); // message.setRawMessageByteAt(2, (m_Data >> 1) & 0xFF); // // message.addField(new FieldValue("Command", command)); // message.addField(new FieldValue("Button", button)); // message.addField(new FieldValue("Channel", address)); // // // It is, check if this really is a repeat // if ((m_RepeatCount > 0) && (m_Data == m_LastData)) { // message.setRepeat(m_RepeatCount); // } // else { // // It is not a repeat, reset counter // m_RepeatCount = 0; // } // // Report the parsed message // m_Sink.parsedMessage(message); // m_State = REPEAT_SCAN; // } // m_BitCounter++; // } // } // Path: src/main/java/nu/nethome/coders/encoders/RisingSunEncoder.java import java.util.ArrayList; import nu.nethome.coders.decoders.RisingSunDecoder; import nu.nethome.util.plugin.Plugin; import nu.nethome.util.ps.*; /** * Copyright (C) 2005-2013, Stefan Strömberg <[email protected]> * * This file is part of OpenNetHome (http://www.nethome.nu). * * OpenNetHome is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenNetHome is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package nu.nethome.coders.encoders; @Plugin public class RisingSunEncoder implements ProtocolEncoder{ public int repeatCount = 5; private int channel = 1; private int button = 1; private int command = 1; protected int onCommandValue; protected int offCommandValue; // Get the pulse lengths from the decoder
protected int LONG_MARK = RisingSunDecoder.RISING_SUN_LONG_MARK.length();
jclawson/hazeltask
hazeltask-core/src/main/java/com/hazeltask/executor/metrics/LocalFuturesWaitingGauge.java
// Path: hazeltask-core/src/main/java/com/hazeltask/executor/DistributedFutureTracker.java // @Slf4j // public class DistributedFutureTracker<GROUP extends Serializable> implements MessageListener<TaskResponse<Serializable>> { // private Cache<UUID, DistributedFuture<GROUP, Serializable>> futures; // // private final Histogram futureWaitTimeHistogram; // private final IExecutorTopologyService<GROUP> topologyService; // // /** // * // * @param metrics (nullable) // */ // public DistributedFutureTracker(final IExecutorTopologyService<GROUP> topologyService, ExecutorMetrics metrics, ExecutorConfig<GROUP> config) { // this.topologyService = topologyService; // futures = CacheBuilder.newBuilder() // //no future will wait for more than this time // .expireAfterAccess(config.getMaximumFutureWaitTime(), TimeUnit.MILLISECONDS) // .removalListener(new RemovalListener<UUID, DistributedFuture<GROUP, Serializable>>() { // @Override // public void onRemoval(RemovalNotification<UUID, DistributedFuture<GROUP, Serializable>> notification) { // if(notification.getCause() == RemovalCause.EXPIRED) { // DistributedFuture<GROUP, Serializable> future = notification.getValue(); // long waitTimeMillis = System.currentTimeMillis() - future.getCreatedTime(); // notification.getValue().setException(new TimeoutException("Future timed out waiting. Waited "+(TimeUnit.MILLISECONDS.toMinutes(waitTimeMillis))+" minutes")); // // topologyService.cancelTask(future.getGroup(), future.getTaskId()); // topologyService.removePendingTask(future.getTaskId()); // } else if(notification.getCause() == RemovalCause.COLLECTED) { // //future was GC'd because we didn't want to track it // log.debug("Future "+notification.getKey()+" was garabge collected and removed from the tracker"); // } // } // }) // .build(); // // if(metrics != null) { // metrics.registerLocalFuturesWaitingGauge(new LocalFuturesWaitingGauge(this)); // futureWaitTimeHistogram = metrics.getFutureWaitTimeHistogram().getMetric(); // } else { // futureWaitTimeHistogram = null; // } // } // // //It is required that T be Serializable // @SuppressWarnings("unchecked") // public <T> DistributedFuture<GROUP, T> createFuture(HazeltaskTask<GROUP> task) { // DistributedFuture<GROUP, T> future = new DistributedFuture<GROUP, T>(topologyService, task.getGroup(), task.getId()); // this.futures.put(task.getId(), (DistributedFuture<GROUP, Serializable>) future); // return future; // } // // protected DistributedFuture<GROUP, Serializable> remove(UUID id) { // DistributedFuture<GROUP, Serializable> f =futures.getIfPresent(id); // futures.invalidate(id); // // if(f != null) { // if(futureWaitTimeHistogram != null) { // futureWaitTimeHistogram.update(System.currentTimeMillis() - f.getCreatedTime()); // } // } // // return f; // } // // public Set<UUID> getTrackedTaskIds() { // return new HashSet<UUID>(futures.asMap().keySet()); // } // // @Override // public void onMessage(Message<TaskResponse<Serializable>> message) { // TaskResponse<Serializable> response = message.getMessageObject(); // UUID taskId = response.getTaskId(); // DistributedFuture<GROUP, Serializable> future = remove(taskId); // if(future != null) { // if(response.getStatus() == Status.FAILURE) { // future.setException(response.getError()); // } else if(response.getStatus() == Status.SUCCESS) { // future.set((Serializable)response.getResponse()); // } else if (response.getStatus() == Status.CANCELLED) { // //TODO: add a status for INTERRUPTED // future.setCancelled(false); // } // // } // } // // /** // * handles when a member leaves and hazelcast partition data is lost. We want // * to find the Futures that are waiting on lost data and error them // */ // public void errorFuture(UUID taskId, Exception e) { // DistributedFuture<GROUP, Serializable> future = remove(taskId); // if(future != null) { // future.setException(e); // } // } // // public int size() { // return (int) futures.size(); // } // // // }
import com.codahale.metrics.Gauge; import com.hazeltask.executor.DistributedFutureTracker;
package com.hazeltask.executor.metrics; @SuppressWarnings("rawtypes") public class LocalFuturesWaitingGauge implements Gauge<Integer> {
// Path: hazeltask-core/src/main/java/com/hazeltask/executor/DistributedFutureTracker.java // @Slf4j // public class DistributedFutureTracker<GROUP extends Serializable> implements MessageListener<TaskResponse<Serializable>> { // private Cache<UUID, DistributedFuture<GROUP, Serializable>> futures; // // private final Histogram futureWaitTimeHistogram; // private final IExecutorTopologyService<GROUP> topologyService; // // /** // * // * @param metrics (nullable) // */ // public DistributedFutureTracker(final IExecutorTopologyService<GROUP> topologyService, ExecutorMetrics metrics, ExecutorConfig<GROUP> config) { // this.topologyService = topologyService; // futures = CacheBuilder.newBuilder() // //no future will wait for more than this time // .expireAfterAccess(config.getMaximumFutureWaitTime(), TimeUnit.MILLISECONDS) // .removalListener(new RemovalListener<UUID, DistributedFuture<GROUP, Serializable>>() { // @Override // public void onRemoval(RemovalNotification<UUID, DistributedFuture<GROUP, Serializable>> notification) { // if(notification.getCause() == RemovalCause.EXPIRED) { // DistributedFuture<GROUP, Serializable> future = notification.getValue(); // long waitTimeMillis = System.currentTimeMillis() - future.getCreatedTime(); // notification.getValue().setException(new TimeoutException("Future timed out waiting. Waited "+(TimeUnit.MILLISECONDS.toMinutes(waitTimeMillis))+" minutes")); // // topologyService.cancelTask(future.getGroup(), future.getTaskId()); // topologyService.removePendingTask(future.getTaskId()); // } else if(notification.getCause() == RemovalCause.COLLECTED) { // //future was GC'd because we didn't want to track it // log.debug("Future "+notification.getKey()+" was garabge collected and removed from the tracker"); // } // } // }) // .build(); // // if(metrics != null) { // metrics.registerLocalFuturesWaitingGauge(new LocalFuturesWaitingGauge(this)); // futureWaitTimeHistogram = metrics.getFutureWaitTimeHistogram().getMetric(); // } else { // futureWaitTimeHistogram = null; // } // } // // //It is required that T be Serializable // @SuppressWarnings("unchecked") // public <T> DistributedFuture<GROUP, T> createFuture(HazeltaskTask<GROUP> task) { // DistributedFuture<GROUP, T> future = new DistributedFuture<GROUP, T>(topologyService, task.getGroup(), task.getId()); // this.futures.put(task.getId(), (DistributedFuture<GROUP, Serializable>) future); // return future; // } // // protected DistributedFuture<GROUP, Serializable> remove(UUID id) { // DistributedFuture<GROUP, Serializable> f =futures.getIfPresent(id); // futures.invalidate(id); // // if(f != null) { // if(futureWaitTimeHistogram != null) { // futureWaitTimeHistogram.update(System.currentTimeMillis() - f.getCreatedTime()); // } // } // // return f; // } // // public Set<UUID> getTrackedTaskIds() { // return new HashSet<UUID>(futures.asMap().keySet()); // } // // @Override // public void onMessage(Message<TaskResponse<Serializable>> message) { // TaskResponse<Serializable> response = message.getMessageObject(); // UUID taskId = response.getTaskId(); // DistributedFuture<GROUP, Serializable> future = remove(taskId); // if(future != null) { // if(response.getStatus() == Status.FAILURE) { // future.setException(response.getError()); // } else if(response.getStatus() == Status.SUCCESS) { // future.set((Serializable)response.getResponse()); // } else if (response.getStatus() == Status.CANCELLED) { // //TODO: add a status for INTERRUPTED // future.setCancelled(false); // } // // } // } // // /** // * handles when a member leaves and hazelcast partition data is lost. We want // * to find the Futures that are waiting on lost data and error them // */ // public void errorFuture(UUID taskId, Exception e) { // DistributedFuture<GROUP, Serializable> future = remove(taskId); // if(future != null) { // future.setException(e); // } // } // // public int size() { // return (int) futures.size(); // } // // // } // Path: hazeltask-core/src/main/java/com/hazeltask/executor/metrics/LocalFuturesWaitingGauge.java import com.codahale.metrics.Gauge; import com.hazeltask.executor.DistributedFutureTracker; package com.hazeltask.executor.metrics; @SuppressWarnings("rawtypes") public class LocalFuturesWaitingGauge implements Gauge<Integer> {
private DistributedFutureTracker tracker;
jclawson/hazeltask
hazeltask-core/src/main/java/com/hazeltask/core/concurrent/collections/grouped/prioritizer/EnumOrdinalPrioritizer.java
// Path: hazeltask-core/src/main/java/com/hazeltask/core/concurrent/collections/grouped/GroupMetadata.java // public final class GroupMetadata<G> implements Comparable<GroupMetadata<G>> { // private final G group; // private final long priority; // // public GroupMetadata(G group, long priority) { // if(group == null) { // throw new IllegalArgumentException("Group cannot be null"); // } // this.group = group; // this.priority = priority; // } // // public G getGroup() { // return group; // } // // public long getPriority() { // return priority; // } // // /** // * compareTo must be consistent with equals. If the priority is // * equal however, and the groups are NOT equal, we want to place // * *this* item at the end of the priority queue. // * // * TODO: do we still need to do this "hack" now that we use a skiplist and // * not a priority queue that breaks ties arbitrarily? // */ // @Override // public int compareTo(GroupMetadata<G> o) { // //return ((Long)priority).compareTo(o.priority); // int comparison = ((Long)priority).compareTo(o.priority); // if(comparison == 0) { // if(!group.equals(o.group)) { // return -1; // } // } // return comparison; // } // // //hash code and equals solely based on group // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((group == null) ? 0 : group.hashCode()); // return result; // } // // /** // * equals only cares about group equality. It doesn't compare priority. // */ // @Override // public boolean equals(Object obj) { // if (this == obj) return true; // if (obj == null) return false; // if (getClass() != obj.getClass()) return false; // GroupMetadata<?> other = (GroupMetadata<?>) obj; // if (group == null) { // if (other.group != null) return false; // } else if (!group.equals(other.group)) return false; // return true; // } // // @Override // public String toString() { // return "GroupMetadata [group=" + group + ", priority=" + priority + "]"; // } // // // // // // // // }
import com.hazeltask.core.concurrent.collections.grouped.GroupMetadata;
package com.hazeltask.core.concurrent.collections.grouped.prioritizer; /** * If your group type is an enum, you may use this EnumOrdinalPrioritizer. * An ordinal of 1 will appear before an ordinal of 0. If this is backwards * for your code usage, use the inverse() method to invert this logic. * * @author jclawson * * @param <G> */ public class EnumOrdinalPrioritizer<G> implements GroupPrioritizer<G> { private boolean isInverted; public EnumOrdinalPrioritizer() { } @Override
// Path: hazeltask-core/src/main/java/com/hazeltask/core/concurrent/collections/grouped/GroupMetadata.java // public final class GroupMetadata<G> implements Comparable<GroupMetadata<G>> { // private final G group; // private final long priority; // // public GroupMetadata(G group, long priority) { // if(group == null) { // throw new IllegalArgumentException("Group cannot be null"); // } // this.group = group; // this.priority = priority; // } // // public G getGroup() { // return group; // } // // public long getPriority() { // return priority; // } // // /** // * compareTo must be consistent with equals. If the priority is // * equal however, and the groups are NOT equal, we want to place // * *this* item at the end of the priority queue. // * // * TODO: do we still need to do this "hack" now that we use a skiplist and // * not a priority queue that breaks ties arbitrarily? // */ // @Override // public int compareTo(GroupMetadata<G> o) { // //return ((Long)priority).compareTo(o.priority); // int comparison = ((Long)priority).compareTo(o.priority); // if(comparison == 0) { // if(!group.equals(o.group)) { // return -1; // } // } // return comparison; // } // // //hash code and equals solely based on group // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((group == null) ? 0 : group.hashCode()); // return result; // } // // /** // * equals only cares about group equality. It doesn't compare priority. // */ // @Override // public boolean equals(Object obj) { // if (this == obj) return true; // if (obj == null) return false; // if (getClass() != obj.getClass()) return false; // GroupMetadata<?> other = (GroupMetadata<?>) obj; // if (group == null) { // if (other.group != null) return false; // } else if (!group.equals(other.group)) return false; // return true; // } // // @Override // public String toString() { // return "GroupMetadata [group=" + group + ", priority=" + priority + "]"; // } // // // // // // // // } // Path: hazeltask-core/src/main/java/com/hazeltask/core/concurrent/collections/grouped/prioritizer/EnumOrdinalPrioritizer.java import com.hazeltask.core.concurrent.collections.grouped.GroupMetadata; package com.hazeltask.core.concurrent.collections.grouped.prioritizer; /** * If your group type is an enum, you may use this EnumOrdinalPrioritizer. * An ordinal of 1 will appear before an ordinal of 0. If this is backwards * for your code usage, use the inverse() method to invert this logic. * * @author jclawson * * @param <G> */ public class EnumOrdinalPrioritizer<G> implements GroupPrioritizer<G> { private boolean isInverted; public EnumOrdinalPrioritizer() { } @Override
public long computePriority(GroupMetadata<G> metadata) {
jclawson/hazeltask
hazeltask-core/src/main/java/com/hazeltask/Hazeltask.java
// Path: hazeltask-core/src/main/java/com/hazeltask/config/HazeltaskConfig.java // public class HazeltaskConfig<GROUP extends Serializable> { // private HazelcastInstance hazelcast; // private String topologyName = Hazeltask.DEFAULT_TOPOLOGY; // private ExecutorConfig<GROUP> executorConfig = new ExecutorConfig<GROUP>(); // private MetricsConfig metricsConfig = new MetricsConfig(); // private NamedThreadFactory threadFactory; // // /** // * Topology names allow you to run multiple Hazeltask platforms on the same JVM. You may retrive your Hazeltask intance // * later through the Hazeltask.getInstanceByName. The default name is defined as Hazeltask.DEFAULT_TOPOLOGY // * // * @param name // * @return // */ // public HazeltaskConfig<GROUP> withName(String name) { // this.topologyName = name; // return this; // } // // /** // * Distributed executor configuration options. The class com.hazeltask.config.defaults.ExecutorConfigs contains // * default common starter execution configurations // * // * @see ExecutorConfigs // * @param executorConfig // * @return // */ // public HazeltaskConfig<GROUP> withExecutorConfig(ExecutorConfig<GROUP> executorConfig) { // this.executorConfig = executorConfig; // return this; // } // // /** // * If you don't specify a hazelcast instance, we will use the default instance // * @param hazelcast // * @return // */ // public HazeltaskConfig<GROUP> withHazelcastInstance(HazelcastInstance hazelcast) { // this.hazelcast = hazelcast; // return this; // } // // /** // * Allows the customization of Yammer metrics collected throughout Hazeltask // * // * @see http://metrics.codahale.com/ // * @param metricsConfig // * @return // */ // public HazeltaskConfig<GROUP> withMetricsConfig(MetricsConfig metricsConfig) { // this.metricsConfig = metricsConfig; // return this; // } // // public MetricsConfig getMetricsConfig() { // return this.metricsConfig; // } // // public MetricRegistry getMetricsRegistry() { // return this.metricsConfig.getMetricsRegistry(); // } // // public HazelcastInstance getHazelcast() { // return hazelcast; // } // // public String getTopologyName() { // return topologyName; // } // // public ExecutorConfig<GROUP> getExecutorConfig() { // return this.executorConfig; // } // // /** // * All threads created by Hazeltask will be created through this threadFactory. This // * allows you to customize all the threads used // * // * @param threadFactory // * @return // */ // public HazeltaskConfig<GROUP> withThreadFactory(NamedThreadFactory threadFactory) { // this.threadFactory = threadFactory; // return this; // } // // public NamedThreadFactory getThreadFactory() { // return this.threadFactory; // } // }
import java.io.Serializable; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import com.hazeltask.config.HazeltaskConfig;
package com.hazeltask; public final class Hazeltask { public static final String DEFAULT_TOPOLOGY = "DefaultTopology"; public static ConcurrentMap<String, HazeltaskInstance<?>> instances = new ConcurrentHashMap<String, HazeltaskInstance<?>>(); private Hazeltask() { } @SuppressWarnings("unchecked") public static <GROUP extends Serializable> HazeltaskInstance<GROUP> getInstanceByName(String topology) { return (HazeltaskInstance<GROUP>) instances.get(topology); } /** * @deprecated This is deprecated because it relies in the deprecated Hazelcast.getDefaultInstance * @see newHazeltaskInstance * @see * @return */ @Deprecated public static HazeltaskInstance<Integer> getDefaultInstance() {
// Path: hazeltask-core/src/main/java/com/hazeltask/config/HazeltaskConfig.java // public class HazeltaskConfig<GROUP extends Serializable> { // private HazelcastInstance hazelcast; // private String topologyName = Hazeltask.DEFAULT_TOPOLOGY; // private ExecutorConfig<GROUP> executorConfig = new ExecutorConfig<GROUP>(); // private MetricsConfig metricsConfig = new MetricsConfig(); // private NamedThreadFactory threadFactory; // // /** // * Topology names allow you to run multiple Hazeltask platforms on the same JVM. You may retrive your Hazeltask intance // * later through the Hazeltask.getInstanceByName. The default name is defined as Hazeltask.DEFAULT_TOPOLOGY // * // * @param name // * @return // */ // public HazeltaskConfig<GROUP> withName(String name) { // this.topologyName = name; // return this; // } // // /** // * Distributed executor configuration options. The class com.hazeltask.config.defaults.ExecutorConfigs contains // * default common starter execution configurations // * // * @see ExecutorConfigs // * @param executorConfig // * @return // */ // public HazeltaskConfig<GROUP> withExecutorConfig(ExecutorConfig<GROUP> executorConfig) { // this.executorConfig = executorConfig; // return this; // } // // /** // * If you don't specify a hazelcast instance, we will use the default instance // * @param hazelcast // * @return // */ // public HazeltaskConfig<GROUP> withHazelcastInstance(HazelcastInstance hazelcast) { // this.hazelcast = hazelcast; // return this; // } // // /** // * Allows the customization of Yammer metrics collected throughout Hazeltask // * // * @see http://metrics.codahale.com/ // * @param metricsConfig // * @return // */ // public HazeltaskConfig<GROUP> withMetricsConfig(MetricsConfig metricsConfig) { // this.metricsConfig = metricsConfig; // return this; // } // // public MetricsConfig getMetricsConfig() { // return this.metricsConfig; // } // // public MetricRegistry getMetricsRegistry() { // return this.metricsConfig.getMetricsRegistry(); // } // // public HazelcastInstance getHazelcast() { // return hazelcast; // } // // public String getTopologyName() { // return topologyName; // } // // public ExecutorConfig<GROUP> getExecutorConfig() { // return this.executorConfig; // } // // /** // * All threads created by Hazeltask will be created through this threadFactory. This // * allows you to customize all the threads used // * // * @param threadFactory // * @return // */ // public HazeltaskConfig<GROUP> withThreadFactory(NamedThreadFactory threadFactory) { // this.threadFactory = threadFactory; // return this; // } // // public NamedThreadFactory getThreadFactory() { // return this.threadFactory; // } // } // Path: hazeltask-core/src/main/java/com/hazeltask/Hazeltask.java import java.io.Serializable; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import com.hazeltask.config.HazeltaskConfig; package com.hazeltask; public final class Hazeltask { public static final String DEFAULT_TOPOLOGY = "DefaultTopology"; public static ConcurrentMap<String, HazeltaskInstance<?>> instances = new ConcurrentHashMap<String, HazeltaskInstance<?>>(); private Hazeltask() { } @SuppressWarnings("unchecked") public static <GROUP extends Serializable> HazeltaskInstance<GROUP> getInstanceByName(String topology) { return (HazeltaskInstance<GROUP>) instances.get(topology); } /** * @deprecated This is deprecated because it relies in the deprecated Hazelcast.getDefaultInstance * @see newHazeltaskInstance * @see * @return */ @Deprecated public static HazeltaskInstance<Integer> getDefaultInstance() {
HazeltaskConfig<Integer> hazeltaskConfig = new HazeltaskConfig<Integer>();
jclawson/hazeltask
hazeltask-core/src/main/java/com/hazeltask/config/ExecutorConfig.java
// Path: hazeltask-core/src/main/java/com/hazeltask/executor/TaskResponseListener.java // public interface TaskResponseListener extends MessageListener<TaskResponse<Serializable>> { // // } // // Path: hazeltask-core/src/main/java/com/hazeltask/executor/task/DefaultTaskIdAdapter.java // public class DefaultTaskIdAdapter implements TaskIdAdapter<Object, Integer, Serializable> { // private static int GROUP = Integer.MIN_VALUE; // // @Override // public Integer getTaskGroup(Object task) { // return GROUP; // } // // @Override // public boolean supports(Object task) { // //we support all objects! // return true; // } // // @Override // public Serializable getTaskInfo(Object task) { // return null; // } // } // // Path: hazeltask-core/src/main/java/com/hazeltask/executor/task/TaskIdAdapter.java // public interface TaskIdAdapter<T, GROUP extends Serializable, INFO extends Serializable> { // // /** // * This might be useful to fill out to be able to get at task information // * without having to deserialize the entire task. It is also the only // * task-specific identifiable information available in TaskResponseListener // * // * @param task // * @return // */ // public INFO getTaskInfo(T task); // // /** // * The group does not need to be equal for successive calls with the same task // * @param task // * @return // */ // public GROUP getTaskGroup(T task); // // /** // * Given an object, return whether this adapater supports identifying the group // * Generally the logic is: <code>return task instanceof T</code> // * // * We have this here as a validation step when you submit a Runnable to the ExecutorService. // * Since ExecutorService isn't generic, we need to take extra steps to ensure the task // * is able to be processed by the system // * // * @param task // * @return // */ // public boolean supports(Object task); // }
import java.io.Serializable; import java.util.List; import java.util.concurrent.TimeUnit; import com.google.common.collect.Lists; import com.hazeltask.executor.TaskResponseListener; import com.hazeltask.executor.task.DefaultTaskIdAdapter; import com.hazeltask.executor.task.TaskIdAdapter;
package com.hazeltask.config; public class ExecutorConfig<GROUP extends Serializable> { protected boolean disableWorkers = false; protected int corePoolSize = 4; protected int maxPoolSize = 4; protected long maxThreadKeepAlive = 60000; @SuppressWarnings("unchecked")
// Path: hazeltask-core/src/main/java/com/hazeltask/executor/TaskResponseListener.java // public interface TaskResponseListener extends MessageListener<TaskResponse<Serializable>> { // // } // // Path: hazeltask-core/src/main/java/com/hazeltask/executor/task/DefaultTaskIdAdapter.java // public class DefaultTaskIdAdapter implements TaskIdAdapter<Object, Integer, Serializable> { // private static int GROUP = Integer.MIN_VALUE; // // @Override // public Integer getTaskGroup(Object task) { // return GROUP; // } // // @Override // public boolean supports(Object task) { // //we support all objects! // return true; // } // // @Override // public Serializable getTaskInfo(Object task) { // return null; // } // } // // Path: hazeltask-core/src/main/java/com/hazeltask/executor/task/TaskIdAdapter.java // public interface TaskIdAdapter<T, GROUP extends Serializable, INFO extends Serializable> { // // /** // * This might be useful to fill out to be able to get at task information // * without having to deserialize the entire task. It is also the only // * task-specific identifiable information available in TaskResponseListener // * // * @param task // * @return // */ // public INFO getTaskInfo(T task); // // /** // * The group does not need to be equal for successive calls with the same task // * @param task // * @return // */ // public GROUP getTaskGroup(T task); // // /** // * Given an object, return whether this adapater supports identifying the group // * Generally the logic is: <code>return task instanceof T</code> // * // * We have this here as a validation step when you submit a Runnable to the ExecutorService. // * Since ExecutorService isn't generic, we need to take extra steps to ensure the task // * is able to be processed by the system // * // * @param task // * @return // */ // public boolean supports(Object task); // } // Path: hazeltask-core/src/main/java/com/hazeltask/config/ExecutorConfig.java import java.io.Serializable; import java.util.List; import java.util.concurrent.TimeUnit; import com.google.common.collect.Lists; import com.hazeltask.executor.TaskResponseListener; import com.hazeltask.executor.task.DefaultTaskIdAdapter; import com.hazeltask.executor.task.TaskIdAdapter; package com.hazeltask.config; public class ExecutorConfig<GROUP extends Serializable> { protected boolean disableWorkers = false; protected int corePoolSize = 4; protected int maxPoolSize = 4; protected long maxThreadKeepAlive = 60000; @SuppressWarnings("unchecked")
protected TaskIdAdapter<?, GROUP, ?> taskIdAdapter = (TaskIdAdapter<?, GROUP, ?>) new DefaultTaskIdAdapter();
jclawson/hazeltask
hazeltask-core/src/main/java/com/hazeltask/config/ExecutorConfig.java
// Path: hazeltask-core/src/main/java/com/hazeltask/executor/TaskResponseListener.java // public interface TaskResponseListener extends MessageListener<TaskResponse<Serializable>> { // // } // // Path: hazeltask-core/src/main/java/com/hazeltask/executor/task/DefaultTaskIdAdapter.java // public class DefaultTaskIdAdapter implements TaskIdAdapter<Object, Integer, Serializable> { // private static int GROUP = Integer.MIN_VALUE; // // @Override // public Integer getTaskGroup(Object task) { // return GROUP; // } // // @Override // public boolean supports(Object task) { // //we support all objects! // return true; // } // // @Override // public Serializable getTaskInfo(Object task) { // return null; // } // } // // Path: hazeltask-core/src/main/java/com/hazeltask/executor/task/TaskIdAdapter.java // public interface TaskIdAdapter<T, GROUP extends Serializable, INFO extends Serializable> { // // /** // * This might be useful to fill out to be able to get at task information // * without having to deserialize the entire task. It is also the only // * task-specific identifiable information available in TaskResponseListener // * // * @param task // * @return // */ // public INFO getTaskInfo(T task); // // /** // * The group does not need to be equal for successive calls with the same task // * @param task // * @return // */ // public GROUP getTaskGroup(T task); // // /** // * Given an object, return whether this adapater supports identifying the group // * Generally the logic is: <code>return task instanceof T</code> // * // * We have this here as a validation step when you submit a Runnable to the ExecutorService. // * Since ExecutorService isn't generic, we need to take extra steps to ensure the task // * is able to be processed by the system // * // * @param task // * @return // */ // public boolean supports(Object task); // }
import java.io.Serializable; import java.util.List; import java.util.concurrent.TimeUnit; import com.google.common.collect.Lists; import com.hazeltask.executor.TaskResponseListener; import com.hazeltask.executor.task.DefaultTaskIdAdapter; import com.hazeltask.executor.task.TaskIdAdapter;
package com.hazeltask.config; public class ExecutorConfig<GROUP extends Serializable> { protected boolean disableWorkers = false; protected int corePoolSize = 4; protected int maxPoolSize = 4; protected long maxThreadKeepAlive = 60000; @SuppressWarnings("unchecked")
// Path: hazeltask-core/src/main/java/com/hazeltask/executor/TaskResponseListener.java // public interface TaskResponseListener extends MessageListener<TaskResponse<Serializable>> { // // } // // Path: hazeltask-core/src/main/java/com/hazeltask/executor/task/DefaultTaskIdAdapter.java // public class DefaultTaskIdAdapter implements TaskIdAdapter<Object, Integer, Serializable> { // private static int GROUP = Integer.MIN_VALUE; // // @Override // public Integer getTaskGroup(Object task) { // return GROUP; // } // // @Override // public boolean supports(Object task) { // //we support all objects! // return true; // } // // @Override // public Serializable getTaskInfo(Object task) { // return null; // } // } // // Path: hazeltask-core/src/main/java/com/hazeltask/executor/task/TaskIdAdapter.java // public interface TaskIdAdapter<T, GROUP extends Serializable, INFO extends Serializable> { // // /** // * This might be useful to fill out to be able to get at task information // * without having to deserialize the entire task. It is also the only // * task-specific identifiable information available in TaskResponseListener // * // * @param task // * @return // */ // public INFO getTaskInfo(T task); // // /** // * The group does not need to be equal for successive calls with the same task // * @param task // * @return // */ // public GROUP getTaskGroup(T task); // // /** // * Given an object, return whether this adapater supports identifying the group // * Generally the logic is: <code>return task instanceof T</code> // * // * We have this here as a validation step when you submit a Runnable to the ExecutorService. // * Since ExecutorService isn't generic, we need to take extra steps to ensure the task // * is able to be processed by the system // * // * @param task // * @return // */ // public boolean supports(Object task); // } // Path: hazeltask-core/src/main/java/com/hazeltask/config/ExecutorConfig.java import java.io.Serializable; import java.util.List; import java.util.concurrent.TimeUnit; import com.google.common.collect.Lists; import com.hazeltask.executor.TaskResponseListener; import com.hazeltask.executor.task.DefaultTaskIdAdapter; import com.hazeltask.executor.task.TaskIdAdapter; package com.hazeltask.config; public class ExecutorConfig<GROUP extends Serializable> { protected boolean disableWorkers = false; protected int corePoolSize = 4; protected int maxPoolSize = 4; protected long maxThreadKeepAlive = 60000; @SuppressWarnings("unchecked")
protected TaskIdAdapter<?, GROUP, ?> taskIdAdapter = (TaskIdAdapter<?, GROUP, ?>) new DefaultTaskIdAdapter();
jclawson/hazeltask
hazeltask-core/src/main/java/com/hazeltask/config/ExecutorConfig.java
// Path: hazeltask-core/src/main/java/com/hazeltask/executor/TaskResponseListener.java // public interface TaskResponseListener extends MessageListener<TaskResponse<Serializable>> { // // } // // Path: hazeltask-core/src/main/java/com/hazeltask/executor/task/DefaultTaskIdAdapter.java // public class DefaultTaskIdAdapter implements TaskIdAdapter<Object, Integer, Serializable> { // private static int GROUP = Integer.MIN_VALUE; // // @Override // public Integer getTaskGroup(Object task) { // return GROUP; // } // // @Override // public boolean supports(Object task) { // //we support all objects! // return true; // } // // @Override // public Serializable getTaskInfo(Object task) { // return null; // } // } // // Path: hazeltask-core/src/main/java/com/hazeltask/executor/task/TaskIdAdapter.java // public interface TaskIdAdapter<T, GROUP extends Serializable, INFO extends Serializable> { // // /** // * This might be useful to fill out to be able to get at task information // * without having to deserialize the entire task. It is also the only // * task-specific identifiable information available in TaskResponseListener // * // * @param task // * @return // */ // public INFO getTaskInfo(T task); // // /** // * The group does not need to be equal for successive calls with the same task // * @param task // * @return // */ // public GROUP getTaskGroup(T task); // // /** // * Given an object, return whether this adapater supports identifying the group // * Generally the logic is: <code>return task instanceof T</code> // * // * We have this here as a validation step when you submit a Runnable to the ExecutorService. // * Since ExecutorService isn't generic, we need to take extra steps to ensure the task // * is able to be processed by the system // * // * @param task // * @return // */ // public boolean supports(Object task); // }
import java.io.Serializable; import java.util.List; import java.util.concurrent.TimeUnit; import com.google.common.collect.Lists; import com.hazeltask.executor.TaskResponseListener; import com.hazeltask.executor.task.DefaultTaskIdAdapter; import com.hazeltask.executor.task.TaskIdAdapter;
package com.hazeltask.config; public class ExecutorConfig<GROUP extends Serializable> { protected boolean disableWorkers = false; protected int corePoolSize = 4; protected int maxPoolSize = 4; protected long maxThreadKeepAlive = 60000; @SuppressWarnings("unchecked") protected TaskIdAdapter<?, GROUP, ?> taskIdAdapter = (TaskIdAdapter<?, GROUP, ?>) new DefaultTaskIdAdapter(); protected boolean autoStart = true; private boolean enableFutureTracking = true; private long maximumFutureWaitTime = TimeUnit.MINUTES.toMillis(60); private boolean asyncronousTaskDistribution = false; private int asyncronousTaskDistributionQueueSize = 500; private long recoveryProcessPollInterval = 30000; private ExecutorLoadBalancingConfig<GROUP> executorLoadBalancingConfig = new ExecutorLoadBalancingConfig<GROUP>();
// Path: hazeltask-core/src/main/java/com/hazeltask/executor/TaskResponseListener.java // public interface TaskResponseListener extends MessageListener<TaskResponse<Serializable>> { // // } // // Path: hazeltask-core/src/main/java/com/hazeltask/executor/task/DefaultTaskIdAdapter.java // public class DefaultTaskIdAdapter implements TaskIdAdapter<Object, Integer, Serializable> { // private static int GROUP = Integer.MIN_VALUE; // // @Override // public Integer getTaskGroup(Object task) { // return GROUP; // } // // @Override // public boolean supports(Object task) { // //we support all objects! // return true; // } // // @Override // public Serializable getTaskInfo(Object task) { // return null; // } // } // // Path: hazeltask-core/src/main/java/com/hazeltask/executor/task/TaskIdAdapter.java // public interface TaskIdAdapter<T, GROUP extends Serializable, INFO extends Serializable> { // // /** // * This might be useful to fill out to be able to get at task information // * without having to deserialize the entire task. It is also the only // * task-specific identifiable information available in TaskResponseListener // * // * @param task // * @return // */ // public INFO getTaskInfo(T task); // // /** // * The group does not need to be equal for successive calls with the same task // * @param task // * @return // */ // public GROUP getTaskGroup(T task); // // /** // * Given an object, return whether this adapater supports identifying the group // * Generally the logic is: <code>return task instanceof T</code> // * // * We have this here as a validation step when you submit a Runnable to the ExecutorService. // * Since ExecutorService isn't generic, we need to take extra steps to ensure the task // * is able to be processed by the system // * // * @param task // * @return // */ // public boolean supports(Object task); // } // Path: hazeltask-core/src/main/java/com/hazeltask/config/ExecutorConfig.java import java.io.Serializable; import java.util.List; import java.util.concurrent.TimeUnit; import com.google.common.collect.Lists; import com.hazeltask.executor.TaskResponseListener; import com.hazeltask.executor.task.DefaultTaskIdAdapter; import com.hazeltask.executor.task.TaskIdAdapter; package com.hazeltask.config; public class ExecutorConfig<GROUP extends Serializable> { protected boolean disableWorkers = false; protected int corePoolSize = 4; protected int maxPoolSize = 4; protected long maxThreadKeepAlive = 60000; @SuppressWarnings("unchecked") protected TaskIdAdapter<?, GROUP, ?> taskIdAdapter = (TaskIdAdapter<?, GROUP, ?>) new DefaultTaskIdAdapter(); protected boolean autoStart = true; private boolean enableFutureTracking = true; private long maximumFutureWaitTime = TimeUnit.MINUTES.toMillis(60); private boolean asyncronousTaskDistribution = false; private int asyncronousTaskDistributionQueueSize = 500; private long recoveryProcessPollInterval = 30000; private ExecutorLoadBalancingConfig<GROUP> executorLoadBalancingConfig = new ExecutorLoadBalancingConfig<GROUP>();
private List<TaskResponseListener> taskResponseListeners = Lists.newArrayList();
jclawson/hazeltask
hazeltask-core/src/main/java/com/hazeltask/config/ConfigValidator.java
// Path: hazeltask-core/src/main/java/com/hazeltask/core/concurrent/NamedThreadFactory.java // public class NamedThreadFactory implements ThreadFactory { // private final ThreadGroup group; // private final AtomicInteger threadNumber = new AtomicInteger(0); // private final String namePrefix; // // protected NamedThreadFactory(String namePrefix, ThreadGroup group) { // this.namePrefix = namePrefix; // this.group = group; // } // // public NamedThreadFactory(String groupName, String threadNamePrefix) { // SecurityManager s = System.getSecurityManager(); // ThreadGroup parent = (s != null)? s.getThreadGroup() : // Thread.currentThread().getThreadGroup(); // // group = new ThreadGroup(parent, groupName); // namePrefix = threadNamePrefix; // } // // public ThreadGroup getThreadGroup() { // return group; // } // // public String getNamePrefix() { // return this.namePrefix; // } // // protected boolean getDaemon(){ // return false; // } // // protected int getPriority(){ // return Thread.NORM_PRIORITY; // } // // @Override // public Thread newThread(Runnable r) { // Thread t = new Thread(group, r, // namePrefix+"-"+ threadNumber.getAndIncrement(), // 0); // t.setDaemon(getDaemon()); // t.setPriority(getPriority()); // return t; // } // // protected static class $ChildNamedThreadFactory extends NamedThreadFactory { // private final NamedThreadFactory parent; // // protected $ChildNamedThreadFactory(NamedThreadFactory parent, String childName) { // super(parent.getNamePrefix()+"-"+childName, parent.getThreadGroup()); // this.parent = parent; // } // // @Override // protected boolean getDaemon() { // return parent.getDaemon(); // } // // @Override // protected int getPriority() { // return parent.getPriority(); // } // // } // // /** // * Creates a NamedThreadFactory that is a "child" of this instance. The name // * provided here will be appended to this instance's name in threads created from // * the returned NamedThreadFactory // * // * @param name // * @return // */ // public NamedThreadFactory named(String name) { // return new $ChildNamedThreadFactory(this, name); // } // // }
import lombok.extern.slf4j.Slf4j; import com.codahale.metrics.MetricRegistry; import com.hazelcast.core.Hazelcast; import com.hazeltask.core.concurrent.NamedThreadFactory;
package com.hazeltask.config; @Slf4j public class ConfigValidator { public static void validate(HazeltaskConfig<?> config) { ExecutorConfig<?> executorConfig = config.getExecutorConfig(); MetricsConfig metricsConfig = config.getMetricsConfig(); if(config.getHazelcast() == null) { log.warn("No hazelcast instance provided, creating a default one to use."); config.withHazelcastInstance(Hazelcast.newHazelcastInstance()); } if(metricsConfig.getMetricsRegistry() == null) { metricsConfig.withMetricsRegistry(new MetricRegistry()); } if(config.getThreadFactory() == null) {
// Path: hazeltask-core/src/main/java/com/hazeltask/core/concurrent/NamedThreadFactory.java // public class NamedThreadFactory implements ThreadFactory { // private final ThreadGroup group; // private final AtomicInteger threadNumber = new AtomicInteger(0); // private final String namePrefix; // // protected NamedThreadFactory(String namePrefix, ThreadGroup group) { // this.namePrefix = namePrefix; // this.group = group; // } // // public NamedThreadFactory(String groupName, String threadNamePrefix) { // SecurityManager s = System.getSecurityManager(); // ThreadGroup parent = (s != null)? s.getThreadGroup() : // Thread.currentThread().getThreadGroup(); // // group = new ThreadGroup(parent, groupName); // namePrefix = threadNamePrefix; // } // // public ThreadGroup getThreadGroup() { // return group; // } // // public String getNamePrefix() { // return this.namePrefix; // } // // protected boolean getDaemon(){ // return false; // } // // protected int getPriority(){ // return Thread.NORM_PRIORITY; // } // // @Override // public Thread newThread(Runnable r) { // Thread t = new Thread(group, r, // namePrefix+"-"+ threadNumber.getAndIncrement(), // 0); // t.setDaemon(getDaemon()); // t.setPriority(getPriority()); // return t; // } // // protected static class $ChildNamedThreadFactory extends NamedThreadFactory { // private final NamedThreadFactory parent; // // protected $ChildNamedThreadFactory(NamedThreadFactory parent, String childName) { // super(parent.getNamePrefix()+"-"+childName, parent.getThreadGroup()); // this.parent = parent; // } // // @Override // protected boolean getDaemon() { // return parent.getDaemon(); // } // // @Override // protected int getPriority() { // return parent.getPriority(); // } // // } // // /** // * Creates a NamedThreadFactory that is a "child" of this instance. The name // * provided here will be appended to this instance's name in threads created from // * the returned NamedThreadFactory // * // * @param name // * @return // */ // public NamedThreadFactory named(String name) { // return new $ChildNamedThreadFactory(this, name); // } // // } // Path: hazeltask-core/src/main/java/com/hazeltask/config/ConfigValidator.java import lombok.extern.slf4j.Slf4j; import com.codahale.metrics.MetricRegistry; import com.hazelcast.core.Hazelcast; import com.hazeltask.core.concurrent.NamedThreadFactory; package com.hazeltask.config; @Slf4j public class ConfigValidator { public static void validate(HazeltaskConfig<?> config) { ExecutorConfig<?> executorConfig = config.getExecutorConfig(); MetricsConfig metricsConfig = config.getMetricsConfig(); if(config.getHazelcast() == null) { log.warn("No hazelcast instance provided, creating a default one to use."); config.withHazelcastInstance(Hazelcast.newHazelcastInstance()); } if(metricsConfig.getMetricsRegistry() == null) { metricsConfig.withMetricsRegistry(new MetricRegistry()); } if(config.getThreadFactory() == null) {
config.withThreadFactory(new NamedThreadFactory("Hazeltask", config.getTopologyName()));
jclawson/hazeltask
hazeltask-core/src/main/java/com/hazeltask/core/concurrent/collections/grouped/IGroupedQueue.java
// Path: hazeltask-core/src/main/java/com/hazeltask/core/concurrent/collections/tracked/ITrackedQueue.java // public interface ITrackedQueue<E> extends Queue<E> { // public Long getOldestItemTime(); // public Long getLastAddedTime(); // public Long getLastRemovedTime(); // }
import java.util.Collection; import java.util.Map; import java.util.concurrent.BlockingQueue; import com.google.common.base.Predicate; import com.hazeltask.core.concurrent.collections.tracked.ITrackedQueue;
package com.hazeltask.core.concurrent.collections.grouped; public interface IGroupedQueue<E extends Groupable<G>, G> extends BlockingQueue<E>{ public abstract Long getOldestQueueTime(); public abstract int drainTo(G partition, Collection<? super E> toCollection); public abstract int drainTo(G partition, Collection<? super E> toCollection, int max); public Collection<G> getGroups(); public Map<G, Integer> getGroupSizes(Predicate<G> predicate);
// Path: hazeltask-core/src/main/java/com/hazeltask/core/concurrent/collections/tracked/ITrackedQueue.java // public interface ITrackedQueue<E> extends Queue<E> { // public Long getOldestItemTime(); // public Long getLastAddedTime(); // public Long getLastRemovedTime(); // } // Path: hazeltask-core/src/main/java/com/hazeltask/core/concurrent/collections/grouped/IGroupedQueue.java import java.util.Collection; import java.util.Map; import java.util.concurrent.BlockingQueue; import com.google.common.base.Predicate; import com.hazeltask.core.concurrent.collections.tracked.ITrackedQueue; package com.hazeltask.core.concurrent.collections.grouped; public interface IGroupedQueue<E extends Groupable<G>, G> extends BlockingQueue<E>{ public abstract Long getOldestQueueTime(); public abstract int drainTo(G partition, Collection<? super E> toCollection); public abstract int drainTo(G partition, Collection<? super E> toCollection, int max); public Collection<G> getGroups(); public Map<G, Integer> getGroupSizes(Predicate<G> predicate);
public ITrackedQueue<E> getQueueByGroup(G group);
jclawson/hazeltask
hazeltask-core/src/main/java/com/hazeltask/core/concurrent/collections/grouped/prioritizer/LoadBalancedPriorityPrioritizer.java
// Path: hazeltask-core/src/main/java/com/hazeltask/core/concurrent/collections/grouped/GroupMetadata.java // public final class GroupMetadata<G> implements Comparable<GroupMetadata<G>> { // private final G group; // private final long priority; // // public GroupMetadata(G group, long priority) { // if(group == null) { // throw new IllegalArgumentException("Group cannot be null"); // } // this.group = group; // this.priority = priority; // } // // public G getGroup() { // return group; // } // // public long getPriority() { // return priority; // } // // /** // * compareTo must be consistent with equals. If the priority is // * equal however, and the groups are NOT equal, we want to place // * *this* item at the end of the priority queue. // * // * TODO: do we still need to do this "hack" now that we use a skiplist and // * not a priority queue that breaks ties arbitrarily? // */ // @Override // public int compareTo(GroupMetadata<G> o) { // //return ((Long)priority).compareTo(o.priority); // int comparison = ((Long)priority).compareTo(o.priority); // if(comparison == 0) { // if(!group.equals(o.group)) { // return -1; // } // } // return comparison; // } // // //hash code and equals solely based on group // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((group == null) ? 0 : group.hashCode()); // return result; // } // // /** // * equals only cares about group equality. It doesn't compare priority. // */ // @Override // public boolean equals(Object obj) { // if (this == obj) return true; // if (obj == null) return false; // if (getClass() != obj.getClass()) return false; // GroupMetadata<?> other = (GroupMetadata<?>) obj; // if (group == null) { // if (other.group != null) return false; // } else if (!group.equals(other.group)) return false; // return true; // } // // @Override // public String toString() { // return "GroupMetadata [group=" + group + ", priority=" + priority + "]"; // } // // // // // // // // }
import com.hazeltask.core.concurrent.collections.grouped.GroupMetadata;
package com.hazeltask.core.concurrent.collections.grouped.prioritizer; /** * Given a source prioritizer, this wrapper will continuously lower the priority of a group * until it reaches 0 at which point its priority will be set to the source prioritizer. The * effect is that HIGH priority items will not be able to starve out LOW priority items forever. * * For example, if your source prioritizer returns 10 for HIGH priority, and 2 for LOW priority * This prioritizer will allow for at least 8 HIGH priority tasks to run before running 1 LOW * priority task, then 1 HIGH, then 1 LOW, then the last HIGH, then if the queue is filled back * up it will run 8 HIGH * * The effect can be tuned based on what your source prioritizer returns and the delta that is * configured here. * * * * @author jclawson * * @param <E> */ public class LoadBalancedPriorityPrioritizer<E> implements GroupPrioritizer<E> { private final GroupPrioritizer<E> source; private final long delta; public LoadBalancedPriorityPrioritizer(GroupPrioritizer<E> source) { this(source, 1); } /** * * @param source * @param delta - how much to reduce the priority by each iteration */ public LoadBalancedPriorityPrioritizer(GroupPrioritizer<E> source, long delta) { this.source = source; this.delta = delta; } @Override
// Path: hazeltask-core/src/main/java/com/hazeltask/core/concurrent/collections/grouped/GroupMetadata.java // public final class GroupMetadata<G> implements Comparable<GroupMetadata<G>> { // private final G group; // private final long priority; // // public GroupMetadata(G group, long priority) { // if(group == null) { // throw new IllegalArgumentException("Group cannot be null"); // } // this.group = group; // this.priority = priority; // } // // public G getGroup() { // return group; // } // // public long getPriority() { // return priority; // } // // /** // * compareTo must be consistent with equals. If the priority is // * equal however, and the groups are NOT equal, we want to place // * *this* item at the end of the priority queue. // * // * TODO: do we still need to do this "hack" now that we use a skiplist and // * not a priority queue that breaks ties arbitrarily? // */ // @Override // public int compareTo(GroupMetadata<G> o) { // //return ((Long)priority).compareTo(o.priority); // int comparison = ((Long)priority).compareTo(o.priority); // if(comparison == 0) { // if(!group.equals(o.group)) { // return -1; // } // } // return comparison; // } // // //hash code and equals solely based on group // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((group == null) ? 0 : group.hashCode()); // return result; // } // // /** // * equals only cares about group equality. It doesn't compare priority. // */ // @Override // public boolean equals(Object obj) { // if (this == obj) return true; // if (obj == null) return false; // if (getClass() != obj.getClass()) return false; // GroupMetadata<?> other = (GroupMetadata<?>) obj; // if (group == null) { // if (other.group != null) return false; // } else if (!group.equals(other.group)) return false; // return true; // } // // @Override // public String toString() { // return "GroupMetadata [group=" + group + ", priority=" + priority + "]"; // } // // // // // // // // } // Path: hazeltask-core/src/main/java/com/hazeltask/core/concurrent/collections/grouped/prioritizer/LoadBalancedPriorityPrioritizer.java import com.hazeltask.core.concurrent.collections.grouped.GroupMetadata; package com.hazeltask.core.concurrent.collections.grouped.prioritizer; /** * Given a source prioritizer, this wrapper will continuously lower the priority of a group * until it reaches 0 at which point its priority will be set to the source prioritizer. The * effect is that HIGH priority items will not be able to starve out LOW priority items forever. * * For example, if your source prioritizer returns 10 for HIGH priority, and 2 for LOW priority * This prioritizer will allow for at least 8 HIGH priority tasks to run before running 1 LOW * priority task, then 1 HIGH, then 1 LOW, then the last HIGH, then if the queue is filled back * up it will run 8 HIGH * * The effect can be tuned based on what your source prioritizer returns and the delta that is * configured here. * * * * @author jclawson * * @param <E> */ public class LoadBalancedPriorityPrioritizer<E> implements GroupPrioritizer<E> { private final GroupPrioritizer<E> source; private final long delta; public LoadBalancedPriorityPrioritizer(GroupPrioritizer<E> source) { this(source, 1); } /** * * @param source * @param delta - how much to reduce the priority by each iteration */ public LoadBalancedPriorityPrioritizer(GroupPrioritizer<E> source, long delta) { this.source = source; this.delta = delta; } @Override
public long computePriority(GroupMetadata<E> metadata) {
jclawson/hazeltask
hazeltask-core/src/main/java/com/hazeltask/ITopologyService.java
// Path: hazeltask-core/src/main/java/com/hazeltask/executor/task/HazeltaskTask.java // public class HazeltaskTask< G extends Serializable> // implements Runnable, Task<G>, HazelcastInstanceAware, TrackCreated { // private static final long serialVersionUID = 1L; // // private Runnable runTask; // private Callable<?> callTask; // // private long createdAtMillis; // private UUID id; // private G group; // private Serializable taskInfo; // // private int submissionCount; // private transient HazelcastInstance hazelcastInstance; // private transient Timer taskExecutedTimer; // // private volatile transient Object result; // private volatile transient Exception e; // // //required for DataSerializable // protected HazeltaskTask(){} // // public HazeltaskTask(UUID id, G group, Serializable taskInfo, Runnable task){ // this.runTask = task; // this.id = id; // this.group = group; // createdAtMillis = System.currentTimeMillis(); // this.submissionCount = 1; // this.taskInfo = taskInfo; // } // // public HazeltaskTask(UUID id, G group, Serializable taskInfo, Callable<?> task){ // this.callTask = task; // this.id = id; // this.group = group; // createdAtMillis = System.currentTimeMillis(); // this.submissionCount = 1; // this.taskInfo = taskInfo; // } // // public void setSubmissionCount(int submissionCount){ // this.submissionCount = submissionCount; // } // // public int getSubmissionCount(){ // return this.submissionCount; // } // // public void updateCreatedTime(){ // this.createdAtMillis = System.currentTimeMillis(); // } // // public G getGroup() { // return group; // } // // public Object getResult() { // return result; // } // // public Exception getException() { // return e; // } // // public long getTimeCreated(){ // return createdAtMillis; // } // // public void run() { // Timer.Context ctx = null; // if(taskExecutedTimer != null) // ctx = taskExecutedTimer.time(); // try { // if(callTask != null) { // if(callTask instanceof HazelcastInstanceAware) { // ((HazelcastInstanceAware) callTask).setHazelcastInstance(hazelcastInstance); // } // this.result = callTask.call(); // } else { // if(runTask instanceof HazelcastInstanceAware) { // ((HazelcastInstanceAware) runTask).setHazelcastInstance(hazelcastInstance); // } // runTask.run(); // } // } catch (Exception t) { // this.e = t; // } finally { // if(ctx != null) // ctx.stop(); // } // } // // public Runnable getInnerRunnable() { // return this.runTask; // } // // public Callable<?> getInnerCallable() { // return this.callTask; // } // // @Override // public UUID getId() { // return id; // } // // @Override // public void setHazelcastInstance(HazelcastInstance hazelcastInstance) { // this.hazelcastInstance = hazelcastInstance; // } // // @Override // public void writeData(ObjectDataOutput out) throws IOException { // out.writeLong(id.getMostSignificantBits()); // out.writeLong(id.getLeastSignificantBits()); // // out.writeObject(group); // out.writeObject(runTask); // out.writeObject(callTask); // // out.writeLong(createdAtMillis); // out.writeInt(submissionCount); // } // // @SuppressWarnings("unchecked") // @Override // public void readData(ObjectDataInput in) throws IOException { // long m = in.readLong(); // long l = in.readLong(); // // id = new UUID(m, l); // group = (G) in.readObject(); // runTask = (Runnable) in.readObject(); // callTask = (Callable<?>) in.readObject(); // // createdAtMillis = in.readLong(); // submissionCount = in.readInt(); // } // // public void setExecutionTimer(Timer taskExecutedTimer) { // this.taskExecutedTimer = taskExecutedTimer; // } // // public Serializable getTaskInfo() { // return taskInfo; // } // // }
import java.io.Serializable; import java.util.List; import java.util.Set; import com.hazelcast.core.Member; import com.hazeltask.executor.task.HazeltaskTask;
package com.hazeltask; /** * Methods here that act on multiple members will query for ready members * to ensure they have the most up to date data. * * TODO: move this to the ClusterService * * * @author jclawson * */ public interface ITopologyService<GROUP extends Serializable> { public Set<Member> getReadyMembers(); public long pingMember(Member member); public void shutdown();
// Path: hazeltask-core/src/main/java/com/hazeltask/executor/task/HazeltaskTask.java // public class HazeltaskTask< G extends Serializable> // implements Runnable, Task<G>, HazelcastInstanceAware, TrackCreated { // private static final long serialVersionUID = 1L; // // private Runnable runTask; // private Callable<?> callTask; // // private long createdAtMillis; // private UUID id; // private G group; // private Serializable taskInfo; // // private int submissionCount; // private transient HazelcastInstance hazelcastInstance; // private transient Timer taskExecutedTimer; // // private volatile transient Object result; // private volatile transient Exception e; // // //required for DataSerializable // protected HazeltaskTask(){} // // public HazeltaskTask(UUID id, G group, Serializable taskInfo, Runnable task){ // this.runTask = task; // this.id = id; // this.group = group; // createdAtMillis = System.currentTimeMillis(); // this.submissionCount = 1; // this.taskInfo = taskInfo; // } // // public HazeltaskTask(UUID id, G group, Serializable taskInfo, Callable<?> task){ // this.callTask = task; // this.id = id; // this.group = group; // createdAtMillis = System.currentTimeMillis(); // this.submissionCount = 1; // this.taskInfo = taskInfo; // } // // public void setSubmissionCount(int submissionCount){ // this.submissionCount = submissionCount; // } // // public int getSubmissionCount(){ // return this.submissionCount; // } // // public void updateCreatedTime(){ // this.createdAtMillis = System.currentTimeMillis(); // } // // public G getGroup() { // return group; // } // // public Object getResult() { // return result; // } // // public Exception getException() { // return e; // } // // public long getTimeCreated(){ // return createdAtMillis; // } // // public void run() { // Timer.Context ctx = null; // if(taskExecutedTimer != null) // ctx = taskExecutedTimer.time(); // try { // if(callTask != null) { // if(callTask instanceof HazelcastInstanceAware) { // ((HazelcastInstanceAware) callTask).setHazelcastInstance(hazelcastInstance); // } // this.result = callTask.call(); // } else { // if(runTask instanceof HazelcastInstanceAware) { // ((HazelcastInstanceAware) runTask).setHazelcastInstance(hazelcastInstance); // } // runTask.run(); // } // } catch (Exception t) { // this.e = t; // } finally { // if(ctx != null) // ctx.stop(); // } // } // // public Runnable getInnerRunnable() { // return this.runTask; // } // // public Callable<?> getInnerCallable() { // return this.callTask; // } // // @Override // public UUID getId() { // return id; // } // // @Override // public void setHazelcastInstance(HazelcastInstance hazelcastInstance) { // this.hazelcastInstance = hazelcastInstance; // } // // @Override // public void writeData(ObjectDataOutput out) throws IOException { // out.writeLong(id.getMostSignificantBits()); // out.writeLong(id.getLeastSignificantBits()); // // out.writeObject(group); // out.writeObject(runTask); // out.writeObject(callTask); // // out.writeLong(createdAtMillis); // out.writeInt(submissionCount); // } // // @SuppressWarnings("unchecked") // @Override // public void readData(ObjectDataInput in) throws IOException { // long m = in.readLong(); // long l = in.readLong(); // // id = new UUID(m, l); // group = (G) in.readObject(); // runTask = (Runnable) in.readObject(); // callTask = (Callable<?>) in.readObject(); // // createdAtMillis = in.readLong(); // submissionCount = in.readInt(); // } // // public void setExecutionTimer(Timer taskExecutedTimer) { // this.taskExecutedTimer = taskExecutedTimer; // } // // public Serializable getTaskInfo() { // return taskInfo; // } // // } // Path: hazeltask-core/src/main/java/com/hazeltask/ITopologyService.java import java.io.Serializable; import java.util.List; import java.util.Set; import com.hazelcast.core.Member; import com.hazeltask.executor.task.HazeltaskTask; package com.hazeltask; /** * Methods here that act on multiple members will query for ready members * to ensure they have the most up to date data. * * TODO: move this to the ClusterService * * * @author jclawson * */ public interface ITopologyService<GROUP extends Serializable> { public Set<Member> getReadyMembers(); public long pingMember(Member member); public void shutdown();
public List<HazeltaskTask<GROUP>> shutdownNow();
jclawson/hazeltask
hazeltask-core/src/main/java/com/hazeltask/executor/task/Task.java
// Path: hazeltask-core/src/main/java/com/hazeltask/core/concurrent/collections/grouped/Groupable.java // public interface Groupable<G> { // /** // * Return the group this object belongs to // * @return // */ // public G getGroup(); // }
import java.io.Serializable; import java.util.UUID; import com.hazelcast.nio.serialization.DataSerializable; import com.hazeltask.core.concurrent.collections.grouped.Groupable;
package com.hazeltask.executor.task; public interface Task< G extends Serializable> extends Runnable,
// Path: hazeltask-core/src/main/java/com/hazeltask/core/concurrent/collections/grouped/Groupable.java // public interface Groupable<G> { // /** // * Return the group this object belongs to // * @return // */ // public G getGroup(); // } // Path: hazeltask-core/src/main/java/com/hazeltask/executor/task/Task.java import java.io.Serializable; import java.util.UUID; import com.hazelcast.nio.serialization.DataSerializable; import com.hazeltask.core.concurrent.collections.grouped.Groupable; package com.hazeltask.executor.task; public interface Task< G extends Serializable> extends Runnable,
Groupable<G>,
jclawson/hazeltask
hazeltask-core/src/main/java/com/hazeltask/core/concurrent/collections/grouped/prioritizer/RoundRobinGroupPrioritizer.java
// Path: hazeltask-core/src/main/java/com/hazeltask/core/concurrent/collections/grouped/GroupMetadata.java // public final class GroupMetadata<G> implements Comparable<GroupMetadata<G>> { // private final G group; // private final long priority; // // public GroupMetadata(G group, long priority) { // if(group == null) { // throw new IllegalArgumentException("Group cannot be null"); // } // this.group = group; // this.priority = priority; // } // // public G getGroup() { // return group; // } // // public long getPriority() { // return priority; // } // // /** // * compareTo must be consistent with equals. If the priority is // * equal however, and the groups are NOT equal, we want to place // * *this* item at the end of the priority queue. // * // * TODO: do we still need to do this "hack" now that we use a skiplist and // * not a priority queue that breaks ties arbitrarily? // */ // @Override // public int compareTo(GroupMetadata<G> o) { // //return ((Long)priority).compareTo(o.priority); // int comparison = ((Long)priority).compareTo(o.priority); // if(comparison == 0) { // if(!group.equals(o.group)) { // return -1; // } // } // return comparison; // } // // //hash code and equals solely based on group // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((group == null) ? 0 : group.hashCode()); // return result; // } // // /** // * equals only cares about group equality. It doesn't compare priority. // */ // @Override // public boolean equals(Object obj) { // if (this == obj) return true; // if (obj == null) return false; // if (getClass() != obj.getClass()) return false; // GroupMetadata<?> other = (GroupMetadata<?>) obj; // if (group == null) { // if (other.group != null) return false; // } else if (!group.equals(other.group)) return false; // return true; // } // // @Override // public String toString() { // return "GroupMetadata [group=" + group + ", priority=" + priority + "]"; // } // // // // // // // // }
import com.hazeltask.core.concurrent.collections.grouped.GroupMetadata;
package com.hazeltask.core.concurrent.collections.grouped.prioritizer; public class RoundRobinGroupPrioritizer<G> implements GroupPrioritizer<G> { @Override
// Path: hazeltask-core/src/main/java/com/hazeltask/core/concurrent/collections/grouped/GroupMetadata.java // public final class GroupMetadata<G> implements Comparable<GroupMetadata<G>> { // private final G group; // private final long priority; // // public GroupMetadata(G group, long priority) { // if(group == null) { // throw new IllegalArgumentException("Group cannot be null"); // } // this.group = group; // this.priority = priority; // } // // public G getGroup() { // return group; // } // // public long getPriority() { // return priority; // } // // /** // * compareTo must be consistent with equals. If the priority is // * equal however, and the groups are NOT equal, we want to place // * *this* item at the end of the priority queue. // * // * TODO: do we still need to do this "hack" now that we use a skiplist and // * not a priority queue that breaks ties arbitrarily? // */ // @Override // public int compareTo(GroupMetadata<G> o) { // //return ((Long)priority).compareTo(o.priority); // int comparison = ((Long)priority).compareTo(o.priority); // if(comparison == 0) { // if(!group.equals(o.group)) { // return -1; // } // } // return comparison; // } // // //hash code and equals solely based on group // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((group == null) ? 0 : group.hashCode()); // return result; // } // // /** // * equals only cares about group equality. It doesn't compare priority. // */ // @Override // public boolean equals(Object obj) { // if (this == obj) return true; // if (obj == null) return false; // if (getClass() != obj.getClass()) return false; // GroupMetadata<?> other = (GroupMetadata<?>) obj; // if (group == null) { // if (other.group != null) return false; // } else if (!group.equals(other.group)) return false; // return true; // } // // @Override // public String toString() { // return "GroupMetadata [group=" + group + ", priority=" + priority + "]"; // } // // // // // // // // } // Path: hazeltask-core/src/main/java/com/hazeltask/core/concurrent/collections/grouped/prioritizer/RoundRobinGroupPrioritizer.java import com.hazeltask.core.concurrent.collections.grouped.GroupMetadata; package com.hazeltask.core.concurrent.collections.grouped.prioritizer; public class RoundRobinGroupPrioritizer<G> implements GroupPrioritizer<G> { @Override
public long computePriority(GroupMetadata<G> metadata) {
jclawson/hazeltask
hazeltask-core/src/main/java/com/hazeltask/executor/local/HazeltaskThreadPoolExecutor.java
// Path: hazeltask-core/src/main/java/com/hazeltask/executor/ExecutorListener.java // public interface ExecutorListener< G extends Serializable>{ // public void beforeExecute(HazeltaskTask<G> runnable); // public void afterExecute(HazeltaskTask<G> runnable, Throwable exception); // } // // Path: hazeltask-core/src/main/java/com/hazeltask/executor/task/HazeltaskTask.java // public class HazeltaskTask< G extends Serializable> // implements Runnable, Task<G>, HazelcastInstanceAware, TrackCreated { // private static final long serialVersionUID = 1L; // // private Runnable runTask; // private Callable<?> callTask; // // private long createdAtMillis; // private UUID id; // private G group; // private Serializable taskInfo; // // private int submissionCount; // private transient HazelcastInstance hazelcastInstance; // private transient Timer taskExecutedTimer; // // private volatile transient Object result; // private volatile transient Exception e; // // //required for DataSerializable // protected HazeltaskTask(){} // // public HazeltaskTask(UUID id, G group, Serializable taskInfo, Runnable task){ // this.runTask = task; // this.id = id; // this.group = group; // createdAtMillis = System.currentTimeMillis(); // this.submissionCount = 1; // this.taskInfo = taskInfo; // } // // public HazeltaskTask(UUID id, G group, Serializable taskInfo, Callable<?> task){ // this.callTask = task; // this.id = id; // this.group = group; // createdAtMillis = System.currentTimeMillis(); // this.submissionCount = 1; // this.taskInfo = taskInfo; // } // // public void setSubmissionCount(int submissionCount){ // this.submissionCount = submissionCount; // } // // public int getSubmissionCount(){ // return this.submissionCount; // } // // public void updateCreatedTime(){ // this.createdAtMillis = System.currentTimeMillis(); // } // // public G getGroup() { // return group; // } // // public Object getResult() { // return result; // } // // public Exception getException() { // return e; // } // // public long getTimeCreated(){ // return createdAtMillis; // } // // public void run() { // Timer.Context ctx = null; // if(taskExecutedTimer != null) // ctx = taskExecutedTimer.time(); // try { // if(callTask != null) { // if(callTask instanceof HazelcastInstanceAware) { // ((HazelcastInstanceAware) callTask).setHazelcastInstance(hazelcastInstance); // } // this.result = callTask.call(); // } else { // if(runTask instanceof HazelcastInstanceAware) { // ((HazelcastInstanceAware) runTask).setHazelcastInstance(hazelcastInstance); // } // runTask.run(); // } // } catch (Exception t) { // this.e = t; // } finally { // if(ctx != null) // ctx.stop(); // } // } // // public Runnable getInnerRunnable() { // return this.runTask; // } // // public Callable<?> getInnerCallable() { // return this.callTask; // } // // @Override // public UUID getId() { // return id; // } // // @Override // public void setHazelcastInstance(HazelcastInstance hazelcastInstance) { // this.hazelcastInstance = hazelcastInstance; // } // // @Override // public void writeData(ObjectDataOutput out) throws IOException { // out.writeLong(id.getMostSignificantBits()); // out.writeLong(id.getLeastSignificantBits()); // // out.writeObject(group); // out.writeObject(runTask); // out.writeObject(callTask); // // out.writeLong(createdAtMillis); // out.writeInt(submissionCount); // } // // @SuppressWarnings("unchecked") // @Override // public void readData(ObjectDataInput in) throws IOException { // long m = in.readLong(); // long l = in.readLong(); // // id = new UUID(m, l); // group = (G) in.readObject(); // runTask = (Runnable) in.readObject(); // callTask = (Callable<?>) in.readObject(); // // createdAtMillis = in.readLong(); // submissionCount = in.readInt(); // } // // public void setExecutionTimer(Timer taskExecutedTimer) { // this.taskExecutedTimer = taskExecutedTimer; // } // // public Serializable getTaskInfo() { // return taskInfo; // } // // }
import java.util.Collection; import java.util.concurrent.BlockingQueue; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import lombok.extern.slf4j.Slf4j; import com.hazeltask.executor.ExecutorListener; import com.hazeltask.executor.task.HazeltaskTask;
package com.hazeltask.executor.local; @Slf4j public class HazeltaskThreadPoolExecutor extends ThreadPoolExecutor {
// Path: hazeltask-core/src/main/java/com/hazeltask/executor/ExecutorListener.java // public interface ExecutorListener< G extends Serializable>{ // public void beforeExecute(HazeltaskTask<G> runnable); // public void afterExecute(HazeltaskTask<G> runnable, Throwable exception); // } // // Path: hazeltask-core/src/main/java/com/hazeltask/executor/task/HazeltaskTask.java // public class HazeltaskTask< G extends Serializable> // implements Runnable, Task<G>, HazelcastInstanceAware, TrackCreated { // private static final long serialVersionUID = 1L; // // private Runnable runTask; // private Callable<?> callTask; // // private long createdAtMillis; // private UUID id; // private G group; // private Serializable taskInfo; // // private int submissionCount; // private transient HazelcastInstance hazelcastInstance; // private transient Timer taskExecutedTimer; // // private volatile transient Object result; // private volatile transient Exception e; // // //required for DataSerializable // protected HazeltaskTask(){} // // public HazeltaskTask(UUID id, G group, Serializable taskInfo, Runnable task){ // this.runTask = task; // this.id = id; // this.group = group; // createdAtMillis = System.currentTimeMillis(); // this.submissionCount = 1; // this.taskInfo = taskInfo; // } // // public HazeltaskTask(UUID id, G group, Serializable taskInfo, Callable<?> task){ // this.callTask = task; // this.id = id; // this.group = group; // createdAtMillis = System.currentTimeMillis(); // this.submissionCount = 1; // this.taskInfo = taskInfo; // } // // public void setSubmissionCount(int submissionCount){ // this.submissionCount = submissionCount; // } // // public int getSubmissionCount(){ // return this.submissionCount; // } // // public void updateCreatedTime(){ // this.createdAtMillis = System.currentTimeMillis(); // } // // public G getGroup() { // return group; // } // // public Object getResult() { // return result; // } // // public Exception getException() { // return e; // } // // public long getTimeCreated(){ // return createdAtMillis; // } // // public void run() { // Timer.Context ctx = null; // if(taskExecutedTimer != null) // ctx = taskExecutedTimer.time(); // try { // if(callTask != null) { // if(callTask instanceof HazelcastInstanceAware) { // ((HazelcastInstanceAware) callTask).setHazelcastInstance(hazelcastInstance); // } // this.result = callTask.call(); // } else { // if(runTask instanceof HazelcastInstanceAware) { // ((HazelcastInstanceAware) runTask).setHazelcastInstance(hazelcastInstance); // } // runTask.run(); // } // } catch (Exception t) { // this.e = t; // } finally { // if(ctx != null) // ctx.stop(); // } // } // // public Runnable getInnerRunnable() { // return this.runTask; // } // // public Callable<?> getInnerCallable() { // return this.callTask; // } // // @Override // public UUID getId() { // return id; // } // // @Override // public void setHazelcastInstance(HazelcastInstance hazelcastInstance) { // this.hazelcastInstance = hazelcastInstance; // } // // @Override // public void writeData(ObjectDataOutput out) throws IOException { // out.writeLong(id.getMostSignificantBits()); // out.writeLong(id.getLeastSignificantBits()); // // out.writeObject(group); // out.writeObject(runTask); // out.writeObject(callTask); // // out.writeLong(createdAtMillis); // out.writeInt(submissionCount); // } // // @SuppressWarnings("unchecked") // @Override // public void readData(ObjectDataInput in) throws IOException { // long m = in.readLong(); // long l = in.readLong(); // // id = new UUID(m, l); // group = (G) in.readObject(); // runTask = (Runnable) in.readObject(); // callTask = (Callable<?>) in.readObject(); // // createdAtMillis = in.readLong(); // submissionCount = in.readInt(); // } // // public void setExecutionTimer(Timer taskExecutedTimer) { // this.taskExecutedTimer = taskExecutedTimer; // } // // public Serializable getTaskInfo() { // return taskInfo; // } // // } // Path: hazeltask-core/src/main/java/com/hazeltask/executor/local/HazeltaskThreadPoolExecutor.java import java.util.Collection; import java.util.concurrent.BlockingQueue; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import lombok.extern.slf4j.Slf4j; import com.hazeltask.executor.ExecutorListener; import com.hazeltask.executor.task.HazeltaskTask; package com.hazeltask.executor.local; @Slf4j public class HazeltaskThreadPoolExecutor extends ThreadPoolExecutor {
private final Collection<ExecutorListener<?>> listeners = new CopyOnWriteArrayList<ExecutorListener<?>>();
jclawson/hazeltask
hazeltask-core/src/test/java/com/hazeltask/core/concurrent/collections/grouped/prioritizer/LoadBalancedPriorityPrioritizerTest.java
// Path: hazeltask-core/src/main/java/com/hazeltask/core/concurrent/collections/grouped/GroupMetadata.java // public final class GroupMetadata<G> implements Comparable<GroupMetadata<G>> { // private final G group; // private final long priority; // // public GroupMetadata(G group, long priority) { // if(group == null) { // throw new IllegalArgumentException("Group cannot be null"); // } // this.group = group; // this.priority = priority; // } // // public G getGroup() { // return group; // } // // public long getPriority() { // return priority; // } // // /** // * compareTo must be consistent with equals. If the priority is // * equal however, and the groups are NOT equal, we want to place // * *this* item at the end of the priority queue. // * // * TODO: do we still need to do this "hack" now that we use a skiplist and // * not a priority queue that breaks ties arbitrarily? // */ // @Override // public int compareTo(GroupMetadata<G> o) { // //return ((Long)priority).compareTo(o.priority); // int comparison = ((Long)priority).compareTo(o.priority); // if(comparison == 0) { // if(!group.equals(o.group)) { // return -1; // } // } // return comparison; // } // // //hash code and equals solely based on group // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((group == null) ? 0 : group.hashCode()); // return result; // } // // /** // * equals only cares about group equality. It doesn't compare priority. // */ // @Override // public boolean equals(Object obj) { // if (this == obj) return true; // if (obj == null) return false; // if (getClass() != obj.getClass()) return false; // GroupMetadata<?> other = (GroupMetadata<?>) obj; // if (group == null) { // if (other.group != null) return false; // } else if (!group.equals(other.group)) return false; // return true; // } // // @Override // public String toString() { // return "GroupMetadata [group=" + group + ", priority=" + priority + "]"; // } // // // // // // // // }
import java.util.EnumMap; import java.util.Map.Entry; import java.util.concurrent.ConcurrentSkipListSet; import junit.framework.Assert; import org.junit.Before; import org.junit.Test; import com.hazeltask.core.concurrent.collections.grouped.GroupMetadata;
package com.hazeltask.core.concurrent.collections.grouped.prioritizer; public class LoadBalancedPriorityPrioritizerTest { private EnumOrdinalPrioritizer<Priority> source; private LoadBalancedPriorityPrioritizer<Priority> prioritizer; @Before public void before() { source = new EnumOrdinalPrioritizer<Priority>(); prioritizer = new LoadBalancedPriorityPrioritizer<Priority>(source); } @Test public void test1() {
// Path: hazeltask-core/src/main/java/com/hazeltask/core/concurrent/collections/grouped/GroupMetadata.java // public final class GroupMetadata<G> implements Comparable<GroupMetadata<G>> { // private final G group; // private final long priority; // // public GroupMetadata(G group, long priority) { // if(group == null) { // throw new IllegalArgumentException("Group cannot be null"); // } // this.group = group; // this.priority = priority; // } // // public G getGroup() { // return group; // } // // public long getPriority() { // return priority; // } // // /** // * compareTo must be consistent with equals. If the priority is // * equal however, and the groups are NOT equal, we want to place // * *this* item at the end of the priority queue. // * // * TODO: do we still need to do this "hack" now that we use a skiplist and // * not a priority queue that breaks ties arbitrarily? // */ // @Override // public int compareTo(GroupMetadata<G> o) { // //return ((Long)priority).compareTo(o.priority); // int comparison = ((Long)priority).compareTo(o.priority); // if(comparison == 0) { // if(!group.equals(o.group)) { // return -1; // } // } // return comparison; // } // // //hash code and equals solely based on group // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((group == null) ? 0 : group.hashCode()); // return result; // } // // /** // * equals only cares about group equality. It doesn't compare priority. // */ // @Override // public boolean equals(Object obj) { // if (this == obj) return true; // if (obj == null) return false; // if (getClass() != obj.getClass()) return false; // GroupMetadata<?> other = (GroupMetadata<?>) obj; // if (group == null) { // if (other.group != null) return false; // } else if (!group.equals(other.group)) return false; // return true; // } // // @Override // public String toString() { // return "GroupMetadata [group=" + group + ", priority=" + priority + "]"; // } // // // // // // // // } // Path: hazeltask-core/src/test/java/com/hazeltask/core/concurrent/collections/grouped/prioritizer/LoadBalancedPriorityPrioritizerTest.java import java.util.EnumMap; import java.util.Map.Entry; import java.util.concurrent.ConcurrentSkipListSet; import junit.framework.Assert; import org.junit.Before; import org.junit.Test; import com.hazeltask.core.concurrent.collections.grouped.GroupMetadata; package com.hazeltask.core.concurrent.collections.grouped.prioritizer; public class LoadBalancedPriorityPrioritizerTest { private EnumOrdinalPrioritizer<Priority> source; private LoadBalancedPriorityPrioritizer<Priority> prioritizer; @Before public void before() { source = new EnumOrdinalPrioritizer<Priority>(); prioritizer = new LoadBalancedPriorityPrioritizer<Priority>(source); } @Test public void test1() {
ConcurrentSkipListSet<GroupMetadata<Priority>> set = new ConcurrentSkipListSet<GroupMetadata<Priority>>();
jclawson/hazeltask
hazeltask-core/src/main/java/com/hazeltask/executor/task/DefaultGroupableInfoProvidableTaskIdAdapter.java
// Path: hazeltask-core/src/main/java/com/hazeltask/core/concurrent/collections/grouped/Groupable.java // public interface Groupable<G> { // /** // * Return the group this object belongs to // * @return // */ // public G getGroup(); // }
import java.io.Serializable; import com.hazeltask.core.concurrent.collections.grouped.Groupable;
package com.hazeltask.executor.task; public class DefaultGroupableInfoProvidableTaskIdAdapter<I extends Serializable, G extends Serializable> implements TaskIdAdapter<TaskInfoProvidable<I,G>, G, Serializable> { @Override public G getTaskGroup(TaskInfoProvidable<I,G> task) { return task.getGroup(); } @Override public boolean supports(Object task) {
// Path: hazeltask-core/src/main/java/com/hazeltask/core/concurrent/collections/grouped/Groupable.java // public interface Groupable<G> { // /** // * Return the group this object belongs to // * @return // */ // public G getGroup(); // } // Path: hazeltask-core/src/main/java/com/hazeltask/executor/task/DefaultGroupableInfoProvidableTaskIdAdapter.java import java.io.Serializable; import com.hazeltask.core.concurrent.collections.grouped.Groupable; package com.hazeltask.executor.task; public class DefaultGroupableInfoProvidableTaskIdAdapter<I extends Serializable, G extends Serializable> implements TaskIdAdapter<TaskInfoProvidable<I,G>, G, Serializable> { @Override public G getTaskGroup(TaskInfoProvidable<I,G> task) { return task.getGroup(); } @Override public boolean supports(Object task) {
return task instanceof Groupable && task instanceof TaskInfoProvidable;
jclawson/hazeltask
hazeltask-core/src/test/java/com/hazeltask/config/ExecutorConfigTest.java
// Path: hazeltask-core/src/main/java/com/hazeltask/executor/task/DefaultTaskIdAdapter.java // public class DefaultTaskIdAdapter implements TaskIdAdapter<Object, Integer, Serializable> { // private static int GROUP = Integer.MIN_VALUE; // // @Override // public Integer getTaskGroup(Object task) { // return GROUP; // } // // @Override // public boolean supports(Object task) { // //we support all objects! // return true; // } // // @Override // public Serializable getTaskInfo(Object task) { // return null; // } // } // // Path: hazeltask-core/src/main/java/com/hazeltask/executor/task/TaskIdAdapter.java // public interface TaskIdAdapter<T, GROUP extends Serializable, INFO extends Serializable> { // // /** // * This might be useful to fill out to be able to get at task information // * without having to deserialize the entire task. It is also the only // * task-specific identifiable information available in TaskResponseListener // * // * @param task // * @return // */ // public INFO getTaskInfo(T task); // // /** // * The group does not need to be equal for successive calls with the same task // * @param task // * @return // */ // public GROUP getTaskGroup(T task); // // /** // * Given an object, return whether this adapater supports identifying the group // * Generally the logic is: <code>return task instanceof T</code> // * // * We have this here as a validation step when you submit a Runnable to the ExecutorService. // * Since ExecutorService isn't generic, we need to take extra steps to ensure the task // * is able to be processed by the system // * // * @param task // * @return // */ // public boolean supports(Object task); // }
import static org.junit.Assert.*; import java.io.Serializable; import junit.framework.Assert; import org.junit.Before; import org.junit.Test; import com.hazeltask.executor.task.DefaultTaskIdAdapter; import com.hazeltask.executor.task.TaskIdAdapter;
@Test public void corePoolSize() { assertEquals(4, config.getThreadCount()); config.withThreadCount(10); assertEquals(10, config.getThreadCount()); } // @Test // public void maxPoolSize() { // } @Test public void fixedThreadPoolTest_1() { assertEquals(4, config.getThreadCount()); assertEquals(4, config.getMaxThreadPoolSize()); config.withThreadCount(10); assertEquals(10, config.getThreadCount()); assertEquals(10, config.getMaxThreadPoolSize()); } @Test public void maxThreadKeepAlive() { assertEquals(60000, config.getMaxThreadKeepAliveTime()); config.withMaxThreadKeepAliveTime(1); assertEquals(1, config.getMaxThreadKeepAliveTime()); } @Test public void taskIdAdapter() {
// Path: hazeltask-core/src/main/java/com/hazeltask/executor/task/DefaultTaskIdAdapter.java // public class DefaultTaskIdAdapter implements TaskIdAdapter<Object, Integer, Serializable> { // private static int GROUP = Integer.MIN_VALUE; // // @Override // public Integer getTaskGroup(Object task) { // return GROUP; // } // // @Override // public boolean supports(Object task) { // //we support all objects! // return true; // } // // @Override // public Serializable getTaskInfo(Object task) { // return null; // } // } // // Path: hazeltask-core/src/main/java/com/hazeltask/executor/task/TaskIdAdapter.java // public interface TaskIdAdapter<T, GROUP extends Serializable, INFO extends Serializable> { // // /** // * This might be useful to fill out to be able to get at task information // * without having to deserialize the entire task. It is also the only // * task-specific identifiable information available in TaskResponseListener // * // * @param task // * @return // */ // public INFO getTaskInfo(T task); // // /** // * The group does not need to be equal for successive calls with the same task // * @param task // * @return // */ // public GROUP getTaskGroup(T task); // // /** // * Given an object, return whether this adapater supports identifying the group // * Generally the logic is: <code>return task instanceof T</code> // * // * We have this here as a validation step when you submit a Runnable to the ExecutorService. // * Since ExecutorService isn't generic, we need to take extra steps to ensure the task // * is able to be processed by the system // * // * @param task // * @return // */ // public boolean supports(Object task); // } // Path: hazeltask-core/src/test/java/com/hazeltask/config/ExecutorConfigTest.java import static org.junit.Assert.*; import java.io.Serializable; import junit.framework.Assert; import org.junit.Before; import org.junit.Test; import com.hazeltask.executor.task.DefaultTaskIdAdapter; import com.hazeltask.executor.task.TaskIdAdapter; @Test public void corePoolSize() { assertEquals(4, config.getThreadCount()); config.withThreadCount(10); assertEquals(10, config.getThreadCount()); } // @Test // public void maxPoolSize() { // } @Test public void fixedThreadPoolTest_1() { assertEquals(4, config.getThreadCount()); assertEquals(4, config.getMaxThreadPoolSize()); config.withThreadCount(10); assertEquals(10, config.getThreadCount()); assertEquals(10, config.getMaxThreadPoolSize()); } @Test public void maxThreadKeepAlive() { assertEquals(60000, config.getMaxThreadKeepAliveTime()); config.withMaxThreadKeepAliveTime(1); assertEquals(1, config.getMaxThreadKeepAliveTime()); } @Test public void taskIdAdapter() {
TaskIdAdapter tmp = new TaskIdAdapter() {
jclawson/hazeltask
hazeltask-core/src/test/java/com/hazeltask/config/ExecutorConfigTest.java
// Path: hazeltask-core/src/main/java/com/hazeltask/executor/task/DefaultTaskIdAdapter.java // public class DefaultTaskIdAdapter implements TaskIdAdapter<Object, Integer, Serializable> { // private static int GROUP = Integer.MIN_VALUE; // // @Override // public Integer getTaskGroup(Object task) { // return GROUP; // } // // @Override // public boolean supports(Object task) { // //we support all objects! // return true; // } // // @Override // public Serializable getTaskInfo(Object task) { // return null; // } // } // // Path: hazeltask-core/src/main/java/com/hazeltask/executor/task/TaskIdAdapter.java // public interface TaskIdAdapter<T, GROUP extends Serializable, INFO extends Serializable> { // // /** // * This might be useful to fill out to be able to get at task information // * without having to deserialize the entire task. It is also the only // * task-specific identifiable information available in TaskResponseListener // * // * @param task // * @return // */ // public INFO getTaskInfo(T task); // // /** // * The group does not need to be equal for successive calls with the same task // * @param task // * @return // */ // public GROUP getTaskGroup(T task); // // /** // * Given an object, return whether this adapater supports identifying the group // * Generally the logic is: <code>return task instanceof T</code> // * // * We have this here as a validation step when you submit a Runnable to the ExecutorService. // * Since ExecutorService isn't generic, we need to take extra steps to ensure the task // * is able to be processed by the system // * // * @param task // * @return // */ // public boolean supports(Object task); // }
import static org.junit.Assert.*; import java.io.Serializable; import junit.framework.Assert; import org.junit.Before; import org.junit.Test; import com.hazeltask.executor.task.DefaultTaskIdAdapter; import com.hazeltask.executor.task.TaskIdAdapter;
// } @Test public void fixedThreadPoolTest_1() { assertEquals(4, config.getThreadCount()); assertEquals(4, config.getMaxThreadPoolSize()); config.withThreadCount(10); assertEquals(10, config.getThreadCount()); assertEquals(10, config.getMaxThreadPoolSize()); } @Test public void maxThreadKeepAlive() { assertEquals(60000, config.getMaxThreadKeepAliveTime()); config.withMaxThreadKeepAliveTime(1); assertEquals(1, config.getMaxThreadKeepAliveTime()); } @Test public void taskIdAdapter() { TaskIdAdapter tmp = new TaskIdAdapter() { public Serializable getTaskGroup(Object task) {return null;} public boolean supports(Object task) {return false;} @Override public Serializable getTaskInfo(Object task) { return null; } };
// Path: hazeltask-core/src/main/java/com/hazeltask/executor/task/DefaultTaskIdAdapter.java // public class DefaultTaskIdAdapter implements TaskIdAdapter<Object, Integer, Serializable> { // private static int GROUP = Integer.MIN_VALUE; // // @Override // public Integer getTaskGroup(Object task) { // return GROUP; // } // // @Override // public boolean supports(Object task) { // //we support all objects! // return true; // } // // @Override // public Serializable getTaskInfo(Object task) { // return null; // } // } // // Path: hazeltask-core/src/main/java/com/hazeltask/executor/task/TaskIdAdapter.java // public interface TaskIdAdapter<T, GROUP extends Serializable, INFO extends Serializable> { // // /** // * This might be useful to fill out to be able to get at task information // * without having to deserialize the entire task. It is also the only // * task-specific identifiable information available in TaskResponseListener // * // * @param task // * @return // */ // public INFO getTaskInfo(T task); // // /** // * The group does not need to be equal for successive calls with the same task // * @param task // * @return // */ // public GROUP getTaskGroup(T task); // // /** // * Given an object, return whether this adapater supports identifying the group // * Generally the logic is: <code>return task instanceof T</code> // * // * We have this here as a validation step when you submit a Runnable to the ExecutorService. // * Since ExecutorService isn't generic, we need to take extra steps to ensure the task // * is able to be processed by the system // * // * @param task // * @return // */ // public boolean supports(Object task); // } // Path: hazeltask-core/src/test/java/com/hazeltask/config/ExecutorConfigTest.java import static org.junit.Assert.*; import java.io.Serializable; import junit.framework.Assert; import org.junit.Before; import org.junit.Test; import com.hazeltask.executor.task.DefaultTaskIdAdapter; import com.hazeltask.executor.task.TaskIdAdapter; // } @Test public void fixedThreadPoolTest_1() { assertEquals(4, config.getThreadCount()); assertEquals(4, config.getMaxThreadPoolSize()); config.withThreadCount(10); assertEquals(10, config.getThreadCount()); assertEquals(10, config.getMaxThreadPoolSize()); } @Test public void maxThreadKeepAlive() { assertEquals(60000, config.getMaxThreadKeepAliveTime()); config.withMaxThreadKeepAliveTime(1); assertEquals(1, config.getMaxThreadKeepAliveTime()); } @Test public void taskIdAdapter() { TaskIdAdapter tmp = new TaskIdAdapter() { public Serializable getTaskGroup(Object task) {return null;} public boolean supports(Object task) {return false;} @Override public Serializable getTaskInfo(Object task) { return null; } };
assertEquals(DefaultTaskIdAdapter.class, config.getTaskIdAdapter().getClass());
jclawson/hazeltask
hazeltask-core/src/main/java/com/hazeltask/HazeltaskStatisticsService.java
// Path: hazeltask-core/src/main/java/com/hazeltask/executor/IExecutorTopologyService.java // public interface IExecutorTopologyService<GROUP extends Serializable> { // //public boolean isMemberReady(Member member); // // public void sendTask(HazeltaskTask<GROUP> task, Member member) throws TimeoutException; // // // /** // * // * @param task // * @param replaceIfExists // * @return // */ // public boolean addPendingTask(HazeltaskTask<GROUP> task, boolean replaceIfExists); // // /** // * Retrive the hazeltasks in the local pending task map with the predicate restriction // * @param predicate // * @return // */ // public Collection<HazeltaskTask<GROUP>> getLocalPendingTasks(String predicate); // // /** // * Get the local queue sizes for each member // * // * // * @return // */ // public Collection<MemberResponse<Long>> getMemberQueueSizes(); // // /** // * Get the local queue sizes for each group on each member // * // * // * @return // */ // public Collection<MemberResponse<Map<GROUP, Integer>>> getMemberGroupSizes(); // // /** // * Get the local partition's size of the pending work map // * TODO: should this live in a different Service class? // * @return // */ // public int getLocalPendingTaskMapSize(); // // public Collection<MemberResponse<Long>> getOldestTaskTimestamps(); // // /** // * // * @param task // * @return true if removed, false it did not exist // */ // public boolean removePendingTask(HazeltaskTask<GROUP> task); // public boolean removePendingTask(UUID taskId); // // public void broadcastTaskCompletion(UUID taskId, Serializable response, Serializable taskInfo); // public void broadcastTaskCancellation(UUID taskId, Serializable taskInfo); // public void broadcastTaskError(UUID taskId, Throwable exception, Serializable taskInfo); // public void addTaskResponseMessageHandler(MessageListener<TaskResponse<Serializable>> listener); // // public Lock getRebalanceTaskClusterLock(); // // public Collection<HazeltaskTask<GROUP>> stealTasks(List<MemberValuePair<Long>> numToTake); // //public boolean addTaskToLocalQueue(HazelcastWork task); // // public Collection<MemberResponse<Integer>> getThreadPoolSizes(); // public Collection<MemberResponse<Map<GROUP, Integer>>> getGroupSizes(Predicate<GROUP> predicate); // public void clearGroupQueue(GROUP group); // // public boolean cancelTask(GROUP group, UUID taskId); // } // // Path: hazeltask-core/src/main/java/com/hazeltask/hazelcast/MemberTasks.java // public static class MemberResponse<T> implements Serializable { // private static final long serialVersionUID = 1L; // // private T value; // private Member member; // // public MemberResponse(){} // // public MemberResponse(Member member, T value) { // this.value = value; // this.member = member; // } // public T getValue() { // return value; // } // public Member getMember() { // return member; // } // }
import java.io.Serializable; import java.util.Collection; import java.util.Map; import com.google.common.base.Predicate; import com.hazeltask.executor.IExecutorTopologyService; import com.hazeltask.hazelcast.MemberTasks.MemberResponse;
package com.hazeltask; public class HazeltaskStatisticsService<GROUP extends Serializable> implements ClusterService<GROUP> { private final IExecutorTopologyService<GROUP> executorTopologyService; public HazeltaskStatisticsService(IExecutorTopologyService<GROUP> executorTopologyService) { this.executorTopologyService = executorTopologyService; } @Override
// Path: hazeltask-core/src/main/java/com/hazeltask/executor/IExecutorTopologyService.java // public interface IExecutorTopologyService<GROUP extends Serializable> { // //public boolean isMemberReady(Member member); // // public void sendTask(HazeltaskTask<GROUP> task, Member member) throws TimeoutException; // // // /** // * // * @param task // * @param replaceIfExists // * @return // */ // public boolean addPendingTask(HazeltaskTask<GROUP> task, boolean replaceIfExists); // // /** // * Retrive the hazeltasks in the local pending task map with the predicate restriction // * @param predicate // * @return // */ // public Collection<HazeltaskTask<GROUP>> getLocalPendingTasks(String predicate); // // /** // * Get the local queue sizes for each member // * // * // * @return // */ // public Collection<MemberResponse<Long>> getMemberQueueSizes(); // // /** // * Get the local queue sizes for each group on each member // * // * // * @return // */ // public Collection<MemberResponse<Map<GROUP, Integer>>> getMemberGroupSizes(); // // /** // * Get the local partition's size of the pending work map // * TODO: should this live in a different Service class? // * @return // */ // public int getLocalPendingTaskMapSize(); // // public Collection<MemberResponse<Long>> getOldestTaskTimestamps(); // // /** // * // * @param task // * @return true if removed, false it did not exist // */ // public boolean removePendingTask(HazeltaskTask<GROUP> task); // public boolean removePendingTask(UUID taskId); // // public void broadcastTaskCompletion(UUID taskId, Serializable response, Serializable taskInfo); // public void broadcastTaskCancellation(UUID taskId, Serializable taskInfo); // public void broadcastTaskError(UUID taskId, Throwable exception, Serializable taskInfo); // public void addTaskResponseMessageHandler(MessageListener<TaskResponse<Serializable>> listener); // // public Lock getRebalanceTaskClusterLock(); // // public Collection<HazeltaskTask<GROUP>> stealTasks(List<MemberValuePair<Long>> numToTake); // //public boolean addTaskToLocalQueue(HazelcastWork task); // // public Collection<MemberResponse<Integer>> getThreadPoolSizes(); // public Collection<MemberResponse<Map<GROUP, Integer>>> getGroupSizes(Predicate<GROUP> predicate); // public void clearGroupQueue(GROUP group); // // public boolean cancelTask(GROUP group, UUID taskId); // } // // Path: hazeltask-core/src/main/java/com/hazeltask/hazelcast/MemberTasks.java // public static class MemberResponse<T> implements Serializable { // private static final long serialVersionUID = 1L; // // private T value; // private Member member; // // public MemberResponse(){} // // public MemberResponse(Member member, T value) { // this.value = value; // this.member = member; // } // public T getValue() { // return value; // } // public Member getMember() { // return member; // } // } // Path: hazeltask-core/src/main/java/com/hazeltask/HazeltaskStatisticsService.java import java.io.Serializable; import java.util.Collection; import java.util.Map; import com.google.common.base.Predicate; import com.hazeltask.executor.IExecutorTopologyService; import com.hazeltask.hazelcast.MemberTasks.MemberResponse; package com.hazeltask; public class HazeltaskStatisticsService<GROUP extends Serializable> implements ClusterService<GROUP> { private final IExecutorTopologyService<GROUP> executorTopologyService; public HazeltaskStatisticsService(IExecutorTopologyService<GROUP> executorTopologyService) { this.executorTopologyService = executorTopologyService; } @Override
public Collection<MemberResponse<Long>> getQueueSizes() {
jclawson/hazeltask
hazeltask-core/src/test/java/com/hazeltask/executor/local/HazeltaskThreadPoolExecutorTest.java
// Path: hazeltask-core/src/main/java/com/hazeltask/executor/ExecutorListener.java // public interface ExecutorListener< G extends Serializable>{ // public void beforeExecute(HazeltaskTask<G> runnable); // public void afterExecute(HazeltaskTask<G> runnable, Throwable exception); // } // // Path: hazeltask-core/src/main/java/com/hazeltask/executor/task/HazeltaskTask.java // public class HazeltaskTask< G extends Serializable> // implements Runnable, Task<G>, HazelcastInstanceAware, TrackCreated { // private static final long serialVersionUID = 1L; // // private Runnable runTask; // private Callable<?> callTask; // // private long createdAtMillis; // private UUID id; // private G group; // private Serializable taskInfo; // // private int submissionCount; // private transient HazelcastInstance hazelcastInstance; // private transient Timer taskExecutedTimer; // // private volatile transient Object result; // private volatile transient Exception e; // // //required for DataSerializable // protected HazeltaskTask(){} // // public HazeltaskTask(UUID id, G group, Serializable taskInfo, Runnable task){ // this.runTask = task; // this.id = id; // this.group = group; // createdAtMillis = System.currentTimeMillis(); // this.submissionCount = 1; // this.taskInfo = taskInfo; // } // // public HazeltaskTask(UUID id, G group, Serializable taskInfo, Callable<?> task){ // this.callTask = task; // this.id = id; // this.group = group; // createdAtMillis = System.currentTimeMillis(); // this.submissionCount = 1; // this.taskInfo = taskInfo; // } // // public void setSubmissionCount(int submissionCount){ // this.submissionCount = submissionCount; // } // // public int getSubmissionCount(){ // return this.submissionCount; // } // // public void updateCreatedTime(){ // this.createdAtMillis = System.currentTimeMillis(); // } // // public G getGroup() { // return group; // } // // public Object getResult() { // return result; // } // // public Exception getException() { // return e; // } // // public long getTimeCreated(){ // return createdAtMillis; // } // // public void run() { // Timer.Context ctx = null; // if(taskExecutedTimer != null) // ctx = taskExecutedTimer.time(); // try { // if(callTask != null) { // if(callTask instanceof HazelcastInstanceAware) { // ((HazelcastInstanceAware) callTask).setHazelcastInstance(hazelcastInstance); // } // this.result = callTask.call(); // } else { // if(runTask instanceof HazelcastInstanceAware) { // ((HazelcastInstanceAware) runTask).setHazelcastInstance(hazelcastInstance); // } // runTask.run(); // } // } catch (Exception t) { // this.e = t; // } finally { // if(ctx != null) // ctx.stop(); // } // } // // public Runnable getInnerRunnable() { // return this.runTask; // } // // public Callable<?> getInnerCallable() { // return this.callTask; // } // // @Override // public UUID getId() { // return id; // } // // @Override // public void setHazelcastInstance(HazelcastInstance hazelcastInstance) { // this.hazelcastInstance = hazelcastInstance; // } // // @Override // public void writeData(ObjectDataOutput out) throws IOException { // out.writeLong(id.getMostSignificantBits()); // out.writeLong(id.getLeastSignificantBits()); // // out.writeObject(group); // out.writeObject(runTask); // out.writeObject(callTask); // // out.writeLong(createdAtMillis); // out.writeInt(submissionCount); // } // // @SuppressWarnings("unchecked") // @Override // public void readData(ObjectDataInput in) throws IOException { // long m = in.readLong(); // long l = in.readLong(); // // id = new UUID(m, l); // group = (G) in.readObject(); // runTask = (Runnable) in.readObject(); // callTask = (Callable<?>) in.readObject(); // // createdAtMillis = in.readLong(); // submissionCount = in.readInt(); // } // // public void setExecutionTimer(Timer taskExecutedTimer) { // this.taskExecutedTimer = taskExecutedTimer; // } // // public Serializable getTaskInfo() { // return taskInfo; // } // // }
import static org.mockito.Matchers.eq; import static org.mockito.Matchers.isNull; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import java.util.UUID; import java.util.concurrent.Executors; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor.AbortPolicy; import java.util.concurrent.TimeUnit; import org.junit.Before; import org.junit.Test; import com.hazeltask.executor.ExecutorListener; import com.hazeltask.executor.task.HazeltaskTask;
package com.hazeltask.executor.local; public class HazeltaskThreadPoolExecutorTest { private HazeltaskThreadPoolExecutor listener;
// Path: hazeltask-core/src/main/java/com/hazeltask/executor/ExecutorListener.java // public interface ExecutorListener< G extends Serializable>{ // public void beforeExecute(HazeltaskTask<G> runnable); // public void afterExecute(HazeltaskTask<G> runnable, Throwable exception); // } // // Path: hazeltask-core/src/main/java/com/hazeltask/executor/task/HazeltaskTask.java // public class HazeltaskTask< G extends Serializable> // implements Runnable, Task<G>, HazelcastInstanceAware, TrackCreated { // private static final long serialVersionUID = 1L; // // private Runnable runTask; // private Callable<?> callTask; // // private long createdAtMillis; // private UUID id; // private G group; // private Serializable taskInfo; // // private int submissionCount; // private transient HazelcastInstance hazelcastInstance; // private transient Timer taskExecutedTimer; // // private volatile transient Object result; // private volatile transient Exception e; // // //required for DataSerializable // protected HazeltaskTask(){} // // public HazeltaskTask(UUID id, G group, Serializable taskInfo, Runnable task){ // this.runTask = task; // this.id = id; // this.group = group; // createdAtMillis = System.currentTimeMillis(); // this.submissionCount = 1; // this.taskInfo = taskInfo; // } // // public HazeltaskTask(UUID id, G group, Serializable taskInfo, Callable<?> task){ // this.callTask = task; // this.id = id; // this.group = group; // createdAtMillis = System.currentTimeMillis(); // this.submissionCount = 1; // this.taskInfo = taskInfo; // } // // public void setSubmissionCount(int submissionCount){ // this.submissionCount = submissionCount; // } // // public int getSubmissionCount(){ // return this.submissionCount; // } // // public void updateCreatedTime(){ // this.createdAtMillis = System.currentTimeMillis(); // } // // public G getGroup() { // return group; // } // // public Object getResult() { // return result; // } // // public Exception getException() { // return e; // } // // public long getTimeCreated(){ // return createdAtMillis; // } // // public void run() { // Timer.Context ctx = null; // if(taskExecutedTimer != null) // ctx = taskExecutedTimer.time(); // try { // if(callTask != null) { // if(callTask instanceof HazelcastInstanceAware) { // ((HazelcastInstanceAware) callTask).setHazelcastInstance(hazelcastInstance); // } // this.result = callTask.call(); // } else { // if(runTask instanceof HazelcastInstanceAware) { // ((HazelcastInstanceAware) runTask).setHazelcastInstance(hazelcastInstance); // } // runTask.run(); // } // } catch (Exception t) { // this.e = t; // } finally { // if(ctx != null) // ctx.stop(); // } // } // // public Runnable getInnerRunnable() { // return this.runTask; // } // // public Callable<?> getInnerCallable() { // return this.callTask; // } // // @Override // public UUID getId() { // return id; // } // // @Override // public void setHazelcastInstance(HazelcastInstance hazelcastInstance) { // this.hazelcastInstance = hazelcastInstance; // } // // @Override // public void writeData(ObjectDataOutput out) throws IOException { // out.writeLong(id.getMostSignificantBits()); // out.writeLong(id.getLeastSignificantBits()); // // out.writeObject(group); // out.writeObject(runTask); // out.writeObject(callTask); // // out.writeLong(createdAtMillis); // out.writeInt(submissionCount); // } // // @SuppressWarnings("unchecked") // @Override // public void readData(ObjectDataInput in) throws IOException { // long m = in.readLong(); // long l = in.readLong(); // // id = new UUID(m, l); // group = (G) in.readObject(); // runTask = (Runnable) in.readObject(); // callTask = (Callable<?>) in.readObject(); // // createdAtMillis = in.readLong(); // submissionCount = in.readInt(); // } // // public void setExecutionTimer(Timer taskExecutedTimer) { // this.taskExecutedTimer = taskExecutedTimer; // } // // public Serializable getTaskInfo() { // return taskInfo; // } // // } // Path: hazeltask-core/src/test/java/com/hazeltask/executor/local/HazeltaskThreadPoolExecutorTest.java import static org.mockito.Matchers.eq; import static org.mockito.Matchers.isNull; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import java.util.UUID; import java.util.concurrent.Executors; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor.AbortPolicy; import java.util.concurrent.TimeUnit; import org.junit.Before; import org.junit.Test; import com.hazeltask.executor.ExecutorListener; import com.hazeltask.executor.task.HazeltaskTask; package com.hazeltask.executor.local; public class HazeltaskThreadPoolExecutorTest { private HazeltaskThreadPoolExecutor listener;
private ExecutorListener listener1;
jclawson/hazeltask
hazeltask-core/src/test/java/com/hazeltask/executor/local/HazeltaskThreadPoolExecutorTest.java
// Path: hazeltask-core/src/main/java/com/hazeltask/executor/ExecutorListener.java // public interface ExecutorListener< G extends Serializable>{ // public void beforeExecute(HazeltaskTask<G> runnable); // public void afterExecute(HazeltaskTask<G> runnable, Throwable exception); // } // // Path: hazeltask-core/src/main/java/com/hazeltask/executor/task/HazeltaskTask.java // public class HazeltaskTask< G extends Serializable> // implements Runnable, Task<G>, HazelcastInstanceAware, TrackCreated { // private static final long serialVersionUID = 1L; // // private Runnable runTask; // private Callable<?> callTask; // // private long createdAtMillis; // private UUID id; // private G group; // private Serializable taskInfo; // // private int submissionCount; // private transient HazelcastInstance hazelcastInstance; // private transient Timer taskExecutedTimer; // // private volatile transient Object result; // private volatile transient Exception e; // // //required for DataSerializable // protected HazeltaskTask(){} // // public HazeltaskTask(UUID id, G group, Serializable taskInfo, Runnable task){ // this.runTask = task; // this.id = id; // this.group = group; // createdAtMillis = System.currentTimeMillis(); // this.submissionCount = 1; // this.taskInfo = taskInfo; // } // // public HazeltaskTask(UUID id, G group, Serializable taskInfo, Callable<?> task){ // this.callTask = task; // this.id = id; // this.group = group; // createdAtMillis = System.currentTimeMillis(); // this.submissionCount = 1; // this.taskInfo = taskInfo; // } // // public void setSubmissionCount(int submissionCount){ // this.submissionCount = submissionCount; // } // // public int getSubmissionCount(){ // return this.submissionCount; // } // // public void updateCreatedTime(){ // this.createdAtMillis = System.currentTimeMillis(); // } // // public G getGroup() { // return group; // } // // public Object getResult() { // return result; // } // // public Exception getException() { // return e; // } // // public long getTimeCreated(){ // return createdAtMillis; // } // // public void run() { // Timer.Context ctx = null; // if(taskExecutedTimer != null) // ctx = taskExecutedTimer.time(); // try { // if(callTask != null) { // if(callTask instanceof HazelcastInstanceAware) { // ((HazelcastInstanceAware) callTask).setHazelcastInstance(hazelcastInstance); // } // this.result = callTask.call(); // } else { // if(runTask instanceof HazelcastInstanceAware) { // ((HazelcastInstanceAware) runTask).setHazelcastInstance(hazelcastInstance); // } // runTask.run(); // } // } catch (Exception t) { // this.e = t; // } finally { // if(ctx != null) // ctx.stop(); // } // } // // public Runnable getInnerRunnable() { // return this.runTask; // } // // public Callable<?> getInnerCallable() { // return this.callTask; // } // // @Override // public UUID getId() { // return id; // } // // @Override // public void setHazelcastInstance(HazelcastInstance hazelcastInstance) { // this.hazelcastInstance = hazelcastInstance; // } // // @Override // public void writeData(ObjectDataOutput out) throws IOException { // out.writeLong(id.getMostSignificantBits()); // out.writeLong(id.getLeastSignificantBits()); // // out.writeObject(group); // out.writeObject(runTask); // out.writeObject(callTask); // // out.writeLong(createdAtMillis); // out.writeInt(submissionCount); // } // // @SuppressWarnings("unchecked") // @Override // public void readData(ObjectDataInput in) throws IOException { // long m = in.readLong(); // long l = in.readLong(); // // id = new UUID(m, l); // group = (G) in.readObject(); // runTask = (Runnable) in.readObject(); // callTask = (Callable<?>) in.readObject(); // // createdAtMillis = in.readLong(); // submissionCount = in.readInt(); // } // // public void setExecutionTimer(Timer taskExecutedTimer) { // this.taskExecutedTimer = taskExecutedTimer; // } // // public Serializable getTaskInfo() { // return taskInfo; // } // // }
import static org.mockito.Matchers.eq; import static org.mockito.Matchers.isNull; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import java.util.UUID; import java.util.concurrent.Executors; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor.AbortPolicy; import java.util.concurrent.TimeUnit; import org.junit.Before; import org.junit.Test; import com.hazeltask.executor.ExecutorListener; import com.hazeltask.executor.task.HazeltaskTask;
package com.hazeltask.executor.local; public class HazeltaskThreadPoolExecutorTest { private HazeltaskThreadPoolExecutor listener; private ExecutorListener listener1; private ExecutorListener listener2;
// Path: hazeltask-core/src/main/java/com/hazeltask/executor/ExecutorListener.java // public interface ExecutorListener< G extends Serializable>{ // public void beforeExecute(HazeltaskTask<G> runnable); // public void afterExecute(HazeltaskTask<G> runnable, Throwable exception); // } // // Path: hazeltask-core/src/main/java/com/hazeltask/executor/task/HazeltaskTask.java // public class HazeltaskTask< G extends Serializable> // implements Runnable, Task<G>, HazelcastInstanceAware, TrackCreated { // private static final long serialVersionUID = 1L; // // private Runnable runTask; // private Callable<?> callTask; // // private long createdAtMillis; // private UUID id; // private G group; // private Serializable taskInfo; // // private int submissionCount; // private transient HazelcastInstance hazelcastInstance; // private transient Timer taskExecutedTimer; // // private volatile transient Object result; // private volatile transient Exception e; // // //required for DataSerializable // protected HazeltaskTask(){} // // public HazeltaskTask(UUID id, G group, Serializable taskInfo, Runnable task){ // this.runTask = task; // this.id = id; // this.group = group; // createdAtMillis = System.currentTimeMillis(); // this.submissionCount = 1; // this.taskInfo = taskInfo; // } // // public HazeltaskTask(UUID id, G group, Serializable taskInfo, Callable<?> task){ // this.callTask = task; // this.id = id; // this.group = group; // createdAtMillis = System.currentTimeMillis(); // this.submissionCount = 1; // this.taskInfo = taskInfo; // } // // public void setSubmissionCount(int submissionCount){ // this.submissionCount = submissionCount; // } // // public int getSubmissionCount(){ // return this.submissionCount; // } // // public void updateCreatedTime(){ // this.createdAtMillis = System.currentTimeMillis(); // } // // public G getGroup() { // return group; // } // // public Object getResult() { // return result; // } // // public Exception getException() { // return e; // } // // public long getTimeCreated(){ // return createdAtMillis; // } // // public void run() { // Timer.Context ctx = null; // if(taskExecutedTimer != null) // ctx = taskExecutedTimer.time(); // try { // if(callTask != null) { // if(callTask instanceof HazelcastInstanceAware) { // ((HazelcastInstanceAware) callTask).setHazelcastInstance(hazelcastInstance); // } // this.result = callTask.call(); // } else { // if(runTask instanceof HazelcastInstanceAware) { // ((HazelcastInstanceAware) runTask).setHazelcastInstance(hazelcastInstance); // } // runTask.run(); // } // } catch (Exception t) { // this.e = t; // } finally { // if(ctx != null) // ctx.stop(); // } // } // // public Runnable getInnerRunnable() { // return this.runTask; // } // // public Callable<?> getInnerCallable() { // return this.callTask; // } // // @Override // public UUID getId() { // return id; // } // // @Override // public void setHazelcastInstance(HazelcastInstance hazelcastInstance) { // this.hazelcastInstance = hazelcastInstance; // } // // @Override // public void writeData(ObjectDataOutput out) throws IOException { // out.writeLong(id.getMostSignificantBits()); // out.writeLong(id.getLeastSignificantBits()); // // out.writeObject(group); // out.writeObject(runTask); // out.writeObject(callTask); // // out.writeLong(createdAtMillis); // out.writeInt(submissionCount); // } // // @SuppressWarnings("unchecked") // @Override // public void readData(ObjectDataInput in) throws IOException { // long m = in.readLong(); // long l = in.readLong(); // // id = new UUID(m, l); // group = (G) in.readObject(); // runTask = (Runnable) in.readObject(); // callTask = (Callable<?>) in.readObject(); // // createdAtMillis = in.readLong(); // submissionCount = in.readInt(); // } // // public void setExecutionTimer(Timer taskExecutedTimer) { // this.taskExecutedTimer = taskExecutedTimer; // } // // public Serializable getTaskInfo() { // return taskInfo; // } // // } // Path: hazeltask-core/src/test/java/com/hazeltask/executor/local/HazeltaskThreadPoolExecutorTest.java import static org.mockito.Matchers.eq; import static org.mockito.Matchers.isNull; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import java.util.UUID; import java.util.concurrent.Executors; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor.AbortPolicy; import java.util.concurrent.TimeUnit; import org.junit.Before; import org.junit.Test; import com.hazeltask.executor.ExecutorListener; import com.hazeltask.executor.task.HazeltaskTask; package com.hazeltask.executor.local; public class HazeltaskThreadPoolExecutorTest { private HazeltaskThreadPoolExecutor listener; private ExecutorListener listener1; private ExecutorListener listener2;
private HazeltaskTask<String> task;
enguerrand/xdat
src/main/java/org/xdat/data/Parameter.java
// Path: src/main/java/org/xdat/exceptions/CorruptDataException.java // public class CorruptDataException extends RuntimeException { // // public CorruptDataException(Parameter corruptParameter) { // super("The data of parameter \"" + corruptParameter.getName() + "\" seems to be corrupt!"); // } // // }
import org.xdat.exceptions.CorruptDataException; import java.awt.FontMetrics; import java.io.Serializable; import java.util.Comparator; import java.util.Iterator; import java.util.Optional; import java.util.TreeSet; import java.util.stream.Collectors;
* @return the numeric representation of the given string */ double getDoubleValueOf(String string) { if (this.numeric) { Optional<Float> parsed = NumberParser.parseNumber(string); if(parsed.isPresent()) { return parsed.get(); } } int index = 0; Iterator<String> it = discreteLevels.iterator(); while (it.hasNext()) { if (string.equalsIgnoreCase(it.next())) { return index; } index++; } // String not found, add it to discrete levels this.discreteLevels.add(string); index = 0; it = discreteLevels.iterator(); while (it.hasNext()) { String next = it.next(); if (string.equalsIgnoreCase(next)) { return index; } index++; }
// Path: src/main/java/org/xdat/exceptions/CorruptDataException.java // public class CorruptDataException extends RuntimeException { // // public CorruptDataException(Parameter corruptParameter) { // super("The data of parameter \"" + corruptParameter.getName() + "\" seems to be corrupt!"); // } // // } // Path: src/main/java/org/xdat/data/Parameter.java import org.xdat.exceptions.CorruptDataException; import java.awt.FontMetrics; import java.io.Serializable; import java.util.Comparator; import java.util.Iterator; import java.util.Optional; import java.util.TreeSet; import java.util.stream.Collectors; * @return the numeric representation of the given string */ double getDoubleValueOf(String string) { if (this.numeric) { Optional<Float> parsed = NumberParser.parseNumber(string); if(parsed.isPresent()) { return parsed.get(); } } int index = 0; Iterator<String> it = discreteLevels.iterator(); while (it.hasNext()) { if (string.equalsIgnoreCase(it.next())) { return index; } index++; } // String not found, add it to discrete levels this.discreteLevels.add(string); index = 0; it = discreteLevels.iterator(); while (it.hasNext()) { String next = it.next(); if (string.equalsIgnoreCase(next)) { return index; } index++; }
throw new CorruptDataException(this);
enguerrand/xdat
src/main/java/org/xdat/gui/panels/TitledSubPanel.java
// Path: src/main/java/org/xdat/gui/UiDefines.java // public class UiDefines { // public static final int PADDING = 5; // }
import org.xdat.gui.UiDefines; import javax.swing.BorderFactory; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import javax.swing.border.TitledBorder; import java.awt.Font;
/* * Copyright 2014, Enguerrand de Rochefort * * This file is part of xdat. * * xdat is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * xdat is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with xdat. If not, see <http://www.gnu.org/licenses/>. * */ package org.xdat.gui.panels; public class TitledSubPanel extends JPanel { public TitledSubPanel(String title) { super(); TitledBorder titledBorder = BorderFactory.createTitledBorder(title); titledBorder.setTitleFont(new Font("SansSerif", Font.BOLD, 16));
// Path: src/main/java/org/xdat/gui/UiDefines.java // public class UiDefines { // public static final int PADDING = 5; // } // Path: src/main/java/org/xdat/gui/panels/TitledSubPanel.java import org.xdat.gui.UiDefines; import javax.swing.BorderFactory; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import javax.swing.border.TitledBorder; import java.awt.Font; /* * Copyright 2014, Enguerrand de Rochefort * * This file is part of xdat. * * xdat is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * xdat is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with xdat. If not, see <http://www.gnu.org/licenses/>. * */ package org.xdat.gui.panels; public class TitledSubPanel extends JPanel { public TitledSubPanel(String title) { super(); TitledBorder titledBorder = BorderFactory.createTitledBorder(title); titledBorder.setTitleFont(new Font("SansSerif", Font.BOLD, 16));
EmptyBorder emptyBorder = (new EmptyBorder(UiDefines.PADDING, UiDefines.PADDING, UiDefines.PADDING, UiDefines.PADDING));
enguerrand/xdat
src/main/java/org/xdat/gui/panels/SettingControlPanel.java
// Path: src/main/java/org/xdat/settings/SettingsTransaction.java // public class SettingsTransaction { // private final List<Setting<?>> changedSettings = new ArrayList<>(); // private final Set<Runnable> handlers = new LinkedHashSet<>(); // // public SettingsTransaction() { // } // // public void execute(Collection<Function<SettingsTransaction, Boolean>> tasks) { // boolean changed = false; // for (Function<SettingsTransaction, Boolean> applyAction : tasks) { // changed |= applyAction.apply(this); // } // if (changed) { // runHandlers(); // } // } // // public void handleOnce(Runnable handler) { // handlers.add(handler); // } // // void addChanged(Setting<?> setting){ // this.changedSettings.add(setting); // } // // private void runHandlers(){ // if (isChanged()) { // for (Runnable handler : handlers) { // handler.run(); // } // } // } // // private boolean isChanged() { // return !this.changedSettings.isEmpty(); // } // }
import org.xdat.settings.SettingsTransaction; import javax.swing.JPanel; import java.awt.LayoutManager;
package org.xdat.gui.panels; public abstract class SettingControlPanel extends JPanel { public SettingControlPanel(LayoutManager layoutManager, boolean b) { super(layoutManager, b); } public SettingControlPanel(LayoutManager layoutManager) { super(layoutManager); } public SettingControlPanel(boolean b) { super(b); } public SettingControlPanel() { } /** * @return whether this operation changed the value */
// Path: src/main/java/org/xdat/settings/SettingsTransaction.java // public class SettingsTransaction { // private final List<Setting<?>> changedSettings = new ArrayList<>(); // private final Set<Runnable> handlers = new LinkedHashSet<>(); // // public SettingsTransaction() { // } // // public void execute(Collection<Function<SettingsTransaction, Boolean>> tasks) { // boolean changed = false; // for (Function<SettingsTransaction, Boolean> applyAction : tasks) { // changed |= applyAction.apply(this); // } // if (changed) { // runHandlers(); // } // } // // public void handleOnce(Runnable handler) { // handlers.add(handler); // } // // void addChanged(Setting<?> setting){ // this.changedSettings.add(setting); // } // // private void runHandlers(){ // if (isChanged()) { // for (Runnable handler : handlers) { // handler.run(); // } // } // } // // private boolean isChanged() { // return !this.changedSettings.isEmpty(); // } // } // Path: src/main/java/org/xdat/gui/panels/SettingControlPanel.java import org.xdat.settings.SettingsTransaction; import javax.swing.JPanel; import java.awt.LayoutManager; package org.xdat.gui.panels; public abstract class SettingControlPanel extends JPanel { public SettingControlPanel(LayoutManager layoutManager, boolean b) { super(layoutManager, b); } public SettingControlPanel(LayoutManager layoutManager) { super(layoutManager); } public SettingControlPanel(boolean b) { super(b); } public SettingControlPanel() { } /** * @return whether this operation changed the value */
public abstract boolean applyValue(SettingsTransaction transaction);
guiying712/AndroidModulePattern
module_news/src/main/java/com/guiying/module/news/data/NewsDataSource.java
// Path: lib_common/src/main/java/com/guiying/module/common/base/InfoCallback.java // @Keep // public interface InfoCallback<T> { // // void onSuccess(T info); // // void onError(int code, String message); // // } // // Path: module_news/src/main/java/com/guiying/module/news/data/bean/MessageDetail.java // public class MessageDetail { // private String body; // private String image_source; // private String title; // private String image; // private String share_url; // private List<String> recommenders; // private String ga_prefix; // private String type; // private String id; // // public String getBody() { // return body; // } // // public void setBody(String body) { // this.body = body; // } // // public String getImage_source() { // return image_source; // } // // public void setImage_source(String image_source) { // this.image_source = image_source; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getImage() { // return image; // } // // public void setImage(String image) { // this.image = image; // } // // public String getShare_url() { // return share_url; // } // // public void setShare_url(String share_url) { // this.share_url = share_url; // } // // public List<String> getRecommenders() { // return recommenders; // } // // public void setRecommenders(List<String> recommenders) { // this.recommenders = recommenders; // } // // public String getGa_prefix() { // return ga_prefix; // } // // public void setGa_prefix(String ga_prefix) { // this.ga_prefix = ga_prefix; // } // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // @Override // public String toString() { // return "MessageDetail{" + // "body='" + body + '\'' + // ", image_source='" + image_source + '\'' + // ", title='" + title + '\'' + // ", image='" + image + '\'' + // ", share_url='" + share_url + '\'' + // ", recommenders=" + recommenders + // ", ga_prefix='" + ga_prefix + '\'' + // ", type='" + type + '\'' + // ", id='" + id + '\'' + // '}'; // } // } // // Path: module_news/src/main/java/com/guiying/module/news/data/bean/StoryList.java // public class StoryList { // // private String date; // private List<Story> stories; // // public String getDate() { // return date; // } // // public void setDate(String date) { // this.date = date; // } // // public List<Story> getStories() { // return stories; // } // // public void setStories(List<Story> stories) { // this.stories = stories; // } // }
import com.guiying.module.common.base.InfoCallback; import com.guiying.module.news.data.bean.MessageDetail; import com.guiying.module.news.data.bean.StoryList;
package com.guiying.module.news.data; /** * <p>类说明</p> * * @author 张华洋 2017/4/20 22:02 * @version V1.2.0 * @name NewsDataSource */ public interface NewsDataSource { /** * 获取当天的新闻列表 * * @param date 日期 * @param callback 回调 */ void getNewsList(String date, InfoCallback<StoryList> callback); /** * 获取某条新闻详情 * * @param id 新闻Id * @param callback 回调 */
// Path: lib_common/src/main/java/com/guiying/module/common/base/InfoCallback.java // @Keep // public interface InfoCallback<T> { // // void onSuccess(T info); // // void onError(int code, String message); // // } // // Path: module_news/src/main/java/com/guiying/module/news/data/bean/MessageDetail.java // public class MessageDetail { // private String body; // private String image_source; // private String title; // private String image; // private String share_url; // private List<String> recommenders; // private String ga_prefix; // private String type; // private String id; // // public String getBody() { // return body; // } // // public void setBody(String body) { // this.body = body; // } // // public String getImage_source() { // return image_source; // } // // public void setImage_source(String image_source) { // this.image_source = image_source; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getImage() { // return image; // } // // public void setImage(String image) { // this.image = image; // } // // public String getShare_url() { // return share_url; // } // // public void setShare_url(String share_url) { // this.share_url = share_url; // } // // public List<String> getRecommenders() { // return recommenders; // } // // public void setRecommenders(List<String> recommenders) { // this.recommenders = recommenders; // } // // public String getGa_prefix() { // return ga_prefix; // } // // public void setGa_prefix(String ga_prefix) { // this.ga_prefix = ga_prefix; // } // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // @Override // public String toString() { // return "MessageDetail{" + // "body='" + body + '\'' + // ", image_source='" + image_source + '\'' + // ", title='" + title + '\'' + // ", image='" + image + '\'' + // ", share_url='" + share_url + '\'' + // ", recommenders=" + recommenders + // ", ga_prefix='" + ga_prefix + '\'' + // ", type='" + type + '\'' + // ", id='" + id + '\'' + // '}'; // } // } // // Path: module_news/src/main/java/com/guiying/module/news/data/bean/StoryList.java // public class StoryList { // // private String date; // private List<Story> stories; // // public String getDate() { // return date; // } // // public void setDate(String date) { // this.date = date; // } // // public List<Story> getStories() { // return stories; // } // // public void setStories(List<Story> stories) { // this.stories = stories; // } // } // Path: module_news/src/main/java/com/guiying/module/news/data/NewsDataSource.java import com.guiying.module.common.base.InfoCallback; import com.guiying.module.news.data.bean.MessageDetail; import com.guiying.module.news.data.bean.StoryList; package com.guiying.module.news.data; /** * <p>类说明</p> * * @author 张华洋 2017/4/20 22:02 * @version V1.2.0 * @name NewsDataSource */ public interface NewsDataSource { /** * 获取当天的新闻列表 * * @param date 日期 * @param callback 回调 */ void getNewsList(String date, InfoCallback<StoryList> callback); /** * 获取某条新闻详情 * * @param id 新闻Id * @param callback 回调 */
void getNewsDetail(String id, InfoCallback<MessageDetail> callback);
guiying712/AndroidModulePattern
lib_common/src/main/java/com/guiying/module/common/base/BaseActivity.java
// Path: lib_common/src/main/java/com/guiying/module/common/utils/Utils.java // public class Utils { // // private static Context context; // // private Utils() { // throw new UnsupportedOperationException("u can't instantiate me..."); // } // // /** // * 初始化工具类 // * // * @param context 上下文 // */ // public static void init(Context context) { // Utils.context = context.getApplicationContext(); // } // // /** // * 获取ApplicationContext // * // * @return ApplicationContext // */ // public static Context getContext() { // if (context != null) return context; // throw new NullPointerException("u should init first"); // } // // /** // * View获取Activity的工具 // * // * @param view view // * @return Activity // */ // public static // @NonNull // Activity getActivity(View view) { // Context context = view.getContext(); // // while (context instanceof ContextWrapper) { // if (context instanceof Activity) { // return (Activity) context; // } // context = ((ContextWrapper) context).getBaseContext(); // } // // throw new IllegalStateException("View " + view + " is not attached to an Activity"); // } // // /** // * 全局获取String的方法 // * // * @param id 资源Id // * @return String // */ // public static String getString(@StringRes int id) { // return context.getResources().getString(id); // } // // /** // * 判断App是否是Debug版本 // * // * @return {@code true}: 是<br>{@code false}: 否 // */ // public static boolean isAppDebug() { // if (StringUtils.isSpace(context.getPackageName())) return false; // try { // PackageManager pm = context.getPackageManager(); // ApplicationInfo ai = pm.getApplicationInfo(context.getPackageName(), 0); // return ai != null && (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0; // } catch (PackageManager.NameNotFoundException e) { // e.printStackTrace(); // return false; // } // } // // // /** // * The {@code fragment} is added to the container view with id {@code frameId}. The operation is // * performed by the {@code fragmentManager}. // */ // public static void addFragmentToActivity(@NonNull FragmentManager fragmentManager, // @NonNull Fragment fragment, int frameId) { // checkNotNull(fragmentManager); // checkNotNull(fragment); // FragmentTransaction transaction = fragmentManager.beginTransaction(); // transaction.add(frameId, fragment); // transaction.commit(); // } // // // public static <T> T checkNotNull(T obj) { // if (obj == null) { // throw new NullPointerException(); // } // return obj; // } // // }
import android.os.Bundle; import android.support.annotation.IdRes; import android.support.annotation.Keep; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import com.guiying.module.common.R; import com.guiying.module.common.utils.Utils;
/** * Setup the toolbar. * * @param toolbar toolbar * @param hideTitle 是否隐藏Title */ protected void setupToolBar(Toolbar toolbar, boolean hideTitle) { setSupportActionBar(toolbar); ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setHomeAsUpIndicator(R.drawable.ic_arrow_back); actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setDisplayShowHomeEnabled(true); if (hideTitle) { //隐藏Title actionBar.setDisplayShowTitleEnabled(false); } } } /** * 添加fragment * * @param fragment * @param frameId */ protected void addFragment(BaseFragment fragment, @IdRes int frameId) {
// Path: lib_common/src/main/java/com/guiying/module/common/utils/Utils.java // public class Utils { // // private static Context context; // // private Utils() { // throw new UnsupportedOperationException("u can't instantiate me..."); // } // // /** // * 初始化工具类 // * // * @param context 上下文 // */ // public static void init(Context context) { // Utils.context = context.getApplicationContext(); // } // // /** // * 获取ApplicationContext // * // * @return ApplicationContext // */ // public static Context getContext() { // if (context != null) return context; // throw new NullPointerException("u should init first"); // } // // /** // * View获取Activity的工具 // * // * @param view view // * @return Activity // */ // public static // @NonNull // Activity getActivity(View view) { // Context context = view.getContext(); // // while (context instanceof ContextWrapper) { // if (context instanceof Activity) { // return (Activity) context; // } // context = ((ContextWrapper) context).getBaseContext(); // } // // throw new IllegalStateException("View " + view + " is not attached to an Activity"); // } // // /** // * 全局获取String的方法 // * // * @param id 资源Id // * @return String // */ // public static String getString(@StringRes int id) { // return context.getResources().getString(id); // } // // /** // * 判断App是否是Debug版本 // * // * @return {@code true}: 是<br>{@code false}: 否 // */ // public static boolean isAppDebug() { // if (StringUtils.isSpace(context.getPackageName())) return false; // try { // PackageManager pm = context.getPackageManager(); // ApplicationInfo ai = pm.getApplicationInfo(context.getPackageName(), 0); // return ai != null && (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0; // } catch (PackageManager.NameNotFoundException e) { // e.printStackTrace(); // return false; // } // } // // // /** // * The {@code fragment} is added to the container view with id {@code frameId}. The operation is // * performed by the {@code fragmentManager}. // */ // public static void addFragmentToActivity(@NonNull FragmentManager fragmentManager, // @NonNull Fragment fragment, int frameId) { // checkNotNull(fragmentManager); // checkNotNull(fragment); // FragmentTransaction transaction = fragmentManager.beginTransaction(); // transaction.add(frameId, fragment); // transaction.commit(); // } // // // public static <T> T checkNotNull(T obj) { // if (obj == null) { // throw new NullPointerException(); // } // return obj; // } // // } // Path: lib_common/src/main/java/com/guiying/module/common/base/BaseActivity.java import android.os.Bundle; import android.support.annotation.IdRes; import android.support.annotation.Keep; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import com.guiying.module.common.R; import com.guiying.module.common.utils.Utils; /** * Setup the toolbar. * * @param toolbar toolbar * @param hideTitle 是否隐藏Title */ protected void setupToolBar(Toolbar toolbar, boolean hideTitle) { setSupportActionBar(toolbar); ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setHomeAsUpIndicator(R.drawable.ic_arrow_back); actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setDisplayShowHomeEnabled(true); if (hideTitle) { //隐藏Title actionBar.setDisplayShowTitleEnabled(false); } } } /** * 添加fragment * * @param fragment * @param frameId */ protected void addFragment(BaseFragment fragment, @IdRes int frameId) {
Utils.checkNotNull(fragment);
guiying712/AndroidModulePattern
lib_common/src/main/java/com/guiying/module/common/glide/OkHttpStreamFetcher.java
// Path: lib_common/src/main/java/com/guiying/module/common/utils/CloseUtils.java // public class CloseUtils { // // private CloseUtils() { // throw new UnsupportedOperationException("u can't instantiate me..."); // } // // /** // * 关闭IO // * // * @param closeables closeable // */ // public static void closeIO(Closeable... closeables) { // if (closeables == null) return; // for (Closeable closeable : closeables) { // if (closeable != null) { // try { // closeable.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // } // // /** // * 安静关闭IO // * // * @param closeables closeable // */ // public static void closeIOQuietly(Closeable... closeables) { // if (closeables == null) return; // for (Closeable closeable : closeables) { // if (closeable != null) { // try { // closeable.close(); // } catch (IOException ignored) { // } // } // } // } // }
import com.bumptech.glide.Priority; import com.bumptech.glide.load.data.DataFetcher; import com.bumptech.glide.load.model.GlideUrl; import com.bumptech.glide.util.ContentLengthInputStream; import com.guiying.module.common.utils.CloseUtils; import java.io.IOException; import java.io.InputStream; import java.util.Map; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import okhttp3.ResponseBody;
.url(url.toStringUrl()); for (Map.Entry<String, String> headerEntry : url.getHeaders().entrySet()) { String key = headerEntry.getKey(); requestBuilder.addHeader(key, headerEntry.getValue()); } Request request = requestBuilder.build(); Response response = client.newCall(request).execute(); responseBody = response.body(); if (!response.isSuccessful()) { throw new IOException("Request failed with code: " + response.code()); } long contentLength = responseBody.contentLength(); stream = ContentLengthInputStream.obtain(responseBody.byteStream(), contentLength); return stream; } @Override public void cleanup() { if (stream != null) { try { stream.close(); } catch (IOException e) { // Ignored } } if (responseBody != null) {
// Path: lib_common/src/main/java/com/guiying/module/common/utils/CloseUtils.java // public class CloseUtils { // // private CloseUtils() { // throw new UnsupportedOperationException("u can't instantiate me..."); // } // // /** // * 关闭IO // * // * @param closeables closeable // */ // public static void closeIO(Closeable... closeables) { // if (closeables == null) return; // for (Closeable closeable : closeables) { // if (closeable != null) { // try { // closeable.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // } // // /** // * 安静关闭IO // * // * @param closeables closeable // */ // public static void closeIOQuietly(Closeable... closeables) { // if (closeables == null) return; // for (Closeable closeable : closeables) { // if (closeable != null) { // try { // closeable.close(); // } catch (IOException ignored) { // } // } // } // } // } // Path: lib_common/src/main/java/com/guiying/module/common/glide/OkHttpStreamFetcher.java import com.bumptech.glide.Priority; import com.bumptech.glide.load.data.DataFetcher; import com.bumptech.glide.load.model.GlideUrl; import com.bumptech.glide.util.ContentLengthInputStream; import com.guiying.module.common.utils.CloseUtils; import java.io.IOException; import java.io.InputStream; import java.util.Map; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import okhttp3.ResponseBody; .url(url.toStringUrl()); for (Map.Entry<String, String> headerEntry : url.getHeaders().entrySet()) { String key = headerEntry.getKey(); requestBuilder.addHeader(key, headerEntry.getValue()); } Request request = requestBuilder.build(); Response response = client.newCall(request).execute(); responseBody = response.body(); if (!response.isSuccessful()) { throw new IOException("Request failed with code: " + response.code()); } long contentLength = responseBody.contentLength(); stream = ContentLengthInputStream.obtain(responseBody.byteStream(), contentLength); return stream; } @Override public void cleanup() { if (stream != null) { try { stream.close(); } catch (IOException e) { // Ignored } } if (responseBody != null) {
CloseUtils.closeIO(responseBody);
guiying712/AndroidModulePattern
lib_common/src/main/java/com/guiying/module/common/base/ClassUtils.java
// Path: lib_common/src/main/java/com/guiying/module/common/utils/Utils.java // public class Utils { // // private static Context context; // // private Utils() { // throw new UnsupportedOperationException("u can't instantiate me..."); // } // // /** // * 初始化工具类 // * // * @param context 上下文 // */ // public static void init(Context context) { // Utils.context = context.getApplicationContext(); // } // // /** // * 获取ApplicationContext // * // * @return ApplicationContext // */ // public static Context getContext() { // if (context != null) return context; // throw new NullPointerException("u should init first"); // } // // /** // * View获取Activity的工具 // * // * @param view view // * @return Activity // */ // public static // @NonNull // Activity getActivity(View view) { // Context context = view.getContext(); // // while (context instanceof ContextWrapper) { // if (context instanceof Activity) { // return (Activity) context; // } // context = ((ContextWrapper) context).getBaseContext(); // } // // throw new IllegalStateException("View " + view + " is not attached to an Activity"); // } // // /** // * 全局获取String的方法 // * // * @param id 资源Id // * @return String // */ // public static String getString(@StringRes int id) { // return context.getResources().getString(id); // } // // /** // * 判断App是否是Debug版本 // * // * @return {@code true}: 是<br>{@code false}: 否 // */ // public static boolean isAppDebug() { // if (StringUtils.isSpace(context.getPackageName())) return false; // try { // PackageManager pm = context.getPackageManager(); // ApplicationInfo ai = pm.getApplicationInfo(context.getPackageName(), 0); // return ai != null && (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0; // } catch (PackageManager.NameNotFoundException e) { // e.printStackTrace(); // return false; // } // } // // // /** // * The {@code fragment} is added to the container view with id {@code frameId}. The operation is // * performed by the {@code fragmentManager}. // */ // public static void addFragmentToActivity(@NonNull FragmentManager fragmentManager, // @NonNull Fragment fragment, int frameId) { // checkNotNull(fragmentManager); // checkNotNull(fragment); // FragmentTransaction transaction = fragmentManager.beginTransaction(); // transaction.add(frameId, fragment); // transaction.commit(); // } // // // public static <T> T checkNotNull(T obj) { // if (obj == null) { // throw new NullPointerException(); // } // return obj; // } // // }
import android.content.Context; import android.content.SharedPreferences; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.os.Build; import android.support.annotation.Keep; import android.util.Log; import com.guiying.module.common.utils.Utils; import java.io.File; import java.io.IOException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.Enumeration; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import dalvik.system.DexFile;
public static List<String> getSourcePaths(Context context) throws PackageManager.NameNotFoundException, IOException { ApplicationInfo applicationInfo = context.getPackageManager().getApplicationInfo(context.getPackageName(), 0); File sourceApk = new File(applicationInfo.sourceDir); List<String> sourcePaths = new ArrayList<>(); sourcePaths.add(applicationInfo.sourceDir); //add the default apk path //the prefix of extracted file, ie: test.classes String extractedFilePrefix = sourceApk.getName() + EXTRACTED_NAME_EXT; //如果VM已经支持了MultiDex,就不要去Secondary Folder加载 Classesx.zip了,那里已经么有了 //通过是否存在sp中的multidex.version是不准确的,因为从低版本升级上来的用户,是包含这个sp配置的 if (!isVMMultidexCapable()) { //the total dex numbers int totalDexNumber = getMultiDexPreferences(context).getInt(KEY_DEX_NUMBER, 1); File dexDir = new File(applicationInfo.dataDir, SECONDARY_FOLDER_NAME); for (int secondaryNumber = 2; secondaryNumber <= totalDexNumber; secondaryNumber++) { //for each dex file, ie: test.classes2.zip, test.classes3.zip... String fileName = extractedFilePrefix + secondaryNumber + EXTRACTED_SUFFIX; File extractedFile = new File(dexDir, fileName); if (extractedFile.isFile()) { sourcePaths.add(extractedFile.getAbsolutePath()); //we ignore the verify zip part } else { throw new IOException("Missing extracted secondary dex file '" + extractedFile.getPath() + "'"); } } }
// Path: lib_common/src/main/java/com/guiying/module/common/utils/Utils.java // public class Utils { // // private static Context context; // // private Utils() { // throw new UnsupportedOperationException("u can't instantiate me..."); // } // // /** // * 初始化工具类 // * // * @param context 上下文 // */ // public static void init(Context context) { // Utils.context = context.getApplicationContext(); // } // // /** // * 获取ApplicationContext // * // * @return ApplicationContext // */ // public static Context getContext() { // if (context != null) return context; // throw new NullPointerException("u should init first"); // } // // /** // * View获取Activity的工具 // * // * @param view view // * @return Activity // */ // public static // @NonNull // Activity getActivity(View view) { // Context context = view.getContext(); // // while (context instanceof ContextWrapper) { // if (context instanceof Activity) { // return (Activity) context; // } // context = ((ContextWrapper) context).getBaseContext(); // } // // throw new IllegalStateException("View " + view + " is not attached to an Activity"); // } // // /** // * 全局获取String的方法 // * // * @param id 资源Id // * @return String // */ // public static String getString(@StringRes int id) { // return context.getResources().getString(id); // } // // /** // * 判断App是否是Debug版本 // * // * @return {@code true}: 是<br>{@code false}: 否 // */ // public static boolean isAppDebug() { // if (StringUtils.isSpace(context.getPackageName())) return false; // try { // PackageManager pm = context.getPackageManager(); // ApplicationInfo ai = pm.getApplicationInfo(context.getPackageName(), 0); // return ai != null && (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0; // } catch (PackageManager.NameNotFoundException e) { // e.printStackTrace(); // return false; // } // } // // // /** // * The {@code fragment} is added to the container view with id {@code frameId}. The operation is // * performed by the {@code fragmentManager}. // */ // public static void addFragmentToActivity(@NonNull FragmentManager fragmentManager, // @NonNull Fragment fragment, int frameId) { // checkNotNull(fragmentManager); // checkNotNull(fragment); // FragmentTransaction transaction = fragmentManager.beginTransaction(); // transaction.add(frameId, fragment); // transaction.commit(); // } // // // public static <T> T checkNotNull(T obj) { // if (obj == null) { // throw new NullPointerException(); // } // return obj; // } // // } // Path: lib_common/src/main/java/com/guiying/module/common/base/ClassUtils.java import android.content.Context; import android.content.SharedPreferences; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.os.Build; import android.support.annotation.Keep; import android.util.Log; import com.guiying.module.common.utils.Utils; import java.io.File; import java.io.IOException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.Enumeration; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import dalvik.system.DexFile; public static List<String> getSourcePaths(Context context) throws PackageManager.NameNotFoundException, IOException { ApplicationInfo applicationInfo = context.getPackageManager().getApplicationInfo(context.getPackageName(), 0); File sourceApk = new File(applicationInfo.sourceDir); List<String> sourcePaths = new ArrayList<>(); sourcePaths.add(applicationInfo.sourceDir); //add the default apk path //the prefix of extracted file, ie: test.classes String extractedFilePrefix = sourceApk.getName() + EXTRACTED_NAME_EXT; //如果VM已经支持了MultiDex,就不要去Secondary Folder加载 Classesx.zip了,那里已经么有了 //通过是否存在sp中的multidex.version是不准确的,因为从低版本升级上来的用户,是包含这个sp配置的 if (!isVMMultidexCapable()) { //the total dex numbers int totalDexNumber = getMultiDexPreferences(context).getInt(KEY_DEX_NUMBER, 1); File dexDir = new File(applicationInfo.dataDir, SECONDARY_FOLDER_NAME); for (int secondaryNumber = 2; secondaryNumber <= totalDexNumber; secondaryNumber++) { //for each dex file, ie: test.classes2.zip, test.classes3.zip... String fileName = extractedFilePrefix + secondaryNumber + EXTRACTED_SUFFIX; File extractedFile = new File(dexDir, fileName); if (extractedFile.isFile()) { sourcePaths.add(extractedFile.getAbsolutePath()); //we ignore the verify zip part } else { throw new IOException("Missing extracted secondary dex file '" + extractedFile.getPath() + "'"); } } }
if (Utils.isAppDebug()) {
guiying712/AndroidModulePattern
module_news/src/main/java/com/guiying/module/news/main/NewsListPresenter.java
// Path: lib_common/src/main/java/com/guiying/module/common/base/InfoCallback.java // @Keep // public interface InfoCallback<T> { // // void onSuccess(T info); // // void onError(int code, String message); // // } // // Path: module_news/src/main/java/com/guiying/module/news/data/NewsDataSource.java // public interface NewsDataSource { // // // /** // * 获取当天的新闻列表 // * // * @param date 日期 // * @param callback 回调 // */ // void getNewsList(String date, InfoCallback<StoryList> callback); // // /** // * 获取某条新闻详情 // * // * @param id 新闻Id // * @param callback 回调 // */ // void getNewsDetail(String id, InfoCallback<MessageDetail> callback); // // } // // Path: module_news/src/main/java/com/guiying/module/news/data/bean/StoryList.java // public class StoryList { // // private String date; // private List<Story> stories; // // public String getDate() { // return date; // } // // public void setDate(String date) { // this.date = date; // } // // public List<Story> getStories() { // return stories; // } // // public void setStories(List<Story> stories) { // this.stories = stories; // } // } // // Path: module_news/src/main/java/com/guiying/module/news/data/source/RemoteNewsDataSource.java // public class RemoteNewsDataSource implements NewsDataSource { // // @Override // public void getNewsList(String date, final InfoCallback<StoryList> callback) { // HttpClient client = new HttpClient.Builder() // .baseUrl(Constants.ZHIHU_DAILY_BEFORE_MESSAGE) // .url(date) // .bodyType(DataType.JSON_OBJECT, StoryList.class) // .build(); // client.get(new OnResultListener<StoryList>() { // // @Override // public void onSuccess(StoryList result) { // callback.onSuccess(result); // } // // @Override // public void onError(int code, String message) { // callback.onError(code, message); // } // // @Override // public void onFailure(String message) { // callback.onError(0, message); // } // }); // } // // // @Override // public void getNewsDetail(String id, final InfoCallback<MessageDetail> callback) { // HttpClient client = new HttpClient.Builder() // .baseUrl(Constants.ZHIHU_DAILY_BEFORE_MESSAGE_DETAIL) // .url(id) // .bodyType(DataType.JSON_OBJECT, MessageDetail.class) // .build(); // client.get(new OnResultListener<MessageDetail>() { // // @Override // public void onSuccess(MessageDetail result) { // callback.onSuccess(result); // } // // @Override // public void onError(int code, String message) { // callback.onError(code, message); // } // // @Override // public void onFailure(String message) { // callback.onError(0, message); // } // }); // } // // // }
import com.guiying.module.common.base.InfoCallback; import com.guiying.module.news.data.NewsDataSource; import com.guiying.module.news.data.bean.StoryList; import com.guiying.module.news.data.source.RemoteNewsDataSource;
package com.guiying.module.news.main; /** * <p>类说明</p> * * @author 张华洋 2017/2/22 20:33 * @version V1.2.0 * @name GirlsPresenter */ public class NewsListPresenter implements NewsListContract.Presenter { private NewsListContract.View mView;
// Path: lib_common/src/main/java/com/guiying/module/common/base/InfoCallback.java // @Keep // public interface InfoCallback<T> { // // void onSuccess(T info); // // void onError(int code, String message); // // } // // Path: module_news/src/main/java/com/guiying/module/news/data/NewsDataSource.java // public interface NewsDataSource { // // // /** // * 获取当天的新闻列表 // * // * @param date 日期 // * @param callback 回调 // */ // void getNewsList(String date, InfoCallback<StoryList> callback); // // /** // * 获取某条新闻详情 // * // * @param id 新闻Id // * @param callback 回调 // */ // void getNewsDetail(String id, InfoCallback<MessageDetail> callback); // // } // // Path: module_news/src/main/java/com/guiying/module/news/data/bean/StoryList.java // public class StoryList { // // private String date; // private List<Story> stories; // // public String getDate() { // return date; // } // // public void setDate(String date) { // this.date = date; // } // // public List<Story> getStories() { // return stories; // } // // public void setStories(List<Story> stories) { // this.stories = stories; // } // } // // Path: module_news/src/main/java/com/guiying/module/news/data/source/RemoteNewsDataSource.java // public class RemoteNewsDataSource implements NewsDataSource { // // @Override // public void getNewsList(String date, final InfoCallback<StoryList> callback) { // HttpClient client = new HttpClient.Builder() // .baseUrl(Constants.ZHIHU_DAILY_BEFORE_MESSAGE) // .url(date) // .bodyType(DataType.JSON_OBJECT, StoryList.class) // .build(); // client.get(new OnResultListener<StoryList>() { // // @Override // public void onSuccess(StoryList result) { // callback.onSuccess(result); // } // // @Override // public void onError(int code, String message) { // callback.onError(code, message); // } // // @Override // public void onFailure(String message) { // callback.onError(0, message); // } // }); // } // // // @Override // public void getNewsDetail(String id, final InfoCallback<MessageDetail> callback) { // HttpClient client = new HttpClient.Builder() // .baseUrl(Constants.ZHIHU_DAILY_BEFORE_MESSAGE_DETAIL) // .url(id) // .bodyType(DataType.JSON_OBJECT, MessageDetail.class) // .build(); // client.get(new OnResultListener<MessageDetail>() { // // @Override // public void onSuccess(MessageDetail result) { // callback.onSuccess(result); // } // // @Override // public void onError(int code, String message) { // callback.onError(code, message); // } // // @Override // public void onFailure(String message) { // callback.onError(0, message); // } // }); // } // // // } // Path: module_news/src/main/java/com/guiying/module/news/main/NewsListPresenter.java import com.guiying.module.common.base.InfoCallback; import com.guiying.module.news.data.NewsDataSource; import com.guiying.module.news.data.bean.StoryList; import com.guiying.module.news.data.source.RemoteNewsDataSource; package com.guiying.module.news.main; /** * <p>类说明</p> * * @author 张华洋 2017/2/22 20:33 * @version V1.2.0 * @name GirlsPresenter */ public class NewsListPresenter implements NewsListContract.Presenter { private NewsListContract.View mView;
private NewsDataSource mDataSource;
guiying712/AndroidModulePattern
module_news/src/main/java/com/guiying/module/news/main/NewsListPresenter.java
// Path: lib_common/src/main/java/com/guiying/module/common/base/InfoCallback.java // @Keep // public interface InfoCallback<T> { // // void onSuccess(T info); // // void onError(int code, String message); // // } // // Path: module_news/src/main/java/com/guiying/module/news/data/NewsDataSource.java // public interface NewsDataSource { // // // /** // * 获取当天的新闻列表 // * // * @param date 日期 // * @param callback 回调 // */ // void getNewsList(String date, InfoCallback<StoryList> callback); // // /** // * 获取某条新闻详情 // * // * @param id 新闻Id // * @param callback 回调 // */ // void getNewsDetail(String id, InfoCallback<MessageDetail> callback); // // } // // Path: module_news/src/main/java/com/guiying/module/news/data/bean/StoryList.java // public class StoryList { // // private String date; // private List<Story> stories; // // public String getDate() { // return date; // } // // public void setDate(String date) { // this.date = date; // } // // public List<Story> getStories() { // return stories; // } // // public void setStories(List<Story> stories) { // this.stories = stories; // } // } // // Path: module_news/src/main/java/com/guiying/module/news/data/source/RemoteNewsDataSource.java // public class RemoteNewsDataSource implements NewsDataSource { // // @Override // public void getNewsList(String date, final InfoCallback<StoryList> callback) { // HttpClient client = new HttpClient.Builder() // .baseUrl(Constants.ZHIHU_DAILY_BEFORE_MESSAGE) // .url(date) // .bodyType(DataType.JSON_OBJECT, StoryList.class) // .build(); // client.get(new OnResultListener<StoryList>() { // // @Override // public void onSuccess(StoryList result) { // callback.onSuccess(result); // } // // @Override // public void onError(int code, String message) { // callback.onError(code, message); // } // // @Override // public void onFailure(String message) { // callback.onError(0, message); // } // }); // } // // // @Override // public void getNewsDetail(String id, final InfoCallback<MessageDetail> callback) { // HttpClient client = new HttpClient.Builder() // .baseUrl(Constants.ZHIHU_DAILY_BEFORE_MESSAGE_DETAIL) // .url(id) // .bodyType(DataType.JSON_OBJECT, MessageDetail.class) // .build(); // client.get(new OnResultListener<MessageDetail>() { // // @Override // public void onSuccess(MessageDetail result) { // callback.onSuccess(result); // } // // @Override // public void onError(int code, String message) { // callback.onError(code, message); // } // // @Override // public void onFailure(String message) { // callback.onError(0, message); // } // }); // } // // // }
import com.guiying.module.common.base.InfoCallback; import com.guiying.module.news.data.NewsDataSource; import com.guiying.module.news.data.bean.StoryList; import com.guiying.module.news.data.source.RemoteNewsDataSource;
package com.guiying.module.news.main; /** * <p>类说明</p> * * @author 张华洋 2017/2/22 20:33 * @version V1.2.0 * @name GirlsPresenter */ public class NewsListPresenter implements NewsListContract.Presenter { private NewsListContract.View mView; private NewsDataSource mDataSource; public NewsListPresenter(NewsListContract.View view) { mView = view;
// Path: lib_common/src/main/java/com/guiying/module/common/base/InfoCallback.java // @Keep // public interface InfoCallback<T> { // // void onSuccess(T info); // // void onError(int code, String message); // // } // // Path: module_news/src/main/java/com/guiying/module/news/data/NewsDataSource.java // public interface NewsDataSource { // // // /** // * 获取当天的新闻列表 // * // * @param date 日期 // * @param callback 回调 // */ // void getNewsList(String date, InfoCallback<StoryList> callback); // // /** // * 获取某条新闻详情 // * // * @param id 新闻Id // * @param callback 回调 // */ // void getNewsDetail(String id, InfoCallback<MessageDetail> callback); // // } // // Path: module_news/src/main/java/com/guiying/module/news/data/bean/StoryList.java // public class StoryList { // // private String date; // private List<Story> stories; // // public String getDate() { // return date; // } // // public void setDate(String date) { // this.date = date; // } // // public List<Story> getStories() { // return stories; // } // // public void setStories(List<Story> stories) { // this.stories = stories; // } // } // // Path: module_news/src/main/java/com/guiying/module/news/data/source/RemoteNewsDataSource.java // public class RemoteNewsDataSource implements NewsDataSource { // // @Override // public void getNewsList(String date, final InfoCallback<StoryList> callback) { // HttpClient client = new HttpClient.Builder() // .baseUrl(Constants.ZHIHU_DAILY_BEFORE_MESSAGE) // .url(date) // .bodyType(DataType.JSON_OBJECT, StoryList.class) // .build(); // client.get(new OnResultListener<StoryList>() { // // @Override // public void onSuccess(StoryList result) { // callback.onSuccess(result); // } // // @Override // public void onError(int code, String message) { // callback.onError(code, message); // } // // @Override // public void onFailure(String message) { // callback.onError(0, message); // } // }); // } // // // @Override // public void getNewsDetail(String id, final InfoCallback<MessageDetail> callback) { // HttpClient client = new HttpClient.Builder() // .baseUrl(Constants.ZHIHU_DAILY_BEFORE_MESSAGE_DETAIL) // .url(id) // .bodyType(DataType.JSON_OBJECT, MessageDetail.class) // .build(); // client.get(new OnResultListener<MessageDetail>() { // // @Override // public void onSuccess(MessageDetail result) { // callback.onSuccess(result); // } // // @Override // public void onError(int code, String message) { // callback.onError(code, message); // } // // @Override // public void onFailure(String message) { // callback.onError(0, message); // } // }); // } // // // } // Path: module_news/src/main/java/com/guiying/module/news/main/NewsListPresenter.java import com.guiying.module.common.base.InfoCallback; import com.guiying.module.news.data.NewsDataSource; import com.guiying.module.news.data.bean.StoryList; import com.guiying.module.news.data.source.RemoteNewsDataSource; package com.guiying.module.news.main; /** * <p>类说明</p> * * @author 张华洋 2017/2/22 20:33 * @version V1.2.0 * @name GirlsPresenter */ public class NewsListPresenter implements NewsListContract.Presenter { private NewsListContract.View mView; private NewsDataSource mDataSource; public NewsListPresenter(NewsListContract.View view) { mView = view;
mDataSource = new RemoteNewsDataSource();
guiying712/AndroidModulePattern
module_news/src/main/java/com/guiying/module/news/main/NewsListPresenter.java
// Path: lib_common/src/main/java/com/guiying/module/common/base/InfoCallback.java // @Keep // public interface InfoCallback<T> { // // void onSuccess(T info); // // void onError(int code, String message); // // } // // Path: module_news/src/main/java/com/guiying/module/news/data/NewsDataSource.java // public interface NewsDataSource { // // // /** // * 获取当天的新闻列表 // * // * @param date 日期 // * @param callback 回调 // */ // void getNewsList(String date, InfoCallback<StoryList> callback); // // /** // * 获取某条新闻详情 // * // * @param id 新闻Id // * @param callback 回调 // */ // void getNewsDetail(String id, InfoCallback<MessageDetail> callback); // // } // // Path: module_news/src/main/java/com/guiying/module/news/data/bean/StoryList.java // public class StoryList { // // private String date; // private List<Story> stories; // // public String getDate() { // return date; // } // // public void setDate(String date) { // this.date = date; // } // // public List<Story> getStories() { // return stories; // } // // public void setStories(List<Story> stories) { // this.stories = stories; // } // } // // Path: module_news/src/main/java/com/guiying/module/news/data/source/RemoteNewsDataSource.java // public class RemoteNewsDataSource implements NewsDataSource { // // @Override // public void getNewsList(String date, final InfoCallback<StoryList> callback) { // HttpClient client = new HttpClient.Builder() // .baseUrl(Constants.ZHIHU_DAILY_BEFORE_MESSAGE) // .url(date) // .bodyType(DataType.JSON_OBJECT, StoryList.class) // .build(); // client.get(new OnResultListener<StoryList>() { // // @Override // public void onSuccess(StoryList result) { // callback.onSuccess(result); // } // // @Override // public void onError(int code, String message) { // callback.onError(code, message); // } // // @Override // public void onFailure(String message) { // callback.onError(0, message); // } // }); // } // // // @Override // public void getNewsDetail(String id, final InfoCallback<MessageDetail> callback) { // HttpClient client = new HttpClient.Builder() // .baseUrl(Constants.ZHIHU_DAILY_BEFORE_MESSAGE_DETAIL) // .url(id) // .bodyType(DataType.JSON_OBJECT, MessageDetail.class) // .build(); // client.get(new OnResultListener<MessageDetail>() { // // @Override // public void onSuccess(MessageDetail result) { // callback.onSuccess(result); // } // // @Override // public void onError(int code, String message) { // callback.onError(code, message); // } // // @Override // public void onFailure(String message) { // callback.onError(0, message); // } // }); // } // // // }
import com.guiying.module.common.base.InfoCallback; import com.guiying.module.news.data.NewsDataSource; import com.guiying.module.news.data.bean.StoryList; import com.guiying.module.news.data.source.RemoteNewsDataSource;
package com.guiying.module.news.main; /** * <p>类说明</p> * * @author 张华洋 2017/2/22 20:33 * @version V1.2.0 * @name GirlsPresenter */ public class NewsListPresenter implements NewsListContract.Presenter { private NewsListContract.View mView; private NewsDataSource mDataSource; public NewsListPresenter(NewsListContract.View view) { mView = view; mDataSource = new RemoteNewsDataSource(); mView.setPresenter(this); } @Override public void start() { } @Override public void getNewMessages(int page, int size, String date) {
// Path: lib_common/src/main/java/com/guiying/module/common/base/InfoCallback.java // @Keep // public interface InfoCallback<T> { // // void onSuccess(T info); // // void onError(int code, String message); // // } // // Path: module_news/src/main/java/com/guiying/module/news/data/NewsDataSource.java // public interface NewsDataSource { // // // /** // * 获取当天的新闻列表 // * // * @param date 日期 // * @param callback 回调 // */ // void getNewsList(String date, InfoCallback<StoryList> callback); // // /** // * 获取某条新闻详情 // * // * @param id 新闻Id // * @param callback 回调 // */ // void getNewsDetail(String id, InfoCallback<MessageDetail> callback); // // } // // Path: module_news/src/main/java/com/guiying/module/news/data/bean/StoryList.java // public class StoryList { // // private String date; // private List<Story> stories; // // public String getDate() { // return date; // } // // public void setDate(String date) { // this.date = date; // } // // public List<Story> getStories() { // return stories; // } // // public void setStories(List<Story> stories) { // this.stories = stories; // } // } // // Path: module_news/src/main/java/com/guiying/module/news/data/source/RemoteNewsDataSource.java // public class RemoteNewsDataSource implements NewsDataSource { // // @Override // public void getNewsList(String date, final InfoCallback<StoryList> callback) { // HttpClient client = new HttpClient.Builder() // .baseUrl(Constants.ZHIHU_DAILY_BEFORE_MESSAGE) // .url(date) // .bodyType(DataType.JSON_OBJECT, StoryList.class) // .build(); // client.get(new OnResultListener<StoryList>() { // // @Override // public void onSuccess(StoryList result) { // callback.onSuccess(result); // } // // @Override // public void onError(int code, String message) { // callback.onError(code, message); // } // // @Override // public void onFailure(String message) { // callback.onError(0, message); // } // }); // } // // // @Override // public void getNewsDetail(String id, final InfoCallback<MessageDetail> callback) { // HttpClient client = new HttpClient.Builder() // .baseUrl(Constants.ZHIHU_DAILY_BEFORE_MESSAGE_DETAIL) // .url(id) // .bodyType(DataType.JSON_OBJECT, MessageDetail.class) // .build(); // client.get(new OnResultListener<MessageDetail>() { // // @Override // public void onSuccess(MessageDetail result) { // callback.onSuccess(result); // } // // @Override // public void onError(int code, String message) { // callback.onError(code, message); // } // // @Override // public void onFailure(String message) { // callback.onError(0, message); // } // }); // } // // // } // Path: module_news/src/main/java/com/guiying/module/news/main/NewsListPresenter.java import com.guiying.module.common.base.InfoCallback; import com.guiying.module.news.data.NewsDataSource; import com.guiying.module.news.data.bean.StoryList; import com.guiying.module.news.data.source.RemoteNewsDataSource; package com.guiying.module.news.main; /** * <p>类说明</p> * * @author 张华洋 2017/2/22 20:33 * @version V1.2.0 * @name GirlsPresenter */ public class NewsListPresenter implements NewsListContract.Presenter { private NewsListContract.View mView; private NewsDataSource mDataSource; public NewsListPresenter(NewsListContract.View view) { mView = view; mDataSource = new RemoteNewsDataSource(); mView.setPresenter(this); } @Override public void start() { } @Override public void getNewMessages(int page, int size, String date) {
mDataSource.getNewsList(date, new InfoCallback<StoryList>() {
guiying712/AndroidModulePattern
module_news/src/main/java/com/guiying/module/news/main/NewsListPresenter.java
// Path: lib_common/src/main/java/com/guiying/module/common/base/InfoCallback.java // @Keep // public interface InfoCallback<T> { // // void onSuccess(T info); // // void onError(int code, String message); // // } // // Path: module_news/src/main/java/com/guiying/module/news/data/NewsDataSource.java // public interface NewsDataSource { // // // /** // * 获取当天的新闻列表 // * // * @param date 日期 // * @param callback 回调 // */ // void getNewsList(String date, InfoCallback<StoryList> callback); // // /** // * 获取某条新闻详情 // * // * @param id 新闻Id // * @param callback 回调 // */ // void getNewsDetail(String id, InfoCallback<MessageDetail> callback); // // } // // Path: module_news/src/main/java/com/guiying/module/news/data/bean/StoryList.java // public class StoryList { // // private String date; // private List<Story> stories; // // public String getDate() { // return date; // } // // public void setDate(String date) { // this.date = date; // } // // public List<Story> getStories() { // return stories; // } // // public void setStories(List<Story> stories) { // this.stories = stories; // } // } // // Path: module_news/src/main/java/com/guiying/module/news/data/source/RemoteNewsDataSource.java // public class RemoteNewsDataSource implements NewsDataSource { // // @Override // public void getNewsList(String date, final InfoCallback<StoryList> callback) { // HttpClient client = new HttpClient.Builder() // .baseUrl(Constants.ZHIHU_DAILY_BEFORE_MESSAGE) // .url(date) // .bodyType(DataType.JSON_OBJECT, StoryList.class) // .build(); // client.get(new OnResultListener<StoryList>() { // // @Override // public void onSuccess(StoryList result) { // callback.onSuccess(result); // } // // @Override // public void onError(int code, String message) { // callback.onError(code, message); // } // // @Override // public void onFailure(String message) { // callback.onError(0, message); // } // }); // } // // // @Override // public void getNewsDetail(String id, final InfoCallback<MessageDetail> callback) { // HttpClient client = new HttpClient.Builder() // .baseUrl(Constants.ZHIHU_DAILY_BEFORE_MESSAGE_DETAIL) // .url(id) // .bodyType(DataType.JSON_OBJECT, MessageDetail.class) // .build(); // client.get(new OnResultListener<MessageDetail>() { // // @Override // public void onSuccess(MessageDetail result) { // callback.onSuccess(result); // } // // @Override // public void onError(int code, String message) { // callback.onError(code, message); // } // // @Override // public void onFailure(String message) { // callback.onError(0, message); // } // }); // } // // // }
import com.guiying.module.common.base.InfoCallback; import com.guiying.module.news.data.NewsDataSource; import com.guiying.module.news.data.bean.StoryList; import com.guiying.module.news.data.source.RemoteNewsDataSource;
package com.guiying.module.news.main; /** * <p>类说明</p> * * @author 张华洋 2017/2/22 20:33 * @version V1.2.0 * @name GirlsPresenter */ public class NewsListPresenter implements NewsListContract.Presenter { private NewsListContract.View mView; private NewsDataSource mDataSource; public NewsListPresenter(NewsListContract.View view) { mView = view; mDataSource = new RemoteNewsDataSource(); mView.setPresenter(this); } @Override public void start() { } @Override public void getNewMessages(int page, int size, String date) {
// Path: lib_common/src/main/java/com/guiying/module/common/base/InfoCallback.java // @Keep // public interface InfoCallback<T> { // // void onSuccess(T info); // // void onError(int code, String message); // // } // // Path: module_news/src/main/java/com/guiying/module/news/data/NewsDataSource.java // public interface NewsDataSource { // // // /** // * 获取当天的新闻列表 // * // * @param date 日期 // * @param callback 回调 // */ // void getNewsList(String date, InfoCallback<StoryList> callback); // // /** // * 获取某条新闻详情 // * // * @param id 新闻Id // * @param callback 回调 // */ // void getNewsDetail(String id, InfoCallback<MessageDetail> callback); // // } // // Path: module_news/src/main/java/com/guiying/module/news/data/bean/StoryList.java // public class StoryList { // // private String date; // private List<Story> stories; // // public String getDate() { // return date; // } // // public void setDate(String date) { // this.date = date; // } // // public List<Story> getStories() { // return stories; // } // // public void setStories(List<Story> stories) { // this.stories = stories; // } // } // // Path: module_news/src/main/java/com/guiying/module/news/data/source/RemoteNewsDataSource.java // public class RemoteNewsDataSource implements NewsDataSource { // // @Override // public void getNewsList(String date, final InfoCallback<StoryList> callback) { // HttpClient client = new HttpClient.Builder() // .baseUrl(Constants.ZHIHU_DAILY_BEFORE_MESSAGE) // .url(date) // .bodyType(DataType.JSON_OBJECT, StoryList.class) // .build(); // client.get(new OnResultListener<StoryList>() { // // @Override // public void onSuccess(StoryList result) { // callback.onSuccess(result); // } // // @Override // public void onError(int code, String message) { // callback.onError(code, message); // } // // @Override // public void onFailure(String message) { // callback.onError(0, message); // } // }); // } // // // @Override // public void getNewsDetail(String id, final InfoCallback<MessageDetail> callback) { // HttpClient client = new HttpClient.Builder() // .baseUrl(Constants.ZHIHU_DAILY_BEFORE_MESSAGE_DETAIL) // .url(id) // .bodyType(DataType.JSON_OBJECT, MessageDetail.class) // .build(); // client.get(new OnResultListener<MessageDetail>() { // // @Override // public void onSuccess(MessageDetail result) { // callback.onSuccess(result); // } // // @Override // public void onError(int code, String message) { // callback.onError(code, message); // } // // @Override // public void onFailure(String message) { // callback.onError(0, message); // } // }); // } // // // } // Path: module_news/src/main/java/com/guiying/module/news/main/NewsListPresenter.java import com.guiying.module.common.base.InfoCallback; import com.guiying.module.news.data.NewsDataSource; import com.guiying.module.news.data.bean.StoryList; import com.guiying.module.news.data.source.RemoteNewsDataSource; package com.guiying.module.news.main; /** * <p>类说明</p> * * @author 张华洋 2017/2/22 20:33 * @version V1.2.0 * @name GirlsPresenter */ public class NewsListPresenter implements NewsListContract.Presenter { private NewsListContract.View mView; private NewsDataSource mDataSource; public NewsListPresenter(NewsListContract.View view) { mView = view; mDataSource = new RemoteNewsDataSource(); mView.setPresenter(this); } @Override public void start() { } @Override public void getNewMessages(int page, int size, String date) {
mDataSource.getNewsList(date, new InfoCallback<StoryList>() {
guiying712/AndroidModulePattern
module_girls/src/main/java/com/guiying/module/girls/data/GirlsDataSource.java
// Path: module_girls/src/main/java/com/guiying/module/girls/data/bean/GirlsParser.java // public class GirlsParser { // // /** // * error : false // * results : [{"_id":"5771d5eb421aa931ddcc50d6","createdAt":"2016-06-28T09:42:03.761Z","desc":"Dagger2图文完全教程","publishedAt":"2016-06-28T11:33:25.276Z","source":"web","type":"Android","url":"https://github.com/luxiaoming/dagger2Demo","used":true,"who":"代码GG陆晓明"},{"_id":"5771c9ca421aa931ca5a7e59","createdAt":"2016-06-28T08:50:18.731Z","desc":"Android Design 设计模板","publishedAt":"2016-06-28T11:33:25.276Z","source":"chrome","type":"Android","url":"https://github.com/andreasschrade/android-design-template","used":true,"who":"代码家"}] // */ // // private boolean error; // /** // * _id : 5771d5eb421aa931ddcc50d6 // * createdAt : 2016-06-28T09:42:03.761Z // * desc : Dagger2图文完全教程 // * publishedAt : 2016-06-28T11:33:25.276Z // * source : web // * type : Android // * url : https://github.com/luxiaoming/dagger2Demo // * used : true // * who : 代码GG陆晓明 // */ // // private List<Girls> results; // // public void setError(boolean error) { // this.error = error; // } // // public void setResults(List<Girls> results) { // this.results = results; // } // // public boolean isError() { // return error; // } // // public List<Girls> getResults() { // return results; // } // // // }
import com.guiying.module.girls.data.bean.GirlsParser;
package com.guiying.module.girls.data; public interface GirlsDataSource { interface LoadGirlsCallback {
// Path: module_girls/src/main/java/com/guiying/module/girls/data/bean/GirlsParser.java // public class GirlsParser { // // /** // * error : false // * results : [{"_id":"5771d5eb421aa931ddcc50d6","createdAt":"2016-06-28T09:42:03.761Z","desc":"Dagger2图文完全教程","publishedAt":"2016-06-28T11:33:25.276Z","source":"web","type":"Android","url":"https://github.com/luxiaoming/dagger2Demo","used":true,"who":"代码GG陆晓明"},{"_id":"5771c9ca421aa931ca5a7e59","createdAt":"2016-06-28T08:50:18.731Z","desc":"Android Design 设计模板","publishedAt":"2016-06-28T11:33:25.276Z","source":"chrome","type":"Android","url":"https://github.com/andreasschrade/android-design-template","used":true,"who":"代码家"}] // */ // // private boolean error; // /** // * _id : 5771d5eb421aa931ddcc50d6 // * createdAt : 2016-06-28T09:42:03.761Z // * desc : Dagger2图文完全教程 // * publishedAt : 2016-06-28T11:33:25.276Z // * source : web // * type : Android // * url : https://github.com/luxiaoming/dagger2Demo // * used : true // * who : 代码GG陆晓明 // */ // // private List<Girls> results; // // public void setError(boolean error) { // this.error = error; // } // // public void setResults(List<Girls> results) { // this.results = results; // } // // public boolean isError() { // return error; // } // // public List<Girls> getResults() { // return results; // } // // // } // Path: module_girls/src/main/java/com/guiying/module/girls/data/GirlsDataSource.java import com.guiying.module.girls.data.bean.GirlsParser; package com.guiying.module.girls.data; public interface GirlsDataSource { interface LoadGirlsCallback {
void onGirlsLoaded(GirlsParser girlsParser);
guiying712/AndroidModulePattern
module_news/src/main/java/com/guiying/module/news/detail/NewsDetailView.java
// Path: module_news/src/main/java/com/guiying/module/news/data/bean/MessageDetail.java // public class MessageDetail { // private String body; // private String image_source; // private String title; // private String image; // private String share_url; // private List<String> recommenders; // private String ga_prefix; // private String type; // private String id; // // public String getBody() { // return body; // } // // public void setBody(String body) { // this.body = body; // } // // public String getImage_source() { // return image_source; // } // // public void setImage_source(String image_source) { // this.image_source = image_source; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getImage() { // return image; // } // // public void setImage(String image) { // this.image = image; // } // // public String getShare_url() { // return share_url; // } // // public void setShare_url(String share_url) { // this.share_url = share_url; // } // // public List<String> getRecommenders() { // return recommenders; // } // // public void setRecommenders(List<String> recommenders) { // this.recommenders = recommenders; // } // // public String getGa_prefix() { // return ga_prefix; // } // // public void setGa_prefix(String ga_prefix) { // this.ga_prefix = ga_prefix; // } // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // @Override // public String toString() { // return "MessageDetail{" + // "body='" + body + '\'' + // ", image_source='" + image_source + '\'' + // ", title='" + title + '\'' + // ", image='" + image + '\'' + // ", share_url='" + share_url + '\'' + // ", recommenders=" + recommenders + // ", ga_prefix='" + ga_prefix + '\'' + // ", type='" + type + '\'' + // ", id='" + id + '\'' + // '}'; // } // }
import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.support.design.widget.CollapsingToolbarLayout; import android.text.Html; import android.text.method.LinkMovementMethod; import android.util.AttributeSet; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.bumptech.glide.request.animation.GlideAnimation; import com.bumptech.glide.request.target.SimpleTarget; import com.guiying.module.news.R; import com.guiying.module.news.data.bean.MessageDetail;
mCollapsingLayout = (CollapsingToolbarLayout) findViewById(R.id.collapsing_layout); mDetailText = (TextView) findViewById(R.id.news_detail_text); isActive = true; } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); isActive = true; } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); isActive = false; } @Override public boolean isActive() { return isActive; } @Override public void setPresenter(NewsDetailContract.Presenter presenter) { mPresenter = presenter; } @Override
// Path: module_news/src/main/java/com/guiying/module/news/data/bean/MessageDetail.java // public class MessageDetail { // private String body; // private String image_source; // private String title; // private String image; // private String share_url; // private List<String> recommenders; // private String ga_prefix; // private String type; // private String id; // // public String getBody() { // return body; // } // // public void setBody(String body) { // this.body = body; // } // // public String getImage_source() { // return image_source; // } // // public void setImage_source(String image_source) { // this.image_source = image_source; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getImage() { // return image; // } // // public void setImage(String image) { // this.image = image; // } // // public String getShare_url() { // return share_url; // } // // public void setShare_url(String share_url) { // this.share_url = share_url; // } // // public List<String> getRecommenders() { // return recommenders; // } // // public void setRecommenders(List<String> recommenders) { // this.recommenders = recommenders; // } // // public String getGa_prefix() { // return ga_prefix; // } // // public void setGa_prefix(String ga_prefix) { // this.ga_prefix = ga_prefix; // } // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // @Override // public String toString() { // return "MessageDetail{" + // "body='" + body + '\'' + // ", image_source='" + image_source + '\'' + // ", title='" + title + '\'' + // ", image='" + image + '\'' + // ", share_url='" + share_url + '\'' + // ", recommenders=" + recommenders + // ", ga_prefix='" + ga_prefix + '\'' + // ", type='" + type + '\'' + // ", id='" + id + '\'' + // '}'; // } // } // Path: module_news/src/main/java/com/guiying/module/news/detail/NewsDetailView.java import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.support.design.widget.CollapsingToolbarLayout; import android.text.Html; import android.text.method.LinkMovementMethod; import android.util.AttributeSet; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.bumptech.glide.request.animation.GlideAnimation; import com.bumptech.glide.request.target.SimpleTarget; import com.guiying.module.news.R; import com.guiying.module.news.data.bean.MessageDetail; mCollapsingLayout = (CollapsingToolbarLayout) findViewById(R.id.collapsing_layout); mDetailText = (TextView) findViewById(R.id.news_detail_text); isActive = true; } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); isActive = true; } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); isActive = false; } @Override public boolean isActive() { return isActive; } @Override public void setPresenter(NewsDetailContract.Presenter presenter) { mPresenter = presenter; } @Override
public void showNewsDetail(MessageDetail detail) {
guiying712/AndroidModulePattern
module_news/src/main/java/com/guiying/module/news/main/NewsListView.java
// Path: module_news/src/main/java/com/guiying/module/news/data/bean/StoryList.java // public class StoryList { // // private String date; // private List<Story> stories; // // public String getDate() { // return date; // } // // public void setDate(String date) { // this.date = date; // } // // public List<Story> getStories() { // return stories; // } // // public void setStories(List<Story> stories) { // this.stories = stories; // } // }
import android.content.Context; import android.support.v4.content.ContextCompat; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.LinearLayoutManager; import android.util.AttributeSet; import com.guiying.module.news.R; import com.guiying.module.news.data.bean.StoryList; import com.jude.easyrecyclerview.EasyRecyclerView; import com.jude.easyrecyclerview.adapter.RecyclerArrayAdapter; import com.jude.easyrecyclerview.decoration.DividerDecoration;
@Override public void onRefresh() { mPresenter.getNewMessages(1, 20, mDate); } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); isActive = true; mPresenter.getNewMessages(1, 20, mDate); } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); isActive = false; } @Override public void setPresenter(NewsListContract.Presenter presenter) { mPresenter = presenter; } @Override public boolean isActive() { return isActive; } @Override
// Path: module_news/src/main/java/com/guiying/module/news/data/bean/StoryList.java // public class StoryList { // // private String date; // private List<Story> stories; // // public String getDate() { // return date; // } // // public void setDate(String date) { // this.date = date; // } // // public List<Story> getStories() { // return stories; // } // // public void setStories(List<Story> stories) { // this.stories = stories; // } // } // Path: module_news/src/main/java/com/guiying/module/news/main/NewsListView.java import android.content.Context; import android.support.v4.content.ContextCompat; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.LinearLayoutManager; import android.util.AttributeSet; import com.guiying.module.news.R; import com.guiying.module.news.data.bean.StoryList; import com.jude.easyrecyclerview.EasyRecyclerView; import com.jude.easyrecyclerview.adapter.RecyclerArrayAdapter; import com.jude.easyrecyclerview.decoration.DividerDecoration; @Override public void onRefresh() { mPresenter.getNewMessages(1, 20, mDate); } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); isActive = true; mPresenter.getNewMessages(1, 20, mDate); } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); isActive = false; } @Override public void setPresenter(NewsListContract.Presenter presenter) { mPresenter = presenter; } @Override public boolean isActive() { return isActive; } @Override
public void showNewsList(StoryList info) {
guiying712/AndroidModulePattern
module_news/src/main/java/com/guiying/module/news/detail/NewsDetailPresenter.java
// Path: lib_common/src/main/java/com/guiying/module/common/base/InfoCallback.java // @Keep // public interface InfoCallback<T> { // // void onSuccess(T info); // // void onError(int code, String message); // // } // // Path: module_news/src/main/java/com/guiying/module/news/data/NewsDataSource.java // public interface NewsDataSource { // // // /** // * 获取当天的新闻列表 // * // * @param date 日期 // * @param callback 回调 // */ // void getNewsList(String date, InfoCallback<StoryList> callback); // // /** // * 获取某条新闻详情 // * // * @param id 新闻Id // * @param callback 回调 // */ // void getNewsDetail(String id, InfoCallback<MessageDetail> callback); // // } // // Path: module_news/src/main/java/com/guiying/module/news/data/bean/MessageDetail.java // public class MessageDetail { // private String body; // private String image_source; // private String title; // private String image; // private String share_url; // private List<String> recommenders; // private String ga_prefix; // private String type; // private String id; // // public String getBody() { // return body; // } // // public void setBody(String body) { // this.body = body; // } // // public String getImage_source() { // return image_source; // } // // public void setImage_source(String image_source) { // this.image_source = image_source; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getImage() { // return image; // } // // public void setImage(String image) { // this.image = image; // } // // public String getShare_url() { // return share_url; // } // // public void setShare_url(String share_url) { // this.share_url = share_url; // } // // public List<String> getRecommenders() { // return recommenders; // } // // public void setRecommenders(List<String> recommenders) { // this.recommenders = recommenders; // } // // public String getGa_prefix() { // return ga_prefix; // } // // public void setGa_prefix(String ga_prefix) { // this.ga_prefix = ga_prefix; // } // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // @Override // public String toString() { // return "MessageDetail{" + // "body='" + body + '\'' + // ", image_source='" + image_source + '\'' + // ", title='" + title + '\'' + // ", image='" + image + '\'' + // ", share_url='" + share_url + '\'' + // ", recommenders=" + recommenders + // ", ga_prefix='" + ga_prefix + '\'' + // ", type='" + type + '\'' + // ", id='" + id + '\'' + // '}'; // } // } // // Path: module_news/src/main/java/com/guiying/module/news/data/source/RemoteNewsDataSource.java // public class RemoteNewsDataSource implements NewsDataSource { // // @Override // public void getNewsList(String date, final InfoCallback<StoryList> callback) { // HttpClient client = new HttpClient.Builder() // .baseUrl(Constants.ZHIHU_DAILY_BEFORE_MESSAGE) // .url(date) // .bodyType(DataType.JSON_OBJECT, StoryList.class) // .build(); // client.get(new OnResultListener<StoryList>() { // // @Override // public void onSuccess(StoryList result) { // callback.onSuccess(result); // } // // @Override // public void onError(int code, String message) { // callback.onError(code, message); // } // // @Override // public void onFailure(String message) { // callback.onError(0, message); // } // }); // } // // // @Override // public void getNewsDetail(String id, final InfoCallback<MessageDetail> callback) { // HttpClient client = new HttpClient.Builder() // .baseUrl(Constants.ZHIHU_DAILY_BEFORE_MESSAGE_DETAIL) // .url(id) // .bodyType(DataType.JSON_OBJECT, MessageDetail.class) // .build(); // client.get(new OnResultListener<MessageDetail>() { // // @Override // public void onSuccess(MessageDetail result) { // callback.onSuccess(result); // } // // @Override // public void onError(int code, String message) { // callback.onError(code, message); // } // // @Override // public void onFailure(String message) { // callback.onError(0, message); // } // }); // } // // // }
import com.guiying.module.common.base.InfoCallback; import com.guiying.module.news.data.NewsDataSource; import com.guiying.module.news.data.bean.MessageDetail; import com.guiying.module.news.data.source.RemoteNewsDataSource;
package com.guiying.module.news.detail; /** * <p>类说明</p> * * @author 张华洋 2017/2/22 20:33 * @version V1.2.0 * @name GirlsPresenter */ public class NewsDetailPresenter implements NewsDetailContract.Presenter { private NewsDetailContract.View mView;
// Path: lib_common/src/main/java/com/guiying/module/common/base/InfoCallback.java // @Keep // public interface InfoCallback<T> { // // void onSuccess(T info); // // void onError(int code, String message); // // } // // Path: module_news/src/main/java/com/guiying/module/news/data/NewsDataSource.java // public interface NewsDataSource { // // // /** // * 获取当天的新闻列表 // * // * @param date 日期 // * @param callback 回调 // */ // void getNewsList(String date, InfoCallback<StoryList> callback); // // /** // * 获取某条新闻详情 // * // * @param id 新闻Id // * @param callback 回调 // */ // void getNewsDetail(String id, InfoCallback<MessageDetail> callback); // // } // // Path: module_news/src/main/java/com/guiying/module/news/data/bean/MessageDetail.java // public class MessageDetail { // private String body; // private String image_source; // private String title; // private String image; // private String share_url; // private List<String> recommenders; // private String ga_prefix; // private String type; // private String id; // // public String getBody() { // return body; // } // // public void setBody(String body) { // this.body = body; // } // // public String getImage_source() { // return image_source; // } // // public void setImage_source(String image_source) { // this.image_source = image_source; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getImage() { // return image; // } // // public void setImage(String image) { // this.image = image; // } // // public String getShare_url() { // return share_url; // } // // public void setShare_url(String share_url) { // this.share_url = share_url; // } // // public List<String> getRecommenders() { // return recommenders; // } // // public void setRecommenders(List<String> recommenders) { // this.recommenders = recommenders; // } // // public String getGa_prefix() { // return ga_prefix; // } // // public void setGa_prefix(String ga_prefix) { // this.ga_prefix = ga_prefix; // } // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // @Override // public String toString() { // return "MessageDetail{" + // "body='" + body + '\'' + // ", image_source='" + image_source + '\'' + // ", title='" + title + '\'' + // ", image='" + image + '\'' + // ", share_url='" + share_url + '\'' + // ", recommenders=" + recommenders + // ", ga_prefix='" + ga_prefix + '\'' + // ", type='" + type + '\'' + // ", id='" + id + '\'' + // '}'; // } // } // // Path: module_news/src/main/java/com/guiying/module/news/data/source/RemoteNewsDataSource.java // public class RemoteNewsDataSource implements NewsDataSource { // // @Override // public void getNewsList(String date, final InfoCallback<StoryList> callback) { // HttpClient client = new HttpClient.Builder() // .baseUrl(Constants.ZHIHU_DAILY_BEFORE_MESSAGE) // .url(date) // .bodyType(DataType.JSON_OBJECT, StoryList.class) // .build(); // client.get(new OnResultListener<StoryList>() { // // @Override // public void onSuccess(StoryList result) { // callback.onSuccess(result); // } // // @Override // public void onError(int code, String message) { // callback.onError(code, message); // } // // @Override // public void onFailure(String message) { // callback.onError(0, message); // } // }); // } // // // @Override // public void getNewsDetail(String id, final InfoCallback<MessageDetail> callback) { // HttpClient client = new HttpClient.Builder() // .baseUrl(Constants.ZHIHU_DAILY_BEFORE_MESSAGE_DETAIL) // .url(id) // .bodyType(DataType.JSON_OBJECT, MessageDetail.class) // .build(); // client.get(new OnResultListener<MessageDetail>() { // // @Override // public void onSuccess(MessageDetail result) { // callback.onSuccess(result); // } // // @Override // public void onError(int code, String message) { // callback.onError(code, message); // } // // @Override // public void onFailure(String message) { // callback.onError(0, message); // } // }); // } // // // } // Path: module_news/src/main/java/com/guiying/module/news/detail/NewsDetailPresenter.java import com.guiying.module.common.base.InfoCallback; import com.guiying.module.news.data.NewsDataSource; import com.guiying.module.news.data.bean.MessageDetail; import com.guiying.module.news.data.source.RemoteNewsDataSource; package com.guiying.module.news.detail; /** * <p>类说明</p> * * @author 张华洋 2017/2/22 20:33 * @version V1.2.0 * @name GirlsPresenter */ public class NewsDetailPresenter implements NewsDetailContract.Presenter { private NewsDetailContract.View mView;
private NewsDataSource mDataSource;
guiying712/AndroidModulePattern
module_news/src/main/java/com/guiying/module/news/detail/NewsDetailPresenter.java
// Path: lib_common/src/main/java/com/guiying/module/common/base/InfoCallback.java // @Keep // public interface InfoCallback<T> { // // void onSuccess(T info); // // void onError(int code, String message); // // } // // Path: module_news/src/main/java/com/guiying/module/news/data/NewsDataSource.java // public interface NewsDataSource { // // // /** // * 获取当天的新闻列表 // * // * @param date 日期 // * @param callback 回调 // */ // void getNewsList(String date, InfoCallback<StoryList> callback); // // /** // * 获取某条新闻详情 // * // * @param id 新闻Id // * @param callback 回调 // */ // void getNewsDetail(String id, InfoCallback<MessageDetail> callback); // // } // // Path: module_news/src/main/java/com/guiying/module/news/data/bean/MessageDetail.java // public class MessageDetail { // private String body; // private String image_source; // private String title; // private String image; // private String share_url; // private List<String> recommenders; // private String ga_prefix; // private String type; // private String id; // // public String getBody() { // return body; // } // // public void setBody(String body) { // this.body = body; // } // // public String getImage_source() { // return image_source; // } // // public void setImage_source(String image_source) { // this.image_source = image_source; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getImage() { // return image; // } // // public void setImage(String image) { // this.image = image; // } // // public String getShare_url() { // return share_url; // } // // public void setShare_url(String share_url) { // this.share_url = share_url; // } // // public List<String> getRecommenders() { // return recommenders; // } // // public void setRecommenders(List<String> recommenders) { // this.recommenders = recommenders; // } // // public String getGa_prefix() { // return ga_prefix; // } // // public void setGa_prefix(String ga_prefix) { // this.ga_prefix = ga_prefix; // } // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // @Override // public String toString() { // return "MessageDetail{" + // "body='" + body + '\'' + // ", image_source='" + image_source + '\'' + // ", title='" + title + '\'' + // ", image='" + image + '\'' + // ", share_url='" + share_url + '\'' + // ", recommenders=" + recommenders + // ", ga_prefix='" + ga_prefix + '\'' + // ", type='" + type + '\'' + // ", id='" + id + '\'' + // '}'; // } // } // // Path: module_news/src/main/java/com/guiying/module/news/data/source/RemoteNewsDataSource.java // public class RemoteNewsDataSource implements NewsDataSource { // // @Override // public void getNewsList(String date, final InfoCallback<StoryList> callback) { // HttpClient client = new HttpClient.Builder() // .baseUrl(Constants.ZHIHU_DAILY_BEFORE_MESSAGE) // .url(date) // .bodyType(DataType.JSON_OBJECT, StoryList.class) // .build(); // client.get(new OnResultListener<StoryList>() { // // @Override // public void onSuccess(StoryList result) { // callback.onSuccess(result); // } // // @Override // public void onError(int code, String message) { // callback.onError(code, message); // } // // @Override // public void onFailure(String message) { // callback.onError(0, message); // } // }); // } // // // @Override // public void getNewsDetail(String id, final InfoCallback<MessageDetail> callback) { // HttpClient client = new HttpClient.Builder() // .baseUrl(Constants.ZHIHU_DAILY_BEFORE_MESSAGE_DETAIL) // .url(id) // .bodyType(DataType.JSON_OBJECT, MessageDetail.class) // .build(); // client.get(new OnResultListener<MessageDetail>() { // // @Override // public void onSuccess(MessageDetail result) { // callback.onSuccess(result); // } // // @Override // public void onError(int code, String message) { // callback.onError(code, message); // } // // @Override // public void onFailure(String message) { // callback.onError(0, message); // } // }); // } // // // }
import com.guiying.module.common.base.InfoCallback; import com.guiying.module.news.data.NewsDataSource; import com.guiying.module.news.data.bean.MessageDetail; import com.guiying.module.news.data.source.RemoteNewsDataSource;
package com.guiying.module.news.detail; /** * <p>类说明</p> * * @author 张华洋 2017/2/22 20:33 * @version V1.2.0 * @name GirlsPresenter */ public class NewsDetailPresenter implements NewsDetailContract.Presenter { private NewsDetailContract.View mView; private NewsDataSource mDataSource; public NewsDetailPresenter(NewsDetailContract.View view) { mView = view;
// Path: lib_common/src/main/java/com/guiying/module/common/base/InfoCallback.java // @Keep // public interface InfoCallback<T> { // // void onSuccess(T info); // // void onError(int code, String message); // // } // // Path: module_news/src/main/java/com/guiying/module/news/data/NewsDataSource.java // public interface NewsDataSource { // // // /** // * 获取当天的新闻列表 // * // * @param date 日期 // * @param callback 回调 // */ // void getNewsList(String date, InfoCallback<StoryList> callback); // // /** // * 获取某条新闻详情 // * // * @param id 新闻Id // * @param callback 回调 // */ // void getNewsDetail(String id, InfoCallback<MessageDetail> callback); // // } // // Path: module_news/src/main/java/com/guiying/module/news/data/bean/MessageDetail.java // public class MessageDetail { // private String body; // private String image_source; // private String title; // private String image; // private String share_url; // private List<String> recommenders; // private String ga_prefix; // private String type; // private String id; // // public String getBody() { // return body; // } // // public void setBody(String body) { // this.body = body; // } // // public String getImage_source() { // return image_source; // } // // public void setImage_source(String image_source) { // this.image_source = image_source; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getImage() { // return image; // } // // public void setImage(String image) { // this.image = image; // } // // public String getShare_url() { // return share_url; // } // // public void setShare_url(String share_url) { // this.share_url = share_url; // } // // public List<String> getRecommenders() { // return recommenders; // } // // public void setRecommenders(List<String> recommenders) { // this.recommenders = recommenders; // } // // public String getGa_prefix() { // return ga_prefix; // } // // public void setGa_prefix(String ga_prefix) { // this.ga_prefix = ga_prefix; // } // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // @Override // public String toString() { // return "MessageDetail{" + // "body='" + body + '\'' + // ", image_source='" + image_source + '\'' + // ", title='" + title + '\'' + // ", image='" + image + '\'' + // ", share_url='" + share_url + '\'' + // ", recommenders=" + recommenders + // ", ga_prefix='" + ga_prefix + '\'' + // ", type='" + type + '\'' + // ", id='" + id + '\'' + // '}'; // } // } // // Path: module_news/src/main/java/com/guiying/module/news/data/source/RemoteNewsDataSource.java // public class RemoteNewsDataSource implements NewsDataSource { // // @Override // public void getNewsList(String date, final InfoCallback<StoryList> callback) { // HttpClient client = new HttpClient.Builder() // .baseUrl(Constants.ZHIHU_DAILY_BEFORE_MESSAGE) // .url(date) // .bodyType(DataType.JSON_OBJECT, StoryList.class) // .build(); // client.get(new OnResultListener<StoryList>() { // // @Override // public void onSuccess(StoryList result) { // callback.onSuccess(result); // } // // @Override // public void onError(int code, String message) { // callback.onError(code, message); // } // // @Override // public void onFailure(String message) { // callback.onError(0, message); // } // }); // } // // // @Override // public void getNewsDetail(String id, final InfoCallback<MessageDetail> callback) { // HttpClient client = new HttpClient.Builder() // .baseUrl(Constants.ZHIHU_DAILY_BEFORE_MESSAGE_DETAIL) // .url(id) // .bodyType(DataType.JSON_OBJECT, MessageDetail.class) // .build(); // client.get(new OnResultListener<MessageDetail>() { // // @Override // public void onSuccess(MessageDetail result) { // callback.onSuccess(result); // } // // @Override // public void onError(int code, String message) { // callback.onError(code, message); // } // // @Override // public void onFailure(String message) { // callback.onError(0, message); // } // }); // } // // // } // Path: module_news/src/main/java/com/guiying/module/news/detail/NewsDetailPresenter.java import com.guiying.module.common.base.InfoCallback; import com.guiying.module.news.data.NewsDataSource; import com.guiying.module.news.data.bean.MessageDetail; import com.guiying.module.news.data.source.RemoteNewsDataSource; package com.guiying.module.news.detail; /** * <p>类说明</p> * * @author 张华洋 2017/2/22 20:33 * @version V1.2.0 * @name GirlsPresenter */ public class NewsDetailPresenter implements NewsDetailContract.Presenter { private NewsDetailContract.View mView; private NewsDataSource mDataSource; public NewsDetailPresenter(NewsDetailContract.View view) { mView = view;
mDataSource = new RemoteNewsDataSource();
guiying712/AndroidModulePattern
module_girls/src/main/java/com/guiying/module/girls/main/GirlsContract.java
// Path: lib_common/src/main/java/com/guiying/module/common/base/BasePresenter.java // @Keep // public interface BasePresenter { // // void start(); // // } // // Path: lib_common/src/main/java/com/guiying/module/common/base/BaseView.java // @Keep // public interface BaseView<T> { // // void setPresenter(T presenter); // // } // // Path: module_girls/src/main/java/com/guiying/module/girls/data/bean/Girls.java // public class Girls implements Parcelable { // // private String _id; // private String createdAt; // private String desc; // private String publishedAt; // private String source; // private String type; // private String url; // private boolean used; // private String who; // // public void set_id(String _id) { // this._id = _id; // } // // public void setCreatedAt(String createdAt) { // this.createdAt = createdAt; // } // // public void setDesc(String desc) { // this.desc = desc; // } // // public void setPublishedAt(String publishedAt) { // this.publishedAt = publishedAt; // } // // public void setSource(String source) { // this.source = source; // } // // public void setType(String type) { // this.type = type; // } // // public void setUrl(String url) { // this.url = url; // } // // public void setUsed(boolean used) { // this.used = used; // } // // public void setWho(String who) { // this.who = who; // } // // public String get_id() { // return _id; // } // // public String getCreatedAt() { // return createdAt; // } // // public String getDesc() { // return desc; // } // // public String getPublishedAt() { // return publishedAt; // } // // public String getSource() { // return source; // } // // public String getType() { // return type; // } // // public String getUrl() { // return url; // } // // public boolean isUsed() { // return used; // } // // public String getWho() { // return who; // } // // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(this._id); // dest.writeString(this.createdAt); // dest.writeString(this.desc); // dest.writeString(this.publishedAt); // dest.writeString(this.source); // dest.writeString(this.type); // dest.writeString(this.url); // dest.writeByte(this.used ? (byte) 1 : (byte) 0); // dest.writeString(this.who); // } // // public Girls() { // } // // protected Girls(Parcel in) { // this._id = in.readString(); // this.createdAt = in.readString(); // this.desc = in.readString(); // this.publishedAt = in.readString(); // this.source = in.readString(); // this.type = in.readString(); // this.url = in.readString(); // this.used = in.readByte() != 0; // this.who = in.readString(); // } // // public static final Creator<Girls> CREATOR = new Creator<Girls>() { // @Override // public Girls createFromParcel(Parcel source) { // return new Girls(source); // } // // @Override // public Girls[] newArray(int size) { // return new Girls[size]; // } // }; // }
import com.guiying.module.common.base.BasePresenter; import com.guiying.module.common.base.BaseView; import com.guiying.module.girls.data.bean.Girls; import java.util.List;
package com.guiying.module.girls.main; /** * <p>类说明</p> * * @author 张华洋 2017/2/22 20:33 * @version V1.2.0 * @name GirlsContract */ public interface GirlsContract { interface View extends BaseView<Presenter> { /** * View 的存活状态 * * @return true or false */ boolean isActive();
// Path: lib_common/src/main/java/com/guiying/module/common/base/BasePresenter.java // @Keep // public interface BasePresenter { // // void start(); // // } // // Path: lib_common/src/main/java/com/guiying/module/common/base/BaseView.java // @Keep // public interface BaseView<T> { // // void setPresenter(T presenter); // // } // // Path: module_girls/src/main/java/com/guiying/module/girls/data/bean/Girls.java // public class Girls implements Parcelable { // // private String _id; // private String createdAt; // private String desc; // private String publishedAt; // private String source; // private String type; // private String url; // private boolean used; // private String who; // // public void set_id(String _id) { // this._id = _id; // } // // public void setCreatedAt(String createdAt) { // this.createdAt = createdAt; // } // // public void setDesc(String desc) { // this.desc = desc; // } // // public void setPublishedAt(String publishedAt) { // this.publishedAt = publishedAt; // } // // public void setSource(String source) { // this.source = source; // } // // public void setType(String type) { // this.type = type; // } // // public void setUrl(String url) { // this.url = url; // } // // public void setUsed(boolean used) { // this.used = used; // } // // public void setWho(String who) { // this.who = who; // } // // public String get_id() { // return _id; // } // // public String getCreatedAt() { // return createdAt; // } // // public String getDesc() { // return desc; // } // // public String getPublishedAt() { // return publishedAt; // } // // public String getSource() { // return source; // } // // public String getType() { // return type; // } // // public String getUrl() { // return url; // } // // public boolean isUsed() { // return used; // } // // public String getWho() { // return who; // } // // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(this._id); // dest.writeString(this.createdAt); // dest.writeString(this.desc); // dest.writeString(this.publishedAt); // dest.writeString(this.source); // dest.writeString(this.type); // dest.writeString(this.url); // dest.writeByte(this.used ? (byte) 1 : (byte) 0); // dest.writeString(this.who); // } // // public Girls() { // } // // protected Girls(Parcel in) { // this._id = in.readString(); // this.createdAt = in.readString(); // this.desc = in.readString(); // this.publishedAt = in.readString(); // this.source = in.readString(); // this.type = in.readString(); // this.url = in.readString(); // this.used = in.readByte() != 0; // this.who = in.readString(); // } // // public static final Creator<Girls> CREATOR = new Creator<Girls>() { // @Override // public Girls createFromParcel(Parcel source) { // return new Girls(source); // } // // @Override // public Girls[] newArray(int size) { // return new Girls[size]; // } // }; // } // Path: module_girls/src/main/java/com/guiying/module/girls/main/GirlsContract.java import com.guiying.module.common.base.BasePresenter; import com.guiying.module.common.base.BaseView; import com.guiying.module.girls.data.bean.Girls; import java.util.List; package com.guiying.module.girls.main; /** * <p>类说明</p> * * @author 张华洋 2017/2/22 20:33 * @version V1.2.0 * @name GirlsContract */ public interface GirlsContract { interface View extends BaseView<Presenter> { /** * View 的存活状态 * * @return true or false */ boolean isActive();
void refresh(List<Girls> data);
guiying712/AndroidModulePattern
module_girls/src/main/java/com/guiying/module/girls/main/GirlsContract.java
// Path: lib_common/src/main/java/com/guiying/module/common/base/BasePresenter.java // @Keep // public interface BasePresenter { // // void start(); // // } // // Path: lib_common/src/main/java/com/guiying/module/common/base/BaseView.java // @Keep // public interface BaseView<T> { // // void setPresenter(T presenter); // // } // // Path: module_girls/src/main/java/com/guiying/module/girls/data/bean/Girls.java // public class Girls implements Parcelable { // // private String _id; // private String createdAt; // private String desc; // private String publishedAt; // private String source; // private String type; // private String url; // private boolean used; // private String who; // // public void set_id(String _id) { // this._id = _id; // } // // public void setCreatedAt(String createdAt) { // this.createdAt = createdAt; // } // // public void setDesc(String desc) { // this.desc = desc; // } // // public void setPublishedAt(String publishedAt) { // this.publishedAt = publishedAt; // } // // public void setSource(String source) { // this.source = source; // } // // public void setType(String type) { // this.type = type; // } // // public void setUrl(String url) { // this.url = url; // } // // public void setUsed(boolean used) { // this.used = used; // } // // public void setWho(String who) { // this.who = who; // } // // public String get_id() { // return _id; // } // // public String getCreatedAt() { // return createdAt; // } // // public String getDesc() { // return desc; // } // // public String getPublishedAt() { // return publishedAt; // } // // public String getSource() { // return source; // } // // public String getType() { // return type; // } // // public String getUrl() { // return url; // } // // public boolean isUsed() { // return used; // } // // public String getWho() { // return who; // } // // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(this._id); // dest.writeString(this.createdAt); // dest.writeString(this.desc); // dest.writeString(this.publishedAt); // dest.writeString(this.source); // dest.writeString(this.type); // dest.writeString(this.url); // dest.writeByte(this.used ? (byte) 1 : (byte) 0); // dest.writeString(this.who); // } // // public Girls() { // } // // protected Girls(Parcel in) { // this._id = in.readString(); // this.createdAt = in.readString(); // this.desc = in.readString(); // this.publishedAt = in.readString(); // this.source = in.readString(); // this.type = in.readString(); // this.url = in.readString(); // this.used = in.readByte() != 0; // this.who = in.readString(); // } // // public static final Creator<Girls> CREATOR = new Creator<Girls>() { // @Override // public Girls createFromParcel(Parcel source) { // return new Girls(source); // } // // @Override // public Girls[] newArray(int size) { // return new Girls[size]; // } // }; // }
import com.guiying.module.common.base.BasePresenter; import com.guiying.module.common.base.BaseView; import com.guiying.module.girls.data.bean.Girls; import java.util.List;
package com.guiying.module.girls.main; /** * <p>类说明</p> * * @author 张华洋 2017/2/22 20:33 * @version V1.2.0 * @name GirlsContract */ public interface GirlsContract { interface View extends BaseView<Presenter> { /** * View 的存活状态 * * @return true or false */ boolean isActive(); void refresh(List<Girls> data); void load(List<Girls> data); void showError(); void showNormal(); }
// Path: lib_common/src/main/java/com/guiying/module/common/base/BasePresenter.java // @Keep // public interface BasePresenter { // // void start(); // // } // // Path: lib_common/src/main/java/com/guiying/module/common/base/BaseView.java // @Keep // public interface BaseView<T> { // // void setPresenter(T presenter); // // } // // Path: module_girls/src/main/java/com/guiying/module/girls/data/bean/Girls.java // public class Girls implements Parcelable { // // private String _id; // private String createdAt; // private String desc; // private String publishedAt; // private String source; // private String type; // private String url; // private boolean used; // private String who; // // public void set_id(String _id) { // this._id = _id; // } // // public void setCreatedAt(String createdAt) { // this.createdAt = createdAt; // } // // public void setDesc(String desc) { // this.desc = desc; // } // // public void setPublishedAt(String publishedAt) { // this.publishedAt = publishedAt; // } // // public void setSource(String source) { // this.source = source; // } // // public void setType(String type) { // this.type = type; // } // // public void setUrl(String url) { // this.url = url; // } // // public void setUsed(boolean used) { // this.used = used; // } // // public void setWho(String who) { // this.who = who; // } // // public String get_id() { // return _id; // } // // public String getCreatedAt() { // return createdAt; // } // // public String getDesc() { // return desc; // } // // public String getPublishedAt() { // return publishedAt; // } // // public String getSource() { // return source; // } // // public String getType() { // return type; // } // // public String getUrl() { // return url; // } // // public boolean isUsed() { // return used; // } // // public String getWho() { // return who; // } // // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(this._id); // dest.writeString(this.createdAt); // dest.writeString(this.desc); // dest.writeString(this.publishedAt); // dest.writeString(this.source); // dest.writeString(this.type); // dest.writeString(this.url); // dest.writeByte(this.used ? (byte) 1 : (byte) 0); // dest.writeString(this.who); // } // // public Girls() { // } // // protected Girls(Parcel in) { // this._id = in.readString(); // this.createdAt = in.readString(); // this.desc = in.readString(); // this.publishedAt = in.readString(); // this.source = in.readString(); // this.type = in.readString(); // this.url = in.readString(); // this.used = in.readByte() != 0; // this.who = in.readString(); // } // // public static final Creator<Girls> CREATOR = new Creator<Girls>() { // @Override // public Girls createFromParcel(Parcel source) { // return new Girls(source); // } // // @Override // public Girls[] newArray(int size) { // return new Girls[size]; // } // }; // } // Path: module_girls/src/main/java/com/guiying/module/girls/main/GirlsContract.java import com.guiying.module.common.base.BasePresenter; import com.guiying.module.common.base.BaseView; import com.guiying.module.girls.data.bean.Girls; import java.util.List; package com.guiying.module.girls.main; /** * <p>类说明</p> * * @author 张华洋 2017/2/22 20:33 * @version V1.2.0 * @name GirlsContract */ public interface GirlsContract { interface View extends BaseView<Presenter> { /** * View 的存活状态 * * @return true or false */ boolean isActive(); void refresh(List<Girls> data); void load(List<Girls> data); void showError(); void showNormal(); }
interface Presenter extends BasePresenter {
guiying712/AndroidModulePattern
module_news/src/main/java/com/guiying/module/news/MyDelegate.java
// Path: lib_common/src/main/java/com/guiying/module/common/base/IApplicationDelegate.java // @Keep // public interface IApplicationDelegate { // // void onCreate(); // // void onTerminate(); // // void onLowMemory(); // // void onTrimMemory(int level); // // } // // Path: lib_common/src/main/java/com/guiying/module/common/base/ViewManager.java // @Keep // public class ViewManager { // // private static Stack<Activity> activityStack; // private static List<BaseFragment> fragmentList; // // public static ViewManager getInstance() { // return ViewManagerHolder.sInstance; // } // // private static class ViewManagerHolder { // private static final ViewManager sInstance = new ViewManager(); // } // // private ViewManager() { // } // // public void addFragment(int index, BaseFragment fragment) { // if (fragmentList == null) { // fragmentList = new ArrayList<>(); // } // fragmentList.add(index, fragment); // } // // // public BaseFragment getFragment(int index) { // if (fragmentList != null) { // return fragmentList.get(index); // } // return null; // } // // // public List<BaseFragment> getAllFragment() { // if (fragmentList != null) { // return fragmentList; // } // return null; // } // // // /** // * 添加指定Activity到堆栈 // */ // public void addActivity(Activity activity) { // if (activityStack == null) { // activityStack = new Stack<Activity>(); // } // activityStack.add(activity); // } // // // /** // * 获取当前Activity // */ // public Activity currentActivity() { // Activity activity = activityStack.lastElement(); // return activity; // } // // // /** // * 结束当前Activity // */ // public void finishActivity() { // Activity activity = activityStack.lastElement(); // finishActivity(activity); // } // // // /** // * 结束指定的Activity // */ // public void finishActivity(Activity activity) { // if (activity != null) { // activityStack.remove(activity); // activity.finish(); // activity = null; // } // } // // // /** // * 结束指定Class的Activity // */ // public void finishActivity(Class<?> cls) { // for (Activity activity : activityStack) { // if (activity.getClass().equals(cls)) { // finishActivity(activity); // return; // } // } // } // // // /** // * 结束全部的Activity // */ // public void finishAllActivity() { // for (int i = 0, size = activityStack.size(); i < size; i++) { // if (null != activityStack.get(i)) { // activityStack.get(i).finish(); // } // } // activityStack.clear(); // } // // // /** // * 退出应用程序 // */ // public void exitApp(Context context) { // try { // finishAllActivity(); // //杀死后台进程需要在AndroidManifest中声明android.permission.KILL_BACKGROUND_PROCESSES; // android.app.ActivityManager activityManager = (android.app.ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); // activityManager.killBackgroundProcesses(context.getPackageName()); // //System.exit(0); // } catch (Exception e) { // Log.e("ActivityManager", "app exit" + e.getMessage()); // } // } // }
import android.support.annotation.Keep; import com.guiying.module.common.base.IApplicationDelegate; import com.guiying.module.common.base.ViewManager; import com.orhanobut.logger.Logger;
package com.guiying.module.news; /** * <p>类说明</p> * * @author 张华洋 2017/9/20 22:29 * @version V2.8.3 * @name MyDelegate */ @Keep public class MyDelegate implements IApplicationDelegate { @Override public void onCreate() { Logger.init("pattern"); //主动添加
// Path: lib_common/src/main/java/com/guiying/module/common/base/IApplicationDelegate.java // @Keep // public interface IApplicationDelegate { // // void onCreate(); // // void onTerminate(); // // void onLowMemory(); // // void onTrimMemory(int level); // // } // // Path: lib_common/src/main/java/com/guiying/module/common/base/ViewManager.java // @Keep // public class ViewManager { // // private static Stack<Activity> activityStack; // private static List<BaseFragment> fragmentList; // // public static ViewManager getInstance() { // return ViewManagerHolder.sInstance; // } // // private static class ViewManagerHolder { // private static final ViewManager sInstance = new ViewManager(); // } // // private ViewManager() { // } // // public void addFragment(int index, BaseFragment fragment) { // if (fragmentList == null) { // fragmentList = new ArrayList<>(); // } // fragmentList.add(index, fragment); // } // // // public BaseFragment getFragment(int index) { // if (fragmentList != null) { // return fragmentList.get(index); // } // return null; // } // // // public List<BaseFragment> getAllFragment() { // if (fragmentList != null) { // return fragmentList; // } // return null; // } // // // /** // * 添加指定Activity到堆栈 // */ // public void addActivity(Activity activity) { // if (activityStack == null) { // activityStack = new Stack<Activity>(); // } // activityStack.add(activity); // } // // // /** // * 获取当前Activity // */ // public Activity currentActivity() { // Activity activity = activityStack.lastElement(); // return activity; // } // // // /** // * 结束当前Activity // */ // public void finishActivity() { // Activity activity = activityStack.lastElement(); // finishActivity(activity); // } // // // /** // * 结束指定的Activity // */ // public void finishActivity(Activity activity) { // if (activity != null) { // activityStack.remove(activity); // activity.finish(); // activity = null; // } // } // // // /** // * 结束指定Class的Activity // */ // public void finishActivity(Class<?> cls) { // for (Activity activity : activityStack) { // if (activity.getClass().equals(cls)) { // finishActivity(activity); // return; // } // } // } // // // /** // * 结束全部的Activity // */ // public void finishAllActivity() { // for (int i = 0, size = activityStack.size(); i < size; i++) { // if (null != activityStack.get(i)) { // activityStack.get(i).finish(); // } // } // activityStack.clear(); // } // // // /** // * 退出应用程序 // */ // public void exitApp(Context context) { // try { // finishAllActivity(); // //杀死后台进程需要在AndroidManifest中声明android.permission.KILL_BACKGROUND_PROCESSES; // android.app.ActivityManager activityManager = (android.app.ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); // activityManager.killBackgroundProcesses(context.getPackageName()); // //System.exit(0); // } catch (Exception e) { // Log.e("ActivityManager", "app exit" + e.getMessage()); // } // } // } // Path: module_news/src/main/java/com/guiying/module/news/MyDelegate.java import android.support.annotation.Keep; import com.guiying.module.common.base.IApplicationDelegate; import com.guiying.module.common.base.ViewManager; import com.orhanobut.logger.Logger; package com.guiying.module.news; /** * <p>类说明</p> * * @author 张华洋 2017/9/20 22:29 * @version V2.8.3 * @name MyDelegate */ @Keep public class MyDelegate implements IApplicationDelegate { @Override public void onCreate() { Logger.init("pattern"); //主动添加
ViewManager.getInstance().addFragment(0, NewsFragment.newInstance());
guiying712/AndroidModulePattern
module_news/src/main/java/debug/LauncherActivity.java
// Path: module_news/src/main/java/com/guiying/module/news/detail/NewsDetailActivity.java // @Route(path = "/news/detail") // public class NewsDetailActivity extends BaseActivity { // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // NewsDetailView detailView = new NewsDetailView(this); // setContentView(detailView); // String id = getIntent().getStringExtra("id"); // new NewsDetailPresenter(detailView).getNewsDetail(id); // } // // }
import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import com.guiying.module.news.detail.NewsDetailActivity;
package debug; /** * <p>组件开发模式下,用于传递数据的启动Activity,集成模式下无效</p> * * @author 张华洋 * @version V1.2.0 * @name LauncherActivity */ public class LauncherActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //在这里传值给需要调试的Activity
// Path: module_news/src/main/java/com/guiying/module/news/detail/NewsDetailActivity.java // @Route(path = "/news/detail") // public class NewsDetailActivity extends BaseActivity { // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // NewsDetailView detailView = new NewsDetailView(this); // setContentView(detailView); // String id = getIntent().getStringExtra("id"); // new NewsDetailPresenter(detailView).getNewsDetail(id); // } // // } // Path: module_news/src/main/java/debug/LauncherActivity.java import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import com.guiying.module.news.detail.NewsDetailActivity; package debug; /** * <p>组件开发模式下,用于传递数据的启动Activity,集成模式下无效</p> * * @author 张华洋 * @version V1.2.0 * @name LauncherActivity */ public class LauncherActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //在这里传值给需要调试的Activity
Intent intent = new Intent(this, NewsDetailActivity.class);
guiying712/AndroidModulePattern
module_news/src/main/java/com/guiying/module/news/detail/NewsDetailContract.java
// Path: lib_common/src/main/java/com/guiying/module/common/base/BasePresenter.java // @Keep // public interface BasePresenter { // // void start(); // // } // // Path: lib_common/src/main/java/com/guiying/module/common/base/BaseView.java // @Keep // public interface BaseView<T> { // // void setPresenter(T presenter); // // } // // Path: module_news/src/main/java/com/guiying/module/news/data/bean/MessageDetail.java // public class MessageDetail { // private String body; // private String image_source; // private String title; // private String image; // private String share_url; // private List<String> recommenders; // private String ga_prefix; // private String type; // private String id; // // public String getBody() { // return body; // } // // public void setBody(String body) { // this.body = body; // } // // public String getImage_source() { // return image_source; // } // // public void setImage_source(String image_source) { // this.image_source = image_source; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getImage() { // return image; // } // // public void setImage(String image) { // this.image = image; // } // // public String getShare_url() { // return share_url; // } // // public void setShare_url(String share_url) { // this.share_url = share_url; // } // // public List<String> getRecommenders() { // return recommenders; // } // // public void setRecommenders(List<String> recommenders) { // this.recommenders = recommenders; // } // // public String getGa_prefix() { // return ga_prefix; // } // // public void setGa_prefix(String ga_prefix) { // this.ga_prefix = ga_prefix; // } // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // @Override // public String toString() { // return "MessageDetail{" + // "body='" + body + '\'' + // ", image_source='" + image_source + '\'' + // ", title='" + title + '\'' + // ", image='" + image + '\'' + // ", share_url='" + share_url + '\'' + // ", recommenders=" + recommenders + // ", ga_prefix='" + ga_prefix + '\'' + // ", type='" + type + '\'' + // ", id='" + id + '\'' + // '}'; // } // }
import com.guiying.module.common.base.BasePresenter; import com.guiying.module.common.base.BaseView; import com.guiying.module.news.data.bean.MessageDetail;
package com.guiying.module.news.detail; /** * <p>类说明</p> * * @author 张华洋 2017/2/22 20:33 * @version V1.2.0 * @name NewsContract */ public interface NewsDetailContract { interface View extends BaseView<Presenter> { boolean isActive();
// Path: lib_common/src/main/java/com/guiying/module/common/base/BasePresenter.java // @Keep // public interface BasePresenter { // // void start(); // // } // // Path: lib_common/src/main/java/com/guiying/module/common/base/BaseView.java // @Keep // public interface BaseView<T> { // // void setPresenter(T presenter); // // } // // Path: module_news/src/main/java/com/guiying/module/news/data/bean/MessageDetail.java // public class MessageDetail { // private String body; // private String image_source; // private String title; // private String image; // private String share_url; // private List<String> recommenders; // private String ga_prefix; // private String type; // private String id; // // public String getBody() { // return body; // } // // public void setBody(String body) { // this.body = body; // } // // public String getImage_source() { // return image_source; // } // // public void setImage_source(String image_source) { // this.image_source = image_source; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getImage() { // return image; // } // // public void setImage(String image) { // this.image = image; // } // // public String getShare_url() { // return share_url; // } // // public void setShare_url(String share_url) { // this.share_url = share_url; // } // // public List<String> getRecommenders() { // return recommenders; // } // // public void setRecommenders(List<String> recommenders) { // this.recommenders = recommenders; // } // // public String getGa_prefix() { // return ga_prefix; // } // // public void setGa_prefix(String ga_prefix) { // this.ga_prefix = ga_prefix; // } // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // @Override // public String toString() { // return "MessageDetail{" + // "body='" + body + '\'' + // ", image_source='" + image_source + '\'' + // ", title='" + title + '\'' + // ", image='" + image + '\'' + // ", share_url='" + share_url + '\'' + // ", recommenders=" + recommenders + // ", ga_prefix='" + ga_prefix + '\'' + // ", type='" + type + '\'' + // ", id='" + id + '\'' + // '}'; // } // } // Path: module_news/src/main/java/com/guiying/module/news/detail/NewsDetailContract.java import com.guiying.module.common.base.BasePresenter; import com.guiying.module.common.base.BaseView; import com.guiying.module.news.data.bean.MessageDetail; package com.guiying.module.news.detail; /** * <p>类说明</p> * * @author 张华洋 2017/2/22 20:33 * @version V1.2.0 * @name NewsContract */ public interface NewsDetailContract { interface View extends BaseView<Presenter> { boolean isActive();
void showNewsDetail(MessageDetail detail);