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
octavian-h/time-series-math
src/test/java/ro/hasna/ts/math/ml/distance/util/DistanceTester.java
// Path: src/main/java/ro/hasna/ts/math/ml/distance/GenericDistanceMeasure.java // public interface GenericDistanceMeasure<T> extends Serializable { // /** // * Compute the distance between two n-dimensional vectors. // * <p> // * The two vectors are required to have the same dimension. // * // * @param a the first vector // * @param b the second vector // * @return the distance between the two vectors // */ // double compute(T a, T b); // // /** // * Compute the distance between two n-dimensional vectors. // * <p> // * The two vectors are required to have the same dimension. // * // * @param a the first vector // * @param b the second vector // * @param cutOffValue if the distance being calculated is above this value // * stop computing the remaining distance // * @return the distance between the two vectors // */ // double compute(T a, T b, double cutOffValue); // } // // Path: src/main/java/ro/hasna/ts/math/representation/GenericTransformer.java // public interface GenericTransformer<I, O> extends Serializable { // /** // * Transform the input vector from type I into type O. // * // * @param input the input vector // * @return the output vector // */ // O transform(I input); // } // // Path: src/main/java/ro/hasna/ts/math/util/TimeSeriesPrecision.java // public class TimeSeriesPrecision { // public static final double EPSILON = FastMath.pow(2, -30); // // /** // * Private constructor. // */ // private TimeSeriesPrecision() { // } // }
import org.apache.commons.math3.ml.distance.DistanceMeasure; import org.junit.Assert; import ro.hasna.ts.math.ml.distance.GenericDistanceMeasure; import ro.hasna.ts.math.representation.GenericTransformer; import ro.hasna.ts.math.util.TimeSeriesPrecision;
this.offset = offset; return this; } public DistanceTester withCutOffValue(double cutOffValue) { this.cutOffValue = cutOffValue; return this; } public DistanceTester withExpectedResult(double expectedResult) { this.expectedResult = expectedResult; return this; } public void testTriangleInequality() throws Exception { double[] a = new double[vectorLength]; double[] b = new double[vectorLength]; double[] c = new double[vectorLength]; for (int i = 0; i < vectorLength; i++) { a[i] = i; b[i] = vectorLength - i; c[i] = i * i; } double ab = distance.compute(a, b); double ba = distance.compute(b, a); double bc = distance.compute(b, c); double ac = distance.compute(a, c);
// Path: src/main/java/ro/hasna/ts/math/ml/distance/GenericDistanceMeasure.java // public interface GenericDistanceMeasure<T> extends Serializable { // /** // * Compute the distance between two n-dimensional vectors. // * <p> // * The two vectors are required to have the same dimension. // * // * @param a the first vector // * @param b the second vector // * @return the distance between the two vectors // */ // double compute(T a, T b); // // /** // * Compute the distance between two n-dimensional vectors. // * <p> // * The two vectors are required to have the same dimension. // * // * @param a the first vector // * @param b the second vector // * @param cutOffValue if the distance being calculated is above this value // * stop computing the remaining distance // * @return the distance between the two vectors // */ // double compute(T a, T b, double cutOffValue); // } // // Path: src/main/java/ro/hasna/ts/math/representation/GenericTransformer.java // public interface GenericTransformer<I, O> extends Serializable { // /** // * Transform the input vector from type I into type O. // * // * @param input the input vector // * @return the output vector // */ // O transform(I input); // } // // Path: src/main/java/ro/hasna/ts/math/util/TimeSeriesPrecision.java // public class TimeSeriesPrecision { // public static final double EPSILON = FastMath.pow(2, -30); // // /** // * Private constructor. // */ // private TimeSeriesPrecision() { // } // } // Path: src/test/java/ro/hasna/ts/math/ml/distance/util/DistanceTester.java import org.apache.commons.math3.ml.distance.DistanceMeasure; import org.junit.Assert; import ro.hasna.ts.math.ml.distance.GenericDistanceMeasure; import ro.hasna.ts.math.representation.GenericTransformer; import ro.hasna.ts.math.util.TimeSeriesPrecision; this.offset = offset; return this; } public DistanceTester withCutOffValue(double cutOffValue) { this.cutOffValue = cutOffValue; return this; } public DistanceTester withExpectedResult(double expectedResult) { this.expectedResult = expectedResult; return this; } public void testTriangleInequality() throws Exception { double[] a = new double[vectorLength]; double[] b = new double[vectorLength]; double[] c = new double[vectorLength]; for (int i = 0; i < vectorLength; i++) { a[i] = i; b[i] = vectorLength - i; c[i] = i * i; } double ab = distance.compute(a, b); double ba = distance.compute(b, a); double bc = distance.compute(b, c); double ac = distance.compute(a, c);
Assert.assertEquals(ab, ba, TimeSeriesPrecision.EPSILON);
octavian-h/time-series-math
src/main/java/ro/hasna/ts/math/representation/AdaptivePiecewiseConstantApproximation.java
// Path: src/main/java/ro/hasna/ts/math/exception/ArrayLengthIsTooSmallException.java // public class ArrayLengthIsTooSmallException extends NumberIsTooSmallException { // private static final long serialVersionUID = -2633584088507009304L; // // /** // * Construct the exception. // * // * @param wrong Value that is smaller than the minimum. // * @param min Minimum. // * @param boundIsAllowed Whether {@code min} is included in the allowed range. // */ // public ArrayLengthIsTooSmallException(Number wrong, Number min, boolean boundIsAllowed) { // super(wrong, min, boundIsAllowed); // } // // /** // * Construct the exception with a specific context. // * // * @param specific Specific context pattern. // * @param wrong Value that is smaller than the minimum. // * @param min Minimum. // * @param boundIsAllowed Whether {@code min} is included in the allowed range. // */ // public ArrayLengthIsTooSmallException(Localizable specific, Number wrong, Number min, boolean boundIsAllowed) { // super(specific, wrong, min, boundIsAllowed); // } // } // // Path: src/main/java/ro/hasna/ts/math/type/MeanLastPair.java // @Data // public class MeanLastPair { // /** // * The mean value for the segment. // */ // private final double mean; // /** // * The position from the last element of the segment. // */ // private final int last; // } // // Path: src/main/java/ro/hasna/ts/math/util/TimeSeriesPrecision.java // public class TimeSeriesPrecision { // public static final double EPSILON = FastMath.pow(2, -30); // // /** // * Private constructor. // */ // private TimeSeriesPrecision() { // } // }
import org.apache.commons.math3.exception.NumberIsTooSmallException; import org.apache.commons.math3.util.FastMath; import org.apache.commons.math3.util.Precision; import ro.hasna.ts.math.exception.ArrayLengthIsTooSmallException; import ro.hasna.ts.math.type.MeanLastPair; import ro.hasna.ts.math.util.TimeSeriesPrecision; import java.util.Set; import java.util.TreeSet;
/* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.representation; /** * Implements the Adaptive Piecewise Constant Approximation (APCA) algorithm. * <p> * Reference: * Chakrabarti K., Keogh E., Mehrotra S., Pazzani M. (2002) * <i>Locally Adaptive Dimensionality Reduction for Indexing Large Time Series Databases</i> * </p> * * @since 0.8 */ public class AdaptivePiecewiseConstantApproximation implements GenericTransformer<double[], MeanLastPair[]> { private static final long serialVersionUID = 5071554004881637993L; private final int segments; private final boolean approximateError; /** * Creates a new instance of this class with approximation enabled. * * @param segments the number of segments * @throws NumberIsTooSmallException if segments lower than 1 */ public AdaptivePiecewiseConstantApproximation(int segments) { this(segments, true); } /** * Creates a new instance of this class with a flag for using approximation. * * @param segments the number of segments * @param approximateError compute the error of unified segments using approximation * @throws NumberIsTooSmallException if segments lower than 1 */ public AdaptivePiecewiseConstantApproximation(int segments, boolean approximateError) { if (segments < 1) { throw new NumberIsTooSmallException(segments, 1, true); } this.segments = segments; this.approximateError = approximateError; } @Override public MeanLastPair[] transform(double[] values) { int length = values.length; if (length < 2 * segments) {
// Path: src/main/java/ro/hasna/ts/math/exception/ArrayLengthIsTooSmallException.java // public class ArrayLengthIsTooSmallException extends NumberIsTooSmallException { // private static final long serialVersionUID = -2633584088507009304L; // // /** // * Construct the exception. // * // * @param wrong Value that is smaller than the minimum. // * @param min Minimum. // * @param boundIsAllowed Whether {@code min} is included in the allowed range. // */ // public ArrayLengthIsTooSmallException(Number wrong, Number min, boolean boundIsAllowed) { // super(wrong, min, boundIsAllowed); // } // // /** // * Construct the exception with a specific context. // * // * @param specific Specific context pattern. // * @param wrong Value that is smaller than the minimum. // * @param min Minimum. // * @param boundIsAllowed Whether {@code min} is included in the allowed range. // */ // public ArrayLengthIsTooSmallException(Localizable specific, Number wrong, Number min, boolean boundIsAllowed) { // super(specific, wrong, min, boundIsAllowed); // } // } // // Path: src/main/java/ro/hasna/ts/math/type/MeanLastPair.java // @Data // public class MeanLastPair { // /** // * The mean value for the segment. // */ // private final double mean; // /** // * The position from the last element of the segment. // */ // private final int last; // } // // Path: src/main/java/ro/hasna/ts/math/util/TimeSeriesPrecision.java // public class TimeSeriesPrecision { // public static final double EPSILON = FastMath.pow(2, -30); // // /** // * Private constructor. // */ // private TimeSeriesPrecision() { // } // } // Path: src/main/java/ro/hasna/ts/math/representation/AdaptivePiecewiseConstantApproximation.java import org.apache.commons.math3.exception.NumberIsTooSmallException; import org.apache.commons.math3.util.FastMath; import org.apache.commons.math3.util.Precision; import ro.hasna.ts.math.exception.ArrayLengthIsTooSmallException; import ro.hasna.ts.math.type.MeanLastPair; import ro.hasna.ts.math.util.TimeSeriesPrecision; import java.util.Set; import java.util.TreeSet; /* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.representation; /** * Implements the Adaptive Piecewise Constant Approximation (APCA) algorithm. * <p> * Reference: * Chakrabarti K., Keogh E., Mehrotra S., Pazzani M. (2002) * <i>Locally Adaptive Dimensionality Reduction for Indexing Large Time Series Databases</i> * </p> * * @since 0.8 */ public class AdaptivePiecewiseConstantApproximation implements GenericTransformer<double[], MeanLastPair[]> { private static final long serialVersionUID = 5071554004881637993L; private final int segments; private final boolean approximateError; /** * Creates a new instance of this class with approximation enabled. * * @param segments the number of segments * @throws NumberIsTooSmallException if segments lower than 1 */ public AdaptivePiecewiseConstantApproximation(int segments) { this(segments, true); } /** * Creates a new instance of this class with a flag for using approximation. * * @param segments the number of segments * @param approximateError compute the error of unified segments using approximation * @throws NumberIsTooSmallException if segments lower than 1 */ public AdaptivePiecewiseConstantApproximation(int segments, boolean approximateError) { if (segments < 1) { throw new NumberIsTooSmallException(segments, 1, true); } this.segments = segments; this.approximateError = approximateError; } @Override public MeanLastPair[] transform(double[] values) { int length = values.length; if (length < 2 * segments) {
throw new ArrayLengthIsTooSmallException(length, 2 * segments, true);
octavian-h/time-series-math
src/main/java/ro/hasna/ts/math/representation/AdaptivePiecewiseConstantApproximation.java
// Path: src/main/java/ro/hasna/ts/math/exception/ArrayLengthIsTooSmallException.java // public class ArrayLengthIsTooSmallException extends NumberIsTooSmallException { // private static final long serialVersionUID = -2633584088507009304L; // // /** // * Construct the exception. // * // * @param wrong Value that is smaller than the minimum. // * @param min Minimum. // * @param boundIsAllowed Whether {@code min} is included in the allowed range. // */ // public ArrayLengthIsTooSmallException(Number wrong, Number min, boolean boundIsAllowed) { // super(wrong, min, boundIsAllowed); // } // // /** // * Construct the exception with a specific context. // * // * @param specific Specific context pattern. // * @param wrong Value that is smaller than the minimum. // * @param min Minimum. // * @param boundIsAllowed Whether {@code min} is included in the allowed range. // */ // public ArrayLengthIsTooSmallException(Localizable specific, Number wrong, Number min, boolean boundIsAllowed) { // super(specific, wrong, min, boundIsAllowed); // } // } // // Path: src/main/java/ro/hasna/ts/math/type/MeanLastPair.java // @Data // public class MeanLastPair { // /** // * The mean value for the segment. // */ // private final double mean; // /** // * The position from the last element of the segment. // */ // private final int last; // } // // Path: src/main/java/ro/hasna/ts/math/util/TimeSeriesPrecision.java // public class TimeSeriesPrecision { // public static final double EPSILON = FastMath.pow(2, -30); // // /** // * Private constructor. // */ // private TimeSeriesPrecision() { // } // }
import org.apache.commons.math3.exception.NumberIsTooSmallException; import org.apache.commons.math3.util.FastMath; import org.apache.commons.math3.util.Precision; import ro.hasna.ts.math.exception.ArrayLengthIsTooSmallException; import ro.hasna.ts.math.type.MeanLastPair; import ro.hasna.ts.math.util.TimeSeriesPrecision; import java.util.Set; import java.util.TreeSet;
set.add(minSegment.prev); } numberOfSegments--; } } return getMeanLastPairs(first, numberOfSegments); } private Segment createSegments(double[] values, int length) { Segment first = null, last = null; for (int i = 0; i < length - 1; i += 2) { double mean = (values[i] + values[i + 1]) / 2; Segment segment = new Segment(i, i + 2, mean, 2 * FastMath.abs(values[i] - mean)); if (first == null) { first = segment; last = first; } else { last.next = segment; segment.prev = last; last = last.next; } } return first; } private TreeSet<Segment> createSegmentsSet(double[] values, Segment first) { TreeSet<Segment> map = new TreeSet<>((s1, s2) ->
// Path: src/main/java/ro/hasna/ts/math/exception/ArrayLengthIsTooSmallException.java // public class ArrayLengthIsTooSmallException extends NumberIsTooSmallException { // private static final long serialVersionUID = -2633584088507009304L; // // /** // * Construct the exception. // * // * @param wrong Value that is smaller than the minimum. // * @param min Minimum. // * @param boundIsAllowed Whether {@code min} is included in the allowed range. // */ // public ArrayLengthIsTooSmallException(Number wrong, Number min, boolean boundIsAllowed) { // super(wrong, min, boundIsAllowed); // } // // /** // * Construct the exception with a specific context. // * // * @param specific Specific context pattern. // * @param wrong Value that is smaller than the minimum. // * @param min Minimum. // * @param boundIsAllowed Whether {@code min} is included in the allowed range. // */ // public ArrayLengthIsTooSmallException(Localizable specific, Number wrong, Number min, boolean boundIsAllowed) { // super(specific, wrong, min, boundIsAllowed); // } // } // // Path: src/main/java/ro/hasna/ts/math/type/MeanLastPair.java // @Data // public class MeanLastPair { // /** // * The mean value for the segment. // */ // private final double mean; // /** // * The position from the last element of the segment. // */ // private final int last; // } // // Path: src/main/java/ro/hasna/ts/math/util/TimeSeriesPrecision.java // public class TimeSeriesPrecision { // public static final double EPSILON = FastMath.pow(2, -30); // // /** // * Private constructor. // */ // private TimeSeriesPrecision() { // } // } // Path: src/main/java/ro/hasna/ts/math/representation/AdaptivePiecewiseConstantApproximation.java import org.apache.commons.math3.exception.NumberIsTooSmallException; import org.apache.commons.math3.util.FastMath; import org.apache.commons.math3.util.Precision; import ro.hasna.ts.math.exception.ArrayLengthIsTooSmallException; import ro.hasna.ts.math.type.MeanLastPair; import ro.hasna.ts.math.util.TimeSeriesPrecision; import java.util.Set; import java.util.TreeSet; set.add(minSegment.prev); } numberOfSegments--; } } return getMeanLastPairs(first, numberOfSegments); } private Segment createSegments(double[] values, int length) { Segment first = null, last = null; for (int i = 0; i < length - 1; i += 2) { double mean = (values[i] + values[i + 1]) / 2; Segment segment = new Segment(i, i + 2, mean, 2 * FastMath.abs(values[i] - mean)); if (first == null) { first = segment; last = first; } else { last.next = segment; segment.prev = last; last = last.next; } } return first; } private TreeSet<Segment> createSegmentsSet(double[] values, Segment first) { TreeSet<Segment> map = new TreeSet<>((s1, s2) ->
Precision.compareTo(s1.errorWithNext, s2.errorWithNext, TimeSeriesPrecision.EPSILON));
octavian-h/time-series-math
src/test/java/ro/hasna/ts/math/representation/SymbolicAggregateApproximationTest.java
// Path: src/main/java/ro/hasna/ts/math/normalization/ZNormalizer.java // public class ZNormalizer implements Normalizer { // private static final long serialVersionUID = 6446811014325682141L; // private final Mean mean; // private final StandardDeviation standardDeviation; // // public ZNormalizer() { // this(new Mean(), new StandardDeviation(false)); // } // // /** // * Creates a new instance of this class with the given mean and standard deviation algorithms. // * // * @param mean the mean // * @param standardDeviation the standard deviation // */ // public ZNormalizer(final Mean mean, final StandardDeviation standardDeviation) { // this.mean = mean; // this.standardDeviation = standardDeviation; // } // // /** // * {@inheritDoc} // */ // @Override // public double[] normalize(double[] values) { // double m = mean.evaluate(values); // double sd = standardDeviation.evaluate(values, m); // // int length = values.length; // double[] normalizedValues = new double[length]; // for (int i = 0; i < length; i++) { // normalizedValues[i] = (values[i] - m) / sd; // } // return normalizedValues; // } // }
import org.junit.Assert; import org.junit.Test; import ro.hasna.ts.math.normalization.ZNormalizer;
/* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.representation; public class SymbolicAggregateApproximationTest { @Test public void testTransformToIntArray1() throws Exception { double[] list = new double[64]; for (int i = 0; i < 32; i++) { list[i] = i; } for (int i = 32; i < 64; i++) { list[i] = 64 - i; } double[] breakpoints = {-0.4307272992954576, 0.4307272992954576}; int[] expected = {0, 0, 1, 2, 2, 2, 1, 0, 0};
// Path: src/main/java/ro/hasna/ts/math/normalization/ZNormalizer.java // public class ZNormalizer implements Normalizer { // private static final long serialVersionUID = 6446811014325682141L; // private final Mean mean; // private final StandardDeviation standardDeviation; // // public ZNormalizer() { // this(new Mean(), new StandardDeviation(false)); // } // // /** // * Creates a new instance of this class with the given mean and standard deviation algorithms. // * // * @param mean the mean // * @param standardDeviation the standard deviation // */ // public ZNormalizer(final Mean mean, final StandardDeviation standardDeviation) { // this.mean = mean; // this.standardDeviation = standardDeviation; // } // // /** // * {@inheritDoc} // */ // @Override // public double[] normalize(double[] values) { // double m = mean.evaluate(values); // double sd = standardDeviation.evaluate(values, m); // // int length = values.length; // double[] normalizedValues = new double[length]; // for (int i = 0; i < length; i++) { // normalizedValues[i] = (values[i] - m) / sd; // } // return normalizedValues; // } // } // Path: src/test/java/ro/hasna/ts/math/representation/SymbolicAggregateApproximationTest.java import org.junit.Assert; import org.junit.Test; import ro.hasna.ts.math.normalization.ZNormalizer; /* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.representation; public class SymbolicAggregateApproximationTest { @Test public void testTransformToIntArray1() throws Exception { double[] list = new double[64]; for (int i = 0; i < 32; i++) { list[i] = i; } for (int i = 32; i < 64; i++) { list[i] = 64 - i; } double[] breakpoints = {-0.4307272992954576, 0.4307272992954576}; int[] expected = {0, 0, 1, 2, 2, 2, 1, 0, 0};
SymbolicAggregateApproximation sax = new SymbolicAggregateApproximation(new PiecewiseAggregateApproximation(9), new ZNormalizer(), breakpoints);
octavian-h/time-series-math
src/test/java/ro/hasna/ts/math/type/MeanLastPairTest.java
// Path: src/main/java/ro/hasna/ts/math/util/TimeSeriesPrecision.java // public class TimeSeriesPrecision { // public static final double EPSILON = FastMath.pow(2, -30); // // /** // * Private constructor. // */ // private TimeSeriesPrecision() { // } // }
import org.junit.Assert; import org.junit.Test; import ro.hasna.ts.math.util.TimeSeriesPrecision;
/* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.type; public class MeanLastPairTest { @Test public void testGetters() throws Exception { MeanLastPair pair = new MeanLastPair(10.0, 20);
// Path: src/main/java/ro/hasna/ts/math/util/TimeSeriesPrecision.java // public class TimeSeriesPrecision { // public static final double EPSILON = FastMath.pow(2, -30); // // /** // * Private constructor. // */ // private TimeSeriesPrecision() { // } // } // Path: src/test/java/ro/hasna/ts/math/type/MeanLastPairTest.java import org.junit.Assert; import org.junit.Test; import ro.hasna.ts.math.util.TimeSeriesPrecision; /* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.type; public class MeanLastPairTest { @Test public void testGetters() throws Exception { MeanLastPair pair = new MeanLastPair(10.0, 20);
Assert.assertEquals(10.0, pair.getMean(), TimeSeriesPrecision.EPSILON);
octavian-h/time-series-math
src/main/java/ro/hasna/ts/math/filter/ExponentialMovingAverageFilter.java
// Path: src/main/java/ro/hasna/ts/math/exception/util/LocalizableMessages.java // public class LocalizableMessages { // public static final Localizable NUMBER_NOT_DIVISIBLE_WITH = new DummyLocalizable("{0} is not divisible with {1}"); // public static final Localizable OUT_OF_RANGE_BOTH_EXCLUSIVE = new DummyLocalizable("{0} out of ({1}, {2}) range"); // public static final Localizable OUT_OF_RANGE_BOTH_INCLUSIVE = new DummyLocalizable("{0} out of [{1}, {2}] range"); // public static final Localizable OPERATION_WAS_CANCELLED = new DummyLocalizable("The operation was cancelled."); // // private LocalizableMessages() { // } // }
import org.apache.commons.math3.exception.OutOfRangeException; import ro.hasna.ts.math.exception.util.LocalizableMessages;
/* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.filter; /** * Implements the exponential moving average filter (exponential smoothing). * * @since 0.3 */ public class ExponentialMovingAverageFilter implements Filter { private static final long serialVersionUID = -5033372522209156302L; private final double smoothingFactor; public ExponentialMovingAverageFilter(double smoothingFactor) { if (smoothingFactor <= 0 || smoothingFactor >= 1) {
// Path: src/main/java/ro/hasna/ts/math/exception/util/LocalizableMessages.java // public class LocalizableMessages { // public static final Localizable NUMBER_NOT_DIVISIBLE_WITH = new DummyLocalizable("{0} is not divisible with {1}"); // public static final Localizable OUT_OF_RANGE_BOTH_EXCLUSIVE = new DummyLocalizable("{0} out of ({1}, {2}) range"); // public static final Localizable OUT_OF_RANGE_BOTH_INCLUSIVE = new DummyLocalizable("{0} out of [{1}, {2}] range"); // public static final Localizable OPERATION_WAS_CANCELLED = new DummyLocalizable("The operation was cancelled."); // // private LocalizableMessages() { // } // } // Path: src/main/java/ro/hasna/ts/math/filter/ExponentialMovingAverageFilter.java import org.apache.commons.math3.exception.OutOfRangeException; import ro.hasna.ts.math.exception.util.LocalizableMessages; /* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.filter; /** * Implements the exponential moving average filter (exponential smoothing). * * @since 0.3 */ public class ExponentialMovingAverageFilter implements Filter { private static final long serialVersionUID = -5033372522209156302L; private final double smoothingFactor; public ExponentialMovingAverageFilter(double smoothingFactor) { if (smoothingFactor <= 0 || smoothingFactor >= 1) {
throw new OutOfRangeException(LocalizableMessages.OUT_OF_RANGE_BOTH_EXCLUSIVE, smoothingFactor, 0, 1);
octavian-h/time-series-math
src/test/java/ro/hasna/ts/math/type/MeanSlopePairTest.java
// Path: src/main/java/ro/hasna/ts/math/util/TimeSeriesPrecision.java // public class TimeSeriesPrecision { // public static final double EPSILON = FastMath.pow(2, -30); // // /** // * Private constructor. // */ // private TimeSeriesPrecision() { // } // }
import org.junit.Assert; import org.junit.Test; import ro.hasna.ts.math.util.TimeSeriesPrecision;
/* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.type; public class MeanSlopePairTest { @Test public void testGetters() throws Exception { MeanSlopePair pair = new MeanSlopePair(10.0, 20.0);
// Path: src/main/java/ro/hasna/ts/math/util/TimeSeriesPrecision.java // public class TimeSeriesPrecision { // public static final double EPSILON = FastMath.pow(2, -30); // // /** // * Private constructor. // */ // private TimeSeriesPrecision() { // } // } // Path: src/test/java/ro/hasna/ts/math/type/MeanSlopePairTest.java import org.junit.Assert; import org.junit.Test; import ro.hasna.ts.math.util.TimeSeriesPrecision; /* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.type; public class MeanSlopePairTest { @Test public void testGetters() throws Exception { MeanSlopePair pair = new MeanSlopePair(10.0, 20.0);
Assert.assertEquals(10.0, pair.getMean(), TimeSeriesPrecision.EPSILON);
krasa/FrameSwitcher
src/krasa/frameswitcher/networking/DummyRemoteSender.java
// Path: src/krasa/frameswitcher/networking/dto/RemoteProject.java // public class RemoteProject implements Serializable { // // private final String name; // private final String projectPath; // // public RemoteProject(String name, String projectPath) { // this.name = name; // this.projectPath = projectPath; // } // // public RemoteProject(Project project) { // this(project.getName(), project.getBasePath()); // } // // public RemoteProject(ReopenProjectAction project) { // this(project.getProjectName(), project.getProjectPath()); // } // // public String getName() { // return name; // } // // public String getProjectPath() { // return projectPath; // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // // RemoteProject that = (RemoteProject) o; // // if (projectPath != null ? !projectPath.equals(that.projectPath) : that.projectPath != null) { // return false; // } // if (name != null ? !name.equals(that.name) : that.name != null) { // return false; // } // // return true; // } // // @Override // public int hashCode() { // int result = name != null ? name.hashCode() : 0; // result = 31 * result + (projectPath != null ? projectPath.hashCode() : 0); // return result; // } // // @Override // public String toString() { // return ReflectionToStringBuilder.toString(this, ToStringStyle.SHORT_PREFIX_STYLE); // } // }
import com.intellij.openapi.project.Project; import krasa.frameswitcher.networking.dto.RemoteProject; import org.jgroups.Message; import java.util.UUID;
package krasa.frameswitcher.networking; /** * @author Vojtech Krasa */ public class DummyRemoteSender implements RemoteSender { @Override public void sendInstanceStarted() { } @Override public void sendProjectsState() { } @Override public void dispose() { } @Override public void asyncPing() { } @Override public void asyncProjectOpened(Project project) { } @Override public void sendProjectClosed(Project project) { } @Override
// Path: src/krasa/frameswitcher/networking/dto/RemoteProject.java // public class RemoteProject implements Serializable { // // private final String name; // private final String projectPath; // // public RemoteProject(String name, String projectPath) { // this.name = name; // this.projectPath = projectPath; // } // // public RemoteProject(Project project) { // this(project.getName(), project.getBasePath()); // } // // public RemoteProject(ReopenProjectAction project) { // this(project.getProjectName(), project.getProjectPath()); // } // // public String getName() { // return name; // } // // public String getProjectPath() { // return projectPath; // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // // RemoteProject that = (RemoteProject) o; // // if (projectPath != null ? !projectPath.equals(that.projectPath) : that.projectPath != null) { // return false; // } // if (name != null ? !name.equals(that.name) : that.name != null) { // return false; // } // // return true; // } // // @Override // public int hashCode() { // int result = name != null ? name.hashCode() : 0; // result = 31 * result + (projectPath != null ? projectPath.hashCode() : 0); // return result; // } // // @Override // public String toString() { // return ReflectionToStringBuilder.toString(this, ToStringStyle.SHORT_PREFIX_STYLE); // } // } // Path: src/krasa/frameswitcher/networking/DummyRemoteSender.java import com.intellij.openapi.project.Project; import krasa.frameswitcher.networking.dto.RemoteProject; import org.jgroups.Message; import java.util.UUID; package krasa.frameswitcher.networking; /** * @author Vojtech Krasa */ public class DummyRemoteSender implements RemoteSender { @Override public void sendInstanceStarted() { } @Override public void sendProjectsState() { } @Override public void dispose() { } @Override public void asyncPing() { } @Override public void asyncProjectOpened(Project project) { } @Override public void sendProjectClosed(Project project) { } @Override
public void openProject(UUID target, RemoteProject remoteProject) {
krasa/FrameSwitcher
src/krasa/frameswitcher/networking/RemoteInstancesState.java
// Path: src/krasa/frameswitcher/FrameSwitcherApplicationService.java // @State(name = "FrameSwitcherSettings", storages = {@Storage("FrameSwitcherSettings.xml")}) // public class FrameSwitcherApplicationService implements PersistentStateComponent<FrameSwitcherSettings>, Disposable { // // private static final Logger LOG = Logger.getInstance(FrameSwitcherApplicationService.class); // // public static final String IDE_MAX_RECENT_PROJECTS = "ide.max.recent.projects"; // // // private FrameSwitcherSettings settings=new FrameSwitcherSettings(); // private RemoteInstancesState remoteInstancesState = new RemoteInstancesState(); // private ProjectFocusMonitor projectFocusMonitor=new ProjectFocusMonitor(); // private RemoteSender remoteSender; // boolean initialized; // // public static FrameSwitcherApplicationService getInstance() { // FrameSwitcherApplicationService service = ServiceManager.getService(FrameSwitcherApplicationService.class); // if (!service.initialized) { // service.initComponent(); // } // return service; // } // // public FrameSwitcherApplicationService() { // } // // public void initComponent() { // long start = System.currentTimeMillis(); // initialized = true; // initRemoting(); // LOG.debug("initComponent done in ", System.currentTimeMillis() - start, "ms"); // } // // private synchronized void initRemoting() { // if (this.settings.isRemoting()) { // if (!(remoteSender instanceof RemoteSenderImpl)) { // try { // UUID uuid = getState().getOrInitializeUuid(); // remoteSender = new RemoteSenderImpl(this, uuid, new Receiver(uuid, this), getState().getPort()); // } catch (Throwable e) { // remoteInstancesState = new RemoteInstancesState(); // remoteSender = new DummyRemoteSender(); // LOG.error(e); // } // } // } else { // if (remoteSender instanceof RemoteSenderImpl) { // remoteSender.dispose(); // } // // if (!(remoteSender instanceof DummyRemoteSender)) { // remoteInstancesState = new RemoteInstancesState(); // remoteSender = new DummyRemoteSender(); // } // } // // } // // public ProjectFocusMonitor getProjectFocusMonitor() { // return projectFocusMonitor; // } // // // @NotNull // @Override // public FrameSwitcherSettings getState() { // return settings; // } // // @Override // public void loadState(FrameSwitcherSettings frameSwitcherSettings) { // this.settings = frameSwitcherSettings; // frameSwitcherSettings.applyMaxRecentProjectsToRegistry(); // } // // public void updateSettings(FrameSwitcherSettings settings) { // this.settings = settings; // this.settings.applyOrResetMaxRecentProjectsToRegistry(); // initRemoting(); // } // // public RemoteInstancesState getRemoteInstancesState() { // return remoteInstancesState; // } // // public RemoteSender getRemoteSender() { // return remoteSender; // } // // @Override // public void dispose() { // long start = System.currentTimeMillis(); // if (getRemoteSender() != null) { // getRemoteSender().dispose(); // } // LOG.debug("disposeComponent done in ", System.currentTimeMillis() - start, "ms"); // } // }
import com.intellij.openapi.diagnostic.Logger; import krasa.frameswitcher.FrameSwitcherApplicationService; import krasa.frameswitcher.networking.dto.*; import java.util.*;
package krasa.frameswitcher.networking; public class RemoteInstancesState { private static final Logger LOG = Logger.getInstance(RemoteInstancesState.class); public static final int TIMEOUT_millis = 10 * 1000; volatile long lastPingSend = 0; public Map<UUID, RemoteIdeInstance> remoteIdeInstances = new HashMap<>(); public synchronized List<RemoteIdeInstance> getRemoteIdeInstances() { List<RemoteIdeInstance> list = new ArrayList<>(this.remoteIdeInstances.values()); list.sort(Comparator.comparing(o -> o.ideName)); return list; } public synchronized void sweepRemoteInstance() { for (Iterator<Map.Entry<UUID, RemoteIdeInstance>> iterator = remoteIdeInstances.entrySet().iterator(); iterator.hasNext(); ) { Map.Entry<UUID, RemoteIdeInstance> entry = iterator.next(); RemoteIdeInstance value = entry.getValue(); if (lastPingSend - value.lastResponse > TIMEOUT_millis) { LOG.debug("Removing " + value); iterator.remove(); } } } public synchronized void processPingResponse(PingResponse object) { RemoteIdeInstance remoteIdeInstance = remoteIdeInstances.get(object.getUuid()); if (remoteIdeInstance != null) { remoteIdeInstance.lastResponse = System.currentTimeMillis(); } else { LOG.warn("DESYNC " + object);
// Path: src/krasa/frameswitcher/FrameSwitcherApplicationService.java // @State(name = "FrameSwitcherSettings", storages = {@Storage("FrameSwitcherSettings.xml")}) // public class FrameSwitcherApplicationService implements PersistentStateComponent<FrameSwitcherSettings>, Disposable { // // private static final Logger LOG = Logger.getInstance(FrameSwitcherApplicationService.class); // // public static final String IDE_MAX_RECENT_PROJECTS = "ide.max.recent.projects"; // // // private FrameSwitcherSettings settings=new FrameSwitcherSettings(); // private RemoteInstancesState remoteInstancesState = new RemoteInstancesState(); // private ProjectFocusMonitor projectFocusMonitor=new ProjectFocusMonitor(); // private RemoteSender remoteSender; // boolean initialized; // // public static FrameSwitcherApplicationService getInstance() { // FrameSwitcherApplicationService service = ServiceManager.getService(FrameSwitcherApplicationService.class); // if (!service.initialized) { // service.initComponent(); // } // return service; // } // // public FrameSwitcherApplicationService() { // } // // public void initComponent() { // long start = System.currentTimeMillis(); // initialized = true; // initRemoting(); // LOG.debug("initComponent done in ", System.currentTimeMillis() - start, "ms"); // } // // private synchronized void initRemoting() { // if (this.settings.isRemoting()) { // if (!(remoteSender instanceof RemoteSenderImpl)) { // try { // UUID uuid = getState().getOrInitializeUuid(); // remoteSender = new RemoteSenderImpl(this, uuid, new Receiver(uuid, this), getState().getPort()); // } catch (Throwable e) { // remoteInstancesState = new RemoteInstancesState(); // remoteSender = new DummyRemoteSender(); // LOG.error(e); // } // } // } else { // if (remoteSender instanceof RemoteSenderImpl) { // remoteSender.dispose(); // } // // if (!(remoteSender instanceof DummyRemoteSender)) { // remoteInstancesState = new RemoteInstancesState(); // remoteSender = new DummyRemoteSender(); // } // } // // } // // public ProjectFocusMonitor getProjectFocusMonitor() { // return projectFocusMonitor; // } // // // @NotNull // @Override // public FrameSwitcherSettings getState() { // return settings; // } // // @Override // public void loadState(FrameSwitcherSettings frameSwitcherSettings) { // this.settings = frameSwitcherSettings; // frameSwitcherSettings.applyMaxRecentProjectsToRegistry(); // } // // public void updateSettings(FrameSwitcherSettings settings) { // this.settings = settings; // this.settings.applyOrResetMaxRecentProjectsToRegistry(); // initRemoting(); // } // // public RemoteInstancesState getRemoteInstancesState() { // return remoteInstancesState; // } // // public RemoteSender getRemoteSender() { // return remoteSender; // } // // @Override // public void dispose() { // long start = System.currentTimeMillis(); // if (getRemoteSender() != null) { // getRemoteSender().dispose(); // } // LOG.debug("disposeComponent done in ", System.currentTimeMillis() - start, "ms"); // } // } // Path: src/krasa/frameswitcher/networking/RemoteInstancesState.java import com.intellij.openapi.diagnostic.Logger; import krasa.frameswitcher.FrameSwitcherApplicationService; import krasa.frameswitcher.networking.dto.*; import java.util.*; package krasa.frameswitcher.networking; public class RemoteInstancesState { private static final Logger LOG = Logger.getInstance(RemoteInstancesState.class); public static final int TIMEOUT_millis = 10 * 1000; volatile long lastPingSend = 0; public Map<UUID, RemoteIdeInstance> remoteIdeInstances = new HashMap<>(); public synchronized List<RemoteIdeInstance> getRemoteIdeInstances() { List<RemoteIdeInstance> list = new ArrayList<>(this.remoteIdeInstances.values()); list.sort(Comparator.comparing(o -> o.ideName)); return list; } public synchronized void sweepRemoteInstance() { for (Iterator<Map.Entry<UUID, RemoteIdeInstance>> iterator = remoteIdeInstances.entrySet().iterator(); iterator.hasNext(); ) { Map.Entry<UUID, RemoteIdeInstance> entry = iterator.next(); RemoteIdeInstance value = entry.getValue(); if (lastPingSend - value.lastResponse > TIMEOUT_millis) { LOG.debug("Removing " + value); iterator.remove(); } } } public synchronized void processPingResponse(PingResponse object) { RemoteIdeInstance remoteIdeInstance = remoteIdeInstances.get(object.getUuid()); if (remoteIdeInstance != null) { remoteIdeInstance.lastResponse = System.currentTimeMillis(); } else { LOG.warn("DESYNC " + object);
FrameSwitcherApplicationService.getInstance().getRemoteSender().asyncSendRefresh();
krasa/FrameSwitcher
src/krasa/frameswitcher/networking/DiagnosticAction.java
// Path: src/krasa/frameswitcher/FrameSwitcherApplicationService.java // @State(name = "FrameSwitcherSettings", storages = {@Storage("FrameSwitcherSettings.xml")}) // public class FrameSwitcherApplicationService implements PersistentStateComponent<FrameSwitcherSettings>, Disposable { // // private static final Logger LOG = Logger.getInstance(FrameSwitcherApplicationService.class); // // public static final String IDE_MAX_RECENT_PROJECTS = "ide.max.recent.projects"; // // // private FrameSwitcherSettings settings=new FrameSwitcherSettings(); // private RemoteInstancesState remoteInstancesState = new RemoteInstancesState(); // private ProjectFocusMonitor projectFocusMonitor=new ProjectFocusMonitor(); // private RemoteSender remoteSender; // boolean initialized; // // public static FrameSwitcherApplicationService getInstance() { // FrameSwitcherApplicationService service = ServiceManager.getService(FrameSwitcherApplicationService.class); // if (!service.initialized) { // service.initComponent(); // } // return service; // } // // public FrameSwitcherApplicationService() { // } // // public void initComponent() { // long start = System.currentTimeMillis(); // initialized = true; // initRemoting(); // LOG.debug("initComponent done in ", System.currentTimeMillis() - start, "ms"); // } // // private synchronized void initRemoting() { // if (this.settings.isRemoting()) { // if (!(remoteSender instanceof RemoteSenderImpl)) { // try { // UUID uuid = getState().getOrInitializeUuid(); // remoteSender = new RemoteSenderImpl(this, uuid, new Receiver(uuid, this), getState().getPort()); // } catch (Throwable e) { // remoteInstancesState = new RemoteInstancesState(); // remoteSender = new DummyRemoteSender(); // LOG.error(e); // } // } // } else { // if (remoteSender instanceof RemoteSenderImpl) { // remoteSender.dispose(); // } // // if (!(remoteSender instanceof DummyRemoteSender)) { // remoteInstancesState = new RemoteInstancesState(); // remoteSender = new DummyRemoteSender(); // } // } // // } // // public ProjectFocusMonitor getProjectFocusMonitor() { // return projectFocusMonitor; // } // // // @NotNull // @Override // public FrameSwitcherSettings getState() { // return settings; // } // // @Override // public void loadState(FrameSwitcherSettings frameSwitcherSettings) { // this.settings = frameSwitcherSettings; // frameSwitcherSettings.applyMaxRecentProjectsToRegistry(); // } // // public void updateSettings(FrameSwitcherSettings settings) { // this.settings = settings; // this.settings.applyOrResetMaxRecentProjectsToRegistry(); // initRemoting(); // } // // public RemoteInstancesState getRemoteInstancesState() { // return remoteInstancesState; // } // // public RemoteSender getRemoteSender() { // return remoteSender; // } // // @Override // public void dispose() { // long start = System.currentTimeMillis(); // if (getRemoteSender() != null) { // getRemoteSender().dispose(); // } // LOG.debug("disposeComponent done in ", System.currentTimeMillis() - start, "ms"); // } // }
import com.intellij.notification.*; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; import krasa.frameswitcher.FrameSwitcherApplicationService;
package krasa.frameswitcher.networking; /** * @author Vojtech Krasa */ public class DiagnosticAction extends AnAction { @Override public void actionPerformed(AnActionEvent e) {
// Path: src/krasa/frameswitcher/FrameSwitcherApplicationService.java // @State(name = "FrameSwitcherSettings", storages = {@Storage("FrameSwitcherSettings.xml")}) // public class FrameSwitcherApplicationService implements PersistentStateComponent<FrameSwitcherSettings>, Disposable { // // private static final Logger LOG = Logger.getInstance(FrameSwitcherApplicationService.class); // // public static final String IDE_MAX_RECENT_PROJECTS = "ide.max.recent.projects"; // // // private FrameSwitcherSettings settings=new FrameSwitcherSettings(); // private RemoteInstancesState remoteInstancesState = new RemoteInstancesState(); // private ProjectFocusMonitor projectFocusMonitor=new ProjectFocusMonitor(); // private RemoteSender remoteSender; // boolean initialized; // // public static FrameSwitcherApplicationService getInstance() { // FrameSwitcherApplicationService service = ServiceManager.getService(FrameSwitcherApplicationService.class); // if (!service.initialized) { // service.initComponent(); // } // return service; // } // // public FrameSwitcherApplicationService() { // } // // public void initComponent() { // long start = System.currentTimeMillis(); // initialized = true; // initRemoting(); // LOG.debug("initComponent done in ", System.currentTimeMillis() - start, "ms"); // } // // private synchronized void initRemoting() { // if (this.settings.isRemoting()) { // if (!(remoteSender instanceof RemoteSenderImpl)) { // try { // UUID uuid = getState().getOrInitializeUuid(); // remoteSender = new RemoteSenderImpl(this, uuid, new Receiver(uuid, this), getState().getPort()); // } catch (Throwable e) { // remoteInstancesState = new RemoteInstancesState(); // remoteSender = new DummyRemoteSender(); // LOG.error(e); // } // } // } else { // if (remoteSender instanceof RemoteSenderImpl) { // remoteSender.dispose(); // } // // if (!(remoteSender instanceof DummyRemoteSender)) { // remoteInstancesState = new RemoteInstancesState(); // remoteSender = new DummyRemoteSender(); // } // } // // } // // public ProjectFocusMonitor getProjectFocusMonitor() { // return projectFocusMonitor; // } // // // @NotNull // @Override // public FrameSwitcherSettings getState() { // return settings; // } // // @Override // public void loadState(FrameSwitcherSettings frameSwitcherSettings) { // this.settings = frameSwitcherSettings; // frameSwitcherSettings.applyMaxRecentProjectsToRegistry(); // } // // public void updateSettings(FrameSwitcherSettings settings) { // this.settings = settings; // this.settings.applyOrResetMaxRecentProjectsToRegistry(); // initRemoting(); // } // // public RemoteInstancesState getRemoteInstancesState() { // return remoteInstancesState; // } // // public RemoteSender getRemoteSender() { // return remoteSender; // } // // @Override // public void dispose() { // long start = System.currentTimeMillis(); // if (getRemoteSender() != null) { // getRemoteSender().dispose(); // } // LOG.debug("disposeComponent done in ", System.currentTimeMillis() - start, "ms"); // } // } // Path: src/krasa/frameswitcher/networking/DiagnosticAction.java import com.intellij.notification.*; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; import krasa.frameswitcher.FrameSwitcherApplicationService; package krasa.frameswitcher.networking; /** * @author Vojtech Krasa */ public class DiagnosticAction extends AnAction { @Override public void actionPerformed(AnActionEvent e) {
final RemoteSender remoteSender1 = FrameSwitcherApplicationService.getInstance().getRemoteSender();
krasa/FrameSwitcher
src/krasa/frameswitcher/FrameSwitcherSettings.java
// Path: src/krasa/frameswitcher/networking/dto/RemoteProject.java // public class RemoteProject implements Serializable { // // private final String name; // private final String projectPath; // // public RemoteProject(String name, String projectPath) { // this.name = name; // this.projectPath = projectPath; // } // // public RemoteProject(Project project) { // this(project.getName(), project.getBasePath()); // } // // public RemoteProject(ReopenProjectAction project) { // this(project.getProjectName(), project.getProjectPath()); // } // // public String getName() { // return name; // } // // public String getProjectPath() { // return projectPath; // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // // RemoteProject that = (RemoteProject) o; // // if (projectPath != null ? !projectPath.equals(that.projectPath) : that.projectPath != null) { // return false; // } // if (name != null ? !name.equals(that.name) : that.name != null) { // return false; // } // // return true; // } // // @Override // public int hashCode() { // int result = name != null ? name.hashCode() : 0; // result = 31 * result + (projectPath != null ? projectPath.hashCode() : 0); // return result; // } // // @Override // public String toString() { // return ReflectionToStringBuilder.toString(this, ToStringStyle.SHORT_PREFIX_STYLE); // } // }
import com.intellij.ide.ReopenProjectAction; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.ui.popup.JBPopupFactory; import com.intellij.openapi.util.registry.Registry; import krasa.frameswitcher.networking.dto.RemoteProject; import org.apache.commons.lang.StringUtils; import java.beans.Transient; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.UUID;
package krasa.frameswitcher; public class FrameSwitcherSettings { private static final Logger LOG = Logger.getInstance(FrameSwitcherSettings.class); private JBPopupFactory.ActionSelectionAid popupSelectionAid = JBPopupFactory.ActionSelectionAid.SPEEDSEARCH; private List<String> recentProjectPaths = new ArrayList<String>(); private List<String> includeLocations = new ArrayList<String>(); private String maxRecentProjects = ""; private String uuid ; private boolean remoting = false; private boolean defaultSelectionCurrentProject = true; private String requestFocusMs = "100"; private boolean selectImmediately = false; private boolean loadProjectIcon = true; private int port=45588; public JBPopupFactory.ActionSelectionAid getPopupSelectionAid() { return popupSelectionAid; }
// Path: src/krasa/frameswitcher/networking/dto/RemoteProject.java // public class RemoteProject implements Serializable { // // private final String name; // private final String projectPath; // // public RemoteProject(String name, String projectPath) { // this.name = name; // this.projectPath = projectPath; // } // // public RemoteProject(Project project) { // this(project.getName(), project.getBasePath()); // } // // public RemoteProject(ReopenProjectAction project) { // this(project.getProjectName(), project.getProjectPath()); // } // // public String getName() { // return name; // } // // public String getProjectPath() { // return projectPath; // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // // RemoteProject that = (RemoteProject) o; // // if (projectPath != null ? !projectPath.equals(that.projectPath) : that.projectPath != null) { // return false; // } // if (name != null ? !name.equals(that.name) : that.name != null) { // return false; // } // // return true; // } // // @Override // public int hashCode() { // int result = name != null ? name.hashCode() : 0; // result = 31 * result + (projectPath != null ? projectPath.hashCode() : 0); // return result; // } // // @Override // public String toString() { // return ReflectionToStringBuilder.toString(this, ToStringStyle.SHORT_PREFIX_STYLE); // } // } // Path: src/krasa/frameswitcher/FrameSwitcherSettings.java import com.intellij.ide.ReopenProjectAction; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.ui.popup.JBPopupFactory; import com.intellij.openapi.util.registry.Registry; import krasa.frameswitcher.networking.dto.RemoteProject; import org.apache.commons.lang.StringUtils; import java.beans.Transient; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.UUID; package krasa.frameswitcher; public class FrameSwitcherSettings { private static final Logger LOG = Logger.getInstance(FrameSwitcherSettings.class); private JBPopupFactory.ActionSelectionAid popupSelectionAid = JBPopupFactory.ActionSelectionAid.SPEEDSEARCH; private List<String> recentProjectPaths = new ArrayList<String>(); private List<String> includeLocations = new ArrayList<String>(); private String maxRecentProjects = ""; private String uuid ; private boolean remoting = false; private boolean defaultSelectionCurrentProject = true; private String requestFocusMs = "100"; private boolean selectImmediately = false; private boolean loadProjectIcon = true; private int port=45588; public JBPopupFactory.ActionSelectionAid getPopupSelectionAid() { return popupSelectionAid; }
public boolean shouldShow(RemoteProject recentProjectsAction) {
krasa/FrameSwitcher
src/krasa/frameswitcher/networking/RemoteSender.java
// Path: src/krasa/frameswitcher/networking/dto/RemoteProject.java // public class RemoteProject implements Serializable { // // private final String name; // private final String projectPath; // // public RemoteProject(String name, String projectPath) { // this.name = name; // this.projectPath = projectPath; // } // // public RemoteProject(Project project) { // this(project.getName(), project.getBasePath()); // } // // public RemoteProject(ReopenProjectAction project) { // this(project.getProjectName(), project.getProjectPath()); // } // // public String getName() { // return name; // } // // public String getProjectPath() { // return projectPath; // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // // RemoteProject that = (RemoteProject) o; // // if (projectPath != null ? !projectPath.equals(that.projectPath) : that.projectPath != null) { // return false; // } // if (name != null ? !name.equals(that.name) : that.name != null) { // return false; // } // // return true; // } // // @Override // public int hashCode() { // int result = name != null ? name.hashCode() : 0; // result = 31 * result + (projectPath != null ? projectPath.hashCode() : 0); // return result; // } // // @Override // public String toString() { // return ReflectionToStringBuilder.toString(this, ToStringStyle.SHORT_PREFIX_STYLE); // } // }
import com.intellij.openapi.project.Project; import krasa.frameswitcher.networking.dto.RemoteProject; import org.jgroups.Message; import java.util.UUID;
package krasa.frameswitcher.networking; /** * @author Vojtech Krasa */ public interface RemoteSender { void sendInstanceStarted(); void sendProjectsState(); void dispose(); void asyncPing(); void asyncProjectOpened(Project project); void sendProjectClosed(Project project);
// Path: src/krasa/frameswitcher/networking/dto/RemoteProject.java // public class RemoteProject implements Serializable { // // private final String name; // private final String projectPath; // // public RemoteProject(String name, String projectPath) { // this.name = name; // this.projectPath = projectPath; // } // // public RemoteProject(Project project) { // this(project.getName(), project.getBasePath()); // } // // public RemoteProject(ReopenProjectAction project) { // this(project.getProjectName(), project.getProjectPath()); // } // // public String getName() { // return name; // } // // public String getProjectPath() { // return projectPath; // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // // RemoteProject that = (RemoteProject) o; // // if (projectPath != null ? !projectPath.equals(that.projectPath) : that.projectPath != null) { // return false; // } // if (name != null ? !name.equals(that.name) : that.name != null) { // return false; // } // // return true; // } // // @Override // public int hashCode() { // int result = name != null ? name.hashCode() : 0; // result = 31 * result + (projectPath != null ? projectPath.hashCode() : 0); // return result; // } // // @Override // public String toString() { // return ReflectionToStringBuilder.toString(this, ToStringStyle.SHORT_PREFIX_STYLE); // } // } // Path: src/krasa/frameswitcher/networking/RemoteSender.java import com.intellij.openapi.project.Project; import krasa.frameswitcher.networking.dto.RemoteProject; import org.jgroups.Message; import java.util.UUID; package krasa.frameswitcher.networking; /** * @author Vojtech Krasa */ public interface RemoteSender { void sendInstanceStarted(); void sendProjectsState(); void dispose(); void asyncPing(); void asyncProjectOpened(Project project); void sendProjectClosed(Project project);
void openProject(UUID target, RemoteProject remoteProject);
dkarv/jdcallgraph
jdcallgraph/src/test/java/com/dkarv/jdcallgraph/util/config/ConfigUtils.java
// Path: jdcallgraph/src/test/java/com/dkarv/jdcallgraph/helper/TestUtils.java // public class TestUtils { // public static File writeFile(final TemporaryFolder tmp, String... content) throws IOException { // File configFile = tmp.newFile(); // PrintWriter out = new PrintWriter(configFile, "UTF-8"); // for (String line : content) { // out.println(line); // } // out.close(); // return configFile; // } // // public static String readFile(final TemporaryFolder tmp, String fileName) throws IOException { // byte[] encoded = Files.readAllBytes(Paths.get(tmp.getRoot().getCanonicalPath(), fileName)); // return new String(encoded, StandardCharsets.UTF_8); // } // // /** // * Clear/Empty a file. // */ // public static void clear(TemporaryFolder tmp, String fileName) throws FileNotFoundException { // (new PrintWriter(new File(tmp.getRoot(), fileName))).close(); // } // // public static InputStream writeInputStream(String content) throws UnsupportedEncodingException { // return new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8.name())); // } // }
import com.dkarv.jdcallgraph.helper.TestUtils; import java.io.IOException; import java.io.InputStream;
package com.dkarv.jdcallgraph.util.config; public class ConfigUtils { public static void replace(boolean addDefaults, String... options) throws IOException { if (addDefaults) { new ConfigReader( ConfigUtils.class.getResourceAsStream("/com/dkarv/jdcallgraph/defaults.ini"), write(options)).read(); } else { new ConfigReader( write(options)).read(); } } public static InputStream write(String... options) throws IOException { StringBuilder str = new StringBuilder(); for (String opt : options) { str.append(opt); str.append('\n'); }
// Path: jdcallgraph/src/test/java/com/dkarv/jdcallgraph/helper/TestUtils.java // public class TestUtils { // public static File writeFile(final TemporaryFolder tmp, String... content) throws IOException { // File configFile = tmp.newFile(); // PrintWriter out = new PrintWriter(configFile, "UTF-8"); // for (String line : content) { // out.println(line); // } // out.close(); // return configFile; // } // // public static String readFile(final TemporaryFolder tmp, String fileName) throws IOException { // byte[] encoded = Files.readAllBytes(Paths.get(tmp.getRoot().getCanonicalPath(), fileName)); // return new String(encoded, StandardCharsets.UTF_8); // } // // /** // * Clear/Empty a file. // */ // public static void clear(TemporaryFolder tmp, String fileName) throws FileNotFoundException { // (new PrintWriter(new File(tmp.getRoot(), fileName))).close(); // } // // public static InputStream writeInputStream(String content) throws UnsupportedEncodingException { // return new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8.name())); // } // } // Path: jdcallgraph/src/test/java/com/dkarv/jdcallgraph/util/config/ConfigUtils.java import com.dkarv.jdcallgraph.helper.TestUtils; import java.io.IOException; import java.io.InputStream; package com.dkarv.jdcallgraph.util.config; public class ConfigUtils { public static void replace(boolean addDefaults, String... options) throws IOException { if (addDefaults) { new ConfigReader( ConfigUtils.class.getResourceAsStream("/com/dkarv/jdcallgraph/defaults.ini"), write(options)).read(); } else { new ConfigReader( write(options)).read(); } } public static InputStream write(String... options) throws IOException { StringBuilder str = new StringBuilder(); for (String opt : options) { str.append(opt); str.append('\n'); }
return TestUtils.writeInputStream(str.toString());
dkarv/jdcallgraph
jdcallgraph/src/main/java/com/dkarv/jdcallgraph/writer/LineNumberFileWriter.java
// Path: jdcallgraph/src/main/java/com/dkarv/jdcallgraph/util/StackItem.java // public class StackItem { // private final String className; // private final String methodName; // private final int lineNumber; // private final boolean returnSafe; // // private final String formatted; // // public StackItem(String className, String methodName, int lineNumber, boolean returnSafe) { // this.className = className; // this.methodName = methodName; // this.lineNumber = lineNumber; // // this.returnSafe = returnSafe; // // this.formatted = Formatter.format(this); // } // // public StackItem(String type, String method, String signature, int lineNumber) { // this(type, method, signature, lineNumber, true); // } // // public StackItem(String type, String method, String signature, int lineNumber, boolean returnSafe) { // this.className = type; // // TODO store them separated // this.methodName = method + signature; // this.lineNumber = lineNumber; // this.returnSafe = returnSafe; // // this.formatted = Formatter.format(this); // } // // public String getClassName() { // return className; // } // // public String getMethodName() { // return methodName; // } // // public int getLineNumber() { // return lineNumber; // } // // @Override // public String toString() { // return formatted; // } // // @Override // public int hashCode() { // return 31 * 31 * className.hashCode() // + 31 * methodName.hashCode() // + lineNumber; // } // // @Override // public boolean equals(Object other) { // if (!(other instanceof StackItem)) { // return false; // } // if (this == other) { // return true; // } // StackItem o = (StackItem) other; // return className.equals(o.className) && // methodName.equals(o.methodName) && // lineNumber == o.lineNumber; // } // // public String getPackageName() { // int indexDot = className.lastIndexOf('.'); // return className.substring(0, indexDot); // } // // public String getShortClassName() { // int indexDot = className.lastIndexOf('.'); // return className.substring(indexDot + 1); // } // // public String getShortMethodName() { // int indexBracket = methodName.indexOf('('); // return methodName.substring(0, indexBracket); // } // // public String getMethodParameters() { // int openBracket = methodName.indexOf('('); // int closingBracket = methodName.indexOf(')'); // return methodName.substring(openBracket + 1, closingBracket); // } // // public boolean isReturnSafe() { // return returnSafe; // } // // public boolean equalTo(StackTraceElement element) { // return element != null // && this.className.equals(element.getClassName()) // && this.getShortMethodName().equals(element.getMethodName()) // // line number comparison does not work because the stack trace number // // is the real line of the call and not beginning of the method // //&& this.lineNumber == element.getLineNumber() // ; // } // }
import com.dkarv.jdcallgraph.util.StackItem; import java.io.IOException; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set;
/* * MIT License * <p> * Copyright (c) 2017 David Krebs * <p> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p> * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * <p> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.dkarv.jdcallgraph.writer; public class LineNumberFileWriter implements GraphWriter { FileWriter writer; @Override public void start(String identifier) throws IOException { if (writer == null) { writer = new FileWriter("lines.csv"); } } @Override
// Path: jdcallgraph/src/main/java/com/dkarv/jdcallgraph/util/StackItem.java // public class StackItem { // private final String className; // private final String methodName; // private final int lineNumber; // private final boolean returnSafe; // // private final String formatted; // // public StackItem(String className, String methodName, int lineNumber, boolean returnSafe) { // this.className = className; // this.methodName = methodName; // this.lineNumber = lineNumber; // // this.returnSafe = returnSafe; // // this.formatted = Formatter.format(this); // } // // public StackItem(String type, String method, String signature, int lineNumber) { // this(type, method, signature, lineNumber, true); // } // // public StackItem(String type, String method, String signature, int lineNumber, boolean returnSafe) { // this.className = type; // // TODO store them separated // this.methodName = method + signature; // this.lineNumber = lineNumber; // this.returnSafe = returnSafe; // // this.formatted = Formatter.format(this); // } // // public String getClassName() { // return className; // } // // public String getMethodName() { // return methodName; // } // // public int getLineNumber() { // return lineNumber; // } // // @Override // public String toString() { // return formatted; // } // // @Override // public int hashCode() { // return 31 * 31 * className.hashCode() // + 31 * methodName.hashCode() // + lineNumber; // } // // @Override // public boolean equals(Object other) { // if (!(other instanceof StackItem)) { // return false; // } // if (this == other) { // return true; // } // StackItem o = (StackItem) other; // return className.equals(o.className) && // methodName.equals(o.methodName) && // lineNumber == o.lineNumber; // } // // public String getPackageName() { // int indexDot = className.lastIndexOf('.'); // return className.substring(0, indexDot); // } // // public String getShortClassName() { // int indexDot = className.lastIndexOf('.'); // return className.substring(indexDot + 1); // } // // public String getShortMethodName() { // int indexBracket = methodName.indexOf('('); // return methodName.substring(0, indexBracket); // } // // public String getMethodParameters() { // int openBracket = methodName.indexOf('('); // int closingBracket = methodName.indexOf(')'); // return methodName.substring(openBracket + 1, closingBracket); // } // // public boolean isReturnSafe() { // return returnSafe; // } // // public boolean equalTo(StackTraceElement element) { // return element != null // && this.className.equals(element.getClassName()) // && this.getShortMethodName().equals(element.getMethodName()) // // line number comparison does not work because the stack trace number // // is the real line of the call and not beginning of the method // //&& this.lineNumber == element.getLineNumber() // ; // } // } // Path: jdcallgraph/src/main/java/com/dkarv/jdcallgraph/writer/LineNumberFileWriter.java import com.dkarv.jdcallgraph.util.StackItem; import java.io.IOException; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; /* * MIT License * <p> * Copyright (c) 2017 David Krebs * <p> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p> * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * <p> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.dkarv.jdcallgraph.writer; public class LineNumberFileWriter implements GraphWriter { FileWriter writer; @Override public void start(String identifier) throws IOException { if (writer == null) { writer = new FileWriter("lines.csv"); } } @Override
public void node(StackItem method) throws IOException {
dkarv/jdcallgraph
jdcallgraph/src/main/java/com/dkarv/jdcallgraph/util/config/ComputedConfig.java
// Path: jdcallgraph/src/main/java/com/dkarv/jdcallgraph/util/options/Target.java // public enum Target { // /** // * Output a test coverage matrix. // */ // MATRIX, // /** // * Output the call graph in dot format. // */ // DOT, // /** // * Coverage csv. // */ // COVERAGE, // /** // * All methods used per entry. // */ // TRACE, // /** // * The line number of each entry (method/test). // */ // LINES, // /** // * Data Dependence graph as dot file. // */ // DD_DOT, // /** // * Data dependence graph as csv. // */ // DD_TRACE; // // public boolean isDataDependency() { // return this == Target.DD_DOT || this == Target.DD_TRACE; // } // }
import com.dkarv.jdcallgraph.util.options.Target;
/* * MIT License * <p> * Copyright (c) 2017 David Krebs * <p> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p> * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * <p> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.dkarv.jdcallgraph.util.config; /** * Some config options that are computed with others. */ public class ComputedConfig { public static boolean dataDependence() {
// Path: jdcallgraph/src/main/java/com/dkarv/jdcallgraph/util/options/Target.java // public enum Target { // /** // * Output a test coverage matrix. // */ // MATRIX, // /** // * Output the call graph in dot format. // */ // DOT, // /** // * Coverage csv. // */ // COVERAGE, // /** // * All methods used per entry. // */ // TRACE, // /** // * The line number of each entry (method/test). // */ // LINES, // /** // * Data Dependence graph as dot file. // */ // DD_DOT, // /** // * Data dependence graph as csv. // */ // DD_TRACE; // // public boolean isDataDependency() { // return this == Target.DD_DOT || this == Target.DD_TRACE; // } // } // Path: jdcallgraph/src/main/java/com/dkarv/jdcallgraph/util/config/ComputedConfig.java import com.dkarv.jdcallgraph.util.options.Target; /* * MIT License * <p> * Copyright (c) 2017 David Krebs * <p> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p> * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * <p> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.dkarv.jdcallgraph.util.config; /** * Some config options that are computed with others. */ public class ComputedConfig { public static boolean dataDependence() {
for (Target t : Config.getInst().writeTo()) {
dkarv/jdcallgraph
jdcallgraph/src/main/java/com/dkarv/jdcallgraph/writer/CsvCoverageFileWriter.java
// Path: jdcallgraph/src/main/java/com/dkarv/jdcallgraph/util/StackItem.java // public class StackItem { // private final String className; // private final String methodName; // private final int lineNumber; // private final boolean returnSafe; // // private final String formatted; // // public StackItem(String className, String methodName, int lineNumber, boolean returnSafe) { // this.className = className; // this.methodName = methodName; // this.lineNumber = lineNumber; // // this.returnSafe = returnSafe; // // this.formatted = Formatter.format(this); // } // // public StackItem(String type, String method, String signature, int lineNumber) { // this(type, method, signature, lineNumber, true); // } // // public StackItem(String type, String method, String signature, int lineNumber, boolean returnSafe) { // this.className = type; // // TODO store them separated // this.methodName = method + signature; // this.lineNumber = lineNumber; // this.returnSafe = returnSafe; // // this.formatted = Formatter.format(this); // } // // public String getClassName() { // return className; // } // // public String getMethodName() { // return methodName; // } // // public int getLineNumber() { // return lineNumber; // } // // @Override // public String toString() { // return formatted; // } // // @Override // public int hashCode() { // return 31 * 31 * className.hashCode() // + 31 * methodName.hashCode() // + lineNumber; // } // // @Override // public boolean equals(Object other) { // if (!(other instanceof StackItem)) { // return false; // } // if (this == other) { // return true; // } // StackItem o = (StackItem) other; // return className.equals(o.className) && // methodName.equals(o.methodName) && // lineNumber == o.lineNumber; // } // // public String getPackageName() { // int indexDot = className.lastIndexOf('.'); // return className.substring(0, indexDot); // } // // public String getShortClassName() { // int indexDot = className.lastIndexOf('.'); // return className.substring(indexDot + 1); // } // // public String getShortMethodName() { // int indexBracket = methodName.indexOf('('); // return methodName.substring(0, indexBracket); // } // // public String getMethodParameters() { // int openBracket = methodName.indexOf('('); // int closingBracket = methodName.indexOf(')'); // return methodName.substring(openBracket + 1, closingBracket); // } // // public boolean isReturnSafe() { // return returnSafe; // } // // public boolean equalTo(StackTraceElement element) { // return element != null // && this.className.equals(element.getClassName()) // && this.getShortMethodName().equals(element.getMethodName()) // // line number comparison does not work because the stack trace number // // is the real line of the call and not beginning of the method // //&& this.lineNumber == element.getLineNumber() // ; // } // }
import com.dkarv.jdcallgraph.util.StackItem; import java.io.IOException; import java.util.*;
/* * MIT License * <p> * Copyright (c) 2017 David Krebs * <p> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p> * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * <p> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.dkarv.jdcallgraph.writer; public class CsvCoverageFileWriter implements GraphWriter { FileWriter writer;
// Path: jdcallgraph/src/main/java/com/dkarv/jdcallgraph/util/StackItem.java // public class StackItem { // private final String className; // private final String methodName; // private final int lineNumber; // private final boolean returnSafe; // // private final String formatted; // // public StackItem(String className, String methodName, int lineNumber, boolean returnSafe) { // this.className = className; // this.methodName = methodName; // this.lineNumber = lineNumber; // // this.returnSafe = returnSafe; // // this.formatted = Formatter.format(this); // } // // public StackItem(String type, String method, String signature, int lineNumber) { // this(type, method, signature, lineNumber, true); // } // // public StackItem(String type, String method, String signature, int lineNumber, boolean returnSafe) { // this.className = type; // // TODO store them separated // this.methodName = method + signature; // this.lineNumber = lineNumber; // this.returnSafe = returnSafe; // // this.formatted = Formatter.format(this); // } // // public String getClassName() { // return className; // } // // public String getMethodName() { // return methodName; // } // // public int getLineNumber() { // return lineNumber; // } // // @Override // public String toString() { // return formatted; // } // // @Override // public int hashCode() { // return 31 * 31 * className.hashCode() // + 31 * methodName.hashCode() // + lineNumber; // } // // @Override // public boolean equals(Object other) { // if (!(other instanceof StackItem)) { // return false; // } // if (this == other) { // return true; // } // StackItem o = (StackItem) other; // return className.equals(o.className) && // methodName.equals(o.methodName) && // lineNumber == o.lineNumber; // } // // public String getPackageName() { // int indexDot = className.lastIndexOf('.'); // return className.substring(0, indexDot); // } // // public String getShortClassName() { // int indexDot = className.lastIndexOf('.'); // return className.substring(indexDot + 1); // } // // public String getShortMethodName() { // int indexBracket = methodName.indexOf('('); // return methodName.substring(0, indexBracket); // } // // public String getMethodParameters() { // int openBracket = methodName.indexOf('('); // int closingBracket = methodName.indexOf(')'); // return methodName.substring(openBracket + 1, closingBracket); // } // // public boolean isReturnSafe() { // return returnSafe; // } // // public boolean equalTo(StackTraceElement element) { // return element != null // && this.className.equals(element.getClassName()) // && this.getShortMethodName().equals(element.getMethodName()) // // line number comparison does not work because the stack trace number // // is the real line of the call and not beginning of the method // //&& this.lineNumber == element.getLineNumber() // ; // } // } // Path: jdcallgraph/src/main/java/com/dkarv/jdcallgraph/writer/CsvCoverageFileWriter.java import com.dkarv.jdcallgraph.util.StackItem; import java.io.IOException; import java.util.*; /* * MIT License * <p> * Copyright (c) 2017 David Krebs * <p> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p> * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * <p> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.dkarv.jdcallgraph.writer; public class CsvCoverageFileWriter implements GraphWriter { FileWriter writer;
private final Map<StackItem, Set<StackItem>> usedIn = new HashMap<>();
dkarv/jdcallgraph
jdcallgraph/src/test/java/com/dkarv/jdcallgraph/util/FormatterTest.java
// Path: jdcallgraph/src/main/java/com/dkarv/jdcallgraph/util/config/Config.java // public abstract class Config { // // static Config instance; // // public static Config getInst() { // return instance; // } // // @Option // public abstract String outDir(); // // @Option // public abstract int logLevel(); // // @Option // public abstract boolean logConsole(); // // @Option // public abstract GroupBy groupBy(); // // @Option // public abstract Target[] writeTo(); // // @Option // public abstract DuplicateDetection duplicateDetection(); // // @Option // public abstract String format(); // // @Option // public abstract boolean javassist(); // // /** // * Check whether everything is set and fix options if necessary. // */ // void check() { // if (!outDir().endsWith(File.separator)) { // // TODO get rid of this by checking each location it is used // throw new IllegalArgumentException("outDir " + outDir() + " does not end with a file separator"); // } // // if (logLevel() < 0 || logLevel() > 6) { // throw new IllegalArgumentException("Invalid log level: " + logLevel()); // } // } // } // // Path: jdcallgraph/src/test/java/com/dkarv/jdcallgraph/util/config/ConfigUtils.java // public class ConfigUtils { // // public static void replace(boolean addDefaults, String... options) throws IOException { // if (addDefaults) { // new ConfigReader( // ConfigUtils.class.getResourceAsStream("/com/dkarv/jdcallgraph/defaults.ini"), // write(options)).read(); // } else { // new ConfigReader( // write(options)).read(); // } // } // // public static InputStream write(String... options) throws IOException { // StringBuilder str = new StringBuilder(); // for (String opt : options) { // str.append(opt); // str.append('\n'); // } // return TestUtils.writeInputStream(str.toString()); // } // // public static void inject(Config config) { // Config.instance = config; // } // } // // Path: jdcallgraph/src/main/java/com/dkarv/jdcallgraph/util/options/Formatter.java // public class Formatter { // private static final Logger LOG = new Logger(Formatter.class); // private static final Pattern P = Pattern.compile("\\{(.+?)}"); // // public static String format(StackItem item) { // Matcher m = P.matcher(Config.getInst().format()); // StringBuffer result = new StringBuffer(); // while (m.find()) { // String replacement = replace(m.group(1), item); // replacement = Matcher.quoteReplacement(replacement); // m.appendReplacement(result, replacement); // } // return result.toString(); // } // // public static String replace(String id, StackItem item) { // switch (id) { // case "package": // return item.getPackageName(); // case "class": // return item.getClassName(); // case "classname": // return item.getShortClassName(); // case "line": // return Integer.toString(item.getLineNumber()); // case "method": // return item.getMethodName(); // case "methodname": // return item.getShortMethodName(); // case "parameters": // return item.getMethodParameters(); // default: // LOG.error("Unknown pattern: {}", id); // // Unknown pattern, return without modification // return '{' + id + '}'; // } // } // }
import com.dkarv.jdcallgraph.util.config.Config; import com.dkarv.jdcallgraph.util.config.ConfigUtils; import com.dkarv.jdcallgraph.util.options.Formatter; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito;
package com.dkarv.jdcallgraph.util; public class FormatterTest { private String METHOD = "method"; private String PARAMETERS = "int,String,int"; private String PACKAGE = "abc.def"; private String CLASS = "Example"; private int LINE = 111; private StackItem item;
// Path: jdcallgraph/src/main/java/com/dkarv/jdcallgraph/util/config/Config.java // public abstract class Config { // // static Config instance; // // public static Config getInst() { // return instance; // } // // @Option // public abstract String outDir(); // // @Option // public abstract int logLevel(); // // @Option // public abstract boolean logConsole(); // // @Option // public abstract GroupBy groupBy(); // // @Option // public abstract Target[] writeTo(); // // @Option // public abstract DuplicateDetection duplicateDetection(); // // @Option // public abstract String format(); // // @Option // public abstract boolean javassist(); // // /** // * Check whether everything is set and fix options if necessary. // */ // void check() { // if (!outDir().endsWith(File.separator)) { // // TODO get rid of this by checking each location it is used // throw new IllegalArgumentException("outDir " + outDir() + " does not end with a file separator"); // } // // if (logLevel() < 0 || logLevel() > 6) { // throw new IllegalArgumentException("Invalid log level: " + logLevel()); // } // } // } // // Path: jdcallgraph/src/test/java/com/dkarv/jdcallgraph/util/config/ConfigUtils.java // public class ConfigUtils { // // public static void replace(boolean addDefaults, String... options) throws IOException { // if (addDefaults) { // new ConfigReader( // ConfigUtils.class.getResourceAsStream("/com/dkarv/jdcallgraph/defaults.ini"), // write(options)).read(); // } else { // new ConfigReader( // write(options)).read(); // } // } // // public static InputStream write(String... options) throws IOException { // StringBuilder str = new StringBuilder(); // for (String opt : options) { // str.append(opt); // str.append('\n'); // } // return TestUtils.writeInputStream(str.toString()); // } // // public static void inject(Config config) { // Config.instance = config; // } // } // // Path: jdcallgraph/src/main/java/com/dkarv/jdcallgraph/util/options/Formatter.java // public class Formatter { // private static final Logger LOG = new Logger(Formatter.class); // private static final Pattern P = Pattern.compile("\\{(.+?)}"); // // public static String format(StackItem item) { // Matcher m = P.matcher(Config.getInst().format()); // StringBuffer result = new StringBuffer(); // while (m.find()) { // String replacement = replace(m.group(1), item); // replacement = Matcher.quoteReplacement(replacement); // m.appendReplacement(result, replacement); // } // return result.toString(); // } // // public static String replace(String id, StackItem item) { // switch (id) { // case "package": // return item.getPackageName(); // case "class": // return item.getClassName(); // case "classname": // return item.getShortClassName(); // case "line": // return Integer.toString(item.getLineNumber()); // case "method": // return item.getMethodName(); // case "methodname": // return item.getShortMethodName(); // case "parameters": // return item.getMethodParameters(); // default: // LOG.error("Unknown pattern: {}", id); // // Unknown pattern, return without modification // return '{' + id + '}'; // } // } // } // Path: jdcallgraph/src/test/java/com/dkarv/jdcallgraph/util/FormatterTest.java import com.dkarv.jdcallgraph.util.config.Config; import com.dkarv.jdcallgraph.util.config.ConfigUtils; import com.dkarv.jdcallgraph.util.options.Formatter; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; package com.dkarv.jdcallgraph.util; public class FormatterTest { private String METHOD = "method"; private String PARAMETERS = "int,String,int"; private String PACKAGE = "abc.def"; private String CLASS = "Example"; private int LINE = 111; private StackItem item;
private Config config;
dkarv/jdcallgraph
jdcallgraph/src/test/java/com/dkarv/jdcallgraph/util/FormatterTest.java
// Path: jdcallgraph/src/main/java/com/dkarv/jdcallgraph/util/config/Config.java // public abstract class Config { // // static Config instance; // // public static Config getInst() { // return instance; // } // // @Option // public abstract String outDir(); // // @Option // public abstract int logLevel(); // // @Option // public abstract boolean logConsole(); // // @Option // public abstract GroupBy groupBy(); // // @Option // public abstract Target[] writeTo(); // // @Option // public abstract DuplicateDetection duplicateDetection(); // // @Option // public abstract String format(); // // @Option // public abstract boolean javassist(); // // /** // * Check whether everything is set and fix options if necessary. // */ // void check() { // if (!outDir().endsWith(File.separator)) { // // TODO get rid of this by checking each location it is used // throw new IllegalArgumentException("outDir " + outDir() + " does not end with a file separator"); // } // // if (logLevel() < 0 || logLevel() > 6) { // throw new IllegalArgumentException("Invalid log level: " + logLevel()); // } // } // } // // Path: jdcallgraph/src/test/java/com/dkarv/jdcallgraph/util/config/ConfigUtils.java // public class ConfigUtils { // // public static void replace(boolean addDefaults, String... options) throws IOException { // if (addDefaults) { // new ConfigReader( // ConfigUtils.class.getResourceAsStream("/com/dkarv/jdcallgraph/defaults.ini"), // write(options)).read(); // } else { // new ConfigReader( // write(options)).read(); // } // } // // public static InputStream write(String... options) throws IOException { // StringBuilder str = new StringBuilder(); // for (String opt : options) { // str.append(opt); // str.append('\n'); // } // return TestUtils.writeInputStream(str.toString()); // } // // public static void inject(Config config) { // Config.instance = config; // } // } // // Path: jdcallgraph/src/main/java/com/dkarv/jdcallgraph/util/options/Formatter.java // public class Formatter { // private static final Logger LOG = new Logger(Formatter.class); // private static final Pattern P = Pattern.compile("\\{(.+?)}"); // // public static String format(StackItem item) { // Matcher m = P.matcher(Config.getInst().format()); // StringBuffer result = new StringBuffer(); // while (m.find()) { // String replacement = replace(m.group(1), item); // replacement = Matcher.quoteReplacement(replacement); // m.appendReplacement(result, replacement); // } // return result.toString(); // } // // public static String replace(String id, StackItem item) { // switch (id) { // case "package": // return item.getPackageName(); // case "class": // return item.getClassName(); // case "classname": // return item.getShortClassName(); // case "line": // return Integer.toString(item.getLineNumber()); // case "method": // return item.getMethodName(); // case "methodname": // return item.getShortMethodName(); // case "parameters": // return item.getMethodParameters(); // default: // LOG.error("Unknown pattern: {}", id); // // Unknown pattern, return without modification // return '{' + id + '}'; // } // } // }
import com.dkarv.jdcallgraph.util.config.Config; import com.dkarv.jdcallgraph.util.config.ConfigUtils; import com.dkarv.jdcallgraph.util.options.Formatter; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito;
package com.dkarv.jdcallgraph.util; public class FormatterTest { private String METHOD = "method"; private String PARAMETERS = "int,String,int"; private String PACKAGE = "abc.def"; private String CLASS = "Example"; private int LINE = 111; private StackItem item; private Config config; @Before public void mock() { item = Mockito.mock(StackItem.class); Mockito.when(item.getMethodName()).thenReturn(METHOD + "(" + PARAMETERS + ")"); Mockito.when(item.getMethodParameters()).thenReturn(PARAMETERS); Mockito.when(item.getShortMethodName()).thenReturn(METHOD); Mockito.when(item.getClassName()).thenReturn(PACKAGE + "." + CLASS); Mockito.when(item.getPackageName()).thenReturn(PACKAGE); Mockito.when(item.getShortClassName()).thenReturn(CLASS); Mockito.when(item.getLineNumber()).thenReturn(LINE); config = Mockito.mock(Config.class);
// Path: jdcallgraph/src/main/java/com/dkarv/jdcallgraph/util/config/Config.java // public abstract class Config { // // static Config instance; // // public static Config getInst() { // return instance; // } // // @Option // public abstract String outDir(); // // @Option // public abstract int logLevel(); // // @Option // public abstract boolean logConsole(); // // @Option // public abstract GroupBy groupBy(); // // @Option // public abstract Target[] writeTo(); // // @Option // public abstract DuplicateDetection duplicateDetection(); // // @Option // public abstract String format(); // // @Option // public abstract boolean javassist(); // // /** // * Check whether everything is set and fix options if necessary. // */ // void check() { // if (!outDir().endsWith(File.separator)) { // // TODO get rid of this by checking each location it is used // throw new IllegalArgumentException("outDir " + outDir() + " does not end with a file separator"); // } // // if (logLevel() < 0 || logLevel() > 6) { // throw new IllegalArgumentException("Invalid log level: " + logLevel()); // } // } // } // // Path: jdcallgraph/src/test/java/com/dkarv/jdcallgraph/util/config/ConfigUtils.java // public class ConfigUtils { // // public static void replace(boolean addDefaults, String... options) throws IOException { // if (addDefaults) { // new ConfigReader( // ConfigUtils.class.getResourceAsStream("/com/dkarv/jdcallgraph/defaults.ini"), // write(options)).read(); // } else { // new ConfigReader( // write(options)).read(); // } // } // // public static InputStream write(String... options) throws IOException { // StringBuilder str = new StringBuilder(); // for (String opt : options) { // str.append(opt); // str.append('\n'); // } // return TestUtils.writeInputStream(str.toString()); // } // // public static void inject(Config config) { // Config.instance = config; // } // } // // Path: jdcallgraph/src/main/java/com/dkarv/jdcallgraph/util/options/Formatter.java // public class Formatter { // private static final Logger LOG = new Logger(Formatter.class); // private static final Pattern P = Pattern.compile("\\{(.+?)}"); // // public static String format(StackItem item) { // Matcher m = P.matcher(Config.getInst().format()); // StringBuffer result = new StringBuffer(); // while (m.find()) { // String replacement = replace(m.group(1), item); // replacement = Matcher.quoteReplacement(replacement); // m.appendReplacement(result, replacement); // } // return result.toString(); // } // // public static String replace(String id, StackItem item) { // switch (id) { // case "package": // return item.getPackageName(); // case "class": // return item.getClassName(); // case "classname": // return item.getShortClassName(); // case "line": // return Integer.toString(item.getLineNumber()); // case "method": // return item.getMethodName(); // case "methodname": // return item.getShortMethodName(); // case "parameters": // return item.getMethodParameters(); // default: // LOG.error("Unknown pattern: {}", id); // // Unknown pattern, return without modification // return '{' + id + '}'; // } // } // } // Path: jdcallgraph/src/test/java/com/dkarv/jdcallgraph/util/FormatterTest.java import com.dkarv.jdcallgraph.util.config.Config; import com.dkarv.jdcallgraph.util.config.ConfigUtils; import com.dkarv.jdcallgraph.util.options.Formatter; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; package com.dkarv.jdcallgraph.util; public class FormatterTest { private String METHOD = "method"; private String PARAMETERS = "int,String,int"; private String PACKAGE = "abc.def"; private String CLASS = "Example"; private int LINE = 111; private StackItem item; private Config config; @Before public void mock() { item = Mockito.mock(StackItem.class); Mockito.when(item.getMethodName()).thenReturn(METHOD + "(" + PARAMETERS + ")"); Mockito.when(item.getMethodParameters()).thenReturn(PARAMETERS); Mockito.when(item.getShortMethodName()).thenReturn(METHOD); Mockito.when(item.getClassName()).thenReturn(PACKAGE + "." + CLASS); Mockito.when(item.getPackageName()).thenReturn(PACKAGE); Mockito.when(item.getShortClassName()).thenReturn(CLASS); Mockito.when(item.getLineNumber()).thenReturn(LINE); config = Mockito.mock(Config.class);
ConfigUtils.inject(config);
dkarv/jdcallgraph
jdcallgraph/src/test/java/com/dkarv/jdcallgraph/util/FormatterTest.java
// Path: jdcallgraph/src/main/java/com/dkarv/jdcallgraph/util/config/Config.java // public abstract class Config { // // static Config instance; // // public static Config getInst() { // return instance; // } // // @Option // public abstract String outDir(); // // @Option // public abstract int logLevel(); // // @Option // public abstract boolean logConsole(); // // @Option // public abstract GroupBy groupBy(); // // @Option // public abstract Target[] writeTo(); // // @Option // public abstract DuplicateDetection duplicateDetection(); // // @Option // public abstract String format(); // // @Option // public abstract boolean javassist(); // // /** // * Check whether everything is set and fix options if necessary. // */ // void check() { // if (!outDir().endsWith(File.separator)) { // // TODO get rid of this by checking each location it is used // throw new IllegalArgumentException("outDir " + outDir() + " does not end with a file separator"); // } // // if (logLevel() < 0 || logLevel() > 6) { // throw new IllegalArgumentException("Invalid log level: " + logLevel()); // } // } // } // // Path: jdcallgraph/src/test/java/com/dkarv/jdcallgraph/util/config/ConfigUtils.java // public class ConfigUtils { // // public static void replace(boolean addDefaults, String... options) throws IOException { // if (addDefaults) { // new ConfigReader( // ConfigUtils.class.getResourceAsStream("/com/dkarv/jdcallgraph/defaults.ini"), // write(options)).read(); // } else { // new ConfigReader( // write(options)).read(); // } // } // // public static InputStream write(String... options) throws IOException { // StringBuilder str = new StringBuilder(); // for (String opt : options) { // str.append(opt); // str.append('\n'); // } // return TestUtils.writeInputStream(str.toString()); // } // // public static void inject(Config config) { // Config.instance = config; // } // } // // Path: jdcallgraph/src/main/java/com/dkarv/jdcallgraph/util/options/Formatter.java // public class Formatter { // private static final Logger LOG = new Logger(Formatter.class); // private static final Pattern P = Pattern.compile("\\{(.+?)}"); // // public static String format(StackItem item) { // Matcher m = P.matcher(Config.getInst().format()); // StringBuffer result = new StringBuffer(); // while (m.find()) { // String replacement = replace(m.group(1), item); // replacement = Matcher.quoteReplacement(replacement); // m.appendReplacement(result, replacement); // } // return result.toString(); // } // // public static String replace(String id, StackItem item) { // switch (id) { // case "package": // return item.getPackageName(); // case "class": // return item.getClassName(); // case "classname": // return item.getShortClassName(); // case "line": // return Integer.toString(item.getLineNumber()); // case "method": // return item.getMethodName(); // case "methodname": // return item.getShortMethodName(); // case "parameters": // return item.getMethodParameters(); // default: // LOG.error("Unknown pattern: {}", id); // // Unknown pattern, return without modification // return '{' + id + '}'; // } // } // }
import com.dkarv.jdcallgraph.util.config.Config; import com.dkarv.jdcallgraph.util.config.ConfigUtils; import com.dkarv.jdcallgraph.util.options.Formatter; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito;
package com.dkarv.jdcallgraph.util; public class FormatterTest { private String METHOD = "method"; private String PARAMETERS = "int,String,int"; private String PACKAGE = "abc.def"; private String CLASS = "Example"; private int LINE = 111; private StackItem item; private Config config; @Before public void mock() { item = Mockito.mock(StackItem.class); Mockito.when(item.getMethodName()).thenReturn(METHOD + "(" + PARAMETERS + ")"); Mockito.when(item.getMethodParameters()).thenReturn(PARAMETERS); Mockito.when(item.getShortMethodName()).thenReturn(METHOD); Mockito.when(item.getClassName()).thenReturn(PACKAGE + "." + CLASS); Mockito.when(item.getPackageName()).thenReturn(PACKAGE); Mockito.when(item.getShortClassName()).thenReturn(CLASS); Mockito.when(item.getLineNumber()).thenReturn(LINE); config = Mockito.mock(Config.class); ConfigUtils.inject(config); } @Test public void test() { Mockito.when(config.format()).thenReturn("{method}");
// Path: jdcallgraph/src/main/java/com/dkarv/jdcallgraph/util/config/Config.java // public abstract class Config { // // static Config instance; // // public static Config getInst() { // return instance; // } // // @Option // public abstract String outDir(); // // @Option // public abstract int logLevel(); // // @Option // public abstract boolean logConsole(); // // @Option // public abstract GroupBy groupBy(); // // @Option // public abstract Target[] writeTo(); // // @Option // public abstract DuplicateDetection duplicateDetection(); // // @Option // public abstract String format(); // // @Option // public abstract boolean javassist(); // // /** // * Check whether everything is set and fix options if necessary. // */ // void check() { // if (!outDir().endsWith(File.separator)) { // // TODO get rid of this by checking each location it is used // throw new IllegalArgumentException("outDir " + outDir() + " does not end with a file separator"); // } // // if (logLevel() < 0 || logLevel() > 6) { // throw new IllegalArgumentException("Invalid log level: " + logLevel()); // } // } // } // // Path: jdcallgraph/src/test/java/com/dkarv/jdcallgraph/util/config/ConfigUtils.java // public class ConfigUtils { // // public static void replace(boolean addDefaults, String... options) throws IOException { // if (addDefaults) { // new ConfigReader( // ConfigUtils.class.getResourceAsStream("/com/dkarv/jdcallgraph/defaults.ini"), // write(options)).read(); // } else { // new ConfigReader( // write(options)).read(); // } // } // // public static InputStream write(String... options) throws IOException { // StringBuilder str = new StringBuilder(); // for (String opt : options) { // str.append(opt); // str.append('\n'); // } // return TestUtils.writeInputStream(str.toString()); // } // // public static void inject(Config config) { // Config.instance = config; // } // } // // Path: jdcallgraph/src/main/java/com/dkarv/jdcallgraph/util/options/Formatter.java // public class Formatter { // private static final Logger LOG = new Logger(Formatter.class); // private static final Pattern P = Pattern.compile("\\{(.+?)}"); // // public static String format(StackItem item) { // Matcher m = P.matcher(Config.getInst().format()); // StringBuffer result = new StringBuffer(); // while (m.find()) { // String replacement = replace(m.group(1), item); // replacement = Matcher.quoteReplacement(replacement); // m.appendReplacement(result, replacement); // } // return result.toString(); // } // // public static String replace(String id, StackItem item) { // switch (id) { // case "package": // return item.getPackageName(); // case "class": // return item.getClassName(); // case "classname": // return item.getShortClassName(); // case "line": // return Integer.toString(item.getLineNumber()); // case "method": // return item.getMethodName(); // case "methodname": // return item.getShortMethodName(); // case "parameters": // return item.getMethodParameters(); // default: // LOG.error("Unknown pattern: {}", id); // // Unknown pattern, return without modification // return '{' + id + '}'; // } // } // } // Path: jdcallgraph/src/test/java/com/dkarv/jdcallgraph/util/FormatterTest.java import com.dkarv.jdcallgraph.util.config.Config; import com.dkarv.jdcallgraph.util.config.ConfigUtils; import com.dkarv.jdcallgraph.util.options.Formatter; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; package com.dkarv.jdcallgraph.util; public class FormatterTest { private String METHOD = "method"; private String PARAMETERS = "int,String,int"; private String PACKAGE = "abc.def"; private String CLASS = "Example"; private int LINE = 111; private StackItem item; private Config config; @Before public void mock() { item = Mockito.mock(StackItem.class); Mockito.when(item.getMethodName()).thenReturn(METHOD + "(" + PARAMETERS + ")"); Mockito.when(item.getMethodParameters()).thenReturn(PARAMETERS); Mockito.when(item.getShortMethodName()).thenReturn(METHOD); Mockito.when(item.getClassName()).thenReturn(PACKAGE + "." + CLASS); Mockito.when(item.getPackageName()).thenReturn(PACKAGE); Mockito.when(item.getShortClassName()).thenReturn(CLASS); Mockito.when(item.getLineNumber()).thenReturn(LINE); config = Mockito.mock(Config.class); ConfigUtils.inject(config); } @Test public void test() { Mockito.when(config.format()).thenReturn("{method}");
Assert.assertEquals(METHOD + "(" + PARAMETERS + ")", Formatter.format(item));
dkarv/jdcallgraph
jdcallgraph/src/main/java/com/dkarv/jdcallgraph/util/StackItem.java
// Path: jdcallgraph/src/main/java/com/dkarv/jdcallgraph/util/options/Formatter.java // public class Formatter { // private static final Logger LOG = new Logger(Formatter.class); // private static final Pattern P = Pattern.compile("\\{(.+?)}"); // // public static String format(StackItem item) { // Matcher m = P.matcher(Config.getInst().format()); // StringBuffer result = new StringBuffer(); // while (m.find()) { // String replacement = replace(m.group(1), item); // replacement = Matcher.quoteReplacement(replacement); // m.appendReplacement(result, replacement); // } // return result.toString(); // } // // public static String replace(String id, StackItem item) { // switch (id) { // case "package": // return item.getPackageName(); // case "class": // return item.getClassName(); // case "classname": // return item.getShortClassName(); // case "line": // return Integer.toString(item.getLineNumber()); // case "method": // return item.getMethodName(); // case "methodname": // return item.getShortMethodName(); // case "parameters": // return item.getMethodParameters(); // default: // LOG.error("Unknown pattern: {}", id); // // Unknown pattern, return without modification // return '{' + id + '}'; // } // } // }
import com.dkarv.jdcallgraph.util.options.Formatter;
/* * MIT License * <p> * Copyright (c) 2017 David Krebs * <p> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p> * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * <p> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.dkarv.jdcallgraph.util; public class StackItem { private final String className; private final String methodName; private final int lineNumber; private final boolean returnSafe; private final String formatted; public StackItem(String className, String methodName, int lineNumber, boolean returnSafe) { this.className = className; this.methodName = methodName; this.lineNumber = lineNumber; this.returnSafe = returnSafe;
// Path: jdcallgraph/src/main/java/com/dkarv/jdcallgraph/util/options/Formatter.java // public class Formatter { // private static final Logger LOG = new Logger(Formatter.class); // private static final Pattern P = Pattern.compile("\\{(.+?)}"); // // public static String format(StackItem item) { // Matcher m = P.matcher(Config.getInst().format()); // StringBuffer result = new StringBuffer(); // while (m.find()) { // String replacement = replace(m.group(1), item); // replacement = Matcher.quoteReplacement(replacement); // m.appendReplacement(result, replacement); // } // return result.toString(); // } // // public static String replace(String id, StackItem item) { // switch (id) { // case "package": // return item.getPackageName(); // case "class": // return item.getClassName(); // case "classname": // return item.getShortClassName(); // case "line": // return Integer.toString(item.getLineNumber()); // case "method": // return item.getMethodName(); // case "methodname": // return item.getShortMethodName(); // case "parameters": // return item.getMethodParameters(); // default: // LOG.error("Unknown pattern: {}", id); // // Unknown pattern, return without modification // return '{' + id + '}'; // } // } // } // Path: jdcallgraph/src/main/java/com/dkarv/jdcallgraph/util/StackItem.java import com.dkarv.jdcallgraph.util.options.Formatter; /* * MIT License * <p> * Copyright (c) 2017 David Krebs * <p> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p> * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * <p> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.dkarv.jdcallgraph.util; public class StackItem { private final String className; private final String methodName; private final int lineNumber; private final boolean returnSafe; private final String formatted; public StackItem(String className, String methodName, int lineNumber, boolean returnSafe) { this.className = className; this.methodName = methodName; this.lineNumber = lineNumber; this.returnSafe = returnSafe;
this.formatted = Formatter.format(this);
dkarv/jdcallgraph
jdcallgraph/src/main/java/com/dkarv/jdcallgraph/writer/CsvMatrixFileWriter.java
// Path: jdcallgraph/src/main/java/com/dkarv/jdcallgraph/util/StackItem.java // public class StackItem { // private final String className; // private final String methodName; // private final int lineNumber; // private final boolean returnSafe; // // private final String formatted; // // public StackItem(String className, String methodName, int lineNumber, boolean returnSafe) { // this.className = className; // this.methodName = methodName; // this.lineNumber = lineNumber; // // this.returnSafe = returnSafe; // // this.formatted = Formatter.format(this); // } // // public StackItem(String type, String method, String signature, int lineNumber) { // this(type, method, signature, lineNumber, true); // } // // public StackItem(String type, String method, String signature, int lineNumber, boolean returnSafe) { // this.className = type; // // TODO store them separated // this.methodName = method + signature; // this.lineNumber = lineNumber; // this.returnSafe = returnSafe; // // this.formatted = Formatter.format(this); // } // // public String getClassName() { // return className; // } // // public String getMethodName() { // return methodName; // } // // public int getLineNumber() { // return lineNumber; // } // // @Override // public String toString() { // return formatted; // } // // @Override // public int hashCode() { // return 31 * 31 * className.hashCode() // + 31 * methodName.hashCode() // + lineNumber; // } // // @Override // public boolean equals(Object other) { // if (!(other instanceof StackItem)) { // return false; // } // if (this == other) { // return true; // } // StackItem o = (StackItem) other; // return className.equals(o.className) && // methodName.equals(o.methodName) && // lineNumber == o.lineNumber; // } // // public String getPackageName() { // int indexDot = className.lastIndexOf('.'); // return className.substring(0, indexDot); // } // // public String getShortClassName() { // int indexDot = className.lastIndexOf('.'); // return className.substring(indexDot + 1); // } // // public String getShortMethodName() { // int indexBracket = methodName.indexOf('('); // return methodName.substring(0, indexBracket); // } // // public String getMethodParameters() { // int openBracket = methodName.indexOf('('); // int closingBracket = methodName.indexOf(')'); // return methodName.substring(openBracket + 1, closingBracket); // } // // public boolean isReturnSafe() { // return returnSafe; // } // // public boolean equalTo(StackTraceElement element) { // return element != null // && this.className.equals(element.getClassName()) // && this.getShortMethodName().equals(element.getMethodName()) // // line number comparison does not work because the stack trace number // // is the real line of the call and not beginning of the method // //&& this.lineNumber == element.getLineNumber() // ; // } // }
import com.dkarv.jdcallgraph.util.StackItem; import java.io.IOException; import java.util.*;
/* * MIT License * <p> * Copyright (c) 2017 David Krebs * <p> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p> * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * <p> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.dkarv.jdcallgraph.writer; public class CsvMatrixFileWriter implements GraphWriter { FileWriter writer;
// Path: jdcallgraph/src/main/java/com/dkarv/jdcallgraph/util/StackItem.java // public class StackItem { // private final String className; // private final String methodName; // private final int lineNumber; // private final boolean returnSafe; // // private final String formatted; // // public StackItem(String className, String methodName, int lineNumber, boolean returnSafe) { // this.className = className; // this.methodName = methodName; // this.lineNumber = lineNumber; // // this.returnSafe = returnSafe; // // this.formatted = Formatter.format(this); // } // // public StackItem(String type, String method, String signature, int lineNumber) { // this(type, method, signature, lineNumber, true); // } // // public StackItem(String type, String method, String signature, int lineNumber, boolean returnSafe) { // this.className = type; // // TODO store them separated // this.methodName = method + signature; // this.lineNumber = lineNumber; // this.returnSafe = returnSafe; // // this.formatted = Formatter.format(this); // } // // public String getClassName() { // return className; // } // // public String getMethodName() { // return methodName; // } // // public int getLineNumber() { // return lineNumber; // } // // @Override // public String toString() { // return formatted; // } // // @Override // public int hashCode() { // return 31 * 31 * className.hashCode() // + 31 * methodName.hashCode() // + lineNumber; // } // // @Override // public boolean equals(Object other) { // if (!(other instanceof StackItem)) { // return false; // } // if (this == other) { // return true; // } // StackItem o = (StackItem) other; // return className.equals(o.className) && // methodName.equals(o.methodName) && // lineNumber == o.lineNumber; // } // // public String getPackageName() { // int indexDot = className.lastIndexOf('.'); // return className.substring(0, indexDot); // } // // public String getShortClassName() { // int indexDot = className.lastIndexOf('.'); // return className.substring(indexDot + 1); // } // // public String getShortMethodName() { // int indexBracket = methodName.indexOf('('); // return methodName.substring(0, indexBracket); // } // // public String getMethodParameters() { // int openBracket = methodName.indexOf('('); // int closingBracket = methodName.indexOf(')'); // return methodName.substring(openBracket + 1, closingBracket); // } // // public boolean isReturnSafe() { // return returnSafe; // } // // public boolean equalTo(StackTraceElement element) { // return element != null // && this.className.equals(element.getClassName()) // && this.getShortMethodName().equals(element.getMethodName()) // // line number comparison does not work because the stack trace number // // is the real line of the call and not beginning of the method // //&& this.lineNumber == element.getLineNumber() // ; // } // } // Path: jdcallgraph/src/main/java/com/dkarv/jdcallgraph/writer/CsvMatrixFileWriter.java import com.dkarv.jdcallgraph.util.StackItem; import java.io.IOException; import java.util.*; /* * MIT License * <p> * Copyright (c) 2017 David Krebs * <p> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p> * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * <p> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.dkarv.jdcallgraph.writer; public class CsvMatrixFileWriter implements GraphWriter { FileWriter writer;
private final Map<StackItem, Integer> indexes = new HashMap<>();
dkarv/jdcallgraph
jdcallgraph/src/test/java/com/dkarv/jdcallgraph/instr/EnhanceClassTest.java
// Path: jdcallgraph/src/main/java/com/dkarv/jdcallgraph/instr/JavassistInstr.java // public class JavassistInstr extends Instr implements ClassFileTransformer { // private final static Logger LOG = new Logger(JavassistInstr.class); // // private final FieldTracer fieldTracer; // // private final boolean callDependence; // // public JavassistInstr(List<Pattern> excludes) { // super(excludes); // if (ComputedConfig.dataDependence()) { // fieldTracer = new FieldTracer(); // } else { // fieldTracer = null; // } // this.callDependence = ComputedConfig.callDependence(); // } // // /** // * Program entry point. Loads the config and starts itself as instrumentation. // * // * @param instrumentation instrumentation // */ // public void instrument(Instrumentation instrumentation) { // instrumentation.addTransformer(this); // } // // public byte[] transform(ClassLoader loader, String className, Class clazz, // ProtectionDomain domain, byte[] bytes) { // boolean enhanceClass = true; // // String name = className.replace("/", "."); // // for (Pattern p : excludes) { // Matcher m = p.matcher(name); // if (m.matches()) { // // LOG.trace("Skipping class {}", name); // enhanceClass = false; // break; // } // } // // if (enhanceClass) { // byte[] b = enhanceClass(bytes); // if (b != null) return b; // } // return bytes; // } // // CtClass makeClass(ClassPool pool, byte[] bytes) throws IOException { // return pool.makeClass(new ByteArrayInputStream(bytes)); // } // // byte[] enhanceClass(byte[] bytes) { // CtClass clazz = null; // try { // boolean ignore = false; // clazz = makeClass(ClassPool.getDefault(), bytes); // // CtClass[] interfaces = clazz.getInterfaces(); // for (CtClass i : interfaces) { // // ignore Mockito classes because modifying them results in errors // ignore = ignore || "org.mockito.cglib.proxy.Factory".equals(i.getName()); // } // ignore = ignore || clazz.isInterface(); // if (!ignore) { // LOG.trace("Enhancing class: {}", clazz.getName()); // CtBehavior[] methods = clazz.getDeclaredBehaviors(); // for (CtBehavior method : methods) { // enhanceMethod(method, clazz.getName()); // } // return clazz.toBytecode(); // } else { // LOG.trace("Ignore class {}", clazz.getName()); // } // } catch (CannotCompileException e) { // LOG.error("Cannot compile", e); // } catch (NotFoundException e) { // LOG.error("Cannot find", e); // } catch (IOException e) { // LOG.error("IO error", e); // } finally { // if (clazz != null) { // clazz.detach(); // } // } // // return null; // } // // void enhanceMethod(CtBehavior method, String className) // throws NotFoundException, CannotCompileException { // String mName = getMethodName(method); // LOG.trace("Enhancing {}", mName); // // if (fieldTracer != null) { // method.instrument(fieldTracer); // } // // if (callDependence) { // int lineNumber = getLineNumber(method); // // String args = '"' + className + '"' + ',' + '"' + mName + '"' + ',' + lineNumber; // // boolean returnSafe = !(method instanceof CtConstructor); // String srcBefore = "com.dkarv.jdcallgraph.CallRecorder.beforeMethod(" + args + "," + // returnSafe + ");"; // String srcAfter = "com.dkarv.jdcallgraph.CallRecorder.afterMethod(" + args + "," + // returnSafe + ");"; // // method.insertBefore(srcBefore); // method.insertAfter(srcAfter, true); // } // } // // public static int getLineNumber(CtBehavior method) { // return method.getMethodInfo().getLineNumber(0); // } // // public static String getMethodName(CtBehavior method) throws NotFoundException { // StringBuilder sb = new StringBuilder(); // if (method instanceof CtConstructor) { // sb.append("<init>"); // } else { // sb.append(method.getName()); // } // sb.append(Descriptor.toString(method.getSignature())); // return sb.toString(); // } // // static String getShortName(final CtClass clazz) { // return getShortName(clazz.getName()); // } // // static String getShortName(final String className) { // return className.substring(className.lastIndexOf('.') + 1, className.length()); // } // }
import com.dkarv.jdcallgraph.instr.JavassistInstr; import javassist.*; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import java.io.IOException; import java.util.ArrayList; import java.util.regex.Pattern;
package com.dkarv.jdcallgraph.instr; public class EnhanceClassTest { byte[] input = new byte[]{1, 2, 3, 4, 5}; byte[] output = new byte[]{5, 4, 3, 2, 1}; CtClass ct; CtClass interf;
// Path: jdcallgraph/src/main/java/com/dkarv/jdcallgraph/instr/JavassistInstr.java // public class JavassistInstr extends Instr implements ClassFileTransformer { // private final static Logger LOG = new Logger(JavassistInstr.class); // // private final FieldTracer fieldTracer; // // private final boolean callDependence; // // public JavassistInstr(List<Pattern> excludes) { // super(excludes); // if (ComputedConfig.dataDependence()) { // fieldTracer = new FieldTracer(); // } else { // fieldTracer = null; // } // this.callDependence = ComputedConfig.callDependence(); // } // // /** // * Program entry point. Loads the config and starts itself as instrumentation. // * // * @param instrumentation instrumentation // */ // public void instrument(Instrumentation instrumentation) { // instrumentation.addTransformer(this); // } // // public byte[] transform(ClassLoader loader, String className, Class clazz, // ProtectionDomain domain, byte[] bytes) { // boolean enhanceClass = true; // // String name = className.replace("/", "."); // // for (Pattern p : excludes) { // Matcher m = p.matcher(name); // if (m.matches()) { // // LOG.trace("Skipping class {}", name); // enhanceClass = false; // break; // } // } // // if (enhanceClass) { // byte[] b = enhanceClass(bytes); // if (b != null) return b; // } // return bytes; // } // // CtClass makeClass(ClassPool pool, byte[] bytes) throws IOException { // return pool.makeClass(new ByteArrayInputStream(bytes)); // } // // byte[] enhanceClass(byte[] bytes) { // CtClass clazz = null; // try { // boolean ignore = false; // clazz = makeClass(ClassPool.getDefault(), bytes); // // CtClass[] interfaces = clazz.getInterfaces(); // for (CtClass i : interfaces) { // // ignore Mockito classes because modifying them results in errors // ignore = ignore || "org.mockito.cglib.proxy.Factory".equals(i.getName()); // } // ignore = ignore || clazz.isInterface(); // if (!ignore) { // LOG.trace("Enhancing class: {}", clazz.getName()); // CtBehavior[] methods = clazz.getDeclaredBehaviors(); // for (CtBehavior method : methods) { // enhanceMethod(method, clazz.getName()); // } // return clazz.toBytecode(); // } else { // LOG.trace("Ignore class {}", clazz.getName()); // } // } catch (CannotCompileException e) { // LOG.error("Cannot compile", e); // } catch (NotFoundException e) { // LOG.error("Cannot find", e); // } catch (IOException e) { // LOG.error("IO error", e); // } finally { // if (clazz != null) { // clazz.detach(); // } // } // // return null; // } // // void enhanceMethod(CtBehavior method, String className) // throws NotFoundException, CannotCompileException { // String mName = getMethodName(method); // LOG.trace("Enhancing {}", mName); // // if (fieldTracer != null) { // method.instrument(fieldTracer); // } // // if (callDependence) { // int lineNumber = getLineNumber(method); // // String args = '"' + className + '"' + ',' + '"' + mName + '"' + ',' + lineNumber; // // boolean returnSafe = !(method instanceof CtConstructor); // String srcBefore = "com.dkarv.jdcallgraph.CallRecorder.beforeMethod(" + args + "," + // returnSafe + ");"; // String srcAfter = "com.dkarv.jdcallgraph.CallRecorder.afterMethod(" + args + "," + // returnSafe + ");"; // // method.insertBefore(srcBefore); // method.insertAfter(srcAfter, true); // } // } // // public static int getLineNumber(CtBehavior method) { // return method.getMethodInfo().getLineNumber(0); // } // // public static String getMethodName(CtBehavior method) throws NotFoundException { // StringBuilder sb = new StringBuilder(); // if (method instanceof CtConstructor) { // sb.append("<init>"); // } else { // sb.append(method.getName()); // } // sb.append(Descriptor.toString(method.getSignature())); // return sb.toString(); // } // // static String getShortName(final CtClass clazz) { // return getShortName(clazz.getName()); // } // // static String getShortName(final String className) { // return className.substring(className.lastIndexOf('.') + 1, className.length()); // } // } // Path: jdcallgraph/src/test/java/com/dkarv/jdcallgraph/instr/EnhanceClassTest.java import com.dkarv.jdcallgraph.instr.JavassistInstr; import javassist.*; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import java.io.IOException; import java.util.ArrayList; import java.util.regex.Pattern; package com.dkarv.jdcallgraph.instr; public class EnhanceClassTest { byte[] input = new byte[]{1, 2, 3, 4, 5}; byte[] output = new byte[]{5, 4, 3, 2, 1}; CtClass ct; CtClass interf;
JavassistInstr p;
dkarv/jdcallgraph
jdcallgraph/src/test/java/com/dkarv/jdcallgraph/util/config/ConfigTest.java
// Path: jdcallgraph/src/main/java/com/dkarv/jdcallgraph/util/options/GroupBy.java // public enum GroupBy { // ENTRY, THREAD // // } // // Path: jdcallgraph/src/main/java/com/dkarv/jdcallgraph/util/options/Target.java // public enum Target { // /** // * Output a test coverage matrix. // */ // MATRIX, // /** // * Output the call graph in dot format. // */ // DOT, // /** // * Coverage csv. // */ // COVERAGE, // /** // * All methods used per entry. // */ // TRACE, // /** // * The line number of each entry (method/test). // */ // LINES, // /** // * Data Dependence graph as dot file. // */ // DD_DOT, // /** // * Data dependence graph as csv. // */ // DD_TRACE; // // public boolean isDataDependency() { // return this == Target.DD_DOT || this == Target.DD_TRACE; // } // }
import com.dkarv.jdcallgraph.util.options.GroupBy; import com.dkarv.jdcallgraph.util.options.Target; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import java.io.IOException;
@Test public void testLogLevel() throws IOException { ConfigUtils.replace(true, "logLevel: 4"); Assert.assertEquals(4, Config.getInst().logLevel()); try { ConfigUtils.replace(true, "logLevel: -1"); Assert.fail("Did not detect negative log level"); } catch (IllegalArgumentException e) { } try { ConfigUtils.replace(true, "logLevel: 7"); Assert.fail("Did not detect too high loglevel"); } catch (IllegalArgumentException e) { } } @Test public void testLogConsole() throws IOException { ConfigUtils.replace(true, "logConsole: true"); Assert.assertEquals(true, Config.getInst().logConsole()); ConfigUtils.replace(true, "logConsole: false"); Assert.assertEquals(false, Config.getInst().logConsole()); } @Test public void testWriteTo() throws IOException {
// Path: jdcallgraph/src/main/java/com/dkarv/jdcallgraph/util/options/GroupBy.java // public enum GroupBy { // ENTRY, THREAD // // } // // Path: jdcallgraph/src/main/java/com/dkarv/jdcallgraph/util/options/Target.java // public enum Target { // /** // * Output a test coverage matrix. // */ // MATRIX, // /** // * Output the call graph in dot format. // */ // DOT, // /** // * Coverage csv. // */ // COVERAGE, // /** // * All methods used per entry. // */ // TRACE, // /** // * The line number of each entry (method/test). // */ // LINES, // /** // * Data Dependence graph as dot file. // */ // DD_DOT, // /** // * Data dependence graph as csv. // */ // DD_TRACE; // // public boolean isDataDependency() { // return this == Target.DD_DOT || this == Target.DD_TRACE; // } // } // Path: jdcallgraph/src/test/java/com/dkarv/jdcallgraph/util/config/ConfigTest.java import com.dkarv.jdcallgraph.util.options.GroupBy; import com.dkarv.jdcallgraph.util.options.Target; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import java.io.IOException; @Test public void testLogLevel() throws IOException { ConfigUtils.replace(true, "logLevel: 4"); Assert.assertEquals(4, Config.getInst().logLevel()); try { ConfigUtils.replace(true, "logLevel: -1"); Assert.fail("Did not detect negative log level"); } catch (IllegalArgumentException e) { } try { ConfigUtils.replace(true, "logLevel: 7"); Assert.fail("Did not detect too high loglevel"); } catch (IllegalArgumentException e) { } } @Test public void testLogConsole() throws IOException { ConfigUtils.replace(true, "logConsole: true"); Assert.assertEquals(true, Config.getInst().logConsole()); ConfigUtils.replace(true, "logConsole: false"); Assert.assertEquals(false, Config.getInst().logConsole()); } @Test public void testWriteTo() throws IOException {
for (Target t : Target.values()) {
dkarv/jdcallgraph
jdcallgraph/src/test/java/com/dkarv/jdcallgraph/util/config/ConfigTest.java
// Path: jdcallgraph/src/main/java/com/dkarv/jdcallgraph/util/options/GroupBy.java // public enum GroupBy { // ENTRY, THREAD // // } // // Path: jdcallgraph/src/main/java/com/dkarv/jdcallgraph/util/options/Target.java // public enum Target { // /** // * Output a test coverage matrix. // */ // MATRIX, // /** // * Output the call graph in dot format. // */ // DOT, // /** // * Coverage csv. // */ // COVERAGE, // /** // * All methods used per entry. // */ // TRACE, // /** // * The line number of each entry (method/test). // */ // LINES, // /** // * Data Dependence graph as dot file. // */ // DD_DOT, // /** // * Data dependence graph as csv. // */ // DD_TRACE; // // public boolean isDataDependency() { // return this == Target.DD_DOT || this == Target.DD_TRACE; // } // }
import com.dkarv.jdcallgraph.util.options.GroupBy; import com.dkarv.jdcallgraph.util.options.Target; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import java.io.IOException;
try { ConfigUtils.replace(true, "logLevel: 7"); Assert.fail("Did not detect too high loglevel"); } catch (IllegalArgumentException e) { } } @Test public void testLogConsole() throws IOException { ConfigUtils.replace(true, "logConsole: true"); Assert.assertEquals(true, Config.getInst().logConsole()); ConfigUtils.replace(true, "logConsole: false"); Assert.assertEquals(false, Config.getInst().logConsole()); } @Test public void testWriteTo() throws IOException { for (Target t : Target.values()) { ConfigUtils.replace(true, "writeTo: " + t.name()); Assert.assertEquals(t, Config.getInst().writeTo()[0]); } ConfigUtils.replace(true, "writeTo: " + Target.DOT + "," + Target.MATRIX); } @Test public void testGroupBy() throws IOException {
// Path: jdcallgraph/src/main/java/com/dkarv/jdcallgraph/util/options/GroupBy.java // public enum GroupBy { // ENTRY, THREAD // // } // // Path: jdcallgraph/src/main/java/com/dkarv/jdcallgraph/util/options/Target.java // public enum Target { // /** // * Output a test coverage matrix. // */ // MATRIX, // /** // * Output the call graph in dot format. // */ // DOT, // /** // * Coverage csv. // */ // COVERAGE, // /** // * All methods used per entry. // */ // TRACE, // /** // * The line number of each entry (method/test). // */ // LINES, // /** // * Data Dependence graph as dot file. // */ // DD_DOT, // /** // * Data dependence graph as csv. // */ // DD_TRACE; // // public boolean isDataDependency() { // return this == Target.DD_DOT || this == Target.DD_TRACE; // } // } // Path: jdcallgraph/src/test/java/com/dkarv/jdcallgraph/util/config/ConfigTest.java import com.dkarv.jdcallgraph.util.options.GroupBy; import com.dkarv.jdcallgraph.util.options.Target; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import java.io.IOException; try { ConfigUtils.replace(true, "logLevel: 7"); Assert.fail("Did not detect too high loglevel"); } catch (IllegalArgumentException e) { } } @Test public void testLogConsole() throws IOException { ConfigUtils.replace(true, "logConsole: true"); Assert.assertEquals(true, Config.getInst().logConsole()); ConfigUtils.replace(true, "logConsole: false"); Assert.assertEquals(false, Config.getInst().logConsole()); } @Test public void testWriteTo() throws IOException { for (Target t : Target.values()) { ConfigUtils.replace(true, "writeTo: " + t.name()); Assert.assertEquals(t, Config.getInst().writeTo()[0]); } ConfigUtils.replace(true, "writeTo: " + Target.DOT + "," + Target.MATRIX); } @Test public void testGroupBy() throws IOException {
for (GroupBy g : GroupBy.values()) {
dkarv/jdcallgraph
jdcallgraph/src/main/java/com/dkarv/jdcallgraph/util/config/Config.java
// Path: jdcallgraph/src/main/java/com/dkarv/jdcallgraph/util/options/DuplicateDetection.java // public enum DuplicateDetection { // /** // * Skip duplicate detection. // */ // OFF, // /** // * Simple detection that only remembers the last N edges. // * This removes local duplicates that happen after each other. // */ // SIMPLE, // /** // * Full detection: remove all duplicate edges and nodes. // */ // FULL // // } // // Path: jdcallgraph/src/main/java/com/dkarv/jdcallgraph/util/options/GroupBy.java // public enum GroupBy { // ENTRY, THREAD // // } // // Path: jdcallgraph/src/main/java/com/dkarv/jdcallgraph/util/options/Target.java // public enum Target { // /** // * Output a test coverage matrix. // */ // MATRIX, // /** // * Output the call graph in dot format. // */ // DOT, // /** // * Coverage csv. // */ // COVERAGE, // /** // * All methods used per entry. // */ // TRACE, // /** // * The line number of each entry (method/test). // */ // LINES, // /** // * Data Dependence graph as dot file. // */ // DD_DOT, // /** // * Data dependence graph as csv. // */ // DD_TRACE; // // public boolean isDataDependency() { // return this == Target.DD_DOT || this == Target.DD_TRACE; // } // }
import com.dkarv.jdcallgraph.util.options.DuplicateDetection; import com.dkarv.jdcallgraph.util.options.GroupBy; import com.dkarv.jdcallgraph.util.options.Target; import java.io.File;
/* * MIT License * <p> * Copyright (c) 2017 David Krebs * <p> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p> * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * <p> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.dkarv.jdcallgraph.util.config; public abstract class Config { static Config instance; public static Config getInst() { return instance; } @Option public abstract String outDir(); @Option public abstract int logLevel(); @Option public abstract boolean logConsole(); @Option
// Path: jdcallgraph/src/main/java/com/dkarv/jdcallgraph/util/options/DuplicateDetection.java // public enum DuplicateDetection { // /** // * Skip duplicate detection. // */ // OFF, // /** // * Simple detection that only remembers the last N edges. // * This removes local duplicates that happen after each other. // */ // SIMPLE, // /** // * Full detection: remove all duplicate edges and nodes. // */ // FULL // // } // // Path: jdcallgraph/src/main/java/com/dkarv/jdcallgraph/util/options/GroupBy.java // public enum GroupBy { // ENTRY, THREAD // // } // // Path: jdcallgraph/src/main/java/com/dkarv/jdcallgraph/util/options/Target.java // public enum Target { // /** // * Output a test coverage matrix. // */ // MATRIX, // /** // * Output the call graph in dot format. // */ // DOT, // /** // * Coverage csv. // */ // COVERAGE, // /** // * All methods used per entry. // */ // TRACE, // /** // * The line number of each entry (method/test). // */ // LINES, // /** // * Data Dependence graph as dot file. // */ // DD_DOT, // /** // * Data dependence graph as csv. // */ // DD_TRACE; // // public boolean isDataDependency() { // return this == Target.DD_DOT || this == Target.DD_TRACE; // } // } // Path: jdcallgraph/src/main/java/com/dkarv/jdcallgraph/util/config/Config.java import com.dkarv.jdcallgraph.util.options.DuplicateDetection; import com.dkarv.jdcallgraph.util.options.GroupBy; import com.dkarv.jdcallgraph.util.options.Target; import java.io.File; /* * MIT License * <p> * Copyright (c) 2017 David Krebs * <p> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p> * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * <p> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.dkarv.jdcallgraph.util.config; public abstract class Config { static Config instance; public static Config getInst() { return instance; } @Option public abstract String outDir(); @Option public abstract int logLevel(); @Option public abstract boolean logConsole(); @Option
public abstract GroupBy groupBy();
dkarv/jdcallgraph
jdcallgraph/src/main/java/com/dkarv/jdcallgraph/util/config/Config.java
// Path: jdcallgraph/src/main/java/com/dkarv/jdcallgraph/util/options/DuplicateDetection.java // public enum DuplicateDetection { // /** // * Skip duplicate detection. // */ // OFF, // /** // * Simple detection that only remembers the last N edges. // * This removes local duplicates that happen after each other. // */ // SIMPLE, // /** // * Full detection: remove all duplicate edges and nodes. // */ // FULL // // } // // Path: jdcallgraph/src/main/java/com/dkarv/jdcallgraph/util/options/GroupBy.java // public enum GroupBy { // ENTRY, THREAD // // } // // Path: jdcallgraph/src/main/java/com/dkarv/jdcallgraph/util/options/Target.java // public enum Target { // /** // * Output a test coverage matrix. // */ // MATRIX, // /** // * Output the call graph in dot format. // */ // DOT, // /** // * Coverage csv. // */ // COVERAGE, // /** // * All methods used per entry. // */ // TRACE, // /** // * The line number of each entry (method/test). // */ // LINES, // /** // * Data Dependence graph as dot file. // */ // DD_DOT, // /** // * Data dependence graph as csv. // */ // DD_TRACE; // // public boolean isDataDependency() { // return this == Target.DD_DOT || this == Target.DD_TRACE; // } // }
import com.dkarv.jdcallgraph.util.options.DuplicateDetection; import com.dkarv.jdcallgraph.util.options.GroupBy; import com.dkarv.jdcallgraph.util.options.Target; import java.io.File;
/* * MIT License * <p> * Copyright (c) 2017 David Krebs * <p> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p> * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * <p> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.dkarv.jdcallgraph.util.config; public abstract class Config { static Config instance; public static Config getInst() { return instance; } @Option public abstract String outDir(); @Option public abstract int logLevel(); @Option public abstract boolean logConsole(); @Option public abstract GroupBy groupBy(); @Option
// Path: jdcallgraph/src/main/java/com/dkarv/jdcallgraph/util/options/DuplicateDetection.java // public enum DuplicateDetection { // /** // * Skip duplicate detection. // */ // OFF, // /** // * Simple detection that only remembers the last N edges. // * This removes local duplicates that happen after each other. // */ // SIMPLE, // /** // * Full detection: remove all duplicate edges and nodes. // */ // FULL // // } // // Path: jdcallgraph/src/main/java/com/dkarv/jdcallgraph/util/options/GroupBy.java // public enum GroupBy { // ENTRY, THREAD // // } // // Path: jdcallgraph/src/main/java/com/dkarv/jdcallgraph/util/options/Target.java // public enum Target { // /** // * Output a test coverage matrix. // */ // MATRIX, // /** // * Output the call graph in dot format. // */ // DOT, // /** // * Coverage csv. // */ // COVERAGE, // /** // * All methods used per entry. // */ // TRACE, // /** // * The line number of each entry (method/test). // */ // LINES, // /** // * Data Dependence graph as dot file. // */ // DD_DOT, // /** // * Data dependence graph as csv. // */ // DD_TRACE; // // public boolean isDataDependency() { // return this == Target.DD_DOT || this == Target.DD_TRACE; // } // } // Path: jdcallgraph/src/main/java/com/dkarv/jdcallgraph/util/config/Config.java import com.dkarv.jdcallgraph.util.options.DuplicateDetection; import com.dkarv.jdcallgraph.util.options.GroupBy; import com.dkarv.jdcallgraph.util.options.Target; import java.io.File; /* * MIT License * <p> * Copyright (c) 2017 David Krebs * <p> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p> * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * <p> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.dkarv.jdcallgraph.util.config; public abstract class Config { static Config instance; public static Config getInst() { return instance; } @Option public abstract String outDir(); @Option public abstract int logLevel(); @Option public abstract boolean logConsole(); @Option public abstract GroupBy groupBy(); @Option
public abstract Target[] writeTo();
dkarv/jdcallgraph
jdcallgraph/src/main/java/com/dkarv/jdcallgraph/util/config/Config.java
// Path: jdcallgraph/src/main/java/com/dkarv/jdcallgraph/util/options/DuplicateDetection.java // public enum DuplicateDetection { // /** // * Skip duplicate detection. // */ // OFF, // /** // * Simple detection that only remembers the last N edges. // * This removes local duplicates that happen after each other. // */ // SIMPLE, // /** // * Full detection: remove all duplicate edges and nodes. // */ // FULL // // } // // Path: jdcallgraph/src/main/java/com/dkarv/jdcallgraph/util/options/GroupBy.java // public enum GroupBy { // ENTRY, THREAD // // } // // Path: jdcallgraph/src/main/java/com/dkarv/jdcallgraph/util/options/Target.java // public enum Target { // /** // * Output a test coverage matrix. // */ // MATRIX, // /** // * Output the call graph in dot format. // */ // DOT, // /** // * Coverage csv. // */ // COVERAGE, // /** // * All methods used per entry. // */ // TRACE, // /** // * The line number of each entry (method/test). // */ // LINES, // /** // * Data Dependence graph as dot file. // */ // DD_DOT, // /** // * Data dependence graph as csv. // */ // DD_TRACE; // // public boolean isDataDependency() { // return this == Target.DD_DOT || this == Target.DD_TRACE; // } // }
import com.dkarv.jdcallgraph.util.options.DuplicateDetection; import com.dkarv.jdcallgraph.util.options.GroupBy; import com.dkarv.jdcallgraph.util.options.Target; import java.io.File;
/* * MIT License * <p> * Copyright (c) 2017 David Krebs * <p> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p> * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * <p> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.dkarv.jdcallgraph.util.config; public abstract class Config { static Config instance; public static Config getInst() { return instance; } @Option public abstract String outDir(); @Option public abstract int logLevel(); @Option public abstract boolean logConsole(); @Option public abstract GroupBy groupBy(); @Option public abstract Target[] writeTo(); @Option
// Path: jdcallgraph/src/main/java/com/dkarv/jdcallgraph/util/options/DuplicateDetection.java // public enum DuplicateDetection { // /** // * Skip duplicate detection. // */ // OFF, // /** // * Simple detection that only remembers the last N edges. // * This removes local duplicates that happen after each other. // */ // SIMPLE, // /** // * Full detection: remove all duplicate edges and nodes. // */ // FULL // // } // // Path: jdcallgraph/src/main/java/com/dkarv/jdcallgraph/util/options/GroupBy.java // public enum GroupBy { // ENTRY, THREAD // // } // // Path: jdcallgraph/src/main/java/com/dkarv/jdcallgraph/util/options/Target.java // public enum Target { // /** // * Output a test coverage matrix. // */ // MATRIX, // /** // * Output the call graph in dot format. // */ // DOT, // /** // * Coverage csv. // */ // COVERAGE, // /** // * All methods used per entry. // */ // TRACE, // /** // * The line number of each entry (method/test). // */ // LINES, // /** // * Data Dependence graph as dot file. // */ // DD_DOT, // /** // * Data dependence graph as csv. // */ // DD_TRACE; // // public boolean isDataDependency() { // return this == Target.DD_DOT || this == Target.DD_TRACE; // } // } // Path: jdcallgraph/src/main/java/com/dkarv/jdcallgraph/util/config/Config.java import com.dkarv.jdcallgraph.util.options.DuplicateDetection; import com.dkarv.jdcallgraph.util.options.GroupBy; import com.dkarv.jdcallgraph.util.options.Target; import java.io.File; /* * MIT License * <p> * Copyright (c) 2017 David Krebs * <p> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p> * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * <p> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.dkarv.jdcallgraph.util.config; public abstract class Config { static Config instance; public static Config getInst() { return instance; } @Option public abstract String outDir(); @Option public abstract int logLevel(); @Option public abstract boolean logConsole(); @Option public abstract GroupBy groupBy(); @Option public abstract Target[] writeTo(); @Option
public abstract DuplicateDetection duplicateDetection();
dkarv/jdcallgraph
jdcallgraph/src/test/java/com/dkarv/jdcallgraph/util/log/LoggerTest.java
// Path: jdcallgraph/src/test/java/com/dkarv/jdcallgraph/helper/Console.java // public class Console { // private final PrintStream err; // private final PrintStream out; // private final ByteArrayOutputStream outContent; // private final ByteArrayOutputStream errContent; // // public Console() { // err = System.err; // out = System.out; // outContent = new ByteArrayOutputStream(); // errContent = new ByteArrayOutputStream(); // } // // public void startCapture() throws UnsupportedEncodingException { // System.setOut(new PrintStream(outContent, true, "UTF-8")); // System.setErr(new PrintStream(errContent, true, "UTF-8")); // } // // public void clear() { // outContent.reset(); // errContent.reset(); // } // // public void reset() { // System.setOut(out); // System.setErr(err); // } // // public String getOut() throws UnsupportedEncodingException { // return outContent.toString("UTF-8"); // } // // public String getErr() throws UnsupportedEncodingException { // return errContent.toString("UTF-8"); // } // } // // Path: jdcallgraph/src/test/java/com/dkarv/jdcallgraph/util/config/ConfigUtils.java // public class ConfigUtils { // // public static void replace(boolean addDefaults, String... options) throws IOException { // if (addDefaults) { // new ConfigReader( // ConfigUtils.class.getResourceAsStream("/com/dkarv/jdcallgraph/defaults.ini"), // write(options)).read(); // } else { // new ConfigReader( // write(options)).read(); // } // } // // public static InputStream write(String... options) throws IOException { // StringBuilder str = new StringBuilder(); // for (String opt : options) { // str.append(opt); // str.append('\n'); // } // return TestUtils.writeInputStream(str.toString()); // } // // public static void inject(Config config) { // Config.instance = config; // } // }
import com.dkarv.jdcallgraph.helper.Console; import com.dkarv.jdcallgraph.util.config.ConfigUtils; import org.hamcrest.text.MatchesPattern; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.mockito.Mockito; import java.io.IOException; import java.util.regex.Pattern; import static org.junit.Assert.*;
package com.dkarv.jdcallgraph.util.log; public class LoggerTest { @Rule public TemporaryFolder tmp = new TemporaryFolder(); private Logger init(int logLevel, boolean stdOut) { try {
// Path: jdcallgraph/src/test/java/com/dkarv/jdcallgraph/helper/Console.java // public class Console { // private final PrintStream err; // private final PrintStream out; // private final ByteArrayOutputStream outContent; // private final ByteArrayOutputStream errContent; // // public Console() { // err = System.err; // out = System.out; // outContent = new ByteArrayOutputStream(); // errContent = new ByteArrayOutputStream(); // } // // public void startCapture() throws UnsupportedEncodingException { // System.setOut(new PrintStream(outContent, true, "UTF-8")); // System.setErr(new PrintStream(errContent, true, "UTF-8")); // } // // public void clear() { // outContent.reset(); // errContent.reset(); // } // // public void reset() { // System.setOut(out); // System.setErr(err); // } // // public String getOut() throws UnsupportedEncodingException { // return outContent.toString("UTF-8"); // } // // public String getErr() throws UnsupportedEncodingException { // return errContent.toString("UTF-8"); // } // } // // Path: jdcallgraph/src/test/java/com/dkarv/jdcallgraph/util/config/ConfigUtils.java // public class ConfigUtils { // // public static void replace(boolean addDefaults, String... options) throws IOException { // if (addDefaults) { // new ConfigReader( // ConfigUtils.class.getResourceAsStream("/com/dkarv/jdcallgraph/defaults.ini"), // write(options)).read(); // } else { // new ConfigReader( // write(options)).read(); // } // } // // public static InputStream write(String... options) throws IOException { // StringBuilder str = new StringBuilder(); // for (String opt : options) { // str.append(opt); // str.append('\n'); // } // return TestUtils.writeInputStream(str.toString()); // } // // public static void inject(Config config) { // Config.instance = config; // } // } // Path: jdcallgraph/src/test/java/com/dkarv/jdcallgraph/util/log/LoggerTest.java import com.dkarv.jdcallgraph.helper.Console; import com.dkarv.jdcallgraph.util.config.ConfigUtils; import org.hamcrest.text.MatchesPattern; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.mockito.Mockito; import java.io.IOException; import java.util.regex.Pattern; import static org.junit.Assert.*; package com.dkarv.jdcallgraph.util.log; public class LoggerTest { @Rule public TemporaryFolder tmp = new TemporaryFolder(); private Logger init(int logLevel, boolean stdOut) { try {
ConfigUtils.replace( true, "logLevel: " + logLevel, "logConsole: " + stdOut);
dkarv/jdcallgraph
jdcallgraph/src/test/java/com/dkarv/jdcallgraph/util/log/LoggerTest.java
// Path: jdcallgraph/src/test/java/com/dkarv/jdcallgraph/helper/Console.java // public class Console { // private final PrintStream err; // private final PrintStream out; // private final ByteArrayOutputStream outContent; // private final ByteArrayOutputStream errContent; // // public Console() { // err = System.err; // out = System.out; // outContent = new ByteArrayOutputStream(); // errContent = new ByteArrayOutputStream(); // } // // public void startCapture() throws UnsupportedEncodingException { // System.setOut(new PrintStream(outContent, true, "UTF-8")); // System.setErr(new PrintStream(errContent, true, "UTF-8")); // } // // public void clear() { // outContent.reset(); // errContent.reset(); // } // // public void reset() { // System.setOut(out); // System.setErr(err); // } // // public String getOut() throws UnsupportedEncodingException { // return outContent.toString("UTF-8"); // } // // public String getErr() throws UnsupportedEncodingException { // return errContent.toString("UTF-8"); // } // } // // Path: jdcallgraph/src/test/java/com/dkarv/jdcallgraph/util/config/ConfigUtils.java // public class ConfigUtils { // // public static void replace(boolean addDefaults, String... options) throws IOException { // if (addDefaults) { // new ConfigReader( // ConfigUtils.class.getResourceAsStream("/com/dkarv/jdcallgraph/defaults.ini"), // write(options)).read(); // } else { // new ConfigReader( // write(options)).read(); // } // } // // public static InputStream write(String... options) throws IOException { // StringBuilder str = new StringBuilder(); // for (String opt : options) { // str.append(opt); // str.append('\n'); // } // return TestUtils.writeInputStream(str.toString()); // } // // public static void inject(Config config) { // Config.instance = config; // } // }
import com.dkarv.jdcallgraph.helper.Console; import com.dkarv.jdcallgraph.util.config.ConfigUtils; import org.hamcrest.text.MatchesPattern; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.mockito.Mockito; import java.io.IOException; import java.util.regex.Pattern; import static org.junit.Assert.*;
arg = null; logger.debug("test {}", arg); Mockito.verify(target).print(Mockito.matches("\\[.*] \\[DEBUG] \\[LoggerTest] test null\n"), Mockito.eq(5)); } @Test public void testWrongArgumentCount() { Logger logger = init(6, false); try { logger.debug("test {}", "123", "456"); fail("Should notice too less {}"); } catch (IllegalArgumentException e) { } try { logger.debug("test {} {}"); fail("Should notice missing arguments"); } catch (IllegalArgumentException e) { } } @Test public void testTargetError() throws IOException { Logger logger = init(6, false); Logger.TARGETS.clear(); LogTarget target = Mockito.mock(LogTarget.class); Mockito.doThrow(new IOException("error")).when(target).print(Mockito.anyString(), Mockito.anyInt()); Logger.TARGETS.add(target);
// Path: jdcallgraph/src/test/java/com/dkarv/jdcallgraph/helper/Console.java // public class Console { // private final PrintStream err; // private final PrintStream out; // private final ByteArrayOutputStream outContent; // private final ByteArrayOutputStream errContent; // // public Console() { // err = System.err; // out = System.out; // outContent = new ByteArrayOutputStream(); // errContent = new ByteArrayOutputStream(); // } // // public void startCapture() throws UnsupportedEncodingException { // System.setOut(new PrintStream(outContent, true, "UTF-8")); // System.setErr(new PrintStream(errContent, true, "UTF-8")); // } // // public void clear() { // outContent.reset(); // errContent.reset(); // } // // public void reset() { // System.setOut(out); // System.setErr(err); // } // // public String getOut() throws UnsupportedEncodingException { // return outContent.toString("UTF-8"); // } // // public String getErr() throws UnsupportedEncodingException { // return errContent.toString("UTF-8"); // } // } // // Path: jdcallgraph/src/test/java/com/dkarv/jdcallgraph/util/config/ConfigUtils.java // public class ConfigUtils { // // public static void replace(boolean addDefaults, String... options) throws IOException { // if (addDefaults) { // new ConfigReader( // ConfigUtils.class.getResourceAsStream("/com/dkarv/jdcallgraph/defaults.ini"), // write(options)).read(); // } else { // new ConfigReader( // write(options)).read(); // } // } // // public static InputStream write(String... options) throws IOException { // StringBuilder str = new StringBuilder(); // for (String opt : options) { // str.append(opt); // str.append('\n'); // } // return TestUtils.writeInputStream(str.toString()); // } // // public static void inject(Config config) { // Config.instance = config; // } // } // Path: jdcallgraph/src/test/java/com/dkarv/jdcallgraph/util/log/LoggerTest.java import com.dkarv.jdcallgraph.helper.Console; import com.dkarv.jdcallgraph.util.config.ConfigUtils; import org.hamcrest.text.MatchesPattern; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.mockito.Mockito; import java.io.IOException; import java.util.regex.Pattern; import static org.junit.Assert.*; arg = null; logger.debug("test {}", arg); Mockito.verify(target).print(Mockito.matches("\\[.*] \\[DEBUG] \\[LoggerTest] test null\n"), Mockito.eq(5)); } @Test public void testWrongArgumentCount() { Logger logger = init(6, false); try { logger.debug("test {}", "123", "456"); fail("Should notice too less {}"); } catch (IllegalArgumentException e) { } try { logger.debug("test {} {}"); fail("Should notice missing arguments"); } catch (IllegalArgumentException e) { } } @Test public void testTargetError() throws IOException { Logger logger = init(6, false); Logger.TARGETS.clear(); LogTarget target = Mockito.mock(LogTarget.class); Mockito.doThrow(new IOException("error")).when(target).print(Mockito.anyString(), Mockito.anyInt()); Logger.TARGETS.add(target);
Console console = new Console();
dkarv/jdcallgraph
jdcallgraph/src/main/java/com/dkarv/jdcallgraph/writer/CsvTraceFileWriter.java
// Path: jdcallgraph/src/main/java/com/dkarv/jdcallgraph/util/StackItem.java // public class StackItem { // private final String className; // private final String methodName; // private final int lineNumber; // private final boolean returnSafe; // // private final String formatted; // // public StackItem(String className, String methodName, int lineNumber, boolean returnSafe) { // this.className = className; // this.methodName = methodName; // this.lineNumber = lineNumber; // // this.returnSafe = returnSafe; // // this.formatted = Formatter.format(this); // } // // public StackItem(String type, String method, String signature, int lineNumber) { // this(type, method, signature, lineNumber, true); // } // // public StackItem(String type, String method, String signature, int lineNumber, boolean returnSafe) { // this.className = type; // // TODO store them separated // this.methodName = method + signature; // this.lineNumber = lineNumber; // this.returnSafe = returnSafe; // // this.formatted = Formatter.format(this); // } // // public String getClassName() { // return className; // } // // public String getMethodName() { // return methodName; // } // // public int getLineNumber() { // return lineNumber; // } // // @Override // public String toString() { // return formatted; // } // // @Override // public int hashCode() { // return 31 * 31 * className.hashCode() // + 31 * methodName.hashCode() // + lineNumber; // } // // @Override // public boolean equals(Object other) { // if (!(other instanceof StackItem)) { // return false; // } // if (this == other) { // return true; // } // StackItem o = (StackItem) other; // return className.equals(o.className) && // methodName.equals(o.methodName) && // lineNumber == o.lineNumber; // } // // public String getPackageName() { // int indexDot = className.lastIndexOf('.'); // return className.substring(0, indexDot); // } // // public String getShortClassName() { // int indexDot = className.lastIndexOf('.'); // return className.substring(indexDot + 1); // } // // public String getShortMethodName() { // int indexBracket = methodName.indexOf('('); // return methodName.substring(0, indexBracket); // } // // public String getMethodParameters() { // int openBracket = methodName.indexOf('('); // int closingBracket = methodName.indexOf(')'); // return methodName.substring(openBracket + 1, closingBracket); // } // // public boolean isReturnSafe() { // return returnSafe; // } // // public boolean equalTo(StackTraceElement element) { // return element != null // && this.className.equals(element.getClassName()) // && this.getShortMethodName().equals(element.getMethodName()) // // line number comparison does not work because the stack trace number // // is the real line of the call and not beginning of the method // //&& this.lineNumber == element.getLineNumber() // ; // } // }
import com.dkarv.jdcallgraph.util.StackItem; import java.io.IOException; import java.util.HashSet; import java.util.Set;
/* * MIT License * <p> * Copyright (c) 2017 David Krebs * <p> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p> * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * <p> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.dkarv.jdcallgraph.writer; public class CsvTraceFileWriter implements GraphWriter { FileWriter writer;
// Path: jdcallgraph/src/main/java/com/dkarv/jdcallgraph/util/StackItem.java // public class StackItem { // private final String className; // private final String methodName; // private final int lineNumber; // private final boolean returnSafe; // // private final String formatted; // // public StackItem(String className, String methodName, int lineNumber, boolean returnSafe) { // this.className = className; // this.methodName = methodName; // this.lineNumber = lineNumber; // // this.returnSafe = returnSafe; // // this.formatted = Formatter.format(this); // } // // public StackItem(String type, String method, String signature, int lineNumber) { // this(type, method, signature, lineNumber, true); // } // // public StackItem(String type, String method, String signature, int lineNumber, boolean returnSafe) { // this.className = type; // // TODO store them separated // this.methodName = method + signature; // this.lineNumber = lineNumber; // this.returnSafe = returnSafe; // // this.formatted = Formatter.format(this); // } // // public String getClassName() { // return className; // } // // public String getMethodName() { // return methodName; // } // // public int getLineNumber() { // return lineNumber; // } // // @Override // public String toString() { // return formatted; // } // // @Override // public int hashCode() { // return 31 * 31 * className.hashCode() // + 31 * methodName.hashCode() // + lineNumber; // } // // @Override // public boolean equals(Object other) { // if (!(other instanceof StackItem)) { // return false; // } // if (this == other) { // return true; // } // StackItem o = (StackItem) other; // return className.equals(o.className) && // methodName.equals(o.methodName) && // lineNumber == o.lineNumber; // } // // public String getPackageName() { // int indexDot = className.lastIndexOf('.'); // return className.substring(0, indexDot); // } // // public String getShortClassName() { // int indexDot = className.lastIndexOf('.'); // return className.substring(indexDot + 1); // } // // public String getShortMethodName() { // int indexBracket = methodName.indexOf('('); // return methodName.substring(0, indexBracket); // } // // public String getMethodParameters() { // int openBracket = methodName.indexOf('('); // int closingBracket = methodName.indexOf(')'); // return methodName.substring(openBracket + 1, closingBracket); // } // // public boolean isReturnSafe() { // return returnSafe; // } // // public boolean equalTo(StackTraceElement element) { // return element != null // && this.className.equals(element.getClassName()) // && this.getShortMethodName().equals(element.getMethodName()) // // line number comparison does not work because the stack trace number // // is the real line of the call and not beginning of the method // //&& this.lineNumber == element.getLineNumber() // ; // } // } // Path: jdcallgraph/src/main/java/com/dkarv/jdcallgraph/writer/CsvTraceFileWriter.java import com.dkarv.jdcallgraph.util.StackItem; import java.io.IOException; import java.util.HashSet; import java.util.Set; /* * MIT License * <p> * Copyright (c) 2017 David Krebs * <p> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p> * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * <p> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.dkarv.jdcallgraph.writer; public class CsvTraceFileWriter implements GraphWriter { FileWriter writer;
private final Set<StackItem> trace = new HashSet<>();
dkarv/jdcallgraph
jdcallgraph/src/test/java/com/dkarv/jdcallgraph/util/log/ConsoleTargetTest.java
// Path: jdcallgraph/src/test/java/com/dkarv/jdcallgraph/helper/Console.java // public class Console { // private final PrintStream err; // private final PrintStream out; // private final ByteArrayOutputStream outContent; // private final ByteArrayOutputStream errContent; // // public Console() { // err = System.err; // out = System.out; // outContent = new ByteArrayOutputStream(); // errContent = new ByteArrayOutputStream(); // } // // public void startCapture() throws UnsupportedEncodingException { // System.setOut(new PrintStream(outContent, true, "UTF-8")); // System.setErr(new PrintStream(errContent, true, "UTF-8")); // } // // public void clear() { // outContent.reset(); // errContent.reset(); // } // // public void reset() { // System.setOut(out); // System.setErr(err); // } // // public String getOut() throws UnsupportedEncodingException { // return outContent.toString("UTF-8"); // } // // public String getErr() throws UnsupportedEncodingException { // return errContent.toString("UTF-8"); // } // }
import com.dkarv.jdcallgraph.helper.Console; import org.junit.Assert; import org.junit.Test; import org.mockito.Mockito; import java.io.IOException; import java.io.UnsupportedEncodingException;
package com.dkarv.jdcallgraph.util.log; public class ConsoleTargetTest { private final static String TEST = "test#+*'!§$%&/()=?\n@@€"; @Test public void testPrint() throws UnsupportedEncodingException {
// Path: jdcallgraph/src/test/java/com/dkarv/jdcallgraph/helper/Console.java // public class Console { // private final PrintStream err; // private final PrintStream out; // private final ByteArrayOutputStream outContent; // private final ByteArrayOutputStream errContent; // // public Console() { // err = System.err; // out = System.out; // outContent = new ByteArrayOutputStream(); // errContent = new ByteArrayOutputStream(); // } // // public void startCapture() throws UnsupportedEncodingException { // System.setOut(new PrintStream(outContent, true, "UTF-8")); // System.setErr(new PrintStream(errContent, true, "UTF-8")); // } // // public void clear() { // outContent.reset(); // errContent.reset(); // } // // public void reset() { // System.setOut(out); // System.setErr(err); // } // // public String getOut() throws UnsupportedEncodingException { // return outContent.toString("UTF-8"); // } // // public String getErr() throws UnsupportedEncodingException { // return errContent.toString("UTF-8"); // } // } // Path: jdcallgraph/src/test/java/com/dkarv/jdcallgraph/util/log/ConsoleTargetTest.java import com.dkarv.jdcallgraph.helper.Console; import org.junit.Assert; import org.junit.Test; import org.mockito.Mockito; import java.io.IOException; import java.io.UnsupportedEncodingException; package com.dkarv.jdcallgraph.util.log; public class ConsoleTargetTest { private final static String TEST = "test#+*'!§$%&/()=?\n@@€"; @Test public void testPrint() throws UnsupportedEncodingException {
Console console = new Console();
dkarv/jdcallgraph
jdcallgraph/src/main/java/com/dkarv/jdcallgraph/writer/GraphWriter.java
// Path: jdcallgraph/src/main/java/com/dkarv/jdcallgraph/util/StackItem.java // public class StackItem { // private final String className; // private final String methodName; // private final int lineNumber; // private final boolean returnSafe; // // private final String formatted; // // public StackItem(String className, String methodName, int lineNumber, boolean returnSafe) { // this.className = className; // this.methodName = methodName; // this.lineNumber = lineNumber; // // this.returnSafe = returnSafe; // // this.formatted = Formatter.format(this); // } // // public StackItem(String type, String method, String signature, int lineNumber) { // this(type, method, signature, lineNumber, true); // } // // public StackItem(String type, String method, String signature, int lineNumber, boolean returnSafe) { // this.className = type; // // TODO store them separated // this.methodName = method + signature; // this.lineNumber = lineNumber; // this.returnSafe = returnSafe; // // this.formatted = Formatter.format(this); // } // // public String getClassName() { // return className; // } // // public String getMethodName() { // return methodName; // } // // public int getLineNumber() { // return lineNumber; // } // // @Override // public String toString() { // return formatted; // } // // @Override // public int hashCode() { // return 31 * 31 * className.hashCode() // + 31 * methodName.hashCode() // + lineNumber; // } // // @Override // public boolean equals(Object other) { // if (!(other instanceof StackItem)) { // return false; // } // if (this == other) { // return true; // } // StackItem o = (StackItem) other; // return className.equals(o.className) && // methodName.equals(o.methodName) && // lineNumber == o.lineNumber; // } // // public String getPackageName() { // int indexDot = className.lastIndexOf('.'); // return className.substring(0, indexDot); // } // // public String getShortClassName() { // int indexDot = className.lastIndexOf('.'); // return className.substring(indexDot + 1); // } // // public String getShortMethodName() { // int indexBracket = methodName.indexOf('('); // return methodName.substring(0, indexBracket); // } // // public String getMethodParameters() { // int openBracket = methodName.indexOf('('); // int closingBracket = methodName.indexOf(')'); // return methodName.substring(openBracket + 1, closingBracket); // } // // public boolean isReturnSafe() { // return returnSafe; // } // // public boolean equalTo(StackTraceElement element) { // return element != null // && this.className.equals(element.getClassName()) // && this.getShortMethodName().equals(element.getMethodName()) // // line number comparison does not work because the stack trace number // // is the real line of the call and not beginning of the method // //&& this.lineNumber == element.getLineNumber() // ; // } // }
import com.dkarv.jdcallgraph.util.StackItem; import java.io.Closeable; import java.io.IOException;
/* * MIT License * <p> * Copyright (c) 2017 David Krebs * <p> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p> * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * <p> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.dkarv.jdcallgraph.writer; public interface GraphWriter extends Closeable { /** * Start a new graph with the given name. * * @param identifier name of the graph */ void start(String identifier) throws IOException; /** * Add a node.This is only called once at the beginning of the graph. * * @param method method */
// Path: jdcallgraph/src/main/java/com/dkarv/jdcallgraph/util/StackItem.java // public class StackItem { // private final String className; // private final String methodName; // private final int lineNumber; // private final boolean returnSafe; // // private final String formatted; // // public StackItem(String className, String methodName, int lineNumber, boolean returnSafe) { // this.className = className; // this.methodName = methodName; // this.lineNumber = lineNumber; // // this.returnSafe = returnSafe; // // this.formatted = Formatter.format(this); // } // // public StackItem(String type, String method, String signature, int lineNumber) { // this(type, method, signature, lineNumber, true); // } // // public StackItem(String type, String method, String signature, int lineNumber, boolean returnSafe) { // this.className = type; // // TODO store them separated // this.methodName = method + signature; // this.lineNumber = lineNumber; // this.returnSafe = returnSafe; // // this.formatted = Formatter.format(this); // } // // public String getClassName() { // return className; // } // // public String getMethodName() { // return methodName; // } // // public int getLineNumber() { // return lineNumber; // } // // @Override // public String toString() { // return formatted; // } // // @Override // public int hashCode() { // return 31 * 31 * className.hashCode() // + 31 * methodName.hashCode() // + lineNumber; // } // // @Override // public boolean equals(Object other) { // if (!(other instanceof StackItem)) { // return false; // } // if (this == other) { // return true; // } // StackItem o = (StackItem) other; // return className.equals(o.className) && // methodName.equals(o.methodName) && // lineNumber == o.lineNumber; // } // // public String getPackageName() { // int indexDot = className.lastIndexOf('.'); // return className.substring(0, indexDot); // } // // public String getShortClassName() { // int indexDot = className.lastIndexOf('.'); // return className.substring(indexDot + 1); // } // // public String getShortMethodName() { // int indexBracket = methodName.indexOf('('); // return methodName.substring(0, indexBracket); // } // // public String getMethodParameters() { // int openBracket = methodName.indexOf('('); // int closingBracket = methodName.indexOf(')'); // return methodName.substring(openBracket + 1, closingBracket); // } // // public boolean isReturnSafe() { // return returnSafe; // } // // public boolean equalTo(StackTraceElement element) { // return element != null // && this.className.equals(element.getClassName()) // && this.getShortMethodName().equals(element.getMethodName()) // // line number comparison does not work because the stack trace number // // is the real line of the call and not beginning of the method // //&& this.lineNumber == element.getLineNumber() // ; // } // } // Path: jdcallgraph/src/main/java/com/dkarv/jdcallgraph/writer/GraphWriter.java import com.dkarv.jdcallgraph.util.StackItem; import java.io.Closeable; import java.io.IOException; /* * MIT License * <p> * Copyright (c) 2017 David Krebs * <p> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p> * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * <p> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.dkarv.jdcallgraph.writer; public interface GraphWriter extends Closeable { /** * Start a new graph with the given name. * * @param identifier name of the graph */ void start(String identifier) throws IOException; /** * Add a node.This is only called once at the beginning of the graph. * * @param method method */
void node(StackItem method) throws IOException;
mikifus/padland
app/src/main/java/com/mikifus/padland/SaferWebView/PadLandSaferWebViewClient.java
// Path: app/src/main/java/com/mikifus/padland/Utils/WhiteListMatcher.java // public class WhiteListMatcher { // /** // * Performs a wildcard matching for the text and pattern // * provided. // * // * @param text the text to be tested for matches. // * // * @param pattern the pattern to be matched for. // * This can contain the wildcard character '*' (asterisk). // * // * @return <tt>true</tt> if a match is found, <tt>false</tt> // * otherwise. // * // * @url http://www.adarshr.com/simple-implementation-of-wildcard-text-matching-using-java // */ // public static boolean wildCardMatch(String text, String pattern) { // // Create the cards by splitting using a RegEx. If more speed // // is desired, a simpler character based splitting can be done. // String [] cards = pattern.split("\\*"); // // // Iterate over the cards. // for (String card : cards) { // int idx = text.indexOf(card); // // // Card not detected in the text. // if(idx == -1) { // return false; // } // // // Move ahead, towards the right of the text. // text = text.substring(idx + card.length()); // } // // return true; // } // // /** // * Checks if the url parameter has a valid host // * among a list of hosts. // * // * @param url // * @param hostsWhitelist // * @return // */ // public static boolean isValidHost(String url, String[] hostsWhitelist){ // if (!TextUtils.isEmpty(url)) { // final String host = Uri.parse(url).getHost(); // if( host == null ) { // return false; // } // for (String whitelistedHost: hostsWhitelist){ // if(wildCardMatch(host, whitelistedHost)) { // return true; // } // } // } // return false; // } // // /** // * Checks if the URL can be parsed. // * // * @param padUrl // * @return // */ // public static boolean checkValidUrl(String padUrl) { // // Check if it is a valid url // try { // new URL(padUrl); // } catch (MalformedURLException e) { // e.printStackTrace(); // return false; // } // return true; // } // }
import android.util.Log; import android.webkit.WebResourceResponse; import android.webkit.WebView; import com.mikifus.padland.Utils.WhiteListMatcher; import java.io.ByteArrayInputStream;
package com.mikifus.padland.SaferWebView; /** * Extended class, I * Created by mikifus on 23/04/16. */ public class PadLandSaferWebViewClient extends SaferWebViewClient { public PadLandSaferWebViewClient(String[] hostsWhitelist) { super(hostsWhitelist); } @Override protected WebResourceResponse getWebResourceResponseFromString() { Log.w("SaferWebViewClient", "Blocked a JS request to an external domains."); return getUtf8EncodedWebResourceResponse(new ByteArrayInputStream("".getBytes())); } /** * Returning false we allow http to https redirects * @param view * @param url * @return */ @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { // return isValidHost(url); return false; } protected boolean isValidHost(String url){
// Path: app/src/main/java/com/mikifus/padland/Utils/WhiteListMatcher.java // public class WhiteListMatcher { // /** // * Performs a wildcard matching for the text and pattern // * provided. // * // * @param text the text to be tested for matches. // * // * @param pattern the pattern to be matched for. // * This can contain the wildcard character '*' (asterisk). // * // * @return <tt>true</tt> if a match is found, <tt>false</tt> // * otherwise. // * // * @url http://www.adarshr.com/simple-implementation-of-wildcard-text-matching-using-java // */ // public static boolean wildCardMatch(String text, String pattern) { // // Create the cards by splitting using a RegEx. If more speed // // is desired, a simpler character based splitting can be done. // String [] cards = pattern.split("\\*"); // // // Iterate over the cards. // for (String card : cards) { // int idx = text.indexOf(card); // // // Card not detected in the text. // if(idx == -1) { // return false; // } // // // Move ahead, towards the right of the text. // text = text.substring(idx + card.length()); // } // // return true; // } // // /** // * Checks if the url parameter has a valid host // * among a list of hosts. // * // * @param url // * @param hostsWhitelist // * @return // */ // public static boolean isValidHost(String url, String[] hostsWhitelist){ // if (!TextUtils.isEmpty(url)) { // final String host = Uri.parse(url).getHost(); // if( host == null ) { // return false; // } // for (String whitelistedHost: hostsWhitelist){ // if(wildCardMatch(host, whitelistedHost)) { // return true; // } // } // } // return false; // } // // /** // * Checks if the URL can be parsed. // * // * @param padUrl // * @return // */ // public static boolean checkValidUrl(String padUrl) { // // Check if it is a valid url // try { // new URL(padUrl); // } catch (MalformedURLException e) { // e.printStackTrace(); // return false; // } // return true; // } // } // Path: app/src/main/java/com/mikifus/padland/SaferWebView/PadLandSaferWebViewClient.java import android.util.Log; import android.webkit.WebResourceResponse; import android.webkit.WebView; import com.mikifus.padland.Utils.WhiteListMatcher; import java.io.ByteArrayInputStream; package com.mikifus.padland.SaferWebView; /** * Extended class, I * Created by mikifus on 23/04/16. */ public class PadLandSaferWebViewClient extends SaferWebViewClient { public PadLandSaferWebViewClient(String[] hostsWhitelist) { super(hostsWhitelist); } @Override protected WebResourceResponse getWebResourceResponseFromString() { Log.w("SaferWebViewClient", "Blocked a JS request to an external domains."); return getUtf8EncodedWebResourceResponse(new ByteArrayInputStream("".getBytes())); } /** * Returning false we allow http to https redirects * @param view * @param url * @return */ @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { // return isValidHost(url); return false; } protected boolean isValidHost(String url){
return WhiteListMatcher.isValidHost(url, hostsWhitelist);
mikifus/padland
app/src/main/java/com/mikifus/padland/IntroActivity.java
// Path: app/src/main/java/com/mikifus/padland/Intro/LinkableAppIntroFragment.java // public class LinkableAppIntroFragment extends CustomAppIntroFragment { // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, // @Nullable Bundle savedInstanceState) { // View v = super.onCreateView(inflater, container, savedInstanceState); // TextView d; // if (v != null) { // d = (TextView) v.findViewById(R.id.description); // d.setLinkTextColor(R.color.intro_link_color); // Linkify.addLinks(d,Linkify.ALL); // } // return v; // } // }
import android.content.Intent; import android.os.Bundle; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.core.content.ContextCompat; import com.github.paolorotolo.appintro.AppIntro2; import com.github.paolorotolo.appintro.AppIntroFragment; import com.mikifus.padland.Intro.LinkableAppIntroFragment;
package com.mikifus.padland; /** * Created by mikifus on 7/10/16. */ public class IntroActivity extends AppIntro2 { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Note here that we DO NOT use setContentView(); // Just set a title, description, background and image. AppIntro will do the rest. // addSlide(AppIntroFragment.newInstance(title, description, image, backgroundColor)); addSlide(AppIntroFragment.newInstance(getString(R.string.intro_first_title), getString(R.string.intro_first_desc), R.drawable.intro_image1, ContextCompat.getColor(this, R.color.intro_first_background))); addSlide(AppIntroFragment.newInstance(getString(R.string.intro_second_title), getString(R.string.intro_second_desc), R.drawable.intro_image2, ContextCompat.getColor(this, R.color.intro_second_background))); addSlide(AppIntroFragment.newInstance(getString(R.string.intro_third_title), getString(R.string.intro_third_desc), R.drawable.intro_image3, ContextCompat.getColor(this, R.color.intro_third_background))); addSlide(AppIntroFragment.newInstance(getString(R.string.intro_fourth_title), getString(R.string.intro_fourth_desc), R.drawable.intro_image4, ContextCompat.getColor(this, R.color.intro_fourth_background)));
// Path: app/src/main/java/com/mikifus/padland/Intro/LinkableAppIntroFragment.java // public class LinkableAppIntroFragment extends CustomAppIntroFragment { // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, // @Nullable Bundle savedInstanceState) { // View v = super.onCreateView(inflater, container, savedInstanceState); // TextView d; // if (v != null) { // d = (TextView) v.findViewById(R.id.description); // d.setLinkTextColor(R.color.intro_link_color); // Linkify.addLinks(d,Linkify.ALL); // } // return v; // } // } // Path: app/src/main/java/com/mikifus/padland/IntroActivity.java import android.content.Intent; import android.os.Bundle; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.core.content.ContextCompat; import com.github.paolorotolo.appintro.AppIntro2; import com.github.paolorotolo.appintro.AppIntroFragment; import com.mikifus.padland.Intro.LinkableAppIntroFragment; package com.mikifus.padland; /** * Created by mikifus on 7/10/16. */ public class IntroActivity extends AppIntro2 { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Note here that we DO NOT use setContentView(); // Just set a title, description, background and image. AppIntro will do the rest. // addSlide(AppIntroFragment.newInstance(title, description, image, backgroundColor)); addSlide(AppIntroFragment.newInstance(getString(R.string.intro_first_title), getString(R.string.intro_first_desc), R.drawable.intro_image1, ContextCompat.getColor(this, R.color.intro_first_background))); addSlide(AppIntroFragment.newInstance(getString(R.string.intro_second_title), getString(R.string.intro_second_desc), R.drawable.intro_image2, ContextCompat.getColor(this, R.color.intro_second_background))); addSlide(AppIntroFragment.newInstance(getString(R.string.intro_third_title), getString(R.string.intro_third_desc), R.drawable.intro_image3, ContextCompat.getColor(this, R.color.intro_third_background))); addSlide(AppIntroFragment.newInstance(getString(R.string.intro_fourth_title), getString(R.string.intro_fourth_desc), R.drawable.intro_image4, ContextCompat.getColor(this, R.color.intro_fourth_background)));
addSlide(LinkableAppIntroFragment.newInstance(getString(R.string.intro_fifth_title),
mikifus/padland
app/src/main/java/com/mikifus/padland/PadInfoActivity.java
// Path: app/src/main/java/com/mikifus/padland/Models/Pad.java // public class Pad // { // private long id; // private String name; // private String local_name; // private String server; // private String url; // private long last_used_date; // private long create_date; // private long access_count; // // public Pad(Cursor c) { // if(c != null && c.getCount() > 0) { // id = c.getLong(0); // name = c.getString(1); // local_name = c.getString(2); // server = c.getString(3); // url = c.getString(4); // last_used_date = c.getLong(5); // create_date = c.getLong(6); // access_count = c.getLong(7); // } // } // public long getId() { // return id; // } // public String getName() { // return name; // } // public String getLocalName() { // if(local_name == null || local_name.isEmpty()) { // return name; // } // return local_name; // } // public String getRawLocalName() { // if(local_name == null || local_name.isEmpty()) { // return ""; // } // return local_name; // } // public String getServer() { // return server; // } // public String getUrl() { // return url; // } // public String getLastUsedDate(Context context) { // return lon_to_date( last_used_date, context ); // } // public long getAccessCount() { // return access_count; // } // public String getCreateDate(Context context) { // return lon_to_date( create_date, context ); // } // public String lon_to_date( long TimeinMilliSeccond, Context context ){ // DateFormat formatter = android.text.format.DateFormat.getDateFormat( context.getApplicationContext() ); // Date dateObj = new Date( TimeinMilliSeccond * 1000 ); // return formatter.format( dateObj ); // } // }
import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.Toast; import com.mikifus.padland.Models.Pad; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map;
package com.mikifus.padland; /** * This activity shows pad info like the last time it was used or when * it was created. It can be upgraded to show useful info. * Its menu as well allows to delete. */ public class PadInfoActivity extends PadLandDataActivity { private static final String TAG = "PadInfoActivity"; long pad_id = 0; /** * * @param savedInstanceState */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_pad_info); pad_id = this._getPadId(); if( pad_id <= 0 ){ Toast.makeText(this, getString(R.string.unexpected_error), Toast.LENGTH_LONG).show(); return; }
// Path: app/src/main/java/com/mikifus/padland/Models/Pad.java // public class Pad // { // private long id; // private String name; // private String local_name; // private String server; // private String url; // private long last_used_date; // private long create_date; // private long access_count; // // public Pad(Cursor c) { // if(c != null && c.getCount() > 0) { // id = c.getLong(0); // name = c.getString(1); // local_name = c.getString(2); // server = c.getString(3); // url = c.getString(4); // last_used_date = c.getLong(5); // create_date = c.getLong(6); // access_count = c.getLong(7); // } // } // public long getId() { // return id; // } // public String getName() { // return name; // } // public String getLocalName() { // if(local_name == null || local_name.isEmpty()) { // return name; // } // return local_name; // } // public String getRawLocalName() { // if(local_name == null || local_name.isEmpty()) { // return ""; // } // return local_name; // } // public String getServer() { // return server; // } // public String getUrl() { // return url; // } // public String getLastUsedDate(Context context) { // return lon_to_date( last_used_date, context ); // } // public long getAccessCount() { // return access_count; // } // public String getCreateDate(Context context) { // return lon_to_date( create_date, context ); // } // public String lon_to_date( long TimeinMilliSeccond, Context context ){ // DateFormat formatter = android.text.format.DateFormat.getDateFormat( context.getApplicationContext() ); // Date dateObj = new Date( TimeinMilliSeccond * 1000 ); // return formatter.format( dateObj ); // } // } // Path: app/src/main/java/com/mikifus/padland/PadInfoActivity.java import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.Toast; import com.mikifus.padland.Models.Pad; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; package com.mikifus.padland; /** * This activity shows pad info like the last time it was used or when * it was created. It can be upgraded to show useful info. * Its menu as well allows to delete. */ public class PadInfoActivity extends PadLandDataActivity { private static final String TAG = "PadInfoActivity"; long pad_id = 0; /** * * @param savedInstanceState */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_pad_info); pad_id = this._getPadId(); if( pad_id <= 0 ){ Toast.makeText(this, getString(R.string.unexpected_error), Toast.LENGTH_LONG).show(); return; }
Pad pad_data = this._getPad( pad_id );
wavky/WavkyHome
src/main/java/action/LoginAction.java
// Path: src/main/java/bean/User.java // public class User { // // private Integer id; // private String name; // private String password; // /** // * @return the id // */ // public Integer getId() { // return id; // } // /** // * @param id the id to set // */ // public void setId(Integer id) { // this.id = id; // } // /** // * @return the name // */ // public String getName() { // return name; // } // /** // * @param name the name to set // */ // public void setName(String name) { // this.name = name; // } // /** // * @return the password // */ // public String getPassword() { // return password; // } // /** // * @param password the password to set // */ // public void setPassword(String password) { // this.password = password; // } // } // // Path: src/main/java/dao/interfaces/UserDao.java // public interface UserDao extends BaseDao<User> { // // /** // * ¸ù¾ÝÓû§ÃûËÑË÷Óû§ // * // * @param name // * @return ²»´æÔÚʱ·µ»Ønull // */ // public abstract User get(String name); // }
import org.apache.struts2.ServletActionContext; import bean.User; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; import dao.interfaces.UserDao;
/** * 2014Äê10ÔÂ25ÈÕ ÉÏÎç10:51:51 */ package action; /** * ÌṩµÇ½Ïà¹Ø²Ù×÷ * * @author wavky.wand * */ public class LoginAction extends ActionSupport { private static final long serialVersionUID = 1L; private String name; private String password;
// Path: src/main/java/bean/User.java // public class User { // // private Integer id; // private String name; // private String password; // /** // * @return the id // */ // public Integer getId() { // return id; // } // /** // * @param id the id to set // */ // public void setId(Integer id) { // this.id = id; // } // /** // * @return the name // */ // public String getName() { // return name; // } // /** // * @param name the name to set // */ // public void setName(String name) { // this.name = name; // } // /** // * @return the password // */ // public String getPassword() { // return password; // } // /** // * @param password the password to set // */ // public void setPassword(String password) { // this.password = password; // } // } // // Path: src/main/java/dao/interfaces/UserDao.java // public interface UserDao extends BaseDao<User> { // // /** // * ¸ù¾ÝÓû§ÃûËÑË÷Óû§ // * // * @param name // * @return ²»´æÔÚʱ·µ»Ønull // */ // public abstract User get(String name); // } // Path: src/main/java/action/LoginAction.java import org.apache.struts2.ServletActionContext; import bean.User; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; import dao.interfaces.UserDao; /** * 2014Äê10ÔÂ25ÈÕ ÉÏÎç10:51:51 */ package action; /** * ÌṩµÇ½Ïà¹Ø²Ù×÷ * * @author wavky.wand * */ public class LoginAction extends ActionSupport { private static final long serialVersionUID = 1L; private String name; private String password;
private UserDao userDao;
wavky/WavkyHome
src/main/java/action/LoginAction.java
// Path: src/main/java/bean/User.java // public class User { // // private Integer id; // private String name; // private String password; // /** // * @return the id // */ // public Integer getId() { // return id; // } // /** // * @param id the id to set // */ // public void setId(Integer id) { // this.id = id; // } // /** // * @return the name // */ // public String getName() { // return name; // } // /** // * @param name the name to set // */ // public void setName(String name) { // this.name = name; // } // /** // * @return the password // */ // public String getPassword() { // return password; // } // /** // * @param password the password to set // */ // public void setPassword(String password) { // this.password = password; // } // } // // Path: src/main/java/dao/interfaces/UserDao.java // public interface UserDao extends BaseDao<User> { // // /** // * ¸ù¾ÝÓû§ÃûËÑË÷Óû§ // * // * @param name // * @return ²»´æÔÚʱ·µ»Ønull // */ // public abstract User get(String name); // }
import org.apache.struts2.ServletActionContext; import bean.User; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; import dao.interfaces.UserDao;
* @param userDao the userDao to set */ public void setUserDao(UserDao userDao) { this.userDao = userDao; } /** * @return the refererUrl */ public String getRefererUrl() { return refererUrl; } /** * @param refererUrl the refererUrl to set */ public void setRefererUrl(String refererUrl) { this.refererUrl = refererUrl; } @Override public String execute() throws Exception { setRefererUrl(ServletActionContext.getRequest().getHeader("referer")); ActionContext ac = ActionContext.getContext(); ac.getSession().put("refererUrl", getRefererUrl()); return SUCCESS; } public String login() throws Exception { ActionContext ac = ActionContext.getContext();
// Path: src/main/java/bean/User.java // public class User { // // private Integer id; // private String name; // private String password; // /** // * @return the id // */ // public Integer getId() { // return id; // } // /** // * @param id the id to set // */ // public void setId(Integer id) { // this.id = id; // } // /** // * @return the name // */ // public String getName() { // return name; // } // /** // * @param name the name to set // */ // public void setName(String name) { // this.name = name; // } // /** // * @return the password // */ // public String getPassword() { // return password; // } // /** // * @param password the password to set // */ // public void setPassword(String password) { // this.password = password; // } // } // // Path: src/main/java/dao/interfaces/UserDao.java // public interface UserDao extends BaseDao<User> { // // /** // * ¸ù¾ÝÓû§ÃûËÑË÷Óû§ // * // * @param name // * @return ²»´æÔÚʱ·µ»Ønull // */ // public abstract User get(String name); // } // Path: src/main/java/action/LoginAction.java import org.apache.struts2.ServletActionContext; import bean.User; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; import dao.interfaces.UserDao; * @param userDao the userDao to set */ public void setUserDao(UserDao userDao) { this.userDao = userDao; } /** * @return the refererUrl */ public String getRefererUrl() { return refererUrl; } /** * @param refererUrl the refererUrl to set */ public void setRefererUrl(String refererUrl) { this.refererUrl = refererUrl; } @Override public String execute() throws Exception { setRefererUrl(ServletActionContext.getRequest().getHeader("referer")); ActionContext ac = ActionContext.getContext(); ac.getSession().put("refererUrl", getRefererUrl()); return SUCCESS; } public String login() throws Exception { ActionContext ac = ActionContext.getContext();
User user = getUserDao().get(name);
wavky/WavkyHome
src/main/java/action/InterfaceAction.java
// Path: src/main/java/bean/Interface.java // public class Interface { // // private Integer id; // private String description; // private String url; // private String request; // private String response; // private Long addTime; // // /** // * @return the id // */ // public Integer getId() { // return id; // } // // /** // * @param id // * the id to set // */ // public void setId(Integer id) { // this.id = id; // } // // /** // * @return the description // */ // public String getDescription() { // return description; // } // // /** // * @param description // * the description to set // */ // public void setDescription(String description) { // this.description = description; // } // // /** // * @return the url // */ // public String getUrl() { // return url; // } // // /** // * @param url // * the url to set // */ // public void setUrl(String url) { // this.url = url; // } // // /** // * @return the request // */ // public String getRequest() { // return request; // } // // /** // * @param request // * the request to set // */ // public void setRequest(String request) { // this.request = request; // } // // /** // * @return the response // */ // public String getResponse() { // return response; // } // // /** // * @param response // * the response to set // */ // public void setResponse(String response) { // this.response = response; // } // // /** // * @return the addTime // */ // public Long getAddTime() { // return addTime; // } // // /** // * @param addTime // * the addTime to set // */ // public void setAddTime(Long addTime) { // this.addTime = addTime; // } // } // // Path: src/main/java/dao/interfaces/InterfaceDao.java // public interface InterfaceDao extends BaseDao<Interface> { // // }
import com.opensymphony.xwork2.ActionSupport; import dao.interfaces.InterfaceDao; import java.util.List; import bean.Interface;
/** * 2014Äê10ÔÂ25ÈÕ ÉÏÎç10:51:51 */ package action; /** * * * @author wavky.wand * */ public class InterfaceAction extends ActionSupport { private static final long serialVersionUID = 1L; private String description; private String interfaceUrl; private String interfaceRequest; private String interfaceResponse; private int targetInterfaceId;
// Path: src/main/java/bean/Interface.java // public class Interface { // // private Integer id; // private String description; // private String url; // private String request; // private String response; // private Long addTime; // // /** // * @return the id // */ // public Integer getId() { // return id; // } // // /** // * @param id // * the id to set // */ // public void setId(Integer id) { // this.id = id; // } // // /** // * @return the description // */ // public String getDescription() { // return description; // } // // /** // * @param description // * the description to set // */ // public void setDescription(String description) { // this.description = description; // } // // /** // * @return the url // */ // public String getUrl() { // return url; // } // // /** // * @param url // * the url to set // */ // public void setUrl(String url) { // this.url = url; // } // // /** // * @return the request // */ // public String getRequest() { // return request; // } // // /** // * @param request // * the request to set // */ // public void setRequest(String request) { // this.request = request; // } // // /** // * @return the response // */ // public String getResponse() { // return response; // } // // /** // * @param response // * the response to set // */ // public void setResponse(String response) { // this.response = response; // } // // /** // * @return the addTime // */ // public Long getAddTime() { // return addTime; // } // // /** // * @param addTime // * the addTime to set // */ // public void setAddTime(Long addTime) { // this.addTime = addTime; // } // } // // Path: src/main/java/dao/interfaces/InterfaceDao.java // public interface InterfaceDao extends BaseDao<Interface> { // // } // Path: src/main/java/action/InterfaceAction.java import com.opensymphony.xwork2.ActionSupport; import dao.interfaces.InterfaceDao; import java.util.List; import bean.Interface; /** * 2014Äê10ÔÂ25ÈÕ ÉÏÎç10:51:51 */ package action; /** * * * @author wavky.wand * */ public class InterfaceAction extends ActionSupport { private static final long serialVersionUID = 1L; private String description; private String interfaceUrl; private String interfaceRequest; private String interfaceResponse; private int targetInterfaceId;
private InterfaceDao interfaceDao;
wavky/WavkyHome
src/main/java/action/InterfaceAction.java
// Path: src/main/java/bean/Interface.java // public class Interface { // // private Integer id; // private String description; // private String url; // private String request; // private String response; // private Long addTime; // // /** // * @return the id // */ // public Integer getId() { // return id; // } // // /** // * @param id // * the id to set // */ // public void setId(Integer id) { // this.id = id; // } // // /** // * @return the description // */ // public String getDescription() { // return description; // } // // /** // * @param description // * the description to set // */ // public void setDescription(String description) { // this.description = description; // } // // /** // * @return the url // */ // public String getUrl() { // return url; // } // // /** // * @param url // * the url to set // */ // public void setUrl(String url) { // this.url = url; // } // // /** // * @return the request // */ // public String getRequest() { // return request; // } // // /** // * @param request // * the request to set // */ // public void setRequest(String request) { // this.request = request; // } // // /** // * @return the response // */ // public String getResponse() { // return response; // } // // /** // * @param response // * the response to set // */ // public void setResponse(String response) { // this.response = response; // } // // /** // * @return the addTime // */ // public Long getAddTime() { // return addTime; // } // // /** // * @param addTime // * the addTime to set // */ // public void setAddTime(Long addTime) { // this.addTime = addTime; // } // } // // Path: src/main/java/dao/interfaces/InterfaceDao.java // public interface InterfaceDao extends BaseDao<Interface> { // // }
import com.opensymphony.xwork2.ActionSupport; import dao.interfaces.InterfaceDao; import java.util.List; import bean.Interface;
/** * 2014Äê10ÔÂ25ÈÕ ÉÏÎç10:51:51 */ package action; /** * * * @author wavky.wand * */ public class InterfaceAction extends ActionSupport { private static final long serialVersionUID = 1L; private String description; private String interfaceUrl; private String interfaceRequest; private String interfaceResponse; private int targetInterfaceId; private InterfaceDao interfaceDao;
// Path: src/main/java/bean/Interface.java // public class Interface { // // private Integer id; // private String description; // private String url; // private String request; // private String response; // private Long addTime; // // /** // * @return the id // */ // public Integer getId() { // return id; // } // // /** // * @param id // * the id to set // */ // public void setId(Integer id) { // this.id = id; // } // // /** // * @return the description // */ // public String getDescription() { // return description; // } // // /** // * @param description // * the description to set // */ // public void setDescription(String description) { // this.description = description; // } // // /** // * @return the url // */ // public String getUrl() { // return url; // } // // /** // * @param url // * the url to set // */ // public void setUrl(String url) { // this.url = url; // } // // /** // * @return the request // */ // public String getRequest() { // return request; // } // // /** // * @param request // * the request to set // */ // public void setRequest(String request) { // this.request = request; // } // // /** // * @return the response // */ // public String getResponse() { // return response; // } // // /** // * @param response // * the response to set // */ // public void setResponse(String response) { // this.response = response; // } // // /** // * @return the addTime // */ // public Long getAddTime() { // return addTime; // } // // /** // * @param addTime // * the addTime to set // */ // public void setAddTime(Long addTime) { // this.addTime = addTime; // } // } // // Path: src/main/java/dao/interfaces/InterfaceDao.java // public interface InterfaceDao extends BaseDao<Interface> { // // } // Path: src/main/java/action/InterfaceAction.java import com.opensymphony.xwork2.ActionSupport; import dao.interfaces.InterfaceDao; import java.util.List; import bean.Interface; /** * 2014Äê10ÔÂ25ÈÕ ÉÏÎç10:51:51 */ package action; /** * * * @author wavky.wand * */ public class InterfaceAction extends ActionSupport { private static final long serialVersionUID = 1L; private String description; private String interfaceUrl; private String interfaceRequest; private String interfaceResponse; private int targetInterfaceId; private InterfaceDao interfaceDao;
private List<Interface> interfaceList;
wavky/WavkyHome
src/main/java/action/UpdateAccountAction.java
// Path: src/main/java/bean/User.java // public class User { // // private Integer id; // private String name; // private String password; // /** // * @return the id // */ // public Integer getId() { // return id; // } // /** // * @param id the id to set // */ // public void setId(Integer id) { // this.id = id; // } // /** // * @return the name // */ // public String getName() { // return name; // } // /** // * @param name the name to set // */ // public void setName(String name) { // this.name = name; // } // /** // * @return the password // */ // public String getPassword() { // return password; // } // /** // * @param password the password to set // */ // public void setPassword(String password) { // this.password = password; // } // } // // Path: src/main/java/dao/interfaces/UserDao.java // public interface UserDao extends BaseDao<User> { // // /** // * ¸ù¾ÝÓû§ÃûËÑË÷Óû§ // * // * @param name // * @return ²»´æÔÚʱ·µ»Ønull // */ // public abstract User get(String name); // }
import com.opensymphony.xwork2.ActionSupport; import dao.interfaces.UserDao; import bean.User; import com.opensymphony.xwork2.ActionContext;
/** * 2014Äê11ÔÂ10ÈÕ ÉÏÎç8:43:19 */ package action; /** * * * @author wavky.wand * */ public class UpdateAccountAction extends ActionSupport { private static final long serialVersionUID = 1L; private String name; private String password;
// Path: src/main/java/bean/User.java // public class User { // // private Integer id; // private String name; // private String password; // /** // * @return the id // */ // public Integer getId() { // return id; // } // /** // * @param id the id to set // */ // public void setId(Integer id) { // this.id = id; // } // /** // * @return the name // */ // public String getName() { // return name; // } // /** // * @param name the name to set // */ // public void setName(String name) { // this.name = name; // } // /** // * @return the password // */ // public String getPassword() { // return password; // } // /** // * @param password the password to set // */ // public void setPassword(String password) { // this.password = password; // } // } // // Path: src/main/java/dao/interfaces/UserDao.java // public interface UserDao extends BaseDao<User> { // // /** // * ¸ù¾ÝÓû§ÃûËÑË÷Óû§ // * // * @param name // * @return ²»´æÔÚʱ·µ»Ønull // */ // public abstract User get(String name); // } // Path: src/main/java/action/UpdateAccountAction.java import com.opensymphony.xwork2.ActionSupport; import dao.interfaces.UserDao; import bean.User; import com.opensymphony.xwork2.ActionContext; /** * 2014Äê11ÔÂ10ÈÕ ÉÏÎç8:43:19 */ package action; /** * * * @author wavky.wand * */ public class UpdateAccountAction extends ActionSupport { private static final long serialVersionUID = 1L; private String name; private String password;
private UserDao userDao;
wavky/WavkyHome
src/main/java/action/UpdateAccountAction.java
// Path: src/main/java/bean/User.java // public class User { // // private Integer id; // private String name; // private String password; // /** // * @return the id // */ // public Integer getId() { // return id; // } // /** // * @param id the id to set // */ // public void setId(Integer id) { // this.id = id; // } // /** // * @return the name // */ // public String getName() { // return name; // } // /** // * @param name the name to set // */ // public void setName(String name) { // this.name = name; // } // /** // * @return the password // */ // public String getPassword() { // return password; // } // /** // * @param password the password to set // */ // public void setPassword(String password) { // this.password = password; // } // } // // Path: src/main/java/dao/interfaces/UserDao.java // public interface UserDao extends BaseDao<User> { // // /** // * ¸ù¾ÝÓû§ÃûËÑË÷Óû§ // * // * @param name // * @return ²»´æÔÚʱ·µ»Ønull // */ // public abstract User get(String name); // }
import com.opensymphony.xwork2.ActionSupport; import dao.interfaces.UserDao; import bean.User; import com.opensymphony.xwork2.ActionContext;
/** * 2014Äê11ÔÂ10ÈÕ ÉÏÎç8:43:19 */ package action; /** * * * @author wavky.wand * */ public class UpdateAccountAction extends ActionSupport { private static final long serialVersionUID = 1L; private String name; private String password; private UserDao userDao; /** * @return the name */ public String getName() { return name; } /** * @param name * the name to set */ public void setName(String name) { this.name = name; } /** * @return the password */ public String getPassword() { return password; } /** * @param password * the password to set */ public void setPassword(String password) { this.password = password; } /** * @return the userDao */ public UserDao getUserDao() { return userDao; } /** * @param userDao * the userDao to set */ public void setUserDao(UserDao userDao) { this.userDao = userDao; } @Override public String execute() throws Exception { ActionContext ac = ActionContext.getContext();
// Path: src/main/java/bean/User.java // public class User { // // private Integer id; // private String name; // private String password; // /** // * @return the id // */ // public Integer getId() { // return id; // } // /** // * @param id the id to set // */ // public void setId(Integer id) { // this.id = id; // } // /** // * @return the name // */ // public String getName() { // return name; // } // /** // * @param name the name to set // */ // public void setName(String name) { // this.name = name; // } // /** // * @return the password // */ // public String getPassword() { // return password; // } // /** // * @param password the password to set // */ // public void setPassword(String password) { // this.password = password; // } // } // // Path: src/main/java/dao/interfaces/UserDao.java // public interface UserDao extends BaseDao<User> { // // /** // * ¸ù¾ÝÓû§ÃûËÑË÷Óû§ // * // * @param name // * @return ²»´æÔÚʱ·µ»Ønull // */ // public abstract User get(String name); // } // Path: src/main/java/action/UpdateAccountAction.java import com.opensymphony.xwork2.ActionSupport; import dao.interfaces.UserDao; import bean.User; import com.opensymphony.xwork2.ActionContext; /** * 2014Äê11ÔÂ10ÈÕ ÉÏÎç8:43:19 */ package action; /** * * * @author wavky.wand * */ public class UpdateAccountAction extends ActionSupport { private static final long serialVersionUID = 1L; private String name; private String password; private UserDao userDao; /** * @return the name */ public String getName() { return name; } /** * @param name * the name to set */ public void setName(String name) { this.name = name; } /** * @return the password */ public String getPassword() { return password; } /** * @param password * the password to set */ public void setPassword(String password) { this.password = password; } /** * @return the userDao */ public UserDao getUserDao() { return userDao; } /** * @param userDao * the userDao to set */ public void setUserDao(UserDao userDao) { this.userDao = userDao; } @Override public String execute() throws Exception { ActionContext ac = ActionContext.getContext();
User master = (User) ac.getSession().get("master");
RoseTec/JigSPuzzle
src/test/java/jigspuzzle/controller/SettingsControllerIT.java
// Path: src/main/java/jigspuzzle/JigSPuzzle.java // public class JigSPuzzle { // // private static JigSPuzzle instance; // // public static JigSPuzzle getInstance() { // if (instance == null) { // instance = new JigSPuzzle(); // } // return instance; // } // // /** // * @param args the command line arguments // */ // public static void main(String[] args) { // getInstance().startGame(); // } // // /** // * The main window, in which the user can play // */ // IPuzzleWindow puzzleWindow; // // /** // * The sound player, that can play sounds in the UI. // */ // ISoundPlayer soundPlayer; // // private JigSPuzzle() { // puzzleWindow = new PuzzleWindow(); // soundPlayer = new SoundPlayer(); // } // // /** // * Exits the complete program // */ // public void exitProgram() { // try { // System.exit(0); // } catch (Exception ex) { // // in the assertJ - tests it is not possible to exit... // // instead, we 'reset' this class and the controller. // resetInstances(); // } // } // // /** // * Returns the window on that the user can puzzle. // * // * @return // */ // public IPuzzleWindow getPuzzleWindow() { // return puzzleWindow; // } // // /** // * Returns the player, that is used for playing sounds on the UI. // * // * @return // */ // public ISoundPlayer getSoundPlayer() { // return soundPlayer; // } // // /** // * A methods that resets all instances to null. With this is is simulated, // * that the programm has exited. However, opened windows are still there. // * Terefore: Use only for tests. // * // * @deprecated Use only in tests. // */ // public void resetInstances() { // instance = null; // PuzzleController.getInstance().resetInstance(); // SettingsController.getInstance().resetInstance(); // VersionController.getInstance().resetInstance(); // } // // /** // * Sets the window on that the user can puzzle. // * // * @param puzzleWindow // * @deprecated Use only, in special cases, e.g. tests. // */ // public void setPuzzleWindow(IPuzzleWindow puzzleWindow) { // this.puzzleWindow = puzzleWindow; // } // // /** // * Starts the game and shows the user the UI. // */ // private void startGame() { // puzzleWindow.showPuzzleWindow(); // } // } // // Path: src/test/java/jigspuzzle/testutils/mockups/DummyMultiMonitorPuzzleWindow.java // public class DummyMultiMonitorPuzzleWindow implements IPuzzleWindow { // // Rectangle[] screens; // // public DummyMultiMonitorPuzzleWindow(Rectangle[] screens) { // this.screens = screens; // } // // @Override // public void bringToFront(PuzzlepieceGroup puzzlepieceGroup) { // } // // @Override // public void displayFatalError(String message) { // } // // @Override // public Rectangle[] getPuzzleareaBounds() { // return screens; // } // // @Override // public void showPuzzleWindow() { // } // // @Override // public void setNewPuzzle(Puzzle puzzle) { // } // // } // // Path: src/test/java/jigspuzzle/testutils/mockups/DummyPuzzleWindow.java // public class DummyPuzzleWindow implements IPuzzleWindow { // // int puzzleareaWidth; // int puzzleareaHeight; // // public DummyPuzzleWindow() { // this(1680, 1050); // } // // public DummyPuzzleWindow(int puzzleareaWidth, int puzzleareaHeight) { // this.puzzleareaWidth = puzzleareaWidth; // this.puzzleareaHeight = puzzleareaHeight; // } // // @Override // public void bringToFront(PuzzlepieceGroup puzzlepieceGroup) { // } // // @Override // public void displayFatalError(String message) { // } // // @Override // public Rectangle[] getPuzzleareaBounds() { // return new Rectangle[]{new Rectangle(0, 0, puzzleareaWidth, puzzleareaHeight)}; // } // // @Override // public void showPuzzleWindow() { // } // // @Override // public void setNewPuzzle(Puzzle puzzle) { // } // // }
import java.awt.Color; import java.awt.Dimension; import java.awt.Rectangle; import java.io.File; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import jigspuzzle.JigSPuzzle; import jigspuzzle.testutils.mockups.DummyMultiMonitorPuzzleWindow; import jigspuzzle.testutils.mockups.DummyPuzzleWindow; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*;
package jigspuzzle.controller; public class SettingsControllerIT { public SettingsControllerIT() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { File file = new File(SettingsController.SETTINGS_FILE_NAME); file.delete(); } @After public void tearDown() { File file = new File(SettingsController.SETTINGS_FILE_NAME); file.delete(); // reset all controllers
// Path: src/main/java/jigspuzzle/JigSPuzzle.java // public class JigSPuzzle { // // private static JigSPuzzle instance; // // public static JigSPuzzle getInstance() { // if (instance == null) { // instance = new JigSPuzzle(); // } // return instance; // } // // /** // * @param args the command line arguments // */ // public static void main(String[] args) { // getInstance().startGame(); // } // // /** // * The main window, in which the user can play // */ // IPuzzleWindow puzzleWindow; // // /** // * The sound player, that can play sounds in the UI. // */ // ISoundPlayer soundPlayer; // // private JigSPuzzle() { // puzzleWindow = new PuzzleWindow(); // soundPlayer = new SoundPlayer(); // } // // /** // * Exits the complete program // */ // public void exitProgram() { // try { // System.exit(0); // } catch (Exception ex) { // // in the assertJ - tests it is not possible to exit... // // instead, we 'reset' this class and the controller. // resetInstances(); // } // } // // /** // * Returns the window on that the user can puzzle. // * // * @return // */ // public IPuzzleWindow getPuzzleWindow() { // return puzzleWindow; // } // // /** // * Returns the player, that is used for playing sounds on the UI. // * // * @return // */ // public ISoundPlayer getSoundPlayer() { // return soundPlayer; // } // // /** // * A methods that resets all instances to null. With this is is simulated, // * that the programm has exited. However, opened windows are still there. // * Terefore: Use only for tests. // * // * @deprecated Use only in tests. // */ // public void resetInstances() { // instance = null; // PuzzleController.getInstance().resetInstance(); // SettingsController.getInstance().resetInstance(); // VersionController.getInstance().resetInstance(); // } // // /** // * Sets the window on that the user can puzzle. // * // * @param puzzleWindow // * @deprecated Use only, in special cases, e.g. tests. // */ // public void setPuzzleWindow(IPuzzleWindow puzzleWindow) { // this.puzzleWindow = puzzleWindow; // } // // /** // * Starts the game and shows the user the UI. // */ // private void startGame() { // puzzleWindow.showPuzzleWindow(); // } // } // // Path: src/test/java/jigspuzzle/testutils/mockups/DummyMultiMonitorPuzzleWindow.java // public class DummyMultiMonitorPuzzleWindow implements IPuzzleWindow { // // Rectangle[] screens; // // public DummyMultiMonitorPuzzleWindow(Rectangle[] screens) { // this.screens = screens; // } // // @Override // public void bringToFront(PuzzlepieceGroup puzzlepieceGroup) { // } // // @Override // public void displayFatalError(String message) { // } // // @Override // public Rectangle[] getPuzzleareaBounds() { // return screens; // } // // @Override // public void showPuzzleWindow() { // } // // @Override // public void setNewPuzzle(Puzzle puzzle) { // } // // } // // Path: src/test/java/jigspuzzle/testutils/mockups/DummyPuzzleWindow.java // public class DummyPuzzleWindow implements IPuzzleWindow { // // int puzzleareaWidth; // int puzzleareaHeight; // // public DummyPuzzleWindow() { // this(1680, 1050); // } // // public DummyPuzzleWindow(int puzzleareaWidth, int puzzleareaHeight) { // this.puzzleareaWidth = puzzleareaWidth; // this.puzzleareaHeight = puzzleareaHeight; // } // // @Override // public void bringToFront(PuzzlepieceGroup puzzlepieceGroup) { // } // // @Override // public void displayFatalError(String message) { // } // // @Override // public Rectangle[] getPuzzleareaBounds() { // return new Rectangle[]{new Rectangle(0, 0, puzzleareaWidth, puzzleareaHeight)}; // } // // @Override // public void showPuzzleWindow() { // } // // @Override // public void setNewPuzzle(Puzzle puzzle) { // } // // } // Path: src/test/java/jigspuzzle/controller/SettingsControllerIT.java import java.awt.Color; import java.awt.Dimension; import java.awt.Rectangle; import java.io.File; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import jigspuzzle.JigSPuzzle; import jigspuzzle.testutils.mockups.DummyMultiMonitorPuzzleWindow; import jigspuzzle.testutils.mockups.DummyPuzzleWindow; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; package jigspuzzle.controller; public class SettingsControllerIT { public SettingsControllerIT() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { File file = new File(SettingsController.SETTINGS_FILE_NAME); file.delete(); } @After public void tearDown() { File file = new File(SettingsController.SETTINGS_FILE_NAME); file.delete(); // reset all controllers
JigSPuzzle.getInstance().resetInstances();
RoseTec/JigSPuzzle
src/test/java/jigspuzzle/controller/SettingsControllerIT.java
// Path: src/main/java/jigspuzzle/JigSPuzzle.java // public class JigSPuzzle { // // private static JigSPuzzle instance; // // public static JigSPuzzle getInstance() { // if (instance == null) { // instance = new JigSPuzzle(); // } // return instance; // } // // /** // * @param args the command line arguments // */ // public static void main(String[] args) { // getInstance().startGame(); // } // // /** // * The main window, in which the user can play // */ // IPuzzleWindow puzzleWindow; // // /** // * The sound player, that can play sounds in the UI. // */ // ISoundPlayer soundPlayer; // // private JigSPuzzle() { // puzzleWindow = new PuzzleWindow(); // soundPlayer = new SoundPlayer(); // } // // /** // * Exits the complete program // */ // public void exitProgram() { // try { // System.exit(0); // } catch (Exception ex) { // // in the assertJ - tests it is not possible to exit... // // instead, we 'reset' this class and the controller. // resetInstances(); // } // } // // /** // * Returns the window on that the user can puzzle. // * // * @return // */ // public IPuzzleWindow getPuzzleWindow() { // return puzzleWindow; // } // // /** // * Returns the player, that is used for playing sounds on the UI. // * // * @return // */ // public ISoundPlayer getSoundPlayer() { // return soundPlayer; // } // // /** // * A methods that resets all instances to null. With this is is simulated, // * that the programm has exited. However, opened windows are still there. // * Terefore: Use only for tests. // * // * @deprecated Use only in tests. // */ // public void resetInstances() { // instance = null; // PuzzleController.getInstance().resetInstance(); // SettingsController.getInstance().resetInstance(); // VersionController.getInstance().resetInstance(); // } // // /** // * Sets the window on that the user can puzzle. // * // * @param puzzleWindow // * @deprecated Use only, in special cases, e.g. tests. // */ // public void setPuzzleWindow(IPuzzleWindow puzzleWindow) { // this.puzzleWindow = puzzleWindow; // } // // /** // * Starts the game and shows the user the UI. // */ // private void startGame() { // puzzleWindow.showPuzzleWindow(); // } // } // // Path: src/test/java/jigspuzzle/testutils/mockups/DummyMultiMonitorPuzzleWindow.java // public class DummyMultiMonitorPuzzleWindow implements IPuzzleWindow { // // Rectangle[] screens; // // public DummyMultiMonitorPuzzleWindow(Rectangle[] screens) { // this.screens = screens; // } // // @Override // public void bringToFront(PuzzlepieceGroup puzzlepieceGroup) { // } // // @Override // public void displayFatalError(String message) { // } // // @Override // public Rectangle[] getPuzzleareaBounds() { // return screens; // } // // @Override // public void showPuzzleWindow() { // } // // @Override // public void setNewPuzzle(Puzzle puzzle) { // } // // } // // Path: src/test/java/jigspuzzle/testutils/mockups/DummyPuzzleWindow.java // public class DummyPuzzleWindow implements IPuzzleWindow { // // int puzzleareaWidth; // int puzzleareaHeight; // // public DummyPuzzleWindow() { // this(1680, 1050); // } // // public DummyPuzzleWindow(int puzzleareaWidth, int puzzleareaHeight) { // this.puzzleareaWidth = puzzleareaWidth; // this.puzzleareaHeight = puzzleareaHeight; // } // // @Override // public void bringToFront(PuzzlepieceGroup puzzlepieceGroup) { // } // // @Override // public void displayFatalError(String message) { // } // // @Override // public Rectangle[] getPuzzleareaBounds() { // return new Rectangle[]{new Rectangle(0, 0, puzzleareaWidth, puzzleareaHeight)}; // } // // @Override // public void showPuzzleWindow() { // } // // @Override // public void setNewPuzzle(Puzzle puzzle) { // } // // }
import java.awt.Color; import java.awt.Dimension; import java.awt.Rectangle; import java.io.File; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import jigspuzzle.JigSPuzzle; import jigspuzzle.testutils.mockups.DummyMultiMonitorPuzzleWindow; import jigspuzzle.testutils.mockups.DummyPuzzleWindow; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*;
@Before public void setUp() { File file = new File(SettingsController.SETTINGS_FILE_NAME); file.delete(); } @After public void tearDown() { File file = new File(SettingsController.SETTINGS_FILE_NAME); file.delete(); // reset all controllers JigSPuzzle.getInstance().resetInstances(); } @Test public void testGetPuzzlepieceSize() { SettingsController instance = SettingsController.getInstance(); instance.setDecreasePuzzleAutomatically(true); instance.setUsedSizeOfPuzzlearea(1); int puzzleareaHeight = 1000; int puzzleareaWidth = 1500; int puzzleHeight = 2000; int puzzleWidth = 2000; int puzzleRows = 4; int puzzleColumns = 4;
// Path: src/main/java/jigspuzzle/JigSPuzzle.java // public class JigSPuzzle { // // private static JigSPuzzle instance; // // public static JigSPuzzle getInstance() { // if (instance == null) { // instance = new JigSPuzzle(); // } // return instance; // } // // /** // * @param args the command line arguments // */ // public static void main(String[] args) { // getInstance().startGame(); // } // // /** // * The main window, in which the user can play // */ // IPuzzleWindow puzzleWindow; // // /** // * The sound player, that can play sounds in the UI. // */ // ISoundPlayer soundPlayer; // // private JigSPuzzle() { // puzzleWindow = new PuzzleWindow(); // soundPlayer = new SoundPlayer(); // } // // /** // * Exits the complete program // */ // public void exitProgram() { // try { // System.exit(0); // } catch (Exception ex) { // // in the assertJ - tests it is not possible to exit... // // instead, we 'reset' this class and the controller. // resetInstances(); // } // } // // /** // * Returns the window on that the user can puzzle. // * // * @return // */ // public IPuzzleWindow getPuzzleWindow() { // return puzzleWindow; // } // // /** // * Returns the player, that is used for playing sounds on the UI. // * // * @return // */ // public ISoundPlayer getSoundPlayer() { // return soundPlayer; // } // // /** // * A methods that resets all instances to null. With this is is simulated, // * that the programm has exited. However, opened windows are still there. // * Terefore: Use only for tests. // * // * @deprecated Use only in tests. // */ // public void resetInstances() { // instance = null; // PuzzleController.getInstance().resetInstance(); // SettingsController.getInstance().resetInstance(); // VersionController.getInstance().resetInstance(); // } // // /** // * Sets the window on that the user can puzzle. // * // * @param puzzleWindow // * @deprecated Use only, in special cases, e.g. tests. // */ // public void setPuzzleWindow(IPuzzleWindow puzzleWindow) { // this.puzzleWindow = puzzleWindow; // } // // /** // * Starts the game and shows the user the UI. // */ // private void startGame() { // puzzleWindow.showPuzzleWindow(); // } // } // // Path: src/test/java/jigspuzzle/testutils/mockups/DummyMultiMonitorPuzzleWindow.java // public class DummyMultiMonitorPuzzleWindow implements IPuzzleWindow { // // Rectangle[] screens; // // public DummyMultiMonitorPuzzleWindow(Rectangle[] screens) { // this.screens = screens; // } // // @Override // public void bringToFront(PuzzlepieceGroup puzzlepieceGroup) { // } // // @Override // public void displayFatalError(String message) { // } // // @Override // public Rectangle[] getPuzzleareaBounds() { // return screens; // } // // @Override // public void showPuzzleWindow() { // } // // @Override // public void setNewPuzzle(Puzzle puzzle) { // } // // } // // Path: src/test/java/jigspuzzle/testutils/mockups/DummyPuzzleWindow.java // public class DummyPuzzleWindow implements IPuzzleWindow { // // int puzzleareaWidth; // int puzzleareaHeight; // // public DummyPuzzleWindow() { // this(1680, 1050); // } // // public DummyPuzzleWindow(int puzzleareaWidth, int puzzleareaHeight) { // this.puzzleareaWidth = puzzleareaWidth; // this.puzzleareaHeight = puzzleareaHeight; // } // // @Override // public void bringToFront(PuzzlepieceGroup puzzlepieceGroup) { // } // // @Override // public void displayFatalError(String message) { // } // // @Override // public Rectangle[] getPuzzleareaBounds() { // return new Rectangle[]{new Rectangle(0, 0, puzzleareaWidth, puzzleareaHeight)}; // } // // @Override // public void showPuzzleWindow() { // } // // @Override // public void setNewPuzzle(Puzzle puzzle) { // } // // } // Path: src/test/java/jigspuzzle/controller/SettingsControllerIT.java import java.awt.Color; import java.awt.Dimension; import java.awt.Rectangle; import java.io.File; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import jigspuzzle.JigSPuzzle; import jigspuzzle.testutils.mockups.DummyMultiMonitorPuzzleWindow; import jigspuzzle.testutils.mockups.DummyPuzzleWindow; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; @Before public void setUp() { File file = new File(SettingsController.SETTINGS_FILE_NAME); file.delete(); } @After public void tearDown() { File file = new File(SettingsController.SETTINGS_FILE_NAME); file.delete(); // reset all controllers JigSPuzzle.getInstance().resetInstances(); } @Test public void testGetPuzzlepieceSize() { SettingsController instance = SettingsController.getInstance(); instance.setDecreasePuzzleAutomatically(true); instance.setUsedSizeOfPuzzlearea(1); int puzzleareaHeight = 1000; int puzzleareaWidth = 1500; int puzzleHeight = 2000; int puzzleWidth = 2000; int puzzleRows = 4; int puzzleColumns = 4;
JigSPuzzle.getInstance().setPuzzleWindow(new DummyPuzzleWindow(puzzleareaWidth, puzzleareaHeight));
RoseTec/JigSPuzzle
src/test/java/jigspuzzle/controller/SettingsControllerIT.java
// Path: src/main/java/jigspuzzle/JigSPuzzle.java // public class JigSPuzzle { // // private static JigSPuzzle instance; // // public static JigSPuzzle getInstance() { // if (instance == null) { // instance = new JigSPuzzle(); // } // return instance; // } // // /** // * @param args the command line arguments // */ // public static void main(String[] args) { // getInstance().startGame(); // } // // /** // * The main window, in which the user can play // */ // IPuzzleWindow puzzleWindow; // // /** // * The sound player, that can play sounds in the UI. // */ // ISoundPlayer soundPlayer; // // private JigSPuzzle() { // puzzleWindow = new PuzzleWindow(); // soundPlayer = new SoundPlayer(); // } // // /** // * Exits the complete program // */ // public void exitProgram() { // try { // System.exit(0); // } catch (Exception ex) { // // in the assertJ - tests it is not possible to exit... // // instead, we 'reset' this class and the controller. // resetInstances(); // } // } // // /** // * Returns the window on that the user can puzzle. // * // * @return // */ // public IPuzzleWindow getPuzzleWindow() { // return puzzleWindow; // } // // /** // * Returns the player, that is used for playing sounds on the UI. // * // * @return // */ // public ISoundPlayer getSoundPlayer() { // return soundPlayer; // } // // /** // * A methods that resets all instances to null. With this is is simulated, // * that the programm has exited. However, opened windows are still there. // * Terefore: Use only for tests. // * // * @deprecated Use only in tests. // */ // public void resetInstances() { // instance = null; // PuzzleController.getInstance().resetInstance(); // SettingsController.getInstance().resetInstance(); // VersionController.getInstance().resetInstance(); // } // // /** // * Sets the window on that the user can puzzle. // * // * @param puzzleWindow // * @deprecated Use only, in special cases, e.g. tests. // */ // public void setPuzzleWindow(IPuzzleWindow puzzleWindow) { // this.puzzleWindow = puzzleWindow; // } // // /** // * Starts the game and shows the user the UI. // */ // private void startGame() { // puzzleWindow.showPuzzleWindow(); // } // } // // Path: src/test/java/jigspuzzle/testutils/mockups/DummyMultiMonitorPuzzleWindow.java // public class DummyMultiMonitorPuzzleWindow implements IPuzzleWindow { // // Rectangle[] screens; // // public DummyMultiMonitorPuzzleWindow(Rectangle[] screens) { // this.screens = screens; // } // // @Override // public void bringToFront(PuzzlepieceGroup puzzlepieceGroup) { // } // // @Override // public void displayFatalError(String message) { // } // // @Override // public Rectangle[] getPuzzleareaBounds() { // return screens; // } // // @Override // public void showPuzzleWindow() { // } // // @Override // public void setNewPuzzle(Puzzle puzzle) { // } // // } // // Path: src/test/java/jigspuzzle/testutils/mockups/DummyPuzzleWindow.java // public class DummyPuzzleWindow implements IPuzzleWindow { // // int puzzleareaWidth; // int puzzleareaHeight; // // public DummyPuzzleWindow() { // this(1680, 1050); // } // // public DummyPuzzleWindow(int puzzleareaWidth, int puzzleareaHeight) { // this.puzzleareaWidth = puzzleareaWidth; // this.puzzleareaHeight = puzzleareaHeight; // } // // @Override // public void bringToFront(PuzzlepieceGroup puzzlepieceGroup) { // } // // @Override // public void displayFatalError(String message) { // } // // @Override // public Rectangle[] getPuzzleareaBounds() { // return new Rectangle[]{new Rectangle(0, 0, puzzleareaWidth, puzzleareaHeight)}; // } // // @Override // public void showPuzzleWindow() { // } // // @Override // public void setNewPuzzle(Puzzle puzzle) { // } // // }
import java.awt.Color; import java.awt.Dimension; import java.awt.Rectangle; import java.io.File; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import jigspuzzle.JigSPuzzle; import jigspuzzle.testutils.mockups.DummyMultiMonitorPuzzleWindow; import jigspuzzle.testutils.mockups.DummyPuzzleWindow; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*;
instance.setEnlargePuzzleAutomatically(false); instance.setUsedSizeOfPuzzlearea(1); int puzzleareaHeight = 1500; int puzzleareaWidth = 2000; int puzzleHeight = 500; int puzzleWidth = 1000; int puzzleRows = 2; int puzzleColumns = 4; JigSPuzzle.getInstance().setPuzzleWindow(new DummyPuzzleWindow(puzzleareaWidth, puzzleareaHeight)); Dimension result = instance.getPuzzlepieceSize(puzzleHeight, puzzleWidth, puzzleRows, puzzleColumns); assertEquals(250, result.height); assertEquals(250, result.width); } @Test public void testGetPuzzlepieceSize15() { Rectangle[] screens = new Rectangle[3]; SettingsController instance = SettingsController.getInstance(); instance.setEnlargePuzzleAutomatically(true); instance.setUsedSizeOfPuzzlearea(1); int puzzleHeight = 500; int puzzleWidth = 1000; int puzzleRows = 2; int puzzleColumns = 4; screens[0] = new Rectangle(-1680, 0, 1680, 1050); screens[1] = new Rectangle(0, 0, 2000, 1500); screens[2] = new Rectangle(2000, 10, 1680, 1050);
// Path: src/main/java/jigspuzzle/JigSPuzzle.java // public class JigSPuzzle { // // private static JigSPuzzle instance; // // public static JigSPuzzle getInstance() { // if (instance == null) { // instance = new JigSPuzzle(); // } // return instance; // } // // /** // * @param args the command line arguments // */ // public static void main(String[] args) { // getInstance().startGame(); // } // // /** // * The main window, in which the user can play // */ // IPuzzleWindow puzzleWindow; // // /** // * The sound player, that can play sounds in the UI. // */ // ISoundPlayer soundPlayer; // // private JigSPuzzle() { // puzzleWindow = new PuzzleWindow(); // soundPlayer = new SoundPlayer(); // } // // /** // * Exits the complete program // */ // public void exitProgram() { // try { // System.exit(0); // } catch (Exception ex) { // // in the assertJ - tests it is not possible to exit... // // instead, we 'reset' this class and the controller. // resetInstances(); // } // } // // /** // * Returns the window on that the user can puzzle. // * // * @return // */ // public IPuzzleWindow getPuzzleWindow() { // return puzzleWindow; // } // // /** // * Returns the player, that is used for playing sounds on the UI. // * // * @return // */ // public ISoundPlayer getSoundPlayer() { // return soundPlayer; // } // // /** // * A methods that resets all instances to null. With this is is simulated, // * that the programm has exited. However, opened windows are still there. // * Terefore: Use only for tests. // * // * @deprecated Use only in tests. // */ // public void resetInstances() { // instance = null; // PuzzleController.getInstance().resetInstance(); // SettingsController.getInstance().resetInstance(); // VersionController.getInstance().resetInstance(); // } // // /** // * Sets the window on that the user can puzzle. // * // * @param puzzleWindow // * @deprecated Use only, in special cases, e.g. tests. // */ // public void setPuzzleWindow(IPuzzleWindow puzzleWindow) { // this.puzzleWindow = puzzleWindow; // } // // /** // * Starts the game and shows the user the UI. // */ // private void startGame() { // puzzleWindow.showPuzzleWindow(); // } // } // // Path: src/test/java/jigspuzzle/testutils/mockups/DummyMultiMonitorPuzzleWindow.java // public class DummyMultiMonitorPuzzleWindow implements IPuzzleWindow { // // Rectangle[] screens; // // public DummyMultiMonitorPuzzleWindow(Rectangle[] screens) { // this.screens = screens; // } // // @Override // public void bringToFront(PuzzlepieceGroup puzzlepieceGroup) { // } // // @Override // public void displayFatalError(String message) { // } // // @Override // public Rectangle[] getPuzzleareaBounds() { // return screens; // } // // @Override // public void showPuzzleWindow() { // } // // @Override // public void setNewPuzzle(Puzzle puzzle) { // } // // } // // Path: src/test/java/jigspuzzle/testutils/mockups/DummyPuzzleWindow.java // public class DummyPuzzleWindow implements IPuzzleWindow { // // int puzzleareaWidth; // int puzzleareaHeight; // // public DummyPuzzleWindow() { // this(1680, 1050); // } // // public DummyPuzzleWindow(int puzzleareaWidth, int puzzleareaHeight) { // this.puzzleareaWidth = puzzleareaWidth; // this.puzzleareaHeight = puzzleareaHeight; // } // // @Override // public void bringToFront(PuzzlepieceGroup puzzlepieceGroup) { // } // // @Override // public void displayFatalError(String message) { // } // // @Override // public Rectangle[] getPuzzleareaBounds() { // return new Rectangle[]{new Rectangle(0, 0, puzzleareaWidth, puzzleareaHeight)}; // } // // @Override // public void showPuzzleWindow() { // } // // @Override // public void setNewPuzzle(Puzzle puzzle) { // } // // } // Path: src/test/java/jigspuzzle/controller/SettingsControllerIT.java import java.awt.Color; import java.awt.Dimension; import java.awt.Rectangle; import java.io.File; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import jigspuzzle.JigSPuzzle; import jigspuzzle.testutils.mockups.DummyMultiMonitorPuzzleWindow; import jigspuzzle.testutils.mockups.DummyPuzzleWindow; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; instance.setEnlargePuzzleAutomatically(false); instance.setUsedSizeOfPuzzlearea(1); int puzzleareaHeight = 1500; int puzzleareaWidth = 2000; int puzzleHeight = 500; int puzzleWidth = 1000; int puzzleRows = 2; int puzzleColumns = 4; JigSPuzzle.getInstance().setPuzzleWindow(new DummyPuzzleWindow(puzzleareaWidth, puzzleareaHeight)); Dimension result = instance.getPuzzlepieceSize(puzzleHeight, puzzleWidth, puzzleRows, puzzleColumns); assertEquals(250, result.height); assertEquals(250, result.width); } @Test public void testGetPuzzlepieceSize15() { Rectangle[] screens = new Rectangle[3]; SettingsController instance = SettingsController.getInstance(); instance.setEnlargePuzzleAutomatically(true); instance.setUsedSizeOfPuzzlearea(1); int puzzleHeight = 500; int puzzleWidth = 1000; int puzzleRows = 2; int puzzleColumns = 4; screens[0] = new Rectangle(-1680, 0, 1680, 1050); screens[1] = new Rectangle(0, 0, 2000, 1500); screens[2] = new Rectangle(2000, 10, 1680, 1050);
JigSPuzzle.getInstance().setPuzzleWindow(new DummyMultiMonitorPuzzleWindow(screens));
RoseTec/JigSPuzzle
src/main/java/jigspuzzle/view/ImageGetter.java
// Path: src/main/java/jigspuzzle/JigSPuzzleResources.java // public class JigSPuzzleResources { // // /** // * Gets the resourse in the given path // * // * @param resourcePath The path for the resource. It should start width a // * <code>/</code> // * @return // */ // public static URL getResource(String resourcePath) { // if (!resourcePath.startsWith("/")) { // resourcePath = "/" + resourcePath; // } // // URL ret = JigSPuzzleResources.class.getResource(resourcePath); // if (ret != null) { // return ret; // } // // // seach also for files // File file = new File(resourcePath.substring(1)); // if (file.exists()) { // try { // return file.toURI().toURL(); // } catch (MalformedURLException ex) { // } // } // return null; // } // // /** // * Gets a stream of the the resourse in the given path. // * // * @param resourcePath The path for the resource. It should start width a // * <code>/</code> // * @return // */ // public static InputStream getResourceAsStream(String resourcePath) { // if (!resourcePath.startsWith("/")) { // resourcePath = "/" + resourcePath; // } // // InputStream ret = JigSPuzzleResources.class.getResourceAsStream(resourcePath); // if (ret != null) { // return ret; // } // // // seach also for files // File file = new File(resourcePath.substring(1)); // if (file.exists()) { // try { // return file.toURI().toURL().openStream(); // } catch (MalformedURLException ex) { // } catch (IOException ex) { // } // } // return null; // } // // /** // * Gets a list of all files in the given path. It does not matter, if it is // * cntained in a jar-file or not. // * // * @param path // * @return // */ // public static List<String> getResourcesInPath(String path) { // try { // return Arrays.asList(getResourceListing(JigSPuzzle.class, path)); // } catch (URISyntaxException | IOException ex) { // return new ArrayList<>(); // } // } // // /** // * List directory contents for a resource folder. Not recursive. This is // * basically a brute-force implementation. Works for regular files and also // * JARs. // * // * Source: // * http://stackoverflow.com/questions/6247144/how-to-load-a-folder-from-a-jar // * // * @author Greg Briggs // * @param clazz Any java class that lives in the same place as the resources // * you want. // * @param path Should end with "/" and start with one. // * @return Just the name of each member item, not the full paths. // * @throws URISyntaxException // * @throws IOException // */ // private static String[] getResourceListing(Class clazz, String path) throws URISyntaxException, IOException { // URL dirURL = clazz.getResource(path); // if (dirURL != null && dirURL.getProtocol().equals("file")) { // /* A file path: easy enough */ // return new File(dirURL.toURI()).list(); // } // // path = path.substring(1); // if (dirURL == null) { // /* // * In case of a jar file, we can't actually find a directory. // * Have to assume the same jar as clazz. // */ // String me = clazz.getName().replace(".", "/") + ".class"; // dirURL = clazz.getClassLoader().getResource(me); // } // // if (dirURL.getProtocol().equals("jar")) { // /* A JAR path */ // String jarPath = dirURL.getPath().substring(5, dirURL.getPath().indexOf("!")); //strip out only the JAR file // JarFile jar = new JarFile(URLDecoder.decode(jarPath, "UTF-8")); // Enumeration<JarEntry> entries = jar.entries(); //gives ALL entries in jar // Set<String> result = new HashSet<String>(); //avoid duplicates in case it is a subdirectory // while (entries.hasMoreElements()) { // String name = entries.nextElement().getName(); // if (name.startsWith(path)) { //filter according to the path // String entry = name.substring(path.length()); // int checkSubdir = entry.indexOf("/"); // if (checkSubdir >= 0) { // // if it is a subdirectory, we just return the directory name // entry = entry.substring(0, checkSubdir); // } // result.add(entry); // } // } // return result.toArray(new String[result.size()]); // } // // throw new UnsupportedOperationException("Cannot list files for URL " + dirURL); // } // // }
import java.awt.Image; import java.awt.Toolkit; import java.io.IOException; import java.net.URL; import javax.imageio.ImageIO; import jigspuzzle.JigSPuzzleResources;
/** * @return The image used for restarting the current puzzle. */ public Image getRestartImage() { return getImage("restart_puzzle.png"); } /** * @return The image used for saving a puzzle to the hdd. * @see #getLoadImage() */ public Image getSaveImage() { return getImage("save.png"); } /** * @return The image used for displaying settings. */ public Image getSettingsImage() { return getImage("settings.png"); } /** * @return The image used for shuffleing the puzzlepieces. */ public Image getShuffleImage() { return getImage("shuffle_puzzlepieces.png"); } private Image getImage(String imageName) {
// Path: src/main/java/jigspuzzle/JigSPuzzleResources.java // public class JigSPuzzleResources { // // /** // * Gets the resourse in the given path // * // * @param resourcePath The path for the resource. It should start width a // * <code>/</code> // * @return // */ // public static URL getResource(String resourcePath) { // if (!resourcePath.startsWith("/")) { // resourcePath = "/" + resourcePath; // } // // URL ret = JigSPuzzleResources.class.getResource(resourcePath); // if (ret != null) { // return ret; // } // // // seach also for files // File file = new File(resourcePath.substring(1)); // if (file.exists()) { // try { // return file.toURI().toURL(); // } catch (MalformedURLException ex) { // } // } // return null; // } // // /** // * Gets a stream of the the resourse in the given path. // * // * @param resourcePath The path for the resource. It should start width a // * <code>/</code> // * @return // */ // public static InputStream getResourceAsStream(String resourcePath) { // if (!resourcePath.startsWith("/")) { // resourcePath = "/" + resourcePath; // } // // InputStream ret = JigSPuzzleResources.class.getResourceAsStream(resourcePath); // if (ret != null) { // return ret; // } // // // seach also for files // File file = new File(resourcePath.substring(1)); // if (file.exists()) { // try { // return file.toURI().toURL().openStream(); // } catch (MalformedURLException ex) { // } catch (IOException ex) { // } // } // return null; // } // // /** // * Gets a list of all files in the given path. It does not matter, if it is // * cntained in a jar-file or not. // * // * @param path // * @return // */ // public static List<String> getResourcesInPath(String path) { // try { // return Arrays.asList(getResourceListing(JigSPuzzle.class, path)); // } catch (URISyntaxException | IOException ex) { // return new ArrayList<>(); // } // } // // /** // * List directory contents for a resource folder. Not recursive. This is // * basically a brute-force implementation. Works for regular files and also // * JARs. // * // * Source: // * http://stackoverflow.com/questions/6247144/how-to-load-a-folder-from-a-jar // * // * @author Greg Briggs // * @param clazz Any java class that lives in the same place as the resources // * you want. // * @param path Should end with "/" and start with one. // * @return Just the name of each member item, not the full paths. // * @throws URISyntaxException // * @throws IOException // */ // private static String[] getResourceListing(Class clazz, String path) throws URISyntaxException, IOException { // URL dirURL = clazz.getResource(path); // if (dirURL != null && dirURL.getProtocol().equals("file")) { // /* A file path: easy enough */ // return new File(dirURL.toURI()).list(); // } // // path = path.substring(1); // if (dirURL == null) { // /* // * In case of a jar file, we can't actually find a directory. // * Have to assume the same jar as clazz. // */ // String me = clazz.getName().replace(".", "/") + ".class"; // dirURL = clazz.getClassLoader().getResource(me); // } // // if (dirURL.getProtocol().equals("jar")) { // /* A JAR path */ // String jarPath = dirURL.getPath().substring(5, dirURL.getPath().indexOf("!")); //strip out only the JAR file // JarFile jar = new JarFile(URLDecoder.decode(jarPath, "UTF-8")); // Enumeration<JarEntry> entries = jar.entries(); //gives ALL entries in jar // Set<String> result = new HashSet<String>(); //avoid duplicates in case it is a subdirectory // while (entries.hasMoreElements()) { // String name = entries.nextElement().getName(); // if (name.startsWith(path)) { //filter according to the path // String entry = name.substring(path.length()); // int checkSubdir = entry.indexOf("/"); // if (checkSubdir >= 0) { // // if it is a subdirectory, we just return the directory name // entry = entry.substring(0, checkSubdir); // } // result.add(entry); // } // } // return result.toArray(new String[result.size()]); // } // // throw new UnsupportedOperationException("Cannot list files for URL " + dirURL); // } // // } // Path: src/main/java/jigspuzzle/view/ImageGetter.java import java.awt.Image; import java.awt.Toolkit; import java.io.IOException; import java.net.URL; import javax.imageio.ImageIO; import jigspuzzle.JigSPuzzleResources; /** * @return The image used for restarting the current puzzle. */ public Image getRestartImage() { return getImage("restart_puzzle.png"); } /** * @return The image used for saving a puzzle to the hdd. * @see #getLoadImage() */ public Image getSaveImage() { return getImage("save.png"); } /** * @return The image used for displaying settings. */ public Image getSettingsImage() { return getImage("settings.png"); } /** * @return The image used for shuffleing the puzzlepieces. */ public Image getShuffleImage() { return getImage("shuffle_puzzlepieces.png"); } private Image getImage(String imageName) {
URL url = JigSPuzzleResources.getResource("/images/" + imageName);
RoseTec/JigSPuzzle
src/test/java/jigspuzzle/cucumber/steps/WindowsSteps.java
// Path: src/main/java/jigspuzzle/JigSPuzzle.java // public class JigSPuzzle { // // private static JigSPuzzle instance; // // public static JigSPuzzle getInstance() { // if (instance == null) { // instance = new JigSPuzzle(); // } // return instance; // } // // /** // * @param args the command line arguments // */ // public static void main(String[] args) { // getInstance().startGame(); // } // // /** // * The main window, in which the user can play // */ // IPuzzleWindow puzzleWindow; // // /** // * The sound player, that can play sounds in the UI. // */ // ISoundPlayer soundPlayer; // // private JigSPuzzle() { // puzzleWindow = new PuzzleWindow(); // soundPlayer = new SoundPlayer(); // } // // /** // * Exits the complete program // */ // public void exitProgram() { // try { // System.exit(0); // } catch (Exception ex) { // // in the assertJ - tests it is not possible to exit... // // instead, we 'reset' this class and the controller. // resetInstances(); // } // } // // /** // * Returns the window on that the user can puzzle. // * // * @return // */ // public IPuzzleWindow getPuzzleWindow() { // return puzzleWindow; // } // // /** // * Returns the player, that is used for playing sounds on the UI. // * // * @return // */ // public ISoundPlayer getSoundPlayer() { // return soundPlayer; // } // // /** // * A methods that resets all instances to null. With this is is simulated, // * that the programm has exited. However, opened windows are still there. // * Terefore: Use only for tests. // * // * @deprecated Use only in tests. // */ // public void resetInstances() { // instance = null; // PuzzleController.getInstance().resetInstance(); // SettingsController.getInstance().resetInstance(); // VersionController.getInstance().resetInstance(); // } // // /** // * Sets the window on that the user can puzzle. // * // * @param puzzleWindow // * @deprecated Use only, in special cases, e.g. tests. // */ // public void setPuzzleWindow(IPuzzleWindow puzzleWindow) { // this.puzzleWindow = puzzleWindow; // } // // /** // * Starts the game and shows the user the UI. // */ // private void startGame() { // puzzleWindow.showPuzzleWindow(); // } // }
import cucumber.api.PendingException; import cucumber.api.java.After; import cucumber.api.java.Before; import cucumber.api.java.en.*; import java.awt.Dimension; import java.awt.Frame; import java.awt.GraphicsDevice; import java.awt.GraphicsEnvironment; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JPopupMenu; import jigspuzzle.JigSPuzzle; import org.assertj.core.api.Assertions; import org.assertj.swing.core.BasicRobot; import org.assertj.swing.core.GenericTypeMatcher; import org.assertj.swing.core.Robot; import org.assertj.swing.data.Index; import org.assertj.swing.fixture.DialogFixture; import org.assertj.swing.fixture.FrameFixture; import org.assertj.swing.security.NoExitSecurityManagerInstaller; import static org.assertj.swing.finder.WindowFinder.findDialog; import static org.assertj.swing.finder.WindowFinder.findFrame; import org.assertj.swing.fixture.AbstractWindowFixture; import static org.assertj.swing.launcher.ApplicationLauncher.application;
@Before public void setUp() { // FailOnThreadViolationRepaintManager.install(); noExitSecurityManagerInstaller = NoExitSecurityManagerInstaller.installNoExitSecurityManager(); } @After public void tearDown() { if (robot != null) { robot.cleanUp(); robot = null; } if (settingsWindow != null) { settingsWindow.cleanUp(); settingsWindow = null; } if (puzzleWindow != null) { puzzleWindow.cleanUp(); puzzleWindow = null; } if (versionWindow != null) { versionWindow.cleanUp(); versionWindow = null; } if (aboutWindow != null) { aboutWindow.cleanUp(); aboutWindow = null; } if (noExitSecurityManagerInstaller != null) {
// Path: src/main/java/jigspuzzle/JigSPuzzle.java // public class JigSPuzzle { // // private static JigSPuzzle instance; // // public static JigSPuzzle getInstance() { // if (instance == null) { // instance = new JigSPuzzle(); // } // return instance; // } // // /** // * @param args the command line arguments // */ // public static void main(String[] args) { // getInstance().startGame(); // } // // /** // * The main window, in which the user can play // */ // IPuzzleWindow puzzleWindow; // // /** // * The sound player, that can play sounds in the UI. // */ // ISoundPlayer soundPlayer; // // private JigSPuzzle() { // puzzleWindow = new PuzzleWindow(); // soundPlayer = new SoundPlayer(); // } // // /** // * Exits the complete program // */ // public void exitProgram() { // try { // System.exit(0); // } catch (Exception ex) { // // in the assertJ - tests it is not possible to exit... // // instead, we 'reset' this class and the controller. // resetInstances(); // } // } // // /** // * Returns the window on that the user can puzzle. // * // * @return // */ // public IPuzzleWindow getPuzzleWindow() { // return puzzleWindow; // } // // /** // * Returns the player, that is used for playing sounds on the UI. // * // * @return // */ // public ISoundPlayer getSoundPlayer() { // return soundPlayer; // } // // /** // * A methods that resets all instances to null. With this is is simulated, // * that the programm has exited. However, opened windows are still there. // * Terefore: Use only for tests. // * // * @deprecated Use only in tests. // */ // public void resetInstances() { // instance = null; // PuzzleController.getInstance().resetInstance(); // SettingsController.getInstance().resetInstance(); // VersionController.getInstance().resetInstance(); // } // // /** // * Sets the window on that the user can puzzle. // * // * @param puzzleWindow // * @deprecated Use only, in special cases, e.g. tests. // */ // public void setPuzzleWindow(IPuzzleWindow puzzleWindow) { // this.puzzleWindow = puzzleWindow; // } // // /** // * Starts the game and shows the user the UI. // */ // private void startGame() { // puzzleWindow.showPuzzleWindow(); // } // } // Path: src/test/java/jigspuzzle/cucumber/steps/WindowsSteps.java import cucumber.api.PendingException; import cucumber.api.java.After; import cucumber.api.java.Before; import cucumber.api.java.en.*; import java.awt.Dimension; import java.awt.Frame; import java.awt.GraphicsDevice; import java.awt.GraphicsEnvironment; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JPopupMenu; import jigspuzzle.JigSPuzzle; import org.assertj.core.api.Assertions; import org.assertj.swing.core.BasicRobot; import org.assertj.swing.core.GenericTypeMatcher; import org.assertj.swing.core.Robot; import org.assertj.swing.data.Index; import org.assertj.swing.fixture.DialogFixture; import org.assertj.swing.fixture.FrameFixture; import org.assertj.swing.security.NoExitSecurityManagerInstaller; import static org.assertj.swing.finder.WindowFinder.findDialog; import static org.assertj.swing.finder.WindowFinder.findFrame; import org.assertj.swing.fixture.AbstractWindowFixture; import static org.assertj.swing.launcher.ApplicationLauncher.application; @Before public void setUp() { // FailOnThreadViolationRepaintManager.install(); noExitSecurityManagerInstaller = NoExitSecurityManagerInstaller.installNoExitSecurityManager(); } @After public void tearDown() { if (robot != null) { robot.cleanUp(); robot = null; } if (settingsWindow != null) { settingsWindow.cleanUp(); settingsWindow = null; } if (puzzleWindow != null) { puzzleWindow.cleanUp(); puzzleWindow = null; } if (versionWindow != null) { versionWindow.cleanUp(); versionWindow = null; } if (aboutWindow != null) { aboutWindow.cleanUp(); aboutWindow = null; } if (noExitSecurityManagerInstaller != null) {
JigSPuzzle.getInstance().exitProgram();
RoseTec/JigSPuzzle
src/main/java/jigspuzzle/model/puzzle/Puzzlepiece.java
// Path: src/main/java/jigspuzzle/util/ImageUtil.java // public class ImageUtil { // // /** // * Transforms a Image into a BufferedImage. // * // * @param img // * @return // */ // public static BufferedImage transformImageToBufferedImage(Image img) { // // source: http://stackoverflow.com/a/13605411 // if (img instanceof BufferedImage) { // return (BufferedImage) img; // } // // // Create a buffered image with transparency // BufferedImage bimage = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB); // // // Draw the image on to the buffered image // Graphics2D bGr = bimage.createGraphics(); // bGr.drawImage(img, 0, 0, null); // bGr.dispose(); // // // Return the buffered image // return bimage; // } // // /** // * Transforms the given image to an icon. For this, the class // * <code>ImageIcon</code> is used. // * // * @param img // * @return An instance of an icon for the given image or <code>null</code>, // * when the given image is <code>null</code>. // */ // public static Icon transformImageToIcon(Image img) { // if (img == null) { // return null; // } else { // return new ImageIcon(img); // } // } // // /** // * Transforms the given image to an icon. For this, the class // * <code>ImageIcon</code> is used. // * // * @param img // * @param size The that the icon should have. // * @return An instance of an icon for the given image or <code>null</code>, // * when the given image is <code>null</code>. // */ // public static Icon transformImageToIcon(Image img, Dimension size) { // if (img == null) { // return null; // } else { // Image resisedImg = img.getScaledInstance(size.width, size.height, Image.SCALE_DEFAULT); // return transformImageToIcon(resisedImg); // } // } // // /** // * Compares two images pixel by pixel and returns if they are equal. // * // * @param imgageA the first image. // * @param imgageB the second image. // * @return whether the images are both the same or not. // */ // public static boolean imagesAreEqual(Image imgageA, Image imgageB) { // BufferedImage imgA = transformImageToBufferedImage(imgageA); // BufferedImage imgB = transformImageToBufferedImage(imgageB); // //source: http://stackoverflow.com/a/29886786 // // The images must be the same size. // if (imgA.getWidth() == imgB.getWidth() && imgA.getHeight() == imgB.getHeight()) { // int width = imgA.getWidth(); // int height = imgA.getHeight(); // // // Loop over every pixel. // for (int y = 0; y < height; y++) { // for (int x = 0; x < width; x++) { // // Compare the pixels for equality. // if (imgA.getRGB(x, y) != imgB.getRGB(x, y)) { // return false; // } // } // } // } else { // return false; // } // // return true; // } // }
import java.awt.Image; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.Arrays; import java.util.Objects; import jigspuzzle.util.ImageUtil; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList;
connectors = new PuzzlepieceConnection[ConnectorPosition.numberOfElements()]; this.image = img; } /** * {@inheritDoc} */ @Override public int hashCode() { int hash = 3; hash = 31 * hash + Objects.hashCode(this.image); hash = 31 * hash + Arrays.deepHashCode(this.connectors); return hash; } /** * {@inheritDoc} */ @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Puzzlepiece other = (Puzzlepiece) obj;
// Path: src/main/java/jigspuzzle/util/ImageUtil.java // public class ImageUtil { // // /** // * Transforms a Image into a BufferedImage. // * // * @param img // * @return // */ // public static BufferedImage transformImageToBufferedImage(Image img) { // // source: http://stackoverflow.com/a/13605411 // if (img instanceof BufferedImage) { // return (BufferedImage) img; // } // // // Create a buffered image with transparency // BufferedImage bimage = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB); // // // Draw the image on to the buffered image // Graphics2D bGr = bimage.createGraphics(); // bGr.drawImage(img, 0, 0, null); // bGr.dispose(); // // // Return the buffered image // return bimage; // } // // /** // * Transforms the given image to an icon. For this, the class // * <code>ImageIcon</code> is used. // * // * @param img // * @return An instance of an icon for the given image or <code>null</code>, // * when the given image is <code>null</code>. // */ // public static Icon transformImageToIcon(Image img) { // if (img == null) { // return null; // } else { // return new ImageIcon(img); // } // } // // /** // * Transforms the given image to an icon. For this, the class // * <code>ImageIcon</code> is used. // * // * @param img // * @param size The that the icon should have. // * @return An instance of an icon for the given image or <code>null</code>, // * when the given image is <code>null</code>. // */ // public static Icon transformImageToIcon(Image img, Dimension size) { // if (img == null) { // return null; // } else { // Image resisedImg = img.getScaledInstance(size.width, size.height, Image.SCALE_DEFAULT); // return transformImageToIcon(resisedImg); // } // } // // /** // * Compares two images pixel by pixel and returns if they are equal. // * // * @param imgageA the first image. // * @param imgageB the second image. // * @return whether the images are both the same or not. // */ // public static boolean imagesAreEqual(Image imgageA, Image imgageB) { // BufferedImage imgA = transformImageToBufferedImage(imgageA); // BufferedImage imgB = transformImageToBufferedImage(imgageB); // //source: http://stackoverflow.com/a/29886786 // // The images must be the same size. // if (imgA.getWidth() == imgB.getWidth() && imgA.getHeight() == imgB.getHeight()) { // int width = imgA.getWidth(); // int height = imgA.getHeight(); // // // Loop over every pixel. // for (int y = 0; y < height; y++) { // for (int x = 0; x < width; x++) { // // Compare the pixels for equality. // if (imgA.getRGB(x, y) != imgB.getRGB(x, y)) { // return false; // } // } // } // } else { // return false; // } // // return true; // } // } // Path: src/main/java/jigspuzzle/model/puzzle/Puzzlepiece.java import java.awt.Image; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.Arrays; import java.util.Objects; import jigspuzzle.util.ImageUtil; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; connectors = new PuzzlepieceConnection[ConnectorPosition.numberOfElements()]; this.image = img; } /** * {@inheritDoc} */ @Override public int hashCode() { int hash = 3; hash = 31 * hash + Objects.hashCode(this.image); hash = 31 * hash + Arrays.deepHashCode(this.connectors); return hash; } /** * {@inheritDoc} */ @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Puzzlepiece other = (Puzzlepiece) obj;
if (!ImageUtil.imagesAreEqual(this.image, other.image)) {
RoseTec/JigSPuzzle
src/test/java/jigspuzzle/cucumber/steps/PuzzleareaSteps.java
// Path: src/test/java/jigspuzzle/cucumber/steps/util/ColorSteps.java // public class ColorSteps { // // public ColorSteps() { // } // // public static Color getColorFromString(String color) throws NoSuchMethodException { // switch (color) { // case "red": // return Color.RED; // case "blue": // return Color.BLUE; // case "yellow": // return Color.YELLOW; // } // throw new NoSuchMethodException("The color " + color + " is not supported in the tests. Please add it to " + ColorSteps.class.getSimpleName()); // } // }
import cucumber.api.PendingException; import cucumber.api.java.en.*; import java.awt.Color; import java.awt.Component; import javax.swing.JLayeredPane; import javax.swing.JPanel; import jigspuzzle.cucumber.steps.util.ColorSteps; import static org.assertj.core.api.Assertions.*; import org.assertj.swing.fixture.FrameFixture;
package jigspuzzle.cucumber.steps; /** * Step definitions for handeling the in- and output for the puzzlearea settings * window. * * @author RoseTec */ public class PuzzleareaSteps { private final WindowsSteps windowsSteps; public PuzzleareaSteps(WindowsSteps windowsSteps) { this.windowsSteps = windowsSteps; } // color of puzzle area @Then("^the background color of the puzzlearea should( not)? be \"([^\"]*)\"$") public void background_color_puzzlearea_should_be(String negation, String colorString) throws NoSuchMethodException {
// Path: src/test/java/jigspuzzle/cucumber/steps/util/ColorSteps.java // public class ColorSteps { // // public ColorSteps() { // } // // public static Color getColorFromString(String color) throws NoSuchMethodException { // switch (color) { // case "red": // return Color.RED; // case "blue": // return Color.BLUE; // case "yellow": // return Color.YELLOW; // } // throw new NoSuchMethodException("The color " + color + " is not supported in the tests. Please add it to " + ColorSteps.class.getSimpleName()); // } // } // Path: src/test/java/jigspuzzle/cucumber/steps/PuzzleareaSteps.java import cucumber.api.PendingException; import cucumber.api.java.en.*; import java.awt.Color; import java.awt.Component; import javax.swing.JLayeredPane; import javax.swing.JPanel; import jigspuzzle.cucumber.steps.util.ColorSteps; import static org.assertj.core.api.Assertions.*; import org.assertj.swing.fixture.FrameFixture; package jigspuzzle.cucumber.steps; /** * Step definitions for handeling the in- and output for the puzzlearea settings * window. * * @author RoseTec */ public class PuzzleareaSteps { private final WindowsSteps windowsSteps; public PuzzleareaSteps(WindowsSteps windowsSteps) { this.windowsSteps = windowsSteps; } // color of puzzle area @Then("^the background color of the puzzlearea should( not)? be \"([^\"]*)\"$") public void background_color_puzzlearea_should_be(String negation, String colorString) throws NoSuchMethodException {
Color colorExpected = ColorSteps.getColorFromString(colorString);
RoseTec/JigSPuzzle
src/test/java/jigspuzzle/model/puzzle/PuzzlepieceIT.java
// Path: src/test/java/jigspuzzle/testutils/factories/FactorySlave.java // public class FactorySlave { // // /** // * Builds a new Instance from the given class with default attributes as // * defined in a separate factory. // * // * A factory is given in this package with the name of the given class and // * adding 'Factory' to the end. E.g: the factory for // * <code>build(MyClass.class)</code> has the name MyClassFactory. // * // * @param classToBuild // * @return // * @throws ClassNotFoundException // */ // public static FactorySlave build(Class<?> classToBuild) throws ClassNotFoundException { // // find factory for this class // Class<?> factoryClass; // // try { // factoryClass = Class.forName(FactorySlave.class.getPackage().getName() + "." + classToBuild.getSimpleName() + "Factory"); // } catch (ClassNotFoundException ex) { // throw new ClassNotFoundException("Cannot find the factory for class: " + classToBuild.toString()); // } // // // instanciate factory // AbstractFactory factoryInstance; // // try { // factoryInstance = (AbstractFactory) factoryClass.getDeclaredConstructor().newInstance(); // } catch (Exception ex) { // throw new ClassNotFoundException("Cannot create an instance of the factory " + factoryClass.toString()); // } // // //let factory create an object // Object createdObject; // // try { // createdObject = factoryInstance.createObject(); // } catch (Exception ex) { // throw new ClassNotFoundException("The factory could not create an instance", ex); // } // // return new FactorySlave(classToBuild, createdObject); // } // // /** // * The class, that this factory should build. // */ // private Class<?> classToBuild; // // /** // * The object, that is created within this factory slave. // */ // private Object createdObject; // // private FactorySlave(Class<?> classToBuild, Object createdObject) { // this.classToBuild = classToBuild; // this.createdObject = createdObject; // } // // /** // * Creates the object and returns it. // * // * @return // */ // public Object create() { // return createdObject; // } // // /** // * Sets the given attribute to the given value in the created object. // * // * @param attribute // * @param value // * @return // * @throws NoSuchFieldException // */ // public FactorySlave withAttribut(String attribute, Object value) throws NoSuchFieldException { // Class<?> clazz = classToBuild; // while (clazz != null) { // try { // Field field = clazz.getDeclaredField(attribute); // field.setAccessible(true); // field.set(createdObject, value); // return this; // } catch (NoSuchFieldException e) { // clazz = clazz.getSuperclass(); // } catch (Exception e) { // throw new IllegalStateException(e); // } // } // // // no attribute found // throw new NoSuchFieldException(); // } // // }
import jigspuzzle.testutils.factories.FactorySlave; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*;
package jigspuzzle.model.puzzle; public class PuzzlepieceIT { public PuzzlepieceIT() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } @Test public void testCreateConnectorToPiece() throws ClassNotFoundException { for (ConnectorPosition position : ConnectorPosition.values()) {
// Path: src/test/java/jigspuzzle/testutils/factories/FactorySlave.java // public class FactorySlave { // // /** // * Builds a new Instance from the given class with default attributes as // * defined in a separate factory. // * // * A factory is given in this package with the name of the given class and // * adding 'Factory' to the end. E.g: the factory for // * <code>build(MyClass.class)</code> has the name MyClassFactory. // * // * @param classToBuild // * @return // * @throws ClassNotFoundException // */ // public static FactorySlave build(Class<?> classToBuild) throws ClassNotFoundException { // // find factory for this class // Class<?> factoryClass; // // try { // factoryClass = Class.forName(FactorySlave.class.getPackage().getName() + "." + classToBuild.getSimpleName() + "Factory"); // } catch (ClassNotFoundException ex) { // throw new ClassNotFoundException("Cannot find the factory for class: " + classToBuild.toString()); // } // // // instanciate factory // AbstractFactory factoryInstance; // // try { // factoryInstance = (AbstractFactory) factoryClass.getDeclaredConstructor().newInstance(); // } catch (Exception ex) { // throw new ClassNotFoundException("Cannot create an instance of the factory " + factoryClass.toString()); // } // // //let factory create an object // Object createdObject; // // try { // createdObject = factoryInstance.createObject(); // } catch (Exception ex) { // throw new ClassNotFoundException("The factory could not create an instance", ex); // } // // return new FactorySlave(classToBuild, createdObject); // } // // /** // * The class, that this factory should build. // */ // private Class<?> classToBuild; // // /** // * The object, that is created within this factory slave. // */ // private Object createdObject; // // private FactorySlave(Class<?> classToBuild, Object createdObject) { // this.classToBuild = classToBuild; // this.createdObject = createdObject; // } // // /** // * Creates the object and returns it. // * // * @return // */ // public Object create() { // return createdObject; // } // // /** // * Sets the given attribute to the given value in the created object. // * // * @param attribute // * @param value // * @return // * @throws NoSuchFieldException // */ // public FactorySlave withAttribut(String attribute, Object value) throws NoSuchFieldException { // Class<?> clazz = classToBuild; // while (clazz != null) { // try { // Field field = clazz.getDeclaredField(attribute); // field.setAccessible(true); // field.set(createdObject, value); // return this; // } catch (NoSuchFieldException e) { // clazz = clazz.getSuperclass(); // } catch (Exception e) { // throw new IllegalStateException(e); // } // } // // // no attribute found // throw new NoSuchFieldException(); // } // // } // Path: src/test/java/jigspuzzle/model/puzzle/PuzzlepieceIT.java import jigspuzzle.testutils.factories.FactorySlave; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; package jigspuzzle.model.puzzle; public class PuzzlepieceIT { public PuzzlepieceIT() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } @Test public void testCreateConnectorToPiece() throws ClassNotFoundException { for (ConnectorPosition position : ConnectorPosition.values()) {
Puzzlepiece instance = (Puzzlepiece) FactorySlave.build(Puzzlepiece.class).create();
RoseTec/JigSPuzzle
src/test/java/jigspuzzle/model/puzzle/PuzzleIT.java
// Path: src/test/java/jigspuzzle/testutils/factories/FactorySlave.java // public class FactorySlave { // // /** // * Builds a new Instance from the given class with default attributes as // * defined in a separate factory. // * // * A factory is given in this package with the name of the given class and // * adding 'Factory' to the end. E.g: the factory for // * <code>build(MyClass.class)</code> has the name MyClassFactory. // * // * @param classToBuild // * @return // * @throws ClassNotFoundException // */ // public static FactorySlave build(Class<?> classToBuild) throws ClassNotFoundException { // // find factory for this class // Class<?> factoryClass; // // try { // factoryClass = Class.forName(FactorySlave.class.getPackage().getName() + "." + classToBuild.getSimpleName() + "Factory"); // } catch (ClassNotFoundException ex) { // throw new ClassNotFoundException("Cannot find the factory for class: " + classToBuild.toString()); // } // // // instanciate factory // AbstractFactory factoryInstance; // // try { // factoryInstance = (AbstractFactory) factoryClass.getDeclaredConstructor().newInstance(); // } catch (Exception ex) { // throw new ClassNotFoundException("Cannot create an instance of the factory " + factoryClass.toString()); // } // // //let factory create an object // Object createdObject; // // try { // createdObject = factoryInstance.createObject(); // } catch (Exception ex) { // throw new ClassNotFoundException("The factory could not create an instance", ex); // } // // return new FactorySlave(classToBuild, createdObject); // } // // /** // * The class, that this factory should build. // */ // private Class<?> classToBuild; // // /** // * The object, that is created within this factory slave. // */ // private Object createdObject; // // private FactorySlave(Class<?> classToBuild, Object createdObject) { // this.classToBuild = classToBuild; // this.createdObject = createdObject; // } // // /** // * Creates the object and returns it. // * // * @return // */ // public Object create() { // return createdObject; // } // // /** // * Sets the given attribute to the given value in the created object. // * // * @param attribute // * @param value // * @return // * @throws NoSuchFieldException // */ // public FactorySlave withAttribut(String attribute, Object value) throws NoSuchFieldException { // Class<?> clazz = classToBuild; // while (clazz != null) { // try { // Field field = clazz.getDeclaredField(attribute); // field.setAccessible(true); // field.set(createdObject, value); // return this; // } catch (NoSuchFieldException e) { // clazz = clazz.getSuperclass(); // } catch (Exception e) { // throw new IllegalStateException(e); // } // } // // // no attribute found // throw new NoSuchFieldException(); // } // // }
import jigspuzzle.testutils.factories.FactorySlave; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*;
package jigspuzzle.model.puzzle; public class PuzzleIT { public PuzzleIT() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } @Test public void testRemovePuzzlepieceGroup() throws ClassNotFoundException {
// Path: src/test/java/jigspuzzle/testutils/factories/FactorySlave.java // public class FactorySlave { // // /** // * Builds a new Instance from the given class with default attributes as // * defined in a separate factory. // * // * A factory is given in this package with the name of the given class and // * adding 'Factory' to the end. E.g: the factory for // * <code>build(MyClass.class)</code> has the name MyClassFactory. // * // * @param classToBuild // * @return // * @throws ClassNotFoundException // */ // public static FactorySlave build(Class<?> classToBuild) throws ClassNotFoundException { // // find factory for this class // Class<?> factoryClass; // // try { // factoryClass = Class.forName(FactorySlave.class.getPackage().getName() + "." + classToBuild.getSimpleName() + "Factory"); // } catch (ClassNotFoundException ex) { // throw new ClassNotFoundException("Cannot find the factory for class: " + classToBuild.toString()); // } // // // instanciate factory // AbstractFactory factoryInstance; // // try { // factoryInstance = (AbstractFactory) factoryClass.getDeclaredConstructor().newInstance(); // } catch (Exception ex) { // throw new ClassNotFoundException("Cannot create an instance of the factory " + factoryClass.toString()); // } // // //let factory create an object // Object createdObject; // // try { // createdObject = factoryInstance.createObject(); // } catch (Exception ex) { // throw new ClassNotFoundException("The factory could not create an instance", ex); // } // // return new FactorySlave(classToBuild, createdObject); // } // // /** // * The class, that this factory should build. // */ // private Class<?> classToBuild; // // /** // * The object, that is created within this factory slave. // */ // private Object createdObject; // // private FactorySlave(Class<?> classToBuild, Object createdObject) { // this.classToBuild = classToBuild; // this.createdObject = createdObject; // } // // /** // * Creates the object and returns it. // * // * @return // */ // public Object create() { // return createdObject; // } // // /** // * Sets the given attribute to the given value in the created object. // * // * @param attribute // * @param value // * @return // * @throws NoSuchFieldException // */ // public FactorySlave withAttribut(String attribute, Object value) throws NoSuchFieldException { // Class<?> clazz = classToBuild; // while (clazz != null) { // try { // Field field = clazz.getDeclaredField(attribute); // field.setAccessible(true); // field.set(createdObject, value); // return this; // } catch (NoSuchFieldException e) { // clazz = clazz.getSuperclass(); // } catch (Exception e) { // throw new IllegalStateException(e); // } // } // // // no attribute found // throw new NoSuchFieldException(); // } // // } // Path: src/test/java/jigspuzzle/model/puzzle/PuzzleIT.java import jigspuzzle.testutils.factories.FactorySlave; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; package jigspuzzle.model.puzzle; public class PuzzleIT { public PuzzleIT() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } @Test public void testRemovePuzzlepieceGroup() throws ClassNotFoundException {
Puzzle puzzle = (Puzzle) FactorySlave.build(Puzzle.class).create();
RoseTec/JigSPuzzle
src/test/java/jigspuzzle/view/util/SelectionGroupIT.java
// Path: src/test/java/jigspuzzle/testutils/mockups/DummySelectionGroupSelectable.java // public class DummySelectionGroupSelectable<T> implements SelectionGroupSelectable<T> { // // private T value; // // private SelectionGroup<T> selectionGroup; // // @Override // public T getSelectionValue() { // return this.value; // } // // @Override // public void setSelectionGroup(SelectionGroup<T> selectionGroup) { // this.selectionGroup = selectionGroup; // } // // @Override // public void setSelectionValue(T value) { // this.value = value; // } // // }
import java.util.Arrays; import java.util.List; import jigspuzzle.testutils.mockups.DummySelectionGroupSelectable; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*;
package jigspuzzle.view.util; public class SelectionGroupIT { public SelectionGroupIT() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } @Test public void testChangeSelectedValue() { SelectionGroup<Integer> instance = new SelectionGroup<>();
// Path: src/test/java/jigspuzzle/testutils/mockups/DummySelectionGroupSelectable.java // public class DummySelectionGroupSelectable<T> implements SelectionGroupSelectable<T> { // // private T value; // // private SelectionGroup<T> selectionGroup; // // @Override // public T getSelectionValue() { // return this.value; // } // // @Override // public void setSelectionGroup(SelectionGroup<T> selectionGroup) { // this.selectionGroup = selectionGroup; // } // // @Override // public void setSelectionValue(T value) { // this.value = value; // } // // } // Path: src/test/java/jigspuzzle/view/util/SelectionGroupIT.java import java.util.Arrays; import java.util.List; import jigspuzzle.testutils.mockups.DummySelectionGroupSelectable; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; package jigspuzzle.view.util; public class SelectionGroupIT { public SelectionGroupIT() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } @Test public void testChangeSelectedValue() { SelectionGroup<Integer> instance = new SelectionGroup<>();
SelectionGroupSelectable<Integer> object = new DummySelectionGroupSelectable<>();
RoseTec/JigSPuzzle
src/main/java/jigspuzzle/view/desktop/settings/SettingViewPanel.java
// Path: src/main/java/jigspuzzle/view/desktop/swing/TopToButtomLayoutManager.java // public class TopToButtomLayoutManager implements LayoutManager { // // /** // * The offset of the components to the left side of this component to be // * left blank. // * // * Default is 0. // */ // public int OFFSET_LEFT = 0; // // /** // * The offset of the components to the right side of this component to be // * left blank. // * // * Default is 0. // */ // public int OFFSET_RIGHT = 0; // // /** // * The offset of the first components to the border to be left blank. // * // * Default is 0. // */ // public int OFFSET_TOP = 0; // // /** // * The offset of the last components to the border to be left blank. // * // * Default is 0. // */ // public int OFFSET_BUTTOM = 0; // // /** // * The size of empty space between two components in the comtainer. // * // * Default is 5. // */ // public int OFFSET_BETWEEN_COMPONENTS = 5; // // /** // * {@inheritDoc} // */ // @Override // public void addLayoutComponent(String name, Component comp) { // } // // /** // * {@inheritDoc} // */ // @Override // public void removeLayoutComponent(Component comp) { // } // // /** // * {@inheritDoc} // */ // @Override // public Dimension preferredLayoutSize(Container parent) { // int width = getParentContainerWidth(parent) - 50; // int height = OFFSET_TOP + OFFSET_BUTTOM + parent.getInsets().top + parent.getInsets().bottom; // Component[] comps = parent.getComponents(); // // if (comps.length > 0) { // height += (comps.length - 1) * OFFSET_BETWEEN_COMPONENTS; // } // for (Component comp : comps) { // height += comp.getPreferredSize().height; // } // // return new Dimension(width, height); // } // // /** // * {@inheritDoc} // */ // @Override // public Dimension minimumLayoutSize(Container parent) { // int width = 100; // int height = OFFSET_TOP + OFFSET_BUTTOM + parent.getInsets().top + parent.getInsets().bottom; // Component[] comps = parent.getComponents(); // // if (comps.length > 0) { // height += (comps.length - 1) * OFFSET_BETWEEN_COMPONENTS; // } // for (Component comp : comps) { // height += comp.getMinimumSize().height; // } // // return new Dimension(width, height); // } // // /** // * {@inheritDoc} // */ // @Override // public void layoutContainer(Container parent) { // Component[] comps = parent.getComponents(); // int compStartHeight = OFFSET_TOP + parent.getInsets().left; // int width = getParentContainerWidth(parent) - OFFSET_LEFT - OFFSET_RIGHT - parent.getInsets().left - parent.getInsets().right; // // for (Component comp : comps) { // int height = comp.getPreferredSize().height; // // comp.setBounds(OFFSET_LEFT, compStartHeight, width, height); // compStartHeight += height; // compStartHeight += OFFSET_BETWEEN_COMPONENTS; // } // } // // /** // * Gets the width of the parent of given container. Normally the given // * container is the container to be layouted. For it to be steched over the // * full width of the parent container, the size has to be known. // * // * @param thisContainer // * @return // */ // private int getParentContainerWidth(Container thisContainer) { // return thisContainer.getWidth(); // } // // }
import jigspuzzle.view.desktop.swing.TopToButtomLayoutManager; import java.awt.Dimension;
package jigspuzzle.view.desktop.settings; /** * A panel designed to be added in a JTabbedPane in the settings view * * @author RoseTec */ class SettingViewPanel extends javax.swing.JPanel { /** * Creates new form SettingViewPanel */ public SettingViewPanel() {
// Path: src/main/java/jigspuzzle/view/desktop/swing/TopToButtomLayoutManager.java // public class TopToButtomLayoutManager implements LayoutManager { // // /** // * The offset of the components to the left side of this component to be // * left blank. // * // * Default is 0. // */ // public int OFFSET_LEFT = 0; // // /** // * The offset of the components to the right side of this component to be // * left blank. // * // * Default is 0. // */ // public int OFFSET_RIGHT = 0; // // /** // * The offset of the first components to the border to be left blank. // * // * Default is 0. // */ // public int OFFSET_TOP = 0; // // /** // * The offset of the last components to the border to be left blank. // * // * Default is 0. // */ // public int OFFSET_BUTTOM = 0; // // /** // * The size of empty space between two components in the comtainer. // * // * Default is 5. // */ // public int OFFSET_BETWEEN_COMPONENTS = 5; // // /** // * {@inheritDoc} // */ // @Override // public void addLayoutComponent(String name, Component comp) { // } // // /** // * {@inheritDoc} // */ // @Override // public void removeLayoutComponent(Component comp) { // } // // /** // * {@inheritDoc} // */ // @Override // public Dimension preferredLayoutSize(Container parent) { // int width = getParentContainerWidth(parent) - 50; // int height = OFFSET_TOP + OFFSET_BUTTOM + parent.getInsets().top + parent.getInsets().bottom; // Component[] comps = parent.getComponents(); // // if (comps.length > 0) { // height += (comps.length - 1) * OFFSET_BETWEEN_COMPONENTS; // } // for (Component comp : comps) { // height += comp.getPreferredSize().height; // } // // return new Dimension(width, height); // } // // /** // * {@inheritDoc} // */ // @Override // public Dimension minimumLayoutSize(Container parent) { // int width = 100; // int height = OFFSET_TOP + OFFSET_BUTTOM + parent.getInsets().top + parent.getInsets().bottom; // Component[] comps = parent.getComponents(); // // if (comps.length > 0) { // height += (comps.length - 1) * OFFSET_BETWEEN_COMPONENTS; // } // for (Component comp : comps) { // height += comp.getMinimumSize().height; // } // // return new Dimension(width, height); // } // // /** // * {@inheritDoc} // */ // @Override // public void layoutContainer(Container parent) { // Component[] comps = parent.getComponents(); // int compStartHeight = OFFSET_TOP + parent.getInsets().left; // int width = getParentContainerWidth(parent) - OFFSET_LEFT - OFFSET_RIGHT - parent.getInsets().left - parent.getInsets().right; // // for (Component comp : comps) { // int height = comp.getPreferredSize().height; // // comp.setBounds(OFFSET_LEFT, compStartHeight, width, height); // compStartHeight += height; // compStartHeight += OFFSET_BETWEEN_COMPONENTS; // } // } // // /** // * Gets the width of the parent of given container. Normally the given // * container is the container to be layouted. For it to be steched over the // * full width of the parent container, the size has to be known. // * // * @param thisContainer // * @return // */ // private int getParentContainerWidth(Container thisContainer) { // return thisContainer.getWidth(); // } // // } // Path: src/main/java/jigspuzzle/view/desktop/settings/SettingViewPanel.java import jigspuzzle.view.desktop.swing.TopToButtomLayoutManager; import java.awt.Dimension; package jigspuzzle.view.desktop.settings; /** * A panel designed to be added in a JTabbedPane in the settings view * * @author RoseTec */ class SettingViewPanel extends javax.swing.JPanel { /** * Creates new form SettingViewPanel */ public SettingViewPanel() {
TopToButtomLayoutManager layout = new TopToButtomLayoutManager();
RoseTec/JigSPuzzle
src/test/java/jigspuzzle/cucumber/steps/VersionSteps.java
// Path: src/test/java/jigspuzzle/cucumber/RunCucumber.java // @RunWith(Cucumber.class) // @CucumberOptions( // features = "../src/test/java/jigspuzzle/cucumber/features", // glue = "jigspuzzle.cucumber.steps", // //tags = {"@test"}, // <- activate this if only scenarios with tag '@test' should be executed. // plugin = {"pretty", "html:../target/cucumber-html-report"} // ) // public class RunCucumber { // // /** // * The timeout that is used, whn searching in a ui-element for an element to // * change. Thgis can e.g. be, when is will become visible or change its text // * because of the user input. // * // * The timeout is a valu in miliseconds. // */ // public static final int TIMEOUT_UI_UPDATED = 15000; // }
import cucumber.api.PendingException; import cucumber.api.java.en.*; import java.util.regex.Pattern; import jigspuzzle.cucumber.RunCucumber; import org.assertj.swing.core.matcher.JLabelMatcher; import org.assertj.swing.edt.GuiActionRunner; import org.assertj.swing.exception.ComponentLookupException; import org.assertj.swing.fixture.DialogFixture; import org.assertj.swing.fixture.FrameFixture; import org.assertj.swing.timing.Condition; import org.assertj.swing.timing.Pause; import org.assertj.swing.timing.Timeout;
package jigspuzzle.cucumber.steps; /** * Step definitions for the input with versions. * * @author RoseTec */ public class VersionSteps { private final WindowsSteps windowsSteps; public VersionSteps(WindowsSteps windowsSteps) { this.windowsSteps = windowsSteps; } // controlling versions @Given("^a newer version is available on the internet$") public void new_version_avalable() { throw new PendingException(); } @Given("^no newer version is available on the internet$") public void no_new_version_avalable() { // do nothing here, since the one in development is always newer then the released one //todo: find out how to do it right } // -- controlling versions end // viewing version results @Then("^I should see, that a newer version is available$") public void see_new_version_avalable() { get_version_window().label("this-version-number").requireText(Pattern.compile("[0-9]+(\\.[0-9]+)*(-SNAPSHOT)?")); Pause.pause(new Condition("notify-this-is-newest-version should be visible") { @Override public boolean test() { return GuiActionRunner.execute(get_version_window().button("navigate-to-new-version")::isEnabled); }
// Path: src/test/java/jigspuzzle/cucumber/RunCucumber.java // @RunWith(Cucumber.class) // @CucumberOptions( // features = "../src/test/java/jigspuzzle/cucumber/features", // glue = "jigspuzzle.cucumber.steps", // //tags = {"@test"}, // <- activate this if only scenarios with tag '@test' should be executed. // plugin = {"pretty", "html:../target/cucumber-html-report"} // ) // public class RunCucumber { // // /** // * The timeout that is used, whn searching in a ui-element for an element to // * change. Thgis can e.g. be, when is will become visible or change its text // * because of the user input. // * // * The timeout is a valu in miliseconds. // */ // public static final int TIMEOUT_UI_UPDATED = 15000; // } // Path: src/test/java/jigspuzzle/cucumber/steps/VersionSteps.java import cucumber.api.PendingException; import cucumber.api.java.en.*; import java.util.regex.Pattern; import jigspuzzle.cucumber.RunCucumber; import org.assertj.swing.core.matcher.JLabelMatcher; import org.assertj.swing.edt.GuiActionRunner; import org.assertj.swing.exception.ComponentLookupException; import org.assertj.swing.fixture.DialogFixture; import org.assertj.swing.fixture.FrameFixture; import org.assertj.swing.timing.Condition; import org.assertj.swing.timing.Pause; import org.assertj.swing.timing.Timeout; package jigspuzzle.cucumber.steps; /** * Step definitions for the input with versions. * * @author RoseTec */ public class VersionSteps { private final WindowsSteps windowsSteps; public VersionSteps(WindowsSteps windowsSteps) { this.windowsSteps = windowsSteps; } // controlling versions @Given("^a newer version is available on the internet$") public void new_version_avalable() { throw new PendingException(); } @Given("^no newer version is available on the internet$") public void no_new_version_avalable() { // do nothing here, since the one in development is always newer then the released one //todo: find out how to do it right } // -- controlling versions end // viewing version results @Then("^I should see, that a newer version is available$") public void see_new_version_avalable() { get_version_window().label("this-version-number").requireText(Pattern.compile("[0-9]+(\\.[0-9]+)*(-SNAPSHOT)?")); Pause.pause(new Condition("notify-this-is-newest-version should be visible") { @Override public boolean test() { return GuiActionRunner.execute(get_version_window().button("navigate-to-new-version")::isEnabled); }
}, RunCucumber.TIMEOUT_UI_UPDATED);
RoseTec/JigSPuzzle
src/test/java/jigspuzzle/model/puzzle/PuzzlepieceConnectionIT.java
// Path: src/test/java/jigspuzzle/testutils/factories/FactorySlave.java // public class FactorySlave { // // /** // * Builds a new Instance from the given class with default attributes as // * defined in a separate factory. // * // * A factory is given in this package with the name of the given class and // * adding 'Factory' to the end. E.g: the factory for // * <code>build(MyClass.class)</code> has the name MyClassFactory. // * // * @param classToBuild // * @return // * @throws ClassNotFoundException // */ // public static FactorySlave build(Class<?> classToBuild) throws ClassNotFoundException { // // find factory for this class // Class<?> factoryClass; // // try { // factoryClass = Class.forName(FactorySlave.class.getPackage().getName() + "." + classToBuild.getSimpleName() + "Factory"); // } catch (ClassNotFoundException ex) { // throw new ClassNotFoundException("Cannot find the factory for class: " + classToBuild.toString()); // } // // // instanciate factory // AbstractFactory factoryInstance; // // try { // factoryInstance = (AbstractFactory) factoryClass.getDeclaredConstructor().newInstance(); // } catch (Exception ex) { // throw new ClassNotFoundException("Cannot create an instance of the factory " + factoryClass.toString()); // } // // //let factory create an object // Object createdObject; // // try { // createdObject = factoryInstance.createObject(); // } catch (Exception ex) { // throw new ClassNotFoundException("The factory could not create an instance", ex); // } // // return new FactorySlave(classToBuild, createdObject); // } // // /** // * The class, that this factory should build. // */ // private Class<?> classToBuild; // // /** // * The object, that is created within this factory slave. // */ // private Object createdObject; // // private FactorySlave(Class<?> classToBuild, Object createdObject) { // this.classToBuild = classToBuild; // this.createdObject = createdObject; // } // // /** // * Creates the object and returns it. // * // * @return // */ // public Object create() { // return createdObject; // } // // /** // * Sets the given attribute to the given value in the created object. // * // * @param attribute // * @param value // * @return // * @throws NoSuchFieldException // */ // public FactorySlave withAttribut(String attribute, Object value) throws NoSuchFieldException { // Class<?> clazz = classToBuild; // while (clazz != null) { // try { // Field field = clazz.getDeclaredField(attribute); // field.setAccessible(true); // field.set(createdObject, value); // return this; // } catch (NoSuchFieldException e) { // clazz = clazz.getSuperclass(); // } catch (Exception e) { // throw new IllegalStateException(e); // } // } // // // no attribute found // throw new NoSuchFieldException(); // } // // }
import jigspuzzle.testutils.factories.FactorySlave; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*;
package jigspuzzle.model.puzzle; public class PuzzlepieceConnectionIT { public PuzzlepieceConnectionIT() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } @Test public void testConvertPuzzlepieceConnections() throws ClassNotFoundException {
// Path: src/test/java/jigspuzzle/testutils/factories/FactorySlave.java // public class FactorySlave { // // /** // * Builds a new Instance from the given class with default attributes as // * defined in a separate factory. // * // * A factory is given in this package with the name of the given class and // * adding 'Factory' to the end. E.g: the factory for // * <code>build(MyClass.class)</code> has the name MyClassFactory. // * // * @param classToBuild // * @return // * @throws ClassNotFoundException // */ // public static FactorySlave build(Class<?> classToBuild) throws ClassNotFoundException { // // find factory for this class // Class<?> factoryClass; // // try { // factoryClass = Class.forName(FactorySlave.class.getPackage().getName() + "." + classToBuild.getSimpleName() + "Factory"); // } catch (ClassNotFoundException ex) { // throw new ClassNotFoundException("Cannot find the factory for class: " + classToBuild.toString()); // } // // // instanciate factory // AbstractFactory factoryInstance; // // try { // factoryInstance = (AbstractFactory) factoryClass.getDeclaredConstructor().newInstance(); // } catch (Exception ex) { // throw new ClassNotFoundException("Cannot create an instance of the factory " + factoryClass.toString()); // } // // //let factory create an object // Object createdObject; // // try { // createdObject = factoryInstance.createObject(); // } catch (Exception ex) { // throw new ClassNotFoundException("The factory could not create an instance", ex); // } // // return new FactorySlave(classToBuild, createdObject); // } // // /** // * The class, that this factory should build. // */ // private Class<?> classToBuild; // // /** // * The object, that is created within this factory slave. // */ // private Object createdObject; // // private FactorySlave(Class<?> classToBuild, Object createdObject) { // this.classToBuild = classToBuild; // this.createdObject = createdObject; // } // // /** // * Creates the object and returns it. // * // * @return // */ // public Object create() { // return createdObject; // } // // /** // * Sets the given attribute to the given value in the created object. // * // * @param attribute // * @param value // * @return // * @throws NoSuchFieldException // */ // public FactorySlave withAttribut(String attribute, Object value) throws NoSuchFieldException { // Class<?> clazz = classToBuild; // while (clazz != null) { // try { // Field field = clazz.getDeclaredField(attribute); // field.setAccessible(true); // field.set(createdObject, value); // return this; // } catch (NoSuchFieldException e) { // clazz = clazz.getSuperclass(); // } catch (Exception e) { // throw new IllegalStateException(e); // } // } // // // no attribute found // throw new NoSuchFieldException(); // } // // } // Path: src/test/java/jigspuzzle/model/puzzle/PuzzlepieceConnectionIT.java import jigspuzzle.testutils.factories.FactorySlave; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; package jigspuzzle.model.puzzle; public class PuzzlepieceConnectionIT { public PuzzlepieceConnectionIT() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } @Test public void testConvertPuzzlepieceConnections() throws ClassNotFoundException {
Puzzlepiece piece1 = (Puzzlepiece) FactorySlave.build(Puzzlepiece.class).create();
thiloplanz/jmockmongo
src/main/java/jmockmongo/wire/DeleteMessage.java
// Path: src/main/java/jmockmongo/wire/MessageDecoder.java // static final String readCString(ChannelBuffer buffer) { // // find the terminating zero-byte // int length = buffer.bytesBefore((byte) 0); // byte[] bytes = new byte[length]; // buffer.readBytes(bytes); // // also skip the terminator // buffer.readByte(); // try { // return new String(bytes, "UTF-8"); // } catch (java.io.UnsupportedEncodingException uee) { // throw new BSONException("impossible", uee); // } // } // // Path: src/main/java/jmockmongo/wire/MessageDecoder.java // static final BSONObject readDocument(ChannelBuffer buffer, byte[] fourBytes) { // int length = readInt32(buffer, fourBytes); // byte[] bson = new byte[length]; // buffer.readBytes(bson, 4, length - 4); // System.arraycopy(fourBytes, 0, bson, 0, 4); // return BSON.decode(bson); // // } // // Path: src/main/java/jmockmongo/wire/MessageDecoder.java // static final int readInt32(ChannelBuffer buffer, byte[] fourBytes) { // buffer.readBytes(fourBytes); // return Bits.readInt(fourBytes); // }
import static jmockmongo.wire.MessageDecoder.readCString; import static jmockmongo.wire.MessageDecoder.readDocument; import static jmockmongo.wire.MessageDecoder.readInt32; import org.bson.BSONObject; import org.jboss.netty.buffer.ChannelBuffer;
/** * Copyright (c) 2012, Thilo Planz. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the Apache License, Version 2.0 * as published by the Apache Software Foundation (the "License"). * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * * You should have received a copy of the License along with this program. * If not, see <http://www.apache.org/licenses/LICENSE-2.0>. */ package jmockmongo.wire; class DeleteMessage extends Message { static final int OP_CODE_DELETE = 2006; // struct { // MsgHeader header; // standard message header // int32 ZERO; // 0 - reserved for future use // cstring fullCollectionName; // "dbname.collectionname" // int32 flags; // bit vector - see below for details. // document selector; // query object. See below for details. // } private final int flags; private final String fullCollectionName; private BSONObject query; DeleteMessage(ChannelBuffer data) { super(data, OP_CODE_DELETE); byte[] fourBytes = new byte[4];
// Path: src/main/java/jmockmongo/wire/MessageDecoder.java // static final String readCString(ChannelBuffer buffer) { // // find the terminating zero-byte // int length = buffer.bytesBefore((byte) 0); // byte[] bytes = new byte[length]; // buffer.readBytes(bytes); // // also skip the terminator // buffer.readByte(); // try { // return new String(bytes, "UTF-8"); // } catch (java.io.UnsupportedEncodingException uee) { // throw new BSONException("impossible", uee); // } // } // // Path: src/main/java/jmockmongo/wire/MessageDecoder.java // static final BSONObject readDocument(ChannelBuffer buffer, byte[] fourBytes) { // int length = readInt32(buffer, fourBytes); // byte[] bson = new byte[length]; // buffer.readBytes(bson, 4, length - 4); // System.arraycopy(fourBytes, 0, bson, 0, 4); // return BSON.decode(bson); // // } // // Path: src/main/java/jmockmongo/wire/MessageDecoder.java // static final int readInt32(ChannelBuffer buffer, byte[] fourBytes) { // buffer.readBytes(fourBytes); // return Bits.readInt(fourBytes); // } // Path: src/main/java/jmockmongo/wire/DeleteMessage.java import static jmockmongo.wire.MessageDecoder.readCString; import static jmockmongo.wire.MessageDecoder.readDocument; import static jmockmongo.wire.MessageDecoder.readInt32; import org.bson.BSONObject; import org.jboss.netty.buffer.ChannelBuffer; /** * Copyright (c) 2012, Thilo Planz. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the Apache License, Version 2.0 * as published by the Apache Software Foundation (the "License"). * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * * You should have received a copy of the License along with this program. * If not, see <http://www.apache.org/licenses/LICENSE-2.0>. */ package jmockmongo.wire; class DeleteMessage extends Message { static final int OP_CODE_DELETE = 2006; // struct { // MsgHeader header; // standard message header // int32 ZERO; // 0 - reserved for future use // cstring fullCollectionName; // "dbname.collectionname" // int32 flags; // bit vector - see below for details. // document selector; // query object. See below for details. // } private final int flags; private final String fullCollectionName; private BSONObject query; DeleteMessage(ChannelBuffer data) { super(data, OP_CODE_DELETE); byte[] fourBytes = new byte[4];
readInt32(data, fourBytes);
thiloplanz/jmockmongo
src/main/java/jmockmongo/wire/DeleteMessage.java
// Path: src/main/java/jmockmongo/wire/MessageDecoder.java // static final String readCString(ChannelBuffer buffer) { // // find the terminating zero-byte // int length = buffer.bytesBefore((byte) 0); // byte[] bytes = new byte[length]; // buffer.readBytes(bytes); // // also skip the terminator // buffer.readByte(); // try { // return new String(bytes, "UTF-8"); // } catch (java.io.UnsupportedEncodingException uee) { // throw new BSONException("impossible", uee); // } // } // // Path: src/main/java/jmockmongo/wire/MessageDecoder.java // static final BSONObject readDocument(ChannelBuffer buffer, byte[] fourBytes) { // int length = readInt32(buffer, fourBytes); // byte[] bson = new byte[length]; // buffer.readBytes(bson, 4, length - 4); // System.arraycopy(fourBytes, 0, bson, 0, 4); // return BSON.decode(bson); // // } // // Path: src/main/java/jmockmongo/wire/MessageDecoder.java // static final int readInt32(ChannelBuffer buffer, byte[] fourBytes) { // buffer.readBytes(fourBytes); // return Bits.readInt(fourBytes); // }
import static jmockmongo.wire.MessageDecoder.readCString; import static jmockmongo.wire.MessageDecoder.readDocument; import static jmockmongo.wire.MessageDecoder.readInt32; import org.bson.BSONObject; import org.jboss.netty.buffer.ChannelBuffer;
/** * Copyright (c) 2012, Thilo Planz. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the Apache License, Version 2.0 * as published by the Apache Software Foundation (the "License"). * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * * You should have received a copy of the License along with this program. * If not, see <http://www.apache.org/licenses/LICENSE-2.0>. */ package jmockmongo.wire; class DeleteMessage extends Message { static final int OP_CODE_DELETE = 2006; // struct { // MsgHeader header; // standard message header // int32 ZERO; // 0 - reserved for future use // cstring fullCollectionName; // "dbname.collectionname" // int32 flags; // bit vector - see below for details. // document selector; // query object. See below for details. // } private final int flags; private final String fullCollectionName; private BSONObject query; DeleteMessage(ChannelBuffer data) { super(data, OP_CODE_DELETE); byte[] fourBytes = new byte[4]; readInt32(data, fourBytes);
// Path: src/main/java/jmockmongo/wire/MessageDecoder.java // static final String readCString(ChannelBuffer buffer) { // // find the terminating zero-byte // int length = buffer.bytesBefore((byte) 0); // byte[] bytes = new byte[length]; // buffer.readBytes(bytes); // // also skip the terminator // buffer.readByte(); // try { // return new String(bytes, "UTF-8"); // } catch (java.io.UnsupportedEncodingException uee) { // throw new BSONException("impossible", uee); // } // } // // Path: src/main/java/jmockmongo/wire/MessageDecoder.java // static final BSONObject readDocument(ChannelBuffer buffer, byte[] fourBytes) { // int length = readInt32(buffer, fourBytes); // byte[] bson = new byte[length]; // buffer.readBytes(bson, 4, length - 4); // System.arraycopy(fourBytes, 0, bson, 0, 4); // return BSON.decode(bson); // // } // // Path: src/main/java/jmockmongo/wire/MessageDecoder.java // static final int readInt32(ChannelBuffer buffer, byte[] fourBytes) { // buffer.readBytes(fourBytes); // return Bits.readInt(fourBytes); // } // Path: src/main/java/jmockmongo/wire/DeleteMessage.java import static jmockmongo.wire.MessageDecoder.readCString; import static jmockmongo.wire.MessageDecoder.readDocument; import static jmockmongo.wire.MessageDecoder.readInt32; import org.bson.BSONObject; import org.jboss.netty.buffer.ChannelBuffer; /** * Copyright (c) 2012, Thilo Planz. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the Apache License, Version 2.0 * as published by the Apache Software Foundation (the "License"). * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * * You should have received a copy of the License along with this program. * If not, see <http://www.apache.org/licenses/LICENSE-2.0>. */ package jmockmongo.wire; class DeleteMessage extends Message { static final int OP_CODE_DELETE = 2006; // struct { // MsgHeader header; // standard message header // int32 ZERO; // 0 - reserved for future use // cstring fullCollectionName; // "dbname.collectionname" // int32 flags; // bit vector - see below for details. // document selector; // query object. See below for details. // } private final int flags; private final String fullCollectionName; private BSONObject query; DeleteMessage(ChannelBuffer data) { super(data, OP_CODE_DELETE); byte[] fourBytes = new byte[4]; readInt32(data, fourBytes);
fullCollectionName = readCString(data);
thiloplanz/jmockmongo
src/main/java/jmockmongo/wire/DeleteMessage.java
// Path: src/main/java/jmockmongo/wire/MessageDecoder.java // static final String readCString(ChannelBuffer buffer) { // // find the terminating zero-byte // int length = buffer.bytesBefore((byte) 0); // byte[] bytes = new byte[length]; // buffer.readBytes(bytes); // // also skip the terminator // buffer.readByte(); // try { // return new String(bytes, "UTF-8"); // } catch (java.io.UnsupportedEncodingException uee) { // throw new BSONException("impossible", uee); // } // } // // Path: src/main/java/jmockmongo/wire/MessageDecoder.java // static final BSONObject readDocument(ChannelBuffer buffer, byte[] fourBytes) { // int length = readInt32(buffer, fourBytes); // byte[] bson = new byte[length]; // buffer.readBytes(bson, 4, length - 4); // System.arraycopy(fourBytes, 0, bson, 0, 4); // return BSON.decode(bson); // // } // // Path: src/main/java/jmockmongo/wire/MessageDecoder.java // static final int readInt32(ChannelBuffer buffer, byte[] fourBytes) { // buffer.readBytes(fourBytes); // return Bits.readInt(fourBytes); // }
import static jmockmongo.wire.MessageDecoder.readCString; import static jmockmongo.wire.MessageDecoder.readDocument; import static jmockmongo.wire.MessageDecoder.readInt32; import org.bson.BSONObject; import org.jboss.netty.buffer.ChannelBuffer;
/** * Copyright (c) 2012, Thilo Planz. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the Apache License, Version 2.0 * as published by the Apache Software Foundation (the "License"). * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * * You should have received a copy of the License along with this program. * If not, see <http://www.apache.org/licenses/LICENSE-2.0>. */ package jmockmongo.wire; class DeleteMessage extends Message { static final int OP_CODE_DELETE = 2006; // struct { // MsgHeader header; // standard message header // int32 ZERO; // 0 - reserved for future use // cstring fullCollectionName; // "dbname.collectionname" // int32 flags; // bit vector - see below for details. // document selector; // query object. See below for details. // } private final int flags; private final String fullCollectionName; private BSONObject query; DeleteMessage(ChannelBuffer data) { super(data, OP_CODE_DELETE); byte[] fourBytes = new byte[4]; readInt32(data, fourBytes); fullCollectionName = readCString(data); flags = readInt32(data, fourBytes); } BSONObject getQuery() { if (query == null) { byte[] fourBytes = new byte[4];
// Path: src/main/java/jmockmongo/wire/MessageDecoder.java // static final String readCString(ChannelBuffer buffer) { // // find the terminating zero-byte // int length = buffer.bytesBefore((byte) 0); // byte[] bytes = new byte[length]; // buffer.readBytes(bytes); // // also skip the terminator // buffer.readByte(); // try { // return new String(bytes, "UTF-8"); // } catch (java.io.UnsupportedEncodingException uee) { // throw new BSONException("impossible", uee); // } // } // // Path: src/main/java/jmockmongo/wire/MessageDecoder.java // static final BSONObject readDocument(ChannelBuffer buffer, byte[] fourBytes) { // int length = readInt32(buffer, fourBytes); // byte[] bson = new byte[length]; // buffer.readBytes(bson, 4, length - 4); // System.arraycopy(fourBytes, 0, bson, 0, 4); // return BSON.decode(bson); // // } // // Path: src/main/java/jmockmongo/wire/MessageDecoder.java // static final int readInt32(ChannelBuffer buffer, byte[] fourBytes) { // buffer.readBytes(fourBytes); // return Bits.readInt(fourBytes); // } // Path: src/main/java/jmockmongo/wire/DeleteMessage.java import static jmockmongo.wire.MessageDecoder.readCString; import static jmockmongo.wire.MessageDecoder.readDocument; import static jmockmongo.wire.MessageDecoder.readInt32; import org.bson.BSONObject; import org.jboss.netty.buffer.ChannelBuffer; /** * Copyright (c) 2012, Thilo Planz. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the Apache License, Version 2.0 * as published by the Apache Software Foundation (the "License"). * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * * You should have received a copy of the License along with this program. * If not, see <http://www.apache.org/licenses/LICENSE-2.0>. */ package jmockmongo.wire; class DeleteMessage extends Message { static final int OP_CODE_DELETE = 2006; // struct { // MsgHeader header; // standard message header // int32 ZERO; // 0 - reserved for future use // cstring fullCollectionName; // "dbname.collectionname" // int32 flags; // bit vector - see below for details. // document selector; // query object. See below for details. // } private final int flags; private final String fullCollectionName; private BSONObject query; DeleteMessage(ChannelBuffer data) { super(data, OP_CODE_DELETE); byte[] fourBytes = new byte[4]; readInt32(data, fourBytes); fullCollectionName = readCString(data); flags = readInt32(data, fourBytes); } BSONObject getQuery() { if (query == null) { byte[] fourBytes = new byte[4];
query = readDocument(data, fourBytes);
thiloplanz/jmockmongo
src/main/java/jmockmongo/wire/ReplyMessage.java
// Path: src/main/java/jmockmongo/wire/MessageDecoder.java // static final int readInt32(ChannelBuffer buffer, byte[] fourBytes) { // buffer.readBytes(fourBytes); // return Bits.readInt(fourBytes); // }
import static jmockmongo.wire.MessageDecoder.readInt32; import org.bson.BSON; import org.bson.BSONObject; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers;
/** * Copyright (c) 2012, Thilo Planz. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the Apache License, Version 2.0 * as published by the Apache Software Foundation (the "License"). * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * * You should have received a copy of the License along with this program. * If not, see <http://www.apache.org/licenses/LICENSE-2.0>. */ package jmockmongo.wire; class ReplyMessage extends Message { static final int OP_CODE_REPLY = 1; // struct { // MsgHeader header; // standard message header // int32 responseFlags; // bit vector - see details below // int64 cursorID; // cursor id if client needs to do get more's // int32 startingFrom; // where in the cursor this reply is starting // int32 numberReturned; // number of documents in the reply // document* documents; // documents // } // private final int responseFlags; private final long cursorId; private final int startingFrom; private final int numberReturned; ReplyMessage(ChannelBuffer data) { super(data, OP_CODE_REPLY); byte[] fourBytes = new byte[4]; byte[] eightBytes = new byte[8];
// Path: src/main/java/jmockmongo/wire/MessageDecoder.java // static final int readInt32(ChannelBuffer buffer, byte[] fourBytes) { // buffer.readBytes(fourBytes); // return Bits.readInt(fourBytes); // } // Path: src/main/java/jmockmongo/wire/ReplyMessage.java import static jmockmongo.wire.MessageDecoder.readInt32; import org.bson.BSON; import org.bson.BSONObject; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; /** * Copyright (c) 2012, Thilo Planz. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the Apache License, Version 2.0 * as published by the Apache Software Foundation (the "License"). * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * * You should have received a copy of the License along with this program. * If not, see <http://www.apache.org/licenses/LICENSE-2.0>. */ package jmockmongo.wire; class ReplyMessage extends Message { static final int OP_CODE_REPLY = 1; // struct { // MsgHeader header; // standard message header // int32 responseFlags; // bit vector - see details below // int64 cursorID; // cursor id if client needs to do get more's // int32 startingFrom; // where in the cursor this reply is starting // int32 numberReturned; // number of documents in the reply // document* documents; // documents // } // private final int responseFlags; private final long cursorId; private final int startingFrom; private final int numberReturned; ReplyMessage(ChannelBuffer data) { super(data, OP_CODE_REPLY); byte[] fourBytes = new byte[4]; byte[] eightBytes = new byte[8];
responseFlags = readInt32(data, fourBytes);
thiloplanz/jmockmongo
src/main/java/jmockmongo/wire/UpdateMessage.java
// Path: src/main/java/jmockmongo/wire/MessageDecoder.java // static final String readCString(ChannelBuffer buffer) { // // find the terminating zero-byte // int length = buffer.bytesBefore((byte) 0); // byte[] bytes = new byte[length]; // buffer.readBytes(bytes); // // also skip the terminator // buffer.readByte(); // try { // return new String(bytes, "UTF-8"); // } catch (java.io.UnsupportedEncodingException uee) { // throw new BSONException("impossible", uee); // } // } // // Path: src/main/java/jmockmongo/wire/MessageDecoder.java // static final BSONObject readDocument(ChannelBuffer buffer, byte[] fourBytes) { // int length = readInt32(buffer, fourBytes); // byte[] bson = new byte[length]; // buffer.readBytes(bson, 4, length - 4); // System.arraycopy(fourBytes, 0, bson, 0, 4); // return BSON.decode(bson); // // } // // Path: src/main/java/jmockmongo/wire/MessageDecoder.java // static final int readInt32(ChannelBuffer buffer, byte[] fourBytes) { // buffer.readBytes(fourBytes); // return Bits.readInt(fourBytes); // }
import static jmockmongo.wire.MessageDecoder.readCString; import static jmockmongo.wire.MessageDecoder.readDocument; import static jmockmongo.wire.MessageDecoder.readInt32; import org.bson.BSONObject; import org.jboss.netty.buffer.ChannelBuffer;
/** * Copyright (c) 2012, Thilo Planz. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the Apache License, Version 2.0 * as published by the Apache Software Foundation (the "License"). * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * * You should have received a copy of the License along with this program. * If not, see <http://www.apache.org/licenses/LICENSE-2.0>. */ package jmockmongo.wire; public class UpdateMessage extends Message { static final int OP_CODE_UPDATE = 2001; // struct OP_UPDATE { // MsgHeader header; // standard message header // int32 ZERO; // 0 - reserved for future use // cstring fullCollectionName; // "dbname.collectionname" // int32 flags; // bit vector. see below // document selector; // the query to select the document // document update; // specification of the update to perform // } private final String fullCollectionName; String getFullCollectionName() { return fullCollectionName; } private final int flags; private BSONObject selector; private BSONObject update; UpdateMessage(ChannelBuffer data) { super(data, OP_CODE_UPDATE); byte[] fourBytes = new byte[4]; // int32 ZERO
// Path: src/main/java/jmockmongo/wire/MessageDecoder.java // static final String readCString(ChannelBuffer buffer) { // // find the terminating zero-byte // int length = buffer.bytesBefore((byte) 0); // byte[] bytes = new byte[length]; // buffer.readBytes(bytes); // // also skip the terminator // buffer.readByte(); // try { // return new String(bytes, "UTF-8"); // } catch (java.io.UnsupportedEncodingException uee) { // throw new BSONException("impossible", uee); // } // } // // Path: src/main/java/jmockmongo/wire/MessageDecoder.java // static final BSONObject readDocument(ChannelBuffer buffer, byte[] fourBytes) { // int length = readInt32(buffer, fourBytes); // byte[] bson = new byte[length]; // buffer.readBytes(bson, 4, length - 4); // System.arraycopy(fourBytes, 0, bson, 0, 4); // return BSON.decode(bson); // // } // // Path: src/main/java/jmockmongo/wire/MessageDecoder.java // static final int readInt32(ChannelBuffer buffer, byte[] fourBytes) { // buffer.readBytes(fourBytes); // return Bits.readInt(fourBytes); // } // Path: src/main/java/jmockmongo/wire/UpdateMessage.java import static jmockmongo.wire.MessageDecoder.readCString; import static jmockmongo.wire.MessageDecoder.readDocument; import static jmockmongo.wire.MessageDecoder.readInt32; import org.bson.BSONObject; import org.jboss.netty.buffer.ChannelBuffer; /** * Copyright (c) 2012, Thilo Planz. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the Apache License, Version 2.0 * as published by the Apache Software Foundation (the "License"). * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * * You should have received a copy of the License along with this program. * If not, see <http://www.apache.org/licenses/LICENSE-2.0>. */ package jmockmongo.wire; public class UpdateMessage extends Message { static final int OP_CODE_UPDATE = 2001; // struct OP_UPDATE { // MsgHeader header; // standard message header // int32 ZERO; // 0 - reserved for future use // cstring fullCollectionName; // "dbname.collectionname" // int32 flags; // bit vector. see below // document selector; // the query to select the document // document update; // specification of the update to perform // } private final String fullCollectionName; String getFullCollectionName() { return fullCollectionName; } private final int flags; private BSONObject selector; private BSONObject update; UpdateMessage(ChannelBuffer data) { super(data, OP_CODE_UPDATE); byte[] fourBytes = new byte[4]; // int32 ZERO
readInt32(data, fourBytes);
thiloplanz/jmockmongo
src/main/java/jmockmongo/wire/UpdateMessage.java
// Path: src/main/java/jmockmongo/wire/MessageDecoder.java // static final String readCString(ChannelBuffer buffer) { // // find the terminating zero-byte // int length = buffer.bytesBefore((byte) 0); // byte[] bytes = new byte[length]; // buffer.readBytes(bytes); // // also skip the terminator // buffer.readByte(); // try { // return new String(bytes, "UTF-8"); // } catch (java.io.UnsupportedEncodingException uee) { // throw new BSONException("impossible", uee); // } // } // // Path: src/main/java/jmockmongo/wire/MessageDecoder.java // static final BSONObject readDocument(ChannelBuffer buffer, byte[] fourBytes) { // int length = readInt32(buffer, fourBytes); // byte[] bson = new byte[length]; // buffer.readBytes(bson, 4, length - 4); // System.arraycopy(fourBytes, 0, bson, 0, 4); // return BSON.decode(bson); // // } // // Path: src/main/java/jmockmongo/wire/MessageDecoder.java // static final int readInt32(ChannelBuffer buffer, byte[] fourBytes) { // buffer.readBytes(fourBytes); // return Bits.readInt(fourBytes); // }
import static jmockmongo.wire.MessageDecoder.readCString; import static jmockmongo.wire.MessageDecoder.readDocument; import static jmockmongo.wire.MessageDecoder.readInt32; import org.bson.BSONObject; import org.jboss.netty.buffer.ChannelBuffer;
/** * Copyright (c) 2012, Thilo Planz. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the Apache License, Version 2.0 * as published by the Apache Software Foundation (the "License"). * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * * You should have received a copy of the License along with this program. * If not, see <http://www.apache.org/licenses/LICENSE-2.0>. */ package jmockmongo.wire; public class UpdateMessage extends Message { static final int OP_CODE_UPDATE = 2001; // struct OP_UPDATE { // MsgHeader header; // standard message header // int32 ZERO; // 0 - reserved for future use // cstring fullCollectionName; // "dbname.collectionname" // int32 flags; // bit vector. see below // document selector; // the query to select the document // document update; // specification of the update to perform // } private final String fullCollectionName; String getFullCollectionName() { return fullCollectionName; } private final int flags; private BSONObject selector; private BSONObject update; UpdateMessage(ChannelBuffer data) { super(data, OP_CODE_UPDATE); byte[] fourBytes = new byte[4]; // int32 ZERO readInt32(data, fourBytes);
// Path: src/main/java/jmockmongo/wire/MessageDecoder.java // static final String readCString(ChannelBuffer buffer) { // // find the terminating zero-byte // int length = buffer.bytesBefore((byte) 0); // byte[] bytes = new byte[length]; // buffer.readBytes(bytes); // // also skip the terminator // buffer.readByte(); // try { // return new String(bytes, "UTF-8"); // } catch (java.io.UnsupportedEncodingException uee) { // throw new BSONException("impossible", uee); // } // } // // Path: src/main/java/jmockmongo/wire/MessageDecoder.java // static final BSONObject readDocument(ChannelBuffer buffer, byte[] fourBytes) { // int length = readInt32(buffer, fourBytes); // byte[] bson = new byte[length]; // buffer.readBytes(bson, 4, length - 4); // System.arraycopy(fourBytes, 0, bson, 0, 4); // return BSON.decode(bson); // // } // // Path: src/main/java/jmockmongo/wire/MessageDecoder.java // static final int readInt32(ChannelBuffer buffer, byte[] fourBytes) { // buffer.readBytes(fourBytes); // return Bits.readInt(fourBytes); // } // Path: src/main/java/jmockmongo/wire/UpdateMessage.java import static jmockmongo.wire.MessageDecoder.readCString; import static jmockmongo.wire.MessageDecoder.readDocument; import static jmockmongo.wire.MessageDecoder.readInt32; import org.bson.BSONObject; import org.jboss.netty.buffer.ChannelBuffer; /** * Copyright (c) 2012, Thilo Planz. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the Apache License, Version 2.0 * as published by the Apache Software Foundation (the "License"). * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * * You should have received a copy of the License along with this program. * If not, see <http://www.apache.org/licenses/LICENSE-2.0>. */ package jmockmongo.wire; public class UpdateMessage extends Message { static final int OP_CODE_UPDATE = 2001; // struct OP_UPDATE { // MsgHeader header; // standard message header // int32 ZERO; // 0 - reserved for future use // cstring fullCollectionName; // "dbname.collectionname" // int32 flags; // bit vector. see below // document selector; // the query to select the document // document update; // specification of the update to perform // } private final String fullCollectionName; String getFullCollectionName() { return fullCollectionName; } private final int flags; private BSONObject selector; private BSONObject update; UpdateMessage(ChannelBuffer data) { super(data, OP_CODE_UPDATE); byte[] fourBytes = new byte[4]; // int32 ZERO readInt32(data, fourBytes);
fullCollectionName = readCString(data);
thiloplanz/jmockmongo
src/main/java/jmockmongo/wire/UpdateMessage.java
// Path: src/main/java/jmockmongo/wire/MessageDecoder.java // static final String readCString(ChannelBuffer buffer) { // // find the terminating zero-byte // int length = buffer.bytesBefore((byte) 0); // byte[] bytes = new byte[length]; // buffer.readBytes(bytes); // // also skip the terminator // buffer.readByte(); // try { // return new String(bytes, "UTF-8"); // } catch (java.io.UnsupportedEncodingException uee) { // throw new BSONException("impossible", uee); // } // } // // Path: src/main/java/jmockmongo/wire/MessageDecoder.java // static final BSONObject readDocument(ChannelBuffer buffer, byte[] fourBytes) { // int length = readInt32(buffer, fourBytes); // byte[] bson = new byte[length]; // buffer.readBytes(bson, 4, length - 4); // System.arraycopy(fourBytes, 0, bson, 0, 4); // return BSON.decode(bson); // // } // // Path: src/main/java/jmockmongo/wire/MessageDecoder.java // static final int readInt32(ChannelBuffer buffer, byte[] fourBytes) { // buffer.readBytes(fourBytes); // return Bits.readInt(fourBytes); // }
import static jmockmongo.wire.MessageDecoder.readCString; import static jmockmongo.wire.MessageDecoder.readDocument; import static jmockmongo.wire.MessageDecoder.readInt32; import org.bson.BSONObject; import org.jboss.netty.buffer.ChannelBuffer;
/** * Copyright (c) 2012, Thilo Planz. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the Apache License, Version 2.0 * as published by the Apache Software Foundation (the "License"). * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * * You should have received a copy of the License along with this program. * If not, see <http://www.apache.org/licenses/LICENSE-2.0>. */ package jmockmongo.wire; public class UpdateMessage extends Message { static final int OP_CODE_UPDATE = 2001; // struct OP_UPDATE { // MsgHeader header; // standard message header // int32 ZERO; // 0 - reserved for future use // cstring fullCollectionName; // "dbname.collectionname" // int32 flags; // bit vector. see below // document selector; // the query to select the document // document update; // specification of the update to perform // } private final String fullCollectionName; String getFullCollectionName() { return fullCollectionName; } private final int flags; private BSONObject selector; private BSONObject update; UpdateMessage(ChannelBuffer data) { super(data, OP_CODE_UPDATE); byte[] fourBytes = new byte[4]; // int32 ZERO readInt32(data, fourBytes); fullCollectionName = readCString(data); flags = readInt32(data, fourBytes); } BSONObject getSelector() { if (selector == null) { byte[] fourBytes = new byte[4];
// Path: src/main/java/jmockmongo/wire/MessageDecoder.java // static final String readCString(ChannelBuffer buffer) { // // find the terminating zero-byte // int length = buffer.bytesBefore((byte) 0); // byte[] bytes = new byte[length]; // buffer.readBytes(bytes); // // also skip the terminator // buffer.readByte(); // try { // return new String(bytes, "UTF-8"); // } catch (java.io.UnsupportedEncodingException uee) { // throw new BSONException("impossible", uee); // } // } // // Path: src/main/java/jmockmongo/wire/MessageDecoder.java // static final BSONObject readDocument(ChannelBuffer buffer, byte[] fourBytes) { // int length = readInt32(buffer, fourBytes); // byte[] bson = new byte[length]; // buffer.readBytes(bson, 4, length - 4); // System.arraycopy(fourBytes, 0, bson, 0, 4); // return BSON.decode(bson); // // } // // Path: src/main/java/jmockmongo/wire/MessageDecoder.java // static final int readInt32(ChannelBuffer buffer, byte[] fourBytes) { // buffer.readBytes(fourBytes); // return Bits.readInt(fourBytes); // } // Path: src/main/java/jmockmongo/wire/UpdateMessage.java import static jmockmongo.wire.MessageDecoder.readCString; import static jmockmongo.wire.MessageDecoder.readDocument; import static jmockmongo.wire.MessageDecoder.readInt32; import org.bson.BSONObject; import org.jboss.netty.buffer.ChannelBuffer; /** * Copyright (c) 2012, Thilo Planz. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the Apache License, Version 2.0 * as published by the Apache Software Foundation (the "License"). * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * * You should have received a copy of the License along with this program. * If not, see <http://www.apache.org/licenses/LICENSE-2.0>. */ package jmockmongo.wire; public class UpdateMessage extends Message { static final int OP_CODE_UPDATE = 2001; // struct OP_UPDATE { // MsgHeader header; // standard message header // int32 ZERO; // 0 - reserved for future use // cstring fullCollectionName; // "dbname.collectionname" // int32 flags; // bit vector. see below // document selector; // the query to select the document // document update; // specification of the update to perform // } private final String fullCollectionName; String getFullCollectionName() { return fullCollectionName; } private final int flags; private BSONObject selector; private BSONObject update; UpdateMessage(ChannelBuffer data) { super(data, OP_CODE_UPDATE); byte[] fourBytes = new byte[4]; // int32 ZERO readInt32(data, fourBytes); fullCollectionName = readCString(data); flags = readInt32(data, fourBytes); } BSONObject getSelector() { if (selector == null) { byte[] fourBytes = new byte[4];
selector = readDocument(data, fourBytes);
thiloplanz/jmockmongo
src/main/java/jmockmongo/wire/QueryMessage.java
// Path: src/main/java/jmockmongo/wire/MessageDecoder.java // static final String readCString(ChannelBuffer buffer) { // // find the terminating zero-byte // int length = buffer.bytesBefore((byte) 0); // byte[] bytes = new byte[length]; // buffer.readBytes(bytes); // // also skip the terminator // buffer.readByte(); // try { // return new String(bytes, "UTF-8"); // } catch (java.io.UnsupportedEncodingException uee) { // throw new BSONException("impossible", uee); // } // } // // Path: src/main/java/jmockmongo/wire/MessageDecoder.java // static final BSONObject readDocument(ChannelBuffer buffer, byte[] fourBytes) { // int length = readInt32(buffer, fourBytes); // byte[] bson = new byte[length]; // buffer.readBytes(bson, 4, length - 4); // System.arraycopy(fourBytes, 0, bson, 0, 4); // return BSON.decode(bson); // // } // // Path: src/main/java/jmockmongo/wire/MessageDecoder.java // static final int readInt32(ChannelBuffer buffer, byte[] fourBytes) { // buffer.readBytes(fourBytes); // return Bits.readInt(fourBytes); // }
import static jmockmongo.wire.MessageDecoder.readCString; import static jmockmongo.wire.MessageDecoder.readDocument; import static jmockmongo.wire.MessageDecoder.readInt32; import org.bson.BSONObject; import org.jboss.netty.buffer.ChannelBuffer;
/** * Copyright (c) 2012, Thilo Planz. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the Apache License, Version 2.0 * as published by the Apache Software Foundation (the "License"). * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * * You should have received a copy of the License along with this program. * If not, see <http://www.apache.org/licenses/LICENSE-2.0>. */ package jmockmongo.wire; class QueryMessage extends Message { static final int OP_CODE_QUERY = 2004; // struct OP_QUERY { // MsgHeader header; // standard message header // int32 flags; // bit vector of query options. See below for details. // cstring fullCollectionName; // "dbname.collectionname" // int32 numberToSkip; // number of documents to skip // int32 numberToReturn; // number of documents to return // // in the first OP_REPLY batch // document query; // query object. See below for details. // [ document returnFieldSelector; ] // Optional. Selector indicating the // fields // // to return. See below for details. // } private final int flags; private final String fullCollectionName; private final int numberToSkip; private final int numberToReturn; private BSONObject query; private BSONObject returnFieldSelector; QueryMessage(ChannelBuffer data) { super(data, OP_CODE_QUERY); byte[] fourBytes = new byte[4];
// Path: src/main/java/jmockmongo/wire/MessageDecoder.java // static final String readCString(ChannelBuffer buffer) { // // find the terminating zero-byte // int length = buffer.bytesBefore((byte) 0); // byte[] bytes = new byte[length]; // buffer.readBytes(bytes); // // also skip the terminator // buffer.readByte(); // try { // return new String(bytes, "UTF-8"); // } catch (java.io.UnsupportedEncodingException uee) { // throw new BSONException("impossible", uee); // } // } // // Path: src/main/java/jmockmongo/wire/MessageDecoder.java // static final BSONObject readDocument(ChannelBuffer buffer, byte[] fourBytes) { // int length = readInt32(buffer, fourBytes); // byte[] bson = new byte[length]; // buffer.readBytes(bson, 4, length - 4); // System.arraycopy(fourBytes, 0, bson, 0, 4); // return BSON.decode(bson); // // } // // Path: src/main/java/jmockmongo/wire/MessageDecoder.java // static final int readInt32(ChannelBuffer buffer, byte[] fourBytes) { // buffer.readBytes(fourBytes); // return Bits.readInt(fourBytes); // } // Path: src/main/java/jmockmongo/wire/QueryMessage.java import static jmockmongo.wire.MessageDecoder.readCString; import static jmockmongo.wire.MessageDecoder.readDocument; import static jmockmongo.wire.MessageDecoder.readInt32; import org.bson.BSONObject; import org.jboss.netty.buffer.ChannelBuffer; /** * Copyright (c) 2012, Thilo Planz. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the Apache License, Version 2.0 * as published by the Apache Software Foundation (the "License"). * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * * You should have received a copy of the License along with this program. * If not, see <http://www.apache.org/licenses/LICENSE-2.0>. */ package jmockmongo.wire; class QueryMessage extends Message { static final int OP_CODE_QUERY = 2004; // struct OP_QUERY { // MsgHeader header; // standard message header // int32 flags; // bit vector of query options. See below for details. // cstring fullCollectionName; // "dbname.collectionname" // int32 numberToSkip; // number of documents to skip // int32 numberToReturn; // number of documents to return // // in the first OP_REPLY batch // document query; // query object. See below for details. // [ document returnFieldSelector; ] // Optional. Selector indicating the // fields // // to return. See below for details. // } private final int flags; private final String fullCollectionName; private final int numberToSkip; private final int numberToReturn; private BSONObject query; private BSONObject returnFieldSelector; QueryMessage(ChannelBuffer data) { super(data, OP_CODE_QUERY); byte[] fourBytes = new byte[4];
flags = readInt32(data, fourBytes);
thiloplanz/jmockmongo
src/main/java/jmockmongo/wire/QueryMessage.java
// Path: src/main/java/jmockmongo/wire/MessageDecoder.java // static final String readCString(ChannelBuffer buffer) { // // find the terminating zero-byte // int length = buffer.bytesBefore((byte) 0); // byte[] bytes = new byte[length]; // buffer.readBytes(bytes); // // also skip the terminator // buffer.readByte(); // try { // return new String(bytes, "UTF-8"); // } catch (java.io.UnsupportedEncodingException uee) { // throw new BSONException("impossible", uee); // } // } // // Path: src/main/java/jmockmongo/wire/MessageDecoder.java // static final BSONObject readDocument(ChannelBuffer buffer, byte[] fourBytes) { // int length = readInt32(buffer, fourBytes); // byte[] bson = new byte[length]; // buffer.readBytes(bson, 4, length - 4); // System.arraycopy(fourBytes, 0, bson, 0, 4); // return BSON.decode(bson); // // } // // Path: src/main/java/jmockmongo/wire/MessageDecoder.java // static final int readInt32(ChannelBuffer buffer, byte[] fourBytes) { // buffer.readBytes(fourBytes); // return Bits.readInt(fourBytes); // }
import static jmockmongo.wire.MessageDecoder.readCString; import static jmockmongo.wire.MessageDecoder.readDocument; import static jmockmongo.wire.MessageDecoder.readInt32; import org.bson.BSONObject; import org.jboss.netty.buffer.ChannelBuffer;
/** * Copyright (c) 2012, Thilo Planz. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the Apache License, Version 2.0 * as published by the Apache Software Foundation (the "License"). * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * * You should have received a copy of the License along with this program. * If not, see <http://www.apache.org/licenses/LICENSE-2.0>. */ package jmockmongo.wire; class QueryMessage extends Message { static final int OP_CODE_QUERY = 2004; // struct OP_QUERY { // MsgHeader header; // standard message header // int32 flags; // bit vector of query options. See below for details. // cstring fullCollectionName; // "dbname.collectionname" // int32 numberToSkip; // number of documents to skip // int32 numberToReturn; // number of documents to return // // in the first OP_REPLY batch // document query; // query object. See below for details. // [ document returnFieldSelector; ] // Optional. Selector indicating the // fields // // to return. See below for details. // } private final int flags; private final String fullCollectionName; private final int numberToSkip; private final int numberToReturn; private BSONObject query; private BSONObject returnFieldSelector; QueryMessage(ChannelBuffer data) { super(data, OP_CODE_QUERY); byte[] fourBytes = new byte[4]; flags = readInt32(data, fourBytes);
// Path: src/main/java/jmockmongo/wire/MessageDecoder.java // static final String readCString(ChannelBuffer buffer) { // // find the terminating zero-byte // int length = buffer.bytesBefore((byte) 0); // byte[] bytes = new byte[length]; // buffer.readBytes(bytes); // // also skip the terminator // buffer.readByte(); // try { // return new String(bytes, "UTF-8"); // } catch (java.io.UnsupportedEncodingException uee) { // throw new BSONException("impossible", uee); // } // } // // Path: src/main/java/jmockmongo/wire/MessageDecoder.java // static final BSONObject readDocument(ChannelBuffer buffer, byte[] fourBytes) { // int length = readInt32(buffer, fourBytes); // byte[] bson = new byte[length]; // buffer.readBytes(bson, 4, length - 4); // System.arraycopy(fourBytes, 0, bson, 0, 4); // return BSON.decode(bson); // // } // // Path: src/main/java/jmockmongo/wire/MessageDecoder.java // static final int readInt32(ChannelBuffer buffer, byte[] fourBytes) { // buffer.readBytes(fourBytes); // return Bits.readInt(fourBytes); // } // Path: src/main/java/jmockmongo/wire/QueryMessage.java import static jmockmongo.wire.MessageDecoder.readCString; import static jmockmongo.wire.MessageDecoder.readDocument; import static jmockmongo.wire.MessageDecoder.readInt32; import org.bson.BSONObject; import org.jboss.netty.buffer.ChannelBuffer; /** * Copyright (c) 2012, Thilo Planz. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the Apache License, Version 2.0 * as published by the Apache Software Foundation (the "License"). * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * * You should have received a copy of the License along with this program. * If not, see <http://www.apache.org/licenses/LICENSE-2.0>. */ package jmockmongo.wire; class QueryMessage extends Message { static final int OP_CODE_QUERY = 2004; // struct OP_QUERY { // MsgHeader header; // standard message header // int32 flags; // bit vector of query options. See below for details. // cstring fullCollectionName; // "dbname.collectionname" // int32 numberToSkip; // number of documents to skip // int32 numberToReturn; // number of documents to return // // in the first OP_REPLY batch // document query; // query object. See below for details. // [ document returnFieldSelector; ] // Optional. Selector indicating the // fields // // to return. See below for details. // } private final int flags; private final String fullCollectionName; private final int numberToSkip; private final int numberToReturn; private BSONObject query; private BSONObject returnFieldSelector; QueryMessage(ChannelBuffer data) { super(data, OP_CODE_QUERY); byte[] fourBytes = new byte[4]; flags = readInt32(data, fourBytes);
fullCollectionName = readCString(data);
thiloplanz/jmockmongo
src/main/java/jmockmongo/wire/QueryMessage.java
// Path: src/main/java/jmockmongo/wire/MessageDecoder.java // static final String readCString(ChannelBuffer buffer) { // // find the terminating zero-byte // int length = buffer.bytesBefore((byte) 0); // byte[] bytes = new byte[length]; // buffer.readBytes(bytes); // // also skip the terminator // buffer.readByte(); // try { // return new String(bytes, "UTF-8"); // } catch (java.io.UnsupportedEncodingException uee) { // throw new BSONException("impossible", uee); // } // } // // Path: src/main/java/jmockmongo/wire/MessageDecoder.java // static final BSONObject readDocument(ChannelBuffer buffer, byte[] fourBytes) { // int length = readInt32(buffer, fourBytes); // byte[] bson = new byte[length]; // buffer.readBytes(bson, 4, length - 4); // System.arraycopy(fourBytes, 0, bson, 0, 4); // return BSON.decode(bson); // // } // // Path: src/main/java/jmockmongo/wire/MessageDecoder.java // static final int readInt32(ChannelBuffer buffer, byte[] fourBytes) { // buffer.readBytes(fourBytes); // return Bits.readInt(fourBytes); // }
import static jmockmongo.wire.MessageDecoder.readCString; import static jmockmongo.wire.MessageDecoder.readDocument; import static jmockmongo.wire.MessageDecoder.readInt32; import org.bson.BSONObject; import org.jboss.netty.buffer.ChannelBuffer;
/** * Copyright (c) 2012, Thilo Planz. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the Apache License, Version 2.0 * as published by the Apache Software Foundation (the "License"). * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * * You should have received a copy of the License along with this program. * If not, see <http://www.apache.org/licenses/LICENSE-2.0>. */ package jmockmongo.wire; class QueryMessage extends Message { static final int OP_CODE_QUERY = 2004; // struct OP_QUERY { // MsgHeader header; // standard message header // int32 flags; // bit vector of query options. See below for details. // cstring fullCollectionName; // "dbname.collectionname" // int32 numberToSkip; // number of documents to skip // int32 numberToReturn; // number of documents to return // // in the first OP_REPLY batch // document query; // query object. See below for details. // [ document returnFieldSelector; ] // Optional. Selector indicating the // fields // // to return. See below for details. // } private final int flags; private final String fullCollectionName; private final int numberToSkip; private final int numberToReturn; private BSONObject query; private BSONObject returnFieldSelector; QueryMessage(ChannelBuffer data) { super(data, OP_CODE_QUERY); byte[] fourBytes = new byte[4]; flags = readInt32(data, fourBytes); fullCollectionName = readCString(data); numberToSkip = readInt32(data, fourBytes); numberToReturn = readInt32(data, fourBytes); } BSONObject getQuery() { if (query == null) { byte[] fourBytes = new byte[4];
// Path: src/main/java/jmockmongo/wire/MessageDecoder.java // static final String readCString(ChannelBuffer buffer) { // // find the terminating zero-byte // int length = buffer.bytesBefore((byte) 0); // byte[] bytes = new byte[length]; // buffer.readBytes(bytes); // // also skip the terminator // buffer.readByte(); // try { // return new String(bytes, "UTF-8"); // } catch (java.io.UnsupportedEncodingException uee) { // throw new BSONException("impossible", uee); // } // } // // Path: src/main/java/jmockmongo/wire/MessageDecoder.java // static final BSONObject readDocument(ChannelBuffer buffer, byte[] fourBytes) { // int length = readInt32(buffer, fourBytes); // byte[] bson = new byte[length]; // buffer.readBytes(bson, 4, length - 4); // System.arraycopy(fourBytes, 0, bson, 0, 4); // return BSON.decode(bson); // // } // // Path: src/main/java/jmockmongo/wire/MessageDecoder.java // static final int readInt32(ChannelBuffer buffer, byte[] fourBytes) { // buffer.readBytes(fourBytes); // return Bits.readInt(fourBytes); // } // Path: src/main/java/jmockmongo/wire/QueryMessage.java import static jmockmongo.wire.MessageDecoder.readCString; import static jmockmongo.wire.MessageDecoder.readDocument; import static jmockmongo.wire.MessageDecoder.readInt32; import org.bson.BSONObject; import org.jboss.netty.buffer.ChannelBuffer; /** * Copyright (c) 2012, Thilo Planz. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the Apache License, Version 2.0 * as published by the Apache Software Foundation (the "License"). * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * * You should have received a copy of the License along with this program. * If not, see <http://www.apache.org/licenses/LICENSE-2.0>. */ package jmockmongo.wire; class QueryMessage extends Message { static final int OP_CODE_QUERY = 2004; // struct OP_QUERY { // MsgHeader header; // standard message header // int32 flags; // bit vector of query options. See below for details. // cstring fullCollectionName; // "dbname.collectionname" // int32 numberToSkip; // number of documents to skip // int32 numberToReturn; // number of documents to return // // in the first OP_REPLY batch // document query; // query object. See below for details. // [ document returnFieldSelector; ] // Optional. Selector indicating the // fields // // to return. See below for details. // } private final int flags; private final String fullCollectionName; private final int numberToSkip; private final int numberToReturn; private BSONObject query; private BSONObject returnFieldSelector; QueryMessage(ChannelBuffer data) { super(data, OP_CODE_QUERY); byte[] fourBytes = new byte[4]; flags = readInt32(data, fourBytes); fullCollectionName = readCString(data); numberToSkip = readInt32(data, fourBytes); numberToReturn = readInt32(data, fourBytes); } BSONObject getQuery() { if (query == null) { byte[] fourBytes = new byte[4];
query = readDocument(data, fourBytes);
thiloplanz/jmockmongo
src/main/java/jmockmongo/wire/Message.java
// Path: src/main/java/jmockmongo/wire/MessageDecoder.java // static final int readInt32(ChannelBuffer buffer, byte[] fourBytes) { // buffer.readBytes(fourBytes); // return Bits.readInt(fourBytes); // }
import static jmockmongo.wire.MessageDecoder.readInt32; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers;
/** * Copyright (c) 2012, Thilo Planz. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the Apache License, Version 2.0 * as published by the Apache Software Foundation (the "License"). * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * * You should have received a copy of the License along with this program. * If not, see <http://www.apache.org/licenses/LICENSE-2.0>. */ package jmockmongo.wire; abstract class Message { // struct MsgHeader { // int32 messageLength; // total message size, including this // int32 requestID; // identifier for this message // int32 responseTo; // requestID from the original request // // (used in reponses from db) // int32 opCode; // request type - see table below // } private final int messageLength; private final int requestId; private final int responseTo; protected final int opCode; protected final ChannelBuffer data; Message(ChannelBuffer data, int expectedOpCode) { byte[] fourBytes = new byte[4]; int check = data.readableBytes();
// Path: src/main/java/jmockmongo/wire/MessageDecoder.java // static final int readInt32(ChannelBuffer buffer, byte[] fourBytes) { // buffer.readBytes(fourBytes); // return Bits.readInt(fourBytes); // } // Path: src/main/java/jmockmongo/wire/Message.java import static jmockmongo.wire.MessageDecoder.readInt32; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; /** * Copyright (c) 2012, Thilo Planz. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the Apache License, Version 2.0 * as published by the Apache Software Foundation (the "License"). * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * * You should have received a copy of the License along with this program. * If not, see <http://www.apache.org/licenses/LICENSE-2.0>. */ package jmockmongo.wire; abstract class Message { // struct MsgHeader { // int32 messageLength; // total message size, including this // int32 requestID; // identifier for this message // int32 responseTo; // requestID from the original request // // (used in reponses from db) // int32 opCode; // request type - see table below // } private final int messageLength; private final int requestId; private final int responseTo; protected final int opCode; protected final ChannelBuffer data; Message(ChannelBuffer data, int expectedOpCode) { byte[] fourBytes = new byte[4]; int check = data.readableBytes();
this.messageLength = readInt32(data, fourBytes);
thiloplanz/jmockmongo
src/main/java/jmockmongo/wire/ReplyHandler.java
// Path: src/main/java/jmockmongo/CommandHandler.java // public interface CommandHandler { // // public BSONObject handleCommand(String database, BSONObject command); // // } // // Path: src/main/java/jmockmongo/DeleteHandler.java // public interface DeleteHandler { // // public Result handleDelete(String database, String collection, // boolean singleRemove, BSONObject selector); // } // // Path: src/main/java/jmockmongo/InsertHandler.java // public interface InsertHandler { // // public Result handleInsert(String database, String collection, // boolean continueOnError, Iterator<BSONObject> data); // } // // Path: src/main/java/jmockmongo/QueryHandler.java // public interface QueryHandler { // // public BSONObject[] handleQuery(String database, String collection, // BSONObject command); // // } // // Path: src/main/java/jmockmongo/Result.java // public class Result { // // // ok - true indicates the getLastError command completed successfully. This // // does NOT indicate there wasn't a last error. // private final boolean ok; // // private final int n; // // private final String error; // // public Result(int n) { // ok = true; // this.n = n; // this.error = null; // } // // public Result(String error) { // ok = true; // n = 0; // this.error = error; // } // // public boolean isOk() { // return ok; // } // // public int getN() { // return n; // } // // public BSONObject toBSON() { // BasicBSONObject r = new BasicBSONObject("ok", ok ? 1 : 0) // .append("n", n); // if (error != null) // r.append("err", error); // return r; // } // // } // // Path: src/main/java/jmockmongo/UpdateHandler.java // public interface UpdateHandler { // // public Result handleUpdate(String database, String collection, // boolean upsert, boolean multiUpdate, BSONObject selector, // BSONObject update); // // }
import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ExceptionEvent; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.SimpleChannelUpstreamHandler; import java.util.HashMap; import java.util.Map; import jmockmongo.CommandHandler; import jmockmongo.DeleteHandler; import jmockmongo.InsertHandler; import jmockmongo.QueryHandler; import jmockmongo.Result; import jmockmongo.UpdateHandler; import org.bson.BSONObject; import org.bson.BasicBSONObject;
/** * Copyright (c) 2012, Thilo Planz. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the Apache License, Version 2.0 * as published by the Apache Software Foundation (the "License"). * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * * You should have received a copy of the License along with this program. * If not, see <http://www.apache.org/licenses/LICENSE-2.0>. */ package jmockmongo.wire; public class ReplyHandler extends SimpleChannelUpstreamHandler { private final Map<String, CommandHandler> commands = new HashMap<String, CommandHandler>();
// Path: src/main/java/jmockmongo/CommandHandler.java // public interface CommandHandler { // // public BSONObject handleCommand(String database, BSONObject command); // // } // // Path: src/main/java/jmockmongo/DeleteHandler.java // public interface DeleteHandler { // // public Result handleDelete(String database, String collection, // boolean singleRemove, BSONObject selector); // } // // Path: src/main/java/jmockmongo/InsertHandler.java // public interface InsertHandler { // // public Result handleInsert(String database, String collection, // boolean continueOnError, Iterator<BSONObject> data); // } // // Path: src/main/java/jmockmongo/QueryHandler.java // public interface QueryHandler { // // public BSONObject[] handleQuery(String database, String collection, // BSONObject command); // // } // // Path: src/main/java/jmockmongo/Result.java // public class Result { // // // ok - true indicates the getLastError command completed successfully. This // // does NOT indicate there wasn't a last error. // private final boolean ok; // // private final int n; // // private final String error; // // public Result(int n) { // ok = true; // this.n = n; // this.error = null; // } // // public Result(String error) { // ok = true; // n = 0; // this.error = error; // } // // public boolean isOk() { // return ok; // } // // public int getN() { // return n; // } // // public BSONObject toBSON() { // BasicBSONObject r = new BasicBSONObject("ok", ok ? 1 : 0) // .append("n", n); // if (error != null) // r.append("err", error); // return r; // } // // } // // Path: src/main/java/jmockmongo/UpdateHandler.java // public interface UpdateHandler { // // public Result handleUpdate(String database, String collection, // boolean upsert, boolean multiUpdate, BSONObject selector, // BSONObject update); // // } // Path: src/main/java/jmockmongo/wire/ReplyHandler.java import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ExceptionEvent; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.SimpleChannelUpstreamHandler; import java.util.HashMap; import java.util.Map; import jmockmongo.CommandHandler; import jmockmongo.DeleteHandler; import jmockmongo.InsertHandler; import jmockmongo.QueryHandler; import jmockmongo.Result; import jmockmongo.UpdateHandler; import org.bson.BSONObject; import org.bson.BasicBSONObject; /** * Copyright (c) 2012, Thilo Planz. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the Apache License, Version 2.0 * as published by the Apache Software Foundation (the "License"). * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * * You should have received a copy of the License along with this program. * If not, see <http://www.apache.org/licenses/LICENSE-2.0>. */ package jmockmongo.wire; public class ReplyHandler extends SimpleChannelUpstreamHandler { private final Map<String, CommandHandler> commands = new HashMap<String, CommandHandler>();
private Result lastError;
thiloplanz/jmockmongo
src/main/java/jmockmongo/wire/ReplyHandler.java
// Path: src/main/java/jmockmongo/CommandHandler.java // public interface CommandHandler { // // public BSONObject handleCommand(String database, BSONObject command); // // } // // Path: src/main/java/jmockmongo/DeleteHandler.java // public interface DeleteHandler { // // public Result handleDelete(String database, String collection, // boolean singleRemove, BSONObject selector); // } // // Path: src/main/java/jmockmongo/InsertHandler.java // public interface InsertHandler { // // public Result handleInsert(String database, String collection, // boolean continueOnError, Iterator<BSONObject> data); // } // // Path: src/main/java/jmockmongo/QueryHandler.java // public interface QueryHandler { // // public BSONObject[] handleQuery(String database, String collection, // BSONObject command); // // } // // Path: src/main/java/jmockmongo/Result.java // public class Result { // // // ok - true indicates the getLastError command completed successfully. This // // does NOT indicate there wasn't a last error. // private final boolean ok; // // private final int n; // // private final String error; // // public Result(int n) { // ok = true; // this.n = n; // this.error = null; // } // // public Result(String error) { // ok = true; // n = 0; // this.error = error; // } // // public boolean isOk() { // return ok; // } // // public int getN() { // return n; // } // // public BSONObject toBSON() { // BasicBSONObject r = new BasicBSONObject("ok", ok ? 1 : 0) // .append("n", n); // if (error != null) // r.append("err", error); // return r; // } // // } // // Path: src/main/java/jmockmongo/UpdateHandler.java // public interface UpdateHandler { // // public Result handleUpdate(String database, String collection, // boolean upsert, boolean multiUpdate, BSONObject selector, // BSONObject update); // // }
import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ExceptionEvent; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.SimpleChannelUpstreamHandler; import java.util.HashMap; import java.util.Map; import jmockmongo.CommandHandler; import jmockmongo.DeleteHandler; import jmockmongo.InsertHandler; import jmockmongo.QueryHandler; import jmockmongo.Result; import jmockmongo.UpdateHandler; import org.bson.BSONObject; import org.bson.BasicBSONObject;
/** * Copyright (c) 2012, Thilo Planz. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the Apache License, Version 2.0 * as published by the Apache Software Foundation (the "License"). * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * * You should have received a copy of the License along with this program. * If not, see <http://www.apache.org/licenses/LICENSE-2.0>. */ package jmockmongo.wire; public class ReplyHandler extends SimpleChannelUpstreamHandler { private final Map<String, CommandHandler> commands = new HashMap<String, CommandHandler>(); private Result lastError;
// Path: src/main/java/jmockmongo/CommandHandler.java // public interface CommandHandler { // // public BSONObject handleCommand(String database, BSONObject command); // // } // // Path: src/main/java/jmockmongo/DeleteHandler.java // public interface DeleteHandler { // // public Result handleDelete(String database, String collection, // boolean singleRemove, BSONObject selector); // } // // Path: src/main/java/jmockmongo/InsertHandler.java // public interface InsertHandler { // // public Result handleInsert(String database, String collection, // boolean continueOnError, Iterator<BSONObject> data); // } // // Path: src/main/java/jmockmongo/QueryHandler.java // public interface QueryHandler { // // public BSONObject[] handleQuery(String database, String collection, // BSONObject command); // // } // // Path: src/main/java/jmockmongo/Result.java // public class Result { // // // ok - true indicates the getLastError command completed successfully. This // // does NOT indicate there wasn't a last error. // private final boolean ok; // // private final int n; // // private final String error; // // public Result(int n) { // ok = true; // this.n = n; // this.error = null; // } // // public Result(String error) { // ok = true; // n = 0; // this.error = error; // } // // public boolean isOk() { // return ok; // } // // public int getN() { // return n; // } // // public BSONObject toBSON() { // BasicBSONObject r = new BasicBSONObject("ok", ok ? 1 : 0) // .append("n", n); // if (error != null) // r.append("err", error); // return r; // } // // } // // Path: src/main/java/jmockmongo/UpdateHandler.java // public interface UpdateHandler { // // public Result handleUpdate(String database, String collection, // boolean upsert, boolean multiUpdate, BSONObject selector, // BSONObject update); // // } // Path: src/main/java/jmockmongo/wire/ReplyHandler.java import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ExceptionEvent; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.SimpleChannelUpstreamHandler; import java.util.HashMap; import java.util.Map; import jmockmongo.CommandHandler; import jmockmongo.DeleteHandler; import jmockmongo.InsertHandler; import jmockmongo.QueryHandler; import jmockmongo.Result; import jmockmongo.UpdateHandler; import org.bson.BSONObject; import org.bson.BasicBSONObject; /** * Copyright (c) 2012, Thilo Planz. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the Apache License, Version 2.0 * as published by the Apache Software Foundation (the "License"). * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * * You should have received a copy of the License along with this program. * If not, see <http://www.apache.org/licenses/LICENSE-2.0>. */ package jmockmongo.wire; public class ReplyHandler extends SimpleChannelUpstreamHandler { private final Map<String, CommandHandler> commands = new HashMap<String, CommandHandler>(); private Result lastError;
private QueryHandler queryHandler;
thiloplanz/jmockmongo
src/main/java/jmockmongo/wire/ReplyHandler.java
// Path: src/main/java/jmockmongo/CommandHandler.java // public interface CommandHandler { // // public BSONObject handleCommand(String database, BSONObject command); // // } // // Path: src/main/java/jmockmongo/DeleteHandler.java // public interface DeleteHandler { // // public Result handleDelete(String database, String collection, // boolean singleRemove, BSONObject selector); // } // // Path: src/main/java/jmockmongo/InsertHandler.java // public interface InsertHandler { // // public Result handleInsert(String database, String collection, // boolean continueOnError, Iterator<BSONObject> data); // } // // Path: src/main/java/jmockmongo/QueryHandler.java // public interface QueryHandler { // // public BSONObject[] handleQuery(String database, String collection, // BSONObject command); // // } // // Path: src/main/java/jmockmongo/Result.java // public class Result { // // // ok - true indicates the getLastError command completed successfully. This // // does NOT indicate there wasn't a last error. // private final boolean ok; // // private final int n; // // private final String error; // // public Result(int n) { // ok = true; // this.n = n; // this.error = null; // } // // public Result(String error) { // ok = true; // n = 0; // this.error = error; // } // // public boolean isOk() { // return ok; // } // // public int getN() { // return n; // } // // public BSONObject toBSON() { // BasicBSONObject r = new BasicBSONObject("ok", ok ? 1 : 0) // .append("n", n); // if (error != null) // r.append("err", error); // return r; // } // // } // // Path: src/main/java/jmockmongo/UpdateHandler.java // public interface UpdateHandler { // // public Result handleUpdate(String database, String collection, // boolean upsert, boolean multiUpdate, BSONObject selector, // BSONObject update); // // }
import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ExceptionEvent; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.SimpleChannelUpstreamHandler; import java.util.HashMap; import java.util.Map; import jmockmongo.CommandHandler; import jmockmongo.DeleteHandler; import jmockmongo.InsertHandler; import jmockmongo.QueryHandler; import jmockmongo.Result; import jmockmongo.UpdateHandler; import org.bson.BSONObject; import org.bson.BasicBSONObject;
/** * Copyright (c) 2012, Thilo Planz. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the Apache License, Version 2.0 * as published by the Apache Software Foundation (the "License"). * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * * You should have received a copy of the License along with this program. * If not, see <http://www.apache.org/licenses/LICENSE-2.0>. */ package jmockmongo.wire; public class ReplyHandler extends SimpleChannelUpstreamHandler { private final Map<String, CommandHandler> commands = new HashMap<String, CommandHandler>(); private Result lastError; private QueryHandler queryHandler;
// Path: src/main/java/jmockmongo/CommandHandler.java // public interface CommandHandler { // // public BSONObject handleCommand(String database, BSONObject command); // // } // // Path: src/main/java/jmockmongo/DeleteHandler.java // public interface DeleteHandler { // // public Result handleDelete(String database, String collection, // boolean singleRemove, BSONObject selector); // } // // Path: src/main/java/jmockmongo/InsertHandler.java // public interface InsertHandler { // // public Result handleInsert(String database, String collection, // boolean continueOnError, Iterator<BSONObject> data); // } // // Path: src/main/java/jmockmongo/QueryHandler.java // public interface QueryHandler { // // public BSONObject[] handleQuery(String database, String collection, // BSONObject command); // // } // // Path: src/main/java/jmockmongo/Result.java // public class Result { // // // ok - true indicates the getLastError command completed successfully. This // // does NOT indicate there wasn't a last error. // private final boolean ok; // // private final int n; // // private final String error; // // public Result(int n) { // ok = true; // this.n = n; // this.error = null; // } // // public Result(String error) { // ok = true; // n = 0; // this.error = error; // } // // public boolean isOk() { // return ok; // } // // public int getN() { // return n; // } // // public BSONObject toBSON() { // BasicBSONObject r = new BasicBSONObject("ok", ok ? 1 : 0) // .append("n", n); // if (error != null) // r.append("err", error); // return r; // } // // } // // Path: src/main/java/jmockmongo/UpdateHandler.java // public interface UpdateHandler { // // public Result handleUpdate(String database, String collection, // boolean upsert, boolean multiUpdate, BSONObject selector, // BSONObject update); // // } // Path: src/main/java/jmockmongo/wire/ReplyHandler.java import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ExceptionEvent; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.SimpleChannelUpstreamHandler; import java.util.HashMap; import java.util.Map; import jmockmongo.CommandHandler; import jmockmongo.DeleteHandler; import jmockmongo.InsertHandler; import jmockmongo.QueryHandler; import jmockmongo.Result; import jmockmongo.UpdateHandler; import org.bson.BSONObject; import org.bson.BasicBSONObject; /** * Copyright (c) 2012, Thilo Planz. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the Apache License, Version 2.0 * as published by the Apache Software Foundation (the "License"). * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * * You should have received a copy of the License along with this program. * If not, see <http://www.apache.org/licenses/LICENSE-2.0>. */ package jmockmongo.wire; public class ReplyHandler extends SimpleChannelUpstreamHandler { private final Map<String, CommandHandler> commands = new HashMap<String, CommandHandler>(); private Result lastError; private QueryHandler queryHandler;
private InsertHandler insertHandler;
thiloplanz/jmockmongo
src/main/java/jmockmongo/wire/ReplyHandler.java
// Path: src/main/java/jmockmongo/CommandHandler.java // public interface CommandHandler { // // public BSONObject handleCommand(String database, BSONObject command); // // } // // Path: src/main/java/jmockmongo/DeleteHandler.java // public interface DeleteHandler { // // public Result handleDelete(String database, String collection, // boolean singleRemove, BSONObject selector); // } // // Path: src/main/java/jmockmongo/InsertHandler.java // public interface InsertHandler { // // public Result handleInsert(String database, String collection, // boolean continueOnError, Iterator<BSONObject> data); // } // // Path: src/main/java/jmockmongo/QueryHandler.java // public interface QueryHandler { // // public BSONObject[] handleQuery(String database, String collection, // BSONObject command); // // } // // Path: src/main/java/jmockmongo/Result.java // public class Result { // // // ok - true indicates the getLastError command completed successfully. This // // does NOT indicate there wasn't a last error. // private final boolean ok; // // private final int n; // // private final String error; // // public Result(int n) { // ok = true; // this.n = n; // this.error = null; // } // // public Result(String error) { // ok = true; // n = 0; // this.error = error; // } // // public boolean isOk() { // return ok; // } // // public int getN() { // return n; // } // // public BSONObject toBSON() { // BasicBSONObject r = new BasicBSONObject("ok", ok ? 1 : 0) // .append("n", n); // if (error != null) // r.append("err", error); // return r; // } // // } // // Path: src/main/java/jmockmongo/UpdateHandler.java // public interface UpdateHandler { // // public Result handleUpdate(String database, String collection, // boolean upsert, boolean multiUpdate, BSONObject selector, // BSONObject update); // // }
import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ExceptionEvent; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.SimpleChannelUpstreamHandler; import java.util.HashMap; import java.util.Map; import jmockmongo.CommandHandler; import jmockmongo.DeleteHandler; import jmockmongo.InsertHandler; import jmockmongo.QueryHandler; import jmockmongo.Result; import jmockmongo.UpdateHandler; import org.bson.BSONObject; import org.bson.BasicBSONObject;
/** * Copyright (c) 2012, Thilo Planz. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the Apache License, Version 2.0 * as published by the Apache Software Foundation (the "License"). * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * * You should have received a copy of the License along with this program. * If not, see <http://www.apache.org/licenses/LICENSE-2.0>. */ package jmockmongo.wire; public class ReplyHandler extends SimpleChannelUpstreamHandler { private final Map<String, CommandHandler> commands = new HashMap<String, CommandHandler>(); private Result lastError; private QueryHandler queryHandler; private InsertHandler insertHandler;
// Path: src/main/java/jmockmongo/CommandHandler.java // public interface CommandHandler { // // public BSONObject handleCommand(String database, BSONObject command); // // } // // Path: src/main/java/jmockmongo/DeleteHandler.java // public interface DeleteHandler { // // public Result handleDelete(String database, String collection, // boolean singleRemove, BSONObject selector); // } // // Path: src/main/java/jmockmongo/InsertHandler.java // public interface InsertHandler { // // public Result handleInsert(String database, String collection, // boolean continueOnError, Iterator<BSONObject> data); // } // // Path: src/main/java/jmockmongo/QueryHandler.java // public interface QueryHandler { // // public BSONObject[] handleQuery(String database, String collection, // BSONObject command); // // } // // Path: src/main/java/jmockmongo/Result.java // public class Result { // // // ok - true indicates the getLastError command completed successfully. This // // does NOT indicate there wasn't a last error. // private final boolean ok; // // private final int n; // // private final String error; // // public Result(int n) { // ok = true; // this.n = n; // this.error = null; // } // // public Result(String error) { // ok = true; // n = 0; // this.error = error; // } // // public boolean isOk() { // return ok; // } // // public int getN() { // return n; // } // // public BSONObject toBSON() { // BasicBSONObject r = new BasicBSONObject("ok", ok ? 1 : 0) // .append("n", n); // if (error != null) // r.append("err", error); // return r; // } // // } // // Path: src/main/java/jmockmongo/UpdateHandler.java // public interface UpdateHandler { // // public Result handleUpdate(String database, String collection, // boolean upsert, boolean multiUpdate, BSONObject selector, // BSONObject update); // // } // Path: src/main/java/jmockmongo/wire/ReplyHandler.java import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ExceptionEvent; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.SimpleChannelUpstreamHandler; import java.util.HashMap; import java.util.Map; import jmockmongo.CommandHandler; import jmockmongo.DeleteHandler; import jmockmongo.InsertHandler; import jmockmongo.QueryHandler; import jmockmongo.Result; import jmockmongo.UpdateHandler; import org.bson.BSONObject; import org.bson.BasicBSONObject; /** * Copyright (c) 2012, Thilo Planz. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the Apache License, Version 2.0 * as published by the Apache Software Foundation (the "License"). * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * * You should have received a copy of the License along with this program. * If not, see <http://www.apache.org/licenses/LICENSE-2.0>. */ package jmockmongo.wire; public class ReplyHandler extends SimpleChannelUpstreamHandler { private final Map<String, CommandHandler> commands = new HashMap<String, CommandHandler>(); private Result lastError; private QueryHandler queryHandler; private InsertHandler insertHandler;
private UpdateHandler updateHandler;
thiloplanz/jmockmongo
src/main/java/jmockmongo/wire/ReplyHandler.java
// Path: src/main/java/jmockmongo/CommandHandler.java // public interface CommandHandler { // // public BSONObject handleCommand(String database, BSONObject command); // // } // // Path: src/main/java/jmockmongo/DeleteHandler.java // public interface DeleteHandler { // // public Result handleDelete(String database, String collection, // boolean singleRemove, BSONObject selector); // } // // Path: src/main/java/jmockmongo/InsertHandler.java // public interface InsertHandler { // // public Result handleInsert(String database, String collection, // boolean continueOnError, Iterator<BSONObject> data); // } // // Path: src/main/java/jmockmongo/QueryHandler.java // public interface QueryHandler { // // public BSONObject[] handleQuery(String database, String collection, // BSONObject command); // // } // // Path: src/main/java/jmockmongo/Result.java // public class Result { // // // ok - true indicates the getLastError command completed successfully. This // // does NOT indicate there wasn't a last error. // private final boolean ok; // // private final int n; // // private final String error; // // public Result(int n) { // ok = true; // this.n = n; // this.error = null; // } // // public Result(String error) { // ok = true; // n = 0; // this.error = error; // } // // public boolean isOk() { // return ok; // } // // public int getN() { // return n; // } // // public BSONObject toBSON() { // BasicBSONObject r = new BasicBSONObject("ok", ok ? 1 : 0) // .append("n", n); // if (error != null) // r.append("err", error); // return r; // } // // } // // Path: src/main/java/jmockmongo/UpdateHandler.java // public interface UpdateHandler { // // public Result handleUpdate(String database, String collection, // boolean upsert, boolean multiUpdate, BSONObject selector, // BSONObject update); // // }
import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ExceptionEvent; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.SimpleChannelUpstreamHandler; import java.util.HashMap; import java.util.Map; import jmockmongo.CommandHandler; import jmockmongo.DeleteHandler; import jmockmongo.InsertHandler; import jmockmongo.QueryHandler; import jmockmongo.Result; import jmockmongo.UpdateHandler; import org.bson.BSONObject; import org.bson.BasicBSONObject;
/** * Copyright (c) 2012, Thilo Planz. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the Apache License, Version 2.0 * as published by the Apache Software Foundation (the "License"). * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * * You should have received a copy of the License along with this program. * If not, see <http://www.apache.org/licenses/LICENSE-2.0>. */ package jmockmongo.wire; public class ReplyHandler extends SimpleChannelUpstreamHandler { private final Map<String, CommandHandler> commands = new HashMap<String, CommandHandler>(); private Result lastError; private QueryHandler queryHandler; private InsertHandler insertHandler; private UpdateHandler updateHandler;
// Path: src/main/java/jmockmongo/CommandHandler.java // public interface CommandHandler { // // public BSONObject handleCommand(String database, BSONObject command); // // } // // Path: src/main/java/jmockmongo/DeleteHandler.java // public interface DeleteHandler { // // public Result handleDelete(String database, String collection, // boolean singleRemove, BSONObject selector); // } // // Path: src/main/java/jmockmongo/InsertHandler.java // public interface InsertHandler { // // public Result handleInsert(String database, String collection, // boolean continueOnError, Iterator<BSONObject> data); // } // // Path: src/main/java/jmockmongo/QueryHandler.java // public interface QueryHandler { // // public BSONObject[] handleQuery(String database, String collection, // BSONObject command); // // } // // Path: src/main/java/jmockmongo/Result.java // public class Result { // // // ok - true indicates the getLastError command completed successfully. This // // does NOT indicate there wasn't a last error. // private final boolean ok; // // private final int n; // // private final String error; // // public Result(int n) { // ok = true; // this.n = n; // this.error = null; // } // // public Result(String error) { // ok = true; // n = 0; // this.error = error; // } // // public boolean isOk() { // return ok; // } // // public int getN() { // return n; // } // // public BSONObject toBSON() { // BasicBSONObject r = new BasicBSONObject("ok", ok ? 1 : 0) // .append("n", n); // if (error != null) // r.append("err", error); // return r; // } // // } // // Path: src/main/java/jmockmongo/UpdateHandler.java // public interface UpdateHandler { // // public Result handleUpdate(String database, String collection, // boolean upsert, boolean multiUpdate, BSONObject selector, // BSONObject update); // // } // Path: src/main/java/jmockmongo/wire/ReplyHandler.java import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ExceptionEvent; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.SimpleChannelUpstreamHandler; import java.util.HashMap; import java.util.Map; import jmockmongo.CommandHandler; import jmockmongo.DeleteHandler; import jmockmongo.InsertHandler; import jmockmongo.QueryHandler; import jmockmongo.Result; import jmockmongo.UpdateHandler; import org.bson.BSONObject; import org.bson.BasicBSONObject; /** * Copyright (c) 2012, Thilo Planz. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the Apache License, Version 2.0 * as published by the Apache Software Foundation (the "License"). * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * * You should have received a copy of the License along with this program. * If not, see <http://www.apache.org/licenses/LICENSE-2.0>. */ package jmockmongo.wire; public class ReplyHandler extends SimpleChannelUpstreamHandler { private final Map<String, CommandHandler> commands = new HashMap<String, CommandHandler>(); private Result lastError; private QueryHandler queryHandler; private InsertHandler insertHandler; private UpdateHandler updateHandler;
private DeleteHandler deleteHandler;
thiloplanz/jmockmongo
src/main/java/jmockmongo/wire/InsertMessage.java
// Path: src/main/java/jmockmongo/wire/MessageDecoder.java // static final String readCString(ChannelBuffer buffer) { // // find the terminating zero-byte // int length = buffer.bytesBefore((byte) 0); // byte[] bytes = new byte[length]; // buffer.readBytes(bytes); // // also skip the terminator // buffer.readByte(); // try { // return new String(bytes, "UTF-8"); // } catch (java.io.UnsupportedEncodingException uee) { // throw new BSONException("impossible", uee); // } // } // // Path: src/main/java/jmockmongo/wire/MessageDecoder.java // static final BSONObject readDocument(ChannelBuffer buffer, byte[] fourBytes) { // int length = readInt32(buffer, fourBytes); // byte[] bson = new byte[length]; // buffer.readBytes(bson, 4, length - 4); // System.arraycopy(fourBytes, 0, bson, 0, 4); // return BSON.decode(bson); // // } // // Path: src/main/java/jmockmongo/wire/MessageDecoder.java // static final int readInt32(ChannelBuffer buffer, byte[] fourBytes) { // buffer.readBytes(fourBytes); // return Bits.readInt(fourBytes); // }
import static jmockmongo.wire.MessageDecoder.readCString; import static jmockmongo.wire.MessageDecoder.readDocument; import static jmockmongo.wire.MessageDecoder.readInt32; import java.util.Iterator; import org.bson.BSONObject; import org.jboss.netty.buffer.ChannelBuffer;
/** * Copyright (c) 2012, Thilo Planz. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the Apache License, Version 2.0 * as published by the Apache Software Foundation (the "License"). * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * * You should have received a copy of the License along with this program. * If not, see <http://www.apache.org/licenses/LICENSE-2.0>. */ package jmockmongo.wire; class InsertMessage extends Message { static final int OP_CODE_INSERT = 2002; // struct { // MsgHeader header; // standard message header // int32 flags; // bit vector - see below // cstring fullCollectionName; // "dbname.collectionname" // document* documents; // one or more documents to insert into the // collection // } private final int flags; private final String fullCollectionName; String getFullCollectionName() { return fullCollectionName; } InsertMessage(ChannelBuffer data) { super(data, OP_CODE_INSERT); byte[] fourBytes = new byte[4];
// Path: src/main/java/jmockmongo/wire/MessageDecoder.java // static final String readCString(ChannelBuffer buffer) { // // find the terminating zero-byte // int length = buffer.bytesBefore((byte) 0); // byte[] bytes = new byte[length]; // buffer.readBytes(bytes); // // also skip the terminator // buffer.readByte(); // try { // return new String(bytes, "UTF-8"); // } catch (java.io.UnsupportedEncodingException uee) { // throw new BSONException("impossible", uee); // } // } // // Path: src/main/java/jmockmongo/wire/MessageDecoder.java // static final BSONObject readDocument(ChannelBuffer buffer, byte[] fourBytes) { // int length = readInt32(buffer, fourBytes); // byte[] bson = new byte[length]; // buffer.readBytes(bson, 4, length - 4); // System.arraycopy(fourBytes, 0, bson, 0, 4); // return BSON.decode(bson); // // } // // Path: src/main/java/jmockmongo/wire/MessageDecoder.java // static final int readInt32(ChannelBuffer buffer, byte[] fourBytes) { // buffer.readBytes(fourBytes); // return Bits.readInt(fourBytes); // } // Path: src/main/java/jmockmongo/wire/InsertMessage.java import static jmockmongo.wire.MessageDecoder.readCString; import static jmockmongo.wire.MessageDecoder.readDocument; import static jmockmongo.wire.MessageDecoder.readInt32; import java.util.Iterator; import org.bson.BSONObject; import org.jboss.netty.buffer.ChannelBuffer; /** * Copyright (c) 2012, Thilo Planz. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the Apache License, Version 2.0 * as published by the Apache Software Foundation (the "License"). * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * * You should have received a copy of the License along with this program. * If not, see <http://www.apache.org/licenses/LICENSE-2.0>. */ package jmockmongo.wire; class InsertMessage extends Message { static final int OP_CODE_INSERT = 2002; // struct { // MsgHeader header; // standard message header // int32 flags; // bit vector - see below // cstring fullCollectionName; // "dbname.collectionname" // document* documents; // one or more documents to insert into the // collection // } private final int flags; private final String fullCollectionName; String getFullCollectionName() { return fullCollectionName; } InsertMessage(ChannelBuffer data) { super(data, OP_CODE_INSERT); byte[] fourBytes = new byte[4];
flags = readInt32(data, fourBytes);
thiloplanz/jmockmongo
src/main/java/jmockmongo/wire/InsertMessage.java
// Path: src/main/java/jmockmongo/wire/MessageDecoder.java // static final String readCString(ChannelBuffer buffer) { // // find the terminating zero-byte // int length = buffer.bytesBefore((byte) 0); // byte[] bytes = new byte[length]; // buffer.readBytes(bytes); // // also skip the terminator // buffer.readByte(); // try { // return new String(bytes, "UTF-8"); // } catch (java.io.UnsupportedEncodingException uee) { // throw new BSONException("impossible", uee); // } // } // // Path: src/main/java/jmockmongo/wire/MessageDecoder.java // static final BSONObject readDocument(ChannelBuffer buffer, byte[] fourBytes) { // int length = readInt32(buffer, fourBytes); // byte[] bson = new byte[length]; // buffer.readBytes(bson, 4, length - 4); // System.arraycopy(fourBytes, 0, bson, 0, 4); // return BSON.decode(bson); // // } // // Path: src/main/java/jmockmongo/wire/MessageDecoder.java // static final int readInt32(ChannelBuffer buffer, byte[] fourBytes) { // buffer.readBytes(fourBytes); // return Bits.readInt(fourBytes); // }
import static jmockmongo.wire.MessageDecoder.readCString; import static jmockmongo.wire.MessageDecoder.readDocument; import static jmockmongo.wire.MessageDecoder.readInt32; import java.util.Iterator; import org.bson.BSONObject; import org.jboss.netty.buffer.ChannelBuffer;
/** * Copyright (c) 2012, Thilo Planz. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the Apache License, Version 2.0 * as published by the Apache Software Foundation (the "License"). * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * * You should have received a copy of the License along with this program. * If not, see <http://www.apache.org/licenses/LICENSE-2.0>. */ package jmockmongo.wire; class InsertMessage extends Message { static final int OP_CODE_INSERT = 2002; // struct { // MsgHeader header; // standard message header // int32 flags; // bit vector - see below // cstring fullCollectionName; // "dbname.collectionname" // document* documents; // one or more documents to insert into the // collection // } private final int flags; private final String fullCollectionName; String getFullCollectionName() { return fullCollectionName; } InsertMessage(ChannelBuffer data) { super(data, OP_CODE_INSERT); byte[] fourBytes = new byte[4]; flags = readInt32(data, fourBytes);
// Path: src/main/java/jmockmongo/wire/MessageDecoder.java // static final String readCString(ChannelBuffer buffer) { // // find the terminating zero-byte // int length = buffer.bytesBefore((byte) 0); // byte[] bytes = new byte[length]; // buffer.readBytes(bytes); // // also skip the terminator // buffer.readByte(); // try { // return new String(bytes, "UTF-8"); // } catch (java.io.UnsupportedEncodingException uee) { // throw new BSONException("impossible", uee); // } // } // // Path: src/main/java/jmockmongo/wire/MessageDecoder.java // static final BSONObject readDocument(ChannelBuffer buffer, byte[] fourBytes) { // int length = readInt32(buffer, fourBytes); // byte[] bson = new byte[length]; // buffer.readBytes(bson, 4, length - 4); // System.arraycopy(fourBytes, 0, bson, 0, 4); // return BSON.decode(bson); // // } // // Path: src/main/java/jmockmongo/wire/MessageDecoder.java // static final int readInt32(ChannelBuffer buffer, byte[] fourBytes) { // buffer.readBytes(fourBytes); // return Bits.readInt(fourBytes); // } // Path: src/main/java/jmockmongo/wire/InsertMessage.java import static jmockmongo.wire.MessageDecoder.readCString; import static jmockmongo.wire.MessageDecoder.readDocument; import static jmockmongo.wire.MessageDecoder.readInt32; import java.util.Iterator; import org.bson.BSONObject; import org.jboss.netty.buffer.ChannelBuffer; /** * Copyright (c) 2012, Thilo Planz. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the Apache License, Version 2.0 * as published by the Apache Software Foundation (the "License"). * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * * You should have received a copy of the License along with this program. * If not, see <http://www.apache.org/licenses/LICENSE-2.0>. */ package jmockmongo.wire; class InsertMessage extends Message { static final int OP_CODE_INSERT = 2002; // struct { // MsgHeader header; // standard message header // int32 flags; // bit vector - see below // cstring fullCollectionName; // "dbname.collectionname" // document* documents; // one or more documents to insert into the // collection // } private final int flags; private final String fullCollectionName; String getFullCollectionName() { return fullCollectionName; } InsertMessage(ChannelBuffer data) { super(data, OP_CODE_INSERT); byte[] fourBytes = new byte[4]; flags = readInt32(data, fourBytes);
fullCollectionName = readCString(data);
thiloplanz/jmockmongo
src/main/java/jmockmongo/wire/InsertMessage.java
// Path: src/main/java/jmockmongo/wire/MessageDecoder.java // static final String readCString(ChannelBuffer buffer) { // // find the terminating zero-byte // int length = buffer.bytesBefore((byte) 0); // byte[] bytes = new byte[length]; // buffer.readBytes(bytes); // // also skip the terminator // buffer.readByte(); // try { // return new String(bytes, "UTF-8"); // } catch (java.io.UnsupportedEncodingException uee) { // throw new BSONException("impossible", uee); // } // } // // Path: src/main/java/jmockmongo/wire/MessageDecoder.java // static final BSONObject readDocument(ChannelBuffer buffer, byte[] fourBytes) { // int length = readInt32(buffer, fourBytes); // byte[] bson = new byte[length]; // buffer.readBytes(bson, 4, length - 4); // System.arraycopy(fourBytes, 0, bson, 0, 4); // return BSON.decode(bson); // // } // // Path: src/main/java/jmockmongo/wire/MessageDecoder.java // static final int readInt32(ChannelBuffer buffer, byte[] fourBytes) { // buffer.readBytes(fourBytes); // return Bits.readInt(fourBytes); // }
import static jmockmongo.wire.MessageDecoder.readCString; import static jmockmongo.wire.MessageDecoder.readDocument; import static jmockmongo.wire.MessageDecoder.readInt32; import java.util.Iterator; import org.bson.BSONObject; import org.jboss.netty.buffer.ChannelBuffer;
/** * Copyright (c) 2012, Thilo Planz. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the Apache License, Version 2.0 * as published by the Apache Software Foundation (the "License"). * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * * You should have received a copy of the License along with this program. * If not, see <http://www.apache.org/licenses/LICENSE-2.0>. */ package jmockmongo.wire; class InsertMessage extends Message { static final int OP_CODE_INSERT = 2002; // struct { // MsgHeader header; // standard message header // int32 flags; // bit vector - see below // cstring fullCollectionName; // "dbname.collectionname" // document* documents; // one or more documents to insert into the // collection // } private final int flags; private final String fullCollectionName; String getFullCollectionName() { return fullCollectionName; } InsertMessage(ChannelBuffer data) { super(data, OP_CODE_INSERT); byte[] fourBytes = new byte[4]; flags = readInt32(data, fourBytes); fullCollectionName = readCString(data); } Iterator<BSONObject> documents() { final ChannelBuffer copy = data.slice(); final byte[] fourBytes = new byte[4]; return new Iterator<BSONObject>() { public boolean hasNext() { return copy.readable(); } public BSONObject next() {
// Path: src/main/java/jmockmongo/wire/MessageDecoder.java // static final String readCString(ChannelBuffer buffer) { // // find the terminating zero-byte // int length = buffer.bytesBefore((byte) 0); // byte[] bytes = new byte[length]; // buffer.readBytes(bytes); // // also skip the terminator // buffer.readByte(); // try { // return new String(bytes, "UTF-8"); // } catch (java.io.UnsupportedEncodingException uee) { // throw new BSONException("impossible", uee); // } // } // // Path: src/main/java/jmockmongo/wire/MessageDecoder.java // static final BSONObject readDocument(ChannelBuffer buffer, byte[] fourBytes) { // int length = readInt32(buffer, fourBytes); // byte[] bson = new byte[length]; // buffer.readBytes(bson, 4, length - 4); // System.arraycopy(fourBytes, 0, bson, 0, 4); // return BSON.decode(bson); // // } // // Path: src/main/java/jmockmongo/wire/MessageDecoder.java // static final int readInt32(ChannelBuffer buffer, byte[] fourBytes) { // buffer.readBytes(fourBytes); // return Bits.readInt(fourBytes); // } // Path: src/main/java/jmockmongo/wire/InsertMessage.java import static jmockmongo.wire.MessageDecoder.readCString; import static jmockmongo.wire.MessageDecoder.readDocument; import static jmockmongo.wire.MessageDecoder.readInt32; import java.util.Iterator; import org.bson.BSONObject; import org.jboss.netty.buffer.ChannelBuffer; /** * Copyright (c) 2012, Thilo Planz. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the Apache License, Version 2.0 * as published by the Apache Software Foundation (the "License"). * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * * You should have received a copy of the License along with this program. * If not, see <http://www.apache.org/licenses/LICENSE-2.0>. */ package jmockmongo.wire; class InsertMessage extends Message { static final int OP_CODE_INSERT = 2002; // struct { // MsgHeader header; // standard message header // int32 flags; // bit vector - see below // cstring fullCollectionName; // "dbname.collectionname" // document* documents; // one or more documents to insert into the // collection // } private final int flags; private final String fullCollectionName; String getFullCollectionName() { return fullCollectionName; } InsertMessage(ChannelBuffer data) { super(data, OP_CODE_INSERT); byte[] fourBytes = new byte[4]; flags = readInt32(data, fourBytes); fullCollectionName = readCString(data); } Iterator<BSONObject> documents() { final ChannelBuffer copy = data.slice(); final byte[] fourBytes = new byte[4]; return new Iterator<BSONObject>() { public boolean hasNext() { return copy.readable(); } public BSONObject next() {
return readDocument(copy, fourBytes);
Knewton/KassandraMRHelper
src/main/java/com/knewton/mapreduce/example/StudentEventAbstractMapper.java
// Path: src/main/java/com/knewton/mapreduce/SSTableCellMapper.java // public abstract class SSTableCellMapper<K1, V1, // K2 extends WritableComparable<?>, V2 extends Writable> // extends AbstractSSTableMapper<Cell, K1, V1, K2, V2> { // // public SSTableCellMapper() { // super(Cell.class); // } // // } // // Path: src/main/java/com/knewton/mapreduce/constant/PropertyConstants.java // public enum PropertyConstants { // // /** // * The Keyspace Name for a data run // */ // KEYSPACE_NAME("com.knewton.inputformat.cassandra.keyspace"), // /** // * Column family type needs to be set if the column family type is Super. // */ // COLUMN_FAMILY_TYPE("com.knewton.cassandra.cftype"), // /** // * Comparator class name for columns. // */ // COLUMN_COMPARATOR("com.knewton.cassandra.column.comparator"), // /** // * A nonstandard comparator requires a subcomparator // */ // COLUMN_SUBCOMPARATOR("com.knewton.cassandra.column.subcomparator"), // /** // * Partitioner for decorating keys. // */ // PARTITIONER("com.knewton.partitioner"), // /** // * True if the columns are sparse, false if they're dense. // */ // SPARSE_COLUMN("com.knewton.column.sparse"), // /** // * Boolean variable. Set true if compression enabled. // */ // COMPRESSION_ENABLED("com.knewton.cassandra.backup.compression"), // /** // * Buffer size for decompression operation. // */ // DECOMPRESS_BUFFER("com.knewton.cassandra.backup.compress.buffersize"), // /** // * Start and end dates for student events processing // */ // START_DATE("com.knewton.studentevents.date.start"), // END_DATE("com.knewton.studentevents.date.end"), // /** // * The Column Family Name for a data run // */ // COLUMN_FAMILY_NAME("com.knewton.inputformat.cassandra.columnfamily"), // /** // * MapReduce run environment. Should be one of the enum values in MREnvironment.java // */ // MAPREDUCE_ENVIRONMENT("com.knewton.mapreduce.environment"), // /** // * Name of serialization factory class // */ // SERIALIZATION_FACTORY_PARAMETER("com.knewton.thrift.serialization.protocol"); // // public final String txt; // // private PropertyConstants(String propertyName) { // this.txt = propertyName; // } // } // // Path: src/main/java/com/knewton/mapreduce/util/CounterConstants.java // public class CounterConstants { // public static final String STUDENT_EVENTS_JOB = "STUDENT_EVENTS"; // public static final String STUDENT_EVENTS_SKIPPED = "STUDENT_EVENTS_SKIPPED"; // public static final String STUDENT_EVENTS_COUNT = "STUDENT_EVENTS_COUNT"; // public static final String STUDENT_EVENTS_PROCESSED = "STUDENT_EVENTS_PROCESSED"; // public static final String STUDENT_EVENT_DESERIALIZATION_ERRORS = // "STUDENT_EVENT_DESERIALIZATION_ERRORS"; // } // // Path: src/main/java/com/knewton/mapreduce/util/SerializationUtils.java // public class SerializationUtils { // // public static final Class<Factory> SERIALIZATION_FACTORY_PARAMETER_DEFAULT = // TCompactProtocol.Factory.class; // // public static TDeserializer getDeserializerFromConf(Configuration conf) { // Class<? extends TProtocolFactory> protocolFactoryClass = // conf.getClass(PropertyConstants.SERIALIZATION_FACTORY_PARAMETER.txt, // SERIALIZATION_FACTORY_PARAMETER_DEFAULT, TProtocolFactory.class); // TProtocolFactory protocolFactory = ReflectionUtils.newInstance(protocolFactoryClass, conf); // return new TDeserializer(protocolFactory); // } // // }
import com.knewton.mapreduce.SSTableCellMapper; import com.knewton.mapreduce.constant.PropertyConstants; import com.knewton.mapreduce.util.CounterConstants; import com.knewton.mapreduce.util.SerializationUtils; import com.knewton.thrift.StudentEvent; import com.knewton.thrift.StudentEventData; import org.apache.cassandra.db.Cell; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.io.Writable; import org.apache.hadoop.io.WritableComparable; import org.apache.thrift.TDeserializer; import org.apache.thrift.TException; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.joda.time.Interval; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.nio.ByteBuffer; import javax.annotation.Nullable;
studentEvent.setId(eventId); studentEvent.setData(studentEventData); context.getCounter(CounterConstants.STUDENT_EVENTS_JOB, CounterConstants.STUDENT_EVENTS_PROCESSED).increment(1); return studentEvent; } /** * Checks to see if the event is in the desired time range. * * @return True if the event is in the configured time interval */ private boolean isInTimeRange(long eventId, Context context) { DateTime eventTime = new DateTime(eventId, DateTimeZone.UTC); // Skip events outside of the desired time range. if (timeRange != null && !timeRange.contains(eventTime)) { context.getCounter(CounterConstants.STUDENT_EVENTS_JOB, CounterConstants.STUDENT_EVENTS_SKIPPED).increment(1); return false; } return true; } /** * Sets up a DateTime interval for excluding student events. When start time is not set then it * defaults to the beginning of time. If end date is not specified then it defaults to * "the end of time". */ private void setupTimeRange(Configuration conf) { DateTimeFormatter dtf = DateTimeFormat.forPattern(DATE_TIME_STRING_FORMAT).withZoneUTC();
// Path: src/main/java/com/knewton/mapreduce/SSTableCellMapper.java // public abstract class SSTableCellMapper<K1, V1, // K2 extends WritableComparable<?>, V2 extends Writable> // extends AbstractSSTableMapper<Cell, K1, V1, K2, V2> { // // public SSTableCellMapper() { // super(Cell.class); // } // // } // // Path: src/main/java/com/knewton/mapreduce/constant/PropertyConstants.java // public enum PropertyConstants { // // /** // * The Keyspace Name for a data run // */ // KEYSPACE_NAME("com.knewton.inputformat.cassandra.keyspace"), // /** // * Column family type needs to be set if the column family type is Super. // */ // COLUMN_FAMILY_TYPE("com.knewton.cassandra.cftype"), // /** // * Comparator class name for columns. // */ // COLUMN_COMPARATOR("com.knewton.cassandra.column.comparator"), // /** // * A nonstandard comparator requires a subcomparator // */ // COLUMN_SUBCOMPARATOR("com.knewton.cassandra.column.subcomparator"), // /** // * Partitioner for decorating keys. // */ // PARTITIONER("com.knewton.partitioner"), // /** // * True if the columns are sparse, false if they're dense. // */ // SPARSE_COLUMN("com.knewton.column.sparse"), // /** // * Boolean variable. Set true if compression enabled. // */ // COMPRESSION_ENABLED("com.knewton.cassandra.backup.compression"), // /** // * Buffer size for decompression operation. // */ // DECOMPRESS_BUFFER("com.knewton.cassandra.backup.compress.buffersize"), // /** // * Start and end dates for student events processing // */ // START_DATE("com.knewton.studentevents.date.start"), // END_DATE("com.knewton.studentevents.date.end"), // /** // * The Column Family Name for a data run // */ // COLUMN_FAMILY_NAME("com.knewton.inputformat.cassandra.columnfamily"), // /** // * MapReduce run environment. Should be one of the enum values in MREnvironment.java // */ // MAPREDUCE_ENVIRONMENT("com.knewton.mapreduce.environment"), // /** // * Name of serialization factory class // */ // SERIALIZATION_FACTORY_PARAMETER("com.knewton.thrift.serialization.protocol"); // // public final String txt; // // private PropertyConstants(String propertyName) { // this.txt = propertyName; // } // } // // Path: src/main/java/com/knewton/mapreduce/util/CounterConstants.java // public class CounterConstants { // public static final String STUDENT_EVENTS_JOB = "STUDENT_EVENTS"; // public static final String STUDENT_EVENTS_SKIPPED = "STUDENT_EVENTS_SKIPPED"; // public static final String STUDENT_EVENTS_COUNT = "STUDENT_EVENTS_COUNT"; // public static final String STUDENT_EVENTS_PROCESSED = "STUDENT_EVENTS_PROCESSED"; // public static final String STUDENT_EVENT_DESERIALIZATION_ERRORS = // "STUDENT_EVENT_DESERIALIZATION_ERRORS"; // } // // Path: src/main/java/com/knewton/mapreduce/util/SerializationUtils.java // public class SerializationUtils { // // public static final Class<Factory> SERIALIZATION_FACTORY_PARAMETER_DEFAULT = // TCompactProtocol.Factory.class; // // public static TDeserializer getDeserializerFromConf(Configuration conf) { // Class<? extends TProtocolFactory> protocolFactoryClass = // conf.getClass(PropertyConstants.SERIALIZATION_FACTORY_PARAMETER.txt, // SERIALIZATION_FACTORY_PARAMETER_DEFAULT, TProtocolFactory.class); // TProtocolFactory protocolFactory = ReflectionUtils.newInstance(protocolFactoryClass, conf); // return new TDeserializer(protocolFactory); // } // // } // Path: src/main/java/com/knewton/mapreduce/example/StudentEventAbstractMapper.java import com.knewton.mapreduce.SSTableCellMapper; import com.knewton.mapreduce.constant.PropertyConstants; import com.knewton.mapreduce.util.CounterConstants; import com.knewton.mapreduce.util.SerializationUtils; import com.knewton.thrift.StudentEvent; import com.knewton.thrift.StudentEventData; import org.apache.cassandra.db.Cell; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.io.Writable; import org.apache.hadoop.io.WritableComparable; import org.apache.thrift.TDeserializer; import org.apache.thrift.TException; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.joda.time.Interval; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.nio.ByteBuffer; import javax.annotation.Nullable; studentEvent.setId(eventId); studentEvent.setData(studentEventData); context.getCounter(CounterConstants.STUDENT_EVENTS_JOB, CounterConstants.STUDENT_EVENTS_PROCESSED).increment(1); return studentEvent; } /** * Checks to see if the event is in the desired time range. * * @return True if the event is in the configured time interval */ private boolean isInTimeRange(long eventId, Context context) { DateTime eventTime = new DateTime(eventId, DateTimeZone.UTC); // Skip events outside of the desired time range. if (timeRange != null && !timeRange.contains(eventTime)) { context.getCounter(CounterConstants.STUDENT_EVENTS_JOB, CounterConstants.STUDENT_EVENTS_SKIPPED).increment(1); return false; } return true; } /** * Sets up a DateTime interval for excluding student events. When start time is not set then it * defaults to the beginning of time. If end date is not specified then it defaults to * "the end of time". */ private void setupTimeRange(Configuration conf) { DateTimeFormatter dtf = DateTimeFormat.forPattern(DATE_TIME_STRING_FORMAT).withZoneUTC();
String startDateStr = conf.get(PropertyConstants.START_DATE.txt);
Knewton/KassandraMRHelper
src/test/java/com/knewton/mapreduce/io/StudentEventWritableTest.java
// Path: src/main/java/com/knewton/mapreduce/io/StudentEventWritable.java // public static class StudentEventIdComparator implements Comparator<StudentEventWritable> { // // @Override // public int compare(StudentEventWritable sew1, StudentEventWritable sew2) { // return new Long(sew1.studentEvent.getId()).compareTo(sew2.studentEvent.getId()); // } // } // // Path: src/main/java/com/knewton/mapreduce/io/StudentEventWritable.java // public static class StudentEventTimestampComparator implements Comparator<StudentEventWritable> { // // @Override // public int compare(StudentEventWritable sew1, StudentEventWritable sew2) { // // Use LongComparator. Takes care of overflows. // return new Long(sew1.timestamp).compareTo(sew2.timestamp); // } // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import com.knewton.mapreduce.io.StudentEventWritable.StudentEventIdComparator; import com.knewton.mapreduce.io.StudentEventWritable.StudentEventTimestampComparator; import com.knewton.thrift.StudentEvent; import com.knewton.thrift.StudentEventData; import org.junit.Test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.util.Random;
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); DataOutputStream dout = new DataOutputStream(byteArrayOutputStream); StudentEventWritable seWritable = new StudentEventWritable(new StudentEvent(), 0L); seWritable.write(dout); } @Test(expected = IOException.class) public void testReadWithException() throws Exception { ByteBuffer bb = ByteBuffer.wrap(new byte[100]); DataInputStream dis = new DataInputStream(new ByteArrayInputStream(bb.array())); StudentEventWritable seWritable = new StudentEventWritable(); seWritable.readFields(dis); } @Test public void testClone() { StudentEventData seData = new StudentEventData(123L, System.currentTimeMillis(), "type", 2); seData.setBook("book"); seData.setCourse("course"); StudentEvent seEvent = new StudentEvent(10L, seData); StudentEventWritable seWritable = new StudentEventWritable(seEvent, 100L); StudentEventWritable clonedWritable = seWritable.clone(); assertEquals(seWritable.getStudentEvent(), clonedWritable.getStudentEvent()); assertEquals(seWritable.getTimestamp(), clonedWritable.getTimestamp()); } @Test public void testCompareTimestamp() {
// Path: src/main/java/com/knewton/mapreduce/io/StudentEventWritable.java // public static class StudentEventIdComparator implements Comparator<StudentEventWritable> { // // @Override // public int compare(StudentEventWritable sew1, StudentEventWritable sew2) { // return new Long(sew1.studentEvent.getId()).compareTo(sew2.studentEvent.getId()); // } // } // // Path: src/main/java/com/knewton/mapreduce/io/StudentEventWritable.java // public static class StudentEventTimestampComparator implements Comparator<StudentEventWritable> { // // @Override // public int compare(StudentEventWritable sew1, StudentEventWritable sew2) { // // Use LongComparator. Takes care of overflows. // return new Long(sew1.timestamp).compareTo(sew2.timestamp); // } // } // Path: src/test/java/com/knewton/mapreduce/io/StudentEventWritableTest.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import com.knewton.mapreduce.io.StudentEventWritable.StudentEventIdComparator; import com.knewton.mapreduce.io.StudentEventWritable.StudentEventTimestampComparator; import com.knewton.thrift.StudentEvent; import com.knewton.thrift.StudentEventData; import org.junit.Test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.util.Random; ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); DataOutputStream dout = new DataOutputStream(byteArrayOutputStream); StudentEventWritable seWritable = new StudentEventWritable(new StudentEvent(), 0L); seWritable.write(dout); } @Test(expected = IOException.class) public void testReadWithException() throws Exception { ByteBuffer bb = ByteBuffer.wrap(new byte[100]); DataInputStream dis = new DataInputStream(new ByteArrayInputStream(bb.array())); StudentEventWritable seWritable = new StudentEventWritable(); seWritable.readFields(dis); } @Test public void testClone() { StudentEventData seData = new StudentEventData(123L, System.currentTimeMillis(), "type", 2); seData.setBook("book"); seData.setCourse("course"); StudentEvent seEvent = new StudentEvent(10L, seData); StudentEventWritable seWritable = new StudentEventWritable(seEvent, 100L); StudentEventWritable clonedWritable = seWritable.clone(); assertEquals(seWritable.getStudentEvent(), clonedWritable.getStudentEvent()); assertEquals(seWritable.getTimestamp(), clonedWritable.getTimestamp()); } @Test public void testCompareTimestamp() {
StudentEventTimestampComparator comparator = new StudentEventTimestampComparator();
Knewton/KassandraMRHelper
src/test/java/com/knewton/mapreduce/io/StudentEventWritableTest.java
// Path: src/main/java/com/knewton/mapreduce/io/StudentEventWritable.java // public static class StudentEventIdComparator implements Comparator<StudentEventWritable> { // // @Override // public int compare(StudentEventWritable sew1, StudentEventWritable sew2) { // return new Long(sew1.studentEvent.getId()).compareTo(sew2.studentEvent.getId()); // } // } // // Path: src/main/java/com/knewton/mapreduce/io/StudentEventWritable.java // public static class StudentEventTimestampComparator implements Comparator<StudentEventWritable> { // // @Override // public int compare(StudentEventWritable sew1, StudentEventWritable sew2) { // // Use LongComparator. Takes care of overflows. // return new Long(sew1.timestamp).compareTo(sew2.timestamp); // } // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import com.knewton.mapreduce.io.StudentEventWritable.StudentEventIdComparator; import com.knewton.mapreduce.io.StudentEventWritable.StudentEventTimestampComparator; import com.knewton.thrift.StudentEvent; import com.knewton.thrift.StudentEventData; import org.junit.Test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.util.Random;
StudentEventWritable seWritable = new StudentEventWritable(); seWritable.readFields(dis); } @Test public void testClone() { StudentEventData seData = new StudentEventData(123L, System.currentTimeMillis(), "type", 2); seData.setBook("book"); seData.setCourse("course"); StudentEvent seEvent = new StudentEvent(10L, seData); StudentEventWritable seWritable = new StudentEventWritable(seEvent, 100L); StudentEventWritable clonedWritable = seWritable.clone(); assertEquals(seWritable.getStudentEvent(), clonedWritable.getStudentEvent()); assertEquals(seWritable.getTimestamp(), clonedWritable.getTimestamp()); } @Test public void testCompareTimestamp() { StudentEventTimestampComparator comparator = new StudentEventTimestampComparator(); StudentEventWritable smaller = new StudentEventWritable(new StudentEvent(), 1L); StudentEventWritable bigger = new StudentEventWritable(new StudentEvent(), 2L); assertTrue(comparator.compare(smaller, bigger) < 0); assertTrue(comparator.compare(bigger, smaller) > 0); assertEquals(0, comparator.compare(smaller, smaller)); } @Test public void testCompareStudentEventId() {
// Path: src/main/java/com/knewton/mapreduce/io/StudentEventWritable.java // public static class StudentEventIdComparator implements Comparator<StudentEventWritable> { // // @Override // public int compare(StudentEventWritable sew1, StudentEventWritable sew2) { // return new Long(sew1.studentEvent.getId()).compareTo(sew2.studentEvent.getId()); // } // } // // Path: src/main/java/com/knewton/mapreduce/io/StudentEventWritable.java // public static class StudentEventTimestampComparator implements Comparator<StudentEventWritable> { // // @Override // public int compare(StudentEventWritable sew1, StudentEventWritable sew2) { // // Use LongComparator. Takes care of overflows. // return new Long(sew1.timestamp).compareTo(sew2.timestamp); // } // } // Path: src/test/java/com/knewton/mapreduce/io/StudentEventWritableTest.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import com.knewton.mapreduce.io.StudentEventWritable.StudentEventIdComparator; import com.knewton.mapreduce.io.StudentEventWritable.StudentEventTimestampComparator; import com.knewton.thrift.StudentEvent; import com.knewton.thrift.StudentEventData; import org.junit.Test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.util.Random; StudentEventWritable seWritable = new StudentEventWritable(); seWritable.readFields(dis); } @Test public void testClone() { StudentEventData seData = new StudentEventData(123L, System.currentTimeMillis(), "type", 2); seData.setBook("book"); seData.setCourse("course"); StudentEvent seEvent = new StudentEvent(10L, seData); StudentEventWritable seWritable = new StudentEventWritable(seEvent, 100L); StudentEventWritable clonedWritable = seWritable.clone(); assertEquals(seWritable.getStudentEvent(), clonedWritable.getStudentEvent()); assertEquals(seWritable.getTimestamp(), clonedWritable.getTimestamp()); } @Test public void testCompareTimestamp() { StudentEventTimestampComparator comparator = new StudentEventTimestampComparator(); StudentEventWritable smaller = new StudentEventWritable(new StudentEvent(), 1L); StudentEventWritable bigger = new StudentEventWritable(new StudentEvent(), 2L); assertTrue(comparator.compare(smaller, bigger) < 0); assertTrue(comparator.compare(bigger, smaller) > 0); assertEquals(0, comparator.compare(smaller, smaller)); } @Test public void testCompareStudentEventId() {
StudentEventIdComparator comparator = new StudentEventIdComparator();
Knewton/KassandraMRHelper
src/test/java/com/knewton/mapreduce/io/SSTableInputFormatTest.java
// Path: src/main/java/com/knewton/mapreduce/constant/PropertyConstants.java // public enum PropertyConstants { // // /** // * The Keyspace Name for a data run // */ // KEYSPACE_NAME("com.knewton.inputformat.cassandra.keyspace"), // /** // * Column family type needs to be set if the column family type is Super. // */ // COLUMN_FAMILY_TYPE("com.knewton.cassandra.cftype"), // /** // * Comparator class name for columns. // */ // COLUMN_COMPARATOR("com.knewton.cassandra.column.comparator"), // /** // * A nonstandard comparator requires a subcomparator // */ // COLUMN_SUBCOMPARATOR("com.knewton.cassandra.column.subcomparator"), // /** // * Partitioner for decorating keys. // */ // PARTITIONER("com.knewton.partitioner"), // /** // * True if the columns are sparse, false if they're dense. // */ // SPARSE_COLUMN("com.knewton.column.sparse"), // /** // * Boolean variable. Set true if compression enabled. // */ // COMPRESSION_ENABLED("com.knewton.cassandra.backup.compression"), // /** // * Buffer size for decompression operation. // */ // DECOMPRESS_BUFFER("com.knewton.cassandra.backup.compress.buffersize"), // /** // * Start and end dates for student events processing // */ // START_DATE("com.knewton.studentevents.date.start"), // END_DATE("com.knewton.studentevents.date.end"), // /** // * The Column Family Name for a data run // */ // COLUMN_FAMILY_NAME("com.knewton.inputformat.cassandra.columnfamily"), // /** // * MapReduce run environment. Should be one of the enum values in MREnvironment.java // */ // MAPREDUCE_ENVIRONMENT("com.knewton.mapreduce.environment"), // /** // * Name of serialization factory class // */ // SERIALIZATION_FACTORY_PARAMETER("com.knewton.thrift.serialization.protocol"); // // public final String txt; // // private PropertyConstants(String propertyName) { // this.txt = propertyName; // } // }
import com.knewton.mapreduce.constant.PropertyConstants; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.JobID; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.task.JobContextImpl; import org.junit.Test; import java.io.IOException; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse;
List<FileStatus> result = testListStatus(conf, "./src/test/resources/backup_input"); assertEquals(NUM_TABLES * NUM_COLUMN_FAMILIES, result.size()); } /** * Tests to see if when given an input directory the {@link SSTableInputFormat} correctly * expands all sub directories and picks up all the data tables corresponding to a specific * column family when a SNAP directory exists. The SST tables should be skipped. */ @Test public void testListStatusWithColumnFamilyNameSkipSST() throws Exception { Job job = Job.getInstance(new Configuration(false)); Configuration conf = job.getConfiguration(); SSTableInputFormat.setColumnFamilyName("col_fam", job); List<FileStatus> result = testListStatus(conf, "./src/test/resources/backup_input"); assertEquals(NUM_TABLES, result.size()); } @Test public void testIsSplittable() { SSTableColumnInputFormat inputFormat = new SSTableColumnInputFormat(); assertFalse(inputFormat.isSplitable(null, null)); } @Test public void testSetComparatorClass() throws Exception { Job job = Job.getInstance(new Configuration(false)); Configuration conf = job.getConfiguration(); String comparator = "my_comparator"; SSTableInputFormat.setComparatorClass(comparator, job);
// Path: src/main/java/com/knewton/mapreduce/constant/PropertyConstants.java // public enum PropertyConstants { // // /** // * The Keyspace Name for a data run // */ // KEYSPACE_NAME("com.knewton.inputformat.cassandra.keyspace"), // /** // * Column family type needs to be set if the column family type is Super. // */ // COLUMN_FAMILY_TYPE("com.knewton.cassandra.cftype"), // /** // * Comparator class name for columns. // */ // COLUMN_COMPARATOR("com.knewton.cassandra.column.comparator"), // /** // * A nonstandard comparator requires a subcomparator // */ // COLUMN_SUBCOMPARATOR("com.knewton.cassandra.column.subcomparator"), // /** // * Partitioner for decorating keys. // */ // PARTITIONER("com.knewton.partitioner"), // /** // * True if the columns are sparse, false if they're dense. // */ // SPARSE_COLUMN("com.knewton.column.sparse"), // /** // * Boolean variable. Set true if compression enabled. // */ // COMPRESSION_ENABLED("com.knewton.cassandra.backup.compression"), // /** // * Buffer size for decompression operation. // */ // DECOMPRESS_BUFFER("com.knewton.cassandra.backup.compress.buffersize"), // /** // * Start and end dates for student events processing // */ // START_DATE("com.knewton.studentevents.date.start"), // END_DATE("com.knewton.studentevents.date.end"), // /** // * The Column Family Name for a data run // */ // COLUMN_FAMILY_NAME("com.knewton.inputformat.cassandra.columnfamily"), // /** // * MapReduce run environment. Should be one of the enum values in MREnvironment.java // */ // MAPREDUCE_ENVIRONMENT("com.knewton.mapreduce.environment"), // /** // * Name of serialization factory class // */ // SERIALIZATION_FACTORY_PARAMETER("com.knewton.thrift.serialization.protocol"); // // public final String txt; // // private PropertyConstants(String propertyName) { // this.txt = propertyName; // } // } // Path: src/test/java/com/knewton/mapreduce/io/SSTableInputFormatTest.java import com.knewton.mapreduce.constant.PropertyConstants; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.JobID; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.task.JobContextImpl; import org.junit.Test; import java.io.IOException; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; List<FileStatus> result = testListStatus(conf, "./src/test/resources/backup_input"); assertEquals(NUM_TABLES * NUM_COLUMN_FAMILIES, result.size()); } /** * Tests to see if when given an input directory the {@link SSTableInputFormat} correctly * expands all sub directories and picks up all the data tables corresponding to a specific * column family when a SNAP directory exists. The SST tables should be skipped. */ @Test public void testListStatusWithColumnFamilyNameSkipSST() throws Exception { Job job = Job.getInstance(new Configuration(false)); Configuration conf = job.getConfiguration(); SSTableInputFormat.setColumnFamilyName("col_fam", job); List<FileStatus> result = testListStatus(conf, "./src/test/resources/backup_input"); assertEquals(NUM_TABLES, result.size()); } @Test public void testIsSplittable() { SSTableColumnInputFormat inputFormat = new SSTableColumnInputFormat(); assertFalse(inputFormat.isSplitable(null, null)); } @Test public void testSetComparatorClass() throws Exception { Job job = Job.getInstance(new Configuration(false)); Configuration conf = job.getConfiguration(); String comparator = "my_comparator"; SSTableInputFormat.setComparatorClass(comparator, job);
assertEquals(comparator, conf.get(PropertyConstants.COLUMN_COMPARATOR.txt));
Knewton/KassandraMRHelper
src/main/java/com/knewton/mapreduce/io/SSTableInputFormat.java
// Path: src/main/java/com/knewton/mapreduce/constant/PropertyConstants.java // public enum PropertyConstants { // // /** // * The Keyspace Name for a data run // */ // KEYSPACE_NAME("com.knewton.inputformat.cassandra.keyspace"), // /** // * Column family type needs to be set if the column family type is Super. // */ // COLUMN_FAMILY_TYPE("com.knewton.cassandra.cftype"), // /** // * Comparator class name for columns. // */ // COLUMN_COMPARATOR("com.knewton.cassandra.column.comparator"), // /** // * A nonstandard comparator requires a subcomparator // */ // COLUMN_SUBCOMPARATOR("com.knewton.cassandra.column.subcomparator"), // /** // * Partitioner for decorating keys. // */ // PARTITIONER("com.knewton.partitioner"), // /** // * True if the columns are sparse, false if they're dense. // */ // SPARSE_COLUMN("com.knewton.column.sparse"), // /** // * Boolean variable. Set true if compression enabled. // */ // COMPRESSION_ENABLED("com.knewton.cassandra.backup.compression"), // /** // * Buffer size for decompression operation. // */ // DECOMPRESS_BUFFER("com.knewton.cassandra.backup.compress.buffersize"), // /** // * Start and end dates for student events processing // */ // START_DATE("com.knewton.studentevents.date.start"), // END_DATE("com.knewton.studentevents.date.end"), // /** // * The Column Family Name for a data run // */ // COLUMN_FAMILY_NAME("com.knewton.inputformat.cassandra.columnfamily"), // /** // * MapReduce run environment. Should be one of the enum values in MREnvironment.java // */ // MAPREDUCE_ENVIRONMENT("com.knewton.mapreduce.environment"), // /** // * Name of serialization factory class // */ // SERIALIZATION_FACTORY_PARAMETER("com.knewton.thrift.serialization.protocol"); // // public final String txt; // // private PropertyConstants(String propertyName) { // this.txt = propertyName; // } // }
import com.knewton.mapreduce.constant.PropertyConstants; import com.google.common.collect.Lists; import org.apache.cassandra.io.sstable.Component; import org.apache.cassandra.io.sstable.Descriptor; import org.apache.cassandra.utils.Pair; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.PathFilter; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.JobContext; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.util.List; import javax.annotation.Nullable;
* found */ private List<FileStatus> cleanUpBackupDir(List<FileStatus> files) { boolean foundFullBackupDir = false; for (FileStatus nestedDirStatus : files) { String nestedDirName = nestedDirStatus.getPath().getName(); if (nestedDirName.equals(FULL_PRIAM_BACKUP_DIR_NAME)) { foundFullBackupDir = true; } } if (foundFullBackupDir) { for (int i = 0; i < files.size(); i++) { FileStatus nestedDirStatus = files.get(i); String nestedDirName = nestedDirStatus.getPath().getName(); if (nestedDirName.equals(INCREMENTAL_PRIAM_BACKUP_DIR_NAME)) { LOG.info("Removing {}", nestedDirStatus.getPath()); files.remove(i); i--; } } } return files; } /** * Configure the DataTableFilter and return it. * * @return The DataTableFilter. */ private DataTablePathFilter getDataTableFilter(Configuration conf) {
// Path: src/main/java/com/knewton/mapreduce/constant/PropertyConstants.java // public enum PropertyConstants { // // /** // * The Keyspace Name for a data run // */ // KEYSPACE_NAME("com.knewton.inputformat.cassandra.keyspace"), // /** // * Column family type needs to be set if the column family type is Super. // */ // COLUMN_FAMILY_TYPE("com.knewton.cassandra.cftype"), // /** // * Comparator class name for columns. // */ // COLUMN_COMPARATOR("com.knewton.cassandra.column.comparator"), // /** // * A nonstandard comparator requires a subcomparator // */ // COLUMN_SUBCOMPARATOR("com.knewton.cassandra.column.subcomparator"), // /** // * Partitioner for decorating keys. // */ // PARTITIONER("com.knewton.partitioner"), // /** // * True if the columns are sparse, false if they're dense. // */ // SPARSE_COLUMN("com.knewton.column.sparse"), // /** // * Boolean variable. Set true if compression enabled. // */ // COMPRESSION_ENABLED("com.knewton.cassandra.backup.compression"), // /** // * Buffer size for decompression operation. // */ // DECOMPRESS_BUFFER("com.knewton.cassandra.backup.compress.buffersize"), // /** // * Start and end dates for student events processing // */ // START_DATE("com.knewton.studentevents.date.start"), // END_DATE("com.knewton.studentevents.date.end"), // /** // * The Column Family Name for a data run // */ // COLUMN_FAMILY_NAME("com.knewton.inputformat.cassandra.columnfamily"), // /** // * MapReduce run environment. Should be one of the enum values in MREnvironment.java // */ // MAPREDUCE_ENVIRONMENT("com.knewton.mapreduce.environment"), // /** // * Name of serialization factory class // */ // SERIALIZATION_FACTORY_PARAMETER("com.knewton.thrift.serialization.protocol"); // // public final String txt; // // private PropertyConstants(String propertyName) { // this.txt = propertyName; // } // } // Path: src/main/java/com/knewton/mapreduce/io/SSTableInputFormat.java import com.knewton.mapreduce.constant.PropertyConstants; import com.google.common.collect.Lists; import org.apache.cassandra.io.sstable.Component; import org.apache.cassandra.io.sstable.Descriptor; import org.apache.cassandra.utils.Pair; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.PathFilter; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.JobContext; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.util.List; import javax.annotation.Nullable; * found */ private List<FileStatus> cleanUpBackupDir(List<FileStatus> files) { boolean foundFullBackupDir = false; for (FileStatus nestedDirStatus : files) { String nestedDirName = nestedDirStatus.getPath().getName(); if (nestedDirName.equals(FULL_PRIAM_BACKUP_DIR_NAME)) { foundFullBackupDir = true; } } if (foundFullBackupDir) { for (int i = 0; i < files.size(); i++) { FileStatus nestedDirStatus = files.get(i); String nestedDirName = nestedDirStatus.getPath().getName(); if (nestedDirName.equals(INCREMENTAL_PRIAM_BACKUP_DIR_NAME)) { LOG.info("Removing {}", nestedDirStatus.getPath()); files.remove(i); i--; } } } return files; } /** * Configure the DataTableFilter and return it. * * @return The DataTableFilter. */ private DataTablePathFilter getDataTableFilter(Configuration conf) {
String operatingCF = conf.get(PropertyConstants.COLUMN_FAMILY_NAME.txt);
Knewton/KassandraMRHelper
src/test/java/com/knewton/mapreduce/io/DataTablePathFilterTest.java
// Path: src/main/java/com/knewton/mapreduce/io/SSTableInputFormat.java // public static class DataTablePathFilter implements PathFilter { // // @Nullable // private String operatingCF; // // @Nullable // private String operatingKeyspace; // // public DataTablePathFilter(@Nullable String operatingCF, // @Nullable String operatingKeyspace) { // this.operatingCF = operatingCF; // this.operatingKeyspace = operatingKeyspace; // } // // public DataTablePathFilter() { // this(null, null); // } // // /** // * {@inheritDoc} // */ // @Override // public boolean accept(Path path) { // if (path == null) { // return false; // } // // // Try and get the component and the descriptor from the filename // Descriptor desc; // Component component; // try { // File parentFile = new File(path.getParent().toString()); // Pair<Descriptor, Component> descCompPair = Component.fromFilename(parentFile, // path.getName()); // desc = descCompPair.left; // component = descCompPair.right; // // } catch (RuntimeException e) { // return false; // } // // if (component != Component.DATA || desc.type.isTemporary) { // return false; // } else { // // these parameters are allowed to be null, but if set, we must match // return (operatingCF == null || desc.cfname.equals(operatingCF)) && // (operatingKeyspace == null || desc.ksname.equals(operatingKeyspace)); // } // } // }
import com.knewton.mapreduce.io.SSTableInputFormat.DataTablePathFilter; import org.apache.hadoop.fs.Path; import org.junit.Test; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue;
/** * Copyright 2013, 2014, 2015 Knewton * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. * */ package com.knewton.mapreduce.io; public class DataTablePathFilterTest { /** * Tests to see if the table path filter can correctly filter through the sstables and only get * the data tables. */ @Test public void testDataTablePathFilter() {
// Path: src/main/java/com/knewton/mapreduce/io/SSTableInputFormat.java // public static class DataTablePathFilter implements PathFilter { // // @Nullable // private String operatingCF; // // @Nullable // private String operatingKeyspace; // // public DataTablePathFilter(@Nullable String operatingCF, // @Nullable String operatingKeyspace) { // this.operatingCF = operatingCF; // this.operatingKeyspace = operatingKeyspace; // } // // public DataTablePathFilter() { // this(null, null); // } // // /** // * {@inheritDoc} // */ // @Override // public boolean accept(Path path) { // if (path == null) { // return false; // } // // // Try and get the component and the descriptor from the filename // Descriptor desc; // Component component; // try { // File parentFile = new File(path.getParent().toString()); // Pair<Descriptor, Component> descCompPair = Component.fromFilename(parentFile, // path.getName()); // desc = descCompPair.left; // component = descCompPair.right; // // } catch (RuntimeException e) { // return false; // } // // if (component != Component.DATA || desc.type.isTemporary) { // return false; // } else { // // these parameters are allowed to be null, but if set, we must match // return (operatingCF == null || desc.cfname.equals(operatingCF)) && // (operatingKeyspace == null || desc.ksname.equals(operatingKeyspace)); // } // } // } // Path: src/test/java/com/knewton/mapreduce/io/DataTablePathFilterTest.java import com.knewton.mapreduce.io.SSTableInputFormat.DataTablePathFilter; import org.apache.hadoop.fs.Path; import org.junit.Test; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; /** * Copyright 2013, 2014, 2015 Knewton * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. * */ package com.knewton.mapreduce.io; public class DataTablePathFilterTest { /** * Tests to see if the table path filter can correctly filter through the sstables and only get * the data tables. */ @Test public void testDataTablePathFilter() {
DataTablePathFilter pathFilter = new DataTablePathFilter();
Knewton/KassandraMRHelper
src/test/java/com/knewton/mapreduce/util/SerializationUtilsTest.java
// Path: src/main/java/com/knewton/mapreduce/constant/PropertyConstants.java // public enum PropertyConstants { // // /** // * The Keyspace Name for a data run // */ // KEYSPACE_NAME("com.knewton.inputformat.cassandra.keyspace"), // /** // * Column family type needs to be set if the column family type is Super. // */ // COLUMN_FAMILY_TYPE("com.knewton.cassandra.cftype"), // /** // * Comparator class name for columns. // */ // COLUMN_COMPARATOR("com.knewton.cassandra.column.comparator"), // /** // * A nonstandard comparator requires a subcomparator // */ // COLUMN_SUBCOMPARATOR("com.knewton.cassandra.column.subcomparator"), // /** // * Partitioner for decorating keys. // */ // PARTITIONER("com.knewton.partitioner"), // /** // * True if the columns are sparse, false if they're dense. // */ // SPARSE_COLUMN("com.knewton.column.sparse"), // /** // * Boolean variable. Set true if compression enabled. // */ // COMPRESSION_ENABLED("com.knewton.cassandra.backup.compression"), // /** // * Buffer size for decompression operation. // */ // DECOMPRESS_BUFFER("com.knewton.cassandra.backup.compress.buffersize"), // /** // * Start and end dates for student events processing // */ // START_DATE("com.knewton.studentevents.date.start"), // END_DATE("com.knewton.studentevents.date.end"), // /** // * The Column Family Name for a data run // */ // COLUMN_FAMILY_NAME("com.knewton.inputformat.cassandra.columnfamily"), // /** // * MapReduce run environment. Should be one of the enum values in MREnvironment.java // */ // MAPREDUCE_ENVIRONMENT("com.knewton.mapreduce.environment"), // /** // * Name of serialization factory class // */ // SERIALIZATION_FACTORY_PARAMETER("com.knewton.thrift.serialization.protocol"); // // public final String txt; // // private PropertyConstants(String propertyName) { // this.txt = propertyName; // } // }
import com.knewton.mapreduce.constant.PropertyConstants; import org.apache.hadoop.conf.Configuration; import org.apache.thrift.TDeserializer; import org.apache.thrift.protocol.TCompactProtocol; import org.junit.Test; import static org.junit.Assert.assertNotNull;
/** * Copyright 2013, 2014, 2015 Knewton * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. * */ package com.knewton.mapreduce.util; public class SerializationUtilsTest { /** * Test if a deserializer can be instantiated correctly from a Hadoop conf property. */ @Test public void testGetDeserializerFromConf() throws Exception { Configuration conf = new Configuration(false);
// Path: src/main/java/com/knewton/mapreduce/constant/PropertyConstants.java // public enum PropertyConstants { // // /** // * The Keyspace Name for a data run // */ // KEYSPACE_NAME("com.knewton.inputformat.cassandra.keyspace"), // /** // * Column family type needs to be set if the column family type is Super. // */ // COLUMN_FAMILY_TYPE("com.knewton.cassandra.cftype"), // /** // * Comparator class name for columns. // */ // COLUMN_COMPARATOR("com.knewton.cassandra.column.comparator"), // /** // * A nonstandard comparator requires a subcomparator // */ // COLUMN_SUBCOMPARATOR("com.knewton.cassandra.column.subcomparator"), // /** // * Partitioner for decorating keys. // */ // PARTITIONER("com.knewton.partitioner"), // /** // * True if the columns are sparse, false if they're dense. // */ // SPARSE_COLUMN("com.knewton.column.sparse"), // /** // * Boolean variable. Set true if compression enabled. // */ // COMPRESSION_ENABLED("com.knewton.cassandra.backup.compression"), // /** // * Buffer size for decompression operation. // */ // DECOMPRESS_BUFFER("com.knewton.cassandra.backup.compress.buffersize"), // /** // * Start and end dates for student events processing // */ // START_DATE("com.knewton.studentevents.date.start"), // END_DATE("com.knewton.studentevents.date.end"), // /** // * The Column Family Name for a data run // */ // COLUMN_FAMILY_NAME("com.knewton.inputformat.cassandra.columnfamily"), // /** // * MapReduce run environment. Should be one of the enum values in MREnvironment.java // */ // MAPREDUCE_ENVIRONMENT("com.knewton.mapreduce.environment"), // /** // * Name of serialization factory class // */ // SERIALIZATION_FACTORY_PARAMETER("com.knewton.thrift.serialization.protocol"); // // public final String txt; // // private PropertyConstants(String propertyName) { // this.txt = propertyName; // } // } // Path: src/test/java/com/knewton/mapreduce/util/SerializationUtilsTest.java import com.knewton.mapreduce.constant.PropertyConstants; import org.apache.hadoop.conf.Configuration; import org.apache.thrift.TDeserializer; import org.apache.thrift.protocol.TCompactProtocol; import org.junit.Test; import static org.junit.Assert.assertNotNull; /** * Copyright 2013, 2014, 2015 Knewton * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. * */ package com.knewton.mapreduce.util; public class SerializationUtilsTest { /** * Test if a deserializer can be instantiated correctly from a Hadoop conf property. */ @Test public void testGetDeserializerFromConf() throws Exception { Configuration conf = new Configuration(false);
conf.set(PropertyConstants.SERIALIZATION_FACTORY_PARAMETER.txt,
Knewton/KassandraMRHelper
src/test/java/com/knewton/mapreduce/SSTableColumnRecordReaderTest.java
// Path: src/main/java/com/knewton/mapreduce/constant/PropertyConstants.java // public enum PropertyConstants { // // /** // * The Keyspace Name for a data run // */ // KEYSPACE_NAME("com.knewton.inputformat.cassandra.keyspace"), // /** // * Column family type needs to be set if the column family type is Super. // */ // COLUMN_FAMILY_TYPE("com.knewton.cassandra.cftype"), // /** // * Comparator class name for columns. // */ // COLUMN_COMPARATOR("com.knewton.cassandra.column.comparator"), // /** // * A nonstandard comparator requires a subcomparator // */ // COLUMN_SUBCOMPARATOR("com.knewton.cassandra.column.subcomparator"), // /** // * Partitioner for decorating keys. // */ // PARTITIONER("com.knewton.partitioner"), // /** // * True if the columns are sparse, false if they're dense. // */ // SPARSE_COLUMN("com.knewton.column.sparse"), // /** // * Boolean variable. Set true if compression enabled. // */ // COMPRESSION_ENABLED("com.knewton.cassandra.backup.compression"), // /** // * Buffer size for decompression operation. // */ // DECOMPRESS_BUFFER("com.knewton.cassandra.backup.compress.buffersize"), // /** // * Start and end dates for student events processing // */ // START_DATE("com.knewton.studentevents.date.start"), // END_DATE("com.knewton.studentevents.date.end"), // /** // * The Column Family Name for a data run // */ // COLUMN_FAMILY_NAME("com.knewton.inputformat.cassandra.columnfamily"), // /** // * MapReduce run environment. Should be one of the enum values in MREnvironment.java // */ // MAPREDUCE_ENVIRONMENT("com.knewton.mapreduce.environment"), // /** // * Name of serialization factory class // */ // SERIALIZATION_FACTORY_PARAMETER("com.knewton.thrift.serialization.protocol"); // // public final String txt; // // private PropertyConstants(String propertyName) { // this.txt = propertyName; // } // }
import com.knewton.mapreduce.constant.PropertyConstants; import org.apache.cassandra.config.CFMetaData; import org.apache.cassandra.db.BufferCounterCell; import org.apache.cassandra.db.BufferDecoratedKey; import org.apache.cassandra.db.ColumnSerializer.Flag; import org.apache.cassandra.db.CounterCell; import org.apache.cassandra.db.DecoratedKey; import org.apache.cassandra.db.composites.CellName; import org.apache.cassandra.db.composites.CellNameType; import org.apache.cassandra.db.composites.SimpleDenseCellNameType; import org.apache.cassandra.db.context.CounterContext; import org.apache.cassandra.db.marshal.BytesType; import org.apache.cassandra.db.marshal.LongType; import org.apache.cassandra.dht.IPartitioner; import org.apache.cassandra.dht.OrderPreservingPartitioner.StringToken; import org.apache.cassandra.dht.RandomPartitioner; import org.apache.cassandra.io.sstable.Descriptor; import org.apache.cassandra.io.sstable.Descriptor.Type; import org.apache.cassandra.io.sstable.ISSTableScanner; import org.apache.cassandra.io.sstable.SSTableIdentityIterator; import org.apache.cassandra.io.sstable.format.SSTableReader; import org.apache.cassandra.utils.CounterId; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.mapreduce.TaskAttemptContext; import org.apache.hadoop.mapreduce.TaskAttemptID; import org.apache.hadoop.mapreduce.lib.input.FileSplit; import org.apache.hadoop.mapreduce.task.TaskAttemptContextImpl; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.runners.MockitoJUnitRunner; import java.io.File; import java.nio.ByteBuffer; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.any; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when;
.openSSTableReader(any(IPartitioner.class), any(CFMetaData.class)); when(ssTableReader.estimatedKeys()).thenReturn(2L); when(ssTableReader.getScanner()).thenReturn(tableScanner); when(tableScanner.hasNext()).thenReturn(true, true, false); key = new BufferDecoratedKey(new StringToken("a"), ByteBuffer.wrap("b".getBytes())); CellNameType simpleDenseCellType = new SimpleDenseCellNameType(BytesType.instance); CellName cellName = simpleDenseCellType.cellFromByteBuffer(ByteBuffer.wrap("n".getBytes())); ByteBuffer counterBB = CounterContext.instance() .createGlobal(CounterId.fromInt(0), System.currentTimeMillis(), 123L); value = BufferCounterCell.create(cellName, counterBB, System.currentTimeMillis(), 0L, Flag.PRESERVE_SIZE); SSTableIdentityIterator row1 = getNewRow(); SSTableIdentityIterator row2 = getNewRow(); when(tableScanner.next()).thenReturn(row1, row2); } private SSTableIdentityIterator getNewRow() { SSTableIdentityIterator row = mock(SSTableIdentityIterator.class); when(row.hasNext()).thenReturn(true, true, false); when(row.getKey()).thenReturn(key); when(row.next()).thenReturn(value); return row; } private TaskAttemptContext getTaskAttemptContext() {
// Path: src/main/java/com/knewton/mapreduce/constant/PropertyConstants.java // public enum PropertyConstants { // // /** // * The Keyspace Name for a data run // */ // KEYSPACE_NAME("com.knewton.inputformat.cassandra.keyspace"), // /** // * Column family type needs to be set if the column family type is Super. // */ // COLUMN_FAMILY_TYPE("com.knewton.cassandra.cftype"), // /** // * Comparator class name for columns. // */ // COLUMN_COMPARATOR("com.knewton.cassandra.column.comparator"), // /** // * A nonstandard comparator requires a subcomparator // */ // COLUMN_SUBCOMPARATOR("com.knewton.cassandra.column.subcomparator"), // /** // * Partitioner for decorating keys. // */ // PARTITIONER("com.knewton.partitioner"), // /** // * True if the columns are sparse, false if they're dense. // */ // SPARSE_COLUMN("com.knewton.column.sparse"), // /** // * Boolean variable. Set true if compression enabled. // */ // COMPRESSION_ENABLED("com.knewton.cassandra.backup.compression"), // /** // * Buffer size for decompression operation. // */ // DECOMPRESS_BUFFER("com.knewton.cassandra.backup.compress.buffersize"), // /** // * Start and end dates for student events processing // */ // START_DATE("com.knewton.studentevents.date.start"), // END_DATE("com.knewton.studentevents.date.end"), // /** // * The Column Family Name for a data run // */ // COLUMN_FAMILY_NAME("com.knewton.inputformat.cassandra.columnfamily"), // /** // * MapReduce run environment. Should be one of the enum values in MREnvironment.java // */ // MAPREDUCE_ENVIRONMENT("com.knewton.mapreduce.environment"), // /** // * Name of serialization factory class // */ // SERIALIZATION_FACTORY_PARAMETER("com.knewton.thrift.serialization.protocol"); // // public final String txt; // // private PropertyConstants(String propertyName) { // this.txt = propertyName; // } // } // Path: src/test/java/com/knewton/mapreduce/SSTableColumnRecordReaderTest.java import com.knewton.mapreduce.constant.PropertyConstants; import org.apache.cassandra.config.CFMetaData; import org.apache.cassandra.db.BufferCounterCell; import org.apache.cassandra.db.BufferDecoratedKey; import org.apache.cassandra.db.ColumnSerializer.Flag; import org.apache.cassandra.db.CounterCell; import org.apache.cassandra.db.DecoratedKey; import org.apache.cassandra.db.composites.CellName; import org.apache.cassandra.db.composites.CellNameType; import org.apache.cassandra.db.composites.SimpleDenseCellNameType; import org.apache.cassandra.db.context.CounterContext; import org.apache.cassandra.db.marshal.BytesType; import org.apache.cassandra.db.marshal.LongType; import org.apache.cassandra.dht.IPartitioner; import org.apache.cassandra.dht.OrderPreservingPartitioner.StringToken; import org.apache.cassandra.dht.RandomPartitioner; import org.apache.cassandra.io.sstable.Descriptor; import org.apache.cassandra.io.sstable.Descriptor.Type; import org.apache.cassandra.io.sstable.ISSTableScanner; import org.apache.cassandra.io.sstable.SSTableIdentityIterator; import org.apache.cassandra.io.sstable.format.SSTableReader; import org.apache.cassandra.utils.CounterId; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.mapreduce.TaskAttemptContext; import org.apache.hadoop.mapreduce.TaskAttemptID; import org.apache.hadoop.mapreduce.lib.input.FileSplit; import org.apache.hadoop.mapreduce.task.TaskAttemptContextImpl; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.runners.MockitoJUnitRunner; import java.io.File; import java.nio.ByteBuffer; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.any; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; .openSSTableReader(any(IPartitioner.class), any(CFMetaData.class)); when(ssTableReader.estimatedKeys()).thenReturn(2L); when(ssTableReader.getScanner()).thenReturn(tableScanner); when(tableScanner.hasNext()).thenReturn(true, true, false); key = new BufferDecoratedKey(new StringToken("a"), ByteBuffer.wrap("b".getBytes())); CellNameType simpleDenseCellType = new SimpleDenseCellNameType(BytesType.instance); CellName cellName = simpleDenseCellType.cellFromByteBuffer(ByteBuffer.wrap("n".getBytes())); ByteBuffer counterBB = CounterContext.instance() .createGlobal(CounterId.fromInt(0), System.currentTimeMillis(), 123L); value = BufferCounterCell.create(cellName, counterBB, System.currentTimeMillis(), 0L, Flag.PRESERVE_SIZE); SSTableIdentityIterator row1 = getNewRow(); SSTableIdentityIterator row2 = getNewRow(); when(tableScanner.next()).thenReturn(row1, row2); } private SSTableIdentityIterator getNewRow() { SSTableIdentityIterator row = mock(SSTableIdentityIterator.class); when(row.hasNext()).thenReturn(true, true, false); when(row.getKey()).thenReturn(key); when(row.next()).thenReturn(value); return row; } private TaskAttemptContext getTaskAttemptContext() {
conf.set(PropertyConstants.COLUMN_COMPARATOR.txt, LongType.class.getName());
Knewton/KassandraMRHelper
src/main/java/com/knewton/mapreduce/util/SerializationUtils.java
// Path: src/main/java/com/knewton/mapreduce/constant/PropertyConstants.java // public enum PropertyConstants { // // /** // * The Keyspace Name for a data run // */ // KEYSPACE_NAME("com.knewton.inputformat.cassandra.keyspace"), // /** // * Column family type needs to be set if the column family type is Super. // */ // COLUMN_FAMILY_TYPE("com.knewton.cassandra.cftype"), // /** // * Comparator class name for columns. // */ // COLUMN_COMPARATOR("com.knewton.cassandra.column.comparator"), // /** // * A nonstandard comparator requires a subcomparator // */ // COLUMN_SUBCOMPARATOR("com.knewton.cassandra.column.subcomparator"), // /** // * Partitioner for decorating keys. // */ // PARTITIONER("com.knewton.partitioner"), // /** // * True if the columns are sparse, false if they're dense. // */ // SPARSE_COLUMN("com.knewton.column.sparse"), // /** // * Boolean variable. Set true if compression enabled. // */ // COMPRESSION_ENABLED("com.knewton.cassandra.backup.compression"), // /** // * Buffer size for decompression operation. // */ // DECOMPRESS_BUFFER("com.knewton.cassandra.backup.compress.buffersize"), // /** // * Start and end dates for student events processing // */ // START_DATE("com.knewton.studentevents.date.start"), // END_DATE("com.knewton.studentevents.date.end"), // /** // * The Column Family Name for a data run // */ // COLUMN_FAMILY_NAME("com.knewton.inputformat.cassandra.columnfamily"), // /** // * MapReduce run environment. Should be one of the enum values in MREnvironment.java // */ // MAPREDUCE_ENVIRONMENT("com.knewton.mapreduce.environment"), // /** // * Name of serialization factory class // */ // SERIALIZATION_FACTORY_PARAMETER("com.knewton.thrift.serialization.protocol"); // // public final String txt; // // private PropertyConstants(String propertyName) { // this.txt = propertyName; // } // }
import com.knewton.mapreduce.constant.PropertyConstants; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.util.ReflectionUtils; import org.apache.thrift.TDeserializer; import org.apache.thrift.protocol.TCompactProtocol; import org.apache.thrift.protocol.TCompactProtocol.Factory; import org.apache.thrift.protocol.TProtocolFactory;
/** * Copyright 2013, 2014, 2015 Knewton * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. * */ package com.knewton.mapreduce.util; public class SerializationUtils { public static final Class<Factory> SERIALIZATION_FACTORY_PARAMETER_DEFAULT = TCompactProtocol.Factory.class; public static TDeserializer getDeserializerFromConf(Configuration conf) { Class<? extends TProtocolFactory> protocolFactoryClass =
// Path: src/main/java/com/knewton/mapreduce/constant/PropertyConstants.java // public enum PropertyConstants { // // /** // * The Keyspace Name for a data run // */ // KEYSPACE_NAME("com.knewton.inputformat.cassandra.keyspace"), // /** // * Column family type needs to be set if the column family type is Super. // */ // COLUMN_FAMILY_TYPE("com.knewton.cassandra.cftype"), // /** // * Comparator class name for columns. // */ // COLUMN_COMPARATOR("com.knewton.cassandra.column.comparator"), // /** // * A nonstandard comparator requires a subcomparator // */ // COLUMN_SUBCOMPARATOR("com.knewton.cassandra.column.subcomparator"), // /** // * Partitioner for decorating keys. // */ // PARTITIONER("com.knewton.partitioner"), // /** // * True if the columns are sparse, false if they're dense. // */ // SPARSE_COLUMN("com.knewton.column.sparse"), // /** // * Boolean variable. Set true if compression enabled. // */ // COMPRESSION_ENABLED("com.knewton.cassandra.backup.compression"), // /** // * Buffer size for decompression operation. // */ // DECOMPRESS_BUFFER("com.knewton.cassandra.backup.compress.buffersize"), // /** // * Start and end dates for student events processing // */ // START_DATE("com.knewton.studentevents.date.start"), // END_DATE("com.knewton.studentevents.date.end"), // /** // * The Column Family Name for a data run // */ // COLUMN_FAMILY_NAME("com.knewton.inputformat.cassandra.columnfamily"), // /** // * MapReduce run environment. Should be one of the enum values in MREnvironment.java // */ // MAPREDUCE_ENVIRONMENT("com.knewton.mapreduce.environment"), // /** // * Name of serialization factory class // */ // SERIALIZATION_FACTORY_PARAMETER("com.knewton.thrift.serialization.protocol"); // // public final String txt; // // private PropertyConstants(String propertyName) { // this.txt = propertyName; // } // } // Path: src/main/java/com/knewton/mapreduce/util/SerializationUtils.java import com.knewton.mapreduce.constant.PropertyConstants; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.util.ReflectionUtils; import org.apache.thrift.TDeserializer; import org.apache.thrift.protocol.TCompactProtocol; import org.apache.thrift.protocol.TCompactProtocol.Factory; import org.apache.thrift.protocol.TProtocolFactory; /** * Copyright 2013, 2014, 2015 Knewton * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. * */ package com.knewton.mapreduce.util; public class SerializationUtils { public static final Class<Factory> SERIALIZATION_FACTORY_PARAMETER_DEFAULT = TCompactProtocol.Factory.class; public static TDeserializer getDeserializerFromConf(Configuration conf) { Class<? extends TProtocolFactory> protocolFactoryClass =
conf.getClass(PropertyConstants.SERIALIZATION_FACTORY_PARAMETER.txt,
Knewton/KassandraMRHelper
src/test/java/com/knewton/mapreduce/SSTableRowRecordReaderTest.java
// Path: src/main/java/com/knewton/mapreduce/constant/PropertyConstants.java // public enum PropertyConstants { // // /** // * The Keyspace Name for a data run // */ // KEYSPACE_NAME("com.knewton.inputformat.cassandra.keyspace"), // /** // * Column family type needs to be set if the column family type is Super. // */ // COLUMN_FAMILY_TYPE("com.knewton.cassandra.cftype"), // /** // * Comparator class name for columns. // */ // COLUMN_COMPARATOR("com.knewton.cassandra.column.comparator"), // /** // * A nonstandard comparator requires a subcomparator // */ // COLUMN_SUBCOMPARATOR("com.knewton.cassandra.column.subcomparator"), // /** // * Partitioner for decorating keys. // */ // PARTITIONER("com.knewton.partitioner"), // /** // * True if the columns are sparse, false if they're dense. // */ // SPARSE_COLUMN("com.knewton.column.sparse"), // /** // * Boolean variable. Set true if compression enabled. // */ // COMPRESSION_ENABLED("com.knewton.cassandra.backup.compression"), // /** // * Buffer size for decompression operation. // */ // DECOMPRESS_BUFFER("com.knewton.cassandra.backup.compress.buffersize"), // /** // * Start and end dates for student events processing // */ // START_DATE("com.knewton.studentevents.date.start"), // END_DATE("com.knewton.studentevents.date.end"), // /** // * The Column Family Name for a data run // */ // COLUMN_FAMILY_NAME("com.knewton.inputformat.cassandra.columnfamily"), // /** // * MapReduce run environment. Should be one of the enum values in MREnvironment.java // */ // MAPREDUCE_ENVIRONMENT("com.knewton.mapreduce.environment"), // /** // * Name of serialization factory class // */ // SERIALIZATION_FACTORY_PARAMETER("com.knewton.thrift.serialization.protocol"); // // public final String txt; // // private PropertyConstants(String propertyName) { // this.txt = propertyName; // } // }
import com.knewton.mapreduce.constant.PropertyConstants; import org.apache.cassandra.config.CFMetaData; import org.apache.cassandra.db.BufferDecoratedKey; import org.apache.cassandra.db.DecoratedKey; import org.apache.cassandra.db.marshal.LongType; import org.apache.cassandra.dht.IPartitioner; import org.apache.cassandra.dht.OrderPreservingPartitioner.StringToken; import org.apache.cassandra.dht.RandomPartitioner; import org.apache.cassandra.io.sstable.Descriptor; import org.apache.cassandra.io.sstable.Descriptor.Type; import org.apache.cassandra.io.sstable.ISSTableScanner; import org.apache.cassandra.io.sstable.SSTableIdentityIterator; import org.apache.cassandra.io.sstable.format.SSTableReader; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.mapreduce.TaskAttemptContext; import org.apache.hadoop.mapreduce.TaskAttemptID; import org.apache.hadoop.mapreduce.lib.input.FileSplit; import org.apache.hadoop.mapreduce.task.TaskAttemptContextImpl; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.runners.MockitoJUnitRunner; import java.io.File; import java.nio.ByteBuffer; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.any; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when;
attemptId = new TaskAttemptID(); Path inputPath = new Path(TABLE_PATH_STR); inputSplit = new FileSplit(inputPath, 0, 1, null); Descriptor desc = new Descriptor(new File(TABLE_PATH_STR), "keyspace", "columnFamily", 1, Type.FINAL); doReturn(desc).when(ssTableRowRecordReader).getDescriptor(); doNothing().when(ssTableRowRecordReader).copyTablesToLocal(any(FileSystem.class), any(FileSystem.class), any(Path.class), any(TaskAttemptContext.class)); doReturn(ssTableReader).when(ssTableRowRecordReader) .openSSTableReader(any(IPartitioner.class), any(CFMetaData.class)); when(ssTableReader.estimatedKeys()).thenReturn(1L); when(ssTableReader.getScanner()).thenReturn(tableScanner); when(tableScanner.hasNext()).thenReturn(true, false); key = new BufferDecoratedKey(new StringToken("a"), ByteBuffer.wrap("b".getBytes())); row = mock(SSTableIdentityIterator.class); when(row.getKey()).thenReturn(key); when(tableScanner.next()).thenReturn(row); } private TaskAttemptContext getTaskAttemptContext() {
// Path: src/main/java/com/knewton/mapreduce/constant/PropertyConstants.java // public enum PropertyConstants { // // /** // * The Keyspace Name for a data run // */ // KEYSPACE_NAME("com.knewton.inputformat.cassandra.keyspace"), // /** // * Column family type needs to be set if the column family type is Super. // */ // COLUMN_FAMILY_TYPE("com.knewton.cassandra.cftype"), // /** // * Comparator class name for columns. // */ // COLUMN_COMPARATOR("com.knewton.cassandra.column.comparator"), // /** // * A nonstandard comparator requires a subcomparator // */ // COLUMN_SUBCOMPARATOR("com.knewton.cassandra.column.subcomparator"), // /** // * Partitioner for decorating keys. // */ // PARTITIONER("com.knewton.partitioner"), // /** // * True if the columns are sparse, false if they're dense. // */ // SPARSE_COLUMN("com.knewton.column.sparse"), // /** // * Boolean variable. Set true if compression enabled. // */ // COMPRESSION_ENABLED("com.knewton.cassandra.backup.compression"), // /** // * Buffer size for decompression operation. // */ // DECOMPRESS_BUFFER("com.knewton.cassandra.backup.compress.buffersize"), // /** // * Start and end dates for student events processing // */ // START_DATE("com.knewton.studentevents.date.start"), // END_DATE("com.knewton.studentevents.date.end"), // /** // * The Column Family Name for a data run // */ // COLUMN_FAMILY_NAME("com.knewton.inputformat.cassandra.columnfamily"), // /** // * MapReduce run environment. Should be one of the enum values in MREnvironment.java // */ // MAPREDUCE_ENVIRONMENT("com.knewton.mapreduce.environment"), // /** // * Name of serialization factory class // */ // SERIALIZATION_FACTORY_PARAMETER("com.knewton.thrift.serialization.protocol"); // // public final String txt; // // private PropertyConstants(String propertyName) { // this.txt = propertyName; // } // } // Path: src/test/java/com/knewton/mapreduce/SSTableRowRecordReaderTest.java import com.knewton.mapreduce.constant.PropertyConstants; import org.apache.cassandra.config.CFMetaData; import org.apache.cassandra.db.BufferDecoratedKey; import org.apache.cassandra.db.DecoratedKey; import org.apache.cassandra.db.marshal.LongType; import org.apache.cassandra.dht.IPartitioner; import org.apache.cassandra.dht.OrderPreservingPartitioner.StringToken; import org.apache.cassandra.dht.RandomPartitioner; import org.apache.cassandra.io.sstable.Descriptor; import org.apache.cassandra.io.sstable.Descriptor.Type; import org.apache.cassandra.io.sstable.ISSTableScanner; import org.apache.cassandra.io.sstable.SSTableIdentityIterator; import org.apache.cassandra.io.sstable.format.SSTableReader; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.mapreduce.TaskAttemptContext; import org.apache.hadoop.mapreduce.TaskAttemptID; import org.apache.hadoop.mapreduce.lib.input.FileSplit; import org.apache.hadoop.mapreduce.task.TaskAttemptContextImpl; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.runners.MockitoJUnitRunner; import java.io.File; import java.nio.ByteBuffer; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.any; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; attemptId = new TaskAttemptID(); Path inputPath = new Path(TABLE_PATH_STR); inputSplit = new FileSplit(inputPath, 0, 1, null); Descriptor desc = new Descriptor(new File(TABLE_PATH_STR), "keyspace", "columnFamily", 1, Type.FINAL); doReturn(desc).when(ssTableRowRecordReader).getDescriptor(); doNothing().when(ssTableRowRecordReader).copyTablesToLocal(any(FileSystem.class), any(FileSystem.class), any(Path.class), any(TaskAttemptContext.class)); doReturn(ssTableReader).when(ssTableRowRecordReader) .openSSTableReader(any(IPartitioner.class), any(CFMetaData.class)); when(ssTableReader.estimatedKeys()).thenReturn(1L); when(ssTableReader.getScanner()).thenReturn(tableScanner); when(tableScanner.hasNext()).thenReturn(true, false); key = new BufferDecoratedKey(new StringToken("a"), ByteBuffer.wrap("b".getBytes())); row = mock(SSTableIdentityIterator.class); when(row.getKey()).thenReturn(key); when(tableScanner.next()).thenReturn(row); } private TaskAttemptContext getTaskAttemptContext() {
conf.set(PropertyConstants.COLUMN_COMPARATOR.txt, LongType.class.getName());
renatoathaydes/LogFX
src/main/java/com/athaydes/logfx/ui/FileOpener.java
// Path: src/main/java/com/athaydes/logfx/data/LogFile.java // public final class LogFile { // public final File file; // private final BindableValue<String> highlightGroup = new BindableValue<>( "" ); // // public LogFile( File file ) { // this.file = file; // } // // public LogFile( File file, String highlightGroupName ) { // this.file = file; // highlightGroup.setValue( highlightGroupName ); // } // // public BindableValue<String> highlightGroupProperty() { // return highlightGroup; // } // // public String getHighlightGroup() { // return highlightGroup.getValue(); // } // // @Override // public boolean equals( Object other ) { // if ( this == other ) return true; // if ( !( other instanceof LogFile ) ) return false; // LogFile logFile = ( LogFile ) other; // return Objects.equals( file, logFile.file ); // } // // @Override // public int hashCode() { // return Objects.hash( file ); // } // // }
import com.athaydes.logfx.data.LogFile; import javafx.stage.FileChooser; import javafx.stage.Stage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.util.Collection; import java.util.function.Consumer;
package com.athaydes.logfx.ui; /** * Operating System File opener Dialog. */ public class FileOpener { public static final int MAX_OPEN_FILES = 10; private static final Logger log = LoggerFactory.getLogger( FileOpener.class ); public static void run( Stage stage,
// Path: src/main/java/com/athaydes/logfx/data/LogFile.java // public final class LogFile { // public final File file; // private final BindableValue<String> highlightGroup = new BindableValue<>( "" ); // // public LogFile( File file ) { // this.file = file; // } // // public LogFile( File file, String highlightGroupName ) { // this.file = file; // highlightGroup.setValue( highlightGroupName ); // } // // public BindableValue<String> highlightGroupProperty() { // return highlightGroup; // } // // public String getHighlightGroup() { // return highlightGroup.getValue(); // } // // @Override // public boolean equals( Object other ) { // if ( this == other ) return true; // if ( !( other instanceof LogFile ) ) return false; // LogFile logFile = ( LogFile ) other; // return Objects.equals( file, logFile.file ); // } // // @Override // public int hashCode() { // return Objects.hash( file ); // } // // } // Path: src/main/java/com/athaydes/logfx/ui/FileOpener.java import com.athaydes.logfx.data.LogFile; import javafx.stage.FileChooser; import javafx.stage.Stage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.util.Collection; import java.util.function.Consumer; package com.athaydes.logfx.ui; /** * Operating System File opener Dialog. */ public class FileOpener { public static final int MAX_OPEN_FILES = 10; private static final Logger log = LoggerFactory.getLogger( FileOpener.class ); public static void run( Stage stage,
Collection<LogFile> logFiles,
renatoathaydes/LogFX
src/main/java/com/athaydes/logfx/ui/HighlightGroupSelector.java
// Path: src/main/java/com/athaydes/logfx/config/HighlightGroups.java // public final class HighlightGroups { // private final ObservableSet<LogFile> observableFiles; // private final ObservableMap<String, ObservableList<HighlightExpression>> configByGroupName; // // private InvalidationListener invalidationListener; // // public HighlightGroups( ObservableSet<LogFile> observableFiles ) { // this.observableFiles = observableFiles; // configByGroupName = FXCollections.observableMap( new LinkedHashMap<>( 4 ) ); // configByGroupName.put( "", createNewExpressions( null ) ); // } // // public ObservableList<HighlightExpression> getByName( String name ) { // return configByGroupName.get( name ); // } // // public ObservableList<HighlightExpression> getDefault() { // return configByGroupName.get( "" ); // } // // public ObservableList<HighlightExpression> add( String groupName ) { // return configByGroupName.computeIfAbsent( groupName, // this::createNewExpressions ); // } // // public void remove( String groupName ) { // if ( groupName.isEmpty() ) { // return; // } // configByGroupName.remove( groupName ); // observableFiles.stream() // .filter( it -> groupName.equals( it.getHighlightGroup() ) ) // .forEach( file -> file.highlightGroupProperty().setValue( "" ) ); // } // // public void renameGroup( String oldName, String newName ) { // configByGroupName.put( newName, configByGroupName.remove( oldName ) ); // observableFiles.stream() // .filter( it -> oldName.equals( it.getHighlightGroup() ) ) // .forEach( file -> file.highlightGroupProperty().setValue( newName ) ); // } // // public Set<String> groupNames() { // return Collections.unmodifiableSet( configByGroupName.keySet() ); // } // // public Map<String, ObservableList<HighlightExpression>> toMap() { // return Collections.unmodifiableMap( configByGroupName ); // } // // public void addGroupNameListener( InvalidationListener listener ) { // configByGroupName.addListener( listener ); // } // // public void removeGroupNameListener( InvalidationListener listener ) { // configByGroupName.removeListener( listener ); // } // // public void clear() { // configByGroupName.clear(); // configByGroupName.put( "", createNewExpressions( null ) ); // } // // void setListener( InvalidationListener listener ) { // if ( invalidationListener != null ) throw new RuntimeException( "invalidation listener has already been set" ); // invalidationListener = listener; // configByGroupName.addListener( listener ); // configByGroupName.values().forEach( ( v ) -> v.addListener( listener ) ); // } // // private ObservableList<HighlightExpression> createNewExpressions( Object ignore ) { // ObservableList<HighlightExpression> newList = FXCollections.observableArrayList(); // if ( invalidationListener != null ) newList.addListener( invalidationListener ); // return newList; // } // }
import com.athaydes.logfx.config.HighlightGroups; import javafx.application.Platform; import javafx.beans.InvalidationListener; import javafx.scene.control.ChoiceBox; import javafx.util.StringConverter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Set;
package com.athaydes.logfx.ui; public final class HighlightGroupSelector extends ChoiceBox<String> { private static final Logger logger = LoggerFactory.getLogger( HighlightGroupSelector.class );
// Path: src/main/java/com/athaydes/logfx/config/HighlightGroups.java // public final class HighlightGroups { // private final ObservableSet<LogFile> observableFiles; // private final ObservableMap<String, ObservableList<HighlightExpression>> configByGroupName; // // private InvalidationListener invalidationListener; // // public HighlightGroups( ObservableSet<LogFile> observableFiles ) { // this.observableFiles = observableFiles; // configByGroupName = FXCollections.observableMap( new LinkedHashMap<>( 4 ) ); // configByGroupName.put( "", createNewExpressions( null ) ); // } // // public ObservableList<HighlightExpression> getByName( String name ) { // return configByGroupName.get( name ); // } // // public ObservableList<HighlightExpression> getDefault() { // return configByGroupName.get( "" ); // } // // public ObservableList<HighlightExpression> add( String groupName ) { // return configByGroupName.computeIfAbsent( groupName, // this::createNewExpressions ); // } // // public void remove( String groupName ) { // if ( groupName.isEmpty() ) { // return; // } // configByGroupName.remove( groupName ); // observableFiles.stream() // .filter( it -> groupName.equals( it.getHighlightGroup() ) ) // .forEach( file -> file.highlightGroupProperty().setValue( "" ) ); // } // // public void renameGroup( String oldName, String newName ) { // configByGroupName.put( newName, configByGroupName.remove( oldName ) ); // observableFiles.stream() // .filter( it -> oldName.equals( it.getHighlightGroup() ) ) // .forEach( file -> file.highlightGroupProperty().setValue( newName ) ); // } // // public Set<String> groupNames() { // return Collections.unmodifiableSet( configByGroupName.keySet() ); // } // // public Map<String, ObservableList<HighlightExpression>> toMap() { // return Collections.unmodifiableMap( configByGroupName ); // } // // public void addGroupNameListener( InvalidationListener listener ) { // configByGroupName.addListener( listener ); // } // // public void removeGroupNameListener( InvalidationListener listener ) { // configByGroupName.removeListener( listener ); // } // // public void clear() { // configByGroupName.clear(); // configByGroupName.put( "", createNewExpressions( null ) ); // } // // void setListener( InvalidationListener listener ) { // if ( invalidationListener != null ) throw new RuntimeException( "invalidation listener has already been set" ); // invalidationListener = listener; // configByGroupName.addListener( listener ); // configByGroupName.values().forEach( ( v ) -> v.addListener( listener ) ); // } // // private ObservableList<HighlightExpression> createNewExpressions( Object ignore ) { // ObservableList<HighlightExpression> newList = FXCollections.observableArrayList(); // if ( invalidationListener != null ) newList.addListener( invalidationListener ); // return newList; // } // } // Path: src/main/java/com/athaydes/logfx/ui/HighlightGroupSelector.java import com.athaydes.logfx.config.HighlightGroups; import javafx.application.Platform; import javafx.beans.InvalidationListener; import javafx.scene.control.ChoiceBox; import javafx.util.StringConverter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Set; package com.athaydes.logfx.ui; public final class HighlightGroupSelector extends ChoiceBox<String> { private static final Logger logger = LoggerFactory.getLogger( HighlightGroupSelector.class );
private final HighlightGroups highlightGroups;
renatoathaydes/LogFX
src/main/java/com/athaydes/logfx/text/HighlightExpression.java
// Path: src/main/java/com/athaydes/logfx/data/LogLineColors.java // public class LogLineColors { // // private final Paint background; // private final Paint fill; // // public LogLineColors( Paint background, Paint fill ) { // this.background = background; // this.fill = fill; // } // // public Paint getBackground() { // return background; // } // // public Paint getFill() { // return fill; // } // }
import com.athaydes.logfx.data.LogLineColors; import javafx.scene.paint.Paint; import java.util.Objects; import java.util.regex.Pattern;
package com.athaydes.logfx.text; /** * A log line highlight expression. * <p> * This class is immutable, so every time the user changes one of its properties * the UI components managing it need to create a new instance. */ public final class HighlightExpression { private final Pattern expression; private final Paint bkgColor; private final Paint fillColor; private final boolean isFiltered; public HighlightExpression( String expression, Paint bkgColor, Paint fillColor, boolean isFiltered ) { this( Pattern.compile( expression ), bkgColor, fillColor, isFiltered ); } public HighlightExpression( Pattern expression, Paint bkgColor, Paint fillColor, boolean isFiltered ) { this.expression = expression; this.bkgColor = bkgColor; this.fillColor = fillColor; this.isFiltered = isFiltered; } public Paint getBkgColor() { return bkgColor; } public Paint getFillColor() { return fillColor; } public Pattern getPattern() { return expression; } public boolean isFiltered() { return isFiltered; }
// Path: src/main/java/com/athaydes/logfx/data/LogLineColors.java // public class LogLineColors { // // private final Paint background; // private final Paint fill; // // public LogLineColors( Paint background, Paint fill ) { // this.background = background; // this.fill = fill; // } // // public Paint getBackground() { // return background; // } // // public Paint getFill() { // return fill; // } // } // Path: src/main/java/com/athaydes/logfx/text/HighlightExpression.java import com.athaydes.logfx.data.LogLineColors; import javafx.scene.paint.Paint; import java.util.Objects; import java.util.regex.Pattern; package com.athaydes.logfx.text; /** * A log line highlight expression. * <p> * This class is immutable, so every time the user changes one of its properties * the UI components managing it need to create a new instance. */ public final class HighlightExpression { private final Pattern expression; private final Paint bkgColor; private final Paint fillColor; private final boolean isFiltered; public HighlightExpression( String expression, Paint bkgColor, Paint fillColor, boolean isFiltered ) { this( Pattern.compile( expression ), bkgColor, fillColor, isFiltered ); } public HighlightExpression( Pattern expression, Paint bkgColor, Paint fillColor, boolean isFiltered ) { this.expression = expression; this.bkgColor = bkgColor; this.fillColor = fillColor; this.isFiltered = isFiltered; } public Paint getBkgColor() { return bkgColor; } public Paint getFillColor() { return fillColor; } public Pattern getPattern() { return expression; } public boolean isFiltered() { return isFiltered; }
public LogLineColors getLogLineColors() {
renatoathaydes/LogFX
src/main/java/com/athaydes/logfx/ui/SelectableContainer.java
// Path: src/main/java/com/athaydes/logfx/iterable/ObservableListView.java // public class ObservableListView<T, N> { // // private final Class<? extends T> elementType; // private final ObservableList<? extends N> delegate; // // public ObservableListView( Class<? extends T> elementType, ObservableList<N> delegate ) { // this.elementType = elementType; // this.delegate = delegate; // } // // public ObservableList<? extends N> getList() { // return delegate; // } // // public Iterable<T> getIterable() { // return () -> new Iter( delegate.iterator() ); // } // // private final class Iter implements Iterator<T> { // private final Iterator<?> iterator; // private T nextItem; // // public Iter( Iterator<?> iterator ) { // this.iterator = iterator; // } // // @Override // public boolean hasNext() { // nextItem = null; // while ( iterator.hasNext() ) { // var next = iterator.next(); // if ( elementType.isInstance( next ) ) { // nextItem = elementType.cast( next ); // break; // } // } // return nextItem != null; // } // // @Override // public T next() { // if ( nextItem == null ) { // throw new NoSuchElementException(); // } // return nextItem; // } // } // }
import com.athaydes.logfx.iterable.ObservableListView; import javafx.scene.Node; import java.util.concurrent.CompletionStage;
package com.athaydes.logfx.ui; interface SelectableContainer { Node getNode();
// Path: src/main/java/com/athaydes/logfx/iterable/ObservableListView.java // public class ObservableListView<T, N> { // // private final Class<? extends T> elementType; // private final ObservableList<? extends N> delegate; // // public ObservableListView( Class<? extends T> elementType, ObservableList<N> delegate ) { // this.elementType = elementType; // this.delegate = delegate; // } // // public ObservableList<? extends N> getList() { // return delegate; // } // // public Iterable<T> getIterable() { // return () -> new Iter( delegate.iterator() ); // } // // private final class Iter implements Iterator<T> { // private final Iterator<?> iterator; // private T nextItem; // // public Iter( Iterator<?> iterator ) { // this.iterator = iterator; // } // // @Override // public boolean hasNext() { // nextItem = null; // while ( iterator.hasNext() ) { // var next = iterator.next(); // if ( elementType.isInstance( next ) ) { // nextItem = elementType.cast( next ); // break; // } // } // return nextItem != null; // } // // @Override // public T next() { // if ( nextItem == null ) { // throw new NoSuchElementException(); // } // return nextItem; // } // } // } // Path: src/main/java/com/athaydes/logfx/ui/SelectableContainer.java import com.athaydes.logfx.iterable.ObservableListView; import javafx.scene.Node; import java.util.concurrent.CompletionStage; package com.athaydes.logfx.ui; interface SelectableContainer { Node getNode();
ObservableListView<? extends SelectionHandler.SelectableNode, Node> getSelectables();
renatoathaydes/LogFX
src/main/java/com/athaydes/logfx/ui/AboutLogFXView.java
// Path: src/main/java-templates/com/athaydes/logfx/Constants.java // public class Constants { // public static final String LOGFX_VERSION = "${logfxVersion}"; // } // // Path: src/main/java/com/athaydes/logfx/ui/FxUtils.java // public static String resourcePath( String name ) { // return resourceUrl( name ).toExternalForm(); // }
import com.athaydes.logfx.Constants; import javafx.geometry.Pos; import javafx.scene.Group; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.scene.text.Text; import javafx.stage.StageStyle; import static com.athaydes.logfx.ui.FxUtils.resourcePath;
package com.athaydes.logfx.ui; /** * About LogFX View. */ public class AboutLogFXView { public static final int WIDTH = 500; public static final int HEIGHT = 350; VBox createNode() { VBox contents = new VBox( 25 ); contents.setPrefSize( WIDTH, HEIGHT ); contents.setAlignment( Pos.CENTER );
// Path: src/main/java-templates/com/athaydes/logfx/Constants.java // public class Constants { // public static final String LOGFX_VERSION = "${logfxVersion}"; // } // // Path: src/main/java/com/athaydes/logfx/ui/FxUtils.java // public static String resourcePath( String name ) { // return resourceUrl( name ).toExternalForm(); // } // Path: src/main/java/com/athaydes/logfx/ui/AboutLogFXView.java import com.athaydes.logfx.Constants; import javafx.geometry.Pos; import javafx.scene.Group; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.scene.text.Text; import javafx.stage.StageStyle; import static com.athaydes.logfx.ui.FxUtils.resourcePath; package com.athaydes.logfx.ui; /** * About LogFX View. */ public class AboutLogFXView { public static final int WIDTH = 500; public static final int HEIGHT = 350; VBox createNode() { VBox contents = new VBox( 25 ); contents.setPrefSize( WIDTH, HEIGHT ); contents.setAlignment( Pos.CENTER );
contents.getStylesheets().add( resourcePath( "css/about.css" ) );
renatoathaydes/LogFX
src/main/java/com/athaydes/logfx/ui/AboutLogFXView.java
// Path: src/main/java-templates/com/athaydes/logfx/Constants.java // public class Constants { // public static final String LOGFX_VERSION = "${logfxVersion}"; // } // // Path: src/main/java/com/athaydes/logfx/ui/FxUtils.java // public static String resourcePath( String name ) { // return resourceUrl( name ).toExternalForm(); // }
import com.athaydes.logfx.Constants; import javafx.geometry.Pos; import javafx.scene.Group; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.scene.text.Text; import javafx.stage.StageStyle; import static com.athaydes.logfx.ui.FxUtils.resourcePath;
package com.athaydes.logfx.ui; /** * About LogFX View. */ public class AboutLogFXView { public static final int WIDTH = 500; public static final int HEIGHT = 350; VBox createNode() { VBox contents = new VBox( 25 ); contents.setPrefSize( WIDTH, HEIGHT ); contents.setAlignment( Pos.CENTER ); contents.getStylesheets().add( resourcePath( "css/about.css" ) ); HBox textBox = new HBox( 0 ); textBox.setPrefWidth( 500 ); textBox.setAlignment( Pos.CENTER ); Text logText = new Text( "Log" ); logText.setId( "logfx-text-log" ); Text fxText = new Text( "FX" ); fxText.setId( "logfx-text-fx" ); textBox.getChildren().addAll( logText, fxText ); VBox smallText = new VBox( 10 ); smallText.setPrefWidth( 500 ); smallText.setAlignment( Pos.CENTER );
// Path: src/main/java-templates/com/athaydes/logfx/Constants.java // public class Constants { // public static final String LOGFX_VERSION = "${logfxVersion}"; // } // // Path: src/main/java/com/athaydes/logfx/ui/FxUtils.java // public static String resourcePath( String name ) { // return resourceUrl( name ).toExternalForm(); // } // Path: src/main/java/com/athaydes/logfx/ui/AboutLogFXView.java import com.athaydes.logfx.Constants; import javafx.geometry.Pos; import javafx.scene.Group; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.scene.text.Text; import javafx.stage.StageStyle; import static com.athaydes.logfx.ui.FxUtils.resourcePath; package com.athaydes.logfx.ui; /** * About LogFX View. */ public class AboutLogFXView { public static final int WIDTH = 500; public static final int HEIGHT = 350; VBox createNode() { VBox contents = new VBox( 25 ); contents.setPrefSize( WIDTH, HEIGHT ); contents.setAlignment( Pos.CENTER ); contents.getStylesheets().add( resourcePath( "css/about.css" ) ); HBox textBox = new HBox( 0 ); textBox.setPrefWidth( 500 ); textBox.setAlignment( Pos.CENTER ); Text logText = new Text( "Log" ); logText.setId( "logfx-text-log" ); Text fxText = new Text( "FX" ); fxText.setId( "logfx-text-fx" ); textBox.getChildren().addAll( logText, fxText ); VBox smallText = new VBox( 10 ); smallText.setPrefWidth( 500 ); smallText.setAlignment( Pos.CENTER );
Text version = new Text( "Version " + Constants.LOGFX_VERSION );
renatoathaydes/LogFX
src/main/java/module-info.java
// Path: src/main/java/com/athaydes/logfx/log/LogFXSlf4jProvider.java // public class LogFXSlf4jProvider extends SubstituteServiceProvider { // @Override // public ILoggerFactory getLoggerFactory() { // return new LogFXLogFactory(); // } // // @Override // public String getRequesteApiVersion() { // return "1.8"; // } // }
import com.athaydes.logfx.log.LogFXSlf4jProvider; import org.slf4j.spi.SLF4JServiceProvider;
module com.athaydes.logfx { requires jdk.unsupported; requires java.desktop; requires org.slf4j; requires javafx.controls; requires javafx.swing; exports com.athaydes.logfx; exports com.athaydes.logfx.log to org.slf4j; opens com.athaydes.logfx.ui to javafx.graphics;
// Path: src/main/java/com/athaydes/logfx/log/LogFXSlf4jProvider.java // public class LogFXSlf4jProvider extends SubstituteServiceProvider { // @Override // public ILoggerFactory getLoggerFactory() { // return new LogFXLogFactory(); // } // // @Override // public String getRequesteApiVersion() { // return "1.8"; // } // } // Path: src/main/java/module-info.java import com.athaydes.logfx.log.LogFXSlf4jProvider; import org.slf4j.spi.SLF4JServiceProvider; module com.athaydes.logfx { requires jdk.unsupported; requires java.desktop; requires org.slf4j; requires javafx.controls; requires javafx.swing; exports com.athaydes.logfx; exports com.athaydes.logfx.log to org.slf4j; opens com.athaydes.logfx.ui to javafx.graphics;
provides SLF4JServiceProvider with LogFXSlf4jProvider;
renatoathaydes/LogFX
src/main/java/com/athaydes/logfx/ui/LogLine.java
// Path: src/main/java/com/athaydes/logfx/binding/BindableValue.java // public class BindableValue<T> extends ObservableValueBase<T> { // // private T value; // // public BindableValue( T value ) { // this.value = value; // } // // public void setValue( T value ) { // this.value = value; // fireValueChangedEvent(); // } // // @Override // public T getValue() { // return value; // } // // } // // Path: src/main/java/com/athaydes/logfx/data/LogLineColors.java // public class LogLineColors { // // private final Paint background; // private final Paint fill; // // public LogLineColors( Paint background, Paint fill ) { // this.background = background; // this.fill = fill; // } // // public Paint getBackground() { // return background; // } // // public Paint getFill() { // return fill; // } // }
import com.athaydes.logfx.binding.BindableValue; import com.athaydes.logfx.data.LogLineColors; import javafx.animation.Animation; import javafx.animation.Interpolator; import javafx.animation.Transition; import javafx.application.Platform; import javafx.beans.binding.NumberBinding; import javafx.scene.Node; import javafx.scene.Parent; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.scene.layout.BackgroundFill; import javafx.scene.paint.Color; import javafx.scene.paint.Paint; import javafx.scene.text.Font; import javafx.util.Duration; import java.util.List;
package com.athaydes.logfx.ui; /** * Node holding a single log line in a {@link LogView}. */ class LogLine extends Parent implements SelectionHandler.SelectableNode { private static final int MAX_LINE_LENGTH = 5000; private final int lineIndex; private String fullText = ""; private final Label stdLine;
// Path: src/main/java/com/athaydes/logfx/binding/BindableValue.java // public class BindableValue<T> extends ObservableValueBase<T> { // // private T value; // // public BindableValue( T value ) { // this.value = value; // } // // public void setValue( T value ) { // this.value = value; // fireValueChangedEvent(); // } // // @Override // public T getValue() { // return value; // } // // } // // Path: src/main/java/com/athaydes/logfx/data/LogLineColors.java // public class LogLineColors { // // private final Paint background; // private final Paint fill; // // public LogLineColors( Paint background, Paint fill ) { // this.background = background; // this.fill = fill; // } // // public Paint getBackground() { // return background; // } // // public Paint getFill() { // return fill; // } // } // Path: src/main/java/com/athaydes/logfx/ui/LogLine.java import com.athaydes.logfx.binding.BindableValue; import com.athaydes.logfx.data.LogLineColors; import javafx.animation.Animation; import javafx.animation.Interpolator; import javafx.animation.Transition; import javafx.application.Platform; import javafx.beans.binding.NumberBinding; import javafx.scene.Node; import javafx.scene.Parent; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.scene.layout.BackgroundFill; import javafx.scene.paint.Color; import javafx.scene.paint.Paint; import javafx.scene.text.Font; import javafx.util.Duration; import java.util.List; package com.athaydes.logfx.ui; /** * Node holding a single log line in a {@link LogView}. */ class LogLine extends Parent implements SelectionHandler.SelectableNode { private static final int MAX_LINE_LENGTH = 5000; private final int lineIndex; private String fullText = ""; private final Label stdLine;
private final BindableValue<Font> fontValue;
renatoathaydes/LogFX
src/main/java/com/athaydes/logfx/ui/LogLine.java
// Path: src/main/java/com/athaydes/logfx/binding/BindableValue.java // public class BindableValue<T> extends ObservableValueBase<T> { // // private T value; // // public BindableValue( T value ) { // this.value = value; // } // // public void setValue( T value ) { // this.value = value; // fireValueChangedEvent(); // } // // @Override // public T getValue() { // return value; // } // // } // // Path: src/main/java/com/athaydes/logfx/data/LogLineColors.java // public class LogLineColors { // // private final Paint background; // private final Paint fill; // // public LogLineColors( Paint background, Paint fill ) { // this.background = background; // this.fill = fill; // } // // public Paint getBackground() { // return background; // } // // public Paint getFill() { // return fill; // } // }
import com.athaydes.logfx.binding.BindableValue; import com.athaydes.logfx.data.LogLineColors; import javafx.animation.Animation; import javafx.animation.Interpolator; import javafx.animation.Transition; import javafx.application.Platform; import javafx.beans.binding.NumberBinding; import javafx.scene.Node; import javafx.scene.Parent; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.scene.layout.BackgroundFill; import javafx.scene.paint.Color; import javafx.scene.paint.Paint; import javafx.scene.text.Font; import javafx.util.Duration; import java.util.List;
return this; } @Override public int getLineIndex() { return lineIndex; } @Override public String getText() { return fullText; } private void swapSelectableText() { var child = getChildren().remove( 0 ); if ( child == stdLine ) { var textField = new TextField( fullText ); textField.setFont( fontValue.getValue() ); textField.minWidthProperty().bind( stdLine.minWidthProperty() ); textField.focusedProperty().addListener( ( ignore ) -> { if ( !textField.isFocused() ) swapSelectableText(); } ); getChildren().add( textField ); Platform.runLater( textField::requestFocus ); } else { getChildren().add( stdLine ); } } @MustCallOnJavaFXThread
// Path: src/main/java/com/athaydes/logfx/binding/BindableValue.java // public class BindableValue<T> extends ObservableValueBase<T> { // // private T value; // // public BindableValue( T value ) { // this.value = value; // } // // public void setValue( T value ) { // this.value = value; // fireValueChangedEvent(); // } // // @Override // public T getValue() { // return value; // } // // } // // Path: src/main/java/com/athaydes/logfx/data/LogLineColors.java // public class LogLineColors { // // private final Paint background; // private final Paint fill; // // public LogLineColors( Paint background, Paint fill ) { // this.background = background; // this.fill = fill; // } // // public Paint getBackground() { // return background; // } // // public Paint getFill() { // return fill; // } // } // Path: src/main/java/com/athaydes/logfx/ui/LogLine.java import com.athaydes.logfx.binding.BindableValue; import com.athaydes.logfx.data.LogLineColors; import javafx.animation.Animation; import javafx.animation.Interpolator; import javafx.animation.Transition; import javafx.application.Platform; import javafx.beans.binding.NumberBinding; import javafx.scene.Node; import javafx.scene.Parent; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.scene.layout.BackgroundFill; import javafx.scene.paint.Color; import javafx.scene.paint.Paint; import javafx.scene.text.Font; import javafx.util.Duration; import java.util.List; return this; } @Override public int getLineIndex() { return lineIndex; } @Override public String getText() { return fullText; } private void swapSelectableText() { var child = getChildren().remove( 0 ); if ( child == stdLine ) { var textField = new TextField( fullText ); textField.setFont( fontValue.getValue() ); textField.minWidthProperty().bind( stdLine.minWidthProperty() ); textField.focusedProperty().addListener( ( ignore ) -> { if ( !textField.isFocused() ) swapSelectableText(); } ); getChildren().add( textField ); Platform.runLater( textField::requestFocus ); } else { getChildren().add( stdLine ); } } @MustCallOnJavaFXThread
void setText( String text, LogLineColors colors ) {
renatoathaydes/LogFX
src/main/java/com/athaydes/logfx/data/LogFile.java
// Path: src/main/java/com/athaydes/logfx/binding/BindableValue.java // public class BindableValue<T> extends ObservableValueBase<T> { // // private T value; // // public BindableValue( T value ) { // this.value = value; // } // // public void setValue( T value ) { // this.value = value; // fireValueChangedEvent(); // } // // @Override // public T getValue() { // return value; // } // // }
import com.athaydes.logfx.binding.BindableValue; import java.io.File; import java.util.Objects;
package com.athaydes.logfx.data; public final class LogFile { public final File file;
// Path: src/main/java/com/athaydes/logfx/binding/BindableValue.java // public class BindableValue<T> extends ObservableValueBase<T> { // // private T value; // // public BindableValue( T value ) { // this.value = value; // } // // public void setValue( T value ) { // this.value = value; // fireValueChangedEvent(); // } // // @Override // public T getValue() { // return value; // } // // } // Path: src/main/java/com/athaydes/logfx/data/LogFile.java import com.athaydes.logfx.binding.BindableValue; import java.io.File; import java.util.Objects; package com.athaydes.logfx.data; public final class LogFile { public final File file;
private final BindableValue<String> highlightGroup = new BindableValue<>( "" );
renatoathaydes/LogFX
src/main/java/com/athaydes/logfx/ui/SelectionHandler.java
// Path: src/main/java/com/athaydes/logfx/iterable/IterableUtils.java // public final class IterableUtils { // public static <N> Optional<N> getFirst( Iterable<N> iterable ) { // N item = null; // var iter = iterable.iterator(); // if ( iter.hasNext() ) { // item = iter.next(); // } // return Optional.ofNullable( item ); // } // // public static <N> Optional<N> getLast( Iterable<N> iterable ) { // N item = null; // for ( N n : iterable ) { // item = n; // } // return Optional.ofNullable( item ); // } // // public static <T> Collection<T> append( T item, Collection<T> collection ) { // var result = new ArrayList<T>( collection.size() + 1 ); // result.add( item ); // result.addAll( collection ); // return result; // } // // public static <T> T getAt( int index, List<T> collection, T defaultValue ) { // if ( index >= 0 && !collection.isEmpty() && index < collection.size() ) { // return collection.get( index ); // } // return defaultValue; // } // // public static double midPoint( List<Double> collection, int index ) { // if ( collection.isEmpty() ) return 0.5; // var before = getAt( Math.min( index, collection.size() ) - 1, collection, 0.0 ); // var after = getAt( index, collection, 1.0 ); // return before + ( ( after - before ) / 2.0 ); // } // }
import com.athaydes.logfx.iterable.IterableUtils; import javafx.collections.FXCollections; import javafx.collections.ListChangeListener; import javafx.collections.ObservableSet; import javafx.scene.Node; import javafx.scene.Parent; import javafx.scene.input.ClipboardContent; import javafx.scene.input.MouseButton; import javafx.scene.input.MouseEvent; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import java.util.stream.Collectors;
while ( target != root.getNode() && !( target instanceof SelectableNode ) ) { target = target.getParent(); } return target; } else { return root.getNode(); } } Optional<ClipboardContent> getSelection() { return selectionManager.getContent(); } ObservableSet<SelectableNode> getSelectedItems() { return selectionManager.getSelectedItems(); } void select( SelectableNode node ) { selectionManager.unselectAll(); selectionManager.select( node, true ); // only scroll to view every 10th line to avoid jumping around too much // var scrollToView = node.getLineIndex() % 10 == 0; // if (scrollToView) { root.scrollToView( node ); // } } CompletionStage<? extends SelectableNode> getNextItem() {
// Path: src/main/java/com/athaydes/logfx/iterable/IterableUtils.java // public final class IterableUtils { // public static <N> Optional<N> getFirst( Iterable<N> iterable ) { // N item = null; // var iter = iterable.iterator(); // if ( iter.hasNext() ) { // item = iter.next(); // } // return Optional.ofNullable( item ); // } // // public static <N> Optional<N> getLast( Iterable<N> iterable ) { // N item = null; // for ( N n : iterable ) { // item = n; // } // return Optional.ofNullable( item ); // } // // public static <T> Collection<T> append( T item, Collection<T> collection ) { // var result = new ArrayList<T>( collection.size() + 1 ); // result.add( item ); // result.addAll( collection ); // return result; // } // // public static <T> T getAt( int index, List<T> collection, T defaultValue ) { // if ( index >= 0 && !collection.isEmpty() && index < collection.size() ) { // return collection.get( index ); // } // return defaultValue; // } // // public static double midPoint( List<Double> collection, int index ) { // if ( collection.isEmpty() ) return 0.5; // var before = getAt( Math.min( index, collection.size() ) - 1, collection, 0.0 ); // var after = getAt( index, collection, 1.0 ); // return before + ( ( after - before ) / 2.0 ); // } // } // Path: src/main/java/com/athaydes/logfx/ui/SelectionHandler.java import com.athaydes.logfx.iterable.IterableUtils; import javafx.collections.FXCollections; import javafx.collections.ListChangeListener; import javafx.collections.ObservableSet; import javafx.scene.Node; import javafx.scene.Parent; import javafx.scene.input.ClipboardContent; import javafx.scene.input.MouseButton; import javafx.scene.input.MouseEvent; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import java.util.stream.Collectors; while ( target != root.getNode() && !( target instanceof SelectableNode ) ) { target = target.getParent(); } return target; } else { return root.getNode(); } } Optional<ClipboardContent> getSelection() { return selectionManager.getContent(); } ObservableSet<SelectableNode> getSelectedItems() { return selectionManager.getSelectedItems(); } void select( SelectableNode node ) { selectionManager.unselectAll(); selectionManager.select( node, true ); // only scroll to view every 10th line to avoid jumping around too much // var scrollToView = node.getLineIndex() % 10 == 0; // if (scrollToView) { root.scrollToView( node ); // } } CompletionStage<? extends SelectableNode> getNextItem() {
return IterableUtils.getLast( getSelectedItems() ).map( last -> {
renatoathaydes/LogFX
src/main/java/com/athaydes/logfx/config/HighlightGroups.java
// Path: src/main/java/com/athaydes/logfx/data/LogFile.java // public final class LogFile { // public final File file; // private final BindableValue<String> highlightGroup = new BindableValue<>( "" ); // // public LogFile( File file ) { // this.file = file; // } // // public LogFile( File file, String highlightGroupName ) { // this.file = file; // highlightGroup.setValue( highlightGroupName ); // } // // public BindableValue<String> highlightGroupProperty() { // return highlightGroup; // } // // public String getHighlightGroup() { // return highlightGroup.getValue(); // } // // @Override // public boolean equals( Object other ) { // if ( this == other ) return true; // if ( !( other instanceof LogFile ) ) return false; // LogFile logFile = ( LogFile ) other; // return Objects.equals( file, logFile.file ); // } // // @Override // public int hashCode() { // return Objects.hash( file ); // } // // } // // Path: src/main/java/com/athaydes/logfx/text/HighlightExpression.java // public final class HighlightExpression { // // private final Pattern expression; // private final Paint bkgColor; // private final Paint fillColor; // private final boolean isFiltered; // // public HighlightExpression( String expression, Paint bkgColor, Paint fillColor, boolean isFiltered ) { // this( Pattern.compile( expression ), bkgColor, fillColor, isFiltered ); // } // // public HighlightExpression( Pattern expression, Paint bkgColor, Paint fillColor, boolean isFiltered ) { // this.expression = expression; // this.bkgColor = bkgColor; // this.fillColor = fillColor; // this.isFiltered = isFiltered; // } // // public Paint getBkgColor() { // return bkgColor; // } // // public Paint getFillColor() { // return fillColor; // } // // public Pattern getPattern() { // return expression; // } // // public boolean isFiltered() { // return isFiltered; // } // // public LogLineColors getLogLineColors() { // return new LogLineColors( bkgColor, fillColor ); // } // // public boolean matches( String text ) { // if ( text == null ) { // text = ""; // } // // // the find method does not anchor the String by default, unlike matches() // return expression.matcher( text ).find(); // } // // public HighlightExpression withFilter( boolean enable ) { // return new HighlightExpression( this.expression, this.bkgColor, this.fillColor, enable ); // } // // @Override // public String toString() { // return "{" + // "expression=" + expression + // ", bkgColor=" + bkgColor + // ", fillColor=" + fillColor + // ", isFiltered=" + isFiltered + // '}'; // } // // @Override // public boolean equals( Object o ) { // if ( this == o ) return true; // if ( o == null || getClass() != o.getClass() ) return false; // HighlightExpression that = ( HighlightExpression ) o; // return isFiltered == that.isFiltered && // expression.toString().equals( that.expression.toString() ) && // bkgColor.equals( that.bkgColor ) && // fillColor.equals( that.fillColor ); // } // // @Override // public int hashCode() { // return Objects.hash( expression.toString(), bkgColor, fillColor, isFiltered ); // } // }
import com.athaydes.logfx.data.LogFile; import com.athaydes.logfx.text.HighlightExpression; import javafx.beans.InvalidationListener; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.collections.ObservableMap; import javafx.collections.ObservableSet; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set;
package com.athaydes.logfx.config; public final class HighlightGroups { private final ObservableSet<LogFile> observableFiles;
// Path: src/main/java/com/athaydes/logfx/data/LogFile.java // public final class LogFile { // public final File file; // private final BindableValue<String> highlightGroup = new BindableValue<>( "" ); // // public LogFile( File file ) { // this.file = file; // } // // public LogFile( File file, String highlightGroupName ) { // this.file = file; // highlightGroup.setValue( highlightGroupName ); // } // // public BindableValue<String> highlightGroupProperty() { // return highlightGroup; // } // // public String getHighlightGroup() { // return highlightGroup.getValue(); // } // // @Override // public boolean equals( Object other ) { // if ( this == other ) return true; // if ( !( other instanceof LogFile ) ) return false; // LogFile logFile = ( LogFile ) other; // return Objects.equals( file, logFile.file ); // } // // @Override // public int hashCode() { // return Objects.hash( file ); // } // // } // // Path: src/main/java/com/athaydes/logfx/text/HighlightExpression.java // public final class HighlightExpression { // // private final Pattern expression; // private final Paint bkgColor; // private final Paint fillColor; // private final boolean isFiltered; // // public HighlightExpression( String expression, Paint bkgColor, Paint fillColor, boolean isFiltered ) { // this( Pattern.compile( expression ), bkgColor, fillColor, isFiltered ); // } // // public HighlightExpression( Pattern expression, Paint bkgColor, Paint fillColor, boolean isFiltered ) { // this.expression = expression; // this.bkgColor = bkgColor; // this.fillColor = fillColor; // this.isFiltered = isFiltered; // } // // public Paint getBkgColor() { // return bkgColor; // } // // public Paint getFillColor() { // return fillColor; // } // // public Pattern getPattern() { // return expression; // } // // public boolean isFiltered() { // return isFiltered; // } // // public LogLineColors getLogLineColors() { // return new LogLineColors( bkgColor, fillColor ); // } // // public boolean matches( String text ) { // if ( text == null ) { // text = ""; // } // // // the find method does not anchor the String by default, unlike matches() // return expression.matcher( text ).find(); // } // // public HighlightExpression withFilter( boolean enable ) { // return new HighlightExpression( this.expression, this.bkgColor, this.fillColor, enable ); // } // // @Override // public String toString() { // return "{" + // "expression=" + expression + // ", bkgColor=" + bkgColor + // ", fillColor=" + fillColor + // ", isFiltered=" + isFiltered + // '}'; // } // // @Override // public boolean equals( Object o ) { // if ( this == o ) return true; // if ( o == null || getClass() != o.getClass() ) return false; // HighlightExpression that = ( HighlightExpression ) o; // return isFiltered == that.isFiltered && // expression.toString().equals( that.expression.toString() ) && // bkgColor.equals( that.bkgColor ) && // fillColor.equals( that.fillColor ); // } // // @Override // public int hashCode() { // return Objects.hash( expression.toString(), bkgColor, fillColor, isFiltered ); // } // } // Path: src/main/java/com/athaydes/logfx/config/HighlightGroups.java import com.athaydes.logfx.data.LogFile; import com.athaydes.logfx.text.HighlightExpression; import javafx.beans.InvalidationListener; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.collections.ObservableMap; import javafx.collections.ObservableSet; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; package com.athaydes.logfx.config; public final class HighlightGroups { private final ObservableSet<LogFile> observableFiles;
private final ObservableMap<String, ObservableList<HighlightExpression>> configByGroupName;
renatoathaydes/LogFX
src/main/java/com/athaydes/logfx/ui/StartUpView.java
// Path: src/main/java/com/athaydes/logfx/data/LogFile.java // public final class LogFile { // public final File file; // private final BindableValue<String> highlightGroup = new BindableValue<>( "" ); // // public LogFile( File file ) { // this.file = file; // } // // public LogFile( File file, String highlightGroupName ) { // this.file = file; // highlightGroup.setValue( highlightGroupName ); // } // // public BindableValue<String> highlightGroupProperty() { // return highlightGroup; // } // // public String getHighlightGroup() { // return highlightGroup.getValue(); // } // // @Override // public boolean equals( Object other ) { // if ( this == other ) return true; // if ( !( other instanceof LogFile ) ) return false; // LogFile logFile = ( LogFile ) other; // return Objects.equals( file, logFile.file ); // } // // @Override // public int hashCode() { // return Objects.hash( file ); // } // // }
import com.athaydes.logfx.data.LogFile; import javafx.scene.control.Hyperlink; import javafx.scene.layout.StackPane; import javafx.scene.layout.VBox; import javafx.scene.text.Text; import javafx.stage.Stage; import java.io.File; import java.util.Collection; import java.util.function.Consumer;
package com.athaydes.logfx.ui; /** * The startup view. * <p> * Shown when no log files are open. */ public class StartUpView extends StackPane { public StartUpView( Stage stage,
// Path: src/main/java/com/athaydes/logfx/data/LogFile.java // public final class LogFile { // public final File file; // private final BindableValue<String> highlightGroup = new BindableValue<>( "" ); // // public LogFile( File file ) { // this.file = file; // } // // public LogFile( File file, String highlightGroupName ) { // this.file = file; // highlightGroup.setValue( highlightGroupName ); // } // // public BindableValue<String> highlightGroupProperty() { // return highlightGroup; // } // // public String getHighlightGroup() { // return highlightGroup.getValue(); // } // // @Override // public boolean equals( Object other ) { // if ( this == other ) return true; // if ( !( other instanceof LogFile ) ) return false; // LogFile logFile = ( LogFile ) other; // return Objects.equals( file, logFile.file ); // } // // @Override // public int hashCode() { // return Objects.hash( file ); // } // // } // Path: src/main/java/com/athaydes/logfx/ui/StartUpView.java import com.athaydes.logfx.data.LogFile; import javafx.scene.control.Hyperlink; import javafx.scene.layout.StackPane; import javafx.scene.layout.VBox; import javafx.scene.text.Text; import javafx.stage.Stage; import java.io.File; import java.util.Collection; import java.util.function.Consumer; package com.athaydes.logfx.ui; /** * The startup view. * <p> * Shown when no log files are open. */ public class StartUpView extends StackPane { public StartUpView( Stage stage,
Collection<LogFile> logFiles,
renatoathaydes/LogFX
src/main/java/com/athaydes/logfx/log/LogConfigFile.java
// Path: src/main/java/com/athaydes/logfx/config/Properties.java // public class Properties { // // public static final Path LOGFX_DIR; // public static final Path DEFAULT_LOGFX_CONFIG; // public static final long UPDATE_CHECK_PERIOD_SECONDS; // public static final String DEFAULT_PROJECT_NAME = "Default"; // // private static volatile LogLevel logLevel = null; // private static volatile LogTarget logTarget = null; // private static final boolean refreshStylesheet; // private static final String customStylesheet; // // static { // String customHome = System.getProperty( "logfx.home" ); // // File homeDir; // if ( customHome == null ) { // homeDir = new File( System.getProperty( "user.home" ), ".logfx" ); // } else { // homeDir = new File( customHome ); // } // // if ( homeDir.isFile() ) { // throw new IllegalStateException( "LogFX home directory is set to a file: " + // homeDir + ", use the 'logfx.home' system property to change LogFX's home." ); // } // // if ( !homeDir.exists() ) { // boolean ok = homeDir.mkdirs(); // if ( !ok ) { // throw new IllegalStateException( "Unable to create LogFX home directory at " + // homeDir + ", use the 'logfx.home' system property to change LogFX's home." ); // } // } // // LOGFX_DIR = homeDir.toPath(); // DEFAULT_LOGFX_CONFIG = LOGFX_DIR.resolve( "config" ); // // String logLevelValue = System.getProperty( "logfx.log.level" ); // // if ( logLevelValue != null && !logLevelValue.trim().isEmpty() ) { // try { // logLevel = LogLevel.valueOf( logLevelValue.trim().toUpperCase() ); // } catch ( IllegalArgumentException e ) { // System.err.println( "Invalid value for 'logfx.log.level' system property: " + logLevelValue ); // System.err.println( "Valid values for 'logfx.log.level' are: TRACE, DEBUG, INFO (default), WARN, " + // "ERROR" ); // } // } // // String logTargetValue = System.getProperty( "logfx.log.target" ); // // if ( logTargetValue != null && !logTargetValue.trim().isEmpty() ) { // switch ( logTargetValue.trim().toUpperCase() ) { // case "SYSOUT": // logTarget = new LogTarget.PrintStreamLogTarget( System.out ); // break; // case "SYSERR": // logTarget = new LogTarget.PrintStreamLogTarget( System.err ); // break; // case "FILE": // logTarget = new LogTarget.FileLogTarget(); // break; // default: // System.err.println( "Invalid value for 'logfx.log.target' system property: " + logTargetValue ); // System.err.println( "Valid values for 'logfx.log.target' are: SYSOUT, SYSERR, FILE (default)" ); // } // } // // customStylesheet = System.getProperty( "logfx.stylesheet.file" ); // refreshStylesheet = System.getProperty( "logfx.stylesheet.norefresh" ) == null; // // String autoUpdatePeriod = System.getProperty( "logfx.auto_update.check_period" ); // Long autoUpdatePeriodSecs = null; // if ( autoUpdatePeriod != null ) { // try { // autoUpdatePeriodSecs = Long.parseLong( autoUpdatePeriod ); // } catch ( NumberFormatException e ) { // System.err.printf( "Invalid value for system property logfx.auto_update.check_period: %s (%s)\n", // autoUpdatePeriod, e ); // } // } // UPDATE_CHECK_PERIOD_SECONDS = autoUpdatePeriodSecs == null ? 24 * 60 * 60 : autoUpdatePeriodSecs; // } // // public static Optional<LogLevel> getLogLevel() { // return Optional.ofNullable( logLevel ); // } // // public static Optional<LogTarget> getLogTarget() { // return Optional.ofNullable( logTarget ); // } // // public static Optional<File> getCustomStylesheet() { // return Optional.ofNullable( customStylesheet ).map( File::new ); // } // // public static boolean isRefreshStylesheet() { // return refreshStylesheet; // } // // public static Collection<String> listProjects() { // var projectsPath = LOGFX_DIR.resolve( Paths.get( "projects" ) ); // Collection<String> projects = List.of(); // if ( projectsPath.toFile().isDirectory() ) { // var files = projectsPath.toFile().listFiles(); // if ( files != null && files.length != 0 ) { // projects = Stream.of( files ) // .map( File::getName ) // .sorted() // .collect( Collectors.toList() ); // } // } // // return append( DEFAULT_PROJECT_NAME, projects ); // } // // public static Optional<Path> getProjectFile( String projectName ) { // if ( DEFAULT_PROJECT_NAME.equals( projectName ) ) { // return Optional.of( LOGFX_DIR.resolve( "config" ) ); // } // var projectPath = LOGFX_DIR.resolve( Paths.get( "projects", projectName ) ); // File file = projectPath.toFile(); // if ( !file.getParentFile().isDirectory() ) { // var ok = file.getParentFile().mkdirs(); // if ( !ok ) { // Dialog.showMessage( "Unable to create projects directory at: " + file.getParentFile(), // Dialog.MessageLevel.ERROR ); // return Optional.empty(); // } // } // if ( !file.isFile() ) { // boolean ok; // try { // ok = file.createNewFile(); // } catch ( IOException e ) { // Dialog.showMessage( "Cannot create project with given name: " + e, Dialog.MessageLevel.ERROR ); // return Optional.empty(); // } // if ( !ok ) { // Dialog.showMessage( "Unable to create project with given name", Dialog.MessageLevel.ERROR ); // return Optional.empty(); // } // } // return Optional.of( projectPath ); // } // }
import com.athaydes.logfx.config.Properties; import java.nio.file.Path;
package com.athaydes.logfx.log; public enum LogConfigFile { INSTANCE;
// Path: src/main/java/com/athaydes/logfx/config/Properties.java // public class Properties { // // public static final Path LOGFX_DIR; // public static final Path DEFAULT_LOGFX_CONFIG; // public static final long UPDATE_CHECK_PERIOD_SECONDS; // public static final String DEFAULT_PROJECT_NAME = "Default"; // // private static volatile LogLevel logLevel = null; // private static volatile LogTarget logTarget = null; // private static final boolean refreshStylesheet; // private static final String customStylesheet; // // static { // String customHome = System.getProperty( "logfx.home" ); // // File homeDir; // if ( customHome == null ) { // homeDir = new File( System.getProperty( "user.home" ), ".logfx" ); // } else { // homeDir = new File( customHome ); // } // // if ( homeDir.isFile() ) { // throw new IllegalStateException( "LogFX home directory is set to a file: " + // homeDir + ", use the 'logfx.home' system property to change LogFX's home." ); // } // // if ( !homeDir.exists() ) { // boolean ok = homeDir.mkdirs(); // if ( !ok ) { // throw new IllegalStateException( "Unable to create LogFX home directory at " + // homeDir + ", use the 'logfx.home' system property to change LogFX's home." ); // } // } // // LOGFX_DIR = homeDir.toPath(); // DEFAULT_LOGFX_CONFIG = LOGFX_DIR.resolve( "config" ); // // String logLevelValue = System.getProperty( "logfx.log.level" ); // // if ( logLevelValue != null && !logLevelValue.trim().isEmpty() ) { // try { // logLevel = LogLevel.valueOf( logLevelValue.trim().toUpperCase() ); // } catch ( IllegalArgumentException e ) { // System.err.println( "Invalid value for 'logfx.log.level' system property: " + logLevelValue ); // System.err.println( "Valid values for 'logfx.log.level' are: TRACE, DEBUG, INFO (default), WARN, " + // "ERROR" ); // } // } // // String logTargetValue = System.getProperty( "logfx.log.target" ); // // if ( logTargetValue != null && !logTargetValue.trim().isEmpty() ) { // switch ( logTargetValue.trim().toUpperCase() ) { // case "SYSOUT": // logTarget = new LogTarget.PrintStreamLogTarget( System.out ); // break; // case "SYSERR": // logTarget = new LogTarget.PrintStreamLogTarget( System.err ); // break; // case "FILE": // logTarget = new LogTarget.FileLogTarget(); // break; // default: // System.err.println( "Invalid value for 'logfx.log.target' system property: " + logTargetValue ); // System.err.println( "Valid values for 'logfx.log.target' are: SYSOUT, SYSERR, FILE (default)" ); // } // } // // customStylesheet = System.getProperty( "logfx.stylesheet.file" ); // refreshStylesheet = System.getProperty( "logfx.stylesheet.norefresh" ) == null; // // String autoUpdatePeriod = System.getProperty( "logfx.auto_update.check_period" ); // Long autoUpdatePeriodSecs = null; // if ( autoUpdatePeriod != null ) { // try { // autoUpdatePeriodSecs = Long.parseLong( autoUpdatePeriod ); // } catch ( NumberFormatException e ) { // System.err.printf( "Invalid value for system property logfx.auto_update.check_period: %s (%s)\n", // autoUpdatePeriod, e ); // } // } // UPDATE_CHECK_PERIOD_SECONDS = autoUpdatePeriodSecs == null ? 24 * 60 * 60 : autoUpdatePeriodSecs; // } // // public static Optional<LogLevel> getLogLevel() { // return Optional.ofNullable( logLevel ); // } // // public static Optional<LogTarget> getLogTarget() { // return Optional.ofNullable( logTarget ); // } // // public static Optional<File> getCustomStylesheet() { // return Optional.ofNullable( customStylesheet ).map( File::new ); // } // // public static boolean isRefreshStylesheet() { // return refreshStylesheet; // } // // public static Collection<String> listProjects() { // var projectsPath = LOGFX_DIR.resolve( Paths.get( "projects" ) ); // Collection<String> projects = List.of(); // if ( projectsPath.toFile().isDirectory() ) { // var files = projectsPath.toFile().listFiles(); // if ( files != null && files.length != 0 ) { // projects = Stream.of( files ) // .map( File::getName ) // .sorted() // .collect( Collectors.toList() ); // } // } // // return append( DEFAULT_PROJECT_NAME, projects ); // } // // public static Optional<Path> getProjectFile( String projectName ) { // if ( DEFAULT_PROJECT_NAME.equals( projectName ) ) { // return Optional.of( LOGFX_DIR.resolve( "config" ) ); // } // var projectPath = LOGFX_DIR.resolve( Paths.get( "projects", projectName ) ); // File file = projectPath.toFile(); // if ( !file.getParentFile().isDirectory() ) { // var ok = file.getParentFile().mkdirs(); // if ( !ok ) { // Dialog.showMessage( "Unable to create projects directory at: " + file.getParentFile(), // Dialog.MessageLevel.ERROR ); // return Optional.empty(); // } // } // if ( !file.isFile() ) { // boolean ok; // try { // ok = file.createNewFile(); // } catch ( IOException e ) { // Dialog.showMessage( "Cannot create project with given name: " + e, Dialog.MessageLevel.ERROR ); // return Optional.empty(); // } // if ( !ok ) { // Dialog.showMessage( "Unable to create project with given name", Dialog.MessageLevel.ERROR ); // return Optional.empty(); // } // } // return Optional.of( projectPath ); // } // } // Path: src/main/java/com/athaydes/logfx/log/LogConfigFile.java import com.athaydes.logfx.config.Properties; import java.nio.file.Path; package com.athaydes.logfx.log; public enum LogConfigFile { INSTANCE;
public final Path logFilePath = Properties.LOGFX_DIR.resolve( "logfx.log" );
renatoathaydes/LogFX
src/main/java/com/athaydes/logfx/SetupTrayIcon.java
// Path: src/main/java/com/athaydes/logfx/ui/FxUtils.java // public static URL resourceUrl( String name ) { // return LogFX.class.getResource( name ); // }
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.swing.ImageIcon; import java.awt.Taskbar; import static com.athaydes.logfx.ui.FxUtils.resourceUrl;
package com.athaydes.logfx; /** * A class that sets up the tray icon, if possible on the current OS. */ class SetupTrayIcon { private static final Logger log = LoggerFactory.getLogger( SetupTrayIcon.class ); /** * Set the Mac tray icon. Only works if this is called on a Mac OS system. */ static void run() { if ( !Taskbar.isTaskbarSupported() ) { log.debug( "Skipping Taskbar setup as it is not supported in this OS" ); return; } log.debug( "Setting up Taskbar icon" );
// Path: src/main/java/com/athaydes/logfx/ui/FxUtils.java // public static URL resourceUrl( String name ) { // return LogFX.class.getResource( name ); // } // Path: src/main/java/com/athaydes/logfx/SetupTrayIcon.java import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.swing.ImageIcon; import java.awt.Taskbar; import static com.athaydes.logfx.ui.FxUtils.resourceUrl; package com.athaydes.logfx; /** * A class that sets up the tray icon, if possible on the current OS. */ class SetupTrayIcon { private static final Logger log = LoggerFactory.getLogger( SetupTrayIcon.class ); /** * Set the Mac tray icon. Only works if this is called on a Mac OS system. */ static void run() { if ( !Taskbar.isTaskbarSupported() ) { log.debug( "Skipping Taskbar setup as it is not supported in this OS" ); return; } log.debug( "Setting up Taskbar icon" );
java.awt.Image image = new ImageIcon( resourceUrl( "images/favicon-large.png" ) ).getImage();
renatoathaydes/LogFX
src/main/java/com/athaydes/logfx/ui/HighlightOptions.java
// Path: src/main/java/com/athaydes/logfx/data/LogLineColors.java // public class LogLineColors { // // private final Paint background; // private final Paint fill; // // public LogLineColors( Paint background, Paint fill ) { // this.background = background; // this.fill = fill; // } // // public Paint getBackground() { // return background; // } // // public Paint getFill() { // return fill; // } // } // // Path: src/main/java/com/athaydes/logfx/text/HighlightExpression.java // public final class HighlightExpression { // // private final Pattern expression; // private final Paint bkgColor; // private final Paint fillColor; // private final boolean isFiltered; // // public HighlightExpression( String expression, Paint bkgColor, Paint fillColor, boolean isFiltered ) { // this( Pattern.compile( expression ), bkgColor, fillColor, isFiltered ); // } // // public HighlightExpression( Pattern expression, Paint bkgColor, Paint fillColor, boolean isFiltered ) { // this.expression = expression; // this.bkgColor = bkgColor; // this.fillColor = fillColor; // this.isFiltered = isFiltered; // } // // public Paint getBkgColor() { // return bkgColor; // } // // public Paint getFillColor() { // return fillColor; // } // // public Pattern getPattern() { // return expression; // } // // public boolean isFiltered() { // return isFiltered; // } // // public LogLineColors getLogLineColors() { // return new LogLineColors( bkgColor, fillColor ); // } // // public boolean matches( String text ) { // if ( text == null ) { // text = ""; // } // // // the find method does not anchor the String by default, unlike matches() // return expression.matcher( text ).find(); // } // // public HighlightExpression withFilter( boolean enable ) { // return new HighlightExpression( this.expression, this.bkgColor, this.fillColor, enable ); // } // // @Override // public String toString() { // return "{" + // "expression=" + expression + // ", bkgColor=" + bkgColor + // ", fillColor=" + fillColor + // ", isFiltered=" + isFiltered + // '}'; // } // // @Override // public boolean equals( Object o ) { // if ( this == o ) return true; // if ( o == null || getClass() != o.getClass() ) return false; // HighlightExpression that = ( HighlightExpression ) o; // return isFiltered == that.isFiltered && // expression.toString().equals( that.expression.toString() ) && // bkgColor.equals( that.bkgColor ) && // fillColor.equals( that.fillColor ); // } // // @Override // public int hashCode() { // return Objects.hash( expression.toString(), bkgColor, fillColor, isFiltered ); // } // } // // Path: src/main/java/com/athaydes/logfx/ui/AwesomeIcons.java // public static final String HELP = "\ue718"; // // Path: src/main/java/com/athaydes/logfx/ui/AwesomeIcons.java // public static final String TRASH = "\ue605"; // // Path: src/main/java/com/athaydes/logfx/ui/FxUtils.java // public static String resourcePath( String name ) { // return resourceUrl( name ).toExternalForm(); // }
import com.athaydes.logfx.data.LogLineColors; import com.athaydes.logfx.text.HighlightExpression; import javafx.application.Platform; import javafx.beans.InvalidationListener; import javafx.beans.property.BooleanProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Cursor; import javafx.scene.Node; import javafx.scene.control.Button; import javafx.scene.control.CheckBox; import javafx.scene.control.Label; import javafx.scene.control.ScrollPane; import javafx.scene.control.TextField; import javafx.scene.control.Tooltip; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; import javafx.scene.paint.Paint; import javafx.scene.text.Text; import javafx.scene.text.TextFlow; import javafx.stage.StageStyle; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; import java.util.function.BiFunction; import java.util.regex.PatternSyntaxException; import java.util.stream.Collectors; import static com.athaydes.logfx.ui.Arrow.Direction.DOWN; import static com.athaydes.logfx.ui.Arrow.Direction.UP; import static com.athaydes.logfx.ui.AwesomeIcons.HELP; import static com.athaydes.logfx.ui.AwesomeIcons.TRASH; import static com.athaydes.logfx.ui.FxUtils.resourcePath;
package com.athaydes.logfx.ui; /** * The highlight options screen. */ public class HighlightOptions extends VBox { private static final Logger log = LoggerFactory.getLogger( HighlightOptions.class );
// Path: src/main/java/com/athaydes/logfx/data/LogLineColors.java // public class LogLineColors { // // private final Paint background; // private final Paint fill; // // public LogLineColors( Paint background, Paint fill ) { // this.background = background; // this.fill = fill; // } // // public Paint getBackground() { // return background; // } // // public Paint getFill() { // return fill; // } // } // // Path: src/main/java/com/athaydes/logfx/text/HighlightExpression.java // public final class HighlightExpression { // // private final Pattern expression; // private final Paint bkgColor; // private final Paint fillColor; // private final boolean isFiltered; // // public HighlightExpression( String expression, Paint bkgColor, Paint fillColor, boolean isFiltered ) { // this( Pattern.compile( expression ), bkgColor, fillColor, isFiltered ); // } // // public HighlightExpression( Pattern expression, Paint bkgColor, Paint fillColor, boolean isFiltered ) { // this.expression = expression; // this.bkgColor = bkgColor; // this.fillColor = fillColor; // this.isFiltered = isFiltered; // } // // public Paint getBkgColor() { // return bkgColor; // } // // public Paint getFillColor() { // return fillColor; // } // // public Pattern getPattern() { // return expression; // } // // public boolean isFiltered() { // return isFiltered; // } // // public LogLineColors getLogLineColors() { // return new LogLineColors( bkgColor, fillColor ); // } // // public boolean matches( String text ) { // if ( text == null ) { // text = ""; // } // // // the find method does not anchor the String by default, unlike matches() // return expression.matcher( text ).find(); // } // // public HighlightExpression withFilter( boolean enable ) { // return new HighlightExpression( this.expression, this.bkgColor, this.fillColor, enable ); // } // // @Override // public String toString() { // return "{" + // "expression=" + expression + // ", bkgColor=" + bkgColor + // ", fillColor=" + fillColor + // ", isFiltered=" + isFiltered + // '}'; // } // // @Override // public boolean equals( Object o ) { // if ( this == o ) return true; // if ( o == null || getClass() != o.getClass() ) return false; // HighlightExpression that = ( HighlightExpression ) o; // return isFiltered == that.isFiltered && // expression.toString().equals( that.expression.toString() ) && // bkgColor.equals( that.bkgColor ) && // fillColor.equals( that.fillColor ); // } // // @Override // public int hashCode() { // return Objects.hash( expression.toString(), bkgColor, fillColor, isFiltered ); // } // } // // Path: src/main/java/com/athaydes/logfx/ui/AwesomeIcons.java // public static final String HELP = "\ue718"; // // Path: src/main/java/com/athaydes/logfx/ui/AwesomeIcons.java // public static final String TRASH = "\ue605"; // // Path: src/main/java/com/athaydes/logfx/ui/FxUtils.java // public static String resourcePath( String name ) { // return resourceUrl( name ).toExternalForm(); // } // Path: src/main/java/com/athaydes/logfx/ui/HighlightOptions.java import com.athaydes.logfx.data.LogLineColors; import com.athaydes.logfx.text.HighlightExpression; import javafx.application.Platform; import javafx.beans.InvalidationListener; import javafx.beans.property.BooleanProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Cursor; import javafx.scene.Node; import javafx.scene.control.Button; import javafx.scene.control.CheckBox; import javafx.scene.control.Label; import javafx.scene.control.ScrollPane; import javafx.scene.control.TextField; import javafx.scene.control.Tooltip; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; import javafx.scene.paint.Paint; import javafx.scene.text.Text; import javafx.scene.text.TextFlow; import javafx.stage.StageStyle; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; import java.util.function.BiFunction; import java.util.regex.PatternSyntaxException; import java.util.stream.Collectors; import static com.athaydes.logfx.ui.Arrow.Direction.DOWN; import static com.athaydes.logfx.ui.Arrow.Direction.UP; import static com.athaydes.logfx.ui.AwesomeIcons.HELP; import static com.athaydes.logfx.ui.AwesomeIcons.TRASH; import static com.athaydes.logfx.ui.FxUtils.resourcePath; package com.athaydes.logfx.ui; /** * The highlight options screen. */ public class HighlightOptions extends VBox { private static final Logger log = LoggerFactory.getLogger( HighlightOptions.class );
private final ObservableList<HighlightExpression> observableExpressions;
renatoathaydes/LogFX
src/main/java/com/athaydes/logfx/ui/HighlightOptions.java
// Path: src/main/java/com/athaydes/logfx/data/LogLineColors.java // public class LogLineColors { // // private final Paint background; // private final Paint fill; // // public LogLineColors( Paint background, Paint fill ) { // this.background = background; // this.fill = fill; // } // // public Paint getBackground() { // return background; // } // // public Paint getFill() { // return fill; // } // } // // Path: src/main/java/com/athaydes/logfx/text/HighlightExpression.java // public final class HighlightExpression { // // private final Pattern expression; // private final Paint bkgColor; // private final Paint fillColor; // private final boolean isFiltered; // // public HighlightExpression( String expression, Paint bkgColor, Paint fillColor, boolean isFiltered ) { // this( Pattern.compile( expression ), bkgColor, fillColor, isFiltered ); // } // // public HighlightExpression( Pattern expression, Paint bkgColor, Paint fillColor, boolean isFiltered ) { // this.expression = expression; // this.bkgColor = bkgColor; // this.fillColor = fillColor; // this.isFiltered = isFiltered; // } // // public Paint getBkgColor() { // return bkgColor; // } // // public Paint getFillColor() { // return fillColor; // } // // public Pattern getPattern() { // return expression; // } // // public boolean isFiltered() { // return isFiltered; // } // // public LogLineColors getLogLineColors() { // return new LogLineColors( bkgColor, fillColor ); // } // // public boolean matches( String text ) { // if ( text == null ) { // text = ""; // } // // // the find method does not anchor the String by default, unlike matches() // return expression.matcher( text ).find(); // } // // public HighlightExpression withFilter( boolean enable ) { // return new HighlightExpression( this.expression, this.bkgColor, this.fillColor, enable ); // } // // @Override // public String toString() { // return "{" + // "expression=" + expression + // ", bkgColor=" + bkgColor + // ", fillColor=" + fillColor + // ", isFiltered=" + isFiltered + // '}'; // } // // @Override // public boolean equals( Object o ) { // if ( this == o ) return true; // if ( o == null || getClass() != o.getClass() ) return false; // HighlightExpression that = ( HighlightExpression ) o; // return isFiltered == that.isFiltered && // expression.toString().equals( that.expression.toString() ) && // bkgColor.equals( that.bkgColor ) && // fillColor.equals( that.fillColor ); // } // // @Override // public int hashCode() { // return Objects.hash( expression.toString(), bkgColor, fillColor, isFiltered ); // } // } // // Path: src/main/java/com/athaydes/logfx/ui/AwesomeIcons.java // public static final String HELP = "\ue718"; // // Path: src/main/java/com/athaydes/logfx/ui/AwesomeIcons.java // public static final String TRASH = "\ue605"; // // Path: src/main/java/com/athaydes/logfx/ui/FxUtils.java // public static String resourcePath( String name ) { // return resourceUrl( name ).toExternalForm(); // }
import com.athaydes.logfx.data.LogLineColors; import com.athaydes.logfx.text.HighlightExpression; import javafx.application.Platform; import javafx.beans.InvalidationListener; import javafx.beans.property.BooleanProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Cursor; import javafx.scene.Node; import javafx.scene.control.Button; import javafx.scene.control.CheckBox; import javafx.scene.control.Label; import javafx.scene.control.ScrollPane; import javafx.scene.control.TextField; import javafx.scene.control.Tooltip; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; import javafx.scene.paint.Paint; import javafx.scene.text.Text; import javafx.scene.text.TextFlow; import javafx.stage.StageStyle; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; import java.util.function.BiFunction; import java.util.regex.PatternSyntaxException; import java.util.stream.Collectors; import static com.athaydes.logfx.ui.Arrow.Direction.DOWN; import static com.athaydes.logfx.ui.Arrow.Direction.UP; import static com.athaydes.logfx.ui.AwesomeIcons.HELP; import static com.athaydes.logfx.ui.AwesomeIcons.TRASH; import static com.athaydes.logfx.ui.FxUtils.resourcePath;
package com.athaydes.logfx.ui; /** * The highlight options screen. */ public class HighlightOptions extends VBox { private static final Logger log = LoggerFactory.getLogger( HighlightOptions.class ); private final ObservableList<HighlightExpression> observableExpressions; private final BooleanProperty isFilterEnabled; private String groupName; private final VBox expressionsBox; private final StandardLogColorsRow standardLogColorsRow; public HighlightOptions( String groupName,
// Path: src/main/java/com/athaydes/logfx/data/LogLineColors.java // public class LogLineColors { // // private final Paint background; // private final Paint fill; // // public LogLineColors( Paint background, Paint fill ) { // this.background = background; // this.fill = fill; // } // // public Paint getBackground() { // return background; // } // // public Paint getFill() { // return fill; // } // } // // Path: src/main/java/com/athaydes/logfx/text/HighlightExpression.java // public final class HighlightExpression { // // private final Pattern expression; // private final Paint bkgColor; // private final Paint fillColor; // private final boolean isFiltered; // // public HighlightExpression( String expression, Paint bkgColor, Paint fillColor, boolean isFiltered ) { // this( Pattern.compile( expression ), bkgColor, fillColor, isFiltered ); // } // // public HighlightExpression( Pattern expression, Paint bkgColor, Paint fillColor, boolean isFiltered ) { // this.expression = expression; // this.bkgColor = bkgColor; // this.fillColor = fillColor; // this.isFiltered = isFiltered; // } // // public Paint getBkgColor() { // return bkgColor; // } // // public Paint getFillColor() { // return fillColor; // } // // public Pattern getPattern() { // return expression; // } // // public boolean isFiltered() { // return isFiltered; // } // // public LogLineColors getLogLineColors() { // return new LogLineColors( bkgColor, fillColor ); // } // // public boolean matches( String text ) { // if ( text == null ) { // text = ""; // } // // // the find method does not anchor the String by default, unlike matches() // return expression.matcher( text ).find(); // } // // public HighlightExpression withFilter( boolean enable ) { // return new HighlightExpression( this.expression, this.bkgColor, this.fillColor, enable ); // } // // @Override // public String toString() { // return "{" + // "expression=" + expression + // ", bkgColor=" + bkgColor + // ", fillColor=" + fillColor + // ", isFiltered=" + isFiltered + // '}'; // } // // @Override // public boolean equals( Object o ) { // if ( this == o ) return true; // if ( o == null || getClass() != o.getClass() ) return false; // HighlightExpression that = ( HighlightExpression ) o; // return isFiltered == that.isFiltered && // expression.toString().equals( that.expression.toString() ) && // bkgColor.equals( that.bkgColor ) && // fillColor.equals( that.fillColor ); // } // // @Override // public int hashCode() { // return Objects.hash( expression.toString(), bkgColor, fillColor, isFiltered ); // } // } // // Path: src/main/java/com/athaydes/logfx/ui/AwesomeIcons.java // public static final String HELP = "\ue718"; // // Path: src/main/java/com/athaydes/logfx/ui/AwesomeIcons.java // public static final String TRASH = "\ue605"; // // Path: src/main/java/com/athaydes/logfx/ui/FxUtils.java // public static String resourcePath( String name ) { // return resourceUrl( name ).toExternalForm(); // } // Path: src/main/java/com/athaydes/logfx/ui/HighlightOptions.java import com.athaydes.logfx.data.LogLineColors; import com.athaydes.logfx.text.HighlightExpression; import javafx.application.Platform; import javafx.beans.InvalidationListener; import javafx.beans.property.BooleanProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Cursor; import javafx.scene.Node; import javafx.scene.control.Button; import javafx.scene.control.CheckBox; import javafx.scene.control.Label; import javafx.scene.control.ScrollPane; import javafx.scene.control.TextField; import javafx.scene.control.Tooltip; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; import javafx.scene.paint.Paint; import javafx.scene.text.Text; import javafx.scene.text.TextFlow; import javafx.stage.StageStyle; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; import java.util.function.BiFunction; import java.util.regex.PatternSyntaxException; import java.util.stream.Collectors; import static com.athaydes.logfx.ui.Arrow.Direction.DOWN; import static com.athaydes.logfx.ui.Arrow.Direction.UP; import static com.athaydes.logfx.ui.AwesomeIcons.HELP; import static com.athaydes.logfx.ui.AwesomeIcons.TRASH; import static com.athaydes.logfx.ui.FxUtils.resourcePath; package com.athaydes.logfx.ui; /** * The highlight options screen. */ public class HighlightOptions extends VBox { private static final Logger log = LoggerFactory.getLogger( HighlightOptions.class ); private final ObservableList<HighlightExpression> observableExpressions; private final BooleanProperty isFilterEnabled; private String groupName; private final VBox expressionsBox; private final StandardLogColorsRow standardLogColorsRow; public HighlightOptions( String groupName,
SimpleObjectProperty<LogLineColors> standardLogColors,