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
blablacar/android-validator
library/src/test/java/com/comuto/validator/constraint/FileConstraintTest.java
// Path: library/src/test/java/com/comuto/validator/Utils.java // public class Utils { // public static File getFileFromResource(Object obj, String resourceName) throws IOException { // TemporaryFolder folder = new TemporaryFolder(); // folder.create(); // File file = folder.newFile(resourceName); // // InputStream stream = obj.getClass().getClassLoader().getResourceAsStream(resourceName); // // byte[] buffer = new byte[stream.available()]; // stream.read(buffer); // // OutputStream outStream = new FileOutputStream(file); // outStream.write(buffer); // // return file; // } // // public static void assertEmpty(String message, Iterable<?> iterable) { // if (iterable.iterator().hasNext()) { // failNotEmpty(message, iterable.toString()); // } // } // // public static void assertNotEmpty(String message, Iterable<?> iterable) { // if (!iterable.iterator().hasNext()) { // failEmpty(message); // } // } // // private static void failNotEmpty( // String message, String actual) { // failWithMessage(message, "expected to be empty, but contained: <" // + actual + ">"); // } // // private static void failEmpty(String message) { // failWithMessage(message, "expected not to be empty, but was"); // } // // private static void failWithMessage(String userMessage, String ourMessage) { // Assert.fail((userMessage == null) // ? ourMessage // : userMessage + ' ' + ourMessage); // } // // } // // Path: library/src/test/java/com/comuto/validator/Utils.java // public static void assertEmpty(String message, Iterable<?> iterable) { // if (iterable.iterator().hasNext()) { // failNotEmpty(message, iterable.toString()); // } // } // // Path: library/src/test/java/com/comuto/validator/Utils.java // public static void assertNotEmpty(String message, Iterable<?> iterable) { // if (!iterable.iterator().hasNext()) { // failEmpty(message); // } // }
import com.comuto.validator.Utils; import org.junit.Before; import org.junit.Test; import static com.comuto.validator.Utils.assertEmpty; import static com.comuto.validator.Utils.assertNotEmpty;
package com.comuto.validator.constraint; public class FileConstraintTest { private java.io.File file; @Before public void setUp() throws Exception { file = Utils.getFileFromResource(this, "test-file.png"); } @Test public void testIsValid() throws Exception {
// Path: library/src/test/java/com/comuto/validator/Utils.java // public class Utils { // public static File getFileFromResource(Object obj, String resourceName) throws IOException { // TemporaryFolder folder = new TemporaryFolder(); // folder.create(); // File file = folder.newFile(resourceName); // // InputStream stream = obj.getClass().getClassLoader().getResourceAsStream(resourceName); // // byte[] buffer = new byte[stream.available()]; // stream.read(buffer); // // OutputStream outStream = new FileOutputStream(file); // outStream.write(buffer); // // return file; // } // // public static void assertEmpty(String message, Iterable<?> iterable) { // if (iterable.iterator().hasNext()) { // failNotEmpty(message, iterable.toString()); // } // } // // public static void assertNotEmpty(String message, Iterable<?> iterable) { // if (!iterable.iterator().hasNext()) { // failEmpty(message); // } // } // // private static void failNotEmpty( // String message, String actual) { // failWithMessage(message, "expected to be empty, but contained: <" // + actual + ">"); // } // // private static void failEmpty(String message) { // failWithMessage(message, "expected not to be empty, but was"); // } // // private static void failWithMessage(String userMessage, String ourMessage) { // Assert.fail((userMessage == null) // ? ourMessage // : userMessage + ' ' + ourMessage); // } // // } // // Path: library/src/test/java/com/comuto/validator/Utils.java // public static void assertEmpty(String message, Iterable<?> iterable) { // if (iterable.iterator().hasNext()) { // failNotEmpty(message, iterable.toString()); // } // } // // Path: library/src/test/java/com/comuto/validator/Utils.java // public static void assertNotEmpty(String message, Iterable<?> iterable) { // if (!iterable.iterator().hasNext()) { // failEmpty(message); // } // } // Path: library/src/test/java/com/comuto/validator/constraint/FileConstraintTest.java import com.comuto.validator.Utils; import org.junit.Before; import org.junit.Test; import static com.comuto.validator.Utils.assertEmpty; import static com.comuto.validator.Utils.assertNotEmpty; package com.comuto.validator.constraint; public class FileConstraintTest { private java.io.File file; @Before public void setUp() throws Exception { file = Utils.getFileFromResource(this, "test-file.png"); } @Test public void testIsValid() throws Exception {
assertEmpty("Is valid", getFileConstraint(0, Double.MAX_VALUE).validate());
blablacar/android-validator
library/src/test/java/com/comuto/validator/constraint/FileConstraintTest.java
// Path: library/src/test/java/com/comuto/validator/Utils.java // public class Utils { // public static File getFileFromResource(Object obj, String resourceName) throws IOException { // TemporaryFolder folder = new TemporaryFolder(); // folder.create(); // File file = folder.newFile(resourceName); // // InputStream stream = obj.getClass().getClassLoader().getResourceAsStream(resourceName); // // byte[] buffer = new byte[stream.available()]; // stream.read(buffer); // // OutputStream outStream = new FileOutputStream(file); // outStream.write(buffer); // // return file; // } // // public static void assertEmpty(String message, Iterable<?> iterable) { // if (iterable.iterator().hasNext()) { // failNotEmpty(message, iterable.toString()); // } // } // // public static void assertNotEmpty(String message, Iterable<?> iterable) { // if (!iterable.iterator().hasNext()) { // failEmpty(message); // } // } // // private static void failNotEmpty( // String message, String actual) { // failWithMessage(message, "expected to be empty, but contained: <" // + actual + ">"); // } // // private static void failEmpty(String message) { // failWithMessage(message, "expected not to be empty, but was"); // } // // private static void failWithMessage(String userMessage, String ourMessage) { // Assert.fail((userMessage == null) // ? ourMessage // : userMessage + ' ' + ourMessage); // } // // } // // Path: library/src/test/java/com/comuto/validator/Utils.java // public static void assertEmpty(String message, Iterable<?> iterable) { // if (iterable.iterator().hasNext()) { // failNotEmpty(message, iterable.toString()); // } // } // // Path: library/src/test/java/com/comuto/validator/Utils.java // public static void assertNotEmpty(String message, Iterable<?> iterable) { // if (!iterable.iterator().hasNext()) { // failEmpty(message); // } // }
import com.comuto.validator.Utils; import org.junit.Before; import org.junit.Test; import static com.comuto.validator.Utils.assertEmpty; import static com.comuto.validator.Utils.assertNotEmpty;
package com.comuto.validator.constraint; public class FileConstraintTest { private java.io.File file; @Before public void setUp() throws Exception { file = Utils.getFileFromResource(this, "test-file.png"); } @Test public void testIsValid() throws Exception { assertEmpty("Is valid", getFileConstraint(0, Double.MAX_VALUE).validate()); } @Test public void testValidateWithMinConstraint() throws Exception {
// Path: library/src/test/java/com/comuto/validator/Utils.java // public class Utils { // public static File getFileFromResource(Object obj, String resourceName) throws IOException { // TemporaryFolder folder = new TemporaryFolder(); // folder.create(); // File file = folder.newFile(resourceName); // // InputStream stream = obj.getClass().getClassLoader().getResourceAsStream(resourceName); // // byte[] buffer = new byte[stream.available()]; // stream.read(buffer); // // OutputStream outStream = new FileOutputStream(file); // outStream.write(buffer); // // return file; // } // // public static void assertEmpty(String message, Iterable<?> iterable) { // if (iterable.iterator().hasNext()) { // failNotEmpty(message, iterable.toString()); // } // } // // public static void assertNotEmpty(String message, Iterable<?> iterable) { // if (!iterable.iterator().hasNext()) { // failEmpty(message); // } // } // // private static void failNotEmpty( // String message, String actual) { // failWithMessage(message, "expected to be empty, but contained: <" // + actual + ">"); // } // // private static void failEmpty(String message) { // failWithMessage(message, "expected not to be empty, but was"); // } // // private static void failWithMessage(String userMessage, String ourMessage) { // Assert.fail((userMessage == null) // ? ourMessage // : userMessage + ' ' + ourMessage); // } // // } // // Path: library/src/test/java/com/comuto/validator/Utils.java // public static void assertEmpty(String message, Iterable<?> iterable) { // if (iterable.iterator().hasNext()) { // failNotEmpty(message, iterable.toString()); // } // } // // Path: library/src/test/java/com/comuto/validator/Utils.java // public static void assertNotEmpty(String message, Iterable<?> iterable) { // if (!iterable.iterator().hasNext()) { // failEmpty(message); // } // } // Path: library/src/test/java/com/comuto/validator/constraint/FileConstraintTest.java import com.comuto.validator.Utils; import org.junit.Before; import org.junit.Test; import static com.comuto.validator.Utils.assertEmpty; import static com.comuto.validator.Utils.assertNotEmpty; package com.comuto.validator.constraint; public class FileConstraintTest { private java.io.File file; @Before public void setUp() throws Exception { file = Utils.getFileFromResource(this, "test-file.png"); } @Test public void testIsValid() throws Exception { assertEmpty("Is valid", getFileConstraint(0, Double.MAX_VALUE).validate()); } @Test public void testValidateWithMinConstraint() throws Exception {
assertNotEmpty("Is invalid", getFileConstraint(100000000d, Double.MAX_VALUE).validate());
blablacar/android-validator
library/src/main/java/com/comuto/validator/constraint/ImageConstraint.java
// Path: library/src/main/java/com/comuto/validator/UnsupportedException.java // public class UnsupportedException extends RuntimeException { // /** // * Constructs a new {@code RuntimeException} with the current stack trace // * and the specified detail message. // * // * @param constraint the constraint for this exception. // * @param o the object invalid value; // * @param propertyName the property. // */ // public UnsupportedException(Constraint constraint, Object o, String propertyName) { // super("Constraint: " // + constraint.getClass().getSimpleName() // + " cannot handle " // + o.getClass().getName() // + "on property: " // + propertyName // + ". If you want to validate a custom Object, you can create a custom Constraint which extends this one and override validate()."); // } // } // // Path: library/src/main/java/com/comuto/validator/Violation.java // public class Violation { // private final String propertyName; // private final Object invalidValue; // private final String message; // private final String code; // // /** // * Construct the violation with final values. // * // * @param propertyName The name of the field. This is defined by the user. // * @param invalidValue The invalid which have violate the constraint. // * @param message The interpolated message. // * @param code The Error code of the constraint. // */ // public Violation(String propertyName, Object invalidValue, String message, String code) { // this.propertyName = propertyName; // this.invalidValue = invalidValue; // this.message = message; // this.code = code; // } // // /** // * @return the interpolated error message for this constraint violation // */ // public String getMessage() { // return message; // } // // /** // * Returns the value failing to pass the constraint. // * For cross-parameter constraints, an {@code Object[]} representing // * the method invocation arguments is returned. // * // * @return the value failing to pass the constraint // */ // public Object getInvalidValue() { // return invalidValue; // } // // /** // * Returns the name of the property. // * // * @return the property name. // */ // public String getPropertyName() { // return propertyName; // } // // /** // * Returns a machine-digestible error code for the violation. // * // * @return String The error code. // */ // public String getCode() { // return code; // } // }
import android.graphics.BitmapFactory; import android.support.annotation.NonNull; import com.comuto.validator.UnsupportedException; import com.comuto.validator.Violation; import java.io.File; import java.util.HashSet; import java.util.Set;
package com.comuto.validator.constraint; /** * Validate a file to have a minimum and maximum image dimensions. */ public class ImageConstraint extends Constraint<File> { /** * Constant pass to Violation when image is too small. */ public static final String ERROR_CODE_SIZE_TOO_SMALL = "ERROR_CODE_SIZE_TOO_SMALL"; /** * Constant pass to Violation when image is too big. */ public static final String ERROR_CODE_SIZE_TOO_BIG = "ERROR_CODE_SIZE_TOO_BIG"; protected int minWidth = 0; protected int minHeight = 0; protected int maxWidth = Integer.MAX_VALUE; protected int maxHeight = Integer.MAX_VALUE; protected String minMessage = "Please choose an image of min. %d x %d pixels."; protected String maxMessage = "Please choose an image of max. %d x %d pixels."; /** * Constructor of the constraint * * @param object the object to validate through this constraint. * @param propertyName the property name of your field, this allow you to have the name of the field in violation. */ public ImageConstraint(@NonNull File object, @NonNull String propertyName) { super(object, propertyName); } /** * Validate file image dimensions. * * @return a non-null set of violation. If there is no violations, this set will be empty. * @throws UnsupportedException when an constraint object to validate is not supported. */ @Override @NonNull
// Path: library/src/main/java/com/comuto/validator/UnsupportedException.java // public class UnsupportedException extends RuntimeException { // /** // * Constructs a new {@code RuntimeException} with the current stack trace // * and the specified detail message. // * // * @param constraint the constraint for this exception. // * @param o the object invalid value; // * @param propertyName the property. // */ // public UnsupportedException(Constraint constraint, Object o, String propertyName) { // super("Constraint: " // + constraint.getClass().getSimpleName() // + " cannot handle " // + o.getClass().getName() // + "on property: " // + propertyName // + ". If you want to validate a custom Object, you can create a custom Constraint which extends this one and override validate()."); // } // } // // Path: library/src/main/java/com/comuto/validator/Violation.java // public class Violation { // private final String propertyName; // private final Object invalidValue; // private final String message; // private final String code; // // /** // * Construct the violation with final values. // * // * @param propertyName The name of the field. This is defined by the user. // * @param invalidValue The invalid which have violate the constraint. // * @param message The interpolated message. // * @param code The Error code of the constraint. // */ // public Violation(String propertyName, Object invalidValue, String message, String code) { // this.propertyName = propertyName; // this.invalidValue = invalidValue; // this.message = message; // this.code = code; // } // // /** // * @return the interpolated error message for this constraint violation // */ // public String getMessage() { // return message; // } // // /** // * Returns the value failing to pass the constraint. // * For cross-parameter constraints, an {@code Object[]} representing // * the method invocation arguments is returned. // * // * @return the value failing to pass the constraint // */ // public Object getInvalidValue() { // return invalidValue; // } // // /** // * Returns the name of the property. // * // * @return the property name. // */ // public String getPropertyName() { // return propertyName; // } // // /** // * Returns a machine-digestible error code for the violation. // * // * @return String The error code. // */ // public String getCode() { // return code; // } // } // Path: library/src/main/java/com/comuto/validator/constraint/ImageConstraint.java import android.graphics.BitmapFactory; import android.support.annotation.NonNull; import com.comuto.validator.UnsupportedException; import com.comuto.validator.Violation; import java.io.File; import java.util.HashSet; import java.util.Set; package com.comuto.validator.constraint; /** * Validate a file to have a minimum and maximum image dimensions. */ public class ImageConstraint extends Constraint<File> { /** * Constant pass to Violation when image is too small. */ public static final String ERROR_CODE_SIZE_TOO_SMALL = "ERROR_CODE_SIZE_TOO_SMALL"; /** * Constant pass to Violation when image is too big. */ public static final String ERROR_CODE_SIZE_TOO_BIG = "ERROR_CODE_SIZE_TOO_BIG"; protected int minWidth = 0; protected int minHeight = 0; protected int maxWidth = Integer.MAX_VALUE; protected int maxHeight = Integer.MAX_VALUE; protected String minMessage = "Please choose an image of min. %d x %d pixels."; protected String maxMessage = "Please choose an image of max. %d x %d pixels."; /** * Constructor of the constraint * * @param object the object to validate through this constraint. * @param propertyName the property name of your field, this allow you to have the name of the field in violation. */ public ImageConstraint(@NonNull File object, @NonNull String propertyName) { super(object, propertyName); } /** * Validate file image dimensions. * * @return a non-null set of violation. If there is no violations, this set will be empty. * @throws UnsupportedException when an constraint object to validate is not supported. */ @Override @NonNull
public Set<Violation> validate() throws UnsupportedException {
blablacar/android-validator
library/src/main/java/com/comuto/validator/constraint/ImageConstraint.java
// Path: library/src/main/java/com/comuto/validator/UnsupportedException.java // public class UnsupportedException extends RuntimeException { // /** // * Constructs a new {@code RuntimeException} with the current stack trace // * and the specified detail message. // * // * @param constraint the constraint for this exception. // * @param o the object invalid value; // * @param propertyName the property. // */ // public UnsupportedException(Constraint constraint, Object o, String propertyName) { // super("Constraint: " // + constraint.getClass().getSimpleName() // + " cannot handle " // + o.getClass().getName() // + "on property: " // + propertyName // + ". If you want to validate a custom Object, you can create a custom Constraint which extends this one and override validate()."); // } // } // // Path: library/src/main/java/com/comuto/validator/Violation.java // public class Violation { // private final String propertyName; // private final Object invalidValue; // private final String message; // private final String code; // // /** // * Construct the violation with final values. // * // * @param propertyName The name of the field. This is defined by the user. // * @param invalidValue The invalid which have violate the constraint. // * @param message The interpolated message. // * @param code The Error code of the constraint. // */ // public Violation(String propertyName, Object invalidValue, String message, String code) { // this.propertyName = propertyName; // this.invalidValue = invalidValue; // this.message = message; // this.code = code; // } // // /** // * @return the interpolated error message for this constraint violation // */ // public String getMessage() { // return message; // } // // /** // * Returns the value failing to pass the constraint. // * For cross-parameter constraints, an {@code Object[]} representing // * the method invocation arguments is returned. // * // * @return the value failing to pass the constraint // */ // public Object getInvalidValue() { // return invalidValue; // } // // /** // * Returns the name of the property. // * // * @return the property name. // */ // public String getPropertyName() { // return propertyName; // } // // /** // * Returns a machine-digestible error code for the violation. // * // * @return String The error code. // */ // public String getCode() { // return code; // } // }
import android.graphics.BitmapFactory; import android.support.annotation.NonNull; import com.comuto.validator.UnsupportedException; import com.comuto.validator.Violation; import java.io.File; import java.util.HashSet; import java.util.Set;
package com.comuto.validator.constraint; /** * Validate a file to have a minimum and maximum image dimensions. */ public class ImageConstraint extends Constraint<File> { /** * Constant pass to Violation when image is too small. */ public static final String ERROR_CODE_SIZE_TOO_SMALL = "ERROR_CODE_SIZE_TOO_SMALL"; /** * Constant pass to Violation when image is too big. */ public static final String ERROR_CODE_SIZE_TOO_BIG = "ERROR_CODE_SIZE_TOO_BIG"; protected int minWidth = 0; protected int minHeight = 0; protected int maxWidth = Integer.MAX_VALUE; protected int maxHeight = Integer.MAX_VALUE; protected String minMessage = "Please choose an image of min. %d x %d pixels."; protected String maxMessage = "Please choose an image of max. %d x %d pixels."; /** * Constructor of the constraint * * @param object the object to validate through this constraint. * @param propertyName the property name of your field, this allow you to have the name of the field in violation. */ public ImageConstraint(@NonNull File object, @NonNull String propertyName) { super(object, propertyName); } /** * Validate file image dimensions. * * @return a non-null set of violation. If there is no violations, this set will be empty. * @throws UnsupportedException when an constraint object to validate is not supported. */ @Override @NonNull
// Path: library/src/main/java/com/comuto/validator/UnsupportedException.java // public class UnsupportedException extends RuntimeException { // /** // * Constructs a new {@code RuntimeException} with the current stack trace // * and the specified detail message. // * // * @param constraint the constraint for this exception. // * @param o the object invalid value; // * @param propertyName the property. // */ // public UnsupportedException(Constraint constraint, Object o, String propertyName) { // super("Constraint: " // + constraint.getClass().getSimpleName() // + " cannot handle " // + o.getClass().getName() // + "on property: " // + propertyName // + ". If you want to validate a custom Object, you can create a custom Constraint which extends this one and override validate()."); // } // } // // Path: library/src/main/java/com/comuto/validator/Violation.java // public class Violation { // private final String propertyName; // private final Object invalidValue; // private final String message; // private final String code; // // /** // * Construct the violation with final values. // * // * @param propertyName The name of the field. This is defined by the user. // * @param invalidValue The invalid which have violate the constraint. // * @param message The interpolated message. // * @param code The Error code of the constraint. // */ // public Violation(String propertyName, Object invalidValue, String message, String code) { // this.propertyName = propertyName; // this.invalidValue = invalidValue; // this.message = message; // this.code = code; // } // // /** // * @return the interpolated error message for this constraint violation // */ // public String getMessage() { // return message; // } // // /** // * Returns the value failing to pass the constraint. // * For cross-parameter constraints, an {@code Object[]} representing // * the method invocation arguments is returned. // * // * @return the value failing to pass the constraint // */ // public Object getInvalidValue() { // return invalidValue; // } // // /** // * Returns the name of the property. // * // * @return the property name. // */ // public String getPropertyName() { // return propertyName; // } // // /** // * Returns a machine-digestible error code for the violation. // * // * @return String The error code. // */ // public String getCode() { // return code; // } // } // Path: library/src/main/java/com/comuto/validator/constraint/ImageConstraint.java import android.graphics.BitmapFactory; import android.support.annotation.NonNull; import com.comuto.validator.UnsupportedException; import com.comuto.validator.Violation; import java.io.File; import java.util.HashSet; import java.util.Set; package com.comuto.validator.constraint; /** * Validate a file to have a minimum and maximum image dimensions. */ public class ImageConstraint extends Constraint<File> { /** * Constant pass to Violation when image is too small. */ public static final String ERROR_CODE_SIZE_TOO_SMALL = "ERROR_CODE_SIZE_TOO_SMALL"; /** * Constant pass to Violation when image is too big. */ public static final String ERROR_CODE_SIZE_TOO_BIG = "ERROR_CODE_SIZE_TOO_BIG"; protected int minWidth = 0; protected int minHeight = 0; protected int maxWidth = Integer.MAX_VALUE; protected int maxHeight = Integer.MAX_VALUE; protected String minMessage = "Please choose an image of min. %d x %d pixels."; protected String maxMessage = "Please choose an image of max. %d x %d pixels."; /** * Constructor of the constraint * * @param object the object to validate through this constraint. * @param propertyName the property name of your field, this allow you to have the name of the field in violation. */ public ImageConstraint(@NonNull File object, @NonNull String propertyName) { super(object, propertyName); } /** * Validate file image dimensions. * * @return a non-null set of violation. If there is no violations, this set will be empty. * @throws UnsupportedException when an constraint object to validate is not supported. */ @Override @NonNull
public Set<Violation> validate() throws UnsupportedException {
blablacar/android-validator
library/src/main/java/com/comuto/validator/constraint/Constraint.java
// Path: library/src/main/java/com/comuto/validator/UnsupportedException.java // public class UnsupportedException extends RuntimeException { // /** // * Constructs a new {@code RuntimeException} with the current stack trace // * and the specified detail message. // * // * @param constraint the constraint for this exception. // * @param o the object invalid value; // * @param propertyName the property. // */ // public UnsupportedException(Constraint constraint, Object o, String propertyName) { // super("Constraint: " // + constraint.getClass().getSimpleName() // + " cannot handle " // + o.getClass().getName() // + "on property: " // + propertyName // + ". If you want to validate a custom Object, you can create a custom Constraint which extends this one and override validate()."); // } // } // // Path: library/src/main/java/com/comuto/validator/Violation.java // public class Violation { // private final String propertyName; // private final Object invalidValue; // private final String message; // private final String code; // // /** // * Construct the violation with final values. // * // * @param propertyName The name of the field. This is defined by the user. // * @param invalidValue The invalid which have violate the constraint. // * @param message The interpolated message. // * @param code The Error code of the constraint. // */ // public Violation(String propertyName, Object invalidValue, String message, String code) { // this.propertyName = propertyName; // this.invalidValue = invalidValue; // this.message = message; // this.code = code; // } // // /** // * @return the interpolated error message for this constraint violation // */ // public String getMessage() { // return message; // } // // /** // * Returns the value failing to pass the constraint. // * For cross-parameter constraints, an {@code Object[]} representing // * the method invocation arguments is returned. // * // * @return the value failing to pass the constraint // */ // public Object getInvalidValue() { // return invalidValue; // } // // /** // * Returns the name of the property. // * // * @return the property name. // */ // public String getPropertyName() { // return propertyName; // } // // /** // * Returns a machine-digestible error code for the violation. // * // * @return String The error code. // */ // public String getCode() { // return code; // } // }
import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.widget.EditText; import android.widget.Spinner; import com.comuto.validator.UnsupportedException; import com.comuto.validator.Violation; import java.util.Set;
package com.comuto.validator.constraint; /** * {@code Constraint} allows you to extend Validator to validate fields in ways that are not * supported by default in the library. */ public abstract class Constraint<T> { protected final T object; protected final String propertyName; /** * Constructor of the constraint * * @param object the object to validate through this constraint. * @param propertyName the property name of your field, this allow you to have the name of the field in violation. */ public Constraint(@NonNull T object, @NonNull String propertyName) { this.object = object; this.propertyName = propertyName; } /** * Implement the validation logic. * * @return a non-null set of violation. If there is no violations, this set will be empty. * @throws UnsupportedException when an constraint object to validate is not supported. */ @NonNull
// Path: library/src/main/java/com/comuto/validator/UnsupportedException.java // public class UnsupportedException extends RuntimeException { // /** // * Constructs a new {@code RuntimeException} with the current stack trace // * and the specified detail message. // * // * @param constraint the constraint for this exception. // * @param o the object invalid value; // * @param propertyName the property. // */ // public UnsupportedException(Constraint constraint, Object o, String propertyName) { // super("Constraint: " // + constraint.getClass().getSimpleName() // + " cannot handle " // + o.getClass().getName() // + "on property: " // + propertyName // + ". If you want to validate a custom Object, you can create a custom Constraint which extends this one and override validate()."); // } // } // // Path: library/src/main/java/com/comuto/validator/Violation.java // public class Violation { // private final String propertyName; // private final Object invalidValue; // private final String message; // private final String code; // // /** // * Construct the violation with final values. // * // * @param propertyName The name of the field. This is defined by the user. // * @param invalidValue The invalid which have violate the constraint. // * @param message The interpolated message. // * @param code The Error code of the constraint. // */ // public Violation(String propertyName, Object invalidValue, String message, String code) { // this.propertyName = propertyName; // this.invalidValue = invalidValue; // this.message = message; // this.code = code; // } // // /** // * @return the interpolated error message for this constraint violation // */ // public String getMessage() { // return message; // } // // /** // * Returns the value failing to pass the constraint. // * For cross-parameter constraints, an {@code Object[]} representing // * the method invocation arguments is returned. // * // * @return the value failing to pass the constraint // */ // public Object getInvalidValue() { // return invalidValue; // } // // /** // * Returns the name of the property. // * // * @return the property name. // */ // public String getPropertyName() { // return propertyName; // } // // /** // * Returns a machine-digestible error code for the violation. // * // * @return String The error code. // */ // public String getCode() { // return code; // } // } // Path: library/src/main/java/com/comuto/validator/constraint/Constraint.java import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.widget.EditText; import android.widget.Spinner; import com.comuto.validator.UnsupportedException; import com.comuto.validator.Violation; import java.util.Set; package com.comuto.validator.constraint; /** * {@code Constraint} allows you to extend Validator to validate fields in ways that are not * supported by default in the library. */ public abstract class Constraint<T> { protected final T object; protected final String propertyName; /** * Constructor of the constraint * * @param object the object to validate through this constraint. * @param propertyName the property name of your field, this allow you to have the name of the field in violation. */ public Constraint(@NonNull T object, @NonNull String propertyName) { this.object = object; this.propertyName = propertyName; } /** * Implement the validation logic. * * @return a non-null set of violation. If there is no violations, this set will be empty. * @throws UnsupportedException when an constraint object to validate is not supported. */ @NonNull
public abstract Set<Violation> validate() throws UnsupportedException;
blablacar/android-validator
library/src/main/java/com/comuto/validator/constraint/Constraint.java
// Path: library/src/main/java/com/comuto/validator/UnsupportedException.java // public class UnsupportedException extends RuntimeException { // /** // * Constructs a new {@code RuntimeException} with the current stack trace // * and the specified detail message. // * // * @param constraint the constraint for this exception. // * @param o the object invalid value; // * @param propertyName the property. // */ // public UnsupportedException(Constraint constraint, Object o, String propertyName) { // super("Constraint: " // + constraint.getClass().getSimpleName() // + " cannot handle " // + o.getClass().getName() // + "on property: " // + propertyName // + ". If you want to validate a custom Object, you can create a custom Constraint which extends this one and override validate()."); // } // } // // Path: library/src/main/java/com/comuto/validator/Violation.java // public class Violation { // private final String propertyName; // private final Object invalidValue; // private final String message; // private final String code; // // /** // * Construct the violation with final values. // * // * @param propertyName The name of the field. This is defined by the user. // * @param invalidValue The invalid which have violate the constraint. // * @param message The interpolated message. // * @param code The Error code of the constraint. // */ // public Violation(String propertyName, Object invalidValue, String message, String code) { // this.propertyName = propertyName; // this.invalidValue = invalidValue; // this.message = message; // this.code = code; // } // // /** // * @return the interpolated error message for this constraint violation // */ // public String getMessage() { // return message; // } // // /** // * Returns the value failing to pass the constraint. // * For cross-parameter constraints, an {@code Object[]} representing // * the method invocation arguments is returned. // * // * @return the value failing to pass the constraint // */ // public Object getInvalidValue() { // return invalidValue; // } // // /** // * Returns the name of the property. // * // * @return the property name. // */ // public String getPropertyName() { // return propertyName; // } // // /** // * Returns a machine-digestible error code for the violation. // * // * @return String The error code. // */ // public String getCode() { // return code; // } // }
import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.widget.EditText; import android.widget.Spinner; import com.comuto.validator.UnsupportedException; import com.comuto.validator.Violation; import java.util.Set;
package com.comuto.validator.constraint; /** * {@code Constraint} allows you to extend Validator to validate fields in ways that are not * supported by default in the library. */ public abstract class Constraint<T> { protected final T object; protected final String propertyName; /** * Constructor of the constraint * * @param object the object to validate through this constraint. * @param propertyName the property name of your field, this allow you to have the name of the field in violation. */ public Constraint(@NonNull T object, @NonNull String propertyName) { this.object = object; this.propertyName = propertyName; } /** * Implement the validation logic. * * @return a non-null set of violation. If there is no violations, this set will be empty. * @throws UnsupportedException when an constraint object to validate is not supported. */ @NonNull
// Path: library/src/main/java/com/comuto/validator/UnsupportedException.java // public class UnsupportedException extends RuntimeException { // /** // * Constructs a new {@code RuntimeException} with the current stack trace // * and the specified detail message. // * // * @param constraint the constraint for this exception. // * @param o the object invalid value; // * @param propertyName the property. // */ // public UnsupportedException(Constraint constraint, Object o, String propertyName) { // super("Constraint: " // + constraint.getClass().getSimpleName() // + " cannot handle " // + o.getClass().getName() // + "on property: " // + propertyName // + ". If you want to validate a custom Object, you can create a custom Constraint which extends this one and override validate()."); // } // } // // Path: library/src/main/java/com/comuto/validator/Violation.java // public class Violation { // private final String propertyName; // private final Object invalidValue; // private final String message; // private final String code; // // /** // * Construct the violation with final values. // * // * @param propertyName The name of the field. This is defined by the user. // * @param invalidValue The invalid which have violate the constraint. // * @param message The interpolated message. // * @param code The Error code of the constraint. // */ // public Violation(String propertyName, Object invalidValue, String message, String code) { // this.propertyName = propertyName; // this.invalidValue = invalidValue; // this.message = message; // this.code = code; // } // // /** // * @return the interpolated error message for this constraint violation // */ // public String getMessage() { // return message; // } // // /** // * Returns the value failing to pass the constraint. // * For cross-parameter constraints, an {@code Object[]} representing // * the method invocation arguments is returned. // * // * @return the value failing to pass the constraint // */ // public Object getInvalidValue() { // return invalidValue; // } // // /** // * Returns the name of the property. // * // * @return the property name. // */ // public String getPropertyName() { // return propertyName; // } // // /** // * Returns a machine-digestible error code for the violation. // * // * @return String The error code. // */ // public String getCode() { // return code; // } // } // Path: library/src/main/java/com/comuto/validator/constraint/Constraint.java import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.widget.EditText; import android.widget.Spinner; import com.comuto.validator.UnsupportedException; import com.comuto.validator.Violation; import java.util.Set; package com.comuto.validator.constraint; /** * {@code Constraint} allows you to extend Validator to validate fields in ways that are not * supported by default in the library. */ public abstract class Constraint<T> { protected final T object; protected final String propertyName; /** * Constructor of the constraint * * @param object the object to validate through this constraint. * @param propertyName the property name of your field, this allow you to have the name of the field in violation. */ public Constraint(@NonNull T object, @NonNull String propertyName) { this.object = object; this.propertyName = propertyName; } /** * Implement the validation logic. * * @return a non-null set of violation. If there is no violations, this set will be empty. * @throws UnsupportedException when an constraint object to validate is not supported. */ @NonNull
public abstract Set<Violation> validate() throws UnsupportedException;
blablacar/android-validator
library/src/test/java/com/comuto/validator/constraint/MatchConstraintTest.java
// Path: library/src/test/java/com/comuto/validator/Utils.java // public static void assertEmpty(String message, Iterable<?> iterable) { // if (iterable.iterator().hasNext()) { // failNotEmpty(message, iterable.toString()); // } // } // // Path: library/src/test/java/com/comuto/validator/Utils.java // public static void assertNotEmpty(String message, Iterable<?> iterable) { // if (!iterable.iterator().hasNext()) { // failEmpty(message); // } // }
import java.util.regex.Pattern; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import static com.comuto.validator.Utils.assertEmpty; import static com.comuto.validator.Utils.assertNotEmpty;
package com.comuto.validator.constraint; @RunWith(RobolectricTestRunner.class) @Config(manifest = Config.NONE) public class MatchConstraintTest extends BaseConstraintTest { private static final String PROPERTY_NAME = "property"; private static final Pattern PATTERN = Pattern.compile("[a-z]+", Pattern.CASE_INSENSITIVE); private static final String VALID = "foo"; private static final String INVALID = "-"; @Test public void isValid() throws Exception {
// Path: library/src/test/java/com/comuto/validator/Utils.java // public static void assertEmpty(String message, Iterable<?> iterable) { // if (iterable.iterator().hasNext()) { // failNotEmpty(message, iterable.toString()); // } // } // // Path: library/src/test/java/com/comuto/validator/Utils.java // public static void assertNotEmpty(String message, Iterable<?> iterable) { // if (!iterable.iterator().hasNext()) { // failEmpty(message); // } // } // Path: library/src/test/java/com/comuto/validator/constraint/MatchConstraintTest.java import java.util.regex.Pattern; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import static com.comuto.validator.Utils.assertEmpty; import static com.comuto.validator.Utils.assertNotEmpty; package com.comuto.validator.constraint; @RunWith(RobolectricTestRunner.class) @Config(manifest = Config.NONE) public class MatchConstraintTest extends BaseConstraintTest { private static final String PROPERTY_NAME = "property"; private static final Pattern PATTERN = Pattern.compile("[a-z]+", Pattern.CASE_INSENSITIVE); private static final String VALID = "foo"; private static final String INVALID = "-"; @Test public void isValid() throws Exception {
assertEmpty("is valid with String", new MatchConstraint(VALID, PATTERN, PROPERTY_NAME).validate());
blablacar/android-validator
library/src/test/java/com/comuto/validator/constraint/MatchConstraintTest.java
// Path: library/src/test/java/com/comuto/validator/Utils.java // public static void assertEmpty(String message, Iterable<?> iterable) { // if (iterable.iterator().hasNext()) { // failNotEmpty(message, iterable.toString()); // } // } // // Path: library/src/test/java/com/comuto/validator/Utils.java // public static void assertNotEmpty(String message, Iterable<?> iterable) { // if (!iterable.iterator().hasNext()) { // failEmpty(message); // } // }
import java.util.regex.Pattern; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import static com.comuto.validator.Utils.assertEmpty; import static com.comuto.validator.Utils.assertNotEmpty;
package com.comuto.validator.constraint; @RunWith(RobolectricTestRunner.class) @Config(manifest = Config.NONE) public class MatchConstraintTest extends BaseConstraintTest { private static final String PROPERTY_NAME = "property"; private static final Pattern PATTERN = Pattern.compile("[a-z]+", Pattern.CASE_INSENSITIVE); private static final String VALID = "foo"; private static final String INVALID = "-"; @Test public void isValid() throws Exception { assertEmpty("is valid with String", new MatchConstraint(VALID, PATTERN, PROPERTY_NAME).validate()); assertEmpty("is valid with ediText", new MatchConstraint(generateEditText(VALID), PATTERN, PROPERTY_NAME).validate()); assertEmpty("is valid with spinner", new MatchConstraint(generateSpinner(VALID), PATTERN, PROPERTY_NAME).validate()); } @Test public void isInValid() throws Exception {
// Path: library/src/test/java/com/comuto/validator/Utils.java // public static void assertEmpty(String message, Iterable<?> iterable) { // if (iterable.iterator().hasNext()) { // failNotEmpty(message, iterable.toString()); // } // } // // Path: library/src/test/java/com/comuto/validator/Utils.java // public static void assertNotEmpty(String message, Iterable<?> iterable) { // if (!iterable.iterator().hasNext()) { // failEmpty(message); // } // } // Path: library/src/test/java/com/comuto/validator/constraint/MatchConstraintTest.java import java.util.regex.Pattern; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import static com.comuto.validator.Utils.assertEmpty; import static com.comuto.validator.Utils.assertNotEmpty; package com.comuto.validator.constraint; @RunWith(RobolectricTestRunner.class) @Config(manifest = Config.NONE) public class MatchConstraintTest extends BaseConstraintTest { private static final String PROPERTY_NAME = "property"; private static final Pattern PATTERN = Pattern.compile("[a-z]+", Pattern.CASE_INSENSITIVE); private static final String VALID = "foo"; private static final String INVALID = "-"; @Test public void isValid() throws Exception { assertEmpty("is valid with String", new MatchConstraint(VALID, PATTERN, PROPERTY_NAME).validate()); assertEmpty("is valid with ediText", new MatchConstraint(generateEditText(VALID), PATTERN, PROPERTY_NAME).validate()); assertEmpty("is valid with spinner", new MatchConstraint(generateSpinner(VALID), PATTERN, PROPERTY_NAME).validate()); } @Test public void isInValid() throws Exception {
assertNotEmpty("is invalid with String", new MatchConstraint(INVALID, PATTERN, PROPERTY_NAME).validate());
blablacar/android-validator
library/src/main/java/com/comuto/validator/constraint/FileConstraint.java
// Path: library/src/main/java/com/comuto/validator/UnsupportedException.java // public class UnsupportedException extends RuntimeException { // /** // * Constructs a new {@code RuntimeException} with the current stack trace // * and the specified detail message. // * // * @param constraint the constraint for this exception. // * @param o the object invalid value; // * @param propertyName the property. // */ // public UnsupportedException(Constraint constraint, Object o, String propertyName) { // super("Constraint: " // + constraint.getClass().getSimpleName() // + " cannot handle " // + o.getClass().getName() // + "on property: " // + propertyName // + ". If you want to validate a custom Object, you can create a custom Constraint which extends this one and override validate()."); // } // } // // Path: library/src/main/java/com/comuto/validator/Violation.java // public class Violation { // private final String propertyName; // private final Object invalidValue; // private final String message; // private final String code; // // /** // * Construct the violation with final values. // * // * @param propertyName The name of the field. This is defined by the user. // * @param invalidValue The invalid which have violate the constraint. // * @param message The interpolated message. // * @param code The Error code of the constraint. // */ // public Violation(String propertyName, Object invalidValue, String message, String code) { // this.propertyName = propertyName; // this.invalidValue = invalidValue; // this.message = message; // this.code = code; // } // // /** // * @return the interpolated error message for this constraint violation // */ // public String getMessage() { // return message; // } // // /** // * Returns the value failing to pass the constraint. // * For cross-parameter constraints, an {@code Object[]} representing // * the method invocation arguments is returned. // * // * @return the value failing to pass the constraint // */ // public Object getInvalidValue() { // return invalidValue; // } // // /** // * Returns the name of the property. // * // * @return the property name. // */ // public String getPropertyName() { // return propertyName; // } // // /** // * Returns a machine-digestible error code for the violation. // * // * @return String The error code. // */ // public String getCode() { // return code; // } // }
import android.support.annotation.NonNull; import com.comuto.validator.UnsupportedException; import com.comuto.validator.Violation; import java.io.File; import java.util.HashSet; import java.util.Set;
package com.comuto.validator.constraint; /** * Validate a file to have a minimum and maximum size. */ public class FileConstraint extends Constraint<File> { protected static final double MEGABYTE = 1024L * 1024L; /** * Constant pass to Violation when file is to small. */ public static final String ERROR_CODE_TOO_SMALL = "ERROR_CODE_TOO_SMALL"; /** * Constant pass to Violation when file is to big. */ public static final String ERROR_CODE_TOO_LARGE = "ERROR_CODE_TOO_LARGE"; protected double min = 0; protected double max = Double.MAX_VALUE; protected String minMessage = "Please choose a file of min. %sMB."; protected String maxMessage = "Please choose a file of max. %sMB."; /** * Constructor of the constraint * * @param object the object to validate through this constraint. * @param propertyName the property name of your field, this allow you to have the name of the field in violation. */ public FileConstraint(@NonNull File object, @NonNull String propertyName) { super(object, propertyName); } /** * Validate file size. * * @return a non-null set of violation. If there is no violations, this set will be empty. * @throws UnsupportedException when an constraint object to validate is not supported. */ @NonNull @Override
// Path: library/src/main/java/com/comuto/validator/UnsupportedException.java // public class UnsupportedException extends RuntimeException { // /** // * Constructs a new {@code RuntimeException} with the current stack trace // * and the specified detail message. // * // * @param constraint the constraint for this exception. // * @param o the object invalid value; // * @param propertyName the property. // */ // public UnsupportedException(Constraint constraint, Object o, String propertyName) { // super("Constraint: " // + constraint.getClass().getSimpleName() // + " cannot handle " // + o.getClass().getName() // + "on property: " // + propertyName // + ". If you want to validate a custom Object, you can create a custom Constraint which extends this one and override validate()."); // } // } // // Path: library/src/main/java/com/comuto/validator/Violation.java // public class Violation { // private final String propertyName; // private final Object invalidValue; // private final String message; // private final String code; // // /** // * Construct the violation with final values. // * // * @param propertyName The name of the field. This is defined by the user. // * @param invalidValue The invalid which have violate the constraint. // * @param message The interpolated message. // * @param code The Error code of the constraint. // */ // public Violation(String propertyName, Object invalidValue, String message, String code) { // this.propertyName = propertyName; // this.invalidValue = invalidValue; // this.message = message; // this.code = code; // } // // /** // * @return the interpolated error message for this constraint violation // */ // public String getMessage() { // return message; // } // // /** // * Returns the value failing to pass the constraint. // * For cross-parameter constraints, an {@code Object[]} representing // * the method invocation arguments is returned. // * // * @return the value failing to pass the constraint // */ // public Object getInvalidValue() { // return invalidValue; // } // // /** // * Returns the name of the property. // * // * @return the property name. // */ // public String getPropertyName() { // return propertyName; // } // // /** // * Returns a machine-digestible error code for the violation. // * // * @return String The error code. // */ // public String getCode() { // return code; // } // } // Path: library/src/main/java/com/comuto/validator/constraint/FileConstraint.java import android.support.annotation.NonNull; import com.comuto.validator.UnsupportedException; import com.comuto.validator.Violation; import java.io.File; import java.util.HashSet; import java.util.Set; package com.comuto.validator.constraint; /** * Validate a file to have a minimum and maximum size. */ public class FileConstraint extends Constraint<File> { protected static final double MEGABYTE = 1024L * 1024L; /** * Constant pass to Violation when file is to small. */ public static final String ERROR_CODE_TOO_SMALL = "ERROR_CODE_TOO_SMALL"; /** * Constant pass to Violation when file is to big. */ public static final String ERROR_CODE_TOO_LARGE = "ERROR_CODE_TOO_LARGE"; protected double min = 0; protected double max = Double.MAX_VALUE; protected String minMessage = "Please choose a file of min. %sMB."; protected String maxMessage = "Please choose a file of max. %sMB."; /** * Constructor of the constraint * * @param object the object to validate through this constraint. * @param propertyName the property name of your field, this allow you to have the name of the field in violation. */ public FileConstraint(@NonNull File object, @NonNull String propertyName) { super(object, propertyName); } /** * Validate file size. * * @return a non-null set of violation. If there is no violations, this set will be empty. * @throws UnsupportedException when an constraint object to validate is not supported. */ @NonNull @Override
public Set<Violation> validate() throws UnsupportedException {
blablacar/android-validator
library/src/main/java/com/comuto/validator/constraint/FileConstraint.java
// Path: library/src/main/java/com/comuto/validator/UnsupportedException.java // public class UnsupportedException extends RuntimeException { // /** // * Constructs a new {@code RuntimeException} with the current stack trace // * and the specified detail message. // * // * @param constraint the constraint for this exception. // * @param o the object invalid value; // * @param propertyName the property. // */ // public UnsupportedException(Constraint constraint, Object o, String propertyName) { // super("Constraint: " // + constraint.getClass().getSimpleName() // + " cannot handle " // + o.getClass().getName() // + "on property: " // + propertyName // + ". If you want to validate a custom Object, you can create a custom Constraint which extends this one and override validate()."); // } // } // // Path: library/src/main/java/com/comuto/validator/Violation.java // public class Violation { // private final String propertyName; // private final Object invalidValue; // private final String message; // private final String code; // // /** // * Construct the violation with final values. // * // * @param propertyName The name of the field. This is defined by the user. // * @param invalidValue The invalid which have violate the constraint. // * @param message The interpolated message. // * @param code The Error code of the constraint. // */ // public Violation(String propertyName, Object invalidValue, String message, String code) { // this.propertyName = propertyName; // this.invalidValue = invalidValue; // this.message = message; // this.code = code; // } // // /** // * @return the interpolated error message for this constraint violation // */ // public String getMessage() { // return message; // } // // /** // * Returns the value failing to pass the constraint. // * For cross-parameter constraints, an {@code Object[]} representing // * the method invocation arguments is returned. // * // * @return the value failing to pass the constraint // */ // public Object getInvalidValue() { // return invalidValue; // } // // /** // * Returns the name of the property. // * // * @return the property name. // */ // public String getPropertyName() { // return propertyName; // } // // /** // * Returns a machine-digestible error code for the violation. // * // * @return String The error code. // */ // public String getCode() { // return code; // } // }
import android.support.annotation.NonNull; import com.comuto.validator.UnsupportedException; import com.comuto.validator.Violation; import java.io.File; import java.util.HashSet; import java.util.Set;
package com.comuto.validator.constraint; /** * Validate a file to have a minimum and maximum size. */ public class FileConstraint extends Constraint<File> { protected static final double MEGABYTE = 1024L * 1024L; /** * Constant pass to Violation when file is to small. */ public static final String ERROR_CODE_TOO_SMALL = "ERROR_CODE_TOO_SMALL"; /** * Constant pass to Violation when file is to big. */ public static final String ERROR_CODE_TOO_LARGE = "ERROR_CODE_TOO_LARGE"; protected double min = 0; protected double max = Double.MAX_VALUE; protected String minMessage = "Please choose a file of min. %sMB."; protected String maxMessage = "Please choose a file of max. %sMB."; /** * Constructor of the constraint * * @param object the object to validate through this constraint. * @param propertyName the property name of your field, this allow you to have the name of the field in violation. */ public FileConstraint(@NonNull File object, @NonNull String propertyName) { super(object, propertyName); } /** * Validate file size. * * @return a non-null set of violation. If there is no violations, this set will be empty. * @throws UnsupportedException when an constraint object to validate is not supported. */ @NonNull @Override
// Path: library/src/main/java/com/comuto/validator/UnsupportedException.java // public class UnsupportedException extends RuntimeException { // /** // * Constructs a new {@code RuntimeException} with the current stack trace // * and the specified detail message. // * // * @param constraint the constraint for this exception. // * @param o the object invalid value; // * @param propertyName the property. // */ // public UnsupportedException(Constraint constraint, Object o, String propertyName) { // super("Constraint: " // + constraint.getClass().getSimpleName() // + " cannot handle " // + o.getClass().getName() // + "on property: " // + propertyName // + ". If you want to validate a custom Object, you can create a custom Constraint which extends this one and override validate()."); // } // } // // Path: library/src/main/java/com/comuto/validator/Violation.java // public class Violation { // private final String propertyName; // private final Object invalidValue; // private final String message; // private final String code; // // /** // * Construct the violation with final values. // * // * @param propertyName The name of the field. This is defined by the user. // * @param invalidValue The invalid which have violate the constraint. // * @param message The interpolated message. // * @param code The Error code of the constraint. // */ // public Violation(String propertyName, Object invalidValue, String message, String code) { // this.propertyName = propertyName; // this.invalidValue = invalidValue; // this.message = message; // this.code = code; // } // // /** // * @return the interpolated error message for this constraint violation // */ // public String getMessage() { // return message; // } // // /** // * Returns the value failing to pass the constraint. // * For cross-parameter constraints, an {@code Object[]} representing // * the method invocation arguments is returned. // * // * @return the value failing to pass the constraint // */ // public Object getInvalidValue() { // return invalidValue; // } // // /** // * Returns the name of the property. // * // * @return the property name. // */ // public String getPropertyName() { // return propertyName; // } // // /** // * Returns a machine-digestible error code for the violation. // * // * @return String The error code. // */ // public String getCode() { // return code; // } // } // Path: library/src/main/java/com/comuto/validator/constraint/FileConstraint.java import android.support.annotation.NonNull; import com.comuto.validator.UnsupportedException; import com.comuto.validator.Violation; import java.io.File; import java.util.HashSet; import java.util.Set; package com.comuto.validator.constraint; /** * Validate a file to have a minimum and maximum size. */ public class FileConstraint extends Constraint<File> { protected static final double MEGABYTE = 1024L * 1024L; /** * Constant pass to Violation when file is to small. */ public static final String ERROR_CODE_TOO_SMALL = "ERROR_CODE_TOO_SMALL"; /** * Constant pass to Violation when file is to big. */ public static final String ERROR_CODE_TOO_LARGE = "ERROR_CODE_TOO_LARGE"; protected double min = 0; protected double max = Double.MAX_VALUE; protected String minMessage = "Please choose a file of min. %sMB."; protected String maxMessage = "Please choose a file of max. %sMB."; /** * Constructor of the constraint * * @param object the object to validate through this constraint. * @param propertyName the property name of your field, this allow you to have the name of the field in violation. */ public FileConstraint(@NonNull File object, @NonNull String propertyName) { super(object, propertyName); } /** * Validate file size. * * @return a non-null set of violation. If there is no violations, this set will be empty. * @throws UnsupportedException when an constraint object to validate is not supported. */ @NonNull @Override
public Set<Violation> validate() throws UnsupportedException {
blablacar/android-validator
library/src/test/java/com/comuto/validator/constraint/DateConstraintTest.java
// Path: library/src/test/java/com/comuto/validator/Utils.java // public static void assertEmpty(String message, Iterable<?> iterable) { // if (iterable.iterator().hasNext()) { // failNotEmpty(message, iterable.toString()); // } // } // // Path: library/src/test/java/com/comuto/validator/Utils.java // public static void assertNotEmpty(String message, Iterable<?> iterable) { // if (!iterable.iterator().hasNext()) { // failEmpty(message); // } // }
import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import static com.comuto.validator.Utils.assertEmpty; import static com.comuto.validator.Utils.assertNotEmpty;
package com.comuto.validator.constraint; @RunWith(RobolectricTestRunner.class) @Config(manifest = Config.NONE) public class DateConstraintTest extends BaseConstraintTest { private static final String PROPERTY_NAME = "property_date"; private static final String VALID = "2015-06-12"; private static final String NOT_VALID = "id"; @Test public void isValid() throws Exception {
// Path: library/src/test/java/com/comuto/validator/Utils.java // public static void assertEmpty(String message, Iterable<?> iterable) { // if (iterable.iterator().hasNext()) { // failNotEmpty(message, iterable.toString()); // } // } // // Path: library/src/test/java/com/comuto/validator/Utils.java // public static void assertNotEmpty(String message, Iterable<?> iterable) { // if (!iterable.iterator().hasNext()) { // failEmpty(message); // } // } // Path: library/src/test/java/com/comuto/validator/constraint/DateConstraintTest.java import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import static com.comuto.validator.Utils.assertEmpty; import static com.comuto.validator.Utils.assertNotEmpty; package com.comuto.validator.constraint; @RunWith(RobolectricTestRunner.class) @Config(manifest = Config.NONE) public class DateConstraintTest extends BaseConstraintTest { private static final String PROPERTY_NAME = "property_date"; private static final String VALID = "2015-06-12"; private static final String NOT_VALID = "id"; @Test public void isValid() throws Exception {
assertEmpty("is valid with String", new DateConstraint(VALID, PROPERTY_NAME).validate());
blablacar/android-validator
library/src/test/java/com/comuto/validator/constraint/DateConstraintTest.java
// Path: library/src/test/java/com/comuto/validator/Utils.java // public static void assertEmpty(String message, Iterable<?> iterable) { // if (iterable.iterator().hasNext()) { // failNotEmpty(message, iterable.toString()); // } // } // // Path: library/src/test/java/com/comuto/validator/Utils.java // public static void assertNotEmpty(String message, Iterable<?> iterable) { // if (!iterable.iterator().hasNext()) { // failEmpty(message); // } // }
import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import static com.comuto.validator.Utils.assertEmpty; import static com.comuto.validator.Utils.assertNotEmpty;
package com.comuto.validator.constraint; @RunWith(RobolectricTestRunner.class) @Config(manifest = Config.NONE) public class DateConstraintTest extends BaseConstraintTest { private static final String PROPERTY_NAME = "property_date"; private static final String VALID = "2015-06-12"; private static final String NOT_VALID = "id"; @Test public void isValid() throws Exception { assertEmpty("is valid with String", new DateConstraint(VALID, PROPERTY_NAME).validate()); assertEmpty("is valid with EditText", new DateConstraint(generateEditText(VALID), PROPERTY_NAME).validate()); assertEmpty("is valid with Spinner", new DateConstraint(generateSpinner(VALID), PROPERTY_NAME).validate()); } @Test public void isNotValid() throws Exception {
// Path: library/src/test/java/com/comuto/validator/Utils.java // public static void assertEmpty(String message, Iterable<?> iterable) { // if (iterable.iterator().hasNext()) { // failNotEmpty(message, iterable.toString()); // } // } // // Path: library/src/test/java/com/comuto/validator/Utils.java // public static void assertNotEmpty(String message, Iterable<?> iterable) { // if (!iterable.iterator().hasNext()) { // failEmpty(message); // } // } // Path: library/src/test/java/com/comuto/validator/constraint/DateConstraintTest.java import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import static com.comuto.validator.Utils.assertEmpty; import static com.comuto.validator.Utils.assertNotEmpty; package com.comuto.validator.constraint; @RunWith(RobolectricTestRunner.class) @Config(manifest = Config.NONE) public class DateConstraintTest extends BaseConstraintTest { private static final String PROPERTY_NAME = "property_date"; private static final String VALID = "2015-06-12"; private static final String NOT_VALID = "id"; @Test public void isValid() throws Exception { assertEmpty("is valid with String", new DateConstraint(VALID, PROPERTY_NAME).validate()); assertEmpty("is valid with EditText", new DateConstraint(generateEditText(VALID), PROPERTY_NAME).validate()); assertEmpty("is valid with Spinner", new DateConstraint(generateSpinner(VALID), PROPERTY_NAME).validate()); } @Test public void isNotValid() throws Exception {
assertNotEmpty("is not valid with String", new DateConstraint(NOT_VALID, PROPERTY_NAME).validate());
blablacar/android-validator
library/src/test/java/com/comuto/validator/constraint/NotBlankConstraintTest.java
// Path: library/src/main/java/com/comuto/validator/UnsupportedException.java // public class UnsupportedException extends RuntimeException { // /** // * Constructs a new {@code RuntimeException} with the current stack trace // * and the specified detail message. // * // * @param constraint the constraint for this exception. // * @param o the object invalid value; // * @param propertyName the property. // */ // public UnsupportedException(Constraint constraint, Object o, String propertyName) { // super("Constraint: " // + constraint.getClass().getSimpleName() // + " cannot handle " // + o.getClass().getName() // + "on property: " // + propertyName // + ". If you want to validate a custom Object, you can create a custom Constraint which extends this one and override validate()."); // } // } // // Path: library/src/test/java/com/comuto/validator/Utils.java // public static void assertEmpty(String message, Iterable<?> iterable) { // if (iterable.iterator().hasNext()) { // failNotEmpty(message, iterable.toString()); // } // } // // Path: library/src/test/java/com/comuto/validator/Utils.java // public static void assertNotEmpty(String message, Iterable<?> iterable) { // if (!iterable.iterator().hasNext()) { // failEmpty(message); // } // }
import com.comuto.validator.UnsupportedException; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import static com.comuto.validator.Utils.assertEmpty; import static com.comuto.validator.Utils.assertNotEmpty;
package com.comuto.validator.constraint; @RunWith(RobolectricTestRunner.class) @Config(manifest = Config.NONE) public class NotBlankConstraintTest extends BaseConstraintTest { private static final String VALID = "test"; private static final String PROPERTY_NAME = "property_not_blank"; @Test public void isValid() throws Exception {
// Path: library/src/main/java/com/comuto/validator/UnsupportedException.java // public class UnsupportedException extends RuntimeException { // /** // * Constructs a new {@code RuntimeException} with the current stack trace // * and the specified detail message. // * // * @param constraint the constraint for this exception. // * @param o the object invalid value; // * @param propertyName the property. // */ // public UnsupportedException(Constraint constraint, Object o, String propertyName) { // super("Constraint: " // + constraint.getClass().getSimpleName() // + " cannot handle " // + o.getClass().getName() // + "on property: " // + propertyName // + ". If you want to validate a custom Object, you can create a custom Constraint which extends this one and override validate()."); // } // } // // Path: library/src/test/java/com/comuto/validator/Utils.java // public static void assertEmpty(String message, Iterable<?> iterable) { // if (iterable.iterator().hasNext()) { // failNotEmpty(message, iterable.toString()); // } // } // // Path: library/src/test/java/com/comuto/validator/Utils.java // public static void assertNotEmpty(String message, Iterable<?> iterable) { // if (!iterable.iterator().hasNext()) { // failEmpty(message); // } // } // Path: library/src/test/java/com/comuto/validator/constraint/NotBlankConstraintTest.java import com.comuto.validator.UnsupportedException; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import static com.comuto.validator.Utils.assertEmpty; import static com.comuto.validator.Utils.assertNotEmpty; package com.comuto.validator.constraint; @RunWith(RobolectricTestRunner.class) @Config(manifest = Config.NONE) public class NotBlankConstraintTest extends BaseConstraintTest { private static final String VALID = "test"; private static final String PROPERTY_NAME = "property_not_blank"; @Test public void isValid() throws Exception {
assertEmpty("is valid with String", new NotBlankConstraint(VALID, PROPERTY_NAME).validate());
blablacar/android-validator
library/src/test/java/com/comuto/validator/constraint/NotBlankConstraintTest.java
// Path: library/src/main/java/com/comuto/validator/UnsupportedException.java // public class UnsupportedException extends RuntimeException { // /** // * Constructs a new {@code RuntimeException} with the current stack trace // * and the specified detail message. // * // * @param constraint the constraint for this exception. // * @param o the object invalid value; // * @param propertyName the property. // */ // public UnsupportedException(Constraint constraint, Object o, String propertyName) { // super("Constraint: " // + constraint.getClass().getSimpleName() // + " cannot handle " // + o.getClass().getName() // + "on property: " // + propertyName // + ". If you want to validate a custom Object, you can create a custom Constraint which extends this one and override validate()."); // } // } // // Path: library/src/test/java/com/comuto/validator/Utils.java // public static void assertEmpty(String message, Iterable<?> iterable) { // if (iterable.iterator().hasNext()) { // failNotEmpty(message, iterable.toString()); // } // } // // Path: library/src/test/java/com/comuto/validator/Utils.java // public static void assertNotEmpty(String message, Iterable<?> iterable) { // if (!iterable.iterator().hasNext()) { // failEmpty(message); // } // }
import com.comuto.validator.UnsupportedException; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import static com.comuto.validator.Utils.assertEmpty; import static com.comuto.validator.Utils.assertNotEmpty;
package com.comuto.validator.constraint; @RunWith(RobolectricTestRunner.class) @Config(manifest = Config.NONE) public class NotBlankConstraintTest extends BaseConstraintTest { private static final String VALID = "test"; private static final String PROPERTY_NAME = "property_not_blank"; @Test public void isValid() throws Exception { assertEmpty("is valid with String", new NotBlankConstraint(VALID, PROPERTY_NAME).validate()); assertEmpty("is valid with EditText", new NotBlankConstraint(generateEditText(VALID), PROPERTY_NAME).validate()); assertEmpty("is valid with Spinner", new NotBlankConstraint(generateSpinner(VALID), PROPERTY_NAME).validate()); } @Test public void isInvalidWithBlank() throws Exception {
// Path: library/src/main/java/com/comuto/validator/UnsupportedException.java // public class UnsupportedException extends RuntimeException { // /** // * Constructs a new {@code RuntimeException} with the current stack trace // * and the specified detail message. // * // * @param constraint the constraint for this exception. // * @param o the object invalid value; // * @param propertyName the property. // */ // public UnsupportedException(Constraint constraint, Object o, String propertyName) { // super("Constraint: " // + constraint.getClass().getSimpleName() // + " cannot handle " // + o.getClass().getName() // + "on property: " // + propertyName // + ". If you want to validate a custom Object, you can create a custom Constraint which extends this one and override validate()."); // } // } // // Path: library/src/test/java/com/comuto/validator/Utils.java // public static void assertEmpty(String message, Iterable<?> iterable) { // if (iterable.iterator().hasNext()) { // failNotEmpty(message, iterable.toString()); // } // } // // Path: library/src/test/java/com/comuto/validator/Utils.java // public static void assertNotEmpty(String message, Iterable<?> iterable) { // if (!iterable.iterator().hasNext()) { // failEmpty(message); // } // } // Path: library/src/test/java/com/comuto/validator/constraint/NotBlankConstraintTest.java import com.comuto.validator.UnsupportedException; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import static com.comuto.validator.Utils.assertEmpty; import static com.comuto.validator.Utils.assertNotEmpty; package com.comuto.validator.constraint; @RunWith(RobolectricTestRunner.class) @Config(manifest = Config.NONE) public class NotBlankConstraintTest extends BaseConstraintTest { private static final String VALID = "test"; private static final String PROPERTY_NAME = "property_not_blank"; @Test public void isValid() throws Exception { assertEmpty("is valid with String", new NotBlankConstraint(VALID, PROPERTY_NAME).validate()); assertEmpty("is valid with EditText", new NotBlankConstraint(generateEditText(VALID), PROPERTY_NAME).validate()); assertEmpty("is valid with Spinner", new NotBlankConstraint(generateSpinner(VALID), PROPERTY_NAME).validate()); } @Test public void isInvalidWithBlank() throws Exception {
assertNotEmpty("is invalid with String", new NotBlankConstraint(BLANK, PROPERTY_NAME).validate());
blablacar/android-validator
library/src/test/java/com/comuto/validator/constraint/NotBlankConstraintTest.java
// Path: library/src/main/java/com/comuto/validator/UnsupportedException.java // public class UnsupportedException extends RuntimeException { // /** // * Constructs a new {@code RuntimeException} with the current stack trace // * and the specified detail message. // * // * @param constraint the constraint for this exception. // * @param o the object invalid value; // * @param propertyName the property. // */ // public UnsupportedException(Constraint constraint, Object o, String propertyName) { // super("Constraint: " // + constraint.getClass().getSimpleName() // + " cannot handle " // + o.getClass().getName() // + "on property: " // + propertyName // + ". If you want to validate a custom Object, you can create a custom Constraint which extends this one and override validate()."); // } // } // // Path: library/src/test/java/com/comuto/validator/Utils.java // public static void assertEmpty(String message, Iterable<?> iterable) { // if (iterable.iterator().hasNext()) { // failNotEmpty(message, iterable.toString()); // } // } // // Path: library/src/test/java/com/comuto/validator/Utils.java // public static void assertNotEmpty(String message, Iterable<?> iterable) { // if (!iterable.iterator().hasNext()) { // failEmpty(message); // } // }
import com.comuto.validator.UnsupportedException; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import static com.comuto.validator.Utils.assertEmpty; import static com.comuto.validator.Utils.assertNotEmpty;
package com.comuto.validator.constraint; @RunWith(RobolectricTestRunner.class) @Config(manifest = Config.NONE) public class NotBlankConstraintTest extends BaseConstraintTest { private static final String VALID = "test"; private static final String PROPERTY_NAME = "property_not_blank"; @Test public void isValid() throws Exception { assertEmpty("is valid with String", new NotBlankConstraint(VALID, PROPERTY_NAME).validate()); assertEmpty("is valid with EditText", new NotBlankConstraint(generateEditText(VALID), PROPERTY_NAME).validate()); assertEmpty("is valid with Spinner", new NotBlankConstraint(generateSpinner(VALID), PROPERTY_NAME).validate()); } @Test public void isInvalidWithBlank() throws Exception { assertNotEmpty("is invalid with String", new NotBlankConstraint(BLANK, PROPERTY_NAME).validate()); assertNotEmpty("is invalid with EditText", new NotBlankConstraint(generateEditText(BLANK), PROPERTY_NAME).validate()); assertNotEmpty("is invalid with Spinner", new NotBlankConstraint(generateSpinner(BLANK), PROPERTY_NAME).validate()); } @Test public void isInvalidWithNull() throws Exception { assertNotEmpty("is invalid with String", new NotBlankConstraint(NULL, PROPERTY_NAME).validate()); assertNotEmpty("is invalid with EditText", new NotBlankConstraint(generateEditText(NULL), PROPERTY_NAME).validate()); assertNotEmpty("is invalid with Spinner", new NotBlankConstraint(generateSpinner(NULL), PROPERTY_NAME).validate()); }
// Path: library/src/main/java/com/comuto/validator/UnsupportedException.java // public class UnsupportedException extends RuntimeException { // /** // * Constructs a new {@code RuntimeException} with the current stack trace // * and the specified detail message. // * // * @param constraint the constraint for this exception. // * @param o the object invalid value; // * @param propertyName the property. // */ // public UnsupportedException(Constraint constraint, Object o, String propertyName) { // super("Constraint: " // + constraint.getClass().getSimpleName() // + " cannot handle " // + o.getClass().getName() // + "on property: " // + propertyName // + ". If you want to validate a custom Object, you can create a custom Constraint which extends this one and override validate()."); // } // } // // Path: library/src/test/java/com/comuto/validator/Utils.java // public static void assertEmpty(String message, Iterable<?> iterable) { // if (iterable.iterator().hasNext()) { // failNotEmpty(message, iterable.toString()); // } // } // // Path: library/src/test/java/com/comuto/validator/Utils.java // public static void assertNotEmpty(String message, Iterable<?> iterable) { // if (!iterable.iterator().hasNext()) { // failEmpty(message); // } // } // Path: library/src/test/java/com/comuto/validator/constraint/NotBlankConstraintTest.java import com.comuto.validator.UnsupportedException; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import static com.comuto.validator.Utils.assertEmpty; import static com.comuto.validator.Utils.assertNotEmpty; package com.comuto.validator.constraint; @RunWith(RobolectricTestRunner.class) @Config(manifest = Config.NONE) public class NotBlankConstraintTest extends BaseConstraintTest { private static final String VALID = "test"; private static final String PROPERTY_NAME = "property_not_blank"; @Test public void isValid() throws Exception { assertEmpty("is valid with String", new NotBlankConstraint(VALID, PROPERTY_NAME).validate()); assertEmpty("is valid with EditText", new NotBlankConstraint(generateEditText(VALID), PROPERTY_NAME).validate()); assertEmpty("is valid with Spinner", new NotBlankConstraint(generateSpinner(VALID), PROPERTY_NAME).validate()); } @Test public void isInvalidWithBlank() throws Exception { assertNotEmpty("is invalid with String", new NotBlankConstraint(BLANK, PROPERTY_NAME).validate()); assertNotEmpty("is invalid with EditText", new NotBlankConstraint(generateEditText(BLANK), PROPERTY_NAME).validate()); assertNotEmpty("is invalid with Spinner", new NotBlankConstraint(generateSpinner(BLANK), PROPERTY_NAME).validate()); } @Test public void isInvalidWithNull() throws Exception { assertNotEmpty("is invalid with String", new NotBlankConstraint(NULL, PROPERTY_NAME).validate()); assertNotEmpty("is invalid with EditText", new NotBlankConstraint(generateEditText(NULL), PROPERTY_NAME).validate()); assertNotEmpty("is invalid with Spinner", new NotBlankConstraint(generateSpinner(NULL), PROPERTY_NAME).validate()); }
@Test(expected = UnsupportedException.class)
blablacar/android-validator
library/src/main/java/com/comuto/validator/constraint/LengthConstraint.java
// Path: library/src/main/java/com/comuto/validator/UnsupportedException.java // public class UnsupportedException extends RuntimeException { // /** // * Constructs a new {@code RuntimeException} with the current stack trace // * and the specified detail message. // * // * @param constraint the constraint for this exception. // * @param o the object invalid value; // * @param propertyName the property. // */ // public UnsupportedException(Constraint constraint, Object o, String propertyName) { // super("Constraint: " // + constraint.getClass().getSimpleName() // + " cannot handle " // + o.getClass().getName() // + "on property: " // + propertyName // + ". If you want to validate a custom Object, you can create a custom Constraint which extends this one and override validate()."); // } // } // // Path: library/src/main/java/com/comuto/validator/Violation.java // public class Violation { // private final String propertyName; // private final Object invalidValue; // private final String message; // private final String code; // // /** // * Construct the violation with final values. // * // * @param propertyName The name of the field. This is defined by the user. // * @param invalidValue The invalid which have violate the constraint. // * @param message The interpolated message. // * @param code The Error code of the constraint. // */ // public Violation(String propertyName, Object invalidValue, String message, String code) { // this.propertyName = propertyName; // this.invalidValue = invalidValue; // this.message = message; // this.code = code; // } // // /** // * @return the interpolated error message for this constraint violation // */ // public String getMessage() { // return message; // } // // /** // * Returns the value failing to pass the constraint. // * For cross-parameter constraints, an {@code Object[]} representing // * the method invocation arguments is returned. // * // * @return the value failing to pass the constraint // */ // public Object getInvalidValue() { // return invalidValue; // } // // /** // * Returns the name of the property. // * // * @return the property name. // */ // public String getPropertyName() { // return propertyName; // } // // /** // * Returns a machine-digestible error code for the violation. // * // * @return String The error code. // */ // public String getCode() { // return code; // } // }
import android.support.annotation.NonNull; import com.comuto.validator.UnsupportedException; import com.comuto.validator.Violation; import java.util.HashSet; import java.util.Set;
package com.comuto.validator.constraint; /** * Validate the object value to have a correct length. */ public class LengthConstraint extends Constraint<Object> { /** * Constant pass to Violation when length is too small. */ public static final String ERROR_CODE_TOO_SMALL = "ERROR_CODE_TOO_SMALL"; /** * Constant pass to Violation when the length value is too large. */ public static final String ERROR_CODE_TOO_LARGE = "ERROR_CODE_TOO_LARGE"; protected double min = 0; protected double max = Double.MAX_VALUE; protected String minMessage = "This value is too short. It should have %s characters or more."; protected String maxMessage = "This value is too long. It should have %s characters or less."; /** * Constructor of the constraint * * @param object the object to validate through this constraint. * @param propertyName the property name of your field, this allow you to have the name of the field in violation. */ public LengthConstraint(@NonNull Object object, @NonNull String propertyName) { super(object, propertyName); } /** * Validate if the value has reach the excepted values. * * @return a non-null set of violation. If there is no violations, this set will be empty. * @throws UnsupportedException when an constraint object to validate is not supported. */ @NonNull @Override
// Path: library/src/main/java/com/comuto/validator/UnsupportedException.java // public class UnsupportedException extends RuntimeException { // /** // * Constructs a new {@code RuntimeException} with the current stack trace // * and the specified detail message. // * // * @param constraint the constraint for this exception. // * @param o the object invalid value; // * @param propertyName the property. // */ // public UnsupportedException(Constraint constraint, Object o, String propertyName) { // super("Constraint: " // + constraint.getClass().getSimpleName() // + " cannot handle " // + o.getClass().getName() // + "on property: " // + propertyName // + ". If you want to validate a custom Object, you can create a custom Constraint which extends this one and override validate()."); // } // } // // Path: library/src/main/java/com/comuto/validator/Violation.java // public class Violation { // private final String propertyName; // private final Object invalidValue; // private final String message; // private final String code; // // /** // * Construct the violation with final values. // * // * @param propertyName The name of the field. This is defined by the user. // * @param invalidValue The invalid which have violate the constraint. // * @param message The interpolated message. // * @param code The Error code of the constraint. // */ // public Violation(String propertyName, Object invalidValue, String message, String code) { // this.propertyName = propertyName; // this.invalidValue = invalidValue; // this.message = message; // this.code = code; // } // // /** // * @return the interpolated error message for this constraint violation // */ // public String getMessage() { // return message; // } // // /** // * Returns the value failing to pass the constraint. // * For cross-parameter constraints, an {@code Object[]} representing // * the method invocation arguments is returned. // * // * @return the value failing to pass the constraint // */ // public Object getInvalidValue() { // return invalidValue; // } // // /** // * Returns the name of the property. // * // * @return the property name. // */ // public String getPropertyName() { // return propertyName; // } // // /** // * Returns a machine-digestible error code for the violation. // * // * @return String The error code. // */ // public String getCode() { // return code; // } // } // Path: library/src/main/java/com/comuto/validator/constraint/LengthConstraint.java import android.support.annotation.NonNull; import com.comuto.validator.UnsupportedException; import com.comuto.validator.Violation; import java.util.HashSet; import java.util.Set; package com.comuto.validator.constraint; /** * Validate the object value to have a correct length. */ public class LengthConstraint extends Constraint<Object> { /** * Constant pass to Violation when length is too small. */ public static final String ERROR_CODE_TOO_SMALL = "ERROR_CODE_TOO_SMALL"; /** * Constant pass to Violation when the length value is too large. */ public static final String ERROR_CODE_TOO_LARGE = "ERROR_CODE_TOO_LARGE"; protected double min = 0; protected double max = Double.MAX_VALUE; protected String minMessage = "This value is too short. It should have %s characters or more."; protected String maxMessage = "This value is too long. It should have %s characters or less."; /** * Constructor of the constraint * * @param object the object to validate through this constraint. * @param propertyName the property name of your field, this allow you to have the name of the field in violation. */ public LengthConstraint(@NonNull Object object, @NonNull String propertyName) { super(object, propertyName); } /** * Validate if the value has reach the excepted values. * * @return a non-null set of violation. If there is no violations, this set will be empty. * @throws UnsupportedException when an constraint object to validate is not supported. */ @NonNull @Override
public Set<Violation> validate() throws UnsupportedException {
blablacar/android-validator
library/src/main/java/com/comuto/validator/constraint/LengthConstraint.java
// Path: library/src/main/java/com/comuto/validator/UnsupportedException.java // public class UnsupportedException extends RuntimeException { // /** // * Constructs a new {@code RuntimeException} with the current stack trace // * and the specified detail message. // * // * @param constraint the constraint for this exception. // * @param o the object invalid value; // * @param propertyName the property. // */ // public UnsupportedException(Constraint constraint, Object o, String propertyName) { // super("Constraint: " // + constraint.getClass().getSimpleName() // + " cannot handle " // + o.getClass().getName() // + "on property: " // + propertyName // + ". If you want to validate a custom Object, you can create a custom Constraint which extends this one and override validate()."); // } // } // // Path: library/src/main/java/com/comuto/validator/Violation.java // public class Violation { // private final String propertyName; // private final Object invalidValue; // private final String message; // private final String code; // // /** // * Construct the violation with final values. // * // * @param propertyName The name of the field. This is defined by the user. // * @param invalidValue The invalid which have violate the constraint. // * @param message The interpolated message. // * @param code The Error code of the constraint. // */ // public Violation(String propertyName, Object invalidValue, String message, String code) { // this.propertyName = propertyName; // this.invalidValue = invalidValue; // this.message = message; // this.code = code; // } // // /** // * @return the interpolated error message for this constraint violation // */ // public String getMessage() { // return message; // } // // /** // * Returns the value failing to pass the constraint. // * For cross-parameter constraints, an {@code Object[]} representing // * the method invocation arguments is returned. // * // * @return the value failing to pass the constraint // */ // public Object getInvalidValue() { // return invalidValue; // } // // /** // * Returns the name of the property. // * // * @return the property name. // */ // public String getPropertyName() { // return propertyName; // } // // /** // * Returns a machine-digestible error code for the violation. // * // * @return String The error code. // */ // public String getCode() { // return code; // } // }
import android.support.annotation.NonNull; import com.comuto.validator.UnsupportedException; import com.comuto.validator.Violation; import java.util.HashSet; import java.util.Set;
package com.comuto.validator.constraint; /** * Validate the object value to have a correct length. */ public class LengthConstraint extends Constraint<Object> { /** * Constant pass to Violation when length is too small. */ public static final String ERROR_CODE_TOO_SMALL = "ERROR_CODE_TOO_SMALL"; /** * Constant pass to Violation when the length value is too large. */ public static final String ERROR_CODE_TOO_LARGE = "ERROR_CODE_TOO_LARGE"; protected double min = 0; protected double max = Double.MAX_VALUE; protected String minMessage = "This value is too short. It should have %s characters or more."; protected String maxMessage = "This value is too long. It should have %s characters or less."; /** * Constructor of the constraint * * @param object the object to validate through this constraint. * @param propertyName the property name of your field, this allow you to have the name of the field in violation. */ public LengthConstraint(@NonNull Object object, @NonNull String propertyName) { super(object, propertyName); } /** * Validate if the value has reach the excepted values. * * @return a non-null set of violation. If there is no violations, this set will be empty. * @throws UnsupportedException when an constraint object to validate is not supported. */ @NonNull @Override
// Path: library/src/main/java/com/comuto/validator/UnsupportedException.java // public class UnsupportedException extends RuntimeException { // /** // * Constructs a new {@code RuntimeException} with the current stack trace // * and the specified detail message. // * // * @param constraint the constraint for this exception. // * @param o the object invalid value; // * @param propertyName the property. // */ // public UnsupportedException(Constraint constraint, Object o, String propertyName) { // super("Constraint: " // + constraint.getClass().getSimpleName() // + " cannot handle " // + o.getClass().getName() // + "on property: " // + propertyName // + ". If you want to validate a custom Object, you can create a custom Constraint which extends this one and override validate()."); // } // } // // Path: library/src/main/java/com/comuto/validator/Violation.java // public class Violation { // private final String propertyName; // private final Object invalidValue; // private final String message; // private final String code; // // /** // * Construct the violation with final values. // * // * @param propertyName The name of the field. This is defined by the user. // * @param invalidValue The invalid which have violate the constraint. // * @param message The interpolated message. // * @param code The Error code of the constraint. // */ // public Violation(String propertyName, Object invalidValue, String message, String code) { // this.propertyName = propertyName; // this.invalidValue = invalidValue; // this.message = message; // this.code = code; // } // // /** // * @return the interpolated error message for this constraint violation // */ // public String getMessage() { // return message; // } // // /** // * Returns the value failing to pass the constraint. // * For cross-parameter constraints, an {@code Object[]} representing // * the method invocation arguments is returned. // * // * @return the value failing to pass the constraint // */ // public Object getInvalidValue() { // return invalidValue; // } // // /** // * Returns the name of the property. // * // * @return the property name. // */ // public String getPropertyName() { // return propertyName; // } // // /** // * Returns a machine-digestible error code for the violation. // * // * @return String The error code. // */ // public String getCode() { // return code; // } // } // Path: library/src/main/java/com/comuto/validator/constraint/LengthConstraint.java import android.support.annotation.NonNull; import com.comuto.validator.UnsupportedException; import com.comuto.validator.Violation; import java.util.HashSet; import java.util.Set; package com.comuto.validator.constraint; /** * Validate the object value to have a correct length. */ public class LengthConstraint extends Constraint<Object> { /** * Constant pass to Violation when length is too small. */ public static final String ERROR_CODE_TOO_SMALL = "ERROR_CODE_TOO_SMALL"; /** * Constant pass to Violation when the length value is too large. */ public static final String ERROR_CODE_TOO_LARGE = "ERROR_CODE_TOO_LARGE"; protected double min = 0; protected double max = Double.MAX_VALUE; protected String minMessage = "This value is too short. It should have %s characters or more."; protected String maxMessage = "This value is too long. It should have %s characters or less."; /** * Constructor of the constraint * * @param object the object to validate through this constraint. * @param propertyName the property name of your field, this allow you to have the name of the field in violation. */ public LengthConstraint(@NonNull Object object, @NonNull String propertyName) { super(object, propertyName); } /** * Validate if the value has reach the excepted values. * * @return a non-null set of violation. If there is no violations, this set will be empty. * @throws UnsupportedException when an constraint object to validate is not supported. */ @NonNull @Override
public Set<Violation> validate() throws UnsupportedException {
blablacar/android-validator
library/src/main/java/com/comuto/validator/constraint/EqualsConstraint.java
// Path: library/src/main/java/com/comuto/validator/UnsupportedException.java // public class UnsupportedException extends RuntimeException { // /** // * Constructs a new {@code RuntimeException} with the current stack trace // * and the specified detail message. // * // * @param constraint the constraint for this exception. // * @param o the object invalid value; // * @param propertyName the property. // */ // public UnsupportedException(Constraint constraint, Object o, String propertyName) { // super("Constraint: " // + constraint.getClass().getSimpleName() // + " cannot handle " // + o.getClass().getName() // + "on property: " // + propertyName // + ". If you want to validate a custom Object, you can create a custom Constraint which extends this one and override validate()."); // } // } // // Path: library/src/main/java/com/comuto/validator/Violation.java // public class Violation { // private final String propertyName; // private final Object invalidValue; // private final String message; // private final String code; // // /** // * Construct the violation with final values. // * // * @param propertyName The name of the field. This is defined by the user. // * @param invalidValue The invalid which have violate the constraint. // * @param message The interpolated message. // * @param code The Error code of the constraint. // */ // public Violation(String propertyName, Object invalidValue, String message, String code) { // this.propertyName = propertyName; // this.invalidValue = invalidValue; // this.message = message; // this.code = code; // } // // /** // * @return the interpolated error message for this constraint violation // */ // public String getMessage() { // return message; // } // // /** // * Returns the value failing to pass the constraint. // * For cross-parameter constraints, an {@code Object[]} representing // * the method invocation arguments is returned. // * // * @return the value failing to pass the constraint // */ // public Object getInvalidValue() { // return invalidValue; // } // // /** // * Returns the name of the property. // * // * @return the property name. // */ // public String getPropertyName() { // return propertyName; // } // // /** // * Returns a machine-digestible error code for the violation. // * // * @return String The error code. // */ // public String getCode() { // return code; // } // }
import android.support.annotation.NonNull; import com.comuto.validator.UnsupportedException; import com.comuto.validator.Violation; import java.util.HashSet; import java.util.Set;
package com.comuto.validator.constraint; /** * Validate the object value to be equals to the excepted one. */ public class EqualsConstraint extends Constraint<Object> { /** * Constant pass to Violation when value is not equals. */ public static final String ERROR_CODE_IS_NOT_EQUALS = "ERROR_CODE_IS_NOT_EQUALS"; protected final String expectedValue; protected String message = "This value should be equal to %s."; /** * Constructor of the constraint * * @param object the object to validate through this constraint. * @param expectedValue the String value you except. * @param propertyName the property name of your field, this allow you to have the name of the field in violation. */ public EqualsConstraint(@NonNull Object object, @NonNull String expectedValue, @NonNull String propertyName) { super(object, propertyName); this.expectedValue = expectedValue; } /** * Validate if the value is a equals to the expected one. * * @return a non-null set of violation. If there is no violations, this set will be empty. * @throws UnsupportedException when an constraint object to validate is not supported. */ @Override @NonNull
// Path: library/src/main/java/com/comuto/validator/UnsupportedException.java // public class UnsupportedException extends RuntimeException { // /** // * Constructs a new {@code RuntimeException} with the current stack trace // * and the specified detail message. // * // * @param constraint the constraint for this exception. // * @param o the object invalid value; // * @param propertyName the property. // */ // public UnsupportedException(Constraint constraint, Object o, String propertyName) { // super("Constraint: " // + constraint.getClass().getSimpleName() // + " cannot handle " // + o.getClass().getName() // + "on property: " // + propertyName // + ". If you want to validate a custom Object, you can create a custom Constraint which extends this one and override validate()."); // } // } // // Path: library/src/main/java/com/comuto/validator/Violation.java // public class Violation { // private final String propertyName; // private final Object invalidValue; // private final String message; // private final String code; // // /** // * Construct the violation with final values. // * // * @param propertyName The name of the field. This is defined by the user. // * @param invalidValue The invalid which have violate the constraint. // * @param message The interpolated message. // * @param code The Error code of the constraint. // */ // public Violation(String propertyName, Object invalidValue, String message, String code) { // this.propertyName = propertyName; // this.invalidValue = invalidValue; // this.message = message; // this.code = code; // } // // /** // * @return the interpolated error message for this constraint violation // */ // public String getMessage() { // return message; // } // // /** // * Returns the value failing to pass the constraint. // * For cross-parameter constraints, an {@code Object[]} representing // * the method invocation arguments is returned. // * // * @return the value failing to pass the constraint // */ // public Object getInvalidValue() { // return invalidValue; // } // // /** // * Returns the name of the property. // * // * @return the property name. // */ // public String getPropertyName() { // return propertyName; // } // // /** // * Returns a machine-digestible error code for the violation. // * // * @return String The error code. // */ // public String getCode() { // return code; // } // } // Path: library/src/main/java/com/comuto/validator/constraint/EqualsConstraint.java import android.support.annotation.NonNull; import com.comuto.validator.UnsupportedException; import com.comuto.validator.Violation; import java.util.HashSet; import java.util.Set; package com.comuto.validator.constraint; /** * Validate the object value to be equals to the excepted one. */ public class EqualsConstraint extends Constraint<Object> { /** * Constant pass to Violation when value is not equals. */ public static final String ERROR_CODE_IS_NOT_EQUALS = "ERROR_CODE_IS_NOT_EQUALS"; protected final String expectedValue; protected String message = "This value should be equal to %s."; /** * Constructor of the constraint * * @param object the object to validate through this constraint. * @param expectedValue the String value you except. * @param propertyName the property name of your field, this allow you to have the name of the field in violation. */ public EqualsConstraint(@NonNull Object object, @NonNull String expectedValue, @NonNull String propertyName) { super(object, propertyName); this.expectedValue = expectedValue; } /** * Validate if the value is a equals to the expected one. * * @return a non-null set of violation. If there is no violations, this set will be empty. * @throws UnsupportedException when an constraint object to validate is not supported. */ @Override @NonNull
public Set<Violation> validate() {
michael-horn/Tern
java/tern/ui/ProgressFlower.java
// Path: java/tern/Palette.java // public class Palette { // // // public static Stroke STROKE1 = new BasicStroke(1); // public static Stroke STROKE2 = new BasicStroke(2); // public static Stroke STROKE3 = new BasicStroke(3); // // public static Font FONT12 = new Font(null, 0, 12); // public static Font FONT20B = new Font(null, Font.BOLD, 20); // // // public static AudioClip SOUND_POP = createAudio("/sounds/pop.wav"); // public static AudioClip SOUND_SHUTTER = createAudio("/sounds/camera.wav"); // // public static BufferedImage LOGO = createImage("/images/logo.png"); // public static BufferedImage CAMERA_ON = createImage("/images/camera_on.png"); // public static BufferedImage CAMERA_OFF = createImage("/images/camera_off.png"); // //public static BufferedImage RCX_SMALL = createImage("/images/nxtBrick_small.png"); // public static BufferedImage NXT_SMALL=createImage("/images/nxtBrick_small.png"); // public static BufferedImage PLAY_UP = createImage("/images/play_button_up.png"); // public static BufferedImage PLAY_DN = createImage("/images/play_button_dn.png"); // public static BufferedImage ICON_LG = createImage("/images/icon.png"); // // public static BufferedImage ERR_NO_RCX = // createImage("/images/error_rcx.png"); // public static BufferedImage ERR_NO_TOWER = // createImage("/images/error_tower.png"); // public static BufferedImage ERR_NO_BEGIN = // createImage("/images/error_begin.png"); // // /** // * Returns an audio clip, or null if the path was invalid. // */ // public static AudioClip createAudio(String path) { // java.net.URL audioURL = Main2.class.getResource(path); // if (audioURL != null) { // return java.applet.Applet.newAudioClip(audioURL); // } else { // System.err.println("Couldn't find file: " + path); // return null; // } // } // // // /** // * Returns a buffered image from the given path. // */ // public static BufferedImage createImage(String path) { // try { // java.net.URL url = Main2.class.getResource(path); // if (url != null) { // return ImageIO.read(url); // } else { // System.err.println("Couldn't find file: " + path); // return null; // } // } catch (java.io.IOException iox) { // System.err.println("Unable to read image file: " + path); // return null; // } // } // }
import java.awt.Font; import java.awt.Color; import java.awt.Graphics2D; import java.awt.geom.RoundRectangle2D; import java.awt.image.BufferedImage; import tern.Palette;
/* * @(#) ProgressFlower.java * * Tern Tangible Programming System * Copyright (C) 2009 Michael S. Horn * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package tern.ui; /** * Displays a compile progress indicator that looks like a spinning * flower. * * @author Michael Horn * @version $Revision: 1.2 $, $Date: 2007/11/14 23:46:01 $ */ public class ProgressFlower { protected static final int PETAL_COUNT = 12; protected static final int BORDER = 25; /** Message to display below the flower */ protected String message; /** Petal count */ protected int count; /** Is the flower visible or not? */ protected boolean visible; protected BufferedImage[] frames; /** * Default constructor */ public ProgressFlower() { this.message = "Compiling..."; this.count = 0; this.visible = false; this.frames = new BufferedImage[PETAL_COUNT]; for (int i=0; i<frames.length; i++) {
// Path: java/tern/Palette.java // public class Palette { // // // public static Stroke STROKE1 = new BasicStroke(1); // public static Stroke STROKE2 = new BasicStroke(2); // public static Stroke STROKE3 = new BasicStroke(3); // // public static Font FONT12 = new Font(null, 0, 12); // public static Font FONT20B = new Font(null, Font.BOLD, 20); // // // public static AudioClip SOUND_POP = createAudio("/sounds/pop.wav"); // public static AudioClip SOUND_SHUTTER = createAudio("/sounds/camera.wav"); // // public static BufferedImage LOGO = createImage("/images/logo.png"); // public static BufferedImage CAMERA_ON = createImage("/images/camera_on.png"); // public static BufferedImage CAMERA_OFF = createImage("/images/camera_off.png"); // //public static BufferedImage RCX_SMALL = createImage("/images/nxtBrick_small.png"); // public static BufferedImage NXT_SMALL=createImage("/images/nxtBrick_small.png"); // public static BufferedImage PLAY_UP = createImage("/images/play_button_up.png"); // public static BufferedImage PLAY_DN = createImage("/images/play_button_dn.png"); // public static BufferedImage ICON_LG = createImage("/images/icon.png"); // // public static BufferedImage ERR_NO_RCX = // createImage("/images/error_rcx.png"); // public static BufferedImage ERR_NO_TOWER = // createImage("/images/error_tower.png"); // public static BufferedImage ERR_NO_BEGIN = // createImage("/images/error_begin.png"); // // /** // * Returns an audio clip, or null if the path was invalid. // */ // public static AudioClip createAudio(String path) { // java.net.URL audioURL = Main2.class.getResource(path); // if (audioURL != null) { // return java.applet.Applet.newAudioClip(audioURL); // } else { // System.err.println("Couldn't find file: " + path); // return null; // } // } // // // /** // * Returns a buffered image from the given path. // */ // public static BufferedImage createImage(String path) { // try { // java.net.URL url = Main2.class.getResource(path); // if (url != null) { // return ImageIO.read(url); // } else { // System.err.println("Couldn't find file: " + path); // return null; // } // } catch (java.io.IOException iox) { // System.err.println("Unable to read image file: " + path); // return null; // } // } // } // Path: java/tern/ui/ProgressFlower.java import java.awt.Font; import java.awt.Color; import java.awt.Graphics2D; import java.awt.geom.RoundRectangle2D; import java.awt.image.BufferedImage; import tern.Palette; /* * @(#) ProgressFlower.java * * Tern Tangible Programming System * Copyright (C) 2009 Michael S. Horn * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package tern.ui; /** * Displays a compile progress indicator that looks like a spinning * flower. * * @author Michael Horn * @version $Revision: 1.2 $, $Date: 2007/11/14 23:46:01 $ */ public class ProgressFlower { protected static final int PETAL_COUNT = 12; protected static final int BORDER = 25; /** Message to display below the flower */ protected String message; /** Petal count */ protected int count; /** Is the flower visible or not? */ protected boolean visible; protected BufferedImage[] frames; /** * Default constructor */ public ProgressFlower() { this.message = "Compiling..."; this.count = 0; this.visible = false; this.frames = new BufferedImage[PETAL_COUNT]; for (int i=0; i<frames.length; i++) {
frames[i] = Palette.createImage("/images/progress" + (i+1) + ".png");
michael-horn/Tern
java/tern/nqc/NXCTransmitter.java
// Path: java/tern/compiler/CompileException.java // public class CompileException extends Exception { // // public static final int ERR_NONE = 0; // public static final int ERR_NO_BLOCKS = 1; // public static final int ERR_NO_BEGIN = 2; // public static final int ERR_SAVE_FILE = 3; // public static final int ERR_CAMERA = 4; // public static final int ERR_NO_NQC = 5; // public static final int ERR_NO_RCX = 6; // public static final int ERR_NO_TOWER = 7; // public static final int ERR_LOAD_FILE = 8; // public static final int ERR_FIRMWARE = 9; // public static final int ERR_UNKNOWN = 10; // public static final int ERR_NO_NXT = 11; // // protected int code = ERR_NONE; // // public CompileException(int code) { // super(); // this.code = code; // } // // public int getErrorCode() { // return this.code; // } // }
import java.io.BufferedInputStream; import java.io.IOException; import tern.compiler.CompileException;
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package tern.nqc; /** * * @author Maruma */ public class NXCTransmitter { private String firmware = "firm0328.lgo"; /** NXC Compiler binary (nqc.exe) */ private String compiler; /** Compiler process */ private Process process; /** NQC command to execute */ private String [] command; private String Path; public NXCTransmitter(java.util.Properties props) { this.compiler = props.getProperty("nxc.compiler"); this.process = null; this.Path = props.getProperty("nxc.path"); this.command = new String[4]; } //Mariam //04-09-2011
// Path: java/tern/compiler/CompileException.java // public class CompileException extends Exception { // // public static final int ERR_NONE = 0; // public static final int ERR_NO_BLOCKS = 1; // public static final int ERR_NO_BEGIN = 2; // public static final int ERR_SAVE_FILE = 3; // public static final int ERR_CAMERA = 4; // public static final int ERR_NO_NQC = 5; // public static final int ERR_NO_RCX = 6; // public static final int ERR_NO_TOWER = 7; // public static final int ERR_LOAD_FILE = 8; // public static final int ERR_FIRMWARE = 9; // public static final int ERR_UNKNOWN = 10; // public static final int ERR_NO_NXT = 11; // // protected int code = ERR_NONE; // // public CompileException(int code) { // super(); // this.code = code; // } // // public int getErrorCode() { // return this.code; // } // } // Path: java/tern/nqc/NXCTransmitter.java import java.io.BufferedInputStream; import java.io.IOException; import tern.compiler.CompileException; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package tern.nqc; /** * * @author Maruma */ public class NXCTransmitter { private String firmware = "firm0328.lgo"; /** NXC Compiler binary (nqc.exe) */ private String compiler; /** Compiler process */ private Process process; /** NQC command to execute */ private String [] command; private String Path; public NXCTransmitter(java.util.Properties props) { this.compiler = props.getProperty("nxc.compiler"); this.process = null; this.Path = props.getProperty("nxc.path"); this.command = new String[4]; } //Mariam //04-09-2011
public void Run(String filename)throws CompileException
upenn-libraries/solrplugins
src/main/java/org/apache/solr/request/BidirectionalFacetResponseBuilder.java
// Path: src/main/java/org/apache/solr/handler/component/FacetComponent.java // public static class TermDocEntry { // public final String term; // public final String docId; // public final String termDocId; // public NamedList<Object> termMetadata; // public final SolrDocument doc; // // public TermDocEntry(String term, String termDocId, String docId, NamedList<Object> termMetadata, SolrDocument doc) { // this.term = term; // this.docId = docId; // this.termDocId = termDocId; // this.termMetadata = termMetadata; // this.doc = doc; // } // // } // // Path: src/main/java/org/apache/solr/handler/component/FacetComponent.java // public static class ShardFacetCount { // public String name; // // the indexed form of the name... used for comparisons // public BytesRef indexed; // public long count; // public Object val; // public int termNum; // term number starting at 0 (used in bit arrays) // // @Override // public String toString() { // return "{term=" + name + ",termNum=" + termNum + ",count=" + count + ",val=" + val + "}"; // } // } // // Path: src/main/java/org/apache/solr/request/BidirectionalFacetResponseBuilder.java // public static interface FacetKey<K extends FacetKey<K>> extends Comparable<K> { // // }
import java.io.IOException; import java.util.AbstractMap.SimpleImmutableEntry; import java.util.ArrayDeque; import java.util.Deque; import java.util.List; import java.util.Map.Entry; import java.util.function.Predicate; import org.apache.lucene.index.LeafReader; import org.apache.lucene.index.PostingsEnum; import org.apache.lucene.index.SortedSetDocValues; import org.apache.lucene.index.Term; import org.apache.lucene.util.Bits; import org.apache.lucene.util.BytesRef; import org.apache.lucene.util.CharsRefBuilder; import org.apache.solr.common.SolrDocument; import org.apache.solr.common.util.NamedList; import org.apache.solr.handler.component.FacetComponent.DistribFieldFacet.TermDocEntry; import org.apache.solr.handler.component.FacetComponent.ShardFacetCount; import org.apache.solr.request.BidirectionalFacetResponseBuilder.FacetKey; import org.apache.solr.schema.FieldType; import org.apache.solr.search.DocSet; import org.apache.solr.search.SolrIndexSearcher;
this.fieldName = fieldName; this.ft = ft; if (ft instanceof MultiSerializable) { ftDelim = ((MultiSerializable)ft).getDelim(); } else { ftDelim = "\u0000"; } this.res = res; } public abstract K incrementKey(K previousKey); public abstract K decrementKey(K previousKey); public abstract void addEntry(LimitMinder<T, K> limitMinder, K facetKey, Deque<Entry<String, Object>> entryBuilder) throws IOException; public abstract K targetKey() throws IOException; public abstract K targetKeyInit(boolean ascending) throws IOException; public abstract void initState(K key); public NamedList<Object> finalize(NamedList<Object> ret) { return ret; } } public static class DistribDocEnv<T extends FieldType & FacetPayload> extends DistribEnv<T> {
// Path: src/main/java/org/apache/solr/handler/component/FacetComponent.java // public static class TermDocEntry { // public final String term; // public final String docId; // public final String termDocId; // public NamedList<Object> termMetadata; // public final SolrDocument doc; // // public TermDocEntry(String term, String termDocId, String docId, NamedList<Object> termMetadata, SolrDocument doc) { // this.term = term; // this.docId = docId; // this.termDocId = termDocId; // this.termMetadata = termMetadata; // this.doc = doc; // } // // } // // Path: src/main/java/org/apache/solr/handler/component/FacetComponent.java // public static class ShardFacetCount { // public String name; // // the indexed form of the name... used for comparisons // public BytesRef indexed; // public long count; // public Object val; // public int termNum; // term number starting at 0 (used in bit arrays) // // @Override // public String toString() { // return "{term=" + name + ",termNum=" + termNum + ",count=" + count + ",val=" + val + "}"; // } // } // // Path: src/main/java/org/apache/solr/request/BidirectionalFacetResponseBuilder.java // public static interface FacetKey<K extends FacetKey<K>> extends Comparable<K> { // // } // Path: src/main/java/org/apache/solr/request/BidirectionalFacetResponseBuilder.java import java.io.IOException; import java.util.AbstractMap.SimpleImmutableEntry; import java.util.ArrayDeque; import java.util.Deque; import java.util.List; import java.util.Map.Entry; import java.util.function.Predicate; import org.apache.lucene.index.LeafReader; import org.apache.lucene.index.PostingsEnum; import org.apache.lucene.index.SortedSetDocValues; import org.apache.lucene.index.Term; import org.apache.lucene.util.Bits; import org.apache.lucene.util.BytesRef; import org.apache.lucene.util.CharsRefBuilder; import org.apache.solr.common.SolrDocument; import org.apache.solr.common.util.NamedList; import org.apache.solr.handler.component.FacetComponent.DistribFieldFacet.TermDocEntry; import org.apache.solr.handler.component.FacetComponent.ShardFacetCount; import org.apache.solr.request.BidirectionalFacetResponseBuilder.FacetKey; import org.apache.solr.schema.FieldType; import org.apache.solr.search.DocSet; import org.apache.solr.search.SolrIndexSearcher; this.fieldName = fieldName; this.ft = ft; if (ft instanceof MultiSerializable) { ftDelim = ((MultiSerializable)ft).getDelim(); } else { ftDelim = "\u0000"; } this.res = res; } public abstract K incrementKey(K previousKey); public abstract K decrementKey(K previousKey); public abstract void addEntry(LimitMinder<T, K> limitMinder, K facetKey, Deque<Entry<String, Object>> entryBuilder) throws IOException; public abstract K targetKey() throws IOException; public abstract K targetKeyInit(boolean ascending) throws IOException; public abstract void initState(K key); public NamedList<Object> finalize(NamedList<Object> ret) { return ret; } } public static class DistribDocEnv<T extends FieldType & FacetPayload> extends DistribEnv<T> {
public DistribDocEnv(int offset, int limit, int targetIdx, int mincount, String fieldName, T ft, NamedList res, ShardFacetCount[] counts) {
upenn-libraries/solrplugins
src/main/java/org/apache/solr/request/BidirectionalFacetResponseBuilder.java
// Path: src/main/java/org/apache/solr/handler/component/FacetComponent.java // public static class TermDocEntry { // public final String term; // public final String docId; // public final String termDocId; // public NamedList<Object> termMetadata; // public final SolrDocument doc; // // public TermDocEntry(String term, String termDocId, String docId, NamedList<Object> termMetadata, SolrDocument doc) { // this.term = term; // this.docId = docId; // this.termDocId = termDocId; // this.termMetadata = termMetadata; // this.doc = doc; // } // // } // // Path: src/main/java/org/apache/solr/handler/component/FacetComponent.java // public static class ShardFacetCount { // public String name; // // the indexed form of the name... used for comparisons // public BytesRef indexed; // public long count; // public Object val; // public int termNum; // term number starting at 0 (used in bit arrays) // // @Override // public String toString() { // return "{term=" + name + ",termNum=" + termNum + ",count=" + count + ",val=" + val + "}"; // } // } // // Path: src/main/java/org/apache/solr/request/BidirectionalFacetResponseBuilder.java // public static interface FacetKey<K extends FacetKey<K>> extends Comparable<K> { // // }
import java.io.IOException; import java.util.AbstractMap.SimpleImmutableEntry; import java.util.ArrayDeque; import java.util.Deque; import java.util.List; import java.util.Map.Entry; import java.util.function.Predicate; import org.apache.lucene.index.LeafReader; import org.apache.lucene.index.PostingsEnum; import org.apache.lucene.index.SortedSetDocValues; import org.apache.lucene.index.Term; import org.apache.lucene.util.Bits; import org.apache.lucene.util.BytesRef; import org.apache.lucene.util.CharsRefBuilder; import org.apache.solr.common.SolrDocument; import org.apache.solr.common.util.NamedList; import org.apache.solr.handler.component.FacetComponent.DistribFieldFacet.TermDocEntry; import org.apache.solr.handler.component.FacetComponent.ShardFacetCount; import org.apache.solr.request.BidirectionalFacetResponseBuilder.FacetKey; import org.apache.solr.schema.FieldType; import org.apache.solr.search.DocSet; import org.apache.solr.search.SolrIndexSearcher;
this.res = res; } public abstract K incrementKey(K previousKey); public abstract K decrementKey(K previousKey); public abstract void addEntry(LimitMinder<T, K> limitMinder, K facetKey, Deque<Entry<String, Object>> entryBuilder) throws IOException; public abstract K targetKey() throws IOException; public abstract K targetKeyInit(boolean ascending) throws IOException; public abstract void initState(K key); public NamedList<Object> finalize(NamedList<Object> ret) { return ret; } } public static class DistribDocEnv<T extends FieldType & FacetPayload> extends DistribEnv<T> { public DistribDocEnv(int offset, int limit, int targetIdx, int mincount, String fieldName, T ft, NamedList res, ShardFacetCount[] counts) { super(offset, limit, targetIdx, mincount, fieldName, ft, res, counts); } @Override public void addEntry(LimitMinder<T, SimpleTermIndexKey> limitMinder, SimpleTermIndexKey facetKey, Deque<Entry<String, Object>> entryBuilder) throws IOException { ShardFacetCount sfc = counts[facetKey.index];
// Path: src/main/java/org/apache/solr/handler/component/FacetComponent.java // public static class TermDocEntry { // public final String term; // public final String docId; // public final String termDocId; // public NamedList<Object> termMetadata; // public final SolrDocument doc; // // public TermDocEntry(String term, String termDocId, String docId, NamedList<Object> termMetadata, SolrDocument doc) { // this.term = term; // this.docId = docId; // this.termDocId = termDocId; // this.termMetadata = termMetadata; // this.doc = doc; // } // // } // // Path: src/main/java/org/apache/solr/handler/component/FacetComponent.java // public static class ShardFacetCount { // public String name; // // the indexed form of the name... used for comparisons // public BytesRef indexed; // public long count; // public Object val; // public int termNum; // term number starting at 0 (used in bit arrays) // // @Override // public String toString() { // return "{term=" + name + ",termNum=" + termNum + ",count=" + count + ",val=" + val + "}"; // } // } // // Path: src/main/java/org/apache/solr/request/BidirectionalFacetResponseBuilder.java // public static interface FacetKey<K extends FacetKey<K>> extends Comparable<K> { // // } // Path: src/main/java/org/apache/solr/request/BidirectionalFacetResponseBuilder.java import java.io.IOException; import java.util.AbstractMap.SimpleImmutableEntry; import java.util.ArrayDeque; import java.util.Deque; import java.util.List; import java.util.Map.Entry; import java.util.function.Predicate; import org.apache.lucene.index.LeafReader; import org.apache.lucene.index.PostingsEnum; import org.apache.lucene.index.SortedSetDocValues; import org.apache.lucene.index.Term; import org.apache.lucene.util.Bits; import org.apache.lucene.util.BytesRef; import org.apache.lucene.util.CharsRefBuilder; import org.apache.solr.common.SolrDocument; import org.apache.solr.common.util.NamedList; import org.apache.solr.handler.component.FacetComponent.DistribFieldFacet.TermDocEntry; import org.apache.solr.handler.component.FacetComponent.ShardFacetCount; import org.apache.solr.request.BidirectionalFacetResponseBuilder.FacetKey; import org.apache.solr.schema.FieldType; import org.apache.solr.search.DocSet; import org.apache.solr.search.SolrIndexSearcher; this.res = res; } public abstract K incrementKey(K previousKey); public abstract K decrementKey(K previousKey); public abstract void addEntry(LimitMinder<T, K> limitMinder, K facetKey, Deque<Entry<String, Object>> entryBuilder) throws IOException; public abstract K targetKey() throws IOException; public abstract K targetKeyInit(boolean ascending) throws IOException; public abstract void initState(K key); public NamedList<Object> finalize(NamedList<Object> ret) { return ret; } } public static class DistribDocEnv<T extends FieldType & FacetPayload> extends DistribEnv<T> { public DistribDocEnv(int offset, int limit, int targetIdx, int mincount, String fieldName, T ft, NamedList res, ShardFacetCount[] counts) { super(offset, limit, targetIdx, mincount, fieldName, ft, res, counts); } @Override public void addEntry(LimitMinder<T, SimpleTermIndexKey> limitMinder, SimpleTermIndexKey facetKey, Deque<Entry<String, Object>> entryBuilder) throws IOException { ShardFacetCount sfc = counts[facetKey.index];
TermDocEntry val = (TermDocEntry)sfc.val;
upenn-libraries/solrplugins
src/main/java/org/apache/solr/request/DocBasedFacetResponseBuilder.java
// Path: src/main/java/org/apache/solr/request/BidirectionalFacetResponseBuilder.java // public static abstract class BaseLocalTermEnv<T extends FieldType & FacetPayload, K extends FacetKey<K>> extends LocalEnv<T, K> { // // public BaseLocalTermEnv(int offset, int limit, int startTermIndex, int adjust, int targetIdx, int nTerms, Predicate<BytesRef> termFilter, // int mincount, int[] counts, CharsRefBuilder charsRef, boolean extend, SortedSetDocValues si, // SolrIndexSearcher searcher, List<Entry<LeafReader, Bits>> leaves, String fieldName, T ft, NamedList res) { // super(offset, limit, startTermIndex, adjust, targetIdx, nTerms, termFilter, mincount, counts, // charsRef, extend, si, searcher, leaves, fieldName, ft, res); // } // // protected final int incrementTermIndex(int lastKeyIndex) { // for (int i = lastKeyIndex + 1; i < endTermOrd; i++) { // if (acceptTerm(i)) { // return i; // } // } // return -1; // } // // protected final int decrementTermIndex(int lastKeyIndex) { // for (int i = lastKeyIndex - 1; i >= startTermOrd; i--) { // if (acceptTerm(i)) { // return i; // } // } // return -1; // } // // protected final int getTargetKeyIndex() { // return (targetIdx < 0 ? ~targetIdx : targetIdx); // } // // protected final int getTargetKeyIndexInit(boolean ascending) { // int index = getTargetKeyIndex(); // if (index >= startTermOrd && index < endTermOrd && acceptTerm(index)) { // return index; // } else if (ascending) { // return incrementTermIndex(index); // } else { // return decrementTermIndex(index); // } // } // } // // Path: src/main/java/org/apache/solr/request/BidirectionalFacetResponseBuilder.java // public static class BaseTermIndexKey<K extends BaseTermIndexKey<K>> implements FacetKey<K> { // // public final int index; // // public BaseTermIndexKey(int index) { // this.index = index; // } // // @Override // public int compareTo(BaseTermIndexKey o) { // return Integer.compare(index, o.index); // } // // @Override // public String toString() { // return BaseTermIndexKey.class.getSimpleName() + "(index=" + index + ')'; // } // // } // // Path: src/main/java/org/apache/solr/request/BidirectionalFacetResponseBuilder.java // public static interface LimitMinder<T extends FieldType & FacetPayload, K extends FacetKey<K>> { // K startKey(); // K nextKey(K lastKey, Env<T, K> env); // void addEntry(Entry<String, Object> entry, Deque<Entry<String, Object>> entryBuilder); // boolean updateEntry(String term, String docId, SolrDocument doc, Deque<Entry<String, Object>> entryBuilder); // void removeTail(Deque<Entry<String, Object>> entryBuilder); // }
import java.io.IOException; import java.util.AbstractMap.SimpleImmutableEntry; import java.util.ArrayDeque; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.Deque; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.function.Predicate; import org.apache.lucene.document.Document; import org.apache.lucene.index.LeafReader; import org.apache.lucene.index.PostingsEnum; import org.apache.lucene.index.SortedSetDocValues; import org.apache.lucene.index.Term; import org.apache.lucene.search.Query; import org.apache.lucene.search.Sort; import org.apache.lucene.search.SortField; import org.apache.lucene.search.TermQuery; import org.apache.lucene.util.Bits; import org.apache.lucene.util.BytesRef; import org.apache.lucene.util.CharsRefBuilder; import org.apache.lucene.util.UnicodeUtil; import org.apache.solr.common.SolrDocument; import org.apache.solr.common.util.NamedList; import org.apache.solr.request.BidirectionalFacetResponseBuilder.BaseLocalTermEnv; import org.apache.solr.request.BidirectionalFacetResponseBuilder.BaseTermIndexKey; import org.apache.solr.request.BidirectionalFacetResponseBuilder.LimitMinder; import org.apache.solr.response.DocsStreamer; import org.apache.solr.schema.FieldType; import org.apache.solr.schema.SchemaField; import org.apache.solr.search.DocList; import org.apache.solr.search.DocSet; import org.apache.solr.search.SolrIndexSearcher;
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.solr.request; /** * * @author magibney */ public class DocBasedFacetResponseBuilder { public static class TermDocIndexKey extends BaseTermIndexKey<TermDocIndexKey> { public final BytesRef docId; public TermDocIndexKey(int index, BytesRef docId) { super(index); this.docId = docId; } @Override public String toString() { return TermDocIndexKey.class.getSimpleName() + "(index=" + index + ", docId=" + LocalDocEnv.brToString(docId) + ')'; } }
// Path: src/main/java/org/apache/solr/request/BidirectionalFacetResponseBuilder.java // public static abstract class BaseLocalTermEnv<T extends FieldType & FacetPayload, K extends FacetKey<K>> extends LocalEnv<T, K> { // // public BaseLocalTermEnv(int offset, int limit, int startTermIndex, int adjust, int targetIdx, int nTerms, Predicate<BytesRef> termFilter, // int mincount, int[] counts, CharsRefBuilder charsRef, boolean extend, SortedSetDocValues si, // SolrIndexSearcher searcher, List<Entry<LeafReader, Bits>> leaves, String fieldName, T ft, NamedList res) { // super(offset, limit, startTermIndex, adjust, targetIdx, nTerms, termFilter, mincount, counts, // charsRef, extend, si, searcher, leaves, fieldName, ft, res); // } // // protected final int incrementTermIndex(int lastKeyIndex) { // for (int i = lastKeyIndex + 1; i < endTermOrd; i++) { // if (acceptTerm(i)) { // return i; // } // } // return -1; // } // // protected final int decrementTermIndex(int lastKeyIndex) { // for (int i = lastKeyIndex - 1; i >= startTermOrd; i--) { // if (acceptTerm(i)) { // return i; // } // } // return -1; // } // // protected final int getTargetKeyIndex() { // return (targetIdx < 0 ? ~targetIdx : targetIdx); // } // // protected final int getTargetKeyIndexInit(boolean ascending) { // int index = getTargetKeyIndex(); // if (index >= startTermOrd && index < endTermOrd && acceptTerm(index)) { // return index; // } else if (ascending) { // return incrementTermIndex(index); // } else { // return decrementTermIndex(index); // } // } // } // // Path: src/main/java/org/apache/solr/request/BidirectionalFacetResponseBuilder.java // public static class BaseTermIndexKey<K extends BaseTermIndexKey<K>> implements FacetKey<K> { // // public final int index; // // public BaseTermIndexKey(int index) { // this.index = index; // } // // @Override // public int compareTo(BaseTermIndexKey o) { // return Integer.compare(index, o.index); // } // // @Override // public String toString() { // return BaseTermIndexKey.class.getSimpleName() + "(index=" + index + ')'; // } // // } // // Path: src/main/java/org/apache/solr/request/BidirectionalFacetResponseBuilder.java // public static interface LimitMinder<T extends FieldType & FacetPayload, K extends FacetKey<K>> { // K startKey(); // K nextKey(K lastKey, Env<T, K> env); // void addEntry(Entry<String, Object> entry, Deque<Entry<String, Object>> entryBuilder); // boolean updateEntry(String term, String docId, SolrDocument doc, Deque<Entry<String, Object>> entryBuilder); // void removeTail(Deque<Entry<String, Object>> entryBuilder); // } // Path: src/main/java/org/apache/solr/request/DocBasedFacetResponseBuilder.java import java.io.IOException; import java.util.AbstractMap.SimpleImmutableEntry; import java.util.ArrayDeque; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.Deque; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.function.Predicate; import org.apache.lucene.document.Document; import org.apache.lucene.index.LeafReader; import org.apache.lucene.index.PostingsEnum; import org.apache.lucene.index.SortedSetDocValues; import org.apache.lucene.index.Term; import org.apache.lucene.search.Query; import org.apache.lucene.search.Sort; import org.apache.lucene.search.SortField; import org.apache.lucene.search.TermQuery; import org.apache.lucene.util.Bits; import org.apache.lucene.util.BytesRef; import org.apache.lucene.util.CharsRefBuilder; import org.apache.lucene.util.UnicodeUtil; import org.apache.solr.common.SolrDocument; import org.apache.solr.common.util.NamedList; import org.apache.solr.request.BidirectionalFacetResponseBuilder.BaseLocalTermEnv; import org.apache.solr.request.BidirectionalFacetResponseBuilder.BaseTermIndexKey; import org.apache.solr.request.BidirectionalFacetResponseBuilder.LimitMinder; import org.apache.solr.response.DocsStreamer; import org.apache.solr.schema.FieldType; import org.apache.solr.schema.SchemaField; import org.apache.solr.search.DocList; import org.apache.solr.search.DocSet; import org.apache.solr.search.SolrIndexSearcher; /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.solr.request; /** * * @author magibney */ public class DocBasedFacetResponseBuilder { public static class TermDocIndexKey extends BaseTermIndexKey<TermDocIndexKey> { public final BytesRef docId; public TermDocIndexKey(int index, BytesRef docId) { super(index); this.docId = docId; } @Override public String toString() { return TermDocIndexKey.class.getSimpleName() + "(index=" + index + ", docId=" + LocalDocEnv.brToString(docId) + ')'; } }
public static class LocalDocEnv<T extends FieldType & FacetPayload> extends BaseLocalTermEnv<T, TermDocIndexKey> {
upenn-libraries/solrplugins
src/main/java/org/apache/solr/request/DocBasedFacetResponseBuilder.java
// Path: src/main/java/org/apache/solr/request/BidirectionalFacetResponseBuilder.java // public static abstract class BaseLocalTermEnv<T extends FieldType & FacetPayload, K extends FacetKey<K>> extends LocalEnv<T, K> { // // public BaseLocalTermEnv(int offset, int limit, int startTermIndex, int adjust, int targetIdx, int nTerms, Predicate<BytesRef> termFilter, // int mincount, int[] counts, CharsRefBuilder charsRef, boolean extend, SortedSetDocValues si, // SolrIndexSearcher searcher, List<Entry<LeafReader, Bits>> leaves, String fieldName, T ft, NamedList res) { // super(offset, limit, startTermIndex, adjust, targetIdx, nTerms, termFilter, mincount, counts, // charsRef, extend, si, searcher, leaves, fieldName, ft, res); // } // // protected final int incrementTermIndex(int lastKeyIndex) { // for (int i = lastKeyIndex + 1; i < endTermOrd; i++) { // if (acceptTerm(i)) { // return i; // } // } // return -1; // } // // protected final int decrementTermIndex(int lastKeyIndex) { // for (int i = lastKeyIndex - 1; i >= startTermOrd; i--) { // if (acceptTerm(i)) { // return i; // } // } // return -1; // } // // protected final int getTargetKeyIndex() { // return (targetIdx < 0 ? ~targetIdx : targetIdx); // } // // protected final int getTargetKeyIndexInit(boolean ascending) { // int index = getTargetKeyIndex(); // if (index >= startTermOrd && index < endTermOrd && acceptTerm(index)) { // return index; // } else if (ascending) { // return incrementTermIndex(index); // } else { // return decrementTermIndex(index); // } // } // } // // Path: src/main/java/org/apache/solr/request/BidirectionalFacetResponseBuilder.java // public static class BaseTermIndexKey<K extends BaseTermIndexKey<K>> implements FacetKey<K> { // // public final int index; // // public BaseTermIndexKey(int index) { // this.index = index; // } // // @Override // public int compareTo(BaseTermIndexKey o) { // return Integer.compare(index, o.index); // } // // @Override // public String toString() { // return BaseTermIndexKey.class.getSimpleName() + "(index=" + index + ')'; // } // // } // // Path: src/main/java/org/apache/solr/request/BidirectionalFacetResponseBuilder.java // public static interface LimitMinder<T extends FieldType & FacetPayload, K extends FacetKey<K>> { // K startKey(); // K nextKey(K lastKey, Env<T, K> env); // void addEntry(Entry<String, Object> entry, Deque<Entry<String, Object>> entryBuilder); // boolean updateEntry(String term, String docId, SolrDocument doc, Deque<Entry<String, Object>> entryBuilder); // void removeTail(Deque<Entry<String, Object>> entryBuilder); // }
import java.io.IOException; import java.util.AbstractMap.SimpleImmutableEntry; import java.util.ArrayDeque; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.Deque; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.function.Predicate; import org.apache.lucene.document.Document; import org.apache.lucene.index.LeafReader; import org.apache.lucene.index.PostingsEnum; import org.apache.lucene.index.SortedSetDocValues; import org.apache.lucene.index.Term; import org.apache.lucene.search.Query; import org.apache.lucene.search.Sort; import org.apache.lucene.search.SortField; import org.apache.lucene.search.TermQuery; import org.apache.lucene.util.Bits; import org.apache.lucene.util.BytesRef; import org.apache.lucene.util.CharsRefBuilder; import org.apache.lucene.util.UnicodeUtil; import org.apache.solr.common.SolrDocument; import org.apache.solr.common.util.NamedList; import org.apache.solr.request.BidirectionalFacetResponseBuilder.BaseLocalTermEnv; import org.apache.solr.request.BidirectionalFacetResponseBuilder.BaseTermIndexKey; import org.apache.solr.request.BidirectionalFacetResponseBuilder.LimitMinder; import org.apache.solr.response.DocsStreamer; import org.apache.solr.schema.FieldType; import org.apache.solr.schema.SchemaField; import org.apache.solr.search.DocList; import org.apache.solr.search.DocSet; import org.apache.solr.search.SolrIndexSearcher;
static String brToString(BytesRef br) { if (br == null) { return "null"; } else if (UnicodeUtil.BIG_TERM.bytesEquals(br)) { return "[UnicodeUtil.BIG_TERM]"; } else { return br.utf8ToString(); } } @Override public TermDocIndexKey decrementKey(TermDocIndexKey previousKey) { int termIndex = previousKey.index; BytesRef docId = previousKey.docId; do { while ((docId = decrementDocId(termIndex, docId)) != null) { int docIndex = acceptDoc(termIndex, docId); if (docIndex >= 0) { localDocIndex = docIndex; return termDocIndexKey = new TermDocIndexKey(termIndex, docId); } } docId = UnicodeUtil.BIG_TERM; } while ((termIndex = decrementTermIndex(termIndex)) >= 0); localDocIndex = -1; return termDocIndexKey = null; } @Override
// Path: src/main/java/org/apache/solr/request/BidirectionalFacetResponseBuilder.java // public static abstract class BaseLocalTermEnv<T extends FieldType & FacetPayload, K extends FacetKey<K>> extends LocalEnv<T, K> { // // public BaseLocalTermEnv(int offset, int limit, int startTermIndex, int adjust, int targetIdx, int nTerms, Predicate<BytesRef> termFilter, // int mincount, int[] counts, CharsRefBuilder charsRef, boolean extend, SortedSetDocValues si, // SolrIndexSearcher searcher, List<Entry<LeafReader, Bits>> leaves, String fieldName, T ft, NamedList res) { // super(offset, limit, startTermIndex, adjust, targetIdx, nTerms, termFilter, mincount, counts, // charsRef, extend, si, searcher, leaves, fieldName, ft, res); // } // // protected final int incrementTermIndex(int lastKeyIndex) { // for (int i = lastKeyIndex + 1; i < endTermOrd; i++) { // if (acceptTerm(i)) { // return i; // } // } // return -1; // } // // protected final int decrementTermIndex(int lastKeyIndex) { // for (int i = lastKeyIndex - 1; i >= startTermOrd; i--) { // if (acceptTerm(i)) { // return i; // } // } // return -1; // } // // protected final int getTargetKeyIndex() { // return (targetIdx < 0 ? ~targetIdx : targetIdx); // } // // protected final int getTargetKeyIndexInit(boolean ascending) { // int index = getTargetKeyIndex(); // if (index >= startTermOrd && index < endTermOrd && acceptTerm(index)) { // return index; // } else if (ascending) { // return incrementTermIndex(index); // } else { // return decrementTermIndex(index); // } // } // } // // Path: src/main/java/org/apache/solr/request/BidirectionalFacetResponseBuilder.java // public static class BaseTermIndexKey<K extends BaseTermIndexKey<K>> implements FacetKey<K> { // // public final int index; // // public BaseTermIndexKey(int index) { // this.index = index; // } // // @Override // public int compareTo(BaseTermIndexKey o) { // return Integer.compare(index, o.index); // } // // @Override // public String toString() { // return BaseTermIndexKey.class.getSimpleName() + "(index=" + index + ')'; // } // // } // // Path: src/main/java/org/apache/solr/request/BidirectionalFacetResponseBuilder.java // public static interface LimitMinder<T extends FieldType & FacetPayload, K extends FacetKey<K>> { // K startKey(); // K nextKey(K lastKey, Env<T, K> env); // void addEntry(Entry<String, Object> entry, Deque<Entry<String, Object>> entryBuilder); // boolean updateEntry(String term, String docId, SolrDocument doc, Deque<Entry<String, Object>> entryBuilder); // void removeTail(Deque<Entry<String, Object>> entryBuilder); // } // Path: src/main/java/org/apache/solr/request/DocBasedFacetResponseBuilder.java import java.io.IOException; import java.util.AbstractMap.SimpleImmutableEntry; import java.util.ArrayDeque; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.Deque; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.function.Predicate; import org.apache.lucene.document.Document; import org.apache.lucene.index.LeafReader; import org.apache.lucene.index.PostingsEnum; import org.apache.lucene.index.SortedSetDocValues; import org.apache.lucene.index.Term; import org.apache.lucene.search.Query; import org.apache.lucene.search.Sort; import org.apache.lucene.search.SortField; import org.apache.lucene.search.TermQuery; import org.apache.lucene.util.Bits; import org.apache.lucene.util.BytesRef; import org.apache.lucene.util.CharsRefBuilder; import org.apache.lucene.util.UnicodeUtil; import org.apache.solr.common.SolrDocument; import org.apache.solr.common.util.NamedList; import org.apache.solr.request.BidirectionalFacetResponseBuilder.BaseLocalTermEnv; import org.apache.solr.request.BidirectionalFacetResponseBuilder.BaseTermIndexKey; import org.apache.solr.request.BidirectionalFacetResponseBuilder.LimitMinder; import org.apache.solr.response.DocsStreamer; import org.apache.solr.schema.FieldType; import org.apache.solr.schema.SchemaField; import org.apache.solr.search.DocList; import org.apache.solr.search.DocSet; import org.apache.solr.search.SolrIndexSearcher; static String brToString(BytesRef br) { if (br == null) { return "null"; } else if (UnicodeUtil.BIG_TERM.bytesEquals(br)) { return "[UnicodeUtil.BIG_TERM]"; } else { return br.utf8ToString(); } } @Override public TermDocIndexKey decrementKey(TermDocIndexKey previousKey) { int termIndex = previousKey.index; BytesRef docId = previousKey.docId; do { while ((docId = decrementDocId(termIndex, docId)) != null) { int docIndex = acceptDoc(termIndex, docId); if (docIndex >= 0) { localDocIndex = docIndex; return termDocIndexKey = new TermDocIndexKey(termIndex, docId); } } docId = UnicodeUtil.BIG_TERM; } while ((termIndex = decrementTermIndex(termIndex)) >= 0); localDocIndex = -1; return termDocIndexKey = null; } @Override
public void addEntry(LimitMinder<T, TermDocIndexKey> limitMinder, TermDocIndexKey facetKey, Deque<Map.Entry<String, Object>> entryBuilder) throws IOException {
upenn-libraries/solrplugins
src/test/java/org/apache/solr/request/BidirectionalFacetResponseBuilderTest.java
// Path: src/main/java/org/apache/solr/request/BidirectionalFacetResponseBuilder.java // public static abstract class Env<T extends FieldType & FacetPayload, K extends FacetKey<K>> { // public final int offset; // public final int limit; // public final int targetIdx; // public final int mincount; // public final String fieldName; // public final T ft; // public final String ftDelim; // public final NamedList res; // // public Env(int offset, int limit, int targetIdx, int mincount, String fieldName, T ft, NamedList res) { // this.offset = offset; // this.limit = limit; // this.targetIdx = targetIdx; // this.mincount = mincount; // this.fieldName = fieldName; // this.ft = ft; // if (ft instanceof MultiSerializable) { // ftDelim = ((MultiSerializable)ft).getDelim(); // } else { // ftDelim = "\u0000"; // } // this.res = res; // } // // public abstract K incrementKey(K previousKey); // // public abstract K decrementKey(K previousKey); // // public abstract void addEntry(LimitMinder<T, K> limitMinder, K facetKey, Deque<Entry<String, Object>> entryBuilder) throws IOException; // // public abstract K targetKey() throws IOException; // // public abstract K targetKeyInit(boolean ascending) throws IOException; // // public abstract void initState(K key); // // public NamedList<Object> finalize(NamedList<Object> ret) { // return ret; // } // // } // // Path: src/main/java/org/apache/solr/request/BidirectionalFacetResponseBuilder.java // public static class SimpleTermIndexKey extends BaseTermIndexKey<SimpleTermIndexKey> { // // public SimpleTermIndexKey(int index) { // super(index); // } // // }
import java.io.IOException; import java.util.AbstractMap; import java.util.Arrays; import java.util.Deque; import java.util.Map; import org.apache.solr.common.util.NamedList; import org.apache.solr.request.BidirectionalFacetResponseBuilder.Env; import org.apache.solr.request.BidirectionalFacetResponseBuilder.SimpleTermIndexKey; import org.apache.solr.schema.FieldType; import org.junit.Test; import static org.junit.Assert.*;
runTest(1, 3, -1, 1, 2); } @Test public void testLargeNegativeOffsetWindowOOB() throws IOException { runTest(1, 1, -2, -1, 2); } @Test public void testPositiveOffsetWindowOOB() throws IOException { runTest(1, 0, 1, 0, 0); } @Test public void testLargePositiveOffsetWindowOOB() throws IOException { runTest(1, 0, 2, 0, 0); runTest(1, 1, 2, 1, 0); } private void runTest(int limit, int targetIdx, int requestedOffset, Integer expectedOffset, int... expectedIndices) throws IOException { runTest(counts, limit, targetIdx, requestedOffset, expectedOffset, expectedIndices); } private void runTest(int[] counts, int limit, int targetIdx, int requestedOffset, Integer expectedOffset, int... expectedIndices) throws IOException { String targetDoc = null; int mincount = 1; String fieldName = "myField"; T ft = null; NamedList exp = buildExpected(expectedOffset, expectedIndices); NamedList actual = new NamedList(3);
// Path: src/main/java/org/apache/solr/request/BidirectionalFacetResponseBuilder.java // public static abstract class Env<T extends FieldType & FacetPayload, K extends FacetKey<K>> { // public final int offset; // public final int limit; // public final int targetIdx; // public final int mincount; // public final String fieldName; // public final T ft; // public final String ftDelim; // public final NamedList res; // // public Env(int offset, int limit, int targetIdx, int mincount, String fieldName, T ft, NamedList res) { // this.offset = offset; // this.limit = limit; // this.targetIdx = targetIdx; // this.mincount = mincount; // this.fieldName = fieldName; // this.ft = ft; // if (ft instanceof MultiSerializable) { // ftDelim = ((MultiSerializable)ft).getDelim(); // } else { // ftDelim = "\u0000"; // } // this.res = res; // } // // public abstract K incrementKey(K previousKey); // // public abstract K decrementKey(K previousKey); // // public abstract void addEntry(LimitMinder<T, K> limitMinder, K facetKey, Deque<Entry<String, Object>> entryBuilder) throws IOException; // // public abstract K targetKey() throws IOException; // // public abstract K targetKeyInit(boolean ascending) throws IOException; // // public abstract void initState(K key); // // public NamedList<Object> finalize(NamedList<Object> ret) { // return ret; // } // // } // // Path: src/main/java/org/apache/solr/request/BidirectionalFacetResponseBuilder.java // public static class SimpleTermIndexKey extends BaseTermIndexKey<SimpleTermIndexKey> { // // public SimpleTermIndexKey(int index) { // super(index); // } // // } // Path: src/test/java/org/apache/solr/request/BidirectionalFacetResponseBuilderTest.java import java.io.IOException; import java.util.AbstractMap; import java.util.Arrays; import java.util.Deque; import java.util.Map; import org.apache.solr.common.util.NamedList; import org.apache.solr.request.BidirectionalFacetResponseBuilder.Env; import org.apache.solr.request.BidirectionalFacetResponseBuilder.SimpleTermIndexKey; import org.apache.solr.schema.FieldType; import org.junit.Test; import static org.junit.Assert.*; runTest(1, 3, -1, 1, 2); } @Test public void testLargeNegativeOffsetWindowOOB() throws IOException { runTest(1, 1, -2, -1, 2); } @Test public void testPositiveOffsetWindowOOB() throws IOException { runTest(1, 0, 1, 0, 0); } @Test public void testLargePositiveOffsetWindowOOB() throws IOException { runTest(1, 0, 2, 0, 0); runTest(1, 1, 2, 1, 0); } private void runTest(int limit, int targetIdx, int requestedOffset, Integer expectedOffset, int... expectedIndices) throws IOException { runTest(counts, limit, targetIdx, requestedOffset, expectedOffset, expectedIndices); } private void runTest(int[] counts, int limit, int targetIdx, int requestedOffset, Integer expectedOffset, int... expectedIndices) throws IOException { String targetDoc = null; int mincount = 1; String fieldName = "myField"; T ft = null; NamedList exp = buildExpected(expectedOffset, expectedIndices); NamedList actual = new NamedList(3);
Env<T, SimpleTermIndexKey> env = new TestEnv<>(requestedOffset, limit, targetIdx, mincount, fieldName, ft, actual, counts);
upenn-libraries/solrplugins
src/test/java/org/apache/solr/request/BidirectionalFacetResponseBuilderTest.java
// Path: src/main/java/org/apache/solr/request/BidirectionalFacetResponseBuilder.java // public static abstract class Env<T extends FieldType & FacetPayload, K extends FacetKey<K>> { // public final int offset; // public final int limit; // public final int targetIdx; // public final int mincount; // public final String fieldName; // public final T ft; // public final String ftDelim; // public final NamedList res; // // public Env(int offset, int limit, int targetIdx, int mincount, String fieldName, T ft, NamedList res) { // this.offset = offset; // this.limit = limit; // this.targetIdx = targetIdx; // this.mincount = mincount; // this.fieldName = fieldName; // this.ft = ft; // if (ft instanceof MultiSerializable) { // ftDelim = ((MultiSerializable)ft).getDelim(); // } else { // ftDelim = "\u0000"; // } // this.res = res; // } // // public abstract K incrementKey(K previousKey); // // public abstract K decrementKey(K previousKey); // // public abstract void addEntry(LimitMinder<T, K> limitMinder, K facetKey, Deque<Entry<String, Object>> entryBuilder) throws IOException; // // public abstract K targetKey() throws IOException; // // public abstract K targetKeyInit(boolean ascending) throws IOException; // // public abstract void initState(K key); // // public NamedList<Object> finalize(NamedList<Object> ret) { // return ret; // } // // } // // Path: src/main/java/org/apache/solr/request/BidirectionalFacetResponseBuilder.java // public static class SimpleTermIndexKey extends BaseTermIndexKey<SimpleTermIndexKey> { // // public SimpleTermIndexKey(int index) { // super(index); // } // // }
import java.io.IOException; import java.util.AbstractMap; import java.util.Arrays; import java.util.Deque; import java.util.Map; import org.apache.solr.common.util.NamedList; import org.apache.solr.request.BidirectionalFacetResponseBuilder.Env; import org.apache.solr.request.BidirectionalFacetResponseBuilder.SimpleTermIndexKey; import org.apache.solr.schema.FieldType; import org.junit.Test; import static org.junit.Assert.*;
runTest(1, 3, -1, 1, 2); } @Test public void testLargeNegativeOffsetWindowOOB() throws IOException { runTest(1, 1, -2, -1, 2); } @Test public void testPositiveOffsetWindowOOB() throws IOException { runTest(1, 0, 1, 0, 0); } @Test public void testLargePositiveOffsetWindowOOB() throws IOException { runTest(1, 0, 2, 0, 0); runTest(1, 1, 2, 1, 0); } private void runTest(int limit, int targetIdx, int requestedOffset, Integer expectedOffset, int... expectedIndices) throws IOException { runTest(counts, limit, targetIdx, requestedOffset, expectedOffset, expectedIndices); } private void runTest(int[] counts, int limit, int targetIdx, int requestedOffset, Integer expectedOffset, int... expectedIndices) throws IOException { String targetDoc = null; int mincount = 1; String fieldName = "myField"; T ft = null; NamedList exp = buildExpected(expectedOffset, expectedIndices); NamedList actual = new NamedList(3);
// Path: src/main/java/org/apache/solr/request/BidirectionalFacetResponseBuilder.java // public static abstract class Env<T extends FieldType & FacetPayload, K extends FacetKey<K>> { // public final int offset; // public final int limit; // public final int targetIdx; // public final int mincount; // public final String fieldName; // public final T ft; // public final String ftDelim; // public final NamedList res; // // public Env(int offset, int limit, int targetIdx, int mincount, String fieldName, T ft, NamedList res) { // this.offset = offset; // this.limit = limit; // this.targetIdx = targetIdx; // this.mincount = mincount; // this.fieldName = fieldName; // this.ft = ft; // if (ft instanceof MultiSerializable) { // ftDelim = ((MultiSerializable)ft).getDelim(); // } else { // ftDelim = "\u0000"; // } // this.res = res; // } // // public abstract K incrementKey(K previousKey); // // public abstract K decrementKey(K previousKey); // // public abstract void addEntry(LimitMinder<T, K> limitMinder, K facetKey, Deque<Entry<String, Object>> entryBuilder) throws IOException; // // public abstract K targetKey() throws IOException; // // public abstract K targetKeyInit(boolean ascending) throws IOException; // // public abstract void initState(K key); // // public NamedList<Object> finalize(NamedList<Object> ret) { // return ret; // } // // } // // Path: src/main/java/org/apache/solr/request/BidirectionalFacetResponseBuilder.java // public static class SimpleTermIndexKey extends BaseTermIndexKey<SimpleTermIndexKey> { // // public SimpleTermIndexKey(int index) { // super(index); // } // // } // Path: src/test/java/org/apache/solr/request/BidirectionalFacetResponseBuilderTest.java import java.io.IOException; import java.util.AbstractMap; import java.util.Arrays; import java.util.Deque; import java.util.Map; import org.apache.solr.common.util.NamedList; import org.apache.solr.request.BidirectionalFacetResponseBuilder.Env; import org.apache.solr.request.BidirectionalFacetResponseBuilder.SimpleTermIndexKey; import org.apache.solr.schema.FieldType; import org.junit.Test; import static org.junit.Assert.*; runTest(1, 3, -1, 1, 2); } @Test public void testLargeNegativeOffsetWindowOOB() throws IOException { runTest(1, 1, -2, -1, 2); } @Test public void testPositiveOffsetWindowOOB() throws IOException { runTest(1, 0, 1, 0, 0); } @Test public void testLargePositiveOffsetWindowOOB() throws IOException { runTest(1, 0, 2, 0, 0); runTest(1, 1, 2, 1, 0); } private void runTest(int limit, int targetIdx, int requestedOffset, Integer expectedOffset, int... expectedIndices) throws IOException { runTest(counts, limit, targetIdx, requestedOffset, expectedOffset, expectedIndices); } private void runTest(int[] counts, int limit, int targetIdx, int requestedOffset, Integer expectedOffset, int... expectedIndices) throws IOException { String targetDoc = null; int mincount = 1; String fieldName = "myField"; T ft = null; NamedList exp = buildExpected(expectedOffset, expectedIndices); NamedList actual = new NamedList(3);
Env<T, SimpleTermIndexKey> env = new TestEnv<>(requestedOffset, limit, targetIdx, mincount, fieldName, ft, actual, counts);
ITVlab/TvAppRepo
app/src/main/java/news/androidtv/tvapprepo/presenters/OptionsCardPresenter.java
// Path: app/src/main/java/news/androidtv/tvapprepo/model/SettingOption.java // public class SettingOption { // private Drawable mIcon; // private String mTitle; // private OnClickListener mOnClickListener; // // public SettingOption(Drawable drawable, String text, OnClickListener onClickListener) { // mIcon = drawable; // mTitle = text; // mOnClickListener = onClickListener; // } // // public Drawable getDrawable() { // return mIcon; // } // // public String getText() { // return mTitle; // } // // public OnClickListener getClickListener() { // return mOnClickListener; // } // // public interface OnClickListener { // void onClick(); // } // }
import android.support.v17.leanback.widget.ImageCardView; import android.support.v17.leanback.widget.Presenter; import android.view.ContextThemeWrapper; import android.view.ViewGroup; import android.widget.ImageView; import news.androidtv.tvapprepo.R; import news.androidtv.tvapprepo.model.SettingOption;
package news.androidtv.tvapprepo.presenters; /** * A presenter which can be used to show options with an optional title along the bottom. * * @author Nick * @version 2016.09.04 */ public class OptionsCardPresenter extends CardPresenter { private ContextThemeWrapper contextThemeWrapper; @Override public ViewHolder onCreateViewHolder(ViewGroup parent) { if (contextThemeWrapper == null) { contextThemeWrapper = new ContextThemeWrapper(parent.getContext(), R.style.OptionsImageCardViewStyle); } ImageCardView cardView = new ImageCardView(contextThemeWrapper); cardView.setFocusable(true); cardView.setFocusableInTouchMode(true); cardView.setBackgroundColor(parent.getResources().getColor(R.color.primaryDark)); return new ViewHolder(cardView); } @Override public void onBindViewHolder(Presenter.ViewHolder viewHolder, Object item) {
// Path: app/src/main/java/news/androidtv/tvapprepo/model/SettingOption.java // public class SettingOption { // private Drawable mIcon; // private String mTitle; // private OnClickListener mOnClickListener; // // public SettingOption(Drawable drawable, String text, OnClickListener onClickListener) { // mIcon = drawable; // mTitle = text; // mOnClickListener = onClickListener; // } // // public Drawable getDrawable() { // return mIcon; // } // // public String getText() { // return mTitle; // } // // public OnClickListener getClickListener() { // return mOnClickListener; // } // // public interface OnClickListener { // void onClick(); // } // } // Path: app/src/main/java/news/androidtv/tvapprepo/presenters/OptionsCardPresenter.java import android.support.v17.leanback.widget.ImageCardView; import android.support.v17.leanback.widget.Presenter; import android.view.ContextThemeWrapper; import android.view.ViewGroup; import android.widget.ImageView; import news.androidtv.tvapprepo.R; import news.androidtv.tvapprepo.model.SettingOption; package news.androidtv.tvapprepo.presenters; /** * A presenter which can be used to show options with an optional title along the bottom. * * @author Nick * @version 2016.09.04 */ public class OptionsCardPresenter extends CardPresenter { private ContextThemeWrapper contextThemeWrapper; @Override public ViewHolder onCreateViewHolder(ViewGroup parent) { if (contextThemeWrapper == null) { contextThemeWrapper = new ContextThemeWrapper(parent.getContext(), R.style.OptionsImageCardViewStyle); } ImageCardView cardView = new ImageCardView(contextThemeWrapper); cardView.setFocusable(true); cardView.setFocusableInTouchMode(true); cardView.setBackgroundColor(parent.getResources().getColor(R.color.primaryDark)); return new ViewHolder(cardView); } @Override public void onBindViewHolder(Presenter.ViewHolder viewHolder, Object item) {
final SettingOption option = (SettingOption) item;
ITVlab/TvAppRepo
app/src/androidTest/java/news/androidtv/tvapprepo/IntentsInstrumentationTest.java
// Path: app/src/main/java/news/androidtv/tvapprepo/intents/IntentUriGenerator.java // public class IntentUriGenerator { // public static String generateWebBookmark(String url) { // Intent i = new Intent(Intent.ACTION_VIEW); // i.setData(Uri.parse(url)); // return i.toUri(Intent.URI_INTENT_SCHEME); // } // // public static String generateVideoPlayback(File myFile) { // MimeTypeMap myMime = MimeTypeMap.getSingleton(); // Intent newIntent = new Intent(Intent.ACTION_VIEW); // String mimeType = myMime.getMimeTypeFromExtension(fileExt(myFile.getAbsolutePath()).substring(1)); // newIntent.setDataAndType(Uri.fromFile(myFile),mimeType); // newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // return newIntent.toUri(Intent.URI_INTENT_SCHEME); // } // // public static String generateFileOpen(File myFile) { // return generateVideoPlayback(myFile); // } // // public static String generateActivityShortcut(ComponentName componentName) { // Intent newIntent = new Intent(); // newIntent.setComponent(componentName); // return newIntent.toUri(Intent.URI_INTENT_SCHEME); // } // // private static String fileExt(String url) { // if (url.indexOf("?") > -1) { // url = url.substring(0, url.indexOf("?")); // } // if (url.lastIndexOf(".") == -1) { // return null; // } else { // String ext = url.substring(url.lastIndexOf(".") + 1); // if (ext.indexOf("%") > -1) { // ext = ext.substring(0, ext.indexOf("%")); // } // if (ext.indexOf("/") > -1) { // ext = ext.substring(0, ext.indexOf("/")); // } // return ext.toLowerCase(); // } // } // }
import android.app.Application; import android.content.ComponentName; import android.content.Intent; import android.test.ApplicationTestCase; import android.util.Log; import java.io.File; import java.net.URISyntaxException; import news.androidtv.tvapprepo.intents.IntentUriGenerator;
package news.androidtv.tvapprepo; /** * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a> */ public class IntentsInstrumentationTest extends ApplicationTestCase<Application> { public static final String TAG = IntentsInstrumentationTest.class.getSimpleName(); public IntentsInstrumentationTest() { super(Application.class); } public void testWebBookmarks() { final String expected = "intent://google.com#Intent;scheme=http;end";
// Path: app/src/main/java/news/androidtv/tvapprepo/intents/IntentUriGenerator.java // public class IntentUriGenerator { // public static String generateWebBookmark(String url) { // Intent i = new Intent(Intent.ACTION_VIEW); // i.setData(Uri.parse(url)); // return i.toUri(Intent.URI_INTENT_SCHEME); // } // // public static String generateVideoPlayback(File myFile) { // MimeTypeMap myMime = MimeTypeMap.getSingleton(); // Intent newIntent = new Intent(Intent.ACTION_VIEW); // String mimeType = myMime.getMimeTypeFromExtension(fileExt(myFile.getAbsolutePath()).substring(1)); // newIntent.setDataAndType(Uri.fromFile(myFile),mimeType); // newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // return newIntent.toUri(Intent.URI_INTENT_SCHEME); // } // // public static String generateFileOpen(File myFile) { // return generateVideoPlayback(myFile); // } // // public static String generateActivityShortcut(ComponentName componentName) { // Intent newIntent = new Intent(); // newIntent.setComponent(componentName); // return newIntent.toUri(Intent.URI_INTENT_SCHEME); // } // // private static String fileExt(String url) { // if (url.indexOf("?") > -1) { // url = url.substring(0, url.indexOf("?")); // } // if (url.lastIndexOf(".") == -1) { // return null; // } else { // String ext = url.substring(url.lastIndexOf(".") + 1); // if (ext.indexOf("%") > -1) { // ext = ext.substring(0, ext.indexOf("%")); // } // if (ext.indexOf("/") > -1) { // ext = ext.substring(0, ext.indexOf("/")); // } // return ext.toLowerCase(); // } // } // } // Path: app/src/androidTest/java/news/androidtv/tvapprepo/IntentsInstrumentationTest.java import android.app.Application; import android.content.ComponentName; import android.content.Intent; import android.test.ApplicationTestCase; import android.util.Log; import java.io.File; import java.net.URISyntaxException; import news.androidtv.tvapprepo.intents.IntentUriGenerator; package news.androidtv.tvapprepo; /** * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a> */ public class IntentsInstrumentationTest extends ApplicationTestCase<Application> { public static final String TAG = IntentsInstrumentationTest.class.getSimpleName(); public IntentsInstrumentationTest() { super(Application.class); } public void testWebBookmarks() { final String expected = "intent://google.com#Intent;scheme=http;end";
String actual = IntentUriGenerator.generateWebBookmark("http://google.com");
ITVlab/TvAppRepo
app/src/main/java/news/androidtv/tvapprepo/activities/BrowseErrorActivity.java
// Path: app/src/main/java/news/androidtv/tvapprepo/fragments/ErrorFragment.java // public class ErrorFragment extends android.support.v17.leanback.app.ErrorFragment { // private static final String TAG = "ErrorFragment"; // private static final boolean TRANSLUCENT = true; // // @Override // public void onCreate(Bundle savedInstanceState) { // Log.d(TAG, "onCreate"); // super.onCreate(savedInstanceState); // setTitle(getResources().getString(R.string.app_name)); // } // // public void setErrorContent() { // setImageDrawable(getResources().getDrawable(R.drawable.lb_ic_sad_cloud)); // setMessage(getResources().getString(R.string.error_fragment_message)); // setDefaultBackground(TRANSLUCENT); // // setButtonText(getResources().getString(R.string.dismiss_error)); // setButtonClickListener(new View.OnClickListener() { // @Override // public void onClick(View arg0) { // getFragmentManager().beginTransaction().remove(ErrorFragment.this).commit(); // } // }); // } // }
import android.app.Activity; import android.app.Fragment; import android.os.Bundle; import android.os.Handler; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.ProgressBar; import news.androidtv.tvapprepo.fragments.ErrorFragment; import news.androidtv.tvapprepo.R;
/* * Copyright (C) 2014 The Android Open Source Project * * 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 news.androidtv.tvapprepo.activities; /* * BrowseErrorActivity shows how to use ErrorFragment */ public class BrowseErrorActivity extends Activity { private static int TIMER_DELAY = 3000; private static int SPINNER_WIDTH = 100; private static int SPINNER_HEIGHT = 100;
// Path: app/src/main/java/news/androidtv/tvapprepo/fragments/ErrorFragment.java // public class ErrorFragment extends android.support.v17.leanback.app.ErrorFragment { // private static final String TAG = "ErrorFragment"; // private static final boolean TRANSLUCENT = true; // // @Override // public void onCreate(Bundle savedInstanceState) { // Log.d(TAG, "onCreate"); // super.onCreate(savedInstanceState); // setTitle(getResources().getString(R.string.app_name)); // } // // public void setErrorContent() { // setImageDrawable(getResources().getDrawable(R.drawable.lb_ic_sad_cloud)); // setMessage(getResources().getString(R.string.error_fragment_message)); // setDefaultBackground(TRANSLUCENT); // // setButtonText(getResources().getString(R.string.dismiss_error)); // setButtonClickListener(new View.OnClickListener() { // @Override // public void onClick(View arg0) { // getFragmentManager().beginTransaction().remove(ErrorFragment.this).commit(); // } // }); // } // } // Path: app/src/main/java/news/androidtv/tvapprepo/activities/BrowseErrorActivity.java import android.app.Activity; import android.app.Fragment; import android.os.Bundle; import android.os.Handler; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.ProgressBar; import news.androidtv.tvapprepo.fragments.ErrorFragment; import news.androidtv.tvapprepo.R; /* * Copyright (C) 2014 The Android Open Source Project * * 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 news.androidtv.tvapprepo.activities; /* * BrowseErrorActivity shows how to use ErrorFragment */ public class BrowseErrorActivity extends Activity { private static int TIMER_DELAY = 3000; private static int SPINNER_WIDTH = 100; private static int SPINNER_HEIGHT = 100;
private ErrorFragment mErrorFragment;
ITVlab/TvAppRepo
app/src/main/java/news/androidtv/tvapprepo/model/AdvancedOptions.java
// Path: app/src/main/java/news/androidtv/tvapprepo/utils/ShortcutPostTask.java // public class ShortcutPostTask { // private static final String TAG = ShortcutPostTask.class.getSimpleName(); // // private static final int TIMEOUT = 90 * 1000; // 90 seconds // // private static final String SUBMISSION_URL = // "http://atvlauncher.trekgonewild.de/index_tvapprepo.php"; // private static final String FORM_APP_NAME = "app_name"; // private static final String FORM_APP_PACKAGE = "app_package"; // private static final String FORM_APP_CATEGORY = "app_category"; // private static final String FORM_APP_LOGO = "app_logo"; // private static final String FORM_APP_BANNER = "app_banner"; // private static final String FORM_UNIQUE_PACKAGE_NAME = "unique"; // private static final String FORM_INTENT_URI = "app_intent"; // private static final String FORM_JSON = "json"; // public static final String CATEGORY_GAMES = "games"; // public static final String CATEGORY_APPS = "apps"; // // private ShortcutPostTask() { // } // // public static void generateShortcut(final Context context, final ResolveInfo app, // final AdvancedOptions options, final Callback callback) { // RequestQueue queue = Volley.newRequestQueue(context); // // VolleyMultipartRequest sr = new VolleyMultipartRequest(Request.Method.POST, // SUBMISSION_URL, // new Response.Listener<NetworkResponse>() { // @Override // public void onResponse(NetworkResponse response) { // Log.d(TAG, "Response: " + new String(response.data)); // callback.onResponse(response); // } // }, new Response.ErrorListener() { // @Override // public void onErrorResponse(VolleyError error) { // if (error.networkResponse != null) { // Log.e(TAG, "Error: " + error.networkResponse.headers); // Log.e(TAG, "Error: " + new String(error.networkResponse.data)); // } // Log.e(TAG, "Error: " + error.getMessage()); // Log.d(TAG, error.toString()); // callback.onError(error); // } // }){ // @Override // protected Map<String,String> getParams(){ // Map<String,String> params = new HashMap<>(); // if (app != null) { // params.put(FORM_APP_NAME, app.activityInfo.loadLabel(context.getPackageManager()).toString()); // params.put(FORM_APP_PACKAGE, app.activityInfo.applicationInfo.packageName); // } else if (!options.getCustomLabel().isEmpty()) { // params.put(FORM_APP_NAME, options.getCustomLabel()); // params.put(FORM_APP_PACKAGE, "news.androidtv.tvapprepo"); // Use our own package name // options.setUniquePackageName(true); // Force to unique. // } // if (!options.getCategory().isEmpty()) { // params.put(FORM_APP_CATEGORY, options.getCategory()); // } else { // params.put(FORM_APP_CATEGORY, CATEGORY_APPS); // } // if (!options.getIntentUri().isEmpty()) { // params.put(FORM_INTENT_URI, options.getIntentUri()); // } // params.put(FORM_UNIQUE_PACKAGE_NAME, options.isUnique()+""); // params.put(FORM_JSON, "true"); // return params; // } // // @Override // protected Map<String, DataPart> getByteData() { // Map<String, DataPart> params = new HashMap<>(); // // file name could found file base or direct access from real path // // for now just get bitmap data from ImageView // if (options.getIcon() != null) { // params.put(FORM_APP_LOGO, new DataPart("file_logo.png", options.getIcon(), // "image/png")); // } else if (app != null) { // try { // byte[] imageData = VolleyMultipartRequest.getFileDataFromDrawable(context, // app.activityInfo.loadIcon(context.getPackageManager())); // params.put(FORM_APP_LOGO, new DataPart("file_logo.png", imageData, // "image/png")); // } catch (ClassCastException e) { // Toast.makeText(context, R.string.error_getting_logo, // Toast.LENGTH_SHORT).show(); // } // } // if (options.getBanner() != null) { // params.put(FORM_APP_BANNER, new DataPart("file_banner.png", options.getBanner(), // "image/png")); // } // return params; // } // }; // try { // Log.d(TAG, sr.getHeaders().toString()); // Log.d(TAG, new String(sr.getBody())); // Log.d(TAG, sr.getBodyContentType()); // } catch (AuthFailureError authFailureError) { // authFailureError.printStackTrace(); // } // sr.setRetryPolicy(new DefaultRetryPolicy(TIMEOUT, 1, 0)); // queue.add(sr); // } // // public interface Callback { // void onResponse(NetworkResponse response); // void onError(VolleyError error); // } // }
import android.app.Activity; import android.content.Context; import android.graphics.Bitmap; import android.os.Handler; import android.os.Looper; import android.os.Parcel; import android.os.Parcelable; import android.util.Log; import com.bumptech.glide.Glide; import org.json.JSONException; import org.json.JSONObject; import java.io.ByteArrayOutputStream; import java.util.concurrent.ExecutionException; import news.androidtv.tvapprepo.utils.ShortcutPostTask;
private byte[] mIconData = null; private byte[] mBannerData = null; private Context mContext = null; public AdvancedOptions(Context context) { if (context == null) { throw new NullPointerException("Context cannot be null!"); } mContext = context; } public AdvancedOptions setBannerUrl(String bannerUrl) { if (bannerUrl == null || bannerUrl.isEmpty()) { // Exit early. return this; } mReady++; mBannerUrl = bannerUrl; // Download from Glide. downloadBanner(mContext, bannerUrl, new GlideCallback() { @Override public void onDone(byte[] binaryData) { mBannerData = binaryData; mReady--; } }); return this; } public AdvancedOptions setIsGame(boolean isGame) {
// Path: app/src/main/java/news/androidtv/tvapprepo/utils/ShortcutPostTask.java // public class ShortcutPostTask { // private static final String TAG = ShortcutPostTask.class.getSimpleName(); // // private static final int TIMEOUT = 90 * 1000; // 90 seconds // // private static final String SUBMISSION_URL = // "http://atvlauncher.trekgonewild.de/index_tvapprepo.php"; // private static final String FORM_APP_NAME = "app_name"; // private static final String FORM_APP_PACKAGE = "app_package"; // private static final String FORM_APP_CATEGORY = "app_category"; // private static final String FORM_APP_LOGO = "app_logo"; // private static final String FORM_APP_BANNER = "app_banner"; // private static final String FORM_UNIQUE_PACKAGE_NAME = "unique"; // private static final String FORM_INTENT_URI = "app_intent"; // private static final String FORM_JSON = "json"; // public static final String CATEGORY_GAMES = "games"; // public static final String CATEGORY_APPS = "apps"; // // private ShortcutPostTask() { // } // // public static void generateShortcut(final Context context, final ResolveInfo app, // final AdvancedOptions options, final Callback callback) { // RequestQueue queue = Volley.newRequestQueue(context); // // VolleyMultipartRequest sr = new VolleyMultipartRequest(Request.Method.POST, // SUBMISSION_URL, // new Response.Listener<NetworkResponse>() { // @Override // public void onResponse(NetworkResponse response) { // Log.d(TAG, "Response: " + new String(response.data)); // callback.onResponse(response); // } // }, new Response.ErrorListener() { // @Override // public void onErrorResponse(VolleyError error) { // if (error.networkResponse != null) { // Log.e(TAG, "Error: " + error.networkResponse.headers); // Log.e(TAG, "Error: " + new String(error.networkResponse.data)); // } // Log.e(TAG, "Error: " + error.getMessage()); // Log.d(TAG, error.toString()); // callback.onError(error); // } // }){ // @Override // protected Map<String,String> getParams(){ // Map<String,String> params = new HashMap<>(); // if (app != null) { // params.put(FORM_APP_NAME, app.activityInfo.loadLabel(context.getPackageManager()).toString()); // params.put(FORM_APP_PACKAGE, app.activityInfo.applicationInfo.packageName); // } else if (!options.getCustomLabel().isEmpty()) { // params.put(FORM_APP_NAME, options.getCustomLabel()); // params.put(FORM_APP_PACKAGE, "news.androidtv.tvapprepo"); // Use our own package name // options.setUniquePackageName(true); // Force to unique. // } // if (!options.getCategory().isEmpty()) { // params.put(FORM_APP_CATEGORY, options.getCategory()); // } else { // params.put(FORM_APP_CATEGORY, CATEGORY_APPS); // } // if (!options.getIntentUri().isEmpty()) { // params.put(FORM_INTENT_URI, options.getIntentUri()); // } // params.put(FORM_UNIQUE_PACKAGE_NAME, options.isUnique()+""); // params.put(FORM_JSON, "true"); // return params; // } // // @Override // protected Map<String, DataPart> getByteData() { // Map<String, DataPart> params = new HashMap<>(); // // file name could found file base or direct access from real path // // for now just get bitmap data from ImageView // if (options.getIcon() != null) { // params.put(FORM_APP_LOGO, new DataPart("file_logo.png", options.getIcon(), // "image/png")); // } else if (app != null) { // try { // byte[] imageData = VolleyMultipartRequest.getFileDataFromDrawable(context, // app.activityInfo.loadIcon(context.getPackageManager())); // params.put(FORM_APP_LOGO, new DataPart("file_logo.png", imageData, // "image/png")); // } catch (ClassCastException e) { // Toast.makeText(context, R.string.error_getting_logo, // Toast.LENGTH_SHORT).show(); // } // } // if (options.getBanner() != null) { // params.put(FORM_APP_BANNER, new DataPart("file_banner.png", options.getBanner(), // "image/png")); // } // return params; // } // }; // try { // Log.d(TAG, sr.getHeaders().toString()); // Log.d(TAG, new String(sr.getBody())); // Log.d(TAG, sr.getBodyContentType()); // } catch (AuthFailureError authFailureError) { // authFailureError.printStackTrace(); // } // sr.setRetryPolicy(new DefaultRetryPolicy(TIMEOUT, 1, 0)); // queue.add(sr); // } // // public interface Callback { // void onResponse(NetworkResponse response); // void onError(VolleyError error); // } // } // Path: app/src/main/java/news/androidtv/tvapprepo/model/AdvancedOptions.java import android.app.Activity; import android.content.Context; import android.graphics.Bitmap; import android.os.Handler; import android.os.Looper; import android.os.Parcel; import android.os.Parcelable; import android.util.Log; import com.bumptech.glide.Glide; import org.json.JSONException; import org.json.JSONObject; import java.io.ByteArrayOutputStream; import java.util.concurrent.ExecutionException; import news.androidtv.tvapprepo.utils.ShortcutPostTask; private byte[] mIconData = null; private byte[] mBannerData = null; private Context mContext = null; public AdvancedOptions(Context context) { if (context == null) { throw new NullPointerException("Context cannot be null!"); } mContext = context; } public AdvancedOptions setBannerUrl(String bannerUrl) { if (bannerUrl == null || bannerUrl.isEmpty()) { // Exit early. return this; } mReady++; mBannerUrl = bannerUrl; // Download from Glide. downloadBanner(mContext, bannerUrl, new GlideCallback() { @Override public void onDone(byte[] binaryData) { mBannerData = binaryData; mReady--; } }); return this; } public AdvancedOptions setIsGame(boolean isGame) {
mCategory = (isGame) ? ShortcutPostTask.CATEGORY_GAMES : ShortcutPostTask.CATEGORY_APPS;
EvilBT/HDImageView
library/src/main/java/xyz/zpayh/hdimage/datasource/DefaultBitmapDataSource.java
// Path: library/src/main/java/xyz/zpayh/hdimage/core/HDImageViewFactory.java // public class HDImageViewFactory { // private static HDImageViewFactory sInstance = null; // // private static HDImageViewFactory sDefaultInstance = null; // // public static HDImageViewFactory getInstance(){ // if (sInstance == null){ // return Preconditions.checkNotNull(sDefaultInstance, "Default HDImageViewFactory was not initialized!"); // } // return sInstance; // } // // public static void initializeDefault(Context context){ // if (sDefaultInstance == null){ // synchronized (HDImageViewFactory.class){ // if (sDefaultInstance == null){ // sDefaultInstance = new HDImageViewFactory(HDImageViewConfig.newBuilder(context.getApplicationContext()).build()); // } // } // } // } // // public static void initialize(Context context){ // initialize(HDImageViewConfig.newBuilder(context.getApplicationContext()).build()); // } // // public static void initialize(HDImageViewConfig config){ // sInstance = new HDImageViewFactory(config); // } // // private final HDImageViewConfig mConfig; // // public HDImageViewFactory(HDImageViewConfig config){ // mConfig = Preconditions.checkNotNull(config); // } // // public Interpolator getScaleAnimationInterpolator() { // return mConfig.getScaleAnimationInterpolator(); // } // // public Interpolator getTranslationAnimationInterpolator() { // return mConfig.getTranslationAnimationInterpolator(); // } // // public List<Interceptor> getDataSourceInterceptor(){ // return mConfig.getInterceptors(); // } // // public List<OrientationInterceptor> getOrientationInterceptor() { // return mConfig.getOrientationInterceptors(); // } // // public Bitmap.Config getBitmapConfig() { // return mConfig.getBitmapConfig(); // } // }
import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.BitmapRegionDecoder; import android.graphics.Point; import android.graphics.Rect; import android.net.Uri; import androidx.annotation.NonNull; import java.io.IOException; import xyz.zpayh.hdimage.core.HDImageViewFactory;
mDecoder = getDecoderWithInterceptorChain(uri); if (mDecoder != null) { if (dimensions != null){ dimensions.set(mDecoder.getWidth(), mDecoder.getHeight()); } if (listener != null){ listener.success(); } }else{ if (listener != null){ listener.failed(new IOException("init failed")); } } } catch (IOException e) { e.printStackTrace(); if (listener != null){ listener.failed(e); } } } @Override public Bitmap decode(Rect sRect, int sampleSize) { if (mDecoder == null){ return null; } synchronized (mDecoderLock) { BitmapFactory.Options options = new BitmapFactory.Options(); options.inSampleSize = sampleSize; // Default RGB_565
// Path: library/src/main/java/xyz/zpayh/hdimage/core/HDImageViewFactory.java // public class HDImageViewFactory { // private static HDImageViewFactory sInstance = null; // // private static HDImageViewFactory sDefaultInstance = null; // // public static HDImageViewFactory getInstance(){ // if (sInstance == null){ // return Preconditions.checkNotNull(sDefaultInstance, "Default HDImageViewFactory was not initialized!"); // } // return sInstance; // } // // public static void initializeDefault(Context context){ // if (sDefaultInstance == null){ // synchronized (HDImageViewFactory.class){ // if (sDefaultInstance == null){ // sDefaultInstance = new HDImageViewFactory(HDImageViewConfig.newBuilder(context.getApplicationContext()).build()); // } // } // } // } // // public static void initialize(Context context){ // initialize(HDImageViewConfig.newBuilder(context.getApplicationContext()).build()); // } // // public static void initialize(HDImageViewConfig config){ // sInstance = new HDImageViewFactory(config); // } // // private final HDImageViewConfig mConfig; // // public HDImageViewFactory(HDImageViewConfig config){ // mConfig = Preconditions.checkNotNull(config); // } // // public Interpolator getScaleAnimationInterpolator() { // return mConfig.getScaleAnimationInterpolator(); // } // // public Interpolator getTranslationAnimationInterpolator() { // return mConfig.getTranslationAnimationInterpolator(); // } // // public List<Interceptor> getDataSourceInterceptor(){ // return mConfig.getInterceptors(); // } // // public List<OrientationInterceptor> getOrientationInterceptor() { // return mConfig.getOrientationInterceptors(); // } // // public Bitmap.Config getBitmapConfig() { // return mConfig.getBitmapConfig(); // } // } // Path: library/src/main/java/xyz/zpayh/hdimage/datasource/DefaultBitmapDataSource.java import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.BitmapRegionDecoder; import android.graphics.Point; import android.graphics.Rect; import android.net.Uri; import androidx.annotation.NonNull; import java.io.IOException; import xyz.zpayh.hdimage.core.HDImageViewFactory; mDecoder = getDecoderWithInterceptorChain(uri); if (mDecoder != null) { if (dimensions != null){ dimensions.set(mDecoder.getWidth(), mDecoder.getHeight()); } if (listener != null){ listener.success(); } }else{ if (listener != null){ listener.failed(new IOException("init failed")); } } } catch (IOException e) { e.printStackTrace(); if (listener != null){ listener.failed(e); } } } @Override public Bitmap decode(Rect sRect, int sampleSize) { if (mDecoder == null){ return null; } synchronized (mDecoderLock) { BitmapFactory.Options options = new BitmapFactory.Options(); options.inSampleSize = sampleSize; // Default RGB_565
options.inPreferredConfig = HDImageViewFactory.getInstance().getBitmapConfig();
EvilBT/HDImageView
library/src/main/java/xyz/zpayh/hdimage/SimpleAnimatorListener.java
// Path: library/src/main/java/xyz/zpayh/hdimage/animation/AnimatorListener.java // public interface AnimatorListener { // /** // * <p>Notifies the start of the animation.</p> // * // * @param animation The started animation. // */ // void onAnimationStart(ValueAnimator animation); // // /** // * <p>Notifies the end of the animation. This callback is not invoked // * for animations with repeat count set to INFINITE.</p> // * // * @param animation The animation which reached its end. // */ // void onAnimationEnd(ValueAnimator animation); // // /** // * <p>Notifies the cancellation of the animation. This callback is not invoked // * for animations with repeat count set to INFINITE.</p> // * // * @param animation The animation which was canceled. // */ // void onAnimationCancel(ValueAnimator animation); // // /** // * <p>Notifies the repetition of the animation.</p> // * // * @param animation The animation which was repeated. // */ // void onAnimationRepeat(ValueAnimator animation); // } // // Path: library/src/main/java/xyz/zpayh/hdimage/animation/ValueAnimator.java // public interface ValueAnimator { // void setTarget(View view); // // void addListener(AnimatorListener listener); // // void setDuration(long duration); // // void start(); // // void cancel(); // // void addUpdateListener(AnimatorUpdateListener animatorUpdateListener); // // float getAnimatedFraction(); // }
import xyz.zpayh.hdimage.animation.AnimatorListener; import xyz.zpayh.hdimage.animation.ValueAnimator;
/* * * * Copyright 2017 陈志鹏 * * * * 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 xyz.zpayh.hdimage; /** * 文 件 名: SimpleAnimatorListener * 创 建 人: 陈志鹏 * 创建日期: 2017/4/20 17:09 * 邮 箱: ch_zh_p@qq.com * 修改时间: * 修改备注: */ public class SimpleAnimatorListener implements AnimatorListener { @Override
// Path: library/src/main/java/xyz/zpayh/hdimage/animation/AnimatorListener.java // public interface AnimatorListener { // /** // * <p>Notifies the start of the animation.</p> // * // * @param animation The started animation. // */ // void onAnimationStart(ValueAnimator animation); // // /** // * <p>Notifies the end of the animation. This callback is not invoked // * for animations with repeat count set to INFINITE.</p> // * // * @param animation The animation which reached its end. // */ // void onAnimationEnd(ValueAnimator animation); // // /** // * <p>Notifies the cancellation of the animation. This callback is not invoked // * for animations with repeat count set to INFINITE.</p> // * // * @param animation The animation which was canceled. // */ // void onAnimationCancel(ValueAnimator animation); // // /** // * <p>Notifies the repetition of the animation.</p> // * // * @param animation The animation which was repeated. // */ // void onAnimationRepeat(ValueAnimator animation); // } // // Path: library/src/main/java/xyz/zpayh/hdimage/animation/ValueAnimator.java // public interface ValueAnimator { // void setTarget(View view); // // void addListener(AnimatorListener listener); // // void setDuration(long duration); // // void start(); // // void cancel(); // // void addUpdateListener(AnimatorUpdateListener animatorUpdateListener); // // float getAnimatedFraction(); // } // Path: library/src/main/java/xyz/zpayh/hdimage/SimpleAnimatorListener.java import xyz.zpayh.hdimage.animation.AnimatorListener; import xyz.zpayh.hdimage.animation.ValueAnimator; /* * * * Copyright 2017 陈志鹏 * * * * 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 xyz.zpayh.hdimage; /** * 文 件 名: SimpleAnimatorListener * 创 建 人: 陈志鹏 * 创建日期: 2017/4/20 17:09 * 邮 箱: ch_zh_p@qq.com * 修改时间: * 修改备注: */ public class SimpleAnimatorListener implements AnimatorListener { @Override
public void onAnimationStart(ValueAnimator animation) {
EvilBT/HDImageView
library/src/main/java/xyz/zpayh/hdimage/SimpleValueAnimator.java
// Path: library/src/main/java/xyz/zpayh/hdimage/animation/AnimatorListener.java // public interface AnimatorListener { // /** // * <p>Notifies the start of the animation.</p> // * // * @param animation The started animation. // */ // void onAnimationStart(ValueAnimator animation); // // /** // * <p>Notifies the end of the animation. This callback is not invoked // * for animations with repeat count set to INFINITE.</p> // * // * @param animation The animation which reached its end. // */ // void onAnimationEnd(ValueAnimator animation); // // /** // * <p>Notifies the cancellation of the animation. This callback is not invoked // * for animations with repeat count set to INFINITE.</p> // * // * @param animation The animation which was canceled. // */ // void onAnimationCancel(ValueAnimator animation); // // /** // * <p>Notifies the repetition of the animation.</p> // * // * @param animation The animation which was repeated. // */ // void onAnimationRepeat(ValueAnimator animation); // } // // Path: library/src/main/java/xyz/zpayh/hdimage/animation/AnimatorUpdateListener.java // public interface AnimatorUpdateListener { // // /** // * <p>Notifies the occurrence of another frame of the animation.</p> // * // * @param animation The animation which was repeated. // */ // void onAnimationUpdate(ValueAnimator animation); // } // // Path: library/src/main/java/xyz/zpayh/hdimage/animation/ValueAnimator.java // public interface ValueAnimator { // void setTarget(View view); // // void addListener(AnimatorListener listener); // // void setDuration(long duration); // // void start(); // // void cancel(); // // void addUpdateListener(AnimatorUpdateListener animatorUpdateListener); // // float getAnimatedFraction(); // }
import android.graphics.PointF; import android.view.View; import android.view.animation.Interpolator; import java.util.ArrayList; import java.util.List; import xyz.zpayh.hdimage.animation.AnimatorListener; import xyz.zpayh.hdimage.animation.AnimatorUpdateListener; import xyz.zpayh.hdimage.animation.ValueAnimator;
/* * * * Copyright 2017 陈志鹏 * * * * 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 xyz.zpayh.hdimage; /** * 文 件 名: SimpleValueAnimator * 创 建 人: 陈志鹏 * 创建日期: 2017/4/20 14:43 * 邮 箱: ch_zh_p@qq.com * 修改时间: * 修改备注: */ public class SimpleValueAnimator implements ValueAnimator { private List<AnimatorListener> mListeners = new ArrayList<>();
// Path: library/src/main/java/xyz/zpayh/hdimage/animation/AnimatorListener.java // public interface AnimatorListener { // /** // * <p>Notifies the start of the animation.</p> // * // * @param animation The started animation. // */ // void onAnimationStart(ValueAnimator animation); // // /** // * <p>Notifies the end of the animation. This callback is not invoked // * for animations with repeat count set to INFINITE.</p> // * // * @param animation The animation which reached its end. // */ // void onAnimationEnd(ValueAnimator animation); // // /** // * <p>Notifies the cancellation of the animation. This callback is not invoked // * for animations with repeat count set to INFINITE.</p> // * // * @param animation The animation which was canceled. // */ // void onAnimationCancel(ValueAnimator animation); // // /** // * <p>Notifies the repetition of the animation.</p> // * // * @param animation The animation which was repeated. // */ // void onAnimationRepeat(ValueAnimator animation); // } // // Path: library/src/main/java/xyz/zpayh/hdimage/animation/AnimatorUpdateListener.java // public interface AnimatorUpdateListener { // // /** // * <p>Notifies the occurrence of another frame of the animation.</p> // * // * @param animation The animation which was repeated. // */ // void onAnimationUpdate(ValueAnimator animation); // } // // Path: library/src/main/java/xyz/zpayh/hdimage/animation/ValueAnimator.java // public interface ValueAnimator { // void setTarget(View view); // // void addListener(AnimatorListener listener); // // void setDuration(long duration); // // void start(); // // void cancel(); // // void addUpdateListener(AnimatorUpdateListener animatorUpdateListener); // // float getAnimatedFraction(); // } // Path: library/src/main/java/xyz/zpayh/hdimage/SimpleValueAnimator.java import android.graphics.PointF; import android.view.View; import android.view.animation.Interpolator; import java.util.ArrayList; import java.util.List; import xyz.zpayh.hdimage.animation.AnimatorListener; import xyz.zpayh.hdimage.animation.AnimatorUpdateListener; import xyz.zpayh.hdimage.animation.ValueAnimator; /* * * * Copyright 2017 陈志鹏 * * * * 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 xyz.zpayh.hdimage; /** * 文 件 名: SimpleValueAnimator * 创 建 人: 陈志鹏 * 创建日期: 2017/4/20 14:43 * 邮 箱: ch_zh_p@qq.com * 修改时间: * 修改备注: */ public class SimpleValueAnimator implements ValueAnimator { private List<AnimatorListener> mListeners = new ArrayList<>();
private List<AnimatorUpdateListener> mUpdateListeners
jgonian/commons-ip-math
commons-ip-math/src/test/java/com/github/jgonian/ipmath/ConservativePrefixFinderTest.java
// Path: commons-ip-math/src/main/java/com/github/jgonian/ipmath/Ipv6Range.java // public static Ipv6Range parse(String range) { // int idx = range.indexOf(DASH); // if (idx != -1) { // Ipv6 start = Ipv6.parse(range.substring(0, idx)); // Ipv6 end = Ipv6.parse(range.substring(idx + 1, range.length())); // return new Ipv6Range(start, end); // } else { // return parseCidr(range); // } // }
import org.junit.Test; import java.util.ArrayList; import java.util.List; import static com.github.jgonian.ipmath.Ipv6Range.parse; import static org.junit.Assert.*;
/** * The MIT License (MIT) * * Copyright (c) 2011-2017, Yannis Gonianakis * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.github.jgonian.ipmath; public class ConservativePrefixFinderTest { private final ConservativePrefixFinder subject = ConservativePrefixFinder.newInstance(); @Test public void shouldReturnNullIfRequestedPrefixIsTooBig() { assertNull(subject.findPrefixOrNull(9, in("::/10, 2::/20, 3::/30"))); } @Test public void shouldFindExactMatch() {
// Path: commons-ip-math/src/main/java/com/github/jgonian/ipmath/Ipv6Range.java // public static Ipv6Range parse(String range) { // int idx = range.indexOf(DASH); // if (idx != -1) { // Ipv6 start = Ipv6.parse(range.substring(0, idx)); // Ipv6 end = Ipv6.parse(range.substring(idx + 1, range.length())); // return new Ipv6Range(start, end); // } else { // return parseCidr(range); // } // } // Path: commons-ip-math/src/test/java/com/github/jgonian/ipmath/ConservativePrefixFinderTest.java import org.junit.Test; import java.util.ArrayList; import java.util.List; import static com.github.jgonian.ipmath.Ipv6Range.parse; import static org.junit.Assert.*; /** * The MIT License (MIT) * * Copyright (c) 2011-2017, Yannis Gonianakis * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.github.jgonian.ipmath; public class ConservativePrefixFinderTest { private final ConservativePrefixFinder subject = ConservativePrefixFinder.newInstance(); @Test public void shouldReturnNullIfRequestedPrefixIsTooBig() { assertNull(subject.findPrefixOrNull(9, in("::/10, 2::/20, 3::/30"))); } @Test public void shouldFindExactMatch() {
assertEquals(parse("::/10"), subject.findPrefixOrNull(10, in("::/10, 2::/20, 3::/30")));
jgonian/commons-ip-math
commons-ip-math/src/test/java/com/github/jgonian/ipmath/Ipv4RangeTest.java
// Path: commons-ip-math/src/main/java/com/github/jgonian/ipmath/Ipv4.java // public static final Ipv4 FIRST_IPV4_ADDRESS = Ipv4.of(MINIMUM_VALUE); // // Path: commons-ip-math/src/main/java/com/github/jgonian/ipmath/Ipv4.java // public static final Ipv4 LAST_IPV4_ADDRESS = Ipv4.of(MAXIMUM_VALUE); // // Path: commons-ip-math/src/main/java/com/github/jgonian/ipmath/Ipv4.java // public static final long MAXIMUM_VALUE = (1L << NUMBER_OF_BITS) - 1;
import static com.github.jgonian.ipmath.Ipv4.LAST_IPV4_ADDRESS; import static com.github.jgonian.ipmath.Ipv4.MAXIMUM_VALUE; import static junit.framework.Assert.assertFalse; import static org.junit.Assert.assertEquals; import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static com.github.jgonian.ipmath.Ipv4.FIRST_IPV4_ADDRESS;
/** * The MIT License (MIT) * * Copyright (c) 2011-2017, Yannis Gonianakis * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.github.jgonian.ipmath; public class Ipv4RangeTest extends AbstractRangeTest<Ipv4, Ipv4Range> { Ipv4 ip1 = Ipv4.of("0.0.0.1"); Ipv4 ip2 = Ipv4.of("0.0.0.2"); Ipv4 ip3 = Ipv4.of("0.0.0.3"); @Override protected Ipv4 from(String s) { return Ipv4.of(Long.parseLong(s)); } @Override protected Ipv4 to(String s) { return Ipv4.of(Long.parseLong(s)); } @Override protected Ipv4 item(String s) { return Ipv4.of(Long.parseLong(s)); } @Override protected Ipv4Range getTestRange(Ipv4 start, Ipv4 end) { return new Ipv4Range(start, end); } @Override protected Ipv4Range getFullRange() {
// Path: commons-ip-math/src/main/java/com/github/jgonian/ipmath/Ipv4.java // public static final Ipv4 FIRST_IPV4_ADDRESS = Ipv4.of(MINIMUM_VALUE); // // Path: commons-ip-math/src/main/java/com/github/jgonian/ipmath/Ipv4.java // public static final Ipv4 LAST_IPV4_ADDRESS = Ipv4.of(MAXIMUM_VALUE); // // Path: commons-ip-math/src/main/java/com/github/jgonian/ipmath/Ipv4.java // public static final long MAXIMUM_VALUE = (1L << NUMBER_OF_BITS) - 1; // Path: commons-ip-math/src/test/java/com/github/jgonian/ipmath/Ipv4RangeTest.java import static com.github.jgonian.ipmath.Ipv4.LAST_IPV4_ADDRESS; import static com.github.jgonian.ipmath.Ipv4.MAXIMUM_VALUE; import static junit.framework.Assert.assertFalse; import static org.junit.Assert.assertEquals; import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static com.github.jgonian.ipmath.Ipv4.FIRST_IPV4_ADDRESS; /** * The MIT License (MIT) * * Copyright (c) 2011-2017, Yannis Gonianakis * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.github.jgonian.ipmath; public class Ipv4RangeTest extends AbstractRangeTest<Ipv4, Ipv4Range> { Ipv4 ip1 = Ipv4.of("0.0.0.1"); Ipv4 ip2 = Ipv4.of("0.0.0.2"); Ipv4 ip3 = Ipv4.of("0.0.0.3"); @Override protected Ipv4 from(String s) { return Ipv4.of(Long.parseLong(s)); } @Override protected Ipv4 to(String s) { return Ipv4.of(Long.parseLong(s)); } @Override protected Ipv4 item(String s) { return Ipv4.of(Long.parseLong(s)); } @Override protected Ipv4Range getTestRange(Ipv4 start, Ipv4 end) { return new Ipv4Range(start, end); } @Override protected Ipv4Range getFullRange() {
return new Ipv4Range(FIRST_IPV4_ADDRESS, LAST_IPV4_ADDRESS);
jgonian/commons-ip-math
commons-ip-math/src/test/java/com/github/jgonian/ipmath/Ipv4RangeTest.java
// Path: commons-ip-math/src/main/java/com/github/jgonian/ipmath/Ipv4.java // public static final Ipv4 FIRST_IPV4_ADDRESS = Ipv4.of(MINIMUM_VALUE); // // Path: commons-ip-math/src/main/java/com/github/jgonian/ipmath/Ipv4.java // public static final Ipv4 LAST_IPV4_ADDRESS = Ipv4.of(MAXIMUM_VALUE); // // Path: commons-ip-math/src/main/java/com/github/jgonian/ipmath/Ipv4.java // public static final long MAXIMUM_VALUE = (1L << NUMBER_OF_BITS) - 1;
import static com.github.jgonian.ipmath.Ipv4.LAST_IPV4_ADDRESS; import static com.github.jgonian.ipmath.Ipv4.MAXIMUM_VALUE; import static junit.framework.Assert.assertFalse; import static org.junit.Assert.assertEquals; import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static com.github.jgonian.ipmath.Ipv4.FIRST_IPV4_ADDRESS;
/** * The MIT License (MIT) * * Copyright (c) 2011-2017, Yannis Gonianakis * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.github.jgonian.ipmath; public class Ipv4RangeTest extends AbstractRangeTest<Ipv4, Ipv4Range> { Ipv4 ip1 = Ipv4.of("0.0.0.1"); Ipv4 ip2 = Ipv4.of("0.0.0.2"); Ipv4 ip3 = Ipv4.of("0.0.0.3"); @Override protected Ipv4 from(String s) { return Ipv4.of(Long.parseLong(s)); } @Override protected Ipv4 to(String s) { return Ipv4.of(Long.parseLong(s)); } @Override protected Ipv4 item(String s) { return Ipv4.of(Long.parseLong(s)); } @Override protected Ipv4Range getTestRange(Ipv4 start, Ipv4 end) { return new Ipv4Range(start, end); } @Override protected Ipv4Range getFullRange() {
// Path: commons-ip-math/src/main/java/com/github/jgonian/ipmath/Ipv4.java // public static final Ipv4 FIRST_IPV4_ADDRESS = Ipv4.of(MINIMUM_VALUE); // // Path: commons-ip-math/src/main/java/com/github/jgonian/ipmath/Ipv4.java // public static final Ipv4 LAST_IPV4_ADDRESS = Ipv4.of(MAXIMUM_VALUE); // // Path: commons-ip-math/src/main/java/com/github/jgonian/ipmath/Ipv4.java // public static final long MAXIMUM_VALUE = (1L << NUMBER_OF_BITS) - 1; // Path: commons-ip-math/src/test/java/com/github/jgonian/ipmath/Ipv4RangeTest.java import static com.github.jgonian.ipmath.Ipv4.LAST_IPV4_ADDRESS; import static com.github.jgonian.ipmath.Ipv4.MAXIMUM_VALUE; import static junit.framework.Assert.assertFalse; import static org.junit.Assert.assertEquals; import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static com.github.jgonian.ipmath.Ipv4.FIRST_IPV4_ADDRESS; /** * The MIT License (MIT) * * Copyright (c) 2011-2017, Yannis Gonianakis * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.github.jgonian.ipmath; public class Ipv4RangeTest extends AbstractRangeTest<Ipv4, Ipv4Range> { Ipv4 ip1 = Ipv4.of("0.0.0.1"); Ipv4 ip2 = Ipv4.of("0.0.0.2"); Ipv4 ip3 = Ipv4.of("0.0.0.3"); @Override protected Ipv4 from(String s) { return Ipv4.of(Long.parseLong(s)); } @Override protected Ipv4 to(String s) { return Ipv4.of(Long.parseLong(s)); } @Override protected Ipv4 item(String s) { return Ipv4.of(Long.parseLong(s)); } @Override protected Ipv4Range getTestRange(Ipv4 start, Ipv4 end) { return new Ipv4Range(start, end); } @Override protected Ipv4Range getFullRange() {
return new Ipv4Range(FIRST_IPV4_ADDRESS, LAST_IPV4_ADDRESS);
jgonian/commons-ip-math
commons-ip-math/src/test/java/com/github/jgonian/ipmath/Ipv4RangeTest.java
// Path: commons-ip-math/src/main/java/com/github/jgonian/ipmath/Ipv4.java // public static final Ipv4 FIRST_IPV4_ADDRESS = Ipv4.of(MINIMUM_VALUE); // // Path: commons-ip-math/src/main/java/com/github/jgonian/ipmath/Ipv4.java // public static final Ipv4 LAST_IPV4_ADDRESS = Ipv4.of(MAXIMUM_VALUE); // // Path: commons-ip-math/src/main/java/com/github/jgonian/ipmath/Ipv4.java // public static final long MAXIMUM_VALUE = (1L << NUMBER_OF_BITS) - 1;
import static com.github.jgonian.ipmath.Ipv4.LAST_IPV4_ADDRESS; import static com.github.jgonian.ipmath.Ipv4.MAXIMUM_VALUE; import static junit.framework.Assert.assertFalse; import static org.junit.Assert.assertEquals; import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static com.github.jgonian.ipmath.Ipv4.FIRST_IPV4_ADDRESS;
} @Test public void testToStringInRangeNotation() { assertEquals("0.0.0.0-255.255.255.255", new Ipv4Range(FIRST_IPV4_ADDRESS, LAST_IPV4_ADDRESS).toStringInRangeNotation()); } @Test public void testToStringInRangeNotationWithSpaces() { assertEquals("0.0.0.0 - 255.255.255.255", new Ipv4Range(FIRST_IPV4_ADDRESS, LAST_IPV4_ADDRESS).toStringInRangeNotationWithSpaces()); } @Test public void testToStringSpecialFoundInvalidCase() { assertFalse("94.126.33.0/23".equals(Ipv4Range.from(1585324288L).to(1585324799L).toString())); } @Test public void testToStringInCidrNotation() { assertEquals("0.0.0.0/0", new Ipv4Range(FIRST_IPV4_ADDRESS, LAST_IPV4_ADDRESS).toStringInCidrNotation()); } @Test public void testToStringInDecimalNotation() { assertEquals("0-4294967295", new Ipv4Range(FIRST_IPV4_ADDRESS, LAST_IPV4_ADDRESS).toStringInDecimalNotation()); } @Test public void testSize() { assertEquals(new Long(1), ip1.asRange().size());
// Path: commons-ip-math/src/main/java/com/github/jgonian/ipmath/Ipv4.java // public static final Ipv4 FIRST_IPV4_ADDRESS = Ipv4.of(MINIMUM_VALUE); // // Path: commons-ip-math/src/main/java/com/github/jgonian/ipmath/Ipv4.java // public static final Ipv4 LAST_IPV4_ADDRESS = Ipv4.of(MAXIMUM_VALUE); // // Path: commons-ip-math/src/main/java/com/github/jgonian/ipmath/Ipv4.java // public static final long MAXIMUM_VALUE = (1L << NUMBER_OF_BITS) - 1; // Path: commons-ip-math/src/test/java/com/github/jgonian/ipmath/Ipv4RangeTest.java import static com.github.jgonian.ipmath.Ipv4.LAST_IPV4_ADDRESS; import static com.github.jgonian.ipmath.Ipv4.MAXIMUM_VALUE; import static junit.framework.Assert.assertFalse; import static org.junit.Assert.assertEquals; import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static com.github.jgonian.ipmath.Ipv4.FIRST_IPV4_ADDRESS; } @Test public void testToStringInRangeNotation() { assertEquals("0.0.0.0-255.255.255.255", new Ipv4Range(FIRST_IPV4_ADDRESS, LAST_IPV4_ADDRESS).toStringInRangeNotation()); } @Test public void testToStringInRangeNotationWithSpaces() { assertEquals("0.0.0.0 - 255.255.255.255", new Ipv4Range(FIRST_IPV4_ADDRESS, LAST_IPV4_ADDRESS).toStringInRangeNotationWithSpaces()); } @Test public void testToStringSpecialFoundInvalidCase() { assertFalse("94.126.33.0/23".equals(Ipv4Range.from(1585324288L).to(1585324799L).toString())); } @Test public void testToStringInCidrNotation() { assertEquals("0.0.0.0/0", new Ipv4Range(FIRST_IPV4_ADDRESS, LAST_IPV4_ADDRESS).toStringInCidrNotation()); } @Test public void testToStringInDecimalNotation() { assertEquals("0-4294967295", new Ipv4Range(FIRST_IPV4_ADDRESS, LAST_IPV4_ADDRESS).toStringInDecimalNotation()); } @Test public void testSize() { assertEquals(new Long(1), ip1.asRange().size());
assertEquals(new Long(MAXIMUM_VALUE + 1), Ipv4Range.from(FIRST_IPV4_ADDRESS).to(LAST_IPV4_ADDRESS).size());
jgonian/commons-ip-math
commons-ip-math/src/test/java/com/github/jgonian/ipmath/Ipv6RangeTest.java
// Path: commons-ip-math/src/main/java/com/github/jgonian/ipmath/Ipv6.java // public static final Ipv6 FIRST_IPV6_ADDRESS = Ipv6.of(MINIMUM_VALUE); // // Path: commons-ip-math/src/main/java/com/github/jgonian/ipmath/Ipv6.java // public static final Ipv6 LAST_IPV6_ADDRESS = Ipv6.of(MAXIMUM_VALUE);
import static com.github.jgonian.ipmath.Ipv6.FIRST_IPV6_ADDRESS; import static com.github.jgonian.ipmath.Ipv6.LAST_IPV6_ADDRESS; import static java.math.BigInteger.ONE; import static org.junit.Assert.assertEquals; import org.junit.Test; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.List;
/** * The MIT License (MIT) * * Copyright (c) 2011-2017, Yannis Gonianakis * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.github.jgonian.ipmath; public class Ipv6RangeTest extends AbstractRangeTest<Ipv6, Ipv6Range> { Ipv6 ip1 = Ipv6.of("::1"); Ipv6 ip2 = Ipv6.of("::2"); Ipv6 ip3 = Ipv6.of("::3"); @Override protected Ipv6 from(String s) { return Ipv6.of(BigInteger.valueOf(Long.parseLong(s))); } @Override protected Ipv6 to(String s) { return Ipv6.of(BigInteger.valueOf(Long.parseLong(s))); } @Override protected Ipv6 item(String s) { return Ipv6.of(BigInteger.valueOf(Long.parseLong(s))); } @Override protected Ipv6Range getTestRange(Ipv6 start, Ipv6 end) { return new Ipv6Range(start, end); } @Override protected Ipv6Range getFullRange() {
// Path: commons-ip-math/src/main/java/com/github/jgonian/ipmath/Ipv6.java // public static final Ipv6 FIRST_IPV6_ADDRESS = Ipv6.of(MINIMUM_VALUE); // // Path: commons-ip-math/src/main/java/com/github/jgonian/ipmath/Ipv6.java // public static final Ipv6 LAST_IPV6_ADDRESS = Ipv6.of(MAXIMUM_VALUE); // Path: commons-ip-math/src/test/java/com/github/jgonian/ipmath/Ipv6RangeTest.java import static com.github.jgonian.ipmath.Ipv6.FIRST_IPV6_ADDRESS; import static com.github.jgonian.ipmath.Ipv6.LAST_IPV6_ADDRESS; import static java.math.BigInteger.ONE; import static org.junit.Assert.assertEquals; import org.junit.Test; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * The MIT License (MIT) * * Copyright (c) 2011-2017, Yannis Gonianakis * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.github.jgonian.ipmath; public class Ipv6RangeTest extends AbstractRangeTest<Ipv6, Ipv6Range> { Ipv6 ip1 = Ipv6.of("::1"); Ipv6 ip2 = Ipv6.of("::2"); Ipv6 ip3 = Ipv6.of("::3"); @Override protected Ipv6 from(String s) { return Ipv6.of(BigInteger.valueOf(Long.parseLong(s))); } @Override protected Ipv6 to(String s) { return Ipv6.of(BigInteger.valueOf(Long.parseLong(s))); } @Override protected Ipv6 item(String s) { return Ipv6.of(BigInteger.valueOf(Long.parseLong(s))); } @Override protected Ipv6Range getTestRange(Ipv6 start, Ipv6 end) { return new Ipv6Range(start, end); } @Override protected Ipv6Range getFullRange() {
return new Ipv6Range(FIRST_IPV6_ADDRESS, LAST_IPV6_ADDRESS);
jgonian/commons-ip-math
commons-ip-math/src/test/java/com/github/jgonian/ipmath/Ipv6RangeTest.java
// Path: commons-ip-math/src/main/java/com/github/jgonian/ipmath/Ipv6.java // public static final Ipv6 FIRST_IPV6_ADDRESS = Ipv6.of(MINIMUM_VALUE); // // Path: commons-ip-math/src/main/java/com/github/jgonian/ipmath/Ipv6.java // public static final Ipv6 LAST_IPV6_ADDRESS = Ipv6.of(MAXIMUM_VALUE);
import static com.github.jgonian.ipmath.Ipv6.FIRST_IPV6_ADDRESS; import static com.github.jgonian.ipmath.Ipv6.LAST_IPV6_ADDRESS; import static java.math.BigInteger.ONE; import static org.junit.Assert.assertEquals; import org.junit.Test; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.List;
/** * The MIT License (MIT) * * Copyright (c) 2011-2017, Yannis Gonianakis * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.github.jgonian.ipmath; public class Ipv6RangeTest extends AbstractRangeTest<Ipv6, Ipv6Range> { Ipv6 ip1 = Ipv6.of("::1"); Ipv6 ip2 = Ipv6.of("::2"); Ipv6 ip3 = Ipv6.of("::3"); @Override protected Ipv6 from(String s) { return Ipv6.of(BigInteger.valueOf(Long.parseLong(s))); } @Override protected Ipv6 to(String s) { return Ipv6.of(BigInteger.valueOf(Long.parseLong(s))); } @Override protected Ipv6 item(String s) { return Ipv6.of(BigInteger.valueOf(Long.parseLong(s))); } @Override protected Ipv6Range getTestRange(Ipv6 start, Ipv6 end) { return new Ipv6Range(start, end); } @Override protected Ipv6Range getFullRange() {
// Path: commons-ip-math/src/main/java/com/github/jgonian/ipmath/Ipv6.java // public static final Ipv6 FIRST_IPV6_ADDRESS = Ipv6.of(MINIMUM_VALUE); // // Path: commons-ip-math/src/main/java/com/github/jgonian/ipmath/Ipv6.java // public static final Ipv6 LAST_IPV6_ADDRESS = Ipv6.of(MAXIMUM_VALUE); // Path: commons-ip-math/src/test/java/com/github/jgonian/ipmath/Ipv6RangeTest.java import static com.github.jgonian.ipmath.Ipv6.FIRST_IPV6_ADDRESS; import static com.github.jgonian.ipmath.Ipv6.LAST_IPV6_ADDRESS; import static java.math.BigInteger.ONE; import static org.junit.Assert.assertEquals; import org.junit.Test; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * The MIT License (MIT) * * Copyright (c) 2011-2017, Yannis Gonianakis * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.github.jgonian.ipmath; public class Ipv6RangeTest extends AbstractRangeTest<Ipv6, Ipv6Range> { Ipv6 ip1 = Ipv6.of("::1"); Ipv6 ip2 = Ipv6.of("::2"); Ipv6 ip3 = Ipv6.of("::3"); @Override protected Ipv6 from(String s) { return Ipv6.of(BigInteger.valueOf(Long.parseLong(s))); } @Override protected Ipv6 to(String s) { return Ipv6.of(BigInteger.valueOf(Long.parseLong(s))); } @Override protected Ipv6 item(String s) { return Ipv6.of(BigInteger.valueOf(Long.parseLong(s))); } @Override protected Ipv6Range getTestRange(Ipv6 start, Ipv6 end) { return new Ipv6Range(start, end); } @Override protected Ipv6Range getFullRange() {
return new Ipv6Range(FIRST_IPV6_ADDRESS, LAST_IPV6_ADDRESS);
ctron/de.dentrassi.camel.milo
camel-milo/src/main/java/org/apache/camel/component/milo/server/MiloServerConsumer.java
// Path: camel-milo/src/main/java/org/apache/camel/component/milo/Messages.java // public final class Messages { // private Messages() { // } // // /** // * Fill a Message from a DataValue // * // * @param value // * the value to feed from // * @param result // * the result to feed to // */ // public static void fillFromDataValue(final DataValue value, final DefaultMessage result) { // result.setBody(value); // result.setFault(value.getStatusCode().isBad()); // } // } // // Path: camel-milo/src/main/java/org/apache/camel/component/milo/server/internal/CamelServerItem.java // public class CamelServerItem { // private static final Logger LOG = LoggerFactory.getLogger(CamelServerItem.class); // // private UaObjectNode baseNode; // private UaVariableNode item; // // private DataValue value = new DataValue(StatusCode.BAD); // private final Set<Consumer<DataValue>> listeners = new CopyOnWriteArraySet<>(); // // public CamelServerItem(final String itemId, final ServerNodeMap nodeManager, final UShort namespaceIndex, // final UaObjectNode baseNode) { // // this.baseNode = baseNode; // // final NodeId nodeId = new NodeId(namespaceIndex, "items-" + itemId); // final QualifiedName qname = new QualifiedName(namespaceIndex, itemId); // final LocalizedText displayName = LocalizedText.english(itemId); // // // create variable node // // this.item = new UaVariableNode(nodeManager, nodeId, qname, displayName) { // // @Override // public DataValue getValue() { // return getDataValue(); // } // // @Override // public synchronized void setValue(final DataValue value) { // setDataValue(value); // } // // }; // // // item.setDataType(); // this.item.setAccessLevel(ubyte(AccessLevel.getMask(AccessLevel.READ_WRITE))); // this.item.setUserAccessLevel(ubyte(AccessLevel.getMask(AccessLevel.READ_WRITE))); // // baseNode.addComponent(this.item); // } // // public void dispose() { // this.baseNode.removeComponent(this.item); // this.listeners.clear(); // } // // public void addWriteListener(final Consumer<DataValue> consumer) { // this.listeners.add(consumer); // } // // public void removeWriteListener(final Consumer<DataValue> consumer) { // this.listeners.remove(consumer); // } // // protected void setDataValue(final DataValue value) { // LOG.debug("setValue -> {}", value); // runThrough(this.listeners, c -> c.accept(value)); // } // // /** // * Run through a list, aggregating errors // * // * <p> // * The consumer is called for each list item, regardless if the consumer did // * through an exception. All exceptions are caught and thrown in one // * RuntimeException. The first exception being wrapped directly while the // * latter ones, if any, are added as suppressed exceptions. // * </p> // * // * @param list // * the list to run through // * @param consumer // * the consumer processing list elements // */ // protected <T> void runThrough(final Collection<Consumer<T>> list, final Consumer<Consumer<T>> consumer) { // LinkedList<Throwable> errors = null; // // for (final Consumer<T> listener : list) { // try { // consumer.accept(listener); // } catch (final Throwable e) { // if (errors == null) { // errors = new LinkedList<>(); // } // errors.add(e); // } // } // // if (errors == null || errors.isEmpty()) { // return; // } // // final RuntimeException ex = new RuntimeException(errors.pollFirst()); // errors.forEach(ex::addSuppressed); // throw ex; // } // // protected DataValue getDataValue() { // return this.value; // } // // public void update(final Object value) { // this.value = new DataValue(new Variant(value), StatusCode.GOOD, DateTime.now()); // } // }
import java.util.function.Consumer; import org.apache.camel.Endpoint; import org.apache.camel.Exchange; import org.apache.camel.Processor; import org.apache.camel.component.milo.Messages; import org.apache.camel.component.milo.server.internal.CamelServerItem; import org.apache.camel.impl.DefaultConsumer; import org.apache.camel.impl.DefaultMessage; import org.eclipse.milo.opcua.stack.core.types.builtin.DataValue;
this.item.addWriteListener(this.writeHandler); } @Override protected void doStop() throws Exception { this.item.removeWriteListener(this.writeHandler); super.doStop(); } protected void performWrite(final DataValue value) { final Exchange exchange = getEndpoint().createExchange(); exchange.setIn(mapToMessage(value)); try { getAsyncProcessor().process(exchange); } catch (final Exception e) { throw new RuntimeException(e); } } private DefaultMessage mapToMessage(final DataValue value) { if (value == null) { return null; } final DefaultMessage result = new DefaultMessage();
// Path: camel-milo/src/main/java/org/apache/camel/component/milo/Messages.java // public final class Messages { // private Messages() { // } // // /** // * Fill a Message from a DataValue // * // * @param value // * the value to feed from // * @param result // * the result to feed to // */ // public static void fillFromDataValue(final DataValue value, final DefaultMessage result) { // result.setBody(value); // result.setFault(value.getStatusCode().isBad()); // } // } // // Path: camel-milo/src/main/java/org/apache/camel/component/milo/server/internal/CamelServerItem.java // public class CamelServerItem { // private static final Logger LOG = LoggerFactory.getLogger(CamelServerItem.class); // // private UaObjectNode baseNode; // private UaVariableNode item; // // private DataValue value = new DataValue(StatusCode.BAD); // private final Set<Consumer<DataValue>> listeners = new CopyOnWriteArraySet<>(); // // public CamelServerItem(final String itemId, final ServerNodeMap nodeManager, final UShort namespaceIndex, // final UaObjectNode baseNode) { // // this.baseNode = baseNode; // // final NodeId nodeId = new NodeId(namespaceIndex, "items-" + itemId); // final QualifiedName qname = new QualifiedName(namespaceIndex, itemId); // final LocalizedText displayName = LocalizedText.english(itemId); // // // create variable node // // this.item = new UaVariableNode(nodeManager, nodeId, qname, displayName) { // // @Override // public DataValue getValue() { // return getDataValue(); // } // // @Override // public synchronized void setValue(final DataValue value) { // setDataValue(value); // } // // }; // // // item.setDataType(); // this.item.setAccessLevel(ubyte(AccessLevel.getMask(AccessLevel.READ_WRITE))); // this.item.setUserAccessLevel(ubyte(AccessLevel.getMask(AccessLevel.READ_WRITE))); // // baseNode.addComponent(this.item); // } // // public void dispose() { // this.baseNode.removeComponent(this.item); // this.listeners.clear(); // } // // public void addWriteListener(final Consumer<DataValue> consumer) { // this.listeners.add(consumer); // } // // public void removeWriteListener(final Consumer<DataValue> consumer) { // this.listeners.remove(consumer); // } // // protected void setDataValue(final DataValue value) { // LOG.debug("setValue -> {}", value); // runThrough(this.listeners, c -> c.accept(value)); // } // // /** // * Run through a list, aggregating errors // * // * <p> // * The consumer is called for each list item, regardless if the consumer did // * through an exception. All exceptions are caught and thrown in one // * RuntimeException. The first exception being wrapped directly while the // * latter ones, if any, are added as suppressed exceptions. // * </p> // * // * @param list // * the list to run through // * @param consumer // * the consumer processing list elements // */ // protected <T> void runThrough(final Collection<Consumer<T>> list, final Consumer<Consumer<T>> consumer) { // LinkedList<Throwable> errors = null; // // for (final Consumer<T> listener : list) { // try { // consumer.accept(listener); // } catch (final Throwable e) { // if (errors == null) { // errors = new LinkedList<>(); // } // errors.add(e); // } // } // // if (errors == null || errors.isEmpty()) { // return; // } // // final RuntimeException ex = new RuntimeException(errors.pollFirst()); // errors.forEach(ex::addSuppressed); // throw ex; // } // // protected DataValue getDataValue() { // return this.value; // } // // public void update(final Object value) { // this.value = new DataValue(new Variant(value), StatusCode.GOOD, DateTime.now()); // } // } // Path: camel-milo/src/main/java/org/apache/camel/component/milo/server/MiloServerConsumer.java import java.util.function.Consumer; import org.apache.camel.Endpoint; import org.apache.camel.Exchange; import org.apache.camel.Processor; import org.apache.camel.component.milo.Messages; import org.apache.camel.component.milo.server.internal.CamelServerItem; import org.apache.camel.impl.DefaultConsumer; import org.apache.camel.impl.DefaultMessage; import org.eclipse.milo.opcua.stack.core.types.builtin.DataValue; this.item.addWriteListener(this.writeHandler); } @Override protected void doStop() throws Exception { this.item.removeWriteListener(this.writeHandler); super.doStop(); } protected void performWrite(final DataValue value) { final Exchange exchange = getEndpoint().createExchange(); exchange.setIn(mapToMessage(value)); try { getAsyncProcessor().process(exchange); } catch (final Exception e) { throw new RuntimeException(e); } } private DefaultMessage mapToMessage(final DataValue value) { if (value == null) { return null; } final DefaultMessage result = new DefaultMessage();
Messages.fillFromDataValue(value, result);
ctron/de.dentrassi.camel.milo
camel-milo/src/main/java/org/apache/camel/component/milo/client/MiloClientConsumer.java
// Path: camel-milo/src/main/java/org/apache/camel/component/milo/Messages.java // public final class Messages { // private Messages() { // } // // /** // * Fill a Message from a DataValue // * // * @param value // * the value to feed from // * @param result // * the result to feed to // */ // public static void fillFromDataValue(final DataValue value, final DefaultMessage result) { // result.setBody(value); // result.setFault(value.getStatusCode().isBad()); // } // } // // Path: camel-milo/src/main/java/org/apache/camel/component/milo/client/MiloClientConnection.java // @FunctionalInterface // public interface MonitorHandle { // public void unregister(); // }
import java.util.Objects; import org.apache.camel.Exchange; import org.apache.camel.Message; import org.apache.camel.Processor; import org.apache.camel.component.milo.Messages; import org.apache.camel.component.milo.client.MiloClientConnection.MonitorHandle; import org.apache.camel.impl.DefaultConsumer; import org.apache.camel.impl.DefaultMessage; import org.eclipse.milo.opcua.stack.core.types.builtin.DataValue; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
/* * Copyright (C) 2016 Jens Reimann <jreimann@redhat.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.milo.client; public class MiloClientConsumer extends DefaultConsumer { private static final Logger LOG = LoggerFactory.getLogger(MiloClientConsumer.class); private final MiloClientConnection connection; private final MiloClientItemConfiguration configuration;
// Path: camel-milo/src/main/java/org/apache/camel/component/milo/Messages.java // public final class Messages { // private Messages() { // } // // /** // * Fill a Message from a DataValue // * // * @param value // * the value to feed from // * @param result // * the result to feed to // */ // public static void fillFromDataValue(final DataValue value, final DefaultMessage result) { // result.setBody(value); // result.setFault(value.getStatusCode().isBad()); // } // } // // Path: camel-milo/src/main/java/org/apache/camel/component/milo/client/MiloClientConnection.java // @FunctionalInterface // public interface MonitorHandle { // public void unregister(); // } // Path: camel-milo/src/main/java/org/apache/camel/component/milo/client/MiloClientConsumer.java import java.util.Objects; import org.apache.camel.Exchange; import org.apache.camel.Message; import org.apache.camel.Processor; import org.apache.camel.component.milo.Messages; import org.apache.camel.component.milo.client.MiloClientConnection.MonitorHandle; import org.apache.camel.impl.DefaultConsumer; import org.apache.camel.impl.DefaultMessage; import org.eclipse.milo.opcua.stack.core.types.builtin.DataValue; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /* * Copyright (C) 2016 Jens Reimann <jreimann@redhat.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.milo.client; public class MiloClientConsumer extends DefaultConsumer { private static final Logger LOG = LoggerFactory.getLogger(MiloClientConsumer.class); private final MiloClientConnection connection; private final MiloClientItemConfiguration configuration;
private MonitorHandle handle;
ctron/de.dentrassi.camel.milo
camel-milo/src/main/java/org/apache/camel/component/milo/client/MiloClientConsumer.java
// Path: camel-milo/src/main/java/org/apache/camel/component/milo/Messages.java // public final class Messages { // private Messages() { // } // // /** // * Fill a Message from a DataValue // * // * @param value // * the value to feed from // * @param result // * the result to feed to // */ // public static void fillFromDataValue(final DataValue value, final DefaultMessage result) { // result.setBody(value); // result.setFault(value.getStatusCode().isBad()); // } // } // // Path: camel-milo/src/main/java/org/apache/camel/component/milo/client/MiloClientConnection.java // @FunctionalInterface // public interface MonitorHandle { // public void unregister(); // }
import java.util.Objects; import org.apache.camel.Exchange; import org.apache.camel.Message; import org.apache.camel.Processor; import org.apache.camel.component.milo.Messages; import org.apache.camel.component.milo.client.MiloClientConnection.MonitorHandle; import org.apache.camel.impl.DefaultConsumer; import org.apache.camel.impl.DefaultMessage; import org.eclipse.milo.opcua.stack.core.types.builtin.DataValue; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
this.handle = this.connection.monitorValue(this.configuration, this::handleValueUpdate); } @Override protected void doStop() throws Exception { if (this.handle != null) { this.handle.unregister(); this.handle = null; } super.doStop(); } private void handleValueUpdate(final DataValue value) { final Exchange exchange = getEndpoint().createExchange(); exchange.setIn(mapMessage(value)); try { getAsyncProcessor().process(exchange); } catch (final Exception e) { LOG.debug("Failed to process message", e); } } private Message mapMessage(final DataValue value) { if (value == null) { return null; } final DefaultMessage result = new DefaultMessage();
// Path: camel-milo/src/main/java/org/apache/camel/component/milo/Messages.java // public final class Messages { // private Messages() { // } // // /** // * Fill a Message from a DataValue // * // * @param value // * the value to feed from // * @param result // * the result to feed to // */ // public static void fillFromDataValue(final DataValue value, final DefaultMessage result) { // result.setBody(value); // result.setFault(value.getStatusCode().isBad()); // } // } // // Path: camel-milo/src/main/java/org/apache/camel/component/milo/client/MiloClientConnection.java // @FunctionalInterface // public interface MonitorHandle { // public void unregister(); // } // Path: camel-milo/src/main/java/org/apache/camel/component/milo/client/MiloClientConsumer.java import java.util.Objects; import org.apache.camel.Exchange; import org.apache.camel.Message; import org.apache.camel.Processor; import org.apache.camel.component.milo.Messages; import org.apache.camel.component.milo.client.MiloClientConnection.MonitorHandle; import org.apache.camel.impl.DefaultConsumer; import org.apache.camel.impl.DefaultMessage; import org.eclipse.milo.opcua.stack.core.types.builtin.DataValue; import org.slf4j.Logger; import org.slf4j.LoggerFactory; this.handle = this.connection.monitorValue(this.configuration, this::handleValueUpdate); } @Override protected void doStop() throws Exception { if (this.handle != null) { this.handle.unregister(); this.handle = null; } super.doStop(); } private void handleValueUpdate(final DataValue value) { final Exchange exchange = getEndpoint().createExchange(); exchange.setIn(mapMessage(value)); try { getAsyncProcessor().process(exchange); } catch (final Exception e) { LOG.debug("Failed to process message", e); } } private Message mapMessage(final DataValue value) { if (value == null) { return null; } final DefaultMessage result = new DefaultMessage();
Messages.fillFromDataValue(value, result);
ctron/de.dentrassi.camel.milo
camel-milo/src/main/java/org/apache/camel/component/milo/client/MiloClientProducer.java
// Path: camel-milo/src/main/java/org/apache/camel/component/milo/NamespaceId.java // public class NamespaceId { // private final String uri; // private final UShort numeric; // // public NamespaceId(final String uri) { // requireNonNull(uri); // // this.uri = uri; // this.numeric = null; // } // // public NamespaceId(final UShort numeric) { // requireNonNull(numeric); // // this.uri = null; // this.numeric = numeric; // } // // public String getUri() { // return this.uri; // } // // public UShort getNumeric() { // return this.numeric; // } // // public boolean isNumeric() { // return this.numeric != null; // } // // @Override // public String toString() { // if (isNumeric()) { // return String.format("[Namespace - numeric: %s]", this.numeric); // } else { // return String.format("[Namespace - URI: %s]", this.uri); // } // } // // public Serializable getValue() { // return this.uri != null ? this.uri : this.numeric; // } // // public static NamespaceId fromExpandedNodeId(final ExpandedNodeId id) { // if (id == null) { // return null; // } // // if (id.getNamespaceUri() != null) { // return new NamespaceId(id.getNamespaceUri()); // } // if (id.getNamespaceIndex() != null) { // return new NamespaceId(id.getNamespaceIndex()); // } // // throw new IllegalStateException(String.format("Unknown namespace type")); // } // } // // Path: camel-milo/src/main/java/org/apache/camel/component/milo/PartialNodeId.java // public class PartialNodeId { // // private IdType type; // // private final Serializable id; // // public PartialNodeId(final int id) { // this(uint(id)); // } // // public PartialNodeId(final UInteger id) { // requireNonNull(id); // this.id = id; // } // // public PartialNodeId(final String id) { // requireNonNull(id); // this.id = id; // } // // public PartialNodeId(final UUID id) { // requireNonNull(id); // this.id = id; // } // // public PartialNodeId(final ByteString id) { // requireNonNull(id); // this.id = id; // } // // public NodeId toNodeId(final int namespaceIndex) { // if (this.id instanceof String) { // return new NodeId(namespaceIndex, (String) this.id); // } else if (this.id instanceof UInteger) { // return new NodeId(ushort(namespaceIndex), (UInteger) this.id); // } else if (this.id instanceof ByteString) { // return new NodeId(namespaceIndex, (ByteString) this.id); // } else if (this.id instanceof UUID) { // return new NodeId(namespaceIndex, (UUID) this.id); // } // throw new IllegalStateException("Invalid id type: " + this.id); // } // // public NodeId toNodeId(final UShort namespaceIndex) { // if (this.id instanceof String) { // return new NodeId(namespaceIndex, (String) this.id); // } else if (this.id instanceof UInteger) { // return new NodeId(namespaceIndex, (UInteger) this.id); // } else if (this.id instanceof ByteString) { // return new NodeId(namespaceIndex, (ByteString) this.id); // } else if (this.id instanceof UUID) { // return new NodeId(namespaceIndex, (UUID) this.id); // } // throw new IllegalStateException("Invalid id type: " + this.id); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this).add("type", this.type).add("id", this.id).toString(); // } // // public Serializable getValue() { // return this.id; // } // // public static PartialNodeId fromExpandedNodeId(final ExpandedNodeId node) { // if (node == null) { // return null; // } // // final Object value = node.getIdentifier(); // // if (value instanceof String) { // return new PartialNodeId((String) value); // } else if (value instanceof UInteger) { // return new PartialNodeId((UInteger) value); // } else if (value instanceof UUID) { // return new PartialNodeId((UUID) value); // } else if (value instanceof ByteString) { // return new PartialNodeId((ByteString) value); // } // // throw new IllegalStateException(String.format("Unknown node id type: " + value)); // } // }
import org.apache.camel.Endpoint; import org.apache.camel.Exchange; import org.apache.camel.Message; import org.apache.camel.component.milo.NamespaceId; import org.apache.camel.component.milo.PartialNodeId; import org.apache.camel.impl.DefaultProducer; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
/* * Copyright (C) 2016 Jens Reimann <jreimann@redhat.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.milo.client; public class MiloClientProducer extends DefaultProducer { private static final Logger LOG = LoggerFactory.getLogger(MiloClientProducer.class); private final MiloClientConnection connection;
// Path: camel-milo/src/main/java/org/apache/camel/component/milo/NamespaceId.java // public class NamespaceId { // private final String uri; // private final UShort numeric; // // public NamespaceId(final String uri) { // requireNonNull(uri); // // this.uri = uri; // this.numeric = null; // } // // public NamespaceId(final UShort numeric) { // requireNonNull(numeric); // // this.uri = null; // this.numeric = numeric; // } // // public String getUri() { // return this.uri; // } // // public UShort getNumeric() { // return this.numeric; // } // // public boolean isNumeric() { // return this.numeric != null; // } // // @Override // public String toString() { // if (isNumeric()) { // return String.format("[Namespace - numeric: %s]", this.numeric); // } else { // return String.format("[Namespace - URI: %s]", this.uri); // } // } // // public Serializable getValue() { // return this.uri != null ? this.uri : this.numeric; // } // // public static NamespaceId fromExpandedNodeId(final ExpandedNodeId id) { // if (id == null) { // return null; // } // // if (id.getNamespaceUri() != null) { // return new NamespaceId(id.getNamespaceUri()); // } // if (id.getNamespaceIndex() != null) { // return new NamespaceId(id.getNamespaceIndex()); // } // // throw new IllegalStateException(String.format("Unknown namespace type")); // } // } // // Path: camel-milo/src/main/java/org/apache/camel/component/milo/PartialNodeId.java // public class PartialNodeId { // // private IdType type; // // private final Serializable id; // // public PartialNodeId(final int id) { // this(uint(id)); // } // // public PartialNodeId(final UInteger id) { // requireNonNull(id); // this.id = id; // } // // public PartialNodeId(final String id) { // requireNonNull(id); // this.id = id; // } // // public PartialNodeId(final UUID id) { // requireNonNull(id); // this.id = id; // } // // public PartialNodeId(final ByteString id) { // requireNonNull(id); // this.id = id; // } // // public NodeId toNodeId(final int namespaceIndex) { // if (this.id instanceof String) { // return new NodeId(namespaceIndex, (String) this.id); // } else if (this.id instanceof UInteger) { // return new NodeId(ushort(namespaceIndex), (UInteger) this.id); // } else if (this.id instanceof ByteString) { // return new NodeId(namespaceIndex, (ByteString) this.id); // } else if (this.id instanceof UUID) { // return new NodeId(namespaceIndex, (UUID) this.id); // } // throw new IllegalStateException("Invalid id type: " + this.id); // } // // public NodeId toNodeId(final UShort namespaceIndex) { // if (this.id instanceof String) { // return new NodeId(namespaceIndex, (String) this.id); // } else if (this.id instanceof UInteger) { // return new NodeId(namespaceIndex, (UInteger) this.id); // } else if (this.id instanceof ByteString) { // return new NodeId(namespaceIndex, (ByteString) this.id); // } else if (this.id instanceof UUID) { // return new NodeId(namespaceIndex, (UUID) this.id); // } // throw new IllegalStateException("Invalid id type: " + this.id); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this).add("type", this.type).add("id", this.id).toString(); // } // // public Serializable getValue() { // return this.id; // } // // public static PartialNodeId fromExpandedNodeId(final ExpandedNodeId node) { // if (node == null) { // return null; // } // // final Object value = node.getIdentifier(); // // if (value instanceof String) { // return new PartialNodeId((String) value); // } else if (value instanceof UInteger) { // return new PartialNodeId((UInteger) value); // } else if (value instanceof UUID) { // return new PartialNodeId((UUID) value); // } else if (value instanceof ByteString) { // return new PartialNodeId((ByteString) value); // } // // throw new IllegalStateException(String.format("Unknown node id type: " + value)); // } // } // Path: camel-milo/src/main/java/org/apache/camel/component/milo/client/MiloClientProducer.java import org.apache.camel.Endpoint; import org.apache.camel.Exchange; import org.apache.camel.Message; import org.apache.camel.component.milo.NamespaceId; import org.apache.camel.component.milo.PartialNodeId; import org.apache.camel.impl.DefaultProducer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /* * Copyright (C) 2016 Jens Reimann <jreimann@redhat.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.milo.client; public class MiloClientProducer extends DefaultProducer { private static final Logger LOG = LoggerFactory.getLogger(MiloClientProducer.class); private final MiloClientConnection connection;
private final NamespaceId namespaceId;
ctron/de.dentrassi.camel.milo
camel-milo/src/main/java/org/apache/camel/component/milo/client/MiloClientItemConfiguration.java
// Path: camel-milo/src/main/java/org/apache/camel/component/milo/NamespaceId.java // public class NamespaceId { // private final String uri; // private final UShort numeric; // // public NamespaceId(final String uri) { // requireNonNull(uri); // // this.uri = uri; // this.numeric = null; // } // // public NamespaceId(final UShort numeric) { // requireNonNull(numeric); // // this.uri = null; // this.numeric = numeric; // } // // public String getUri() { // return this.uri; // } // // public UShort getNumeric() { // return this.numeric; // } // // public boolean isNumeric() { // return this.numeric != null; // } // // @Override // public String toString() { // if (isNumeric()) { // return String.format("[Namespace - numeric: %s]", this.numeric); // } else { // return String.format("[Namespace - URI: %s]", this.uri); // } // } // // public Serializable getValue() { // return this.uri != null ? this.uri : this.numeric; // } // // public static NamespaceId fromExpandedNodeId(final ExpandedNodeId id) { // if (id == null) { // return null; // } // // if (id.getNamespaceUri() != null) { // return new NamespaceId(id.getNamespaceUri()); // } // if (id.getNamespaceIndex() != null) { // return new NamespaceId(id.getNamespaceIndex()); // } // // throw new IllegalStateException(String.format("Unknown namespace type")); // } // } // // Path: camel-milo/src/main/java/org/apache/camel/component/milo/PartialNodeId.java // public class PartialNodeId { // // private IdType type; // // private final Serializable id; // // public PartialNodeId(final int id) { // this(uint(id)); // } // // public PartialNodeId(final UInteger id) { // requireNonNull(id); // this.id = id; // } // // public PartialNodeId(final String id) { // requireNonNull(id); // this.id = id; // } // // public PartialNodeId(final UUID id) { // requireNonNull(id); // this.id = id; // } // // public PartialNodeId(final ByteString id) { // requireNonNull(id); // this.id = id; // } // // public NodeId toNodeId(final int namespaceIndex) { // if (this.id instanceof String) { // return new NodeId(namespaceIndex, (String) this.id); // } else if (this.id instanceof UInteger) { // return new NodeId(ushort(namespaceIndex), (UInteger) this.id); // } else if (this.id instanceof ByteString) { // return new NodeId(namespaceIndex, (ByteString) this.id); // } else if (this.id instanceof UUID) { // return new NodeId(namespaceIndex, (UUID) this.id); // } // throw new IllegalStateException("Invalid id type: " + this.id); // } // // public NodeId toNodeId(final UShort namespaceIndex) { // if (this.id instanceof String) { // return new NodeId(namespaceIndex, (String) this.id); // } else if (this.id instanceof UInteger) { // return new NodeId(namespaceIndex, (UInteger) this.id); // } else if (this.id instanceof ByteString) { // return new NodeId(namespaceIndex, (ByteString) this.id); // } else if (this.id instanceof UUID) { // return new NodeId(namespaceIndex, (UUID) this.id); // } // throw new IllegalStateException("Invalid id type: " + this.id); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this).add("type", this.type).add("id", this.id).toString(); // } // // public Serializable getValue() { // return this.id; // } // // public static PartialNodeId fromExpandedNodeId(final ExpandedNodeId node) { // if (node == null) { // return null; // } // // final Object value = node.getIdentifier(); // // if (value instanceof String) { // return new PartialNodeId((String) value); // } else if (value instanceof UInteger) { // return new PartialNodeId((UInteger) value); // } else if (value instanceof UUID) { // return new PartialNodeId((UUID) value); // } else if (value instanceof ByteString) { // return new PartialNodeId((ByteString) value); // } // // throw new IllegalStateException(String.format("Unknown node id type: " + value)); // } // }
import org.apache.camel.component.milo.NamespaceId; import org.apache.camel.component.milo.PartialNodeId;
/* * Copyright (C) 2016 Jens Reimann <jreimann@redhat.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.milo.client; public interface MiloClientItemConfiguration { public NamespaceId makeNamespaceId();
// Path: camel-milo/src/main/java/org/apache/camel/component/milo/NamespaceId.java // public class NamespaceId { // private final String uri; // private final UShort numeric; // // public NamespaceId(final String uri) { // requireNonNull(uri); // // this.uri = uri; // this.numeric = null; // } // // public NamespaceId(final UShort numeric) { // requireNonNull(numeric); // // this.uri = null; // this.numeric = numeric; // } // // public String getUri() { // return this.uri; // } // // public UShort getNumeric() { // return this.numeric; // } // // public boolean isNumeric() { // return this.numeric != null; // } // // @Override // public String toString() { // if (isNumeric()) { // return String.format("[Namespace - numeric: %s]", this.numeric); // } else { // return String.format("[Namespace - URI: %s]", this.uri); // } // } // // public Serializable getValue() { // return this.uri != null ? this.uri : this.numeric; // } // // public static NamespaceId fromExpandedNodeId(final ExpandedNodeId id) { // if (id == null) { // return null; // } // // if (id.getNamespaceUri() != null) { // return new NamespaceId(id.getNamespaceUri()); // } // if (id.getNamespaceIndex() != null) { // return new NamespaceId(id.getNamespaceIndex()); // } // // throw new IllegalStateException(String.format("Unknown namespace type")); // } // } // // Path: camel-milo/src/main/java/org/apache/camel/component/milo/PartialNodeId.java // public class PartialNodeId { // // private IdType type; // // private final Serializable id; // // public PartialNodeId(final int id) { // this(uint(id)); // } // // public PartialNodeId(final UInteger id) { // requireNonNull(id); // this.id = id; // } // // public PartialNodeId(final String id) { // requireNonNull(id); // this.id = id; // } // // public PartialNodeId(final UUID id) { // requireNonNull(id); // this.id = id; // } // // public PartialNodeId(final ByteString id) { // requireNonNull(id); // this.id = id; // } // // public NodeId toNodeId(final int namespaceIndex) { // if (this.id instanceof String) { // return new NodeId(namespaceIndex, (String) this.id); // } else if (this.id instanceof UInteger) { // return new NodeId(ushort(namespaceIndex), (UInteger) this.id); // } else if (this.id instanceof ByteString) { // return new NodeId(namespaceIndex, (ByteString) this.id); // } else if (this.id instanceof UUID) { // return new NodeId(namespaceIndex, (UUID) this.id); // } // throw new IllegalStateException("Invalid id type: " + this.id); // } // // public NodeId toNodeId(final UShort namespaceIndex) { // if (this.id instanceof String) { // return new NodeId(namespaceIndex, (String) this.id); // } else if (this.id instanceof UInteger) { // return new NodeId(namespaceIndex, (UInteger) this.id); // } else if (this.id instanceof ByteString) { // return new NodeId(namespaceIndex, (ByteString) this.id); // } else if (this.id instanceof UUID) { // return new NodeId(namespaceIndex, (UUID) this.id); // } // throw new IllegalStateException("Invalid id type: " + this.id); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this).add("type", this.type).add("id", this.id).toString(); // } // // public Serializable getValue() { // return this.id; // } // // public static PartialNodeId fromExpandedNodeId(final ExpandedNodeId node) { // if (node == null) { // return null; // } // // final Object value = node.getIdentifier(); // // if (value instanceof String) { // return new PartialNodeId((String) value); // } else if (value instanceof UInteger) { // return new PartialNodeId((UInteger) value); // } else if (value instanceof UUID) { // return new PartialNodeId((UUID) value); // } else if (value instanceof ByteString) { // return new PartialNodeId((ByteString) value); // } // // throw new IllegalStateException(String.format("Unknown node id type: " + value)); // } // } // Path: camel-milo/src/main/java/org/apache/camel/component/milo/client/MiloClientItemConfiguration.java import org.apache.camel.component.milo.NamespaceId; import org.apache.camel.component.milo.PartialNodeId; /* * Copyright (C) 2016 Jens Reimann <jreimann@redhat.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.milo.client; public interface MiloClientItemConfiguration { public NamespaceId makeNamespaceId();
public PartialNodeId makePartialNodeId();
ctron/de.dentrassi.camel.milo
camel-milo/src/main/java/org/apache/camel/component/milo/client/MiloClientConfiguration.java
// Path: camel-milo/src/main/java/org/apache/camel/component/milo/KeyStoreLoader.java // public class KeyStoreLoader { // public static final String DEFAULT_KEY_STORE_TYPE = "PKCS12"; // // private String type = DEFAULT_KEY_STORE_TYPE; // private URL url; // private String keyStorePassword; // private String keyPassword; // private String keyAlias; // // public static class Result { // // private final X509Certificate certificate; // private final KeyPair keyPair; // // public Result(final X509Certificate certificate, final KeyPair keyPair) { // this.certificate = certificate; // this.keyPair = keyPair; // } // // public X509Certificate getCertificate() { // return this.certificate; // } // // public KeyPair getKeyPair() { // return this.keyPair; // } // } // // public KeyStoreLoader() { // } // // public void setType(final String type) { // this.type = type != null ? type : DEFAULT_KEY_STORE_TYPE; // } // // public String getType() { // return this.type; // } // // public void setUrl(final URL url) { // this.url = url; // } // // public URL getUrl() { // return this.url; // } // // public void setUrl(final String url) throws MalformedURLException { // this.url = new URL(url); // } // // public void setKeyStorePassword(final String keyStorePassword) { // this.keyStorePassword = keyStorePassword; // } // // public String getKeyStorePassword() { // return this.keyStorePassword; // } // // public void setKeyPassword(final String keyPassword) { // this.keyPassword = keyPassword; // } // // public String getKeyPassword() { // return this.keyPassword; // } // // public void setKeyAlias(final String keyAlias) { // this.keyAlias = keyAlias; // } // // public String getKeyAlias() { // return this.keyAlias; // } // // public Result load() throws GeneralSecurityException, IOException { // // final KeyStore keyStore = KeyStore.getInstance(this.type); // // try (InputStream stream = this.url.openStream()) { // keyStore.load(stream, this.keyStorePassword != null ? this.keyStorePassword.toCharArray() : null); // } // // String effectiveKeyAlias = this.keyAlias; // // if (effectiveKeyAlias == null) { // if (keyStore.size() != 1) { // throw new IllegalArgumentException( // "Key store contains more than one key. The use of the 'keyAlias' parameter is required."); // } // try { // effectiveKeyAlias = keyStore.aliases().nextElement(); // } catch (final NoSuchElementException e) { // throw new RuntimeException("Failed to enumerate key alias", e); // } // } // // final Key privateKey = keyStore.getKey(effectiveKeyAlias, // this.keyPassword != null ? this.keyPassword.toCharArray() : null); // // if (privateKey instanceof PrivateKey) { // final X509Certificate certificate = (X509Certificate) keyStore.getCertificate(effectiveKeyAlias); // if (certificate == null) { // return null; // } // // final PublicKey publicKey = certificate.getPublicKey(); // final KeyPair keyPair = new KeyPair(publicKey, (PrivateKey) privateKey); // return new Result(certificate, keyPair); // } // // return null; // } // }
import java.net.MalformedURLException; import java.net.URL; import org.apache.camel.component.milo.KeyStoreLoader; import org.apache.camel.spi.UriParam; import org.apache.camel.spi.UriParams;
private String applicationUri = DEFAULT_APPLICATION_URI; @UriParam(label = "client", defaultValue = DEFAULT_PRODUCT_URI) private String productUri = DEFAULT_PRODUCT_URI; @UriParam(label = "client") private Long requestTimeout; @UriParam(label = "client") private Long channelLifetime; @UriParam(label = "client") private String sessionName; @UriParam(label = "client") private Long sessionTimeout; @UriParam(label = "client") private Long maxPendingPublishRequests; @UriParam(label = "client") private Long maxResponseMessageSize; @UriParam(label = "client") private Boolean secureChannelReauthenticationEnabled; @UriParam(label = "client") private URL keyStoreUrl; @UriParam(label = "client")
// Path: camel-milo/src/main/java/org/apache/camel/component/milo/KeyStoreLoader.java // public class KeyStoreLoader { // public static final String DEFAULT_KEY_STORE_TYPE = "PKCS12"; // // private String type = DEFAULT_KEY_STORE_TYPE; // private URL url; // private String keyStorePassword; // private String keyPassword; // private String keyAlias; // // public static class Result { // // private final X509Certificate certificate; // private final KeyPair keyPair; // // public Result(final X509Certificate certificate, final KeyPair keyPair) { // this.certificate = certificate; // this.keyPair = keyPair; // } // // public X509Certificate getCertificate() { // return this.certificate; // } // // public KeyPair getKeyPair() { // return this.keyPair; // } // } // // public KeyStoreLoader() { // } // // public void setType(final String type) { // this.type = type != null ? type : DEFAULT_KEY_STORE_TYPE; // } // // public String getType() { // return this.type; // } // // public void setUrl(final URL url) { // this.url = url; // } // // public URL getUrl() { // return this.url; // } // // public void setUrl(final String url) throws MalformedURLException { // this.url = new URL(url); // } // // public void setKeyStorePassword(final String keyStorePassword) { // this.keyStorePassword = keyStorePassword; // } // // public String getKeyStorePassword() { // return this.keyStorePassword; // } // // public void setKeyPassword(final String keyPassword) { // this.keyPassword = keyPassword; // } // // public String getKeyPassword() { // return this.keyPassword; // } // // public void setKeyAlias(final String keyAlias) { // this.keyAlias = keyAlias; // } // // public String getKeyAlias() { // return this.keyAlias; // } // // public Result load() throws GeneralSecurityException, IOException { // // final KeyStore keyStore = KeyStore.getInstance(this.type); // // try (InputStream stream = this.url.openStream()) { // keyStore.load(stream, this.keyStorePassword != null ? this.keyStorePassword.toCharArray() : null); // } // // String effectiveKeyAlias = this.keyAlias; // // if (effectiveKeyAlias == null) { // if (keyStore.size() != 1) { // throw new IllegalArgumentException( // "Key store contains more than one key. The use of the 'keyAlias' parameter is required."); // } // try { // effectiveKeyAlias = keyStore.aliases().nextElement(); // } catch (final NoSuchElementException e) { // throw new RuntimeException("Failed to enumerate key alias", e); // } // } // // final Key privateKey = keyStore.getKey(effectiveKeyAlias, // this.keyPassword != null ? this.keyPassword.toCharArray() : null); // // if (privateKey instanceof PrivateKey) { // final X509Certificate certificate = (X509Certificate) keyStore.getCertificate(effectiveKeyAlias); // if (certificate == null) { // return null; // } // // final PublicKey publicKey = certificate.getPublicKey(); // final KeyPair keyPair = new KeyPair(publicKey, (PrivateKey) privateKey); // return new Result(certificate, keyPair); // } // // return null; // } // } // Path: camel-milo/src/main/java/org/apache/camel/component/milo/client/MiloClientConfiguration.java import java.net.MalformedURLException; import java.net.URL; import org.apache.camel.component.milo.KeyStoreLoader; import org.apache.camel.spi.UriParam; import org.apache.camel.spi.UriParams; private String applicationUri = DEFAULT_APPLICATION_URI; @UriParam(label = "client", defaultValue = DEFAULT_PRODUCT_URI) private String productUri = DEFAULT_PRODUCT_URI; @UriParam(label = "client") private Long requestTimeout; @UriParam(label = "client") private Long channelLifetime; @UriParam(label = "client") private String sessionName; @UriParam(label = "client") private Long sessionTimeout; @UriParam(label = "client") private Long maxPendingPublishRequests; @UriParam(label = "client") private Long maxResponseMessageSize; @UriParam(label = "client") private Boolean secureChannelReauthenticationEnabled; @UriParam(label = "client") private URL keyStoreUrl; @UriParam(label = "client")
private String keyStoreType = KeyStoreLoader.DEFAULT_KEY_STORE_TYPE;
robtimus/sftp-fs
src/test/java/com/github/robtimus/filesystems/sftp/SFTPFileSystemWithoutSystemDirsTest.java
// Path: src/test/java/com/github/robtimus/filesystems/sftp/server/FixedSftpSubsystem.java // @SuppressWarnings("javadoc") // public class FixedSftpSubsystem extends SftpSubsystem { // // public FixedSftpSubsystem(ExecutorService executorService, boolean shutdownOnExit, UnsupportedAttributePolicy policy, // SftpFileSystemAccessor accessor, SftpErrorStatusDataHandler errorStatusDataHandler) { // super(executorService, shutdownOnExit, policy, accessor, errorStatusDataHandler); // } // // @Override // protected Map<String, Object> doStat(int id, String path, int flags) throws IOException { // Path p = resolveFile(path); // return resolveFileAttributes(p, flags, IoUtils.getLinkOptions(true)); // } // // public static final class Factory extends SftpSubsystemFactory { // // @Override // public Command create() { // SftpSubsystem subsystem = new FixedSftpSubsystem(getExecutorService(), isShutdownOnExit(), getUnsupportedAttributePolicy(), // getFileSystemAccessor(), getErrorStatusDataHandler()); // Collection<? extends SftpEventListener> listeners = getRegisteredListeners(); // if (GenericUtils.size(listeners) > 0) { // for (SftpEventListener l : listeners) { // subsystem.addSftpEventListener(l); // } // } // // return subsystem; // } // } // // public static final class FactoryWithoutSystemDirs extends SftpSubsystemFactory { // // @Override // public Command create() { // SftpSubsystem subsystem = new FixedSftpSubsystem(getExecutorService(), isShutdownOnExit(), getUnsupportedAttributePolicy(), // getFileSystemAccessor(), getErrorStatusDataHandler()); // Collection<? extends SftpEventListener> listeners = getRegisteredListeners(); // if (GenericUtils.size(listeners) > 0) { // for (SftpEventListener l : listeners) { // subsystem.addSftpEventListener(l); // } // } // subsystem.addSftpEventListener(new AbstractSftpEventListenerAdapter() { // @Override // public void open(ServerSession session, String remoteHandle, Handle localHandle) { // if (localHandle instanceof DirectoryHandle) { // DirectoryHandle directoryHandle = (DirectoryHandle) localHandle; // directoryHandle.markDotSent(); // directoryHandle.markDotDotSent(); // } // } // }); // // return subsystem; // } // } // }
import java.io.IOException; import java.security.NoSuchAlgorithmException; import org.junit.jupiter.api.BeforeAll; import com.github.robtimus.filesystems.sftp.server.FixedSftpSubsystem;
/* * SFTPFileSystemWithoutSystemDirsTest.java * Copyright 2019 Rob Spoor * * 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.github.robtimus.filesystems.sftp; class SFTPFileSystemWithoutSystemDirsTest extends SFTPFileSystemTest { @BeforeAll static void setupClass() throws NoSuchAlgorithmException, IOException {
// Path: src/test/java/com/github/robtimus/filesystems/sftp/server/FixedSftpSubsystem.java // @SuppressWarnings("javadoc") // public class FixedSftpSubsystem extends SftpSubsystem { // // public FixedSftpSubsystem(ExecutorService executorService, boolean shutdownOnExit, UnsupportedAttributePolicy policy, // SftpFileSystemAccessor accessor, SftpErrorStatusDataHandler errorStatusDataHandler) { // super(executorService, shutdownOnExit, policy, accessor, errorStatusDataHandler); // } // // @Override // protected Map<String, Object> doStat(int id, String path, int flags) throws IOException { // Path p = resolveFile(path); // return resolveFileAttributes(p, flags, IoUtils.getLinkOptions(true)); // } // // public static final class Factory extends SftpSubsystemFactory { // // @Override // public Command create() { // SftpSubsystem subsystem = new FixedSftpSubsystem(getExecutorService(), isShutdownOnExit(), getUnsupportedAttributePolicy(), // getFileSystemAccessor(), getErrorStatusDataHandler()); // Collection<? extends SftpEventListener> listeners = getRegisteredListeners(); // if (GenericUtils.size(listeners) > 0) { // for (SftpEventListener l : listeners) { // subsystem.addSftpEventListener(l); // } // } // // return subsystem; // } // } // // public static final class FactoryWithoutSystemDirs extends SftpSubsystemFactory { // // @Override // public Command create() { // SftpSubsystem subsystem = new FixedSftpSubsystem(getExecutorService(), isShutdownOnExit(), getUnsupportedAttributePolicy(), // getFileSystemAccessor(), getErrorStatusDataHandler()); // Collection<? extends SftpEventListener> listeners = getRegisteredListeners(); // if (GenericUtils.size(listeners) > 0) { // for (SftpEventListener l : listeners) { // subsystem.addSftpEventListener(l); // } // } // subsystem.addSftpEventListener(new AbstractSftpEventListenerAdapter() { // @Override // public void open(ServerSession session, String remoteHandle, Handle localHandle) { // if (localHandle instanceof DirectoryHandle) { // DirectoryHandle directoryHandle = (DirectoryHandle) localHandle; // directoryHandle.markDotSent(); // directoryHandle.markDotDotSent(); // } // } // }); // // return subsystem; // } // } // } // Path: src/test/java/com/github/robtimus/filesystems/sftp/SFTPFileSystemWithoutSystemDirsTest.java import java.io.IOException; import java.security.NoSuchAlgorithmException; import org.junit.jupiter.api.BeforeAll; import com.github.robtimus.filesystems.sftp.server.FixedSftpSubsystem; /* * SFTPFileSystemWithoutSystemDirsTest.java * Copyright 2019 Rob Spoor * * 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.github.robtimus.filesystems.sftp; class SFTPFileSystemWithoutSystemDirsTest extends SFTPFileSystemTest { @BeforeAll static void setupClass() throws NoSuchAlgorithmException, IOException {
setupClass(new FixedSftpSubsystem.FactoryWithoutSystemDirs());
robtimus/sftp-fs
src/test/java/com/github/robtimus/filesystems/sftp/AbstractSFTPFileSystemTest.java
// Path: src/test/java/com/github/robtimus/filesystems/sftp/server/FixedSftpSubsystem.java // @SuppressWarnings("javadoc") // public class FixedSftpSubsystem extends SftpSubsystem { // // public FixedSftpSubsystem(ExecutorService executorService, boolean shutdownOnExit, UnsupportedAttributePolicy policy, // SftpFileSystemAccessor accessor, SftpErrorStatusDataHandler errorStatusDataHandler) { // super(executorService, shutdownOnExit, policy, accessor, errorStatusDataHandler); // } // // @Override // protected Map<String, Object> doStat(int id, String path, int flags) throws IOException { // Path p = resolveFile(path); // return resolveFileAttributes(p, flags, IoUtils.getLinkOptions(true)); // } // // public static final class Factory extends SftpSubsystemFactory { // // @Override // public Command create() { // SftpSubsystem subsystem = new FixedSftpSubsystem(getExecutorService(), isShutdownOnExit(), getUnsupportedAttributePolicy(), // getFileSystemAccessor(), getErrorStatusDataHandler()); // Collection<? extends SftpEventListener> listeners = getRegisteredListeners(); // if (GenericUtils.size(listeners) > 0) { // for (SftpEventListener l : listeners) { // subsystem.addSftpEventListener(l); // } // } // // return subsystem; // } // } // // public static final class FactoryWithoutSystemDirs extends SftpSubsystemFactory { // // @Override // public Command create() { // SftpSubsystem subsystem = new FixedSftpSubsystem(getExecutorService(), isShutdownOnExit(), getUnsupportedAttributePolicy(), // getFileSystemAccessor(), getErrorStatusDataHandler()); // Collection<? extends SftpEventListener> listeners = getRegisteredListeners(); // if (GenericUtils.size(listeners) > 0) { // for (SftpEventListener l : listeners) { // subsystem.addSftpEventListener(l); // } // } // subsystem.addSftpEventListener(new AbstractSftpEventListenerAdapter() { // @Override // public void open(ServerSession session, String remoteHandle, Handle localHandle) { // if (localHandle instanceof DirectoryHandle) { // DirectoryHandle directoryHandle = (DirectoryHandle) localHandle; // directoryHandle.markDotSent(); // directoryHandle.markDotDotSent(); // } // } // }); // // return subsystem; // } // } // }
import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.spy; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.ServerSocket; import java.net.URI; import java.nio.charset.StandardCharsets; import java.nio.file.DirectoryStream; import java.nio.file.FileSystemException; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.LinkOption; import java.nio.file.NoSuchFileException; import java.nio.file.OpenOption; import java.nio.file.Path; import java.nio.file.SimpleFileVisitor; import java.nio.file.StandardOpenOption; import java.nio.file.attribute.BasicFileAttributes; import java.security.GeneralSecurityException; import java.security.KeyFactory; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import java.security.PublicKey; import java.security.spec.X509EncodedKeySpec; import java.util.Arrays; import java.util.Base64; import java.util.Collection; import java.util.Iterator; import java.util.Map; import org.apache.sshd.common.file.virtualfs.VirtualFileSystemFactory; import org.apache.sshd.common.keyprovider.MappedKeyPairProvider; import org.apache.sshd.server.SshServer; import org.apache.sshd.server.session.ServerSession; import org.apache.sshd.server.subsystem.sftp.SftpSubsystemFactory; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import com.github.robtimus.filesystems.sftp.server.FixedSftpSubsystem; import com.jcraft.jsch.SftpException;
protected final SFTPFileSystem fileSystem = sftpFileSystem; protected final SFTPFileSystem fileSystem2 = sftpFileSystem2; private static PublicKey readPublicKey(String resource) { try { ByteArrayOutputStream output = new ByteArrayOutputStream(); try (InputStream input = AbstractSFTPFileSystemTest.class.getResourceAsStream(resource)) { byte[] buffer = new byte[1024]; int len; while ((len = input.read(buffer)) != -1) { output.write(buffer, 0, len); } } // public key parsing based on https://gist.github.com/destan/b708d11bd4f403506d6d5bb5fe6a82c5 String publicKeyContent = new String(output.toString("UTF-8")) .replace("\\n", "") .replace("-----BEGIN PUBLIC KEY-----", "") .replace("-----END PUBLIC KEY-----", ""); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64.getMimeDecoder().decode(publicKeyContent)); return keyFactory.generatePublic(keySpec); } catch (IOException | GeneralSecurityException e) { throw new IllegalStateException(e); } } @BeforeAll static void setupClass() throws NoSuchAlgorithmException, IOException {
// Path: src/test/java/com/github/robtimus/filesystems/sftp/server/FixedSftpSubsystem.java // @SuppressWarnings("javadoc") // public class FixedSftpSubsystem extends SftpSubsystem { // // public FixedSftpSubsystem(ExecutorService executorService, boolean shutdownOnExit, UnsupportedAttributePolicy policy, // SftpFileSystemAccessor accessor, SftpErrorStatusDataHandler errorStatusDataHandler) { // super(executorService, shutdownOnExit, policy, accessor, errorStatusDataHandler); // } // // @Override // protected Map<String, Object> doStat(int id, String path, int flags) throws IOException { // Path p = resolveFile(path); // return resolveFileAttributes(p, flags, IoUtils.getLinkOptions(true)); // } // // public static final class Factory extends SftpSubsystemFactory { // // @Override // public Command create() { // SftpSubsystem subsystem = new FixedSftpSubsystem(getExecutorService(), isShutdownOnExit(), getUnsupportedAttributePolicy(), // getFileSystemAccessor(), getErrorStatusDataHandler()); // Collection<? extends SftpEventListener> listeners = getRegisteredListeners(); // if (GenericUtils.size(listeners) > 0) { // for (SftpEventListener l : listeners) { // subsystem.addSftpEventListener(l); // } // } // // return subsystem; // } // } // // public static final class FactoryWithoutSystemDirs extends SftpSubsystemFactory { // // @Override // public Command create() { // SftpSubsystem subsystem = new FixedSftpSubsystem(getExecutorService(), isShutdownOnExit(), getUnsupportedAttributePolicy(), // getFileSystemAccessor(), getErrorStatusDataHandler()); // Collection<? extends SftpEventListener> listeners = getRegisteredListeners(); // if (GenericUtils.size(listeners) > 0) { // for (SftpEventListener l : listeners) { // subsystem.addSftpEventListener(l); // } // } // subsystem.addSftpEventListener(new AbstractSftpEventListenerAdapter() { // @Override // public void open(ServerSession session, String remoteHandle, Handle localHandle) { // if (localHandle instanceof DirectoryHandle) { // DirectoryHandle directoryHandle = (DirectoryHandle) localHandle; // directoryHandle.markDotSent(); // directoryHandle.markDotDotSent(); // } // } // }); // // return subsystem; // } // } // } // Path: src/test/java/com/github/robtimus/filesystems/sftp/AbstractSFTPFileSystemTest.java import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.spy; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.ServerSocket; import java.net.URI; import java.nio.charset.StandardCharsets; import java.nio.file.DirectoryStream; import java.nio.file.FileSystemException; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.LinkOption; import java.nio.file.NoSuchFileException; import java.nio.file.OpenOption; import java.nio.file.Path; import java.nio.file.SimpleFileVisitor; import java.nio.file.StandardOpenOption; import java.nio.file.attribute.BasicFileAttributes; import java.security.GeneralSecurityException; import java.security.KeyFactory; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import java.security.PublicKey; import java.security.spec.X509EncodedKeySpec; import java.util.Arrays; import java.util.Base64; import java.util.Collection; import java.util.Iterator; import java.util.Map; import org.apache.sshd.common.file.virtualfs.VirtualFileSystemFactory; import org.apache.sshd.common.keyprovider.MappedKeyPairProvider; import org.apache.sshd.server.SshServer; import org.apache.sshd.server.session.ServerSession; import org.apache.sshd.server.subsystem.sftp.SftpSubsystemFactory; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import com.github.robtimus.filesystems.sftp.server.FixedSftpSubsystem; import com.jcraft.jsch.SftpException; protected final SFTPFileSystem fileSystem = sftpFileSystem; protected final SFTPFileSystem fileSystem2 = sftpFileSystem2; private static PublicKey readPublicKey(String resource) { try { ByteArrayOutputStream output = new ByteArrayOutputStream(); try (InputStream input = AbstractSFTPFileSystemTest.class.getResourceAsStream(resource)) { byte[] buffer = new byte[1024]; int len; while ((len = input.read(buffer)) != -1) { output.write(buffer, 0, len); } } // public key parsing based on https://gist.github.com/destan/b708d11bd4f403506d6d5bb5fe6a82c5 String publicKeyContent = new String(output.toString("UTF-8")) .replace("\\n", "") .replace("-----BEGIN PUBLIC KEY-----", "") .replace("-----END PUBLIC KEY-----", ""); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64.getMimeDecoder().decode(publicKeyContent)); return keyFactory.generatePublic(keySpec); } catch (IOException | GeneralSecurityException e) { throw new IllegalStateException(e); } } @BeforeAll static void setupClass() throws NoSuchAlgorithmException, IOException {
setupClass(new FixedSftpSubsystem.Factory());
radkovo/CSSBox
src/main/java/org/fit/cssbox/render/RadialGradient.java
// Path: src/main/java/org/fit/cssbox/layout/Rectangle.java // public class Rectangle // { // public float x; // public float y; // public float width; // public float height; // // public Rectangle(float x, float y, float width, float height) // { // this.x = x; // this.y = y; // this.width = width; // this.height = height; // } // // public Rectangle(float width, float height) // { // this.x = 0; // this.y = 0; // this.width = width; // this.height = height; // } // // public Rectangle() // { // this.x = 0; // this.y = 0; // this.width = 0; // this.height = 0; // } // // public Rectangle(Rectangle src) // { // this.x = src.x; // this.y = src.y; // this.width = src.width; // this.height = src.height; // } // // public Rectangle(Dimension src) // { // this.x = 0; // this.y = 0; // this.width = src.width; // this.height = src.height; // } // // public float getX() // { // return x; // } // // public void setX(float x) // { // this.x = x; // } // // public float getY() // { // return y; // } // // public void setY(float y) // { // this.y = y; // } // // public float getWidth() // { // return width; // } // // public void setWidth(float width) // { // this.width = width; // } // // public float getHeight() // { // return height; // } // // public void setHeight(float height) // { // this.height = height; // } // // public void setLocation(float x, float y) // { // this.x = x; // this.y = y; // } // // public void setSize(float width, float height) // { // this.width = width; // this.height = height; // } // // public Dimension getSize() // { // return new Dimension(width, height); // } // // public boolean contains(float x, float y) // { // if (width <= 0 || height <= 0) // return false; // return (x >= this.x && x < this.x + this.width && // y >= this.y && y < this.y + this.height); // } // // public boolean intersects(Rectangle r) // { // float tw = this.width; // float th = this.height; // float rw = r.width; // float rh = r.height; // if (rw <= 0 || rh <= 0 || tw <= 0 || th <= 0) { // return false; // } // float tx = this.x; // float ty = this.y; // float rx = r.x; // float ry = r.y; // rw += rx; // rh += ry; // tw += tx; // th += ty; // // overflow || intersect // return ((rw < rx || rw > tx) && // (rh < ry || rh > ty) && // (tw < tx || tw > rx) && // (th < ty || th > ry)); // } // // public Rectangle intersection(Rectangle r) // { // float tx1 = this.x; // float ty1 = this.y; // float rx1 = r.x; // float ry1 = r.y; // float tx2 = tx1; tx2 += this.width; // float ty2 = ty1; ty2 += this.height; // float rx2 = rx1; rx2 += r.width; // float ry2 = ry1; ry2 += r.height; // if (tx1 < rx1) tx1 = rx1; // if (ty1 < ry1) ty1 = ry1; // if (tx2 > rx2) tx2 = rx2; // if (ty2 > ry2) ty2 = ry2; // tx2 -= tx1; // ty2 -= ty1; // return new Rectangle(tx1, ty1, tx2, ty2); // } // // @Override // public String toString() // { // return "Rectangle[x=" + x + ", y=" + y + ", width=" + width // + ", height=" + height + "]"; // } // }
import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.fit.cssbox.layout.Rectangle; import cz.vutbr.web.css.TermIdent;
/* * RadialGradient.java * Copyright (c) 2005-2020 Radek Burget * * CSSBox is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CSSBox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with CSSBox. If not, see <http://www.gnu.org/licenses/>. * */ package org.fit.cssbox.render; /** * A radial gradient representation. * * @author safar * @author burgetr */ public class RadialGradient extends Gradient { // an elipse/circle switch private boolean circle; // center point and radiuses private float cx; private float cy; private float rx; private float ry; /** Position and size of the gradient in the background area */
// Path: src/main/java/org/fit/cssbox/layout/Rectangle.java // public class Rectangle // { // public float x; // public float y; // public float width; // public float height; // // public Rectangle(float x, float y, float width, float height) // { // this.x = x; // this.y = y; // this.width = width; // this.height = height; // } // // public Rectangle(float width, float height) // { // this.x = 0; // this.y = 0; // this.width = width; // this.height = height; // } // // public Rectangle() // { // this.x = 0; // this.y = 0; // this.width = 0; // this.height = 0; // } // // public Rectangle(Rectangle src) // { // this.x = src.x; // this.y = src.y; // this.width = src.width; // this.height = src.height; // } // // public Rectangle(Dimension src) // { // this.x = 0; // this.y = 0; // this.width = src.width; // this.height = src.height; // } // // public float getX() // { // return x; // } // // public void setX(float x) // { // this.x = x; // } // // public float getY() // { // return y; // } // // public void setY(float y) // { // this.y = y; // } // // public float getWidth() // { // return width; // } // // public void setWidth(float width) // { // this.width = width; // } // // public float getHeight() // { // return height; // } // // public void setHeight(float height) // { // this.height = height; // } // // public void setLocation(float x, float y) // { // this.x = x; // this.y = y; // } // // public void setSize(float width, float height) // { // this.width = width; // this.height = height; // } // // public Dimension getSize() // { // return new Dimension(width, height); // } // // public boolean contains(float x, float y) // { // if (width <= 0 || height <= 0) // return false; // return (x >= this.x && x < this.x + this.width && // y >= this.y && y < this.y + this.height); // } // // public boolean intersects(Rectangle r) // { // float tw = this.width; // float th = this.height; // float rw = r.width; // float rh = r.height; // if (rw <= 0 || rh <= 0 || tw <= 0 || th <= 0) { // return false; // } // float tx = this.x; // float ty = this.y; // float rx = r.x; // float ry = r.y; // rw += rx; // rh += ry; // tw += tx; // th += ty; // // overflow || intersect // return ((rw < rx || rw > tx) && // (rh < ry || rh > ty) && // (tw < tx || tw > rx) && // (th < ty || th > ry)); // } // // public Rectangle intersection(Rectangle r) // { // float tx1 = this.x; // float ty1 = this.y; // float rx1 = r.x; // float ry1 = r.y; // float tx2 = tx1; tx2 += this.width; // float ty2 = ty1; ty2 += this.height; // float rx2 = rx1; rx2 += r.width; // float ry2 = ry1; ry2 += r.height; // if (tx1 < rx1) tx1 = rx1; // if (ty1 < ry1) ty1 = ry1; // if (tx2 > rx2) tx2 = rx2; // if (ty2 > ry2) ty2 = ry2; // tx2 -= tx1; // ty2 -= ty1; // return new Rectangle(tx1, ty1, tx2, ty2); // } // // @Override // public String toString() // { // return "Rectangle[x=" + x + ", y=" + y + ", width=" + width // + ", height=" + height + "]"; // } // } // Path: src/main/java/org/fit/cssbox/render/RadialGradient.java import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.fit.cssbox.layout.Rectangle; import cz.vutbr.web.css.TermIdent; /* * RadialGradient.java * Copyright (c) 2005-2020 Radek Burget * * CSSBox is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CSSBox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with CSSBox. If not, see <http://www.gnu.org/licenses/>. * */ package org.fit.cssbox.render; /** * A radial gradient representation. * * @author safar * @author burgetr */ public class RadialGradient extends Gradient { // an elipse/circle switch private boolean circle; // center point and radiuses private float cx; private float cy; private float rx; private float ry; /** Position and size of the gradient in the background area */
private Rectangle bgRect;
radkovo/CSSBox
src/main/java/org/fit/cssbox/awt/CSSStroke.java
// Path: src/main/java/org/fit/cssbox/misc/Coords.java // public class Coords // { // /** A difference threshold to consider two coordinates to be equal */ // public static final float COORDS_THRESHOLD = 0.0001f; // // /** // * Comapres two coordinate values and returns true when they should be considered equal. // * @param v1 // * @param v2 // * @return // */ // public static boolean eq(float v1, float v2) // { // return (Math.abs(v1 - v2) < COORDS_THRESHOLD); // } // // }
import java.awt.*; import java.awt.geom.GeneralPath; import java.awt.geom.Line2D; import java.awt.geom.Rectangle2D; import org.fit.cssbox.misc.Coords; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import cz.vutbr.web.css.CSSProperty;
/* * CSSStroke.java * Copyright (c) 2005-2010 Radek Burget * * CSSBox is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CSSBox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with CSSBox. If not, see <http://www.gnu.org/licenses/>. * * Created on 9.11.2010, 17:31:58 by burgetr */ package org.fit.cssbox.awt; /** * Stroke for drawing the CSS borders. * * @author burgetr */ public class CSSStroke implements Stroke { private static Logger log = LoggerFactory.getLogger(CSSStroke.class); private float width; private CSSProperty.BorderStyle style; private boolean reverse; /** * Creates a new CSS stroke. * @param width Border width * @param style Border css style * @param reverse Should be true for right and bottom border - used for reversing the shape of 'double' style border. */ public CSSStroke(float width, CSSProperty.BorderStyle style, boolean reverse) { this.width = width; this.style = style; this.reverse = reverse; } public Shape createStrokedShape(Shape s) { if (s instanceof Line2D.Float) { Line2D.Float l = (Line2D.Float) s; float x1 = l.x1; float y1 = l.y1; float x2 = l.x2; float y2 = l.y2;
// Path: src/main/java/org/fit/cssbox/misc/Coords.java // public class Coords // { // /** A difference threshold to consider two coordinates to be equal */ // public static final float COORDS_THRESHOLD = 0.0001f; // // /** // * Comapres two coordinate values and returns true when they should be considered equal. // * @param v1 // * @param v2 // * @return // */ // public static boolean eq(float v1, float v2) // { // return (Math.abs(v1 - v2) < COORDS_THRESHOLD); // } // // } // Path: src/main/java/org/fit/cssbox/awt/CSSStroke.java import java.awt.*; import java.awt.geom.GeneralPath; import java.awt.geom.Line2D; import java.awt.geom.Rectangle2D; import org.fit.cssbox.misc.Coords; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import cz.vutbr.web.css.CSSProperty; /* * CSSStroke.java * Copyright (c) 2005-2010 Radek Burget * * CSSBox is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CSSBox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with CSSBox. If not, see <http://www.gnu.org/licenses/>. * * Created on 9.11.2010, 17:31:58 by burgetr */ package org.fit.cssbox.awt; /** * Stroke for drawing the CSS borders. * * @author burgetr */ public class CSSStroke implements Stroke { private static Logger log = LoggerFactory.getLogger(CSSStroke.class); private float width; private CSSProperty.BorderStyle style; private boolean reverse; /** * Creates a new CSS stroke. * @param width Border width * @param style Border css style * @param reverse Should be true for right and bottom border - used for reversing the shape of 'double' style border. */ public CSSStroke(float width, CSSProperty.BorderStyle style, boolean reverse) { this.width = width; this.style = style; this.reverse = reverse; } public Shape createStrokedShape(Shape s) { if (s instanceof Line2D.Float) { Line2D.Float l = (Line2D.Float) s; float x1 = l.x1; float y1 = l.y1; float x2 = l.x2; float y2 = l.y2;
if (Coords.eq(y1, y2) && x2 > x1)
radkovo/CSSBox
src/main/java/org/fit/cssbox/layout/Viewport.java
// Path: src/main/java/org/fit/cssbox/render/BoxRenderer.java // public interface BoxRenderer extends Closeable // { // /** // * Initializes the renderer for rendering a ready-to-render viewport. // * @param vp The viewport that will be rendered. The viewport must be fully initialized // * and ready to draw. // */ // public void init(Viewport vp); // // /** // * Initializes the rendering of an element. This is called before any contents of the element // * or child boxes are rendered. Note that the {@link BoxRenderer#renderElementBackground} method // * may be called before this method. // * @param elem the element // */ // public void startElementContents(ElementBox elem); // // /** // * Finishes the rendering of an element. This is called after all contents of the element // * and the child boxes are rendered. // * @param elem the element // */ // public void finishElementContents(ElementBox elem); // // /** // * Renders the background and borders of the given element box according to its style. // * @param elem // */ // public void renderElementBackground(ElementBox elem); // // /** // * Renders the marker (the bullet or item number) used by the list-item boxes. // * @param elem the list-item box // */ // public void renderMarker(ListItemBox elem); // // /** // * Renders the text represented by a text box according to its computed style. // * @param text // */ // public void renderTextContent(TextBox text); // // /** // * Renders the contents of a replaced box. // * @param box // */ // public void renderReplacedContent(ReplacedBox box); // // /** // * Finishes and the output. // */ // public void close() throws IOException; // // }
import java.util.Vector; import org.fit.cssbox.render.BoxRenderer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Element; import cz.vutbr.web.css.CSSFactory;
/* * Viewport.java * Copyright (c) 2005-2020 Radek Burget * * CSSBox is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CSSBox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with CSSBox. If not, see <http://www.gnu.org/licenses/>. */ package org.fit.cssbox.layout; /** * The viewport is a special case of BlockElement that has several widths and heights: * * <ul> * <li><strong>Viewport size</strong> - the width and height of the visible area used for * computing the sizes of the contained blocks.</li> * <li><strong>Canvas size</strong> - the width and height of the whole rendered page</li> * * @author radek */ public class Viewport extends BlockBox { private static Logger log = LoggerFactory.getLogger(Viewport.class); /** Total canvas width */ private float width; /** Total canvas height */ private float height; /** Visible rectagle -- the position and size of the CSS viewport */ private Rectangle visibleRect; protected BrowserConfig config; private BoxFactory factory;
// Path: src/main/java/org/fit/cssbox/render/BoxRenderer.java // public interface BoxRenderer extends Closeable // { // /** // * Initializes the renderer for rendering a ready-to-render viewport. // * @param vp The viewport that will be rendered. The viewport must be fully initialized // * and ready to draw. // */ // public void init(Viewport vp); // // /** // * Initializes the rendering of an element. This is called before any contents of the element // * or child boxes are rendered. Note that the {@link BoxRenderer#renderElementBackground} method // * may be called before this method. // * @param elem the element // */ // public void startElementContents(ElementBox elem); // // /** // * Finishes the rendering of an element. This is called after all contents of the element // * and the child boxes are rendered. // * @param elem the element // */ // public void finishElementContents(ElementBox elem); // // /** // * Renders the background and borders of the given element box according to its style. // * @param elem // */ // public void renderElementBackground(ElementBox elem); // // /** // * Renders the marker (the bullet or item number) used by the list-item boxes. // * @param elem the list-item box // */ // public void renderMarker(ListItemBox elem); // // /** // * Renders the text represented by a text box according to its computed style. // * @param text // */ // public void renderTextContent(TextBox text); // // /** // * Renders the contents of a replaced box. // * @param box // */ // public void renderReplacedContent(ReplacedBox box); // // /** // * Finishes and the output. // */ // public void close() throws IOException; // // } // Path: src/main/java/org/fit/cssbox/layout/Viewport.java import java.util.Vector; import org.fit.cssbox.render.BoxRenderer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Element; import cz.vutbr.web.css.CSSFactory; /* * Viewport.java * Copyright (c) 2005-2020 Radek Burget * * CSSBox is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CSSBox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with CSSBox. If not, see <http://www.gnu.org/licenses/>. */ package org.fit.cssbox.layout; /** * The viewport is a special case of BlockElement that has several widths and heights: * * <ul> * <li><strong>Viewport size</strong> - the width and height of the visible area used for * computing the sizes of the contained blocks.</li> * <li><strong>Canvas size</strong> - the width and height of the whole rendered page</li> * * @author radek */ public class Viewport extends BlockBox { private static Logger log = LoggerFactory.getLogger(Viewport.class); /** Total canvas width */ private float width; /** Total canvas height */ private float height; /** Visible rectagle -- the position and size of the CSS viewport */ private Rectangle visibleRect; protected BrowserConfig config; private BoxFactory factory;
private BoxRenderer renderer;
radkovo/CSSBox
src/main/java/org/fit/cssbox/css/FontDecoder.java
// Path: src/main/java/org/fit/cssbox/io/DocumentSource.java // public abstract class DocumentSource implements java.io.Closeable // { // // /** // * Creates a new document source from an URL. // * @param url the document URL // * @throws IOException // */ // public DocumentSource(URL url) throws IOException // { // } // // /** // * Creates a new document source based on a string representation of the URL. // * @param urlstring the URL string // * @throws IOException // */ // public DocumentSource(URL base, String urlstring) throws IOException // { // } // // /** // * Obtains the final URL of the obtained document. This URL may be different // * from the URL used for DocumentSource construction, e.g. when some HTTP redirect // * occurs. // * @return the document URL. // */ // abstract public URL getURL(); // // /** // * Obtains the MIME content type of the target document. // * @return a MIME string. // */ // abstract public String getContentType(); // // /** // * Obtains the input stream for reading the referenced document. // * @return The input stream. // * @throws IOException // */ // abstract public InputStream getInputStream() throws IOException; // // /** // * Closes the document source. // */ // abstract public void close() throws IOException; // // }
import java.awt.Font; import java.awt.FontFormatException; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.fit.cssbox.io.DocumentSource;
/* * FontDecoder.java * Copyright (c) 2005-2017 Radek Burget * * CSSBox is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CSSBox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with CSSBox. If not, see <http://www.gnu.org/licenses/>. * * Created on 1. 11. 2017, 23:23:03 by burgetr */ package org.fit.cssbox.css; /** * * @author burgetr */ public class FontDecoder { public static List<String> supportedFormats; static { supportedFormats = new ArrayList<String>(1); supportedFormats.add("truetype"); } private static Map<URL, String> registeredFonts = new HashMap<>(); public static void registerFont(URL url, String family) { registeredFonts.put(url, family); } public static String findRegisteredFont(URL url) { return registeredFonts.get(url); }
// Path: src/main/java/org/fit/cssbox/io/DocumentSource.java // public abstract class DocumentSource implements java.io.Closeable // { // // /** // * Creates a new document source from an URL. // * @param url the document URL // * @throws IOException // */ // public DocumentSource(URL url) throws IOException // { // } // // /** // * Creates a new document source based on a string representation of the URL. // * @param urlstring the URL string // * @throws IOException // */ // public DocumentSource(URL base, String urlstring) throws IOException // { // } // // /** // * Obtains the final URL of the obtained document. This URL may be different // * from the URL used for DocumentSource construction, e.g. when some HTTP redirect // * occurs. // * @return the document URL. // */ // abstract public URL getURL(); // // /** // * Obtains the MIME content type of the target document. // * @return a MIME string. // */ // abstract public String getContentType(); // // /** // * Obtains the input stream for reading the referenced document. // * @return The input stream. // * @throws IOException // */ // abstract public InputStream getInputStream() throws IOException; // // /** // * Closes the document source. // */ // abstract public void close() throws IOException; // // } // Path: src/main/java/org/fit/cssbox/css/FontDecoder.java import java.awt.Font; import java.awt.FontFormatException; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.fit.cssbox.io.DocumentSource; /* * FontDecoder.java * Copyright (c) 2005-2017 Radek Burget * * CSSBox is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CSSBox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with CSSBox. If not, see <http://www.gnu.org/licenses/>. * * Created on 1. 11. 2017, 23:23:03 by burgetr */ package org.fit.cssbox.css; /** * * @author burgetr */ public class FontDecoder { public static List<String> supportedFormats; static { supportedFormats = new ArrayList<String>(1); supportedFormats.add("truetype"); } private static Map<URL, String> registeredFonts = new HashMap<>(); public static void registerFont(URL url, String family) { registeredFonts.put(url, family); } public static String findRegisteredFont(URL url) { return registeredFonts.get(url); }
public static Font decodeFont(DocumentSource fontSource, String format) throws FontFormatException, IOException
radkovo/CSSBox
src/main/java/org/fit/cssbox/render/BackgroundRepeater.java
// Path: src/main/java/org/fit/cssbox/layout/Rectangle.java // public class Rectangle // { // public float x; // public float y; // public float width; // public float height; // // public Rectangle(float x, float y, float width, float height) // { // this.x = x; // this.y = y; // this.width = width; // this.height = height; // } // // public Rectangle(float width, float height) // { // this.x = 0; // this.y = 0; // this.width = width; // this.height = height; // } // // public Rectangle() // { // this.x = 0; // this.y = 0; // this.width = 0; // this.height = 0; // } // // public Rectangle(Rectangle src) // { // this.x = src.x; // this.y = src.y; // this.width = src.width; // this.height = src.height; // } // // public Rectangle(Dimension src) // { // this.x = 0; // this.y = 0; // this.width = src.width; // this.height = src.height; // } // // public float getX() // { // return x; // } // // public void setX(float x) // { // this.x = x; // } // // public float getY() // { // return y; // } // // public void setY(float y) // { // this.y = y; // } // // public float getWidth() // { // return width; // } // // public void setWidth(float width) // { // this.width = width; // } // // public float getHeight() // { // return height; // } // // public void setHeight(float height) // { // this.height = height; // } // // public void setLocation(float x, float y) // { // this.x = x; // this.y = y; // } // // public void setSize(float width, float height) // { // this.width = width; // this.height = height; // } // // public Dimension getSize() // { // return new Dimension(width, height); // } // // public boolean contains(float x, float y) // { // if (width <= 0 || height <= 0) // return false; // return (x >= this.x && x < this.x + this.width && // y >= this.y && y < this.y + this.height); // } // // public boolean intersects(Rectangle r) // { // float tw = this.width; // float th = this.height; // float rw = r.width; // float rh = r.height; // if (rw <= 0 || rh <= 0 || tw <= 0 || th <= 0) { // return false; // } // float tx = this.x; // float ty = this.y; // float rx = r.x; // float ry = r.y; // rw += rx; // rh += ry; // tw += tx; // th += ty; // // overflow || intersect // return ((rw < rx || rw > tx) && // (rh < ry || rh > ty) && // (tw < tx || tw > rx) && // (th < ty || th > ry)); // } // // public Rectangle intersection(Rectangle r) // { // float tx1 = this.x; // float ty1 = this.y; // float rx1 = r.x; // float ry1 = r.y; // float tx2 = tx1; tx2 += this.width; // float ty2 = ty1; ty2 += this.height; // float rx2 = rx1; rx2 += r.width; // float ry2 = ry1; ry2 += r.height; // if (tx1 < rx1) tx1 = rx1; // if (ty1 < ry1) ty1 = ry1; // if (tx2 > rx2) tx2 = rx2; // if (ty2 > ry2) ty2 = ry2; // tx2 -= tx1; // ty2 -= ty1; // return new Rectangle(tx1, ty1, tx2, ty2); // } // // @Override // public String toString() // { // return "Rectangle[x=" + x + ", y=" + y + ", width=" + width // + ", height=" + height + "]"; // } // }
import org.fit.cssbox.layout.Rectangle;
/* * BackgroundRepeater.java * Copyright (c) 2005-2020 Radek Burget * * CSSBox is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CSSBox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with CSSBox. If not, see <http://www.gnu.org/licenses/>. * * Created on 16. 4. 2020, 18:47:15 by burgetr */ package org.fit.cssbox.render; /** * This class implements the repetition of background images within a background area. * * @author burgetr */ public class BackgroundRepeater { /** * A target function that applies a single copy of the background image to the given * absolute coordinates. * * @author burgetr */ public static interface Target { void apply(float x, float y); } /** * Repeats the image over the background area in specified directions. * * @param bb the entire background bounds * @param pos the initial absolute position and size of the background image * @param clip a clipping box to be applied on the repetitions * @param repeatX repeat in X-axis? * @param repeatY repeat in Y-axis? * @param target the target function to be called for each copy */
// Path: src/main/java/org/fit/cssbox/layout/Rectangle.java // public class Rectangle // { // public float x; // public float y; // public float width; // public float height; // // public Rectangle(float x, float y, float width, float height) // { // this.x = x; // this.y = y; // this.width = width; // this.height = height; // } // // public Rectangle(float width, float height) // { // this.x = 0; // this.y = 0; // this.width = width; // this.height = height; // } // // public Rectangle() // { // this.x = 0; // this.y = 0; // this.width = 0; // this.height = 0; // } // // public Rectangle(Rectangle src) // { // this.x = src.x; // this.y = src.y; // this.width = src.width; // this.height = src.height; // } // // public Rectangle(Dimension src) // { // this.x = 0; // this.y = 0; // this.width = src.width; // this.height = src.height; // } // // public float getX() // { // return x; // } // // public void setX(float x) // { // this.x = x; // } // // public float getY() // { // return y; // } // // public void setY(float y) // { // this.y = y; // } // // public float getWidth() // { // return width; // } // // public void setWidth(float width) // { // this.width = width; // } // // public float getHeight() // { // return height; // } // // public void setHeight(float height) // { // this.height = height; // } // // public void setLocation(float x, float y) // { // this.x = x; // this.y = y; // } // // public void setSize(float width, float height) // { // this.width = width; // this.height = height; // } // // public Dimension getSize() // { // return new Dimension(width, height); // } // // public boolean contains(float x, float y) // { // if (width <= 0 || height <= 0) // return false; // return (x >= this.x && x < this.x + this.width && // y >= this.y && y < this.y + this.height); // } // // public boolean intersects(Rectangle r) // { // float tw = this.width; // float th = this.height; // float rw = r.width; // float rh = r.height; // if (rw <= 0 || rh <= 0 || tw <= 0 || th <= 0) { // return false; // } // float tx = this.x; // float ty = this.y; // float rx = r.x; // float ry = r.y; // rw += rx; // rh += ry; // tw += tx; // th += ty; // // overflow || intersect // return ((rw < rx || rw > tx) && // (rh < ry || rh > ty) && // (tw < tx || tw > rx) && // (th < ty || th > ry)); // } // // public Rectangle intersection(Rectangle r) // { // float tx1 = this.x; // float ty1 = this.y; // float rx1 = r.x; // float ry1 = r.y; // float tx2 = tx1; tx2 += this.width; // float ty2 = ty1; ty2 += this.height; // float rx2 = rx1; rx2 += r.width; // float ry2 = ry1; ry2 += r.height; // if (tx1 < rx1) tx1 = rx1; // if (ty1 < ry1) ty1 = ry1; // if (tx2 > rx2) tx2 = rx2; // if (ty2 > ry2) ty2 = ry2; // tx2 -= tx1; // ty2 -= ty1; // return new Rectangle(tx1, ty1, tx2, ty2); // } // // @Override // public String toString() // { // return "Rectangle[x=" + x + ", y=" + y + ", width=" + width // + ", height=" + height + "]"; // } // } // Path: src/main/java/org/fit/cssbox/render/BackgroundRepeater.java import org.fit.cssbox.layout.Rectangle; /* * BackgroundRepeater.java * Copyright (c) 2005-2020 Radek Burget * * CSSBox is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CSSBox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with CSSBox. If not, see <http://www.gnu.org/licenses/>. * * Created on 16. 4. 2020, 18:47:15 by burgetr */ package org.fit.cssbox.render; /** * This class implements the repetition of background images within a background area. * * @author burgetr */ public class BackgroundRepeater { /** * A target function that applies a single copy of the background image to the given * absolute coordinates. * * @author burgetr */ public static interface Target { void apply(float x, float y); } /** * Repeats the image over the background area in specified directions. * * @param bb the entire background bounds * @param pos the initial absolute position and size of the background image * @param clip a clipping box to be applied on the repetitions * @param repeatX repeat in X-axis? * @param repeatY repeat in Y-axis? * @param target the target function to be called for each copy */
public void repeatImage(Rectangle bb, Rectangle pos, Rectangle clip,
radkovo/CSSBox
src/main/java/org/fit/cssbox/testing/TestBatch.java
// Path: src/main/java/org/fit/cssbox/io/DefaultDOMSource.java // public class DefaultDOMSource extends DOMSource // { // static boolean neko_fixed = false; // // public DefaultDOMSource(DocumentSource src) // { // super(src); // } // // @Override // public Document parse() throws SAXException, IOException // { // //temporay NekoHTML fix until nekohtml gets fixed // if (!neko_fixed) // { // HTMLElements.Element li = HTMLElements.getElement(HTMLElements.LI); // HTMLElements.Element[] oldparents = li.parent; // li.parent = new HTMLElements.Element[oldparents.length + 1]; // for (int i = 0; i < oldparents.length; i++) // li.parent[i] = oldparents[i]; // li.parent[oldparents.length] = HTMLElements.getElement(HTMLElements.MENU); // neko_fixed = true; // } // // DOMParser parser = new DOMParser(new HTMLConfiguration()); // parser.setProperty("http://cyberneko.org/html/properties/names/elems", "lower"); // if (charset != null) // parser.setProperty("http://cyberneko.org/html/properties/default-encoding", charset); // parser.parse(new org.xml.sax.InputSource(getDocumentSource().getInputStream())); // return parser.getDocument(); // } // // } // // Path: src/main/java/org/fit/cssbox/io/DefaultDocumentSource.java // public class DefaultDocumentSource extends DocumentSource // { // /** The user-agent string used for HTTP connection */ // private static String USER_AGENT = "Mozilla/5.0 (compatible; BoxBrowserTest/4.x; Linux) CSSBox/4.x (like Gecko)"; // // private URLConnection con; // private InputStream is; // // /** // * Creates a network data source based on the target document URL. // * @param url the document URL // * @throws IOException // */ // public DefaultDocumentSource(URL url) throws IOException // { // super(url); // con = createConnection(url); // is = null; // } // // /** // * Creates a data source based on the URL string. The data: urls are automatically // * recognized and processed. // * @param urlstring The URL string // * @throws IOException // */ // public DefaultDocumentSource(String urlstring) throws IOException // { // super(null, urlstring); // URL url = DataURLHandler.createURL(null, urlstring); // con = createConnection(url); // is = null; // } // // /** // * Creates a data source based on the URL string. The data: urls are automatically // * recognized and processed. // * @param base The base URL to be used for the relative URLs in the urlstring // * @param urlstring The URL string // * @throws IOException // */ // public DefaultDocumentSource(URL base, String urlstring) throws IOException // { // super(base, urlstring); // URL url = DataURLHandler.createURL(base, urlstring); // con = createConnection(url); // is = null; // } // // /** // * Creates and configures the URL connection. // * @param url the target URL // * @return the created connection instance // * @throws IOException // */ // protected URLConnection createConnection(URL url) throws IOException // { // URLConnection con = url.openConnection(); // con.setRequestProperty("User-Agent", USER_AGENT); // return con; // } // // @Override // public URL getURL() // { // return con.getURL(); // } // // @Override // public InputStream getInputStream() throws IOException // { // if (is == null) // is = con.getInputStream(); // return is; // } // // @Override // public String getContentType() // { // return con.getHeaderField("Content-Type"); // } // // /** // * Obtains the current User-agent string used for new connections. // * @return the user-agent string. // */ // public static String getUserAgent() // { // return USER_AGENT; // } // // /** // * Sets the user agent string that will be used for new connections. // * @param userAgent the user-agent string // */ // public static void setUserAgent(String userAgent) // { // USER_AGENT = userAgent; // } // // @Override // public void close() throws IOException // { // if (is != null) // is.close(); // } // // // }
import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.Callable; import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import org.fit.cssbox.io.DefaultDOMSource; import org.fit.cssbox.io.DefaultDocumentSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xml.sax.SAXException;
* file that is used for obtaining the test names. * @param testURL * @param threadCount the number of threads to be used for parallel testing */ public TestBatch(URL testURL, int threadCount) { this.threadsUsed = threadCount; this.testURL = testURL; this.tests = new LinkedList<SourceEntry>(); this.results = new LinkedHashMap<String, Float>(); parseToc(); } /** * Obtain the number of tests available. * @return */ public int getTestCount() { return tests.size(); } /** * Parses the HTML TOC and extracts the test names and tags. Fills the list of tests. */ private void parseToc() { try { URL tocURL = new URL(testURL, "reftest-toc.htm");
// Path: src/main/java/org/fit/cssbox/io/DefaultDOMSource.java // public class DefaultDOMSource extends DOMSource // { // static boolean neko_fixed = false; // // public DefaultDOMSource(DocumentSource src) // { // super(src); // } // // @Override // public Document parse() throws SAXException, IOException // { // //temporay NekoHTML fix until nekohtml gets fixed // if (!neko_fixed) // { // HTMLElements.Element li = HTMLElements.getElement(HTMLElements.LI); // HTMLElements.Element[] oldparents = li.parent; // li.parent = new HTMLElements.Element[oldparents.length + 1]; // for (int i = 0; i < oldparents.length; i++) // li.parent[i] = oldparents[i]; // li.parent[oldparents.length] = HTMLElements.getElement(HTMLElements.MENU); // neko_fixed = true; // } // // DOMParser parser = new DOMParser(new HTMLConfiguration()); // parser.setProperty("http://cyberneko.org/html/properties/names/elems", "lower"); // if (charset != null) // parser.setProperty("http://cyberneko.org/html/properties/default-encoding", charset); // parser.parse(new org.xml.sax.InputSource(getDocumentSource().getInputStream())); // return parser.getDocument(); // } // // } // // Path: src/main/java/org/fit/cssbox/io/DefaultDocumentSource.java // public class DefaultDocumentSource extends DocumentSource // { // /** The user-agent string used for HTTP connection */ // private static String USER_AGENT = "Mozilla/5.0 (compatible; BoxBrowserTest/4.x; Linux) CSSBox/4.x (like Gecko)"; // // private URLConnection con; // private InputStream is; // // /** // * Creates a network data source based on the target document URL. // * @param url the document URL // * @throws IOException // */ // public DefaultDocumentSource(URL url) throws IOException // { // super(url); // con = createConnection(url); // is = null; // } // // /** // * Creates a data source based on the URL string. The data: urls are automatically // * recognized and processed. // * @param urlstring The URL string // * @throws IOException // */ // public DefaultDocumentSource(String urlstring) throws IOException // { // super(null, urlstring); // URL url = DataURLHandler.createURL(null, urlstring); // con = createConnection(url); // is = null; // } // // /** // * Creates a data source based on the URL string. The data: urls are automatically // * recognized and processed. // * @param base The base URL to be used for the relative URLs in the urlstring // * @param urlstring The URL string // * @throws IOException // */ // public DefaultDocumentSource(URL base, String urlstring) throws IOException // { // super(base, urlstring); // URL url = DataURLHandler.createURL(base, urlstring); // con = createConnection(url); // is = null; // } // // /** // * Creates and configures the URL connection. // * @param url the target URL // * @return the created connection instance // * @throws IOException // */ // protected URLConnection createConnection(URL url) throws IOException // { // URLConnection con = url.openConnection(); // con.setRequestProperty("User-Agent", USER_AGENT); // return con; // } // // @Override // public URL getURL() // { // return con.getURL(); // } // // @Override // public InputStream getInputStream() throws IOException // { // if (is == null) // is = con.getInputStream(); // return is; // } // // @Override // public String getContentType() // { // return con.getHeaderField("Content-Type"); // } // // /** // * Obtains the current User-agent string used for new connections. // * @return the user-agent string. // */ // public static String getUserAgent() // { // return USER_AGENT; // } // // /** // * Sets the user agent string that will be used for new connections. // * @param userAgent the user-agent string // */ // public static void setUserAgent(String userAgent) // { // USER_AGENT = userAgent; // } // // @Override // public void close() throws IOException // { // if (is != null) // is.close(); // } // // // } // Path: src/main/java/org/fit/cssbox/testing/TestBatch.java import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.Callable; import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import org.fit.cssbox.io.DefaultDOMSource; import org.fit.cssbox.io.DefaultDocumentSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; * file that is used for obtaining the test names. * @param testURL * @param threadCount the number of threads to be used for parallel testing */ public TestBatch(URL testURL, int threadCount) { this.threadsUsed = threadCount; this.testURL = testURL; this.tests = new LinkedList<SourceEntry>(); this.results = new LinkedHashMap<String, Float>(); parseToc(); } /** * Obtain the number of tests available. * @return */ public int getTestCount() { return tests.size(); } /** * Parses the HTML TOC and extracts the test names and tags. Fills the list of tests. */ private void parseToc() { try { URL tocURL = new URL(testURL, "reftest-toc.htm");
DefaultDocumentSource docSource = new DefaultDocumentSource(tocURL.toString());
radkovo/CSSBox
src/main/java/org/fit/cssbox/testing/TestBatch.java
// Path: src/main/java/org/fit/cssbox/io/DefaultDOMSource.java // public class DefaultDOMSource extends DOMSource // { // static boolean neko_fixed = false; // // public DefaultDOMSource(DocumentSource src) // { // super(src); // } // // @Override // public Document parse() throws SAXException, IOException // { // //temporay NekoHTML fix until nekohtml gets fixed // if (!neko_fixed) // { // HTMLElements.Element li = HTMLElements.getElement(HTMLElements.LI); // HTMLElements.Element[] oldparents = li.parent; // li.parent = new HTMLElements.Element[oldparents.length + 1]; // for (int i = 0; i < oldparents.length; i++) // li.parent[i] = oldparents[i]; // li.parent[oldparents.length] = HTMLElements.getElement(HTMLElements.MENU); // neko_fixed = true; // } // // DOMParser parser = new DOMParser(new HTMLConfiguration()); // parser.setProperty("http://cyberneko.org/html/properties/names/elems", "lower"); // if (charset != null) // parser.setProperty("http://cyberneko.org/html/properties/default-encoding", charset); // parser.parse(new org.xml.sax.InputSource(getDocumentSource().getInputStream())); // return parser.getDocument(); // } // // } // // Path: src/main/java/org/fit/cssbox/io/DefaultDocumentSource.java // public class DefaultDocumentSource extends DocumentSource // { // /** The user-agent string used for HTTP connection */ // private static String USER_AGENT = "Mozilla/5.0 (compatible; BoxBrowserTest/4.x; Linux) CSSBox/4.x (like Gecko)"; // // private URLConnection con; // private InputStream is; // // /** // * Creates a network data source based on the target document URL. // * @param url the document URL // * @throws IOException // */ // public DefaultDocumentSource(URL url) throws IOException // { // super(url); // con = createConnection(url); // is = null; // } // // /** // * Creates a data source based on the URL string. The data: urls are automatically // * recognized and processed. // * @param urlstring The URL string // * @throws IOException // */ // public DefaultDocumentSource(String urlstring) throws IOException // { // super(null, urlstring); // URL url = DataURLHandler.createURL(null, urlstring); // con = createConnection(url); // is = null; // } // // /** // * Creates a data source based on the URL string. The data: urls are automatically // * recognized and processed. // * @param base The base URL to be used for the relative URLs in the urlstring // * @param urlstring The URL string // * @throws IOException // */ // public DefaultDocumentSource(URL base, String urlstring) throws IOException // { // super(base, urlstring); // URL url = DataURLHandler.createURL(base, urlstring); // con = createConnection(url); // is = null; // } // // /** // * Creates and configures the URL connection. // * @param url the target URL // * @return the created connection instance // * @throws IOException // */ // protected URLConnection createConnection(URL url) throws IOException // { // URLConnection con = url.openConnection(); // con.setRequestProperty("User-Agent", USER_AGENT); // return con; // } // // @Override // public URL getURL() // { // return con.getURL(); // } // // @Override // public InputStream getInputStream() throws IOException // { // if (is == null) // is = con.getInputStream(); // return is; // } // // @Override // public String getContentType() // { // return con.getHeaderField("Content-Type"); // } // // /** // * Obtains the current User-agent string used for new connections. // * @return the user-agent string. // */ // public static String getUserAgent() // { // return USER_AGENT; // } // // /** // * Sets the user agent string that will be used for new connections. // * @param userAgent the user-agent string // */ // public static void setUserAgent(String userAgent) // { // USER_AGENT = userAgent; // } // // @Override // public void close() throws IOException // { // if (is != null) // is.close(); // } // // // }
import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.Callable; import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import org.fit.cssbox.io.DefaultDOMSource; import org.fit.cssbox.io.DefaultDocumentSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xml.sax.SAXException;
* @param testURL * @param threadCount the number of threads to be used for parallel testing */ public TestBatch(URL testURL, int threadCount) { this.threadsUsed = threadCount; this.testURL = testURL; this.tests = new LinkedList<SourceEntry>(); this.results = new LinkedHashMap<String, Float>(); parseToc(); } /** * Obtain the number of tests available. * @return */ public int getTestCount() { return tests.size(); } /** * Parses the HTML TOC and extracts the test names and tags. Fills the list of tests. */ private void parseToc() { try { URL tocURL = new URL(testURL, "reftest-toc.htm"); DefaultDocumentSource docSource = new DefaultDocumentSource(tocURL.toString());
// Path: src/main/java/org/fit/cssbox/io/DefaultDOMSource.java // public class DefaultDOMSource extends DOMSource // { // static boolean neko_fixed = false; // // public DefaultDOMSource(DocumentSource src) // { // super(src); // } // // @Override // public Document parse() throws SAXException, IOException // { // //temporay NekoHTML fix until nekohtml gets fixed // if (!neko_fixed) // { // HTMLElements.Element li = HTMLElements.getElement(HTMLElements.LI); // HTMLElements.Element[] oldparents = li.parent; // li.parent = new HTMLElements.Element[oldparents.length + 1]; // for (int i = 0; i < oldparents.length; i++) // li.parent[i] = oldparents[i]; // li.parent[oldparents.length] = HTMLElements.getElement(HTMLElements.MENU); // neko_fixed = true; // } // // DOMParser parser = new DOMParser(new HTMLConfiguration()); // parser.setProperty("http://cyberneko.org/html/properties/names/elems", "lower"); // if (charset != null) // parser.setProperty("http://cyberneko.org/html/properties/default-encoding", charset); // parser.parse(new org.xml.sax.InputSource(getDocumentSource().getInputStream())); // return parser.getDocument(); // } // // } // // Path: src/main/java/org/fit/cssbox/io/DefaultDocumentSource.java // public class DefaultDocumentSource extends DocumentSource // { // /** The user-agent string used for HTTP connection */ // private static String USER_AGENT = "Mozilla/5.0 (compatible; BoxBrowserTest/4.x; Linux) CSSBox/4.x (like Gecko)"; // // private URLConnection con; // private InputStream is; // // /** // * Creates a network data source based on the target document URL. // * @param url the document URL // * @throws IOException // */ // public DefaultDocumentSource(URL url) throws IOException // { // super(url); // con = createConnection(url); // is = null; // } // // /** // * Creates a data source based on the URL string. The data: urls are automatically // * recognized and processed. // * @param urlstring The URL string // * @throws IOException // */ // public DefaultDocumentSource(String urlstring) throws IOException // { // super(null, urlstring); // URL url = DataURLHandler.createURL(null, urlstring); // con = createConnection(url); // is = null; // } // // /** // * Creates a data source based on the URL string. The data: urls are automatically // * recognized and processed. // * @param base The base URL to be used for the relative URLs in the urlstring // * @param urlstring The URL string // * @throws IOException // */ // public DefaultDocumentSource(URL base, String urlstring) throws IOException // { // super(base, urlstring); // URL url = DataURLHandler.createURL(base, urlstring); // con = createConnection(url); // is = null; // } // // /** // * Creates and configures the URL connection. // * @param url the target URL // * @return the created connection instance // * @throws IOException // */ // protected URLConnection createConnection(URL url) throws IOException // { // URLConnection con = url.openConnection(); // con.setRequestProperty("User-Agent", USER_AGENT); // return con; // } // // @Override // public URL getURL() // { // return con.getURL(); // } // // @Override // public InputStream getInputStream() throws IOException // { // if (is == null) // is = con.getInputStream(); // return is; // } // // @Override // public String getContentType() // { // return con.getHeaderField("Content-Type"); // } // // /** // * Obtains the current User-agent string used for new connections. // * @return the user-agent string. // */ // public static String getUserAgent() // { // return USER_AGENT; // } // // /** // * Sets the user agent string that will be used for new connections. // * @param userAgent the user-agent string // */ // public static void setUserAgent(String userAgent) // { // USER_AGENT = userAgent; // } // // @Override // public void close() throws IOException // { // if (is != null) // is.close(); // } // // // } // Path: src/main/java/org/fit/cssbox/testing/TestBatch.java import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.Callable; import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import org.fit.cssbox.io.DefaultDOMSource; import org.fit.cssbox.io.DefaultDocumentSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; * @param testURL * @param threadCount the number of threads to be used for parallel testing */ public TestBatch(URL testURL, int threadCount) { this.threadsUsed = threadCount; this.testURL = testURL; this.tests = new LinkedList<SourceEntry>(); this.results = new LinkedHashMap<String, Float>(); parseToc(); } /** * Obtain the number of tests available. * @return */ public int getTestCount() { return tests.size(); } /** * Parses the HTML TOC and extracts the test names and tags. Fills the list of tests. */ private void parseToc() { try { URL tocURL = new URL(testURL, "reftest-toc.htm"); DefaultDocumentSource docSource = new DefaultDocumentSource(tocURL.toString());
DefaultDOMSource parser = new DefaultDOMSource(docSource);
Orange-OpenSource/android-trail-drawing
src/test/java/com/orange/dgil/trail/core/vecto/SlidingWindowGetInsertIndexTest.java
// Path: src/main/java/com/orange/dgil/trail/core/common/TrailPoint.java // @Getter // @NoArgsConstructor // public class TrailPoint { // private int x = -1; // private int y = -1; // // public TrailPoint(int x, int y) { // set(x, y); // } // // public void set(int x, int y) { // this.x = x; // this.y = y; // } // // public boolean isSameAs(TrailPoint point) { // return x == point.x && y == point.y; // } // // public double getDistanceTo(TrailPoint point) { // int dx = x - point.getX(); // int dy = y - point.getY(); // return Math.sqrt(dx * dx + dy * dy); // } // // public void deepCopy(TrailPoint point) { // x = point.x; // y = point.y; // } // }
import com.orange.dgil.trail.TestTools; import com.orange.dgil.trail.core.common.TrailPoint; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito;
/** * Trail drawing library * Copyright (C) 2014 Orange * Authors: christophe.maldivi@orange.com, eric.petit@orange.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.orange.dgil.trail.core.vecto; public class SlidingWindowGetInsertIndexTest { private SlidingWindow slidingWindow; @Before public void setUp() { slidingWindow = Mockito.mock(SlidingWindow.class); } @Test public void shouldDoGetInsertIndexWithAddedElementsNumber() throws IllegalAccessException { // given int addedElementsNumber = 1; int windowSize = 3;
// Path: src/main/java/com/orange/dgil/trail/core/common/TrailPoint.java // @Getter // @NoArgsConstructor // public class TrailPoint { // private int x = -1; // private int y = -1; // // public TrailPoint(int x, int y) { // set(x, y); // } // // public void set(int x, int y) { // this.x = x; // this.y = y; // } // // public boolean isSameAs(TrailPoint point) { // return x == point.x && y == point.y; // } // // public double getDistanceTo(TrailPoint point) { // int dx = x - point.getX(); // int dy = y - point.getY(); // return Math.sqrt(dx * dx + dy * dy); // } // // public void deepCopy(TrailPoint point) { // x = point.x; // y = point.y; // } // } // Path: src/test/java/com/orange/dgil/trail/core/vecto/SlidingWindowGetInsertIndexTest.java import com.orange.dgil.trail.TestTools; import com.orange.dgil.trail.core.common.TrailPoint; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; /** * Trail drawing library * Copyright (C) 2014 Orange * Authors: christophe.maldivi@orange.com, eric.petit@orange.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.orange.dgil.trail.core.vecto; public class SlidingWindowGetInsertIndexTest { private SlidingWindow slidingWindow; @Before public void setUp() { slidingWindow = Mockito.mock(SlidingWindow.class); } @Test public void shouldDoGetInsertIndexWithAddedElementsNumber() throws IllegalAccessException { // given int addedElementsNumber = 1; int windowSize = 3;
TrailPoint[] points = new TrailPoint[windowSize];
Orange-OpenSource/android-trail-drawing
src/test/java/com/orange/dgil/trail/core/vecto/SlidingWindowGetXYIsIndexValidGetMaxIndexTest.java
// Path: src/main/java/com/orange/dgil/trail/core/common/TrailPoint.java // @Getter // @NoArgsConstructor // public class TrailPoint { // private int x = -1; // private int y = -1; // // public TrailPoint(int x, int y) { // set(x, y); // } // // public void set(int x, int y) { // this.x = x; // this.y = y; // } // // public boolean isSameAs(TrailPoint point) { // return x == point.x && y == point.y; // } // // public double getDistanceTo(TrailPoint point) { // int dx = x - point.getX(); // int dy = y - point.getY(); // return Math.sqrt(dx * dx + dy * dy); // } // // public void deepCopy(TrailPoint point) { // x = point.x; // y = point.y; // } // }
import com.orange.dgil.trail.core.common.TrailPoint; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito;
try { slidingWindow.getX(0); } catch (SlidingWindowIndexException e) { getException = true; } // then Assert.assertTrue(getException); } @Test public void shouldGetXWhenNegativeIndex() throws IllegalAccessException { // given int windowSize = 3; slidingWindow = new SlidingWindow(windowSize); // do boolean getException = false; try { slidingWindow.getX(-1); } catch (SlidingWindowIndexException e) { getException = true; } // then Assert.assertTrue(getException); } @Test public void shouldGetXWhenPointsAndIndexOk() throws IllegalAccessException { // given int windowSize = 3; slidingWindow = new SlidingWindow(windowSize);
// Path: src/main/java/com/orange/dgil/trail/core/common/TrailPoint.java // @Getter // @NoArgsConstructor // public class TrailPoint { // private int x = -1; // private int y = -1; // // public TrailPoint(int x, int y) { // set(x, y); // } // // public void set(int x, int y) { // this.x = x; // this.y = y; // } // // public boolean isSameAs(TrailPoint point) { // return x == point.x && y == point.y; // } // // public double getDistanceTo(TrailPoint point) { // int dx = x - point.getX(); // int dy = y - point.getY(); // return Math.sqrt(dx * dx + dy * dy); // } // // public void deepCopy(TrailPoint point) { // x = point.x; // y = point.y; // } // } // Path: src/test/java/com/orange/dgil/trail/core/vecto/SlidingWindowGetXYIsIndexValidGetMaxIndexTest.java import com.orange.dgil.trail.core.common.TrailPoint; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; try { slidingWindow.getX(0); } catch (SlidingWindowIndexException e) { getException = true; } // then Assert.assertTrue(getException); } @Test public void shouldGetXWhenNegativeIndex() throws IllegalAccessException { // given int windowSize = 3; slidingWindow = new SlidingWindow(windowSize); // do boolean getException = false; try { slidingWindow.getX(-1); } catch (SlidingWindowIndexException e) { getException = true; } // then Assert.assertTrue(getException); } @Test public void shouldGetXWhenPointsAndIndexOk() throws IllegalAccessException { // given int windowSize = 3; slidingWindow = new SlidingWindow(windowSize);
TrailPoint point = new TrailPoint();
Orange-OpenSource/android-trail-drawing
src/main/java/com/orange/dgil/trail/android/drawingtool/DrawingToolsContext.java
// Path: src/main/java/com/orange/dgil/trail/android/AndroidMetrics.java // @Getter // @RequiredArgsConstructor // public class AndroidMetrics { // private static final int MICROMETERS_PER_INCH = 25400; // // private final float ydpi; // private final float density; // private final int widthPixels; // private final int heightPixels; // // public int getMicrometersPerPixel() { // return (int) (MICROMETERS_PER_INCH/ydpi); // } // // public int pixelsToMillimeters(int pixels) { // return pixelsToMicrometers(pixels) / 1000; // } // // public int pixelsToMicrometers(int pixels) { // return pixels * getMicrometersPerPixel(); // } // // public int micrometersToPixels(int micrometers) { // return micrometers / getMicrometersPerPixel(); // } // // // not unit tested, android stuff // public static AndroidMetrics get(Context ctx) { // DisplayMetrics metrics = new DisplayMetrics(); // WindowManager wm = (WindowManager) ctx.getSystemService(Context.WINDOW_SERVICE); // updateMetrics(wm.getDefaultDisplay(), metrics); // return new AndroidMetrics(metrics.ydpi, metrics.density, metrics.widthPixels, metrics.heightPixels); // } // // private static void updateMetrics(Display display, DisplayMetrics metrics) { // try { // doUpdateMetrics(display, metrics); // } catch (NoSuchMethodException e) { // showErrorAndSetDefaults(e, display, metrics); // } catch (IllegalAccessException e) { // showErrorAndSetDefaults(e, display, metrics); // } catch (InvocationTargetException e) { // showErrorAndSetDefaults(e, display, metrics); // } // } // // private static void doUpdateMetrics(Display display, DisplayMetrics metrics) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { // if (Build.VERSION.SDK_INT >= 14 && Build.VERSION.SDK_INT < 17) { // updateMetricsBeforeJBMR1(display, metrics); // } else if (Build.VERSION.SDK_INT >= 17) { // updateMetricsStartingWithJBMR1(display, metrics); // } else { // throw new NoSuchMethodException("The library does not support devices before android ICE CREAM SANDWICH (api 14)"); // } // } // // private static void updateMetricsBeforeJBMR1(Display display, DisplayMetrics metrics) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { // // Mandatory for yDpi & density // display.getMetrics(metrics); // metrics.widthPixels = (int) Display.class.getMethod("getRawWidth").invoke(display); // metrics.heightPixels = (int) Display.class.getMethod("getRawHeight").invoke(display); // } // // private static void updateMetricsStartingWithJBMR1(Display display, DisplayMetrics metrics) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { // Display.class.getMethod("getRealMetrics", DisplayMetrics.class).invoke(display, metrics); // } // // private static void showErrorAndSetDefaults(Exception e, Display display, DisplayMetrics metrics) { // Log.e(AndroidMetrics.class.getName(), String.format("Failed to get metrics, %s, %s", e.getMessage(), e.getClass().getName())); // display.getMetrics(metrics); // } // } // // Path: src/main/java/com/orange/dgil/trail/android/animation/AnimManager.java // public class AnimManager { // // private final AnimRunnable animRunnable; // private final AnimParameters animParameters = new AnimParameters(); // // public AnimManager(IAnimDrawer drawer) { // animRunnable = new AnimRunnable(drawer, animParameters); // } // // public void start() { // animRunnable.start(); // } // // public int getAnimColor() { // int startColor = animParameters.getStartColor(); // int endColor = animParameters.getEndColor(); // return getInterpolatedColor(startColor, endColor, animRunnable.getFactor()); // } // // public int getAnimShadowColor() { // int startColor = animParameters.getShadowStartColor(); // int endColor = animParameters.getShadowEndColor(); // return getInterpolatedColor(startColor, endColor, animRunnable.getFactor()); // } // // private int getInterpolatedColor(int startColor, int endColor, float factor) { // return Color.argb( // getInterp(Color.alpha(startColor), Color.alpha(endColor), factor), // getInterp(Color.red (startColor), Color.red (endColor), factor), // getInterp(Color.green(startColor), Color.green(endColor), factor), // getInterp(Color.blue (startColor), Color.blue (endColor), factor)); // } // private int getInterp(int start, int end, float factor) { // return (int) (start * factor + end * (1 - factor)); // } // // // public float getFactor() { // return animRunnable.getFactor(); // } // // /** // * The width factor is made to dilate the trail during fading // * @return the width factor // */ // public float getWidthFactor() { // float factor = getFactor(); // return 1 + animParameters.getWidthDilatationFactor() * (1-factor); // } // // public void reset() { // animRunnable.reset(); // } // // public AnimParameters getAnimationParameters() { // return animParameters; // } // // public boolean isRunning() { // return animRunnable.isRunning(); // } // // public boolean isAlphaAnimationRunning() { // return isRunning() && animParameters.areStartEndColorsRgbEqual(); // } // }
import android.view.View; import com.orange.dgil.trail.android.AndroidMetrics; import com.orange.dgil.trail.android.animation.AnimManager; import lombok.Getter; import lombok.RequiredArgsConstructor;
/** * Trail drawing library * Copyright (C) 2014 Orange * Authors: christophe.maldivi@orange.com, eric.petit@orange.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.orange.dgil.trail.android.drawingtool; @RequiredArgsConstructor @Getter public class DrawingToolsContext { private final View view;
// Path: src/main/java/com/orange/dgil/trail/android/AndroidMetrics.java // @Getter // @RequiredArgsConstructor // public class AndroidMetrics { // private static final int MICROMETERS_PER_INCH = 25400; // // private final float ydpi; // private final float density; // private final int widthPixels; // private final int heightPixels; // // public int getMicrometersPerPixel() { // return (int) (MICROMETERS_PER_INCH/ydpi); // } // // public int pixelsToMillimeters(int pixels) { // return pixelsToMicrometers(pixels) / 1000; // } // // public int pixelsToMicrometers(int pixels) { // return pixels * getMicrometersPerPixel(); // } // // public int micrometersToPixels(int micrometers) { // return micrometers / getMicrometersPerPixel(); // } // // // not unit tested, android stuff // public static AndroidMetrics get(Context ctx) { // DisplayMetrics metrics = new DisplayMetrics(); // WindowManager wm = (WindowManager) ctx.getSystemService(Context.WINDOW_SERVICE); // updateMetrics(wm.getDefaultDisplay(), metrics); // return new AndroidMetrics(metrics.ydpi, metrics.density, metrics.widthPixels, metrics.heightPixels); // } // // private static void updateMetrics(Display display, DisplayMetrics metrics) { // try { // doUpdateMetrics(display, metrics); // } catch (NoSuchMethodException e) { // showErrorAndSetDefaults(e, display, metrics); // } catch (IllegalAccessException e) { // showErrorAndSetDefaults(e, display, metrics); // } catch (InvocationTargetException e) { // showErrorAndSetDefaults(e, display, metrics); // } // } // // private static void doUpdateMetrics(Display display, DisplayMetrics metrics) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { // if (Build.VERSION.SDK_INT >= 14 && Build.VERSION.SDK_INT < 17) { // updateMetricsBeforeJBMR1(display, metrics); // } else if (Build.VERSION.SDK_INT >= 17) { // updateMetricsStartingWithJBMR1(display, metrics); // } else { // throw new NoSuchMethodException("The library does not support devices before android ICE CREAM SANDWICH (api 14)"); // } // } // // private static void updateMetricsBeforeJBMR1(Display display, DisplayMetrics metrics) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { // // Mandatory for yDpi & density // display.getMetrics(metrics); // metrics.widthPixels = (int) Display.class.getMethod("getRawWidth").invoke(display); // metrics.heightPixels = (int) Display.class.getMethod("getRawHeight").invoke(display); // } // // private static void updateMetricsStartingWithJBMR1(Display display, DisplayMetrics metrics) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { // Display.class.getMethod("getRealMetrics", DisplayMetrics.class).invoke(display, metrics); // } // // private static void showErrorAndSetDefaults(Exception e, Display display, DisplayMetrics metrics) { // Log.e(AndroidMetrics.class.getName(), String.format("Failed to get metrics, %s, %s", e.getMessage(), e.getClass().getName())); // display.getMetrics(metrics); // } // } // // Path: src/main/java/com/orange/dgil/trail/android/animation/AnimManager.java // public class AnimManager { // // private final AnimRunnable animRunnable; // private final AnimParameters animParameters = new AnimParameters(); // // public AnimManager(IAnimDrawer drawer) { // animRunnable = new AnimRunnable(drawer, animParameters); // } // // public void start() { // animRunnable.start(); // } // // public int getAnimColor() { // int startColor = animParameters.getStartColor(); // int endColor = animParameters.getEndColor(); // return getInterpolatedColor(startColor, endColor, animRunnable.getFactor()); // } // // public int getAnimShadowColor() { // int startColor = animParameters.getShadowStartColor(); // int endColor = animParameters.getShadowEndColor(); // return getInterpolatedColor(startColor, endColor, animRunnable.getFactor()); // } // // private int getInterpolatedColor(int startColor, int endColor, float factor) { // return Color.argb( // getInterp(Color.alpha(startColor), Color.alpha(endColor), factor), // getInterp(Color.red (startColor), Color.red (endColor), factor), // getInterp(Color.green(startColor), Color.green(endColor), factor), // getInterp(Color.blue (startColor), Color.blue (endColor), factor)); // } // private int getInterp(int start, int end, float factor) { // return (int) (start * factor + end * (1 - factor)); // } // // // public float getFactor() { // return animRunnable.getFactor(); // } // // /** // * The width factor is made to dilate the trail during fading // * @return the width factor // */ // public float getWidthFactor() { // float factor = getFactor(); // return 1 + animParameters.getWidthDilatationFactor() * (1-factor); // } // // public void reset() { // animRunnable.reset(); // } // // public AnimParameters getAnimationParameters() { // return animParameters; // } // // public boolean isRunning() { // return animRunnable.isRunning(); // } // // public boolean isAlphaAnimationRunning() { // return isRunning() && animParameters.areStartEndColorsRgbEqual(); // } // } // Path: src/main/java/com/orange/dgil/trail/android/drawingtool/DrawingToolsContext.java import android.view.View; import com.orange.dgil.trail.android.AndroidMetrics; import com.orange.dgil.trail.android.animation.AnimManager; import lombok.Getter; import lombok.RequiredArgsConstructor; /** * Trail drawing library * Copyright (C) 2014 Orange * Authors: christophe.maldivi@orange.com, eric.petit@orange.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.orange.dgil.trail.android.drawingtool; @RequiredArgsConstructor @Getter public class DrawingToolsContext { private final View view;
private final AnimManager animManager;
Orange-OpenSource/android-trail-drawing
src/main/java/com/orange/dgil/trail/android/drawingtool/DrawingToolsContext.java
// Path: src/main/java/com/orange/dgil/trail/android/AndroidMetrics.java // @Getter // @RequiredArgsConstructor // public class AndroidMetrics { // private static final int MICROMETERS_PER_INCH = 25400; // // private final float ydpi; // private final float density; // private final int widthPixels; // private final int heightPixels; // // public int getMicrometersPerPixel() { // return (int) (MICROMETERS_PER_INCH/ydpi); // } // // public int pixelsToMillimeters(int pixels) { // return pixelsToMicrometers(pixels) / 1000; // } // // public int pixelsToMicrometers(int pixels) { // return pixels * getMicrometersPerPixel(); // } // // public int micrometersToPixels(int micrometers) { // return micrometers / getMicrometersPerPixel(); // } // // // not unit tested, android stuff // public static AndroidMetrics get(Context ctx) { // DisplayMetrics metrics = new DisplayMetrics(); // WindowManager wm = (WindowManager) ctx.getSystemService(Context.WINDOW_SERVICE); // updateMetrics(wm.getDefaultDisplay(), metrics); // return new AndroidMetrics(metrics.ydpi, metrics.density, metrics.widthPixels, metrics.heightPixels); // } // // private static void updateMetrics(Display display, DisplayMetrics metrics) { // try { // doUpdateMetrics(display, metrics); // } catch (NoSuchMethodException e) { // showErrorAndSetDefaults(e, display, metrics); // } catch (IllegalAccessException e) { // showErrorAndSetDefaults(e, display, metrics); // } catch (InvocationTargetException e) { // showErrorAndSetDefaults(e, display, metrics); // } // } // // private static void doUpdateMetrics(Display display, DisplayMetrics metrics) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { // if (Build.VERSION.SDK_INT >= 14 && Build.VERSION.SDK_INT < 17) { // updateMetricsBeforeJBMR1(display, metrics); // } else if (Build.VERSION.SDK_INT >= 17) { // updateMetricsStartingWithJBMR1(display, metrics); // } else { // throw new NoSuchMethodException("The library does not support devices before android ICE CREAM SANDWICH (api 14)"); // } // } // // private static void updateMetricsBeforeJBMR1(Display display, DisplayMetrics metrics) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { // // Mandatory for yDpi & density // display.getMetrics(metrics); // metrics.widthPixels = (int) Display.class.getMethod("getRawWidth").invoke(display); // metrics.heightPixels = (int) Display.class.getMethod("getRawHeight").invoke(display); // } // // private static void updateMetricsStartingWithJBMR1(Display display, DisplayMetrics metrics) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { // Display.class.getMethod("getRealMetrics", DisplayMetrics.class).invoke(display, metrics); // } // // private static void showErrorAndSetDefaults(Exception e, Display display, DisplayMetrics metrics) { // Log.e(AndroidMetrics.class.getName(), String.format("Failed to get metrics, %s, %s", e.getMessage(), e.getClass().getName())); // display.getMetrics(metrics); // } // } // // Path: src/main/java/com/orange/dgil/trail/android/animation/AnimManager.java // public class AnimManager { // // private final AnimRunnable animRunnable; // private final AnimParameters animParameters = new AnimParameters(); // // public AnimManager(IAnimDrawer drawer) { // animRunnable = new AnimRunnable(drawer, animParameters); // } // // public void start() { // animRunnable.start(); // } // // public int getAnimColor() { // int startColor = animParameters.getStartColor(); // int endColor = animParameters.getEndColor(); // return getInterpolatedColor(startColor, endColor, animRunnable.getFactor()); // } // // public int getAnimShadowColor() { // int startColor = animParameters.getShadowStartColor(); // int endColor = animParameters.getShadowEndColor(); // return getInterpolatedColor(startColor, endColor, animRunnable.getFactor()); // } // // private int getInterpolatedColor(int startColor, int endColor, float factor) { // return Color.argb( // getInterp(Color.alpha(startColor), Color.alpha(endColor), factor), // getInterp(Color.red (startColor), Color.red (endColor), factor), // getInterp(Color.green(startColor), Color.green(endColor), factor), // getInterp(Color.blue (startColor), Color.blue (endColor), factor)); // } // private int getInterp(int start, int end, float factor) { // return (int) (start * factor + end * (1 - factor)); // } // // // public float getFactor() { // return animRunnable.getFactor(); // } // // /** // * The width factor is made to dilate the trail during fading // * @return the width factor // */ // public float getWidthFactor() { // float factor = getFactor(); // return 1 + animParameters.getWidthDilatationFactor() * (1-factor); // } // // public void reset() { // animRunnable.reset(); // } // // public AnimParameters getAnimationParameters() { // return animParameters; // } // // public boolean isRunning() { // return animRunnable.isRunning(); // } // // public boolean isAlphaAnimationRunning() { // return isRunning() && animParameters.areStartEndColorsRgbEqual(); // } // }
import android.view.View; import com.orange.dgil.trail.android.AndroidMetrics; import com.orange.dgil.trail.android.animation.AnimManager; import lombok.Getter; import lombok.RequiredArgsConstructor;
/** * Trail drawing library * Copyright (C) 2014 Orange * Authors: christophe.maldivi@orange.com, eric.petit@orange.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.orange.dgil.trail.android.drawingtool; @RequiredArgsConstructor @Getter public class DrawingToolsContext { private final View view; private final AnimManager animManager;
// Path: src/main/java/com/orange/dgil/trail/android/AndroidMetrics.java // @Getter // @RequiredArgsConstructor // public class AndroidMetrics { // private static final int MICROMETERS_PER_INCH = 25400; // // private final float ydpi; // private final float density; // private final int widthPixels; // private final int heightPixels; // // public int getMicrometersPerPixel() { // return (int) (MICROMETERS_PER_INCH/ydpi); // } // // public int pixelsToMillimeters(int pixels) { // return pixelsToMicrometers(pixels) / 1000; // } // // public int pixelsToMicrometers(int pixels) { // return pixels * getMicrometersPerPixel(); // } // // public int micrometersToPixels(int micrometers) { // return micrometers / getMicrometersPerPixel(); // } // // // not unit tested, android stuff // public static AndroidMetrics get(Context ctx) { // DisplayMetrics metrics = new DisplayMetrics(); // WindowManager wm = (WindowManager) ctx.getSystemService(Context.WINDOW_SERVICE); // updateMetrics(wm.getDefaultDisplay(), metrics); // return new AndroidMetrics(metrics.ydpi, metrics.density, metrics.widthPixels, metrics.heightPixels); // } // // private static void updateMetrics(Display display, DisplayMetrics metrics) { // try { // doUpdateMetrics(display, metrics); // } catch (NoSuchMethodException e) { // showErrorAndSetDefaults(e, display, metrics); // } catch (IllegalAccessException e) { // showErrorAndSetDefaults(e, display, metrics); // } catch (InvocationTargetException e) { // showErrorAndSetDefaults(e, display, metrics); // } // } // // private static void doUpdateMetrics(Display display, DisplayMetrics metrics) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { // if (Build.VERSION.SDK_INT >= 14 && Build.VERSION.SDK_INT < 17) { // updateMetricsBeforeJBMR1(display, metrics); // } else if (Build.VERSION.SDK_INT >= 17) { // updateMetricsStartingWithJBMR1(display, metrics); // } else { // throw new NoSuchMethodException("The library does not support devices before android ICE CREAM SANDWICH (api 14)"); // } // } // // private static void updateMetricsBeforeJBMR1(Display display, DisplayMetrics metrics) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { // // Mandatory for yDpi & density // display.getMetrics(metrics); // metrics.widthPixels = (int) Display.class.getMethod("getRawWidth").invoke(display); // metrics.heightPixels = (int) Display.class.getMethod("getRawHeight").invoke(display); // } // // private static void updateMetricsStartingWithJBMR1(Display display, DisplayMetrics metrics) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { // Display.class.getMethod("getRealMetrics", DisplayMetrics.class).invoke(display, metrics); // } // // private static void showErrorAndSetDefaults(Exception e, Display display, DisplayMetrics metrics) { // Log.e(AndroidMetrics.class.getName(), String.format("Failed to get metrics, %s, %s", e.getMessage(), e.getClass().getName())); // display.getMetrics(metrics); // } // } // // Path: src/main/java/com/orange/dgil/trail/android/animation/AnimManager.java // public class AnimManager { // // private final AnimRunnable animRunnable; // private final AnimParameters animParameters = new AnimParameters(); // // public AnimManager(IAnimDrawer drawer) { // animRunnable = new AnimRunnable(drawer, animParameters); // } // // public void start() { // animRunnable.start(); // } // // public int getAnimColor() { // int startColor = animParameters.getStartColor(); // int endColor = animParameters.getEndColor(); // return getInterpolatedColor(startColor, endColor, animRunnable.getFactor()); // } // // public int getAnimShadowColor() { // int startColor = animParameters.getShadowStartColor(); // int endColor = animParameters.getShadowEndColor(); // return getInterpolatedColor(startColor, endColor, animRunnable.getFactor()); // } // // private int getInterpolatedColor(int startColor, int endColor, float factor) { // return Color.argb( // getInterp(Color.alpha(startColor), Color.alpha(endColor), factor), // getInterp(Color.red (startColor), Color.red (endColor), factor), // getInterp(Color.green(startColor), Color.green(endColor), factor), // getInterp(Color.blue (startColor), Color.blue (endColor), factor)); // } // private int getInterp(int start, int end, float factor) { // return (int) (start * factor + end * (1 - factor)); // } // // // public float getFactor() { // return animRunnable.getFactor(); // } // // /** // * The width factor is made to dilate the trail during fading // * @return the width factor // */ // public float getWidthFactor() { // float factor = getFactor(); // return 1 + animParameters.getWidthDilatationFactor() * (1-factor); // } // // public void reset() { // animRunnable.reset(); // } // // public AnimParameters getAnimationParameters() { // return animParameters; // } // // public boolean isRunning() { // return animRunnable.isRunning(); // } // // public boolean isAlphaAnimationRunning() { // return isRunning() && animParameters.areStartEndColorsRgbEqual(); // } // } // Path: src/main/java/com/orange/dgil/trail/android/drawingtool/DrawingToolsContext.java import android.view.View; import com.orange.dgil.trail.android.AndroidMetrics; import com.orange.dgil.trail.android.animation.AnimManager; import lombok.Getter; import lombok.RequiredArgsConstructor; /** * Trail drawing library * Copyright (C) 2014 Orange * Authors: christophe.maldivi@orange.com, eric.petit@orange.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.orange.dgil.trail.android.drawingtool; @RequiredArgsConstructor @Getter public class DrawingToolsContext { private final View view; private final AnimManager animManager;
private final AndroidMetrics androidMetrics;
Orange-OpenSource/android-trail-drawing
src/test/java/com/orange/dgil/trail/core/vecto/SlidingWindowGetLastElementIndexTest.java
// Path: src/main/java/com/orange/dgil/trail/core/common/TrailPoint.java // @Getter // @NoArgsConstructor // public class TrailPoint { // private int x = -1; // private int y = -1; // // public TrailPoint(int x, int y) { // set(x, y); // } // // public void set(int x, int y) { // this.x = x; // this.y = y; // } // // public boolean isSameAs(TrailPoint point) { // return x == point.x && y == point.y; // } // // public double getDistanceTo(TrailPoint point) { // int dx = x - point.getX(); // int dy = y - point.getY(); // return Math.sqrt(dx * dx + dy * dy); // } // // public void deepCopy(TrailPoint point) { // x = point.x; // y = point.y; // } // }
import com.orange.dgil.trail.TestTools; import com.orange.dgil.trail.core.common.TrailPoint; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito;
/** * Trail drawing library * Copyright (C) 2014 Orange * Authors: christophe.maldivi@orange.com, eric.petit@orange.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.orange.dgil.trail.core.vecto; public class SlidingWindowGetLastElementIndexTest { private SlidingWindow slidingWindow; @Before public void setUp() { slidingWindow = Mockito.mock(SlidingWindow.class); } @Test public void shouldDoGetLastElementWithAddedElementsNumber() throws IllegalAccessException { // given int addedElementsNumber = 1; int windowSize = 3;
// Path: src/main/java/com/orange/dgil/trail/core/common/TrailPoint.java // @Getter // @NoArgsConstructor // public class TrailPoint { // private int x = -1; // private int y = -1; // // public TrailPoint(int x, int y) { // set(x, y); // } // // public void set(int x, int y) { // this.x = x; // this.y = y; // } // // public boolean isSameAs(TrailPoint point) { // return x == point.x && y == point.y; // } // // public double getDistanceTo(TrailPoint point) { // int dx = x - point.getX(); // int dy = y - point.getY(); // return Math.sqrt(dx * dx + dy * dy); // } // // public void deepCopy(TrailPoint point) { // x = point.x; // y = point.y; // } // } // Path: src/test/java/com/orange/dgil/trail/core/vecto/SlidingWindowGetLastElementIndexTest.java import com.orange.dgil.trail.TestTools; import com.orange.dgil.trail.core.common.TrailPoint; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; /** * Trail drawing library * Copyright (C) 2014 Orange * Authors: christophe.maldivi@orange.com, eric.petit@orange.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.orange.dgil.trail.core.vecto; public class SlidingWindowGetLastElementIndexTest { private SlidingWindow slidingWindow; @Before public void setUp() { slidingWindow = Mockito.mock(SlidingWindow.class); } @Test public void shouldDoGetLastElementWithAddedElementsNumber() throws IllegalAccessException { // given int addedElementsNumber = 1; int windowSize = 3;
TrailPoint[] points = new TrailPoint[windowSize];
Orange-OpenSource/android-trail-drawing
src/main/java/com/orange/dgil/trail/android/drawingtool/quillpen/QuillParameters.java
// Path: src/main/java/com/orange/dgil/trail/android/AndroidMetrics.java // @Getter // @RequiredArgsConstructor // public class AndroidMetrics { // private static final int MICROMETERS_PER_INCH = 25400; // // private final float ydpi; // private final float density; // private final int widthPixels; // private final int heightPixels; // // public int getMicrometersPerPixel() { // return (int) (MICROMETERS_PER_INCH/ydpi); // } // // public int pixelsToMillimeters(int pixels) { // return pixelsToMicrometers(pixels) / 1000; // } // // public int pixelsToMicrometers(int pixels) { // return pixels * getMicrometersPerPixel(); // } // // public int micrometersToPixels(int micrometers) { // return micrometers / getMicrometersPerPixel(); // } // // // not unit tested, android stuff // public static AndroidMetrics get(Context ctx) { // DisplayMetrics metrics = new DisplayMetrics(); // WindowManager wm = (WindowManager) ctx.getSystemService(Context.WINDOW_SERVICE); // updateMetrics(wm.getDefaultDisplay(), metrics); // return new AndroidMetrics(metrics.ydpi, metrics.density, metrics.widthPixels, metrics.heightPixels); // } // // private static void updateMetrics(Display display, DisplayMetrics metrics) { // try { // doUpdateMetrics(display, metrics); // } catch (NoSuchMethodException e) { // showErrorAndSetDefaults(e, display, metrics); // } catch (IllegalAccessException e) { // showErrorAndSetDefaults(e, display, metrics); // } catch (InvocationTargetException e) { // showErrorAndSetDefaults(e, display, metrics); // } // } // // private static void doUpdateMetrics(Display display, DisplayMetrics metrics) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { // if (Build.VERSION.SDK_INT >= 14 && Build.VERSION.SDK_INT < 17) { // updateMetricsBeforeJBMR1(display, metrics); // } else if (Build.VERSION.SDK_INT >= 17) { // updateMetricsStartingWithJBMR1(display, metrics); // } else { // throw new NoSuchMethodException("The library does not support devices before android ICE CREAM SANDWICH (api 14)"); // } // } // // private static void updateMetricsBeforeJBMR1(Display display, DisplayMetrics metrics) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { // // Mandatory for yDpi & density // display.getMetrics(metrics); // metrics.widthPixels = (int) Display.class.getMethod("getRawWidth").invoke(display); // metrics.heightPixels = (int) Display.class.getMethod("getRawHeight").invoke(display); // } // // private static void updateMetricsStartingWithJBMR1(Display display, DisplayMetrics metrics) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { // Display.class.getMethod("getRealMetrics", DisplayMetrics.class).invoke(display, metrics); // } // // private static void showErrorAndSetDefaults(Exception e, Display display, DisplayMetrics metrics) { // Log.e(AndroidMetrics.class.getName(), String.format("Failed to get metrics, %s, %s", e.getMessage(), e.getClass().getName())); // display.getMetrics(metrics); // } // } // // Path: src/main/java/com/orange/dgil/trail/android/DefaultDrawerConf.java // public class DefaultDrawerConf { // public static final int TRAIL_COLOR = Color.rgb(0xFF, 0x99, 0); // public static final int TRAIL_WIDTH_UM = 2500; // // public static final float SHADOW_RADIUS_FACTOR = 0.5f; // public static final float SHADOW_OFFSET_FACTOR = 0.33f; // public static final int SHADOW_COLOR = Color.BLACK; // // public static final int ANIM_PRE_ANIM_DELAY_MS = 100; // public static final int ANIM_DURATION_MS = 400; // // public static final int QUILL_WIDTH_UM = 3000; // public static final int QUILL_HEIGHT_UM = 1000; // public static final int QUILL_ANGLE_DEG = 45; // }
import com.orange.dgil.trail.android.AndroidMetrics; import com.orange.dgil.trail.android.DefaultDrawerConf; import lombok.AccessLevel; import lombok.Getter;
/** * Trail drawing library * Copyright (C) 2014 Orange * Authors: christophe.maldivi@orange.com, eric.petit@orange.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.orange.dgil.trail.android.drawingtool.quillpen; @Getter public class QuillParameters { @Getter(AccessLevel.NONE)
// Path: src/main/java/com/orange/dgil/trail/android/AndroidMetrics.java // @Getter // @RequiredArgsConstructor // public class AndroidMetrics { // private static final int MICROMETERS_PER_INCH = 25400; // // private final float ydpi; // private final float density; // private final int widthPixels; // private final int heightPixels; // // public int getMicrometersPerPixel() { // return (int) (MICROMETERS_PER_INCH/ydpi); // } // // public int pixelsToMillimeters(int pixels) { // return pixelsToMicrometers(pixels) / 1000; // } // // public int pixelsToMicrometers(int pixels) { // return pixels * getMicrometersPerPixel(); // } // // public int micrometersToPixels(int micrometers) { // return micrometers / getMicrometersPerPixel(); // } // // // not unit tested, android stuff // public static AndroidMetrics get(Context ctx) { // DisplayMetrics metrics = new DisplayMetrics(); // WindowManager wm = (WindowManager) ctx.getSystemService(Context.WINDOW_SERVICE); // updateMetrics(wm.getDefaultDisplay(), metrics); // return new AndroidMetrics(metrics.ydpi, metrics.density, metrics.widthPixels, metrics.heightPixels); // } // // private static void updateMetrics(Display display, DisplayMetrics metrics) { // try { // doUpdateMetrics(display, metrics); // } catch (NoSuchMethodException e) { // showErrorAndSetDefaults(e, display, metrics); // } catch (IllegalAccessException e) { // showErrorAndSetDefaults(e, display, metrics); // } catch (InvocationTargetException e) { // showErrorAndSetDefaults(e, display, metrics); // } // } // // private static void doUpdateMetrics(Display display, DisplayMetrics metrics) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { // if (Build.VERSION.SDK_INT >= 14 && Build.VERSION.SDK_INT < 17) { // updateMetricsBeforeJBMR1(display, metrics); // } else if (Build.VERSION.SDK_INT >= 17) { // updateMetricsStartingWithJBMR1(display, metrics); // } else { // throw new NoSuchMethodException("The library does not support devices before android ICE CREAM SANDWICH (api 14)"); // } // } // // private static void updateMetricsBeforeJBMR1(Display display, DisplayMetrics metrics) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { // // Mandatory for yDpi & density // display.getMetrics(metrics); // metrics.widthPixels = (int) Display.class.getMethod("getRawWidth").invoke(display); // metrics.heightPixels = (int) Display.class.getMethod("getRawHeight").invoke(display); // } // // private static void updateMetricsStartingWithJBMR1(Display display, DisplayMetrics metrics) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { // Display.class.getMethod("getRealMetrics", DisplayMetrics.class).invoke(display, metrics); // } // // private static void showErrorAndSetDefaults(Exception e, Display display, DisplayMetrics metrics) { // Log.e(AndroidMetrics.class.getName(), String.format("Failed to get metrics, %s, %s", e.getMessage(), e.getClass().getName())); // display.getMetrics(metrics); // } // } // // Path: src/main/java/com/orange/dgil/trail/android/DefaultDrawerConf.java // public class DefaultDrawerConf { // public static final int TRAIL_COLOR = Color.rgb(0xFF, 0x99, 0); // public static final int TRAIL_WIDTH_UM = 2500; // // public static final float SHADOW_RADIUS_FACTOR = 0.5f; // public static final float SHADOW_OFFSET_FACTOR = 0.33f; // public static final int SHADOW_COLOR = Color.BLACK; // // public static final int ANIM_PRE_ANIM_DELAY_MS = 100; // public static final int ANIM_DURATION_MS = 400; // // public static final int QUILL_WIDTH_UM = 3000; // public static final int QUILL_HEIGHT_UM = 1000; // public static final int QUILL_ANGLE_DEG = 45; // } // Path: src/main/java/com/orange/dgil/trail/android/drawingtool/quillpen/QuillParameters.java import com.orange.dgil.trail.android.AndroidMetrics; import com.orange.dgil.trail.android.DefaultDrawerConf; import lombok.AccessLevel; import lombok.Getter; /** * Trail drawing library * Copyright (C) 2014 Orange * Authors: christophe.maldivi@orange.com, eric.petit@orange.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.orange.dgil.trail.android.drawingtool.quillpen; @Getter public class QuillParameters { @Getter(AccessLevel.NONE)
private final AndroidMetrics metrics;
Orange-OpenSource/android-trail-drawing
src/main/java/com/orange/dgil/trail/android/drawingtool/quillpen/QuillParameters.java
// Path: src/main/java/com/orange/dgil/trail/android/AndroidMetrics.java // @Getter // @RequiredArgsConstructor // public class AndroidMetrics { // private static final int MICROMETERS_PER_INCH = 25400; // // private final float ydpi; // private final float density; // private final int widthPixels; // private final int heightPixels; // // public int getMicrometersPerPixel() { // return (int) (MICROMETERS_PER_INCH/ydpi); // } // // public int pixelsToMillimeters(int pixels) { // return pixelsToMicrometers(pixels) / 1000; // } // // public int pixelsToMicrometers(int pixels) { // return pixels * getMicrometersPerPixel(); // } // // public int micrometersToPixels(int micrometers) { // return micrometers / getMicrometersPerPixel(); // } // // // not unit tested, android stuff // public static AndroidMetrics get(Context ctx) { // DisplayMetrics metrics = new DisplayMetrics(); // WindowManager wm = (WindowManager) ctx.getSystemService(Context.WINDOW_SERVICE); // updateMetrics(wm.getDefaultDisplay(), metrics); // return new AndroidMetrics(metrics.ydpi, metrics.density, metrics.widthPixels, metrics.heightPixels); // } // // private static void updateMetrics(Display display, DisplayMetrics metrics) { // try { // doUpdateMetrics(display, metrics); // } catch (NoSuchMethodException e) { // showErrorAndSetDefaults(e, display, metrics); // } catch (IllegalAccessException e) { // showErrorAndSetDefaults(e, display, metrics); // } catch (InvocationTargetException e) { // showErrorAndSetDefaults(e, display, metrics); // } // } // // private static void doUpdateMetrics(Display display, DisplayMetrics metrics) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { // if (Build.VERSION.SDK_INT >= 14 && Build.VERSION.SDK_INT < 17) { // updateMetricsBeforeJBMR1(display, metrics); // } else if (Build.VERSION.SDK_INT >= 17) { // updateMetricsStartingWithJBMR1(display, metrics); // } else { // throw new NoSuchMethodException("The library does not support devices before android ICE CREAM SANDWICH (api 14)"); // } // } // // private static void updateMetricsBeforeJBMR1(Display display, DisplayMetrics metrics) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { // // Mandatory for yDpi & density // display.getMetrics(metrics); // metrics.widthPixels = (int) Display.class.getMethod("getRawWidth").invoke(display); // metrics.heightPixels = (int) Display.class.getMethod("getRawHeight").invoke(display); // } // // private static void updateMetricsStartingWithJBMR1(Display display, DisplayMetrics metrics) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { // Display.class.getMethod("getRealMetrics", DisplayMetrics.class).invoke(display, metrics); // } // // private static void showErrorAndSetDefaults(Exception e, Display display, DisplayMetrics metrics) { // Log.e(AndroidMetrics.class.getName(), String.format("Failed to get metrics, %s, %s", e.getMessage(), e.getClass().getName())); // display.getMetrics(metrics); // } // } // // Path: src/main/java/com/orange/dgil/trail/android/DefaultDrawerConf.java // public class DefaultDrawerConf { // public static final int TRAIL_COLOR = Color.rgb(0xFF, 0x99, 0); // public static final int TRAIL_WIDTH_UM = 2500; // // public static final float SHADOW_RADIUS_FACTOR = 0.5f; // public static final float SHADOW_OFFSET_FACTOR = 0.33f; // public static final int SHADOW_COLOR = Color.BLACK; // // public static final int ANIM_PRE_ANIM_DELAY_MS = 100; // public static final int ANIM_DURATION_MS = 400; // // public static final int QUILL_WIDTH_UM = 3000; // public static final int QUILL_HEIGHT_UM = 1000; // public static final int QUILL_ANGLE_DEG = 45; // }
import com.orange.dgil.trail.android.AndroidMetrics; import com.orange.dgil.trail.android.DefaultDrawerConf; import lombok.AccessLevel; import lombok.Getter;
/** * Trail drawing library * Copyright (C) 2014 Orange * Authors: christophe.maldivi@orange.com, eric.petit@orange.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.orange.dgil.trail.android.drawingtool.quillpen; @Getter public class QuillParameters { @Getter(AccessLevel.NONE) private final AndroidMetrics metrics; private int quillWidthPixels; private int quillHeightPixels; private int quillAngleDeg; private int quillAngleXOffset; private int radius; public QuillParameters(AndroidMetrics metrics) { this.metrics = metrics; init(); } private void init() {
// Path: src/main/java/com/orange/dgil/trail/android/AndroidMetrics.java // @Getter // @RequiredArgsConstructor // public class AndroidMetrics { // private static final int MICROMETERS_PER_INCH = 25400; // // private final float ydpi; // private final float density; // private final int widthPixels; // private final int heightPixels; // // public int getMicrometersPerPixel() { // return (int) (MICROMETERS_PER_INCH/ydpi); // } // // public int pixelsToMillimeters(int pixels) { // return pixelsToMicrometers(pixels) / 1000; // } // // public int pixelsToMicrometers(int pixels) { // return pixels * getMicrometersPerPixel(); // } // // public int micrometersToPixels(int micrometers) { // return micrometers / getMicrometersPerPixel(); // } // // // not unit tested, android stuff // public static AndroidMetrics get(Context ctx) { // DisplayMetrics metrics = new DisplayMetrics(); // WindowManager wm = (WindowManager) ctx.getSystemService(Context.WINDOW_SERVICE); // updateMetrics(wm.getDefaultDisplay(), metrics); // return new AndroidMetrics(metrics.ydpi, metrics.density, metrics.widthPixels, metrics.heightPixels); // } // // private static void updateMetrics(Display display, DisplayMetrics metrics) { // try { // doUpdateMetrics(display, metrics); // } catch (NoSuchMethodException e) { // showErrorAndSetDefaults(e, display, metrics); // } catch (IllegalAccessException e) { // showErrorAndSetDefaults(e, display, metrics); // } catch (InvocationTargetException e) { // showErrorAndSetDefaults(e, display, metrics); // } // } // // private static void doUpdateMetrics(Display display, DisplayMetrics metrics) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { // if (Build.VERSION.SDK_INT >= 14 && Build.VERSION.SDK_INT < 17) { // updateMetricsBeforeJBMR1(display, metrics); // } else if (Build.VERSION.SDK_INT >= 17) { // updateMetricsStartingWithJBMR1(display, metrics); // } else { // throw new NoSuchMethodException("The library does not support devices before android ICE CREAM SANDWICH (api 14)"); // } // } // // private static void updateMetricsBeforeJBMR1(Display display, DisplayMetrics metrics) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { // // Mandatory for yDpi & density // display.getMetrics(metrics); // metrics.widthPixels = (int) Display.class.getMethod("getRawWidth").invoke(display); // metrics.heightPixels = (int) Display.class.getMethod("getRawHeight").invoke(display); // } // // private static void updateMetricsStartingWithJBMR1(Display display, DisplayMetrics metrics) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { // Display.class.getMethod("getRealMetrics", DisplayMetrics.class).invoke(display, metrics); // } // // private static void showErrorAndSetDefaults(Exception e, Display display, DisplayMetrics metrics) { // Log.e(AndroidMetrics.class.getName(), String.format("Failed to get metrics, %s, %s", e.getMessage(), e.getClass().getName())); // display.getMetrics(metrics); // } // } // // Path: src/main/java/com/orange/dgil/trail/android/DefaultDrawerConf.java // public class DefaultDrawerConf { // public static final int TRAIL_COLOR = Color.rgb(0xFF, 0x99, 0); // public static final int TRAIL_WIDTH_UM = 2500; // // public static final float SHADOW_RADIUS_FACTOR = 0.5f; // public static final float SHADOW_OFFSET_FACTOR = 0.33f; // public static final int SHADOW_COLOR = Color.BLACK; // // public static final int ANIM_PRE_ANIM_DELAY_MS = 100; // public static final int ANIM_DURATION_MS = 400; // // public static final int QUILL_WIDTH_UM = 3000; // public static final int QUILL_HEIGHT_UM = 1000; // public static final int QUILL_ANGLE_DEG = 45; // } // Path: src/main/java/com/orange/dgil/trail/android/drawingtool/quillpen/QuillParameters.java import com.orange.dgil.trail.android.AndroidMetrics; import com.orange.dgil.trail.android.DefaultDrawerConf; import lombok.AccessLevel; import lombok.Getter; /** * Trail drawing library * Copyright (C) 2014 Orange * Authors: christophe.maldivi@orange.com, eric.petit@orange.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.orange.dgil.trail.android.drawingtool.quillpen; @Getter public class QuillParameters { @Getter(AccessLevel.NONE) private final AndroidMetrics metrics; private int quillWidthPixels; private int quillHeightPixels; private int quillAngleDeg; private int quillAngleXOffset; private int radius; public QuillParameters(AndroidMetrics metrics) { this.metrics = metrics; init(); } private void init() {
setQuillWidthHeightMicrometers(DefaultDrawerConf.QUILL_WIDTH_UM, DefaultDrawerConf.QUILL_HEIGHT_UM);
Orange-OpenSource/android-trail-drawing
src/test/java/com/orange/dgil/trail/core/vecto/SlidingWindowIsFullTest.java
// Path: src/main/java/com/orange/dgil/trail/core/common/TrailPoint.java // @Getter // @NoArgsConstructor // public class TrailPoint { // private int x = -1; // private int y = -1; // // public TrailPoint(int x, int y) { // set(x, y); // } // // public void set(int x, int y) { // this.x = x; // this.y = y; // } // // public boolean isSameAs(TrailPoint point) { // return x == point.x && y == point.y; // } // // public double getDistanceTo(TrailPoint point) { // int dx = x - point.getX(); // int dy = y - point.getY(); // return Math.sqrt(dx * dx + dy * dy); // } // // public void deepCopy(TrailPoint point) { // x = point.x; // y = point.y; // } // }
import com.orange.dgil.trail.TestTools; import com.orange.dgil.trail.core.common.TrailPoint; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito;
/** * Trail drawing library * Copyright (C) 2014 Orange * Authors: christophe.maldivi@orange.com, eric.petit@orange.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.orange.dgil.trail.core.vecto; public class SlidingWindowIsFullTest { private SlidingWindow slidingWindow; @Before public void setUp() { slidingWindow = Mockito.mock(SlidingWindow.class); } @Test public void shouldReturnTrueWhenIsFull() throws IllegalAccessException { // given int addedElementsNumber = 3; int windowSize = 3;
// Path: src/main/java/com/orange/dgil/trail/core/common/TrailPoint.java // @Getter // @NoArgsConstructor // public class TrailPoint { // private int x = -1; // private int y = -1; // // public TrailPoint(int x, int y) { // set(x, y); // } // // public void set(int x, int y) { // this.x = x; // this.y = y; // } // // public boolean isSameAs(TrailPoint point) { // return x == point.x && y == point.y; // } // // public double getDistanceTo(TrailPoint point) { // int dx = x - point.getX(); // int dy = y - point.getY(); // return Math.sqrt(dx * dx + dy * dy); // } // // public void deepCopy(TrailPoint point) { // x = point.x; // y = point.y; // } // } // Path: src/test/java/com/orange/dgil/trail/core/vecto/SlidingWindowIsFullTest.java import com.orange.dgil.trail.TestTools; import com.orange.dgil.trail.core.common.TrailPoint; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; /** * Trail drawing library * Copyright (C) 2014 Orange * Authors: christophe.maldivi@orange.com, eric.petit@orange.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.orange.dgil.trail.core.vecto; public class SlidingWindowIsFullTest { private SlidingWindow slidingWindow; @Before public void setUp() { slidingWindow = Mockito.mock(SlidingWindow.class); } @Test public void shouldReturnTrueWhenIsFull() throws IllegalAccessException { // given int addedElementsNumber = 3; int windowSize = 3;
TrailPoint[] points = new TrailPoint[windowSize];
Orange-OpenSource/android-trail-drawing
src/test/java/com/orange/dgil/trail/core/vecto/SlidingWindowGetLastElementTest.java
// Path: src/main/java/com/orange/dgil/trail/core/common/TrailPoint.java // @Getter // @NoArgsConstructor // public class TrailPoint { // private int x = -1; // private int y = -1; // // public TrailPoint(int x, int y) { // set(x, y); // } // // public void set(int x, int y) { // this.x = x; // this.y = y; // } // // public boolean isSameAs(TrailPoint point) { // return x == point.x && y == point.y; // } // // public double getDistanceTo(TrailPoint point) { // int dx = x - point.getX(); // int dy = y - point.getY(); // return Math.sqrt(dx * dx + dy * dy); // } // // public void deepCopy(TrailPoint point) { // x = point.x; // y = point.y; // } // }
import com.orange.dgil.trail.core.common.TrailPoint; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito;
/** * Trail drawing library * Copyright (C) 2014 Orange * Authors: christophe.maldivi@orange.com, eric.petit@orange.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.orange.dgil.trail.core.vecto; public class SlidingWindowGetLastElementTest { private SlidingWindow slidingWindow; @Before public void setUp() { slidingWindow = Mockito.mock(SlidingWindow.class); } @Test public void shouldGetLastElement() throws IllegalAccessException { // given int lastIndex = 3; Mockito.when(slidingWindow.getLastElementIndex()).thenReturn(lastIndex);
// Path: src/main/java/com/orange/dgil/trail/core/common/TrailPoint.java // @Getter // @NoArgsConstructor // public class TrailPoint { // private int x = -1; // private int y = -1; // // public TrailPoint(int x, int y) { // set(x, y); // } // // public void set(int x, int y) { // this.x = x; // this.y = y; // } // // public boolean isSameAs(TrailPoint point) { // return x == point.x && y == point.y; // } // // public double getDistanceTo(TrailPoint point) { // int dx = x - point.getX(); // int dy = y - point.getY(); // return Math.sqrt(dx * dx + dy * dy); // } // // public void deepCopy(TrailPoint point) { // x = point.x; // y = point.y; // } // } // Path: src/test/java/com/orange/dgil/trail/core/vecto/SlidingWindowGetLastElementTest.java import com.orange.dgil.trail.core.common.TrailPoint; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; /** * Trail drawing library * Copyright (C) 2014 Orange * Authors: christophe.maldivi@orange.com, eric.petit@orange.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.orange.dgil.trail.core.vecto; public class SlidingWindowGetLastElementTest { private SlidingWindow slidingWindow; @Before public void setUp() { slidingWindow = Mockito.mock(SlidingWindow.class); } @Test public void shouldGetLastElement() throws IllegalAccessException { // given int lastIndex = 3; Mockito.when(slidingWindow.getLastElementIndex()).thenReturn(lastIndex);
TrailPoint lastPoint = new TrailPoint();
Orange-OpenSource/android-trail-drawing
src/main/java/com/orange/dgil/trail/core/quad/QuadDat.java
// Path: src/main/java/com/orange/dgil/trail/core/common/TrailPoint.java // @Getter // @NoArgsConstructor // public class TrailPoint { // private int x = -1; // private int y = -1; // // public TrailPoint(int x, int y) { // set(x, y); // } // // public void set(int x, int y) { // this.x = x; // this.y = y; // } // // public boolean isSameAs(TrailPoint point) { // return x == point.x && y == point.y; // } // // public double getDistanceTo(TrailPoint point) { // int dx = x - point.getX(); // int dy = y - point.getY(); // return Math.sqrt(dx * dx + dy * dy); // } // // public void deepCopy(TrailPoint point) { // x = point.x; // y = point.y; // } // }
import com.orange.dgil.trail.core.common.TrailPoint; import lombok.AccessLevel; import lombok.Getter; import lombok.Setter;
/** * Trail drawing library * Copyright (C) 2014 Orange * Authors: christophe.maldivi@orange.com, eric.petit@orange.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.orange.dgil.trail.core.quad; @Getter(AccessLevel.PACKAGE) @Setter(AccessLevel.PACKAGE) class QuadDat {
// Path: src/main/java/com/orange/dgil/trail/core/common/TrailPoint.java // @Getter // @NoArgsConstructor // public class TrailPoint { // private int x = -1; // private int y = -1; // // public TrailPoint(int x, int y) { // set(x, y); // } // // public void set(int x, int y) { // this.x = x; // this.y = y; // } // // public boolean isSameAs(TrailPoint point) { // return x == point.x && y == point.y; // } // // public double getDistanceTo(TrailPoint point) { // int dx = x - point.getX(); // int dy = y - point.getY(); // return Math.sqrt(dx * dx + dy * dy); // } // // public void deepCopy(TrailPoint point) { // x = point.x; // y = point.y; // } // } // Path: src/main/java/com/orange/dgil/trail/core/quad/QuadDat.java import com.orange.dgil.trail.core.common.TrailPoint; import lombok.AccessLevel; import lombok.Getter; import lombok.Setter; /** * Trail drawing library * Copyright (C) 2014 Orange * Authors: christophe.maldivi@orange.com, eric.petit@orange.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.orange.dgil.trail.core.quad; @Getter(AccessLevel.PACKAGE) @Setter(AccessLevel.PACKAGE) class QuadDat {
private final TrailPoint interpStartPoint = new TrailPoint();
Orange-OpenSource/android-trail-drawing
src/main/java/com/orange/dgil/trail/core/quad/QuadInterpolator.java
// Path: src/main/java/com/orange/dgil/trail/core/common/TrailPoint.java // @Getter // @NoArgsConstructor // public class TrailPoint { // private int x = -1; // private int y = -1; // // public TrailPoint(int x, int y) { // set(x, y); // } // // public void set(int x, int y) { // this.x = x; // this.y = y; // } // // public boolean isSameAs(TrailPoint point) { // return x == point.x && y == point.y; // } // // public double getDistanceTo(TrailPoint point) { // int dx = x - point.getX(); // int dy = y - point.getY(); // return Math.sqrt(dx * dx + dy * dy); // } // // public void deepCopy(TrailPoint point) { // x = point.x; // y = point.y; // } // } // // Path: src/main/java/com/orange/dgil/trail/core/vecto/SlidingWindow.java // public class SlidingWindow { // // private TrailPoint[] points; // // @Getter // private int addedElementsNumber; // // public SlidingWindow(int windowSize) { // setWindowSize(windowSize); // } // // public void setWindowSize(int windowSize) { // points = new TrailPoint[windowSize]; // allocatePoints(); // } // // public int getWindowSize() { // return points.length; // } // // private void allocatePoints() { // for (int i = 0; i < points.length; i++) { // points[i] = new TrailPoint(); // } // } // // public void reset() { // addedElementsNumber = 0; // } // // public void add(int x, int y) { // if (isFull()) { // slidePointsToTheLeft(); // } // doAdd(x, y); // } // // public void add(TrailPoint point) { // add(point.getX(), point.getY()); // } // // public int getX(int index) { // if (isIndexValid(index)) { // return points[index].getX(); // } else { // throw new SlidingWindowIndexException(String.format("Invalid index '%d' (max index %d)", index, getMaxIndex())); // } // } // // public int getY(int index) { // if (isIndexValid(index)) { // return points[index].getY(); // } else { // throw getInvalidIndexException(index); // } // } // // boolean isIndexValid(int index) { // return index >= 0 && index <= getMaxIndex(); // } // // int getMaxIndex() { // return Math.min(addedElementsNumber, points.length) - 1; // } // // void slidePointsToTheLeft() { // TrailPoint p0 = points[0]; // for (int i = 0; i < points.length-1; i++) { // points[i] = points[i+1]; // } // points[points.length-1] = p0; // } // // void doAdd(int x, int y) { // points[getInsertIndex()].set(x, y); // addedElementsNumber++; // } // // public TrailPoint getElementAt(int index) { // if (isIndexValid(index)) { // return points[index]; // } else { // throw getInvalidIndexException(index); // } // } // // public TrailPoint getLastElement() { // return getElementAt(getLastElementIndex()); // } // // public boolean isSameAsLast(TrailPoint p) { // if (addedElementsNumber == 0) { // return false; // } else { // return p.isSameAs(points[getLastElementIndex()]); // } // } // // int getInsertIndex() { // return Math.min(addedElementsNumber, points.length - 1); // } // // public int getLastElementIndex() { // return Math.min(addedElementsNumber - 1, points.length - 1); // } // // public boolean isFull() { // return addedElementsNumber >= points.length; // } // // public void removeElementsAtLeftOf(int index) { // if (isIndexValid(index)) { // doRemoveElementsAtLeftOf(index); // } else { // throw getInvalidIndexException(index); // } // } // // private void doRemoveElementsAtLeftOf(int index) { // for (int i = 0; i <= getLastElementIndex()-index; i++) { // int sourceIndex = index + i; // shiftPoint(i, sourceIndex); // } // addedElementsNumber -= index; // } // // private void shiftPoint(int destIndex, int sourceIndex) { // if (sourceIndex < points.length) { // TrailPoint source = points[sourceIndex]; // points[destIndex].set(source.getX(), source.getY()); // } // } // // private SlidingWindowIndexException getInvalidIndexException(int index) { // return new SlidingWindowIndexException(String.format("Invalid index '%d' (max index %d)", index, getMaxIndex())); // } // }
import com.orange.dgil.trail.core.common.TrailPoint; import com.orange.dgil.trail.core.vecto.SlidingWindow; import lombok.AccessLevel; import lombok.Getter; import lombok.Setter;
private void doInterpolation() { quadDat.setPoint0(slidingWindow.getElementAt(0)); quadDat.setPoint1(slidingWindow.getElementAt(1)); quadDat.setPoint2(slidingWindow.getElementAt(2)); interpolate(); quadDat.setCurveStart(false); } void interpolate() { updateInterpStartAndEndPoints(); rawInterpolate(); handleCurveEnd(); } private void updateInterpStartAndEndPoints() { updateInterpStartEndWithMiddles(); if (quadDat.isCurveStart()) { quadDat.getInterpStartPoint().deepCopy(quadDat.getPoint0()); } if (quadDat.isCurveEnd()) { quadDat.getInterpEndPoint().deepCopy(quadDat.getPoint2()); } } private void updateInterpStartEndWithMiddles() { updateWithMiddle(quadDat.getInterpStartPoint(), quadDat.getPoint0(), quadDat.getPoint1()); updateWithMiddle(quadDat.getInterpEndPoint(), quadDat.getPoint1(), quadDat.getPoint2()); }
// Path: src/main/java/com/orange/dgil/trail/core/common/TrailPoint.java // @Getter // @NoArgsConstructor // public class TrailPoint { // private int x = -1; // private int y = -1; // // public TrailPoint(int x, int y) { // set(x, y); // } // // public void set(int x, int y) { // this.x = x; // this.y = y; // } // // public boolean isSameAs(TrailPoint point) { // return x == point.x && y == point.y; // } // // public double getDistanceTo(TrailPoint point) { // int dx = x - point.getX(); // int dy = y - point.getY(); // return Math.sqrt(dx * dx + dy * dy); // } // // public void deepCopy(TrailPoint point) { // x = point.x; // y = point.y; // } // } // // Path: src/main/java/com/orange/dgil/trail/core/vecto/SlidingWindow.java // public class SlidingWindow { // // private TrailPoint[] points; // // @Getter // private int addedElementsNumber; // // public SlidingWindow(int windowSize) { // setWindowSize(windowSize); // } // // public void setWindowSize(int windowSize) { // points = new TrailPoint[windowSize]; // allocatePoints(); // } // // public int getWindowSize() { // return points.length; // } // // private void allocatePoints() { // for (int i = 0; i < points.length; i++) { // points[i] = new TrailPoint(); // } // } // // public void reset() { // addedElementsNumber = 0; // } // // public void add(int x, int y) { // if (isFull()) { // slidePointsToTheLeft(); // } // doAdd(x, y); // } // // public void add(TrailPoint point) { // add(point.getX(), point.getY()); // } // // public int getX(int index) { // if (isIndexValid(index)) { // return points[index].getX(); // } else { // throw new SlidingWindowIndexException(String.format("Invalid index '%d' (max index %d)", index, getMaxIndex())); // } // } // // public int getY(int index) { // if (isIndexValid(index)) { // return points[index].getY(); // } else { // throw getInvalidIndexException(index); // } // } // // boolean isIndexValid(int index) { // return index >= 0 && index <= getMaxIndex(); // } // // int getMaxIndex() { // return Math.min(addedElementsNumber, points.length) - 1; // } // // void slidePointsToTheLeft() { // TrailPoint p0 = points[0]; // for (int i = 0; i < points.length-1; i++) { // points[i] = points[i+1]; // } // points[points.length-1] = p0; // } // // void doAdd(int x, int y) { // points[getInsertIndex()].set(x, y); // addedElementsNumber++; // } // // public TrailPoint getElementAt(int index) { // if (isIndexValid(index)) { // return points[index]; // } else { // throw getInvalidIndexException(index); // } // } // // public TrailPoint getLastElement() { // return getElementAt(getLastElementIndex()); // } // // public boolean isSameAsLast(TrailPoint p) { // if (addedElementsNumber == 0) { // return false; // } else { // return p.isSameAs(points[getLastElementIndex()]); // } // } // // int getInsertIndex() { // return Math.min(addedElementsNumber, points.length - 1); // } // // public int getLastElementIndex() { // return Math.min(addedElementsNumber - 1, points.length - 1); // } // // public boolean isFull() { // return addedElementsNumber >= points.length; // } // // public void removeElementsAtLeftOf(int index) { // if (isIndexValid(index)) { // doRemoveElementsAtLeftOf(index); // } else { // throw getInvalidIndexException(index); // } // } // // private void doRemoveElementsAtLeftOf(int index) { // for (int i = 0; i <= getLastElementIndex()-index; i++) { // int sourceIndex = index + i; // shiftPoint(i, sourceIndex); // } // addedElementsNumber -= index; // } // // private void shiftPoint(int destIndex, int sourceIndex) { // if (sourceIndex < points.length) { // TrailPoint source = points[sourceIndex]; // points[destIndex].set(source.getX(), source.getY()); // } // } // // private SlidingWindowIndexException getInvalidIndexException(int index) { // return new SlidingWindowIndexException(String.format("Invalid index '%d' (max index %d)", index, getMaxIndex())); // } // } // Path: src/main/java/com/orange/dgil/trail/core/quad/QuadInterpolator.java import com.orange.dgil.trail.core.common.TrailPoint; import com.orange.dgil.trail.core.vecto.SlidingWindow; import lombok.AccessLevel; import lombok.Getter; import lombok.Setter; private void doInterpolation() { quadDat.setPoint0(slidingWindow.getElementAt(0)); quadDat.setPoint1(slidingWindow.getElementAt(1)); quadDat.setPoint2(slidingWindow.getElementAt(2)); interpolate(); quadDat.setCurveStart(false); } void interpolate() { updateInterpStartAndEndPoints(); rawInterpolate(); handleCurveEnd(); } private void updateInterpStartAndEndPoints() { updateInterpStartEndWithMiddles(); if (quadDat.isCurveStart()) { quadDat.getInterpStartPoint().deepCopy(quadDat.getPoint0()); } if (quadDat.isCurveEnd()) { quadDat.getInterpEndPoint().deepCopy(quadDat.getPoint2()); } } private void updateInterpStartEndWithMiddles() { updateWithMiddle(quadDat.getInterpStartPoint(), quadDat.getPoint0(), quadDat.getPoint1()); updateWithMiddle(quadDat.getInterpEndPoint(), quadDat.getPoint1(), quadDat.getPoint2()); }
private void updateWithMiddle(TrailPoint destPoint, TrailPoint point0, TrailPoint point1) {
Orange-OpenSource/android-trail-drawing
src/main/java/com/orange/dgil/trail/android/drawingtool/markerpen/MarkerPaths.java
// Path: src/main/java/com/orange/dgil/trail/android/drawingtool/DrawingToolsContext.java // @RequiredArgsConstructor // @Getter // public class DrawingToolsContext { // private final View view; // private final AnimManager animManager; // private final AndroidMetrics androidMetrics; // private final TrailOptions trailOptions; // } // // Path: src/main/java/com/orange/dgil/trail/android/drawingtool/IDrawingTool.java // public interface IDrawingTool { // void reset(); // // void touchDown(int x, int y); // void touchMove(int x, int y); // void touchUp(); // // void draw(Canvas c); // // void invalidateAreaOnMove(); // void invalidatePath(); // // void forceRedrawForAnimation(boolean eraseBitmap); // // void trimMemory(); // } // // Path: src/main/java/com/orange/dgil/trail/android/drawingtool/InvalidateArea.java // @Getter // @Setter // public class InvalidateArea { // private final Rect rect = new Rect(); // private int radius; // // public void setOrigin(int x, int y) { // rect.set(x - radius, y - radius, x + radius, y + radius); // } // public void setOrigin(Point p) { // setOrigin(p.x, p.y); // } // // public void add(int x, int y) { // rect.union(x - radius, y - radius, x + radius, y + radius); // } // public void add(Point p) { // add(p.x, p.y); // } // // public void setEmpty() { // rect.setEmpty(); // } // }
import android.graphics.Canvas; import android.graphics.Path; import android.graphics.Point; import android.graphics.RectF; import android.view.View; import com.orange.dgil.trail.android.drawingtool.DrawingToolsContext; import com.orange.dgil.trail.android.drawingtool.IDrawingTool; import com.orange.dgil.trail.android.drawingtool.InvalidateArea;
/** * Trail drawing library * Copyright (C) 2014 Orange * Authors: christophe.maldivi@orange.com, eric.petit@orange.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.orange.dgil.trail.android.drawingtool.markerpen; public class MarkerPaths implements IDrawingTool { private final Path path = new Path(); private final RectF rectF = new RectF();
// Path: src/main/java/com/orange/dgil/trail/android/drawingtool/DrawingToolsContext.java // @RequiredArgsConstructor // @Getter // public class DrawingToolsContext { // private final View view; // private final AnimManager animManager; // private final AndroidMetrics androidMetrics; // private final TrailOptions trailOptions; // } // // Path: src/main/java/com/orange/dgil/trail/android/drawingtool/IDrawingTool.java // public interface IDrawingTool { // void reset(); // // void touchDown(int x, int y); // void touchMove(int x, int y); // void touchUp(); // // void draw(Canvas c); // // void invalidateAreaOnMove(); // void invalidatePath(); // // void forceRedrawForAnimation(boolean eraseBitmap); // // void trimMemory(); // } // // Path: src/main/java/com/orange/dgil/trail/android/drawingtool/InvalidateArea.java // @Getter // @Setter // public class InvalidateArea { // private final Rect rect = new Rect(); // private int radius; // // public void setOrigin(int x, int y) { // rect.set(x - radius, y - radius, x + radius, y + radius); // } // public void setOrigin(Point p) { // setOrigin(p.x, p.y); // } // // public void add(int x, int y) { // rect.union(x - radius, y - radius, x + radius, y + radius); // } // public void add(Point p) { // add(p.x, p.y); // } // // public void setEmpty() { // rect.setEmpty(); // } // } // Path: src/main/java/com/orange/dgil/trail/android/drawingtool/markerpen/MarkerPaths.java import android.graphics.Canvas; import android.graphics.Path; import android.graphics.Point; import android.graphics.RectF; import android.view.View; import com.orange.dgil.trail.android.drawingtool.DrawingToolsContext; import com.orange.dgil.trail.android.drawingtool.IDrawingTool; import com.orange.dgil.trail.android.drawingtool.InvalidateArea; /** * Trail drawing library * Copyright (C) 2014 Orange * Authors: christophe.maldivi@orange.com, eric.petit@orange.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.orange.dgil.trail.android.drawingtool.markerpen; public class MarkerPaths implements IDrawingTool { private final Path path = new Path(); private final RectF rectF = new RectF();
private final InvalidateArea invalidateArea = new InvalidateArea();
Orange-OpenSource/android-trail-drawing
src/main/java/com/orange/dgil/trail/android/drawingtool/markerpen/MarkerPaths.java
// Path: src/main/java/com/orange/dgil/trail/android/drawingtool/DrawingToolsContext.java // @RequiredArgsConstructor // @Getter // public class DrawingToolsContext { // private final View view; // private final AnimManager animManager; // private final AndroidMetrics androidMetrics; // private final TrailOptions trailOptions; // } // // Path: src/main/java/com/orange/dgil/trail/android/drawingtool/IDrawingTool.java // public interface IDrawingTool { // void reset(); // // void touchDown(int x, int y); // void touchMove(int x, int y); // void touchUp(); // // void draw(Canvas c); // // void invalidateAreaOnMove(); // void invalidatePath(); // // void forceRedrawForAnimation(boolean eraseBitmap); // // void trimMemory(); // } // // Path: src/main/java/com/orange/dgil/trail/android/drawingtool/InvalidateArea.java // @Getter // @Setter // public class InvalidateArea { // private final Rect rect = new Rect(); // private int radius; // // public void setOrigin(int x, int y) { // rect.set(x - radius, y - radius, x + radius, y + radius); // } // public void setOrigin(Point p) { // setOrigin(p.x, p.y); // } // // public void add(int x, int y) { // rect.union(x - radius, y - radius, x + radius, y + radius); // } // public void add(Point p) { // add(p.x, p.y); // } // // public void setEmpty() { // rect.setEmpty(); // } // }
import android.graphics.Canvas; import android.graphics.Path; import android.graphics.Point; import android.graphics.RectF; import android.view.View; import com.orange.dgil.trail.android.drawingtool.DrawingToolsContext; import com.orange.dgil.trail.android.drawingtool.IDrawingTool; import com.orange.dgil.trail.android.drawingtool.InvalidateArea;
/** * Trail drawing library * Copyright (C) 2014 Orange * Authors: christophe.maldivi@orange.com, eric.petit@orange.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.orange.dgil.trail.android.drawingtool.markerpen; public class MarkerPaths implements IDrawingTool { private final Path path = new Path(); private final RectF rectF = new RectF(); private final InvalidateArea invalidateArea = new InvalidateArea(); private final View view; private final Painters painters; private final Point position = new Point(); private final Point middlePos = new Point(); private final Point prevPos = new Point(); private final Point prevMiddlePos = new Point();
// Path: src/main/java/com/orange/dgil/trail/android/drawingtool/DrawingToolsContext.java // @RequiredArgsConstructor // @Getter // public class DrawingToolsContext { // private final View view; // private final AnimManager animManager; // private final AndroidMetrics androidMetrics; // private final TrailOptions trailOptions; // } // // Path: src/main/java/com/orange/dgil/trail/android/drawingtool/IDrawingTool.java // public interface IDrawingTool { // void reset(); // // void touchDown(int x, int y); // void touchMove(int x, int y); // void touchUp(); // // void draw(Canvas c); // // void invalidateAreaOnMove(); // void invalidatePath(); // // void forceRedrawForAnimation(boolean eraseBitmap); // // void trimMemory(); // } // // Path: src/main/java/com/orange/dgil/trail/android/drawingtool/InvalidateArea.java // @Getter // @Setter // public class InvalidateArea { // private final Rect rect = new Rect(); // private int radius; // // public void setOrigin(int x, int y) { // rect.set(x - radius, y - radius, x + radius, y + radius); // } // public void setOrigin(Point p) { // setOrigin(p.x, p.y); // } // // public void add(int x, int y) { // rect.union(x - radius, y - radius, x + radius, y + radius); // } // public void add(Point p) { // add(p.x, p.y); // } // // public void setEmpty() { // rect.setEmpty(); // } // } // Path: src/main/java/com/orange/dgil/trail/android/drawingtool/markerpen/MarkerPaths.java import android.graphics.Canvas; import android.graphics.Path; import android.graphics.Point; import android.graphics.RectF; import android.view.View; import com.orange.dgil.trail.android.drawingtool.DrawingToolsContext; import com.orange.dgil.trail.android.drawingtool.IDrawingTool; import com.orange.dgil.trail.android.drawingtool.InvalidateArea; /** * Trail drawing library * Copyright (C) 2014 Orange * Authors: christophe.maldivi@orange.com, eric.petit@orange.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.orange.dgil.trail.android.drawingtool.markerpen; public class MarkerPaths implements IDrawingTool { private final Path path = new Path(); private final RectF rectF = new RectF(); private final InvalidateArea invalidateArea = new InvalidateArea(); private final View view; private final Painters painters; private final Point position = new Point(); private final Point middlePos = new Point(); private final Point prevPos = new Point(); private final Point prevMiddlePos = new Point();
public MarkerPaths(DrawingToolsContext drawingToolsContext) {
Orange-OpenSource/android-trail-drawing
src/test/java/com/orange/dgil/trail/core/vecto/linearwindowfilter/LinearWindowFilterComputeNewPointTest.java
// Path: src/main/java/com/orange/dgil/trail/core/common/TrailPoint.java // @Getter // @NoArgsConstructor // public class TrailPoint { // private int x = -1; // private int y = -1; // // public TrailPoint(int x, int y) { // set(x, y); // } // // public void set(int x, int y) { // this.x = x; // this.y = y; // } // // public boolean isSameAs(TrailPoint point) { // return x == point.x && y == point.y; // } // // public double getDistanceTo(TrailPoint point) { // int dx = x - point.getX(); // int dy = y - point.getY(); // return Math.sqrt(dx * dx + dy * dy); // } // // public void deepCopy(TrailPoint point) { // x = point.x; // y = point.y; // } // } // // Path: src/main/java/com/orange/dgil/trail/core/vecto/SlidingWindow.java // public class SlidingWindow { // // private TrailPoint[] points; // // @Getter // private int addedElementsNumber; // // public SlidingWindow(int windowSize) { // setWindowSize(windowSize); // } // // public void setWindowSize(int windowSize) { // points = new TrailPoint[windowSize]; // allocatePoints(); // } // // public int getWindowSize() { // return points.length; // } // // private void allocatePoints() { // for (int i = 0; i < points.length; i++) { // points[i] = new TrailPoint(); // } // } // // public void reset() { // addedElementsNumber = 0; // } // // public void add(int x, int y) { // if (isFull()) { // slidePointsToTheLeft(); // } // doAdd(x, y); // } // // public void add(TrailPoint point) { // add(point.getX(), point.getY()); // } // // public int getX(int index) { // if (isIndexValid(index)) { // return points[index].getX(); // } else { // throw new SlidingWindowIndexException(String.format("Invalid index '%d' (max index %d)", index, getMaxIndex())); // } // } // // public int getY(int index) { // if (isIndexValid(index)) { // return points[index].getY(); // } else { // throw getInvalidIndexException(index); // } // } // // boolean isIndexValid(int index) { // return index >= 0 && index <= getMaxIndex(); // } // // int getMaxIndex() { // return Math.min(addedElementsNumber, points.length) - 1; // } // // void slidePointsToTheLeft() { // TrailPoint p0 = points[0]; // for (int i = 0; i < points.length-1; i++) { // points[i] = points[i+1]; // } // points[points.length-1] = p0; // } // // void doAdd(int x, int y) { // points[getInsertIndex()].set(x, y); // addedElementsNumber++; // } // // public TrailPoint getElementAt(int index) { // if (isIndexValid(index)) { // return points[index]; // } else { // throw getInvalidIndexException(index); // } // } // // public TrailPoint getLastElement() { // return getElementAt(getLastElementIndex()); // } // // public boolean isSameAsLast(TrailPoint p) { // if (addedElementsNumber == 0) { // return false; // } else { // return p.isSameAs(points[getLastElementIndex()]); // } // } // // int getInsertIndex() { // return Math.min(addedElementsNumber, points.length - 1); // } // // public int getLastElementIndex() { // return Math.min(addedElementsNumber - 1, points.length - 1); // } // // public boolean isFull() { // return addedElementsNumber >= points.length; // } // // public void removeElementsAtLeftOf(int index) { // if (isIndexValid(index)) { // doRemoveElementsAtLeftOf(index); // } else { // throw getInvalidIndexException(index); // } // } // // private void doRemoveElementsAtLeftOf(int index) { // for (int i = 0; i <= getLastElementIndex()-index; i++) { // int sourceIndex = index + i; // shiftPoint(i, sourceIndex); // } // addedElementsNumber -= index; // } // // private void shiftPoint(int destIndex, int sourceIndex) { // if (sourceIndex < points.length) { // TrailPoint source = points[sourceIndex]; // points[destIndex].set(source.getX(), source.getY()); // } // } // // private SlidingWindowIndexException getInvalidIndexException(int index) { // return new SlidingWindowIndexException(String.format("Invalid index '%d' (max index %d)", index, getMaxIndex())); // } // }
import com.orange.dgil.trail.TestTools; import com.orange.dgil.trail.core.common.TrailPoint; import com.orange.dgil.trail.core.vecto.SlidingWindow; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito;
/** * Trail drawing library * Copyright (C) 2014 Orange * Authors: christophe.maldivi@orange.com, eric.petit@orange.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.orange.dgil.trail.core.vecto.linearwindowfilter; public class LinearWindowFilterComputeNewPointTest { private LinearWindowFilter filter; @Before public void setUp() { filter = Mockito.mock(LinearWindowFilter.class); } @Test public void shouldComputeNewPointWithOnePoint() throws IllegalAccessException { // given LinearWindowFilterListener linearWindowFilterListener = Mockito.mock(LinearWindowFilterListener.class);
// Path: src/main/java/com/orange/dgil/trail/core/common/TrailPoint.java // @Getter // @NoArgsConstructor // public class TrailPoint { // private int x = -1; // private int y = -1; // // public TrailPoint(int x, int y) { // set(x, y); // } // // public void set(int x, int y) { // this.x = x; // this.y = y; // } // // public boolean isSameAs(TrailPoint point) { // return x == point.x && y == point.y; // } // // public double getDistanceTo(TrailPoint point) { // int dx = x - point.getX(); // int dy = y - point.getY(); // return Math.sqrt(dx * dx + dy * dy); // } // // public void deepCopy(TrailPoint point) { // x = point.x; // y = point.y; // } // } // // Path: src/main/java/com/orange/dgil/trail/core/vecto/SlidingWindow.java // public class SlidingWindow { // // private TrailPoint[] points; // // @Getter // private int addedElementsNumber; // // public SlidingWindow(int windowSize) { // setWindowSize(windowSize); // } // // public void setWindowSize(int windowSize) { // points = new TrailPoint[windowSize]; // allocatePoints(); // } // // public int getWindowSize() { // return points.length; // } // // private void allocatePoints() { // for (int i = 0; i < points.length; i++) { // points[i] = new TrailPoint(); // } // } // // public void reset() { // addedElementsNumber = 0; // } // // public void add(int x, int y) { // if (isFull()) { // slidePointsToTheLeft(); // } // doAdd(x, y); // } // // public void add(TrailPoint point) { // add(point.getX(), point.getY()); // } // // public int getX(int index) { // if (isIndexValid(index)) { // return points[index].getX(); // } else { // throw new SlidingWindowIndexException(String.format("Invalid index '%d' (max index %d)", index, getMaxIndex())); // } // } // // public int getY(int index) { // if (isIndexValid(index)) { // return points[index].getY(); // } else { // throw getInvalidIndexException(index); // } // } // // boolean isIndexValid(int index) { // return index >= 0 && index <= getMaxIndex(); // } // // int getMaxIndex() { // return Math.min(addedElementsNumber, points.length) - 1; // } // // void slidePointsToTheLeft() { // TrailPoint p0 = points[0]; // for (int i = 0; i < points.length-1; i++) { // points[i] = points[i+1]; // } // points[points.length-1] = p0; // } // // void doAdd(int x, int y) { // points[getInsertIndex()].set(x, y); // addedElementsNumber++; // } // // public TrailPoint getElementAt(int index) { // if (isIndexValid(index)) { // return points[index]; // } else { // throw getInvalidIndexException(index); // } // } // // public TrailPoint getLastElement() { // return getElementAt(getLastElementIndex()); // } // // public boolean isSameAsLast(TrailPoint p) { // if (addedElementsNumber == 0) { // return false; // } else { // return p.isSameAs(points[getLastElementIndex()]); // } // } // // int getInsertIndex() { // return Math.min(addedElementsNumber, points.length - 1); // } // // public int getLastElementIndex() { // return Math.min(addedElementsNumber - 1, points.length - 1); // } // // public boolean isFull() { // return addedElementsNumber >= points.length; // } // // public void removeElementsAtLeftOf(int index) { // if (isIndexValid(index)) { // doRemoveElementsAtLeftOf(index); // } else { // throw getInvalidIndexException(index); // } // } // // private void doRemoveElementsAtLeftOf(int index) { // for (int i = 0; i <= getLastElementIndex()-index; i++) { // int sourceIndex = index + i; // shiftPoint(i, sourceIndex); // } // addedElementsNumber -= index; // } // // private void shiftPoint(int destIndex, int sourceIndex) { // if (sourceIndex < points.length) { // TrailPoint source = points[sourceIndex]; // points[destIndex].set(source.getX(), source.getY()); // } // } // // private SlidingWindowIndexException getInvalidIndexException(int index) { // return new SlidingWindowIndexException(String.format("Invalid index '%d' (max index %d)", index, getMaxIndex())); // } // } // Path: src/test/java/com/orange/dgil/trail/core/vecto/linearwindowfilter/LinearWindowFilterComputeNewPointTest.java import com.orange.dgil.trail.TestTools; import com.orange.dgil.trail.core.common.TrailPoint; import com.orange.dgil.trail.core.vecto.SlidingWindow; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; /** * Trail drawing library * Copyright (C) 2014 Orange * Authors: christophe.maldivi@orange.com, eric.petit@orange.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.orange.dgil.trail.core.vecto.linearwindowfilter; public class LinearWindowFilterComputeNewPointTest { private LinearWindowFilter filter; @Before public void setUp() { filter = Mockito.mock(LinearWindowFilter.class); } @Test public void shouldComputeNewPointWithOnePoint() throws IllegalAccessException { // given LinearWindowFilterListener linearWindowFilterListener = Mockito.mock(LinearWindowFilterListener.class);
SlidingWindow slidingWindow = Mockito.mock(SlidingWindow.class);
Orange-OpenSource/android-trail-drawing
src/main/java/com/orange/dgil/trail/core/vecto/vecto/RawVectoFilter.java
// Path: src/main/java/com/orange/dgil/trail/core/common/TrailPoint.java // @Getter // @NoArgsConstructor // public class TrailPoint { // private int x = -1; // private int y = -1; // // public TrailPoint(int x, int y) { // set(x, y); // } // // public void set(int x, int y) { // this.x = x; // this.y = y; // } // // public boolean isSameAs(TrailPoint point) { // return x == point.x && y == point.y; // } // // public double getDistanceTo(TrailPoint point) { // int dx = x - point.getX(); // int dy = y - point.getY(); // return Math.sqrt(dx * dx + dy * dy); // } // // public void deepCopy(TrailPoint point) { // x = point.x; // y = point.y; // } // } // // Path: src/main/java/com/orange/dgil/trail/core/vecto/SlidingWindow.java // public class SlidingWindow { // // private TrailPoint[] points; // // @Getter // private int addedElementsNumber; // // public SlidingWindow(int windowSize) { // setWindowSize(windowSize); // } // // public void setWindowSize(int windowSize) { // points = new TrailPoint[windowSize]; // allocatePoints(); // } // // public int getWindowSize() { // return points.length; // } // // private void allocatePoints() { // for (int i = 0; i < points.length; i++) { // points[i] = new TrailPoint(); // } // } // // public void reset() { // addedElementsNumber = 0; // } // // public void add(int x, int y) { // if (isFull()) { // slidePointsToTheLeft(); // } // doAdd(x, y); // } // // public void add(TrailPoint point) { // add(point.getX(), point.getY()); // } // // public int getX(int index) { // if (isIndexValid(index)) { // return points[index].getX(); // } else { // throw new SlidingWindowIndexException(String.format("Invalid index '%d' (max index %d)", index, getMaxIndex())); // } // } // // public int getY(int index) { // if (isIndexValid(index)) { // return points[index].getY(); // } else { // throw getInvalidIndexException(index); // } // } // // boolean isIndexValid(int index) { // return index >= 0 && index <= getMaxIndex(); // } // // int getMaxIndex() { // return Math.min(addedElementsNumber, points.length) - 1; // } // // void slidePointsToTheLeft() { // TrailPoint p0 = points[0]; // for (int i = 0; i < points.length-1; i++) { // points[i] = points[i+1]; // } // points[points.length-1] = p0; // } // // void doAdd(int x, int y) { // points[getInsertIndex()].set(x, y); // addedElementsNumber++; // } // // public TrailPoint getElementAt(int index) { // if (isIndexValid(index)) { // return points[index]; // } else { // throw getInvalidIndexException(index); // } // } // // public TrailPoint getLastElement() { // return getElementAt(getLastElementIndex()); // } // // public boolean isSameAsLast(TrailPoint p) { // if (addedElementsNumber == 0) { // return false; // } else { // return p.isSameAs(points[getLastElementIndex()]); // } // } // // int getInsertIndex() { // return Math.min(addedElementsNumber, points.length - 1); // } // // public int getLastElementIndex() { // return Math.min(addedElementsNumber - 1, points.length - 1); // } // // public boolean isFull() { // return addedElementsNumber >= points.length; // } // // public void removeElementsAtLeftOf(int index) { // if (isIndexValid(index)) { // doRemoveElementsAtLeftOf(index); // } else { // throw getInvalidIndexException(index); // } // } // // private void doRemoveElementsAtLeftOf(int index) { // for (int i = 0; i <= getLastElementIndex()-index; i++) { // int sourceIndex = index + i; // shiftPoint(i, sourceIndex); // } // addedElementsNumber -= index; // } // // private void shiftPoint(int destIndex, int sourceIndex) { // if (sourceIndex < points.length) { // TrailPoint source = points[sourceIndex]; // points[destIndex].set(source.getX(), source.getY()); // } // } // // private SlidingWindowIndexException getInvalidIndexException(int index) { // return new SlidingWindowIndexException(String.format("Invalid index '%d' (max index %d)", index, getMaxIndex())); // } // }
import com.orange.dgil.trail.core.common.TrailPoint; import com.orange.dgil.trail.core.vecto.SlidingWindow;
/** * Trail drawing library * Copyright (C) 2014 Orange * Authors: christophe.maldivi@orange.com, eric.petit@orange.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.orange.dgil.trail.core.vecto.vecto; /** * Fine vectorization method based on the height analysis of all possible vectors * of the sliding window. */ public class RawVectoFilter implements OnWindowSizeListener { private final WindowAnalysis windowAnalysis = new WindowAnalysis(this);
// Path: src/main/java/com/orange/dgil/trail/core/common/TrailPoint.java // @Getter // @NoArgsConstructor // public class TrailPoint { // private int x = -1; // private int y = -1; // // public TrailPoint(int x, int y) { // set(x, y); // } // // public void set(int x, int y) { // this.x = x; // this.y = y; // } // // public boolean isSameAs(TrailPoint point) { // return x == point.x && y == point.y; // } // // public double getDistanceTo(TrailPoint point) { // int dx = x - point.getX(); // int dy = y - point.getY(); // return Math.sqrt(dx * dx + dy * dy); // } // // public void deepCopy(TrailPoint point) { // x = point.x; // y = point.y; // } // } // // Path: src/main/java/com/orange/dgil/trail/core/vecto/SlidingWindow.java // public class SlidingWindow { // // private TrailPoint[] points; // // @Getter // private int addedElementsNumber; // // public SlidingWindow(int windowSize) { // setWindowSize(windowSize); // } // // public void setWindowSize(int windowSize) { // points = new TrailPoint[windowSize]; // allocatePoints(); // } // // public int getWindowSize() { // return points.length; // } // // private void allocatePoints() { // for (int i = 0; i < points.length; i++) { // points[i] = new TrailPoint(); // } // } // // public void reset() { // addedElementsNumber = 0; // } // // public void add(int x, int y) { // if (isFull()) { // slidePointsToTheLeft(); // } // doAdd(x, y); // } // // public void add(TrailPoint point) { // add(point.getX(), point.getY()); // } // // public int getX(int index) { // if (isIndexValid(index)) { // return points[index].getX(); // } else { // throw new SlidingWindowIndexException(String.format("Invalid index '%d' (max index %d)", index, getMaxIndex())); // } // } // // public int getY(int index) { // if (isIndexValid(index)) { // return points[index].getY(); // } else { // throw getInvalidIndexException(index); // } // } // // boolean isIndexValid(int index) { // return index >= 0 && index <= getMaxIndex(); // } // // int getMaxIndex() { // return Math.min(addedElementsNumber, points.length) - 1; // } // // void slidePointsToTheLeft() { // TrailPoint p0 = points[0]; // for (int i = 0; i < points.length-1; i++) { // points[i] = points[i+1]; // } // points[points.length-1] = p0; // } // // void doAdd(int x, int y) { // points[getInsertIndex()].set(x, y); // addedElementsNumber++; // } // // public TrailPoint getElementAt(int index) { // if (isIndexValid(index)) { // return points[index]; // } else { // throw getInvalidIndexException(index); // } // } // // public TrailPoint getLastElement() { // return getElementAt(getLastElementIndex()); // } // // public boolean isSameAsLast(TrailPoint p) { // if (addedElementsNumber == 0) { // return false; // } else { // return p.isSameAs(points[getLastElementIndex()]); // } // } // // int getInsertIndex() { // return Math.min(addedElementsNumber, points.length - 1); // } // // public int getLastElementIndex() { // return Math.min(addedElementsNumber - 1, points.length - 1); // } // // public boolean isFull() { // return addedElementsNumber >= points.length; // } // // public void removeElementsAtLeftOf(int index) { // if (isIndexValid(index)) { // doRemoveElementsAtLeftOf(index); // } else { // throw getInvalidIndexException(index); // } // } // // private void doRemoveElementsAtLeftOf(int index) { // for (int i = 0; i <= getLastElementIndex()-index; i++) { // int sourceIndex = index + i; // shiftPoint(i, sourceIndex); // } // addedElementsNumber -= index; // } // // private void shiftPoint(int destIndex, int sourceIndex) { // if (sourceIndex < points.length) { // TrailPoint source = points[sourceIndex]; // points[destIndex].set(source.getX(), source.getY()); // } // } // // private SlidingWindowIndexException getInvalidIndexException(int index) { // return new SlidingWindowIndexException(String.format("Invalid index '%d' (max index %d)", index, getMaxIndex())); // } // } // Path: src/main/java/com/orange/dgil/trail/core/vecto/vecto/RawVectoFilter.java import com.orange.dgil.trail.core.common.TrailPoint; import com.orange.dgil.trail.core.vecto.SlidingWindow; /** * Trail drawing library * Copyright (C) 2014 Orange * Authors: christophe.maldivi@orange.com, eric.petit@orange.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.orange.dgil.trail.core.vecto.vecto; /** * Fine vectorization method based on the height analysis of all possible vectors * of the sliding window. */ public class RawVectoFilter implements OnWindowSizeListener { private final WindowAnalysis windowAnalysis = new WindowAnalysis(this);
private final SlidingWindow slidingWindow = windowAnalysis.getSlidingWindow();
Orange-OpenSource/android-trail-drawing
src/main/java/com/orange/dgil/trail/core/vecto/vecto/RawVectoFilter.java
// Path: src/main/java/com/orange/dgil/trail/core/common/TrailPoint.java // @Getter // @NoArgsConstructor // public class TrailPoint { // private int x = -1; // private int y = -1; // // public TrailPoint(int x, int y) { // set(x, y); // } // // public void set(int x, int y) { // this.x = x; // this.y = y; // } // // public boolean isSameAs(TrailPoint point) { // return x == point.x && y == point.y; // } // // public double getDistanceTo(TrailPoint point) { // int dx = x - point.getX(); // int dy = y - point.getY(); // return Math.sqrt(dx * dx + dy * dy); // } // // public void deepCopy(TrailPoint point) { // x = point.x; // y = point.y; // } // } // // Path: src/main/java/com/orange/dgil/trail/core/vecto/SlidingWindow.java // public class SlidingWindow { // // private TrailPoint[] points; // // @Getter // private int addedElementsNumber; // // public SlidingWindow(int windowSize) { // setWindowSize(windowSize); // } // // public void setWindowSize(int windowSize) { // points = new TrailPoint[windowSize]; // allocatePoints(); // } // // public int getWindowSize() { // return points.length; // } // // private void allocatePoints() { // for (int i = 0; i < points.length; i++) { // points[i] = new TrailPoint(); // } // } // // public void reset() { // addedElementsNumber = 0; // } // // public void add(int x, int y) { // if (isFull()) { // slidePointsToTheLeft(); // } // doAdd(x, y); // } // // public void add(TrailPoint point) { // add(point.getX(), point.getY()); // } // // public int getX(int index) { // if (isIndexValid(index)) { // return points[index].getX(); // } else { // throw new SlidingWindowIndexException(String.format("Invalid index '%d' (max index %d)", index, getMaxIndex())); // } // } // // public int getY(int index) { // if (isIndexValid(index)) { // return points[index].getY(); // } else { // throw getInvalidIndexException(index); // } // } // // boolean isIndexValid(int index) { // return index >= 0 && index <= getMaxIndex(); // } // // int getMaxIndex() { // return Math.min(addedElementsNumber, points.length) - 1; // } // // void slidePointsToTheLeft() { // TrailPoint p0 = points[0]; // for (int i = 0; i < points.length-1; i++) { // points[i] = points[i+1]; // } // points[points.length-1] = p0; // } // // void doAdd(int x, int y) { // points[getInsertIndex()].set(x, y); // addedElementsNumber++; // } // // public TrailPoint getElementAt(int index) { // if (isIndexValid(index)) { // return points[index]; // } else { // throw getInvalidIndexException(index); // } // } // // public TrailPoint getLastElement() { // return getElementAt(getLastElementIndex()); // } // // public boolean isSameAsLast(TrailPoint p) { // if (addedElementsNumber == 0) { // return false; // } else { // return p.isSameAs(points[getLastElementIndex()]); // } // } // // int getInsertIndex() { // return Math.min(addedElementsNumber, points.length - 1); // } // // public int getLastElementIndex() { // return Math.min(addedElementsNumber - 1, points.length - 1); // } // // public boolean isFull() { // return addedElementsNumber >= points.length; // } // // public void removeElementsAtLeftOf(int index) { // if (isIndexValid(index)) { // doRemoveElementsAtLeftOf(index); // } else { // throw getInvalidIndexException(index); // } // } // // private void doRemoveElementsAtLeftOf(int index) { // for (int i = 0; i <= getLastElementIndex()-index; i++) { // int sourceIndex = index + i; // shiftPoint(i, sourceIndex); // } // addedElementsNumber -= index; // } // // private void shiftPoint(int destIndex, int sourceIndex) { // if (sourceIndex < points.length) { // TrailPoint source = points[sourceIndex]; // points[destIndex].set(source.getX(), source.getY()); // } // } // // private SlidingWindowIndexException getInvalidIndexException(int index) { // return new SlidingWindowIndexException(String.format("Invalid index '%d' (max index %d)", index, getMaxIndex())); // } // }
import com.orange.dgil.trail.core.common.TrailPoint; import com.orange.dgil.trail.core.vecto.SlidingWindow;
/** * Trail drawing library * Copyright (C) 2014 Orange * Authors: christophe.maldivi@orange.com, eric.petit@orange.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.orange.dgil.trail.core.vecto.vecto; /** * Fine vectorization method based on the height analysis of all possible vectors * of the sliding window. */ public class RawVectoFilter implements OnWindowSizeListener { private final WindowAnalysis windowAnalysis = new WindowAnalysis(this); private final SlidingWindow slidingWindow = windowAnalysis.getSlidingWindow(); private final VectoFilterListener vectoFilterListener;
// Path: src/main/java/com/orange/dgil/trail/core/common/TrailPoint.java // @Getter // @NoArgsConstructor // public class TrailPoint { // private int x = -1; // private int y = -1; // // public TrailPoint(int x, int y) { // set(x, y); // } // // public void set(int x, int y) { // this.x = x; // this.y = y; // } // // public boolean isSameAs(TrailPoint point) { // return x == point.x && y == point.y; // } // // public double getDistanceTo(TrailPoint point) { // int dx = x - point.getX(); // int dy = y - point.getY(); // return Math.sqrt(dx * dx + dy * dy); // } // // public void deepCopy(TrailPoint point) { // x = point.x; // y = point.y; // } // } // // Path: src/main/java/com/orange/dgil/trail/core/vecto/SlidingWindow.java // public class SlidingWindow { // // private TrailPoint[] points; // // @Getter // private int addedElementsNumber; // // public SlidingWindow(int windowSize) { // setWindowSize(windowSize); // } // // public void setWindowSize(int windowSize) { // points = new TrailPoint[windowSize]; // allocatePoints(); // } // // public int getWindowSize() { // return points.length; // } // // private void allocatePoints() { // for (int i = 0; i < points.length; i++) { // points[i] = new TrailPoint(); // } // } // // public void reset() { // addedElementsNumber = 0; // } // // public void add(int x, int y) { // if (isFull()) { // slidePointsToTheLeft(); // } // doAdd(x, y); // } // // public void add(TrailPoint point) { // add(point.getX(), point.getY()); // } // // public int getX(int index) { // if (isIndexValid(index)) { // return points[index].getX(); // } else { // throw new SlidingWindowIndexException(String.format("Invalid index '%d' (max index %d)", index, getMaxIndex())); // } // } // // public int getY(int index) { // if (isIndexValid(index)) { // return points[index].getY(); // } else { // throw getInvalidIndexException(index); // } // } // // boolean isIndexValid(int index) { // return index >= 0 && index <= getMaxIndex(); // } // // int getMaxIndex() { // return Math.min(addedElementsNumber, points.length) - 1; // } // // void slidePointsToTheLeft() { // TrailPoint p0 = points[0]; // for (int i = 0; i < points.length-1; i++) { // points[i] = points[i+1]; // } // points[points.length-1] = p0; // } // // void doAdd(int x, int y) { // points[getInsertIndex()].set(x, y); // addedElementsNumber++; // } // // public TrailPoint getElementAt(int index) { // if (isIndexValid(index)) { // return points[index]; // } else { // throw getInvalidIndexException(index); // } // } // // public TrailPoint getLastElement() { // return getElementAt(getLastElementIndex()); // } // // public boolean isSameAsLast(TrailPoint p) { // if (addedElementsNumber == 0) { // return false; // } else { // return p.isSameAs(points[getLastElementIndex()]); // } // } // // int getInsertIndex() { // return Math.min(addedElementsNumber, points.length - 1); // } // // public int getLastElementIndex() { // return Math.min(addedElementsNumber - 1, points.length - 1); // } // // public boolean isFull() { // return addedElementsNumber >= points.length; // } // // public void removeElementsAtLeftOf(int index) { // if (isIndexValid(index)) { // doRemoveElementsAtLeftOf(index); // } else { // throw getInvalidIndexException(index); // } // } // // private void doRemoveElementsAtLeftOf(int index) { // for (int i = 0; i <= getLastElementIndex()-index; i++) { // int sourceIndex = index + i; // shiftPoint(i, sourceIndex); // } // addedElementsNumber -= index; // } // // private void shiftPoint(int destIndex, int sourceIndex) { // if (sourceIndex < points.length) { // TrailPoint source = points[sourceIndex]; // points[destIndex].set(source.getX(), source.getY()); // } // } // // private SlidingWindowIndexException getInvalidIndexException(int index) { // return new SlidingWindowIndexException(String.format("Invalid index '%d' (max index %d)", index, getMaxIndex())); // } // } // Path: src/main/java/com/orange/dgil/trail/core/vecto/vecto/RawVectoFilter.java import com.orange.dgil.trail.core.common.TrailPoint; import com.orange.dgil.trail.core.vecto.SlidingWindow; /** * Trail drawing library * Copyright (C) 2014 Orange * Authors: christophe.maldivi@orange.com, eric.petit@orange.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.orange.dgil.trail.core.vecto.vecto; /** * Fine vectorization method based on the height analysis of all possible vectors * of the sliding window. */ public class RawVectoFilter implements OnWindowSizeListener { private final WindowAnalysis windowAnalysis = new WindowAnalysis(this); private final SlidingWindow slidingWindow = windowAnalysis.getSlidingWindow(); private final VectoFilterListener vectoFilterListener;
private TrailPoint[] pointsForListener = new TrailPoint[slidingWindow.getWindowSize()];
Orange-OpenSource/android-trail-drawing
src/test/java/com/orange/dgil/trail/core/vecto/SlidingWindowSlidePointsToTheLeftTest.java
// Path: src/main/java/com/orange/dgil/trail/core/common/TrailPoint.java // @Getter // @NoArgsConstructor // public class TrailPoint { // private int x = -1; // private int y = -1; // // public TrailPoint(int x, int y) { // set(x, y); // } // // public void set(int x, int y) { // this.x = x; // this.y = y; // } // // public boolean isSameAs(TrailPoint point) { // return x == point.x && y == point.y; // } // // public double getDistanceTo(TrailPoint point) { // int dx = x - point.getX(); // int dy = y - point.getY(); // return Math.sqrt(dx * dx + dy * dy); // } // // public void deepCopy(TrailPoint point) { // x = point.x; // y = point.y; // } // }
import com.orange.dgil.trail.TestTools; import com.orange.dgil.trail.core.common.TrailPoint; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito;
/** * Trail drawing library * Copyright (C) 2014 Orange * Authors: christophe.maldivi@orange.com, eric.petit@orange.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.orange.dgil.trail.core.vecto; public class SlidingWindowSlidePointsToTheLeftTest { private SlidingWindow slidingWindow; @Before public void setUp() { slidingWindow = Mockito.mock(SlidingWindow.class); } @Test public void shouldSlidePointsToTheLeft() throws IllegalAccessException { // given
// Path: src/main/java/com/orange/dgil/trail/core/common/TrailPoint.java // @Getter // @NoArgsConstructor // public class TrailPoint { // private int x = -1; // private int y = -1; // // public TrailPoint(int x, int y) { // set(x, y); // } // // public void set(int x, int y) { // this.x = x; // this.y = y; // } // // public boolean isSameAs(TrailPoint point) { // return x == point.x && y == point.y; // } // // public double getDistanceTo(TrailPoint point) { // int dx = x - point.getX(); // int dy = y - point.getY(); // return Math.sqrt(dx * dx + dy * dy); // } // // public void deepCopy(TrailPoint point) { // x = point.x; // y = point.y; // } // } // Path: src/test/java/com/orange/dgil/trail/core/vecto/SlidingWindowSlidePointsToTheLeftTest.java import com.orange.dgil.trail.TestTools; import com.orange.dgil.trail.core.common.TrailPoint; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; /** * Trail drawing library * Copyright (C) 2014 Orange * Authors: christophe.maldivi@orange.com, eric.petit@orange.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.orange.dgil.trail.core.vecto; public class SlidingWindowSlidePointsToTheLeftTest { private SlidingWindow slidingWindow; @Before public void setUp() { slidingWindow = Mockito.mock(SlidingWindow.class); } @Test public void shouldSlidePointsToTheLeft() throws IllegalAccessException { // given
TrailPoint[] points = new TrailPoint[3];
Orange-OpenSource/android-trail-drawing
src/test/java/com/orange/dgil/trail/core/vecto/SlidingWindowDoAddTest.java
// Path: src/main/java/com/orange/dgil/trail/core/common/TrailPoint.java // @Getter // @NoArgsConstructor // public class TrailPoint { // private int x = -1; // private int y = -1; // // public TrailPoint(int x, int y) { // set(x, y); // } // // public void set(int x, int y) { // this.x = x; // this.y = y; // } // // public boolean isSameAs(TrailPoint point) { // return x == point.x && y == point.y; // } // // public double getDistanceTo(TrailPoint point) { // int dx = x - point.getX(); // int dy = y - point.getY(); // return Math.sqrt(dx * dx + dy * dy); // } // // public void deepCopy(TrailPoint point) { // x = point.x; // y = point.y; // } // }
import com.orange.dgil.trail.TestTools; import com.orange.dgil.trail.core.common.TrailPoint; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito;
/** * Trail drawing library * Copyright (C) 2014 Orange * Authors: christophe.maldivi@orange.com, eric.petit@orange.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.orange.dgil.trail.core.vecto; public class SlidingWindowDoAddTest { private SlidingWindow slidingWindow; @Before public void setUp() { slidingWindow = Mockito.mock(SlidingWindow.class); } @Test public void shouldDoAdd() throws IllegalAccessException { // given
// Path: src/main/java/com/orange/dgil/trail/core/common/TrailPoint.java // @Getter // @NoArgsConstructor // public class TrailPoint { // private int x = -1; // private int y = -1; // // public TrailPoint(int x, int y) { // set(x, y); // } // // public void set(int x, int y) { // this.x = x; // this.y = y; // } // // public boolean isSameAs(TrailPoint point) { // return x == point.x && y == point.y; // } // // public double getDistanceTo(TrailPoint point) { // int dx = x - point.getX(); // int dy = y - point.getY(); // return Math.sqrt(dx * dx + dy * dy); // } // // public void deepCopy(TrailPoint point) { // x = point.x; // y = point.y; // } // } // Path: src/test/java/com/orange/dgil/trail/core/vecto/SlidingWindowDoAddTest.java import com.orange.dgil.trail.TestTools; import com.orange.dgil.trail.core.common.TrailPoint; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; /** * Trail drawing library * Copyright (C) 2014 Orange * Authors: christophe.maldivi@orange.com, eric.petit@orange.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.orange.dgil.trail.core.vecto; public class SlidingWindowDoAddTest { private SlidingWindow slidingWindow; @Before public void setUp() { slidingWindow = Mockito.mock(SlidingWindow.class); } @Test public void shouldDoAdd() throws IllegalAccessException { // given
TrailPoint point = new TrailPoint();
Orange-OpenSource/android-trail-drawing
src/main/java/com/orange/dgil/trail/android/animation/AnimParameters.java
// Path: src/main/java/com/orange/dgil/trail/android/DefaultDrawerConf.java // public class DefaultDrawerConf { // public static final int TRAIL_COLOR = Color.rgb(0xFF, 0x99, 0); // public static final int TRAIL_WIDTH_UM = 2500; // // public static final float SHADOW_RADIUS_FACTOR = 0.5f; // public static final float SHADOW_OFFSET_FACTOR = 0.33f; // public static final int SHADOW_COLOR = Color.BLACK; // // public static final int ANIM_PRE_ANIM_DELAY_MS = 100; // public static final int ANIM_DURATION_MS = 400; // // public static final int QUILL_WIDTH_UM = 3000; // public static final int QUILL_HEIGHT_UM = 1000; // public static final int QUILL_ANGLE_DEG = 45; // }
import lombok.Setter; import android.graphics.Color; import com.orange.dgil.trail.android.DefaultDrawerConf; import lombok.Getter;
/** * Trail drawing library * Copyright (C) 2014 Orange * Authors: christophe.maldivi@orange.com, eric.petit@orange.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.orange.dgil.trail.android.animation; @Getter public class AnimParameters {
// Path: src/main/java/com/orange/dgil/trail/android/DefaultDrawerConf.java // public class DefaultDrawerConf { // public static final int TRAIL_COLOR = Color.rgb(0xFF, 0x99, 0); // public static final int TRAIL_WIDTH_UM = 2500; // // public static final float SHADOW_RADIUS_FACTOR = 0.5f; // public static final float SHADOW_OFFSET_FACTOR = 0.33f; // public static final int SHADOW_COLOR = Color.BLACK; // // public static final int ANIM_PRE_ANIM_DELAY_MS = 100; // public static final int ANIM_DURATION_MS = 400; // // public static final int QUILL_WIDTH_UM = 3000; // public static final int QUILL_HEIGHT_UM = 1000; // public static final int QUILL_ANGLE_DEG = 45; // } // Path: src/main/java/com/orange/dgil/trail/android/animation/AnimParameters.java import lombok.Setter; import android.graphics.Color; import com.orange.dgil.trail.android.DefaultDrawerConf; import lombok.Getter; /** * Trail drawing library * Copyright (C) 2014 Orange * Authors: christophe.maldivi@orange.com, eric.petit@orange.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.orange.dgil.trail.android.animation; @Getter public class AnimParameters {
private int preAnimDelay = DefaultDrawerConf.ANIM_PRE_ANIM_DELAY_MS;
Orange-OpenSource/android-trail-drawing
src/main/java/com/orange/dgil/trail/android/drawingtool/quillpen/BitmapDrawer.java
// Path: src/main/java/com/orange/dgil/trail/android/drawingtool/TrailOptions.java // @Getter // public class TrailOptions { // @Getter(AccessLevel.NONE) // private DrawingTools drawingTools; // @Getter(AccessLevel.NONE) // private AndroidMetrics metrics; // // @Setter // private int color = DefaultDrawerConf.TRAIL_COLOR; // @Setter // private int shadowColor; // // private QuillParameters quillParameters; // // private boolean shadowEnabled; // private int shadowOffsetPixels; // private int widthPixels; // // public TrailOptions(AndroidMetrics metrics, DrawingTools drawingTools) { // init(metrics, drawingTools); // } // // private void init(AndroidMetrics metrics, DrawingTools drawingTools) { // this.metrics = metrics; // this.drawingTools = drawingTools; // quillParameters = new QuillParameters(metrics); // setTrailWidthMicrometers(DefaultDrawerConf.TRAIL_WIDTH_UM); // } // // public void setTrailWidthMicrometers(int micrometers) { // widthPixels = metrics.micrometersToPixels(micrometers); // shadowOffsetPixels = (int) (widthPixels * DefaultDrawerConf.SHADOW_OFFSET_FACTOR); // } // // public boolean isShadowAvailable() { // return android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH; // } // // public void setShadowEnabled(boolean shadowEnabled) { // this.shadowEnabled = shadowEnabled && isShadowAvailable(); // } // // public void selectMarkerPen() { // drawingTools.selectMarkerPen(); // } // // public void selectQuillPen() { // drawingTools.selectQuillPen(); // } // }
import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.RectF; import com.orange.dgil.trail.android.drawingtool.TrailOptions; import lombok.RequiredArgsConstructor;
/** * Trail drawing library * Copyright (C) 2014 Orange * Authors: christophe.maldivi@orange.com, eric.petit@orange.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.orange.dgil.trail.android.drawingtool.quillpen; @RequiredArgsConstructor class BitmapDrawer { private final Paint paint = new Paint(); private final RectF rectF = new RectF();
// Path: src/main/java/com/orange/dgil/trail/android/drawingtool/TrailOptions.java // @Getter // public class TrailOptions { // @Getter(AccessLevel.NONE) // private DrawingTools drawingTools; // @Getter(AccessLevel.NONE) // private AndroidMetrics metrics; // // @Setter // private int color = DefaultDrawerConf.TRAIL_COLOR; // @Setter // private int shadowColor; // // private QuillParameters quillParameters; // // private boolean shadowEnabled; // private int shadowOffsetPixels; // private int widthPixels; // // public TrailOptions(AndroidMetrics metrics, DrawingTools drawingTools) { // init(metrics, drawingTools); // } // // private void init(AndroidMetrics metrics, DrawingTools drawingTools) { // this.metrics = metrics; // this.drawingTools = drawingTools; // quillParameters = new QuillParameters(metrics); // setTrailWidthMicrometers(DefaultDrawerConf.TRAIL_WIDTH_UM); // } // // public void setTrailWidthMicrometers(int micrometers) { // widthPixels = metrics.micrometersToPixels(micrometers); // shadowOffsetPixels = (int) (widthPixels * DefaultDrawerConf.SHADOW_OFFSET_FACTOR); // } // // public boolean isShadowAvailable() { // return android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH; // } // // public void setShadowEnabled(boolean shadowEnabled) { // this.shadowEnabled = shadowEnabled && isShadowAvailable(); // } // // public void selectMarkerPen() { // drawingTools.selectMarkerPen(); // } // // public void selectQuillPen() { // drawingTools.selectQuillPen(); // } // } // Path: src/main/java/com/orange/dgil/trail/android/drawingtool/quillpen/BitmapDrawer.java import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.RectF; import com.orange.dgil.trail.android.drawingtool.TrailOptions; import lombok.RequiredArgsConstructor; /** * Trail drawing library * Copyright (C) 2014 Orange * Authors: christophe.maldivi@orange.com, eric.petit@orange.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.orange.dgil.trail.android.drawingtool.quillpen; @RequiredArgsConstructor class BitmapDrawer { private final Paint paint = new Paint(); private final RectF rectF = new RectF();
private final TrailOptions trailOptions;
Orange-OpenSource/android-trail-drawing
src/test/java/com/orange/dgil/trail/core/vecto/SlidingWindowGetElementAtTest.java
// Path: src/main/java/com/orange/dgil/trail/core/common/TrailPoint.java // @Getter // @NoArgsConstructor // public class TrailPoint { // private int x = -1; // private int y = -1; // // public TrailPoint(int x, int y) { // set(x, y); // } // // public void set(int x, int y) { // this.x = x; // this.y = y; // } // // public boolean isSameAs(TrailPoint point) { // return x == point.x && y == point.y; // } // // public double getDistanceTo(TrailPoint point) { // int dx = x - point.getX(); // int dy = y - point.getY(); // return Math.sqrt(dx * dx + dy * dy); // } // // public void deepCopy(TrailPoint point) { // x = point.x; // y = point.y; // } // }
import com.orange.dgil.trail.TestTools; import com.orange.dgil.trail.core.common.TrailPoint; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito;
/** * Trail drawing library * Copyright (C) 2014 Orange * Authors: christophe.maldivi@orange.com, eric.petit@orange.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.orange.dgil.trail.core.vecto; public class SlidingWindowGetElementAtTest { private SlidingWindow slidingWindow; @Before public void setUp() { slidingWindow = Mockito.mock(SlidingWindow.class); } @Test public void shouldGetElementAt() throws IllegalAccessException { // given
// Path: src/main/java/com/orange/dgil/trail/core/common/TrailPoint.java // @Getter // @NoArgsConstructor // public class TrailPoint { // private int x = -1; // private int y = -1; // // public TrailPoint(int x, int y) { // set(x, y); // } // // public void set(int x, int y) { // this.x = x; // this.y = y; // } // // public boolean isSameAs(TrailPoint point) { // return x == point.x && y == point.y; // } // // public double getDistanceTo(TrailPoint point) { // int dx = x - point.getX(); // int dy = y - point.getY(); // return Math.sqrt(dx * dx + dy * dy); // } // // public void deepCopy(TrailPoint point) { // x = point.x; // y = point.y; // } // } // Path: src/test/java/com/orange/dgil/trail/core/vecto/SlidingWindowGetElementAtTest.java import com.orange.dgil.trail.TestTools; import com.orange.dgil.trail.core.common.TrailPoint; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; /** * Trail drawing library * Copyright (C) 2014 Orange * Authors: christophe.maldivi@orange.com, eric.petit@orange.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.orange.dgil.trail.core.vecto; public class SlidingWindowGetElementAtTest { private SlidingWindow slidingWindow; @Before public void setUp() { slidingWindow = Mockito.mock(SlidingWindow.class); } @Test public void shouldGetElementAt() throws IllegalAccessException { // given
TrailPoint[] points = new TrailPoint[3];
Orange-OpenSource/android-trail-drawing
src/test/java/com/orange/dgil/trail/core/vecto/SlidingWindowAddTest.java
// Path: src/main/java/com/orange/dgil/trail/core/common/TrailPoint.java // @Getter // @NoArgsConstructor // public class TrailPoint { // private int x = -1; // private int y = -1; // // public TrailPoint(int x, int y) { // set(x, y); // } // // public void set(int x, int y) { // this.x = x; // this.y = y; // } // // public boolean isSameAs(TrailPoint point) { // return x == point.x && y == point.y; // } // // public double getDistanceTo(TrailPoint point) { // int dx = x - point.getX(); // int dy = y - point.getY(); // return Math.sqrt(dx * dx + dy * dy); // } // // public void deepCopy(TrailPoint point) { // x = point.x; // y = point.y; // } // }
import com.orange.dgil.trail.core.common.TrailPoint; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito;
/** * Trail drawing library * Copyright (C) 2014 Orange * Authors: christophe.maldivi@orange.com, eric.petit@orange.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.orange.dgil.trail.core.vecto; public class SlidingWindowAddTest { private SlidingWindow slidingWindow; @Before public void setUp() { slidingWindow = Mockito.mock(SlidingWindow.class); } @Test public void shouldAddWhenWindowFull() throws IllegalAccessException { // given boolean full = true;
// Path: src/main/java/com/orange/dgil/trail/core/common/TrailPoint.java // @Getter // @NoArgsConstructor // public class TrailPoint { // private int x = -1; // private int y = -1; // // public TrailPoint(int x, int y) { // set(x, y); // } // // public void set(int x, int y) { // this.x = x; // this.y = y; // } // // public boolean isSameAs(TrailPoint point) { // return x == point.x && y == point.y; // } // // public double getDistanceTo(TrailPoint point) { // int dx = x - point.getX(); // int dy = y - point.getY(); // return Math.sqrt(dx * dx + dy * dy); // } // // public void deepCopy(TrailPoint point) { // x = point.x; // y = point.y; // } // } // Path: src/test/java/com/orange/dgil/trail/core/vecto/SlidingWindowAddTest.java import com.orange.dgil.trail.core.common.TrailPoint; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; /** * Trail drawing library * Copyright (C) 2014 Orange * Authors: christophe.maldivi@orange.com, eric.petit@orange.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.orange.dgil.trail.core.vecto; public class SlidingWindowAddTest { private SlidingWindow slidingWindow; @Before public void setUp() { slidingWindow = Mockito.mock(SlidingWindow.class); } @Test public void shouldAddWhenWindowFull() throws IllegalAccessException { // given boolean full = true;
TrailPoint point = new TrailPoint(12, 34);
Orange-OpenSource/android-trail-drawing
src/test/java/com/orange/dgil/trail/core/vecto/linearwindowfilter/LinearWindowFilterGetLastPointTest.java
// Path: src/main/java/com/orange/dgil/trail/core/common/TrailPoint.java // @Getter // @NoArgsConstructor // public class TrailPoint { // private int x = -1; // private int y = -1; // // public TrailPoint(int x, int y) { // set(x, y); // } // // public void set(int x, int y) { // this.x = x; // this.y = y; // } // // public boolean isSameAs(TrailPoint point) { // return x == point.x && y == point.y; // } // // public double getDistanceTo(TrailPoint point) { // int dx = x - point.getX(); // int dy = y - point.getY(); // return Math.sqrt(dx * dx + dy * dy); // } // // public void deepCopy(TrailPoint point) { // x = point.x; // y = point.y; // } // } // // Path: src/main/java/com/orange/dgil/trail/core/vecto/SlidingWindow.java // public class SlidingWindow { // // private TrailPoint[] points; // // @Getter // private int addedElementsNumber; // // public SlidingWindow(int windowSize) { // setWindowSize(windowSize); // } // // public void setWindowSize(int windowSize) { // points = new TrailPoint[windowSize]; // allocatePoints(); // } // // public int getWindowSize() { // return points.length; // } // // private void allocatePoints() { // for (int i = 0; i < points.length; i++) { // points[i] = new TrailPoint(); // } // } // // public void reset() { // addedElementsNumber = 0; // } // // public void add(int x, int y) { // if (isFull()) { // slidePointsToTheLeft(); // } // doAdd(x, y); // } // // public void add(TrailPoint point) { // add(point.getX(), point.getY()); // } // // public int getX(int index) { // if (isIndexValid(index)) { // return points[index].getX(); // } else { // throw new SlidingWindowIndexException(String.format("Invalid index '%d' (max index %d)", index, getMaxIndex())); // } // } // // public int getY(int index) { // if (isIndexValid(index)) { // return points[index].getY(); // } else { // throw getInvalidIndexException(index); // } // } // // boolean isIndexValid(int index) { // return index >= 0 && index <= getMaxIndex(); // } // // int getMaxIndex() { // return Math.min(addedElementsNumber, points.length) - 1; // } // // void slidePointsToTheLeft() { // TrailPoint p0 = points[0]; // for (int i = 0; i < points.length-1; i++) { // points[i] = points[i+1]; // } // points[points.length-1] = p0; // } // // void doAdd(int x, int y) { // points[getInsertIndex()].set(x, y); // addedElementsNumber++; // } // // public TrailPoint getElementAt(int index) { // if (isIndexValid(index)) { // return points[index]; // } else { // throw getInvalidIndexException(index); // } // } // // public TrailPoint getLastElement() { // return getElementAt(getLastElementIndex()); // } // // public boolean isSameAsLast(TrailPoint p) { // if (addedElementsNumber == 0) { // return false; // } else { // return p.isSameAs(points[getLastElementIndex()]); // } // } // // int getInsertIndex() { // return Math.min(addedElementsNumber, points.length - 1); // } // // public int getLastElementIndex() { // return Math.min(addedElementsNumber - 1, points.length - 1); // } // // public boolean isFull() { // return addedElementsNumber >= points.length; // } // // public void removeElementsAtLeftOf(int index) { // if (isIndexValid(index)) { // doRemoveElementsAtLeftOf(index); // } else { // throw getInvalidIndexException(index); // } // } // // private void doRemoveElementsAtLeftOf(int index) { // for (int i = 0; i <= getLastElementIndex()-index; i++) { // int sourceIndex = index + i; // shiftPoint(i, sourceIndex); // } // addedElementsNumber -= index; // } // // private void shiftPoint(int destIndex, int sourceIndex) { // if (sourceIndex < points.length) { // TrailPoint source = points[sourceIndex]; // points[destIndex].set(source.getX(), source.getY()); // } // } // // private SlidingWindowIndexException getInvalidIndexException(int index) { // return new SlidingWindowIndexException(String.format("Invalid index '%d' (max index %d)", index, getMaxIndex())); // } // }
import com.orange.dgil.trail.TestTools; import com.orange.dgil.trail.core.common.TrailPoint; import com.orange.dgil.trail.core.vecto.SlidingWindow; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito;
/** * Trail drawing library * Copyright (C) 2014 Orange * Authors: christophe.maldivi@orange.com, eric.petit@orange.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.orange.dgil.trail.core.vecto.linearwindowfilter; public class LinearWindowFilterGetLastPointTest { private LinearWindowFilter filter; @Before public void setUp() { filter = Mockito.mock(LinearWindowFilter.class); } @Test public void shouldGetNewPointWhenAvailable() throws IllegalAccessException { // given
// Path: src/main/java/com/orange/dgil/trail/core/common/TrailPoint.java // @Getter // @NoArgsConstructor // public class TrailPoint { // private int x = -1; // private int y = -1; // // public TrailPoint(int x, int y) { // set(x, y); // } // // public void set(int x, int y) { // this.x = x; // this.y = y; // } // // public boolean isSameAs(TrailPoint point) { // return x == point.x && y == point.y; // } // // public double getDistanceTo(TrailPoint point) { // int dx = x - point.getX(); // int dy = y - point.getY(); // return Math.sqrt(dx * dx + dy * dy); // } // // public void deepCopy(TrailPoint point) { // x = point.x; // y = point.y; // } // } // // Path: src/main/java/com/orange/dgil/trail/core/vecto/SlidingWindow.java // public class SlidingWindow { // // private TrailPoint[] points; // // @Getter // private int addedElementsNumber; // // public SlidingWindow(int windowSize) { // setWindowSize(windowSize); // } // // public void setWindowSize(int windowSize) { // points = new TrailPoint[windowSize]; // allocatePoints(); // } // // public int getWindowSize() { // return points.length; // } // // private void allocatePoints() { // for (int i = 0; i < points.length; i++) { // points[i] = new TrailPoint(); // } // } // // public void reset() { // addedElementsNumber = 0; // } // // public void add(int x, int y) { // if (isFull()) { // slidePointsToTheLeft(); // } // doAdd(x, y); // } // // public void add(TrailPoint point) { // add(point.getX(), point.getY()); // } // // public int getX(int index) { // if (isIndexValid(index)) { // return points[index].getX(); // } else { // throw new SlidingWindowIndexException(String.format("Invalid index '%d' (max index %d)", index, getMaxIndex())); // } // } // // public int getY(int index) { // if (isIndexValid(index)) { // return points[index].getY(); // } else { // throw getInvalidIndexException(index); // } // } // // boolean isIndexValid(int index) { // return index >= 0 && index <= getMaxIndex(); // } // // int getMaxIndex() { // return Math.min(addedElementsNumber, points.length) - 1; // } // // void slidePointsToTheLeft() { // TrailPoint p0 = points[0]; // for (int i = 0; i < points.length-1; i++) { // points[i] = points[i+1]; // } // points[points.length-1] = p0; // } // // void doAdd(int x, int y) { // points[getInsertIndex()].set(x, y); // addedElementsNumber++; // } // // public TrailPoint getElementAt(int index) { // if (isIndexValid(index)) { // return points[index]; // } else { // throw getInvalidIndexException(index); // } // } // // public TrailPoint getLastElement() { // return getElementAt(getLastElementIndex()); // } // // public boolean isSameAsLast(TrailPoint p) { // if (addedElementsNumber == 0) { // return false; // } else { // return p.isSameAs(points[getLastElementIndex()]); // } // } // // int getInsertIndex() { // return Math.min(addedElementsNumber, points.length - 1); // } // // public int getLastElementIndex() { // return Math.min(addedElementsNumber - 1, points.length - 1); // } // // public boolean isFull() { // return addedElementsNumber >= points.length; // } // // public void removeElementsAtLeftOf(int index) { // if (isIndexValid(index)) { // doRemoveElementsAtLeftOf(index); // } else { // throw getInvalidIndexException(index); // } // } // // private void doRemoveElementsAtLeftOf(int index) { // for (int i = 0; i <= getLastElementIndex()-index; i++) { // int sourceIndex = index + i; // shiftPoint(i, sourceIndex); // } // addedElementsNumber -= index; // } // // private void shiftPoint(int destIndex, int sourceIndex) { // if (sourceIndex < points.length) { // TrailPoint source = points[sourceIndex]; // points[destIndex].set(source.getX(), source.getY()); // } // } // // private SlidingWindowIndexException getInvalidIndexException(int index) { // return new SlidingWindowIndexException(String.format("Invalid index '%d' (max index %d)", index, getMaxIndex())); // } // } // Path: src/test/java/com/orange/dgil/trail/core/vecto/linearwindowfilter/LinearWindowFilterGetLastPointTest.java import com.orange.dgil.trail.TestTools; import com.orange.dgil.trail.core.common.TrailPoint; import com.orange.dgil.trail.core.vecto.SlidingWindow; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; /** * Trail drawing library * Copyright (C) 2014 Orange * Authors: christophe.maldivi@orange.com, eric.petit@orange.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.orange.dgil.trail.core.vecto.linearwindowfilter; public class LinearWindowFilterGetLastPointTest { private LinearWindowFilter filter; @Before public void setUp() { filter = Mockito.mock(LinearWindowFilter.class); } @Test public void shouldGetNewPointWhenAvailable() throws IllegalAccessException { // given
SlidingWindow slidingWindow = Mockito.mock(SlidingWindow.class);
Orange-OpenSource/android-trail-drawing
src/test/java/com/orange/dgil/trail/core/vecto/linearwindowfilter/LinearWindowFilterGetLastPointTest.java
// Path: src/main/java/com/orange/dgil/trail/core/common/TrailPoint.java // @Getter // @NoArgsConstructor // public class TrailPoint { // private int x = -1; // private int y = -1; // // public TrailPoint(int x, int y) { // set(x, y); // } // // public void set(int x, int y) { // this.x = x; // this.y = y; // } // // public boolean isSameAs(TrailPoint point) { // return x == point.x && y == point.y; // } // // public double getDistanceTo(TrailPoint point) { // int dx = x - point.getX(); // int dy = y - point.getY(); // return Math.sqrt(dx * dx + dy * dy); // } // // public void deepCopy(TrailPoint point) { // x = point.x; // y = point.y; // } // } // // Path: src/main/java/com/orange/dgil/trail/core/vecto/SlidingWindow.java // public class SlidingWindow { // // private TrailPoint[] points; // // @Getter // private int addedElementsNumber; // // public SlidingWindow(int windowSize) { // setWindowSize(windowSize); // } // // public void setWindowSize(int windowSize) { // points = new TrailPoint[windowSize]; // allocatePoints(); // } // // public int getWindowSize() { // return points.length; // } // // private void allocatePoints() { // for (int i = 0; i < points.length; i++) { // points[i] = new TrailPoint(); // } // } // // public void reset() { // addedElementsNumber = 0; // } // // public void add(int x, int y) { // if (isFull()) { // slidePointsToTheLeft(); // } // doAdd(x, y); // } // // public void add(TrailPoint point) { // add(point.getX(), point.getY()); // } // // public int getX(int index) { // if (isIndexValid(index)) { // return points[index].getX(); // } else { // throw new SlidingWindowIndexException(String.format("Invalid index '%d' (max index %d)", index, getMaxIndex())); // } // } // // public int getY(int index) { // if (isIndexValid(index)) { // return points[index].getY(); // } else { // throw getInvalidIndexException(index); // } // } // // boolean isIndexValid(int index) { // return index >= 0 && index <= getMaxIndex(); // } // // int getMaxIndex() { // return Math.min(addedElementsNumber, points.length) - 1; // } // // void slidePointsToTheLeft() { // TrailPoint p0 = points[0]; // for (int i = 0; i < points.length-1; i++) { // points[i] = points[i+1]; // } // points[points.length-1] = p0; // } // // void doAdd(int x, int y) { // points[getInsertIndex()].set(x, y); // addedElementsNumber++; // } // // public TrailPoint getElementAt(int index) { // if (isIndexValid(index)) { // return points[index]; // } else { // throw getInvalidIndexException(index); // } // } // // public TrailPoint getLastElement() { // return getElementAt(getLastElementIndex()); // } // // public boolean isSameAsLast(TrailPoint p) { // if (addedElementsNumber == 0) { // return false; // } else { // return p.isSameAs(points[getLastElementIndex()]); // } // } // // int getInsertIndex() { // return Math.min(addedElementsNumber, points.length - 1); // } // // public int getLastElementIndex() { // return Math.min(addedElementsNumber - 1, points.length - 1); // } // // public boolean isFull() { // return addedElementsNumber >= points.length; // } // // public void removeElementsAtLeftOf(int index) { // if (isIndexValid(index)) { // doRemoveElementsAtLeftOf(index); // } else { // throw getInvalidIndexException(index); // } // } // // private void doRemoveElementsAtLeftOf(int index) { // for (int i = 0; i <= getLastElementIndex()-index; i++) { // int sourceIndex = index + i; // shiftPoint(i, sourceIndex); // } // addedElementsNumber -= index; // } // // private void shiftPoint(int destIndex, int sourceIndex) { // if (sourceIndex < points.length) { // TrailPoint source = points[sourceIndex]; // points[destIndex].set(source.getX(), source.getY()); // } // } // // private SlidingWindowIndexException getInvalidIndexException(int index) { // return new SlidingWindowIndexException(String.format("Invalid index '%d' (max index %d)", index, getMaxIndex())); // } // }
import com.orange.dgil.trail.TestTools; import com.orange.dgil.trail.core.common.TrailPoint; import com.orange.dgil.trail.core.vecto.SlidingWindow; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito;
/** * Trail drawing library * Copyright (C) 2014 Orange * Authors: christophe.maldivi@orange.com, eric.petit@orange.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.orange.dgil.trail.core.vecto.linearwindowfilter; public class LinearWindowFilterGetLastPointTest { private LinearWindowFilter filter; @Before public void setUp() { filter = Mockito.mock(LinearWindowFilter.class); } @Test public void shouldGetNewPointWhenAvailable() throws IllegalAccessException { // given SlidingWindow slidingWindow = Mockito.mock(SlidingWindow.class); TestTools.setObj("slidingWindow", LinearWindowFilter.class, filter, slidingWindow);
// Path: src/main/java/com/orange/dgil/trail/core/common/TrailPoint.java // @Getter // @NoArgsConstructor // public class TrailPoint { // private int x = -1; // private int y = -1; // // public TrailPoint(int x, int y) { // set(x, y); // } // // public void set(int x, int y) { // this.x = x; // this.y = y; // } // // public boolean isSameAs(TrailPoint point) { // return x == point.x && y == point.y; // } // // public double getDistanceTo(TrailPoint point) { // int dx = x - point.getX(); // int dy = y - point.getY(); // return Math.sqrt(dx * dx + dy * dy); // } // // public void deepCopy(TrailPoint point) { // x = point.x; // y = point.y; // } // } // // Path: src/main/java/com/orange/dgil/trail/core/vecto/SlidingWindow.java // public class SlidingWindow { // // private TrailPoint[] points; // // @Getter // private int addedElementsNumber; // // public SlidingWindow(int windowSize) { // setWindowSize(windowSize); // } // // public void setWindowSize(int windowSize) { // points = new TrailPoint[windowSize]; // allocatePoints(); // } // // public int getWindowSize() { // return points.length; // } // // private void allocatePoints() { // for (int i = 0; i < points.length; i++) { // points[i] = new TrailPoint(); // } // } // // public void reset() { // addedElementsNumber = 0; // } // // public void add(int x, int y) { // if (isFull()) { // slidePointsToTheLeft(); // } // doAdd(x, y); // } // // public void add(TrailPoint point) { // add(point.getX(), point.getY()); // } // // public int getX(int index) { // if (isIndexValid(index)) { // return points[index].getX(); // } else { // throw new SlidingWindowIndexException(String.format("Invalid index '%d' (max index %d)", index, getMaxIndex())); // } // } // // public int getY(int index) { // if (isIndexValid(index)) { // return points[index].getY(); // } else { // throw getInvalidIndexException(index); // } // } // // boolean isIndexValid(int index) { // return index >= 0 && index <= getMaxIndex(); // } // // int getMaxIndex() { // return Math.min(addedElementsNumber, points.length) - 1; // } // // void slidePointsToTheLeft() { // TrailPoint p0 = points[0]; // for (int i = 0; i < points.length-1; i++) { // points[i] = points[i+1]; // } // points[points.length-1] = p0; // } // // void doAdd(int x, int y) { // points[getInsertIndex()].set(x, y); // addedElementsNumber++; // } // // public TrailPoint getElementAt(int index) { // if (isIndexValid(index)) { // return points[index]; // } else { // throw getInvalidIndexException(index); // } // } // // public TrailPoint getLastElement() { // return getElementAt(getLastElementIndex()); // } // // public boolean isSameAsLast(TrailPoint p) { // if (addedElementsNumber == 0) { // return false; // } else { // return p.isSameAs(points[getLastElementIndex()]); // } // } // // int getInsertIndex() { // return Math.min(addedElementsNumber, points.length - 1); // } // // public int getLastElementIndex() { // return Math.min(addedElementsNumber - 1, points.length - 1); // } // // public boolean isFull() { // return addedElementsNumber >= points.length; // } // // public void removeElementsAtLeftOf(int index) { // if (isIndexValid(index)) { // doRemoveElementsAtLeftOf(index); // } else { // throw getInvalidIndexException(index); // } // } // // private void doRemoveElementsAtLeftOf(int index) { // for (int i = 0; i <= getLastElementIndex()-index; i++) { // int sourceIndex = index + i; // shiftPoint(i, sourceIndex); // } // addedElementsNumber -= index; // } // // private void shiftPoint(int destIndex, int sourceIndex) { // if (sourceIndex < points.length) { // TrailPoint source = points[sourceIndex]; // points[destIndex].set(source.getX(), source.getY()); // } // } // // private SlidingWindowIndexException getInvalidIndexException(int index) { // return new SlidingWindowIndexException(String.format("Invalid index '%d' (max index %d)", index, getMaxIndex())); // } // } // Path: src/test/java/com/orange/dgil/trail/core/vecto/linearwindowfilter/LinearWindowFilterGetLastPointTest.java import com.orange.dgil.trail.TestTools; import com.orange.dgil.trail.core.common.TrailPoint; import com.orange.dgil.trail.core.vecto.SlidingWindow; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; /** * Trail drawing library * Copyright (C) 2014 Orange * Authors: christophe.maldivi@orange.com, eric.petit@orange.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.orange.dgil.trail.core.vecto.linearwindowfilter; public class LinearWindowFilterGetLastPointTest { private LinearWindowFilter filter; @Before public void setUp() { filter = Mockito.mock(LinearWindowFilter.class); } @Test public void shouldGetNewPointWhenAvailable() throws IllegalAccessException { // given SlidingWindow slidingWindow = Mockito.mock(SlidingWindow.class); TestTools.setObj("slidingWindow", LinearWindowFilter.class, filter, slidingWindow);
TrailPoint point = new TrailPoint();
Orange-OpenSource/android-trail-drawing
src/test/java/com/orange/dgil/trail/core/vecto/SlidingWindowCtorAllocatePointsTest.java
// Path: src/main/java/com/orange/dgil/trail/core/common/TrailPoint.java // @Getter // @NoArgsConstructor // public class TrailPoint { // private int x = -1; // private int y = -1; // // public TrailPoint(int x, int y) { // set(x, y); // } // // public void set(int x, int y) { // this.x = x; // this.y = y; // } // // public boolean isSameAs(TrailPoint point) { // return x == point.x && y == point.y; // } // // public double getDistanceTo(TrailPoint point) { // int dx = x - point.getX(); // int dy = y - point.getY(); // return Math.sqrt(dx * dx + dy * dy); // } // // public void deepCopy(TrailPoint point) { // x = point.x; // y = point.y; // } // }
import com.orange.dgil.trail.TestTools; import com.orange.dgil.trail.core.common.TrailPoint; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito;
/** * Trail drawing library * Copyright (C) 2014 Orange * Authors: christophe.maldivi@orange.com, eric.petit@orange.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.orange.dgil.trail.core.vecto; public class SlidingWindowCtorAllocatePointsTest { private SlidingWindow slidingWindow; @Before public void setUp() { slidingWindow = Mockito.mock(SlidingWindow.class); } @Test public void shouldInstantiate() throws IllegalAccessException { // given int windowSize = 5; // do slidingWindow = new SlidingWindow(windowSize); // then
// Path: src/main/java/com/orange/dgil/trail/core/common/TrailPoint.java // @Getter // @NoArgsConstructor // public class TrailPoint { // private int x = -1; // private int y = -1; // // public TrailPoint(int x, int y) { // set(x, y); // } // // public void set(int x, int y) { // this.x = x; // this.y = y; // } // // public boolean isSameAs(TrailPoint point) { // return x == point.x && y == point.y; // } // // public double getDistanceTo(TrailPoint point) { // int dx = x - point.getX(); // int dy = y - point.getY(); // return Math.sqrt(dx * dx + dy * dy); // } // // public void deepCopy(TrailPoint point) { // x = point.x; // y = point.y; // } // } // Path: src/test/java/com/orange/dgil/trail/core/vecto/SlidingWindowCtorAllocatePointsTest.java import com.orange.dgil.trail.TestTools; import com.orange.dgil.trail.core.common.TrailPoint; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; /** * Trail drawing library * Copyright (C) 2014 Orange * Authors: christophe.maldivi@orange.com, eric.petit@orange.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.orange.dgil.trail.core.vecto; public class SlidingWindowCtorAllocatePointsTest { private SlidingWindow slidingWindow; @Before public void setUp() { slidingWindow = Mockito.mock(SlidingWindow.class); } @Test public void shouldInstantiate() throws IllegalAccessException { // given int windowSize = 5; // do slidingWindow = new SlidingWindow(windowSize); // then
TrailPoint[] points = (TrailPoint[]) TestTools.getObj("points", SlidingWindow.class, slidingWindow);
Orange-OpenSource/android-trail-drawing
src/main/java/com/orange/dgil/trail/android/drawingtool/quillpen/TrailBounds.java
// Path: src/main/java/com/orange/dgil/trail/android/drawingtool/InvalidateArea.java // @Getter // @Setter // public class InvalidateArea { // private final Rect rect = new Rect(); // private int radius; // // public void setOrigin(int x, int y) { // rect.set(x - radius, y - radius, x + radius, y + radius); // } // public void setOrigin(Point p) { // setOrigin(p.x, p.y); // } // // public void add(int x, int y) { // rect.union(x - radius, y - radius, x + radius, y + radius); // } // public void add(Point p) { // add(p.x, p.y); // } // // public void setEmpty() { // rect.setEmpty(); // } // } // // Path: src/main/java/com/orange/dgil/trail/core/common/TrailPoint.java // @Getter // @NoArgsConstructor // public class TrailPoint { // private int x = -1; // private int y = -1; // // public TrailPoint(int x, int y) { // set(x, y); // } // // public void set(int x, int y) { // this.x = x; // this.y = y; // } // // public boolean isSameAs(TrailPoint point) { // return x == point.x && y == point.y; // } // // public double getDistanceTo(TrailPoint point) { // int dx = x - point.getX(); // int dy = y - point.getY(); // return Math.sqrt(dx * dx + dy * dy); // } // // public void deepCopy(TrailPoint point) { // x = point.x; // y = point.y; // } // } // // Path: src/main/java/com/orange/dgil/trail/core/common/TrailRect.java // @Getter // public class TrailRect { // private int left; // private int top; // private int right; // private int bottom; // // public void initAtPoint(int x, int y) { // left = x; // top = y; // right = x; // bottom = y; // } // // public void union(int x, int y) { // left = Math.min(left, x); // right = Math.max(right, x); // top = Math.min(top, y); // bottom = Math.max(bottom, y); // } // }
import android.view.View; import com.orange.dgil.trail.android.drawingtool.InvalidateArea; import com.orange.dgil.trail.core.common.TrailPoint; import com.orange.dgil.trail.core.common.TrailRect; import lombok.RequiredArgsConstructor;
/** * Trail drawing library * Copyright (C) 2014 Orange * Authors: christophe.maldivi@orange.com, eric.petit@orange.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.orange.dgil.trail.android.drawingtool.quillpen; @RequiredArgsConstructor class TrailBounds { private final QuillParameters quillParameters;
// Path: src/main/java/com/orange/dgil/trail/android/drawingtool/InvalidateArea.java // @Getter // @Setter // public class InvalidateArea { // private final Rect rect = new Rect(); // private int radius; // // public void setOrigin(int x, int y) { // rect.set(x - radius, y - radius, x + radius, y + radius); // } // public void setOrigin(Point p) { // setOrigin(p.x, p.y); // } // // public void add(int x, int y) { // rect.union(x - radius, y - radius, x + radius, y + radius); // } // public void add(Point p) { // add(p.x, p.y); // } // // public void setEmpty() { // rect.setEmpty(); // } // } // // Path: src/main/java/com/orange/dgil/trail/core/common/TrailPoint.java // @Getter // @NoArgsConstructor // public class TrailPoint { // private int x = -1; // private int y = -1; // // public TrailPoint(int x, int y) { // set(x, y); // } // // public void set(int x, int y) { // this.x = x; // this.y = y; // } // // public boolean isSameAs(TrailPoint point) { // return x == point.x && y == point.y; // } // // public double getDistanceTo(TrailPoint point) { // int dx = x - point.getX(); // int dy = y - point.getY(); // return Math.sqrt(dx * dx + dy * dy); // } // // public void deepCopy(TrailPoint point) { // x = point.x; // y = point.y; // } // } // // Path: src/main/java/com/orange/dgil/trail/core/common/TrailRect.java // @Getter // public class TrailRect { // private int left; // private int top; // private int right; // private int bottom; // // public void initAtPoint(int x, int y) { // left = x; // top = y; // right = x; // bottom = y; // } // // public void union(int x, int y) { // left = Math.min(left, x); // right = Math.max(right, x); // top = Math.min(top, y); // bottom = Math.max(bottom, y); // } // } // Path: src/main/java/com/orange/dgil/trail/android/drawingtool/quillpen/TrailBounds.java import android.view.View; import com.orange.dgil.trail.android.drawingtool.InvalidateArea; import com.orange.dgil.trail.core.common.TrailPoint; import com.orange.dgil.trail.core.common.TrailRect; import lombok.RequiredArgsConstructor; /** * Trail drawing library * Copyright (C) 2014 Orange * Authors: christophe.maldivi@orange.com, eric.petit@orange.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.orange.dgil.trail.android.drawingtool.quillpen; @RequiredArgsConstructor class TrailBounds { private final QuillParameters quillParameters;
private final TrailRect trailRect;
Orange-OpenSource/android-trail-drawing
src/main/java/com/orange/dgil/trail/android/drawingtool/quillpen/TrailBounds.java
// Path: src/main/java/com/orange/dgil/trail/android/drawingtool/InvalidateArea.java // @Getter // @Setter // public class InvalidateArea { // private final Rect rect = new Rect(); // private int radius; // // public void setOrigin(int x, int y) { // rect.set(x - radius, y - radius, x + radius, y + radius); // } // public void setOrigin(Point p) { // setOrigin(p.x, p.y); // } // // public void add(int x, int y) { // rect.union(x - radius, y - radius, x + radius, y + radius); // } // public void add(Point p) { // add(p.x, p.y); // } // // public void setEmpty() { // rect.setEmpty(); // } // } // // Path: src/main/java/com/orange/dgil/trail/core/common/TrailPoint.java // @Getter // @NoArgsConstructor // public class TrailPoint { // private int x = -1; // private int y = -1; // // public TrailPoint(int x, int y) { // set(x, y); // } // // public void set(int x, int y) { // this.x = x; // this.y = y; // } // // public boolean isSameAs(TrailPoint point) { // return x == point.x && y == point.y; // } // // public double getDistanceTo(TrailPoint point) { // int dx = x - point.getX(); // int dy = y - point.getY(); // return Math.sqrt(dx * dx + dy * dy); // } // // public void deepCopy(TrailPoint point) { // x = point.x; // y = point.y; // } // } // // Path: src/main/java/com/orange/dgil/trail/core/common/TrailRect.java // @Getter // public class TrailRect { // private int left; // private int top; // private int right; // private int bottom; // // public void initAtPoint(int x, int y) { // left = x; // top = y; // right = x; // bottom = y; // } // // public void union(int x, int y) { // left = Math.min(left, x); // right = Math.max(right, x); // top = Math.min(top, y); // bottom = Math.max(bottom, y); // } // }
import android.view.View; import com.orange.dgil.trail.android.drawingtool.InvalidateArea; import com.orange.dgil.trail.core.common.TrailPoint; import com.orange.dgil.trail.core.common.TrailRect; import lombok.RequiredArgsConstructor;
/** * Trail drawing library * Copyright (C) 2014 Orange * Authors: christophe.maldivi@orange.com, eric.petit@orange.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.orange.dgil.trail.android.drawingtool.quillpen; @RequiredArgsConstructor class TrailBounds { private final QuillParameters quillParameters; private final TrailRect trailRect;
// Path: src/main/java/com/orange/dgil/trail/android/drawingtool/InvalidateArea.java // @Getter // @Setter // public class InvalidateArea { // private final Rect rect = new Rect(); // private int radius; // // public void setOrigin(int x, int y) { // rect.set(x - radius, y - radius, x + radius, y + radius); // } // public void setOrigin(Point p) { // setOrigin(p.x, p.y); // } // // public void add(int x, int y) { // rect.union(x - radius, y - radius, x + radius, y + radius); // } // public void add(Point p) { // add(p.x, p.y); // } // // public void setEmpty() { // rect.setEmpty(); // } // } // // Path: src/main/java/com/orange/dgil/trail/core/common/TrailPoint.java // @Getter // @NoArgsConstructor // public class TrailPoint { // private int x = -1; // private int y = -1; // // public TrailPoint(int x, int y) { // set(x, y); // } // // public void set(int x, int y) { // this.x = x; // this.y = y; // } // // public boolean isSameAs(TrailPoint point) { // return x == point.x && y == point.y; // } // // public double getDistanceTo(TrailPoint point) { // int dx = x - point.getX(); // int dy = y - point.getY(); // return Math.sqrt(dx * dx + dy * dy); // } // // public void deepCopy(TrailPoint point) { // x = point.x; // y = point.y; // } // } // // Path: src/main/java/com/orange/dgil/trail/core/common/TrailRect.java // @Getter // public class TrailRect { // private int left; // private int top; // private int right; // private int bottom; // // public void initAtPoint(int x, int y) { // left = x; // top = y; // right = x; // bottom = y; // } // // public void union(int x, int y) { // left = Math.min(left, x); // right = Math.max(right, x); // top = Math.min(top, y); // bottom = Math.max(bottom, y); // } // } // Path: src/main/java/com/orange/dgil/trail/android/drawingtool/quillpen/TrailBounds.java import android.view.View; import com.orange.dgil.trail.android.drawingtool.InvalidateArea; import com.orange.dgil.trail.core.common.TrailPoint; import com.orange.dgil.trail.core.common.TrailRect; import lombok.RequiredArgsConstructor; /** * Trail drawing library * Copyright (C) 2014 Orange * Authors: christophe.maldivi@orange.com, eric.petit@orange.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.orange.dgil.trail.android.drawingtool.quillpen; @RequiredArgsConstructor class TrailBounds { private final QuillParameters quillParameters; private final TrailRect trailRect;
private final InvalidateArea trailBounds = new InvalidateArea();
Orange-OpenSource/android-trail-drawing
src/main/java/com/orange/dgil/trail/android/drawingtool/quillpen/TrailBounds.java
// Path: src/main/java/com/orange/dgil/trail/android/drawingtool/InvalidateArea.java // @Getter // @Setter // public class InvalidateArea { // private final Rect rect = new Rect(); // private int radius; // // public void setOrigin(int x, int y) { // rect.set(x - radius, y - radius, x + radius, y + radius); // } // public void setOrigin(Point p) { // setOrigin(p.x, p.y); // } // // public void add(int x, int y) { // rect.union(x - radius, y - radius, x + radius, y + radius); // } // public void add(Point p) { // add(p.x, p.y); // } // // public void setEmpty() { // rect.setEmpty(); // } // } // // Path: src/main/java/com/orange/dgil/trail/core/common/TrailPoint.java // @Getter // @NoArgsConstructor // public class TrailPoint { // private int x = -1; // private int y = -1; // // public TrailPoint(int x, int y) { // set(x, y); // } // // public void set(int x, int y) { // this.x = x; // this.y = y; // } // // public boolean isSameAs(TrailPoint point) { // return x == point.x && y == point.y; // } // // public double getDistanceTo(TrailPoint point) { // int dx = x - point.getX(); // int dy = y - point.getY(); // return Math.sqrt(dx * dx + dy * dy); // } // // public void deepCopy(TrailPoint point) { // x = point.x; // y = point.y; // } // } // // Path: src/main/java/com/orange/dgil/trail/core/common/TrailRect.java // @Getter // public class TrailRect { // private int left; // private int top; // private int right; // private int bottom; // // public void initAtPoint(int x, int y) { // left = x; // top = y; // right = x; // bottom = y; // } // // public void union(int x, int y) { // left = Math.min(left, x); // right = Math.max(right, x); // top = Math.min(top, y); // bottom = Math.max(bottom, y); // } // }
import android.view.View; import com.orange.dgil.trail.android.drawingtool.InvalidateArea; import com.orange.dgil.trail.core.common.TrailPoint; import com.orange.dgil.trail.core.common.TrailRect; import lombok.RequiredArgsConstructor;
/** * Trail drawing library * Copyright (C) 2014 Orange * Authors: christophe.maldivi@orange.com, eric.petit@orange.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.orange.dgil.trail.android.drawingtool.quillpen; @RequiredArgsConstructor class TrailBounds { private final QuillParameters quillParameters; private final TrailRect trailRect; private final InvalidateArea trailBounds = new InvalidateArea(); private final InvalidateArea lastMoveBounds = new InvalidateArea();
// Path: src/main/java/com/orange/dgil/trail/android/drawingtool/InvalidateArea.java // @Getter // @Setter // public class InvalidateArea { // private final Rect rect = new Rect(); // private int radius; // // public void setOrigin(int x, int y) { // rect.set(x - radius, y - radius, x + radius, y + radius); // } // public void setOrigin(Point p) { // setOrigin(p.x, p.y); // } // // public void add(int x, int y) { // rect.union(x - radius, y - radius, x + radius, y + radius); // } // public void add(Point p) { // add(p.x, p.y); // } // // public void setEmpty() { // rect.setEmpty(); // } // } // // Path: src/main/java/com/orange/dgil/trail/core/common/TrailPoint.java // @Getter // @NoArgsConstructor // public class TrailPoint { // private int x = -1; // private int y = -1; // // public TrailPoint(int x, int y) { // set(x, y); // } // // public void set(int x, int y) { // this.x = x; // this.y = y; // } // // public boolean isSameAs(TrailPoint point) { // return x == point.x && y == point.y; // } // // public double getDistanceTo(TrailPoint point) { // int dx = x - point.getX(); // int dy = y - point.getY(); // return Math.sqrt(dx * dx + dy * dy); // } // // public void deepCopy(TrailPoint point) { // x = point.x; // y = point.y; // } // } // // Path: src/main/java/com/orange/dgil/trail/core/common/TrailRect.java // @Getter // public class TrailRect { // private int left; // private int top; // private int right; // private int bottom; // // public void initAtPoint(int x, int y) { // left = x; // top = y; // right = x; // bottom = y; // } // // public void union(int x, int y) { // left = Math.min(left, x); // right = Math.max(right, x); // top = Math.min(top, y); // bottom = Math.max(bottom, y); // } // } // Path: src/main/java/com/orange/dgil/trail/android/drawingtool/quillpen/TrailBounds.java import android.view.View; import com.orange.dgil.trail.android.drawingtool.InvalidateArea; import com.orange.dgil.trail.core.common.TrailPoint; import com.orange.dgil.trail.core.common.TrailRect; import lombok.RequiredArgsConstructor; /** * Trail drawing library * Copyright (C) 2014 Orange * Authors: christophe.maldivi@orange.com, eric.petit@orange.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.orange.dgil.trail.android.drawingtool.quillpen; @RequiredArgsConstructor class TrailBounds { private final QuillParameters quillParameters; private final TrailRect trailRect; private final InvalidateArea trailBounds = new InvalidateArea(); private final InvalidateArea lastMoveBounds = new InvalidateArea();
private final TrailPoint lastPoint = new TrailPoint();
Orange-OpenSource/android-trail-drawing
src/main/java/com/orange/dgil/trail/android/ITrailDrawer.java
// Path: src/main/java/com/orange/dgil/trail/android/animation/AnimParameters.java // @Getter // public class AnimParameters { // // private int preAnimDelay = DefaultDrawerConf.ANIM_PRE_ANIM_DELAY_MS; // private int animDuration = DefaultDrawerConf.ANIM_DURATION_MS; // private int startColor = DefaultDrawerConf.TRAIL_COLOR; // private int endColor = getColorWithNullAlpha(startColor); // // @Setter // private boolean shadowEnabled; // private int shadowStartColor = DefaultDrawerConf.SHADOW_COLOR; // private int shadowEndColor = shadowStartColor; // // @Setter // private float widthDilatationFactor; // // private static int getColorWithNullAlpha(int col) { // return Color.argb(0, Color.red(col), Color.green(col), Color.blue(col)); // } // // public void setTimeProperties(int preAnimDelay, int animDuration) { // this.preAnimDelay = preAnimDelay; // this.animDuration = animDuration; // } // // // /** // * Will start the animation with provided color, and decrease the alpha channel. // * @param color animation start color // */ // public void setColorForAlphaAnimation(int color) { // setColorProperties(color, getColorWithNullAlpha(color)); // } // // public void setColorProperties(int startColor, int endColor) { // this.startColor = startColor; // this.endColor = endColor; // } // // /** // * Will start the animation with provided color, and decrease the alpha channel. // * @param color animation start color // */ // public void setShadowColorForAlphaAnimation(int color) { // setShadowColorProperties(color, getColorWithNullAlpha(color)); // } // // public void setShadowColorProperties(int startColor, int endColor) { // this.shadowStartColor = startColor; // this.shadowEndColor = endColor; // } // // public boolean areStartEndColorsRgbEqual() { // return (Color.red(startColor) == Color.red(endColor)) && // (Color.green(startColor) == Color.green(endColor)) && // (Color.blue(startColor) == Color.blue(endColor)); // } // } // // Path: src/main/java/com/orange/dgil/trail/android/animation/IAnimListener.java // public interface IAnimListener { // void animationFinished(); // } // // Path: src/main/java/com/orange/dgil/trail/android/drawingtool/TrailOptions.java // @Getter // public class TrailOptions { // @Getter(AccessLevel.NONE) // private DrawingTools drawingTools; // @Getter(AccessLevel.NONE) // private AndroidMetrics metrics; // // @Setter // private int color = DefaultDrawerConf.TRAIL_COLOR; // @Setter // private int shadowColor; // // private QuillParameters quillParameters; // // private boolean shadowEnabled; // private int shadowOffsetPixels; // private int widthPixels; // // public TrailOptions(AndroidMetrics metrics, DrawingTools drawingTools) { // init(metrics, drawingTools); // } // // private void init(AndroidMetrics metrics, DrawingTools drawingTools) { // this.metrics = metrics; // this.drawingTools = drawingTools; // quillParameters = new QuillParameters(metrics); // setTrailWidthMicrometers(DefaultDrawerConf.TRAIL_WIDTH_UM); // } // // public void setTrailWidthMicrometers(int micrometers) { // widthPixels = metrics.micrometersToPixels(micrometers); // shadowOffsetPixels = (int) (widthPixels * DefaultDrawerConf.SHADOW_OFFSET_FACTOR); // } // // public boolean isShadowAvailable() { // return android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH; // } // // public void setShadowEnabled(boolean shadowEnabled) { // this.shadowEnabled = shadowEnabled && isShadowAvailable(); // } // // public void selectMarkerPen() { // drawingTools.selectMarkerPen(); // } // // public void selectQuillPen() { // drawingTools.selectQuillPen(); // } // }
import android.graphics.Canvas; import com.orange.dgil.trail.android.animation.AnimParameters; import com.orange.dgil.trail.android.animation.IAnimListener; import com.orange.dgil.trail.android.drawingtool.TrailOptions;
/** * Trail drawing library * Copyright (C) 2014 Orange * Authors: christophe.maldivi@orange.com, eric.petit@orange.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.orange.dgil.trail.android; public interface ITrailDrawer { void setAnimationListener(IAnimListener i);
// Path: src/main/java/com/orange/dgil/trail/android/animation/AnimParameters.java // @Getter // public class AnimParameters { // // private int preAnimDelay = DefaultDrawerConf.ANIM_PRE_ANIM_DELAY_MS; // private int animDuration = DefaultDrawerConf.ANIM_DURATION_MS; // private int startColor = DefaultDrawerConf.TRAIL_COLOR; // private int endColor = getColorWithNullAlpha(startColor); // // @Setter // private boolean shadowEnabled; // private int shadowStartColor = DefaultDrawerConf.SHADOW_COLOR; // private int shadowEndColor = shadowStartColor; // // @Setter // private float widthDilatationFactor; // // private static int getColorWithNullAlpha(int col) { // return Color.argb(0, Color.red(col), Color.green(col), Color.blue(col)); // } // // public void setTimeProperties(int preAnimDelay, int animDuration) { // this.preAnimDelay = preAnimDelay; // this.animDuration = animDuration; // } // // // /** // * Will start the animation with provided color, and decrease the alpha channel. // * @param color animation start color // */ // public void setColorForAlphaAnimation(int color) { // setColorProperties(color, getColorWithNullAlpha(color)); // } // // public void setColorProperties(int startColor, int endColor) { // this.startColor = startColor; // this.endColor = endColor; // } // // /** // * Will start the animation with provided color, and decrease the alpha channel. // * @param color animation start color // */ // public void setShadowColorForAlphaAnimation(int color) { // setShadowColorProperties(color, getColorWithNullAlpha(color)); // } // // public void setShadowColorProperties(int startColor, int endColor) { // this.shadowStartColor = startColor; // this.shadowEndColor = endColor; // } // // public boolean areStartEndColorsRgbEqual() { // return (Color.red(startColor) == Color.red(endColor)) && // (Color.green(startColor) == Color.green(endColor)) && // (Color.blue(startColor) == Color.blue(endColor)); // } // } // // Path: src/main/java/com/orange/dgil/trail/android/animation/IAnimListener.java // public interface IAnimListener { // void animationFinished(); // } // // Path: src/main/java/com/orange/dgil/trail/android/drawingtool/TrailOptions.java // @Getter // public class TrailOptions { // @Getter(AccessLevel.NONE) // private DrawingTools drawingTools; // @Getter(AccessLevel.NONE) // private AndroidMetrics metrics; // // @Setter // private int color = DefaultDrawerConf.TRAIL_COLOR; // @Setter // private int shadowColor; // // private QuillParameters quillParameters; // // private boolean shadowEnabled; // private int shadowOffsetPixels; // private int widthPixels; // // public TrailOptions(AndroidMetrics metrics, DrawingTools drawingTools) { // init(metrics, drawingTools); // } // // private void init(AndroidMetrics metrics, DrawingTools drawingTools) { // this.metrics = metrics; // this.drawingTools = drawingTools; // quillParameters = new QuillParameters(metrics); // setTrailWidthMicrometers(DefaultDrawerConf.TRAIL_WIDTH_UM); // } // // public void setTrailWidthMicrometers(int micrometers) { // widthPixels = metrics.micrometersToPixels(micrometers); // shadowOffsetPixels = (int) (widthPixels * DefaultDrawerConf.SHADOW_OFFSET_FACTOR); // } // // public boolean isShadowAvailable() { // return android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH; // } // // public void setShadowEnabled(boolean shadowEnabled) { // this.shadowEnabled = shadowEnabled && isShadowAvailable(); // } // // public void selectMarkerPen() { // drawingTools.selectMarkerPen(); // } // // public void selectQuillPen() { // drawingTools.selectQuillPen(); // } // } // Path: src/main/java/com/orange/dgil/trail/android/ITrailDrawer.java import android.graphics.Canvas; import com.orange.dgil.trail.android.animation.AnimParameters; import com.orange.dgil.trail.android.animation.IAnimListener; import com.orange.dgil.trail.android.drawingtool.TrailOptions; /** * Trail drawing library * Copyright (C) 2014 Orange * Authors: christophe.maldivi@orange.com, eric.petit@orange.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.orange.dgil.trail.android; public interface ITrailDrawer { void setAnimationListener(IAnimListener i);
TrailOptions getTrailOptions();
Orange-OpenSource/android-trail-drawing
src/main/java/com/orange/dgil/trail/android/ITrailDrawer.java
// Path: src/main/java/com/orange/dgil/trail/android/animation/AnimParameters.java // @Getter // public class AnimParameters { // // private int preAnimDelay = DefaultDrawerConf.ANIM_PRE_ANIM_DELAY_MS; // private int animDuration = DefaultDrawerConf.ANIM_DURATION_MS; // private int startColor = DefaultDrawerConf.TRAIL_COLOR; // private int endColor = getColorWithNullAlpha(startColor); // // @Setter // private boolean shadowEnabled; // private int shadowStartColor = DefaultDrawerConf.SHADOW_COLOR; // private int shadowEndColor = shadowStartColor; // // @Setter // private float widthDilatationFactor; // // private static int getColorWithNullAlpha(int col) { // return Color.argb(0, Color.red(col), Color.green(col), Color.blue(col)); // } // // public void setTimeProperties(int preAnimDelay, int animDuration) { // this.preAnimDelay = preAnimDelay; // this.animDuration = animDuration; // } // // // /** // * Will start the animation with provided color, and decrease the alpha channel. // * @param color animation start color // */ // public void setColorForAlphaAnimation(int color) { // setColorProperties(color, getColorWithNullAlpha(color)); // } // // public void setColorProperties(int startColor, int endColor) { // this.startColor = startColor; // this.endColor = endColor; // } // // /** // * Will start the animation with provided color, and decrease the alpha channel. // * @param color animation start color // */ // public void setShadowColorForAlphaAnimation(int color) { // setShadowColorProperties(color, getColorWithNullAlpha(color)); // } // // public void setShadowColorProperties(int startColor, int endColor) { // this.shadowStartColor = startColor; // this.shadowEndColor = endColor; // } // // public boolean areStartEndColorsRgbEqual() { // return (Color.red(startColor) == Color.red(endColor)) && // (Color.green(startColor) == Color.green(endColor)) && // (Color.blue(startColor) == Color.blue(endColor)); // } // } // // Path: src/main/java/com/orange/dgil/trail/android/animation/IAnimListener.java // public interface IAnimListener { // void animationFinished(); // } // // Path: src/main/java/com/orange/dgil/trail/android/drawingtool/TrailOptions.java // @Getter // public class TrailOptions { // @Getter(AccessLevel.NONE) // private DrawingTools drawingTools; // @Getter(AccessLevel.NONE) // private AndroidMetrics metrics; // // @Setter // private int color = DefaultDrawerConf.TRAIL_COLOR; // @Setter // private int shadowColor; // // private QuillParameters quillParameters; // // private boolean shadowEnabled; // private int shadowOffsetPixels; // private int widthPixels; // // public TrailOptions(AndroidMetrics metrics, DrawingTools drawingTools) { // init(metrics, drawingTools); // } // // private void init(AndroidMetrics metrics, DrawingTools drawingTools) { // this.metrics = metrics; // this.drawingTools = drawingTools; // quillParameters = new QuillParameters(metrics); // setTrailWidthMicrometers(DefaultDrawerConf.TRAIL_WIDTH_UM); // } // // public void setTrailWidthMicrometers(int micrometers) { // widthPixels = metrics.micrometersToPixels(micrometers); // shadowOffsetPixels = (int) (widthPixels * DefaultDrawerConf.SHADOW_OFFSET_FACTOR); // } // // public boolean isShadowAvailable() { // return android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH; // } // // public void setShadowEnabled(boolean shadowEnabled) { // this.shadowEnabled = shadowEnabled && isShadowAvailable(); // } // // public void selectMarkerPen() { // drawingTools.selectMarkerPen(); // } // // public void selectQuillPen() { // drawingTools.selectQuillPen(); // } // }
import android.graphics.Canvas; import com.orange.dgil.trail.android.animation.AnimParameters; import com.orange.dgil.trail.android.animation.IAnimListener; import com.orange.dgil.trail.android.drawingtool.TrailOptions;
/** * Trail drawing library * Copyright (C) 2014 Orange * Authors: christophe.maldivi@orange.com, eric.petit@orange.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.orange.dgil.trail.android; public interface ITrailDrawer { void setAnimationListener(IAnimListener i); TrailOptions getTrailOptions();
// Path: src/main/java/com/orange/dgil/trail/android/animation/AnimParameters.java // @Getter // public class AnimParameters { // // private int preAnimDelay = DefaultDrawerConf.ANIM_PRE_ANIM_DELAY_MS; // private int animDuration = DefaultDrawerConf.ANIM_DURATION_MS; // private int startColor = DefaultDrawerConf.TRAIL_COLOR; // private int endColor = getColorWithNullAlpha(startColor); // // @Setter // private boolean shadowEnabled; // private int shadowStartColor = DefaultDrawerConf.SHADOW_COLOR; // private int shadowEndColor = shadowStartColor; // // @Setter // private float widthDilatationFactor; // // private static int getColorWithNullAlpha(int col) { // return Color.argb(0, Color.red(col), Color.green(col), Color.blue(col)); // } // // public void setTimeProperties(int preAnimDelay, int animDuration) { // this.preAnimDelay = preAnimDelay; // this.animDuration = animDuration; // } // // // /** // * Will start the animation with provided color, and decrease the alpha channel. // * @param color animation start color // */ // public void setColorForAlphaAnimation(int color) { // setColorProperties(color, getColorWithNullAlpha(color)); // } // // public void setColorProperties(int startColor, int endColor) { // this.startColor = startColor; // this.endColor = endColor; // } // // /** // * Will start the animation with provided color, and decrease the alpha channel. // * @param color animation start color // */ // public void setShadowColorForAlphaAnimation(int color) { // setShadowColorProperties(color, getColorWithNullAlpha(color)); // } // // public void setShadowColorProperties(int startColor, int endColor) { // this.shadowStartColor = startColor; // this.shadowEndColor = endColor; // } // // public boolean areStartEndColorsRgbEqual() { // return (Color.red(startColor) == Color.red(endColor)) && // (Color.green(startColor) == Color.green(endColor)) && // (Color.blue(startColor) == Color.blue(endColor)); // } // } // // Path: src/main/java/com/orange/dgil/trail/android/animation/IAnimListener.java // public interface IAnimListener { // void animationFinished(); // } // // Path: src/main/java/com/orange/dgil/trail/android/drawingtool/TrailOptions.java // @Getter // public class TrailOptions { // @Getter(AccessLevel.NONE) // private DrawingTools drawingTools; // @Getter(AccessLevel.NONE) // private AndroidMetrics metrics; // // @Setter // private int color = DefaultDrawerConf.TRAIL_COLOR; // @Setter // private int shadowColor; // // private QuillParameters quillParameters; // // private boolean shadowEnabled; // private int shadowOffsetPixels; // private int widthPixels; // // public TrailOptions(AndroidMetrics metrics, DrawingTools drawingTools) { // init(metrics, drawingTools); // } // // private void init(AndroidMetrics metrics, DrawingTools drawingTools) { // this.metrics = metrics; // this.drawingTools = drawingTools; // quillParameters = new QuillParameters(metrics); // setTrailWidthMicrometers(DefaultDrawerConf.TRAIL_WIDTH_UM); // } // // public void setTrailWidthMicrometers(int micrometers) { // widthPixels = metrics.micrometersToPixels(micrometers); // shadowOffsetPixels = (int) (widthPixels * DefaultDrawerConf.SHADOW_OFFSET_FACTOR); // } // // public boolean isShadowAvailable() { // return android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH; // } // // public void setShadowEnabled(boolean shadowEnabled) { // this.shadowEnabled = shadowEnabled && isShadowAvailable(); // } // // public void selectMarkerPen() { // drawingTools.selectMarkerPen(); // } // // public void selectQuillPen() { // drawingTools.selectQuillPen(); // } // } // Path: src/main/java/com/orange/dgil/trail/android/ITrailDrawer.java import android.graphics.Canvas; import com.orange.dgil.trail.android.animation.AnimParameters; import com.orange.dgil.trail.android.animation.IAnimListener; import com.orange.dgil.trail.android.drawingtool.TrailOptions; /** * Trail drawing library * Copyright (C) 2014 Orange * Authors: christophe.maldivi@orange.com, eric.petit@orange.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.orange.dgil.trail.android; public interface ITrailDrawer { void setAnimationListener(IAnimListener i); TrailOptions getTrailOptions();
AnimParameters getAnimationParameters();
Orange-OpenSource/android-trail-drawing
src/main/java/com/orange/dgil/trail/android/drawingtool/quillpen/QuillTrailBitmapEnd.java
// Path: src/main/java/com/orange/dgil/trail/android/drawingtool/DrawingToolsContext.java // @RequiredArgsConstructor // @Getter // public class DrawingToolsContext { // private final View view; // private final AnimManager animManager; // private final AndroidMetrics androidMetrics; // private final TrailOptions trailOptions; // } // // Path: src/main/java/com/orange/dgil/trail/android/drawingtool/IDrawingTool.java // public interface IDrawingTool { // void reset(); // // void touchDown(int x, int y); // void touchMove(int x, int y); // void touchUp(); // // void draw(Canvas c); // // void invalidateAreaOnMove(); // void invalidatePath(); // // void forceRedrawForAnimation(boolean eraseBitmap); // // void trimMemory(); // } // // Path: src/main/java/com/orange/dgil/trail/core/common/TrailPoint.java // @Getter // @NoArgsConstructor // public class TrailPoint { // private int x = -1; // private int y = -1; // // public TrailPoint(int x, int y) { // set(x, y); // } // // public void set(int x, int y) { // this.x = x; // this.y = y; // } // // public boolean isSameAs(TrailPoint point) { // return x == point.x && y == point.y; // } // // public double getDistanceTo(TrailPoint point) { // int dx = x - point.getX(); // int dy = y - point.getY(); // return Math.sqrt(dx * dx + dy * dy); // } // // public void deepCopy(TrailPoint point) { // x = point.x; // y = point.y; // } // }
import android.graphics.Canvas; import android.graphics.Color; import android.view.View; import com.orange.dgil.trail.android.drawingtool.DrawingToolsContext; import com.orange.dgil.trail.android.drawingtool.IDrawingTool; import com.orange.dgil.trail.core.common.TrailPoint; import com.orange.dgil.trail.core.quad.QuadCurveArray;
/** * Trail drawing library * Copyright (C) 2014 Orange * Authors: christophe.maldivi@orange.com, eric.petit@orange.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.orange.dgil.trail.android.drawingtool.quillpen; class QuillTrailBitmapEnd implements IDrawingTool { private final View view; private final BitmapDrawer bitmapDrawer; private final QuillBitmap quillBitmap; private final TrailBounds trailBounds; private final QuadCurveArray quadCurveArray; private boolean inGesture; private int readIndex;
// Path: src/main/java/com/orange/dgil/trail/android/drawingtool/DrawingToolsContext.java // @RequiredArgsConstructor // @Getter // public class DrawingToolsContext { // private final View view; // private final AnimManager animManager; // private final AndroidMetrics androidMetrics; // private final TrailOptions trailOptions; // } // // Path: src/main/java/com/orange/dgil/trail/android/drawingtool/IDrawingTool.java // public interface IDrawingTool { // void reset(); // // void touchDown(int x, int y); // void touchMove(int x, int y); // void touchUp(); // // void draw(Canvas c); // // void invalidateAreaOnMove(); // void invalidatePath(); // // void forceRedrawForAnimation(boolean eraseBitmap); // // void trimMemory(); // } // // Path: src/main/java/com/orange/dgil/trail/core/common/TrailPoint.java // @Getter // @NoArgsConstructor // public class TrailPoint { // private int x = -1; // private int y = -1; // // public TrailPoint(int x, int y) { // set(x, y); // } // // public void set(int x, int y) { // this.x = x; // this.y = y; // } // // public boolean isSameAs(TrailPoint point) { // return x == point.x && y == point.y; // } // // public double getDistanceTo(TrailPoint point) { // int dx = x - point.getX(); // int dy = y - point.getY(); // return Math.sqrt(dx * dx + dy * dy); // } // // public void deepCopy(TrailPoint point) { // x = point.x; // y = point.y; // } // } // Path: src/main/java/com/orange/dgil/trail/android/drawingtool/quillpen/QuillTrailBitmapEnd.java import android.graphics.Canvas; import android.graphics.Color; import android.view.View; import com.orange.dgil.trail.android.drawingtool.DrawingToolsContext; import com.orange.dgil.trail.android.drawingtool.IDrawingTool; import com.orange.dgil.trail.core.common.TrailPoint; import com.orange.dgil.trail.core.quad.QuadCurveArray; /** * Trail drawing library * Copyright (C) 2014 Orange * Authors: christophe.maldivi@orange.com, eric.petit@orange.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.orange.dgil.trail.android.drawingtool.quillpen; class QuillTrailBitmapEnd implements IDrawingTool { private final View view; private final BitmapDrawer bitmapDrawer; private final QuillBitmap quillBitmap; private final TrailBounds trailBounds; private final QuadCurveArray quadCurveArray; private boolean inGesture; private int readIndex;
QuillTrailBitmapEnd(DrawingToolsContext drawingToolsContext, BitmapDrawer bitmapDrawer, QuadCurveArray quadCurveArray) {
Orange-OpenSource/android-trail-drawing
src/main/java/com/orange/dgil/trail/android/drawingtool/quillpen/QuillTrailBitmapEnd.java
// Path: src/main/java/com/orange/dgil/trail/android/drawingtool/DrawingToolsContext.java // @RequiredArgsConstructor // @Getter // public class DrawingToolsContext { // private final View view; // private final AnimManager animManager; // private final AndroidMetrics androidMetrics; // private final TrailOptions trailOptions; // } // // Path: src/main/java/com/orange/dgil/trail/android/drawingtool/IDrawingTool.java // public interface IDrawingTool { // void reset(); // // void touchDown(int x, int y); // void touchMove(int x, int y); // void touchUp(); // // void draw(Canvas c); // // void invalidateAreaOnMove(); // void invalidatePath(); // // void forceRedrawForAnimation(boolean eraseBitmap); // // void trimMemory(); // } // // Path: src/main/java/com/orange/dgil/trail/core/common/TrailPoint.java // @Getter // @NoArgsConstructor // public class TrailPoint { // private int x = -1; // private int y = -1; // // public TrailPoint(int x, int y) { // set(x, y); // } // // public void set(int x, int y) { // this.x = x; // this.y = y; // } // // public boolean isSameAs(TrailPoint point) { // return x == point.x && y == point.y; // } // // public double getDistanceTo(TrailPoint point) { // int dx = x - point.getX(); // int dy = y - point.getY(); // return Math.sqrt(dx * dx + dy * dy); // } // // public void deepCopy(TrailPoint point) { // x = point.x; // y = point.y; // } // }
import android.graphics.Canvas; import android.graphics.Color; import android.view.View; import com.orange.dgil.trail.android.drawingtool.DrawingToolsContext; import com.orange.dgil.trail.android.drawingtool.IDrawingTool; import com.orange.dgil.trail.core.common.TrailPoint; import com.orange.dgil.trail.core.quad.QuadCurveArray;
this.quadCurveArray = quadCurveArray; this.bitmapDrawer = bitmapDrawer; quillBitmap = new QuillBitmap(view); trailBounds = new TrailBounds(drawingToolsContext.getTrailOptions().getQuillParameters(), quadCurveArray.getTrailRect()); } @Override public void reset() { } @Override public void trimMemory() { quillBitmap.releaseBitmap(); } @Override public void touchDown(int x, int y) { inGesture = true; readIndex = 0; trailBounds.updateTrailBoundsOnTouchDown(x, y); } @Override public void touchMove(int x, int y) { updateTrailBounds(); } private void updateTrailBounds() { if (quadCurveArray.isNotEmpty()) {
// Path: src/main/java/com/orange/dgil/trail/android/drawingtool/DrawingToolsContext.java // @RequiredArgsConstructor // @Getter // public class DrawingToolsContext { // private final View view; // private final AnimManager animManager; // private final AndroidMetrics androidMetrics; // private final TrailOptions trailOptions; // } // // Path: src/main/java/com/orange/dgil/trail/android/drawingtool/IDrawingTool.java // public interface IDrawingTool { // void reset(); // // void touchDown(int x, int y); // void touchMove(int x, int y); // void touchUp(); // // void draw(Canvas c); // // void invalidateAreaOnMove(); // void invalidatePath(); // // void forceRedrawForAnimation(boolean eraseBitmap); // // void trimMemory(); // } // // Path: src/main/java/com/orange/dgil/trail/core/common/TrailPoint.java // @Getter // @NoArgsConstructor // public class TrailPoint { // private int x = -1; // private int y = -1; // // public TrailPoint(int x, int y) { // set(x, y); // } // // public void set(int x, int y) { // this.x = x; // this.y = y; // } // // public boolean isSameAs(TrailPoint point) { // return x == point.x && y == point.y; // } // // public double getDistanceTo(TrailPoint point) { // int dx = x - point.getX(); // int dy = y - point.getY(); // return Math.sqrt(dx * dx + dy * dy); // } // // public void deepCopy(TrailPoint point) { // x = point.x; // y = point.y; // } // } // Path: src/main/java/com/orange/dgil/trail/android/drawingtool/quillpen/QuillTrailBitmapEnd.java import android.graphics.Canvas; import android.graphics.Color; import android.view.View; import com.orange.dgil.trail.android.drawingtool.DrawingToolsContext; import com.orange.dgil.trail.android.drawingtool.IDrawingTool; import com.orange.dgil.trail.core.common.TrailPoint; import com.orange.dgil.trail.core.quad.QuadCurveArray; this.quadCurveArray = quadCurveArray; this.bitmapDrawer = bitmapDrawer; quillBitmap = new QuillBitmap(view); trailBounds = new TrailBounds(drawingToolsContext.getTrailOptions().getQuillParameters(), quadCurveArray.getTrailRect()); } @Override public void reset() { } @Override public void trimMemory() { quillBitmap.releaseBitmap(); } @Override public void touchDown(int x, int y) { inGesture = true; readIndex = 0; trailBounds.updateTrailBoundsOnTouchDown(x, y); } @Override public void touchMove(int x, int y) { updateTrailBounds(); } private void updateTrailBounds() { if (quadCurveArray.isNotEmpty()) {
TrailPoint lastPoint = quadCurveArray.getLastPoint();
Orange-OpenSource/android-trail-drawing
demo/JavaFxTest/src/main/java/com/orange/dgil/trail/app/fxdrawertest/drawer/GraphicContextDrawer.java
// Path: demo/JavaFxTest/src/main/java/com/orange/dgil/trail/app/fxdrawertest/curves/Curves.java // public class Curves implements LinearWindowFilterListener, VectoFilterListener { // // private boolean rawCurveEnabled; // private boolean linearFilterCurveEnabled; // private boolean vectoCurveEnabled; // private boolean quadCurveEnabled; // // private List<Point2D> rawCurvePoints = new ArrayList<Point2D>(); // private List<Point2D> linearFilterCurvePoints = new ArrayList<Point2D>(); // private List<Point2D> vectoCurvePoints = new ArrayList<Point2D>(); // private List<Point2D> quadCurvePoints = new ArrayList<Point2D>(); // // private final LinearWindowFilter linearWindowFilter = new LinearWindowFilter(this); // private final VectoFilter vectoFilter = new VectoFilter(this); // private final QuadCurve quadCurve = new QuadCurve(true); // // public void clear() { // rawCurvePoints.clear(); // linearFilterCurvePoints.clear(); // vectoCurvePoints.clear(); // quadCurvePoints.clear(); // linearWindowFilter.reset(); // vectoFilter.reset(); // quadCurve.reset(); // } // // public void end() { // TrailPoint lastPoint = linearWindowFilter.getLastPoint(); // linearFilterCurvePoints.add(new Point2D(lastPoint.getX(), lastPoint.getY())); // endVecto(); // endQuadCurve(); // } // // private void endVecto() { // vectoFilter.epilogue(); // } // // private void endQuadCurve() { // quadCurve.epilogue(); // fillQuadCurve(); // } // // // public void addPoint(double x, double y) { // rawCurvePoints.add(new Point2D(x, y)); // addPointToLinearFilter(x, y); // addPointToVecto(x, y); // addPointToQuadCurve(x, y); // } // // private void addPointToLinearFilter(double x, double y) { // linearWindowFilter.addPoint(new TrailPoint((int)x, (int)y)); // } // // private void addPointToVecto(double x, double y) { // vectoFilter.addPoint((int)x, (int)y); // } // // private void addPointToQuadCurve(double x, double y) { // quadCurve.addPoint((int)x, (int)y); // fillQuadCurve(); // } // // private void fillQuadCurve() { // QuadCurveArray quadCurveArray = quadCurve.getQuadCurveArray(); // for (int i = quadCurvePoints.size(); i <= quadCurveArray.getLastPointIndex(); i++) { // TrailPoint p = quadCurveArray.get(i); // quadCurvePoints.add(new Point2D(p.getX(), p.getY())); // } // } // // public boolean isRawCurveEnabled() { // return rawCurveEnabled; // } // public void setRawCurveEnabled(boolean rawCurveEnabled) { // this.rawCurveEnabled = rawCurveEnabled; // } // // public boolean isLinearFilterCurveEnabled() { // return linearFilterCurveEnabled; // } // public void setLinearFilterCurveEnabled(boolean linearFilterCurveEnabled) { // this.linearFilterCurveEnabled = linearFilterCurveEnabled; // } // // public boolean isVectoCurveEnabled() { // return vectoCurveEnabled; // } // public void setVectoCurveEnabled(boolean vectoCurveEnabled) { // this.vectoCurveEnabled = vectoCurveEnabled; // } // // public boolean isQuadCurveEnabled() { // return quadCurveEnabled; // } // public void setQuadCurveEnabled(boolean quadCurveEnabled) { // this.quadCurveEnabled = quadCurveEnabled; // } // // public List<Point2D> getRawCurvePoints() { // return rawCurvePoints; // } // // public List<Point2D> getLinearFilterCurvePoints() { // return linearFilterCurvePoints; // } // // public List<Point2D> getVectoCurvePoints() { // return vectoCurvePoints; // } // // public List<Point2D> getQuadCurvePoints() { // return quadCurvePoints; // } // // public void setVectoErrorPixels(int error) { // vectoFilter.getVectoSettings().setVectorsHeightThreshold(error); // } // public void setVectoWindowSize(int windowSize) { // vectoFilter.getVectoSettings().setWindowSize(windowSize); // } // // @Override // public void onNewFilteredPointAvailable(int x, int y) { // linearFilterCurvePoints.add(new Point2D(x, y)); // } // // @Override // public void onNewVectoPointAvailable(int x, int y) { // vectoCurvePoints.add(new Point2D(x, y)); // } // @Override // public void onLastVectoPointAvailable(int x, int y) { // onNewVectoPointAvailable(x, y); // } // }
import com.orange.dgil.trail.app.fxdrawertest.curves.Curves; import java.util.List; import javafx.geometry.Point2D; import javafx.scene.canvas.Canvas; import javafx.scene.canvas.GraphicsContext; import javafx.scene.paint.Color;
private int plumeCurveIndex; public GraphicContextDrawer(GraphicsContext graphicsContext) { this.graphicsContext = graphicsContext; initDrawer(); } private void initDrawer() { graphicsContext.setLineWidth(1); } private void initColor(Color color) { graphicsContext.setFill(color); } public void drawCircle(double x, double y) { graphicsContext.fillOval(x, y, CIRCLE_RADIUS, CIRCLE_RADIUS); } public void clear() { plumeCurveIndex = 0; Canvas canvas = graphicsContext.getCanvas(); graphicsContext.clearRect(0, 0, canvas.getWidth(), canvas.getHeight()); } public void setOffsets(int xOffset, int yOffset) { this.xOffset = xOffset; this.yOffset = yOffset; }
// Path: demo/JavaFxTest/src/main/java/com/orange/dgil/trail/app/fxdrawertest/curves/Curves.java // public class Curves implements LinearWindowFilterListener, VectoFilterListener { // // private boolean rawCurveEnabled; // private boolean linearFilterCurveEnabled; // private boolean vectoCurveEnabled; // private boolean quadCurveEnabled; // // private List<Point2D> rawCurvePoints = new ArrayList<Point2D>(); // private List<Point2D> linearFilterCurvePoints = new ArrayList<Point2D>(); // private List<Point2D> vectoCurvePoints = new ArrayList<Point2D>(); // private List<Point2D> quadCurvePoints = new ArrayList<Point2D>(); // // private final LinearWindowFilter linearWindowFilter = new LinearWindowFilter(this); // private final VectoFilter vectoFilter = new VectoFilter(this); // private final QuadCurve quadCurve = new QuadCurve(true); // // public void clear() { // rawCurvePoints.clear(); // linearFilterCurvePoints.clear(); // vectoCurvePoints.clear(); // quadCurvePoints.clear(); // linearWindowFilter.reset(); // vectoFilter.reset(); // quadCurve.reset(); // } // // public void end() { // TrailPoint lastPoint = linearWindowFilter.getLastPoint(); // linearFilterCurvePoints.add(new Point2D(lastPoint.getX(), lastPoint.getY())); // endVecto(); // endQuadCurve(); // } // // private void endVecto() { // vectoFilter.epilogue(); // } // // private void endQuadCurve() { // quadCurve.epilogue(); // fillQuadCurve(); // } // // // public void addPoint(double x, double y) { // rawCurvePoints.add(new Point2D(x, y)); // addPointToLinearFilter(x, y); // addPointToVecto(x, y); // addPointToQuadCurve(x, y); // } // // private void addPointToLinearFilter(double x, double y) { // linearWindowFilter.addPoint(new TrailPoint((int)x, (int)y)); // } // // private void addPointToVecto(double x, double y) { // vectoFilter.addPoint((int)x, (int)y); // } // // private void addPointToQuadCurve(double x, double y) { // quadCurve.addPoint((int)x, (int)y); // fillQuadCurve(); // } // // private void fillQuadCurve() { // QuadCurveArray quadCurveArray = quadCurve.getQuadCurveArray(); // for (int i = quadCurvePoints.size(); i <= quadCurveArray.getLastPointIndex(); i++) { // TrailPoint p = quadCurveArray.get(i); // quadCurvePoints.add(new Point2D(p.getX(), p.getY())); // } // } // // public boolean isRawCurveEnabled() { // return rawCurveEnabled; // } // public void setRawCurveEnabled(boolean rawCurveEnabled) { // this.rawCurveEnabled = rawCurveEnabled; // } // // public boolean isLinearFilterCurveEnabled() { // return linearFilterCurveEnabled; // } // public void setLinearFilterCurveEnabled(boolean linearFilterCurveEnabled) { // this.linearFilterCurveEnabled = linearFilterCurveEnabled; // } // // public boolean isVectoCurveEnabled() { // return vectoCurveEnabled; // } // public void setVectoCurveEnabled(boolean vectoCurveEnabled) { // this.vectoCurveEnabled = vectoCurveEnabled; // } // // public boolean isQuadCurveEnabled() { // return quadCurveEnabled; // } // public void setQuadCurveEnabled(boolean quadCurveEnabled) { // this.quadCurveEnabled = quadCurveEnabled; // } // // public List<Point2D> getRawCurvePoints() { // return rawCurvePoints; // } // // public List<Point2D> getLinearFilterCurvePoints() { // return linearFilterCurvePoints; // } // // public List<Point2D> getVectoCurvePoints() { // return vectoCurvePoints; // } // // public List<Point2D> getQuadCurvePoints() { // return quadCurvePoints; // } // // public void setVectoErrorPixels(int error) { // vectoFilter.getVectoSettings().setVectorsHeightThreshold(error); // } // public void setVectoWindowSize(int windowSize) { // vectoFilter.getVectoSettings().setWindowSize(windowSize); // } // // @Override // public void onNewFilteredPointAvailable(int x, int y) { // linearFilterCurvePoints.add(new Point2D(x, y)); // } // // @Override // public void onNewVectoPointAvailable(int x, int y) { // vectoCurvePoints.add(new Point2D(x, y)); // } // @Override // public void onLastVectoPointAvailable(int x, int y) { // onNewVectoPointAvailable(x, y); // } // } // Path: demo/JavaFxTest/src/main/java/com/orange/dgil/trail/app/fxdrawertest/drawer/GraphicContextDrawer.java import com.orange.dgil.trail.app.fxdrawertest.curves.Curves; import java.util.List; import javafx.geometry.Point2D; import javafx.scene.canvas.Canvas; import javafx.scene.canvas.GraphicsContext; import javafx.scene.paint.Color; private int plumeCurveIndex; public GraphicContextDrawer(GraphicsContext graphicsContext) { this.graphicsContext = graphicsContext; initDrawer(); } private void initDrawer() { graphicsContext.setLineWidth(1); } private void initColor(Color color) { graphicsContext.setFill(color); } public void drawCircle(double x, double y) { graphicsContext.fillOval(x, y, CIRCLE_RADIUS, CIRCLE_RADIUS); } public void clear() { plumeCurveIndex = 0; Canvas canvas = graphicsContext.getCanvas(); graphicsContext.clearRect(0, 0, canvas.getWidth(), canvas.getHeight()); } public void setOffsets(int xOffset, int yOffset) { this.xOffset = xOffset; this.yOffset = yOffset; }
public void draw(Curves curves) {
Orange-OpenSource/android-trail-drawing
src/main/java/com/orange/dgil/trail/android/drawingtool/markerpen/Painters.java
// Path: src/main/java/com/orange/dgil/trail/android/drawingtool/TrailOptions.java // @Getter // public class TrailOptions { // @Getter(AccessLevel.NONE) // private DrawingTools drawingTools; // @Getter(AccessLevel.NONE) // private AndroidMetrics metrics; // // @Setter // private int color = DefaultDrawerConf.TRAIL_COLOR; // @Setter // private int shadowColor; // // private QuillParameters quillParameters; // // private boolean shadowEnabled; // private int shadowOffsetPixels; // private int widthPixels; // // public TrailOptions(AndroidMetrics metrics, DrawingTools drawingTools) { // init(metrics, drawingTools); // } // // private void init(AndroidMetrics metrics, DrawingTools drawingTools) { // this.metrics = metrics; // this.drawingTools = drawingTools; // quillParameters = new QuillParameters(metrics); // setTrailWidthMicrometers(DefaultDrawerConf.TRAIL_WIDTH_UM); // } // // public void setTrailWidthMicrometers(int micrometers) { // widthPixels = metrics.micrometersToPixels(micrometers); // shadowOffsetPixels = (int) (widthPixels * DefaultDrawerConf.SHADOW_OFFSET_FACTOR); // } // // public boolean isShadowAvailable() { // return android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH; // } // // public void setShadowEnabled(boolean shadowEnabled) { // this.shadowEnabled = shadowEnabled && isShadowAvailable(); // } // // public void selectMarkerPen() { // drawingTools.selectMarkerPen(); // } // // public void selectQuillPen() { // drawingTools.selectQuillPen(); // } // } // // Path: src/main/java/com/orange/dgil/trail/android/animation/AnimManager.java // public class AnimManager { // // private final AnimRunnable animRunnable; // private final AnimParameters animParameters = new AnimParameters(); // // public AnimManager(IAnimDrawer drawer) { // animRunnable = new AnimRunnable(drawer, animParameters); // } // // public void start() { // animRunnable.start(); // } // // public int getAnimColor() { // int startColor = animParameters.getStartColor(); // int endColor = animParameters.getEndColor(); // return getInterpolatedColor(startColor, endColor, animRunnable.getFactor()); // } // // public int getAnimShadowColor() { // int startColor = animParameters.getShadowStartColor(); // int endColor = animParameters.getShadowEndColor(); // return getInterpolatedColor(startColor, endColor, animRunnable.getFactor()); // } // // private int getInterpolatedColor(int startColor, int endColor, float factor) { // return Color.argb( // getInterp(Color.alpha(startColor), Color.alpha(endColor), factor), // getInterp(Color.red (startColor), Color.red (endColor), factor), // getInterp(Color.green(startColor), Color.green(endColor), factor), // getInterp(Color.blue (startColor), Color.blue (endColor), factor)); // } // private int getInterp(int start, int end, float factor) { // return (int) (start * factor + end * (1 - factor)); // } // // // public float getFactor() { // return animRunnable.getFactor(); // } // // /** // * The width factor is made to dilate the trail during fading // * @return the width factor // */ // public float getWidthFactor() { // float factor = getFactor(); // return 1 + animParameters.getWidthDilatationFactor() * (1-factor); // } // // public void reset() { // animRunnable.reset(); // } // // public AnimParameters getAnimationParameters() { // return animParameters; // } // // public boolean isRunning() { // return animRunnable.isRunning(); // } // // public boolean isAlphaAnimationRunning() { // return isRunning() && animParameters.areStartEndColorsRgbEqual(); // } // }
import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Path; import com.orange.dgil.trail.android.drawingtool.TrailOptions; import com.orange.dgil.trail.android.animation.AnimManager;
/** * Trail drawing library * Copyright (C) 2014 Orange * Authors: christophe.maldivi@orange.com, eric.petit@orange.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.orange.dgil.trail.android.drawingtool.markerpen; class Painters { private final Paint painter = new Paint(); private final Path shadowPath = new Path();
// Path: src/main/java/com/orange/dgil/trail/android/drawingtool/TrailOptions.java // @Getter // public class TrailOptions { // @Getter(AccessLevel.NONE) // private DrawingTools drawingTools; // @Getter(AccessLevel.NONE) // private AndroidMetrics metrics; // // @Setter // private int color = DefaultDrawerConf.TRAIL_COLOR; // @Setter // private int shadowColor; // // private QuillParameters quillParameters; // // private boolean shadowEnabled; // private int shadowOffsetPixels; // private int widthPixels; // // public TrailOptions(AndroidMetrics metrics, DrawingTools drawingTools) { // init(metrics, drawingTools); // } // // private void init(AndroidMetrics metrics, DrawingTools drawingTools) { // this.metrics = metrics; // this.drawingTools = drawingTools; // quillParameters = new QuillParameters(metrics); // setTrailWidthMicrometers(DefaultDrawerConf.TRAIL_WIDTH_UM); // } // // public void setTrailWidthMicrometers(int micrometers) { // widthPixels = metrics.micrometersToPixels(micrometers); // shadowOffsetPixels = (int) (widthPixels * DefaultDrawerConf.SHADOW_OFFSET_FACTOR); // } // // public boolean isShadowAvailable() { // return android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH; // } // // public void setShadowEnabled(boolean shadowEnabled) { // this.shadowEnabled = shadowEnabled && isShadowAvailable(); // } // // public void selectMarkerPen() { // drawingTools.selectMarkerPen(); // } // // public void selectQuillPen() { // drawingTools.selectQuillPen(); // } // } // // Path: src/main/java/com/orange/dgil/trail/android/animation/AnimManager.java // public class AnimManager { // // private final AnimRunnable animRunnable; // private final AnimParameters animParameters = new AnimParameters(); // // public AnimManager(IAnimDrawer drawer) { // animRunnable = new AnimRunnable(drawer, animParameters); // } // // public void start() { // animRunnable.start(); // } // // public int getAnimColor() { // int startColor = animParameters.getStartColor(); // int endColor = animParameters.getEndColor(); // return getInterpolatedColor(startColor, endColor, animRunnable.getFactor()); // } // // public int getAnimShadowColor() { // int startColor = animParameters.getShadowStartColor(); // int endColor = animParameters.getShadowEndColor(); // return getInterpolatedColor(startColor, endColor, animRunnable.getFactor()); // } // // private int getInterpolatedColor(int startColor, int endColor, float factor) { // return Color.argb( // getInterp(Color.alpha(startColor), Color.alpha(endColor), factor), // getInterp(Color.red (startColor), Color.red (endColor), factor), // getInterp(Color.green(startColor), Color.green(endColor), factor), // getInterp(Color.blue (startColor), Color.blue (endColor), factor)); // } // private int getInterp(int start, int end, float factor) { // return (int) (start * factor + end * (1 - factor)); // } // // // public float getFactor() { // return animRunnable.getFactor(); // } // // /** // * The width factor is made to dilate the trail during fading // * @return the width factor // */ // public float getWidthFactor() { // float factor = getFactor(); // return 1 + animParameters.getWidthDilatationFactor() * (1-factor); // } // // public void reset() { // animRunnable.reset(); // } // // public AnimParameters getAnimationParameters() { // return animParameters; // } // // public boolean isRunning() { // return animRunnable.isRunning(); // } // // public boolean isAlphaAnimationRunning() { // return isRunning() && animParameters.areStartEndColorsRgbEqual(); // } // } // Path: src/main/java/com/orange/dgil/trail/android/drawingtool/markerpen/Painters.java import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Path; import com.orange.dgil.trail.android.drawingtool.TrailOptions; import com.orange.dgil.trail.android.animation.AnimManager; /** * Trail drawing library * Copyright (C) 2014 Orange * Authors: christophe.maldivi@orange.com, eric.petit@orange.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.orange.dgil.trail.android.drawingtool.markerpen; class Painters { private final Paint painter = new Paint(); private final Path shadowPath = new Path();
private final AnimManager animManager;
Orange-OpenSource/android-trail-drawing
src/main/java/com/orange/dgil/trail/android/drawingtool/markerpen/Painters.java
// Path: src/main/java/com/orange/dgil/trail/android/drawingtool/TrailOptions.java // @Getter // public class TrailOptions { // @Getter(AccessLevel.NONE) // private DrawingTools drawingTools; // @Getter(AccessLevel.NONE) // private AndroidMetrics metrics; // // @Setter // private int color = DefaultDrawerConf.TRAIL_COLOR; // @Setter // private int shadowColor; // // private QuillParameters quillParameters; // // private boolean shadowEnabled; // private int shadowOffsetPixels; // private int widthPixels; // // public TrailOptions(AndroidMetrics metrics, DrawingTools drawingTools) { // init(metrics, drawingTools); // } // // private void init(AndroidMetrics metrics, DrawingTools drawingTools) { // this.metrics = metrics; // this.drawingTools = drawingTools; // quillParameters = new QuillParameters(metrics); // setTrailWidthMicrometers(DefaultDrawerConf.TRAIL_WIDTH_UM); // } // // public void setTrailWidthMicrometers(int micrometers) { // widthPixels = metrics.micrometersToPixels(micrometers); // shadowOffsetPixels = (int) (widthPixels * DefaultDrawerConf.SHADOW_OFFSET_FACTOR); // } // // public boolean isShadowAvailable() { // return android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH; // } // // public void setShadowEnabled(boolean shadowEnabled) { // this.shadowEnabled = shadowEnabled && isShadowAvailable(); // } // // public void selectMarkerPen() { // drawingTools.selectMarkerPen(); // } // // public void selectQuillPen() { // drawingTools.selectQuillPen(); // } // } // // Path: src/main/java/com/orange/dgil/trail/android/animation/AnimManager.java // public class AnimManager { // // private final AnimRunnable animRunnable; // private final AnimParameters animParameters = new AnimParameters(); // // public AnimManager(IAnimDrawer drawer) { // animRunnable = new AnimRunnable(drawer, animParameters); // } // // public void start() { // animRunnable.start(); // } // // public int getAnimColor() { // int startColor = animParameters.getStartColor(); // int endColor = animParameters.getEndColor(); // return getInterpolatedColor(startColor, endColor, animRunnable.getFactor()); // } // // public int getAnimShadowColor() { // int startColor = animParameters.getShadowStartColor(); // int endColor = animParameters.getShadowEndColor(); // return getInterpolatedColor(startColor, endColor, animRunnable.getFactor()); // } // // private int getInterpolatedColor(int startColor, int endColor, float factor) { // return Color.argb( // getInterp(Color.alpha(startColor), Color.alpha(endColor), factor), // getInterp(Color.red (startColor), Color.red (endColor), factor), // getInterp(Color.green(startColor), Color.green(endColor), factor), // getInterp(Color.blue (startColor), Color.blue (endColor), factor)); // } // private int getInterp(int start, int end, float factor) { // return (int) (start * factor + end * (1 - factor)); // } // // // public float getFactor() { // return animRunnable.getFactor(); // } // // /** // * The width factor is made to dilate the trail during fading // * @return the width factor // */ // public float getWidthFactor() { // float factor = getFactor(); // return 1 + animParameters.getWidthDilatationFactor() * (1-factor); // } // // public void reset() { // animRunnable.reset(); // } // // public AnimParameters getAnimationParameters() { // return animParameters; // } // // public boolean isRunning() { // return animRunnable.isRunning(); // } // // public boolean isAlphaAnimationRunning() { // return isRunning() && animParameters.areStartEndColorsRgbEqual(); // } // }
import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Path; import com.orange.dgil.trail.android.drawingtool.TrailOptions; import com.orange.dgil.trail.android.animation.AnimManager;
/** * Trail drawing library * Copyright (C) 2014 Orange * Authors: christophe.maldivi@orange.com, eric.petit@orange.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.orange.dgil.trail.android.drawingtool.markerpen; class Painters { private final Paint painter = new Paint(); private final Path shadowPath = new Path(); private final AnimManager animManager; private Paint shadowPainter;
// Path: src/main/java/com/orange/dgil/trail/android/drawingtool/TrailOptions.java // @Getter // public class TrailOptions { // @Getter(AccessLevel.NONE) // private DrawingTools drawingTools; // @Getter(AccessLevel.NONE) // private AndroidMetrics metrics; // // @Setter // private int color = DefaultDrawerConf.TRAIL_COLOR; // @Setter // private int shadowColor; // // private QuillParameters quillParameters; // // private boolean shadowEnabled; // private int shadowOffsetPixels; // private int widthPixels; // // public TrailOptions(AndroidMetrics metrics, DrawingTools drawingTools) { // init(metrics, drawingTools); // } // // private void init(AndroidMetrics metrics, DrawingTools drawingTools) { // this.metrics = metrics; // this.drawingTools = drawingTools; // quillParameters = new QuillParameters(metrics); // setTrailWidthMicrometers(DefaultDrawerConf.TRAIL_WIDTH_UM); // } // // public void setTrailWidthMicrometers(int micrometers) { // widthPixels = metrics.micrometersToPixels(micrometers); // shadowOffsetPixels = (int) (widthPixels * DefaultDrawerConf.SHADOW_OFFSET_FACTOR); // } // // public boolean isShadowAvailable() { // return android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH; // } // // public void setShadowEnabled(boolean shadowEnabled) { // this.shadowEnabled = shadowEnabled && isShadowAvailable(); // } // // public void selectMarkerPen() { // drawingTools.selectMarkerPen(); // } // // public void selectQuillPen() { // drawingTools.selectQuillPen(); // } // } // // Path: src/main/java/com/orange/dgil/trail/android/animation/AnimManager.java // public class AnimManager { // // private final AnimRunnable animRunnable; // private final AnimParameters animParameters = new AnimParameters(); // // public AnimManager(IAnimDrawer drawer) { // animRunnable = new AnimRunnable(drawer, animParameters); // } // // public void start() { // animRunnable.start(); // } // // public int getAnimColor() { // int startColor = animParameters.getStartColor(); // int endColor = animParameters.getEndColor(); // return getInterpolatedColor(startColor, endColor, animRunnable.getFactor()); // } // // public int getAnimShadowColor() { // int startColor = animParameters.getShadowStartColor(); // int endColor = animParameters.getShadowEndColor(); // return getInterpolatedColor(startColor, endColor, animRunnable.getFactor()); // } // // private int getInterpolatedColor(int startColor, int endColor, float factor) { // return Color.argb( // getInterp(Color.alpha(startColor), Color.alpha(endColor), factor), // getInterp(Color.red (startColor), Color.red (endColor), factor), // getInterp(Color.green(startColor), Color.green(endColor), factor), // getInterp(Color.blue (startColor), Color.blue (endColor), factor)); // } // private int getInterp(int start, int end, float factor) { // return (int) (start * factor + end * (1 - factor)); // } // // // public float getFactor() { // return animRunnable.getFactor(); // } // // /** // * The width factor is made to dilate the trail during fading // * @return the width factor // */ // public float getWidthFactor() { // float factor = getFactor(); // return 1 + animParameters.getWidthDilatationFactor() * (1-factor); // } // // public void reset() { // animRunnable.reset(); // } // // public AnimParameters getAnimationParameters() { // return animParameters; // } // // public boolean isRunning() { // return animRunnable.isRunning(); // } // // public boolean isAlphaAnimationRunning() { // return isRunning() && animParameters.areStartEndColorsRgbEqual(); // } // } // Path: src/main/java/com/orange/dgil/trail/android/drawingtool/markerpen/Painters.java import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Path; import com.orange.dgil.trail.android.drawingtool.TrailOptions; import com.orange.dgil.trail.android.animation.AnimManager; /** * Trail drawing library * Copyright (C) 2014 Orange * Authors: christophe.maldivi@orange.com, eric.petit@orange.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.orange.dgil.trail.android.drawingtool.markerpen; class Painters { private final Paint painter = new Paint(); private final Path shadowPath = new Path(); private final AnimManager animManager; private Paint shadowPainter;
private final TrailOptions trailOptions;
Orange-OpenSource/android-trail-drawing
src/test/java/com/orange/dgil/trail/core/vecto/linearwindowfilter/LinearWindowFilterGetMeanXYTest.java
// Path: src/main/java/com/orange/dgil/trail/core/common/TrailPoint.java // @Getter // @NoArgsConstructor // public class TrailPoint { // private int x = -1; // private int y = -1; // // public TrailPoint(int x, int y) { // set(x, y); // } // // public void set(int x, int y) { // this.x = x; // this.y = y; // } // // public boolean isSameAs(TrailPoint point) { // return x == point.x && y == point.y; // } // // public double getDistanceTo(TrailPoint point) { // int dx = x - point.getX(); // int dy = y - point.getY(); // return Math.sqrt(dx * dx + dy * dy); // } // // public void deepCopy(TrailPoint point) { // x = point.x; // y = point.y; // } // } // // Path: src/main/java/com/orange/dgil/trail/core/vecto/SlidingWindow.java // public class SlidingWindow { // // private TrailPoint[] points; // // @Getter // private int addedElementsNumber; // // public SlidingWindow(int windowSize) { // setWindowSize(windowSize); // } // // public void setWindowSize(int windowSize) { // points = new TrailPoint[windowSize]; // allocatePoints(); // } // // public int getWindowSize() { // return points.length; // } // // private void allocatePoints() { // for (int i = 0; i < points.length; i++) { // points[i] = new TrailPoint(); // } // } // // public void reset() { // addedElementsNumber = 0; // } // // public void add(int x, int y) { // if (isFull()) { // slidePointsToTheLeft(); // } // doAdd(x, y); // } // // public void add(TrailPoint point) { // add(point.getX(), point.getY()); // } // // public int getX(int index) { // if (isIndexValid(index)) { // return points[index].getX(); // } else { // throw new SlidingWindowIndexException(String.format("Invalid index '%d' (max index %d)", index, getMaxIndex())); // } // } // // public int getY(int index) { // if (isIndexValid(index)) { // return points[index].getY(); // } else { // throw getInvalidIndexException(index); // } // } // // boolean isIndexValid(int index) { // return index >= 0 && index <= getMaxIndex(); // } // // int getMaxIndex() { // return Math.min(addedElementsNumber, points.length) - 1; // } // // void slidePointsToTheLeft() { // TrailPoint p0 = points[0]; // for (int i = 0; i < points.length-1; i++) { // points[i] = points[i+1]; // } // points[points.length-1] = p0; // } // // void doAdd(int x, int y) { // points[getInsertIndex()].set(x, y); // addedElementsNumber++; // } // // public TrailPoint getElementAt(int index) { // if (isIndexValid(index)) { // return points[index]; // } else { // throw getInvalidIndexException(index); // } // } // // public TrailPoint getLastElement() { // return getElementAt(getLastElementIndex()); // } // // public boolean isSameAsLast(TrailPoint p) { // if (addedElementsNumber == 0) { // return false; // } else { // return p.isSameAs(points[getLastElementIndex()]); // } // } // // int getInsertIndex() { // return Math.min(addedElementsNumber, points.length - 1); // } // // public int getLastElementIndex() { // return Math.min(addedElementsNumber - 1, points.length - 1); // } // // public boolean isFull() { // return addedElementsNumber >= points.length; // } // // public void removeElementsAtLeftOf(int index) { // if (isIndexValid(index)) { // doRemoveElementsAtLeftOf(index); // } else { // throw getInvalidIndexException(index); // } // } // // private void doRemoveElementsAtLeftOf(int index) { // for (int i = 0; i <= getLastElementIndex()-index; i++) { // int sourceIndex = index + i; // shiftPoint(i, sourceIndex); // } // addedElementsNumber -= index; // } // // private void shiftPoint(int destIndex, int sourceIndex) { // if (sourceIndex < points.length) { // TrailPoint source = points[sourceIndex]; // points[destIndex].set(source.getX(), source.getY()); // } // } // // private SlidingWindowIndexException getInvalidIndexException(int index) { // return new SlidingWindowIndexException(String.format("Invalid index '%d' (max index %d)", index, getMaxIndex())); // } // }
import com.orange.dgil.trail.TestTools; import com.orange.dgil.trail.core.common.TrailPoint; import com.orange.dgil.trail.core.vecto.SlidingWindow; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito;
/** * Trail drawing library * Copyright (C) 2014 Orange * Authors: christophe.maldivi@orange.com, eric.petit@orange.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.orange.dgil.trail.core.vecto.linearwindowfilter; public class LinearWindowFilterGetMeanXYTest { private LinearWindowFilter filter; @Before public void setUp() { filter = Mockito.mock(LinearWindowFilter.class); } @Test public void shouldGetMeanX() throws IllegalAccessException { // given int[] windowWeights = {1, 2, 1}; TestTools.setObj("windowWeights", LinearWindowFilter.class, filter, windowWeights); TestTools.setObj("weightsSum", LinearWindowFilter.class, filter, 4);
// Path: src/main/java/com/orange/dgil/trail/core/common/TrailPoint.java // @Getter // @NoArgsConstructor // public class TrailPoint { // private int x = -1; // private int y = -1; // // public TrailPoint(int x, int y) { // set(x, y); // } // // public void set(int x, int y) { // this.x = x; // this.y = y; // } // // public boolean isSameAs(TrailPoint point) { // return x == point.x && y == point.y; // } // // public double getDistanceTo(TrailPoint point) { // int dx = x - point.getX(); // int dy = y - point.getY(); // return Math.sqrt(dx * dx + dy * dy); // } // // public void deepCopy(TrailPoint point) { // x = point.x; // y = point.y; // } // } // // Path: src/main/java/com/orange/dgil/trail/core/vecto/SlidingWindow.java // public class SlidingWindow { // // private TrailPoint[] points; // // @Getter // private int addedElementsNumber; // // public SlidingWindow(int windowSize) { // setWindowSize(windowSize); // } // // public void setWindowSize(int windowSize) { // points = new TrailPoint[windowSize]; // allocatePoints(); // } // // public int getWindowSize() { // return points.length; // } // // private void allocatePoints() { // for (int i = 0; i < points.length; i++) { // points[i] = new TrailPoint(); // } // } // // public void reset() { // addedElementsNumber = 0; // } // // public void add(int x, int y) { // if (isFull()) { // slidePointsToTheLeft(); // } // doAdd(x, y); // } // // public void add(TrailPoint point) { // add(point.getX(), point.getY()); // } // // public int getX(int index) { // if (isIndexValid(index)) { // return points[index].getX(); // } else { // throw new SlidingWindowIndexException(String.format("Invalid index '%d' (max index %d)", index, getMaxIndex())); // } // } // // public int getY(int index) { // if (isIndexValid(index)) { // return points[index].getY(); // } else { // throw getInvalidIndexException(index); // } // } // // boolean isIndexValid(int index) { // return index >= 0 && index <= getMaxIndex(); // } // // int getMaxIndex() { // return Math.min(addedElementsNumber, points.length) - 1; // } // // void slidePointsToTheLeft() { // TrailPoint p0 = points[0]; // for (int i = 0; i < points.length-1; i++) { // points[i] = points[i+1]; // } // points[points.length-1] = p0; // } // // void doAdd(int x, int y) { // points[getInsertIndex()].set(x, y); // addedElementsNumber++; // } // // public TrailPoint getElementAt(int index) { // if (isIndexValid(index)) { // return points[index]; // } else { // throw getInvalidIndexException(index); // } // } // // public TrailPoint getLastElement() { // return getElementAt(getLastElementIndex()); // } // // public boolean isSameAsLast(TrailPoint p) { // if (addedElementsNumber == 0) { // return false; // } else { // return p.isSameAs(points[getLastElementIndex()]); // } // } // // int getInsertIndex() { // return Math.min(addedElementsNumber, points.length - 1); // } // // public int getLastElementIndex() { // return Math.min(addedElementsNumber - 1, points.length - 1); // } // // public boolean isFull() { // return addedElementsNumber >= points.length; // } // // public void removeElementsAtLeftOf(int index) { // if (isIndexValid(index)) { // doRemoveElementsAtLeftOf(index); // } else { // throw getInvalidIndexException(index); // } // } // // private void doRemoveElementsAtLeftOf(int index) { // for (int i = 0; i <= getLastElementIndex()-index; i++) { // int sourceIndex = index + i; // shiftPoint(i, sourceIndex); // } // addedElementsNumber -= index; // } // // private void shiftPoint(int destIndex, int sourceIndex) { // if (sourceIndex < points.length) { // TrailPoint source = points[sourceIndex]; // points[destIndex].set(source.getX(), source.getY()); // } // } // // private SlidingWindowIndexException getInvalidIndexException(int index) { // return new SlidingWindowIndexException(String.format("Invalid index '%d' (max index %d)", index, getMaxIndex())); // } // } // Path: src/test/java/com/orange/dgil/trail/core/vecto/linearwindowfilter/LinearWindowFilterGetMeanXYTest.java import com.orange.dgil.trail.TestTools; import com.orange.dgil.trail.core.common.TrailPoint; import com.orange.dgil.trail.core.vecto.SlidingWindow; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; /** * Trail drawing library * Copyright (C) 2014 Orange * Authors: christophe.maldivi@orange.com, eric.petit@orange.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.orange.dgil.trail.core.vecto.linearwindowfilter; public class LinearWindowFilterGetMeanXYTest { private LinearWindowFilter filter; @Before public void setUp() { filter = Mockito.mock(LinearWindowFilter.class); } @Test public void shouldGetMeanX() throws IllegalAccessException { // given int[] windowWeights = {1, 2, 1}; TestTools.setObj("windowWeights", LinearWindowFilter.class, filter, windowWeights); TestTools.setObj("weightsSum", LinearWindowFilter.class, filter, 4);
SlidingWindow slidingWindow = new SlidingWindow(windowWeights.length);
Orange-OpenSource/android-trail-drawing
src/test/java/com/orange/dgil/trail/core/vecto/linearwindowfilter/LinearWindowFilterAddPointTest.java
// Path: src/main/java/com/orange/dgil/trail/core/common/TrailPoint.java // @Getter // @NoArgsConstructor // public class TrailPoint { // private int x = -1; // private int y = -1; // // public TrailPoint(int x, int y) { // set(x, y); // } // // public void set(int x, int y) { // this.x = x; // this.y = y; // } // // public boolean isSameAs(TrailPoint point) { // return x == point.x && y == point.y; // } // // public double getDistanceTo(TrailPoint point) { // int dx = x - point.getX(); // int dy = y - point.getY(); // return Math.sqrt(dx * dx + dy * dy); // } // // public void deepCopy(TrailPoint point) { // x = point.x; // y = point.y; // } // } // // Path: src/main/java/com/orange/dgil/trail/core/vecto/SlidingWindow.java // public class SlidingWindow { // // private TrailPoint[] points; // // @Getter // private int addedElementsNumber; // // public SlidingWindow(int windowSize) { // setWindowSize(windowSize); // } // // public void setWindowSize(int windowSize) { // points = new TrailPoint[windowSize]; // allocatePoints(); // } // // public int getWindowSize() { // return points.length; // } // // private void allocatePoints() { // for (int i = 0; i < points.length; i++) { // points[i] = new TrailPoint(); // } // } // // public void reset() { // addedElementsNumber = 0; // } // // public void add(int x, int y) { // if (isFull()) { // slidePointsToTheLeft(); // } // doAdd(x, y); // } // // public void add(TrailPoint point) { // add(point.getX(), point.getY()); // } // // public int getX(int index) { // if (isIndexValid(index)) { // return points[index].getX(); // } else { // throw new SlidingWindowIndexException(String.format("Invalid index '%d' (max index %d)", index, getMaxIndex())); // } // } // // public int getY(int index) { // if (isIndexValid(index)) { // return points[index].getY(); // } else { // throw getInvalidIndexException(index); // } // } // // boolean isIndexValid(int index) { // return index >= 0 && index <= getMaxIndex(); // } // // int getMaxIndex() { // return Math.min(addedElementsNumber, points.length) - 1; // } // // void slidePointsToTheLeft() { // TrailPoint p0 = points[0]; // for (int i = 0; i < points.length-1; i++) { // points[i] = points[i+1]; // } // points[points.length-1] = p0; // } // // void doAdd(int x, int y) { // points[getInsertIndex()].set(x, y); // addedElementsNumber++; // } // // public TrailPoint getElementAt(int index) { // if (isIndexValid(index)) { // return points[index]; // } else { // throw getInvalidIndexException(index); // } // } // // public TrailPoint getLastElement() { // return getElementAt(getLastElementIndex()); // } // // public boolean isSameAsLast(TrailPoint p) { // if (addedElementsNumber == 0) { // return false; // } else { // return p.isSameAs(points[getLastElementIndex()]); // } // } // // int getInsertIndex() { // return Math.min(addedElementsNumber, points.length - 1); // } // // public int getLastElementIndex() { // return Math.min(addedElementsNumber - 1, points.length - 1); // } // // public boolean isFull() { // return addedElementsNumber >= points.length; // } // // public void removeElementsAtLeftOf(int index) { // if (isIndexValid(index)) { // doRemoveElementsAtLeftOf(index); // } else { // throw getInvalidIndexException(index); // } // } // // private void doRemoveElementsAtLeftOf(int index) { // for (int i = 0; i <= getLastElementIndex()-index; i++) { // int sourceIndex = index + i; // shiftPoint(i, sourceIndex); // } // addedElementsNumber -= index; // } // // private void shiftPoint(int destIndex, int sourceIndex) { // if (sourceIndex < points.length) { // TrailPoint source = points[sourceIndex]; // points[destIndex].set(source.getX(), source.getY()); // } // } // // private SlidingWindowIndexException getInvalidIndexException(int index) { // return new SlidingWindowIndexException(String.format("Invalid index '%d' (max index %d)", index, getMaxIndex())); // } // }
import com.orange.dgil.trail.TestTools; import com.orange.dgil.trail.core.common.TrailPoint; import com.orange.dgil.trail.core.vecto.SlidingWindow; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito;
/** * Trail drawing library * Copyright (C) 2014 Orange * Authors: christophe.maldivi@orange.com, eric.petit@orange.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.orange.dgil.trail.core.vecto.linearwindowfilter; public class LinearWindowFilterAddPointTest { private LinearWindowFilter filter; @Before public void setUp() { filter = Mockito.mock(LinearWindowFilter.class); } @Test public void shouldAddPointWhenSameAsLast() throws IllegalAccessException { // given boolean sameAsLast = true;
// Path: src/main/java/com/orange/dgil/trail/core/common/TrailPoint.java // @Getter // @NoArgsConstructor // public class TrailPoint { // private int x = -1; // private int y = -1; // // public TrailPoint(int x, int y) { // set(x, y); // } // // public void set(int x, int y) { // this.x = x; // this.y = y; // } // // public boolean isSameAs(TrailPoint point) { // return x == point.x && y == point.y; // } // // public double getDistanceTo(TrailPoint point) { // int dx = x - point.getX(); // int dy = y - point.getY(); // return Math.sqrt(dx * dx + dy * dy); // } // // public void deepCopy(TrailPoint point) { // x = point.x; // y = point.y; // } // } // // Path: src/main/java/com/orange/dgil/trail/core/vecto/SlidingWindow.java // public class SlidingWindow { // // private TrailPoint[] points; // // @Getter // private int addedElementsNumber; // // public SlidingWindow(int windowSize) { // setWindowSize(windowSize); // } // // public void setWindowSize(int windowSize) { // points = new TrailPoint[windowSize]; // allocatePoints(); // } // // public int getWindowSize() { // return points.length; // } // // private void allocatePoints() { // for (int i = 0; i < points.length; i++) { // points[i] = new TrailPoint(); // } // } // // public void reset() { // addedElementsNumber = 0; // } // // public void add(int x, int y) { // if (isFull()) { // slidePointsToTheLeft(); // } // doAdd(x, y); // } // // public void add(TrailPoint point) { // add(point.getX(), point.getY()); // } // // public int getX(int index) { // if (isIndexValid(index)) { // return points[index].getX(); // } else { // throw new SlidingWindowIndexException(String.format("Invalid index '%d' (max index %d)", index, getMaxIndex())); // } // } // // public int getY(int index) { // if (isIndexValid(index)) { // return points[index].getY(); // } else { // throw getInvalidIndexException(index); // } // } // // boolean isIndexValid(int index) { // return index >= 0 && index <= getMaxIndex(); // } // // int getMaxIndex() { // return Math.min(addedElementsNumber, points.length) - 1; // } // // void slidePointsToTheLeft() { // TrailPoint p0 = points[0]; // for (int i = 0; i < points.length-1; i++) { // points[i] = points[i+1]; // } // points[points.length-1] = p0; // } // // void doAdd(int x, int y) { // points[getInsertIndex()].set(x, y); // addedElementsNumber++; // } // // public TrailPoint getElementAt(int index) { // if (isIndexValid(index)) { // return points[index]; // } else { // throw getInvalidIndexException(index); // } // } // // public TrailPoint getLastElement() { // return getElementAt(getLastElementIndex()); // } // // public boolean isSameAsLast(TrailPoint p) { // if (addedElementsNumber == 0) { // return false; // } else { // return p.isSameAs(points[getLastElementIndex()]); // } // } // // int getInsertIndex() { // return Math.min(addedElementsNumber, points.length - 1); // } // // public int getLastElementIndex() { // return Math.min(addedElementsNumber - 1, points.length - 1); // } // // public boolean isFull() { // return addedElementsNumber >= points.length; // } // // public void removeElementsAtLeftOf(int index) { // if (isIndexValid(index)) { // doRemoveElementsAtLeftOf(index); // } else { // throw getInvalidIndexException(index); // } // } // // private void doRemoveElementsAtLeftOf(int index) { // for (int i = 0; i <= getLastElementIndex()-index; i++) { // int sourceIndex = index + i; // shiftPoint(i, sourceIndex); // } // addedElementsNumber -= index; // } // // private void shiftPoint(int destIndex, int sourceIndex) { // if (sourceIndex < points.length) { // TrailPoint source = points[sourceIndex]; // points[destIndex].set(source.getX(), source.getY()); // } // } // // private SlidingWindowIndexException getInvalidIndexException(int index) { // return new SlidingWindowIndexException(String.format("Invalid index '%d' (max index %d)", index, getMaxIndex())); // } // } // Path: src/test/java/com/orange/dgil/trail/core/vecto/linearwindowfilter/LinearWindowFilterAddPointTest.java import com.orange.dgil.trail.TestTools; import com.orange.dgil.trail.core.common.TrailPoint; import com.orange.dgil.trail.core.vecto.SlidingWindow; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; /** * Trail drawing library * Copyright (C) 2014 Orange * Authors: christophe.maldivi@orange.com, eric.petit@orange.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.orange.dgil.trail.core.vecto.linearwindowfilter; public class LinearWindowFilterAddPointTest { private LinearWindowFilter filter; @Before public void setUp() { filter = Mockito.mock(LinearWindowFilter.class); } @Test public void shouldAddPointWhenSameAsLast() throws IllegalAccessException { // given boolean sameAsLast = true;
TrailPoint point = new TrailPoint();
Orange-OpenSource/android-trail-drawing
src/test/java/com/orange/dgil/trail/core/vecto/linearwindowfilter/LinearWindowFilterAddPointTest.java
// Path: src/main/java/com/orange/dgil/trail/core/common/TrailPoint.java // @Getter // @NoArgsConstructor // public class TrailPoint { // private int x = -1; // private int y = -1; // // public TrailPoint(int x, int y) { // set(x, y); // } // // public void set(int x, int y) { // this.x = x; // this.y = y; // } // // public boolean isSameAs(TrailPoint point) { // return x == point.x && y == point.y; // } // // public double getDistanceTo(TrailPoint point) { // int dx = x - point.getX(); // int dy = y - point.getY(); // return Math.sqrt(dx * dx + dy * dy); // } // // public void deepCopy(TrailPoint point) { // x = point.x; // y = point.y; // } // } // // Path: src/main/java/com/orange/dgil/trail/core/vecto/SlidingWindow.java // public class SlidingWindow { // // private TrailPoint[] points; // // @Getter // private int addedElementsNumber; // // public SlidingWindow(int windowSize) { // setWindowSize(windowSize); // } // // public void setWindowSize(int windowSize) { // points = new TrailPoint[windowSize]; // allocatePoints(); // } // // public int getWindowSize() { // return points.length; // } // // private void allocatePoints() { // for (int i = 0; i < points.length; i++) { // points[i] = new TrailPoint(); // } // } // // public void reset() { // addedElementsNumber = 0; // } // // public void add(int x, int y) { // if (isFull()) { // slidePointsToTheLeft(); // } // doAdd(x, y); // } // // public void add(TrailPoint point) { // add(point.getX(), point.getY()); // } // // public int getX(int index) { // if (isIndexValid(index)) { // return points[index].getX(); // } else { // throw new SlidingWindowIndexException(String.format("Invalid index '%d' (max index %d)", index, getMaxIndex())); // } // } // // public int getY(int index) { // if (isIndexValid(index)) { // return points[index].getY(); // } else { // throw getInvalidIndexException(index); // } // } // // boolean isIndexValid(int index) { // return index >= 0 && index <= getMaxIndex(); // } // // int getMaxIndex() { // return Math.min(addedElementsNumber, points.length) - 1; // } // // void slidePointsToTheLeft() { // TrailPoint p0 = points[0]; // for (int i = 0; i < points.length-1; i++) { // points[i] = points[i+1]; // } // points[points.length-1] = p0; // } // // void doAdd(int x, int y) { // points[getInsertIndex()].set(x, y); // addedElementsNumber++; // } // // public TrailPoint getElementAt(int index) { // if (isIndexValid(index)) { // return points[index]; // } else { // throw getInvalidIndexException(index); // } // } // // public TrailPoint getLastElement() { // return getElementAt(getLastElementIndex()); // } // // public boolean isSameAsLast(TrailPoint p) { // if (addedElementsNumber == 0) { // return false; // } else { // return p.isSameAs(points[getLastElementIndex()]); // } // } // // int getInsertIndex() { // return Math.min(addedElementsNumber, points.length - 1); // } // // public int getLastElementIndex() { // return Math.min(addedElementsNumber - 1, points.length - 1); // } // // public boolean isFull() { // return addedElementsNumber >= points.length; // } // // public void removeElementsAtLeftOf(int index) { // if (isIndexValid(index)) { // doRemoveElementsAtLeftOf(index); // } else { // throw getInvalidIndexException(index); // } // } // // private void doRemoveElementsAtLeftOf(int index) { // for (int i = 0; i <= getLastElementIndex()-index; i++) { // int sourceIndex = index + i; // shiftPoint(i, sourceIndex); // } // addedElementsNumber -= index; // } // // private void shiftPoint(int destIndex, int sourceIndex) { // if (sourceIndex < points.length) { // TrailPoint source = points[sourceIndex]; // points[destIndex].set(source.getX(), source.getY()); // } // } // // private SlidingWindowIndexException getInvalidIndexException(int index) { // return new SlidingWindowIndexException(String.format("Invalid index '%d' (max index %d)", index, getMaxIndex())); // } // }
import com.orange.dgil.trail.TestTools; import com.orange.dgil.trail.core.common.TrailPoint; import com.orange.dgil.trail.core.vecto.SlidingWindow; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito;
/** * Trail drawing library * Copyright (C) 2014 Orange * Authors: christophe.maldivi@orange.com, eric.petit@orange.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.orange.dgil.trail.core.vecto.linearwindowfilter; public class LinearWindowFilterAddPointTest { private LinearWindowFilter filter; @Before public void setUp() { filter = Mockito.mock(LinearWindowFilter.class); } @Test public void shouldAddPointWhenSameAsLast() throws IllegalAccessException { // given boolean sameAsLast = true; TrailPoint point = new TrailPoint();
// Path: src/main/java/com/orange/dgil/trail/core/common/TrailPoint.java // @Getter // @NoArgsConstructor // public class TrailPoint { // private int x = -1; // private int y = -1; // // public TrailPoint(int x, int y) { // set(x, y); // } // // public void set(int x, int y) { // this.x = x; // this.y = y; // } // // public boolean isSameAs(TrailPoint point) { // return x == point.x && y == point.y; // } // // public double getDistanceTo(TrailPoint point) { // int dx = x - point.getX(); // int dy = y - point.getY(); // return Math.sqrt(dx * dx + dy * dy); // } // // public void deepCopy(TrailPoint point) { // x = point.x; // y = point.y; // } // } // // Path: src/main/java/com/orange/dgil/trail/core/vecto/SlidingWindow.java // public class SlidingWindow { // // private TrailPoint[] points; // // @Getter // private int addedElementsNumber; // // public SlidingWindow(int windowSize) { // setWindowSize(windowSize); // } // // public void setWindowSize(int windowSize) { // points = new TrailPoint[windowSize]; // allocatePoints(); // } // // public int getWindowSize() { // return points.length; // } // // private void allocatePoints() { // for (int i = 0; i < points.length; i++) { // points[i] = new TrailPoint(); // } // } // // public void reset() { // addedElementsNumber = 0; // } // // public void add(int x, int y) { // if (isFull()) { // slidePointsToTheLeft(); // } // doAdd(x, y); // } // // public void add(TrailPoint point) { // add(point.getX(), point.getY()); // } // // public int getX(int index) { // if (isIndexValid(index)) { // return points[index].getX(); // } else { // throw new SlidingWindowIndexException(String.format("Invalid index '%d' (max index %d)", index, getMaxIndex())); // } // } // // public int getY(int index) { // if (isIndexValid(index)) { // return points[index].getY(); // } else { // throw getInvalidIndexException(index); // } // } // // boolean isIndexValid(int index) { // return index >= 0 && index <= getMaxIndex(); // } // // int getMaxIndex() { // return Math.min(addedElementsNumber, points.length) - 1; // } // // void slidePointsToTheLeft() { // TrailPoint p0 = points[0]; // for (int i = 0; i < points.length-1; i++) { // points[i] = points[i+1]; // } // points[points.length-1] = p0; // } // // void doAdd(int x, int y) { // points[getInsertIndex()].set(x, y); // addedElementsNumber++; // } // // public TrailPoint getElementAt(int index) { // if (isIndexValid(index)) { // return points[index]; // } else { // throw getInvalidIndexException(index); // } // } // // public TrailPoint getLastElement() { // return getElementAt(getLastElementIndex()); // } // // public boolean isSameAsLast(TrailPoint p) { // if (addedElementsNumber == 0) { // return false; // } else { // return p.isSameAs(points[getLastElementIndex()]); // } // } // // int getInsertIndex() { // return Math.min(addedElementsNumber, points.length - 1); // } // // public int getLastElementIndex() { // return Math.min(addedElementsNumber - 1, points.length - 1); // } // // public boolean isFull() { // return addedElementsNumber >= points.length; // } // // public void removeElementsAtLeftOf(int index) { // if (isIndexValid(index)) { // doRemoveElementsAtLeftOf(index); // } else { // throw getInvalidIndexException(index); // } // } // // private void doRemoveElementsAtLeftOf(int index) { // for (int i = 0; i <= getLastElementIndex()-index; i++) { // int sourceIndex = index + i; // shiftPoint(i, sourceIndex); // } // addedElementsNumber -= index; // } // // private void shiftPoint(int destIndex, int sourceIndex) { // if (sourceIndex < points.length) { // TrailPoint source = points[sourceIndex]; // points[destIndex].set(source.getX(), source.getY()); // } // } // // private SlidingWindowIndexException getInvalidIndexException(int index) { // return new SlidingWindowIndexException(String.format("Invalid index '%d' (max index %d)", index, getMaxIndex())); // } // } // Path: src/test/java/com/orange/dgil/trail/core/vecto/linearwindowfilter/LinearWindowFilterAddPointTest.java import com.orange.dgil.trail.TestTools; import com.orange.dgil.trail.core.common.TrailPoint; import com.orange.dgil.trail.core.vecto.SlidingWindow; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; /** * Trail drawing library * Copyright (C) 2014 Orange * Authors: christophe.maldivi@orange.com, eric.petit@orange.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.orange.dgil.trail.core.vecto.linearwindowfilter; public class LinearWindowFilterAddPointTest { private LinearWindowFilter filter; @Before public void setUp() { filter = Mockito.mock(LinearWindowFilter.class); } @Test public void shouldAddPointWhenSameAsLast() throws IllegalAccessException { // given boolean sameAsLast = true; TrailPoint point = new TrailPoint();
SlidingWindow slidingWindow = Mockito.mock(SlidingWindow.class);
Orange-OpenSource/android-trail-drawing
src/main/java/com/orange/dgil/trail/core/quad/QuadCurve.java
// Path: src/main/java/com/orange/dgil/trail/core/common/TrailPoint.java // @Getter // @NoArgsConstructor // public class TrailPoint { // private int x = -1; // private int y = -1; // // public TrailPoint(int x, int y) { // set(x, y); // } // // public void set(int x, int y) { // this.x = x; // this.y = y; // } // // public boolean isSameAs(TrailPoint point) { // return x == point.x && y == point.y; // } // // public double getDistanceTo(TrailPoint point) { // int dx = x - point.getX(); // int dy = y - point.getY(); // return Math.sqrt(dx * dx + dy * dy); // } // // public void deepCopy(TrailPoint point) { // x = point.x; // y = point.y; // } // } // // Path: src/main/java/com/orange/dgil/trail/core/vecto/vecto/VectoFilter.java // @RequiredArgsConstructor // public class VectoFilter implements LinearWindowFilterListener, VectoFilterListener { // // private final LinearWindowFilter linearWindowFilter = new LinearWindowFilter(this); // private final RawVectoFilter rawVectoFilter = new RawVectoFilter(this); // private final VectoFilterListener vectoFilterListener; // private final TrailPoint trailPoint = new TrailPoint(); // // public void reset() { // linearWindowFilter.reset(); // rawVectoFilter.reset(); // } // // public void addPoint(int x, int y) { // trailPoint.set(x, y); // linearWindowFilter.addPoint(trailPoint); // } // // public void epilogue() { // rawVectoFilter.addPoint(linearWindowFilter.getLastPoint()); // rawVectoFilter.epilogue(); // } // // @Override // public void onNewFilteredPointAvailable(int x, int y) { // trailPoint.set(x, y); // rawVectoFilter.addPoint(trailPoint); // } // // @Override // public void onNewVectoPointAvailable(int x, int y) { // vectoFilterListener.onNewVectoPointAvailable(x, y); // } // // @Override // public void onLastVectoPointAvailable(int x, int y) { // vectoFilterListener.onLastVectoPointAvailable(x, y); // } // // public VectoSettings getVectoSettings() { // return rawVectoFilter.getVectoSettings(); // } // } // // Path: src/main/java/com/orange/dgil/trail/core/vecto/vecto/VectoFilterListener.java // public interface VectoFilterListener { // void onNewVectoPointAvailable(int x, int y); // void onLastVectoPointAvailable(int x, int y); // }
import com.orange.dgil.trail.core.common.TrailPoint; import com.orange.dgil.trail.core.vecto.vecto.VectoFilter; import com.orange.dgil.trail.core.vecto.vecto.VectoFilterListener; import com.orange.dgil.trail.core.vecto.vecto.VectoSettings; import lombok.Getter;
/** * Trail drawing library * Copyright (C) 2014 Orange * Authors: christophe.maldivi@orange.com, eric.petit@orange.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.orange.dgil.trail.core.quad; public class QuadCurve implements VectoFilterListener { @Getter
// Path: src/main/java/com/orange/dgil/trail/core/common/TrailPoint.java // @Getter // @NoArgsConstructor // public class TrailPoint { // private int x = -1; // private int y = -1; // // public TrailPoint(int x, int y) { // set(x, y); // } // // public void set(int x, int y) { // this.x = x; // this.y = y; // } // // public boolean isSameAs(TrailPoint point) { // return x == point.x && y == point.y; // } // // public double getDistanceTo(TrailPoint point) { // int dx = x - point.getX(); // int dy = y - point.getY(); // return Math.sqrt(dx * dx + dy * dy); // } // // public void deepCopy(TrailPoint point) { // x = point.x; // y = point.y; // } // } // // Path: src/main/java/com/orange/dgil/trail/core/vecto/vecto/VectoFilter.java // @RequiredArgsConstructor // public class VectoFilter implements LinearWindowFilterListener, VectoFilterListener { // // private final LinearWindowFilter linearWindowFilter = new LinearWindowFilter(this); // private final RawVectoFilter rawVectoFilter = new RawVectoFilter(this); // private final VectoFilterListener vectoFilterListener; // private final TrailPoint trailPoint = new TrailPoint(); // // public void reset() { // linearWindowFilter.reset(); // rawVectoFilter.reset(); // } // // public void addPoint(int x, int y) { // trailPoint.set(x, y); // linearWindowFilter.addPoint(trailPoint); // } // // public void epilogue() { // rawVectoFilter.addPoint(linearWindowFilter.getLastPoint()); // rawVectoFilter.epilogue(); // } // // @Override // public void onNewFilteredPointAvailable(int x, int y) { // trailPoint.set(x, y); // rawVectoFilter.addPoint(trailPoint); // } // // @Override // public void onNewVectoPointAvailable(int x, int y) { // vectoFilterListener.onNewVectoPointAvailable(x, y); // } // // @Override // public void onLastVectoPointAvailable(int x, int y) { // vectoFilterListener.onLastVectoPointAvailable(x, y); // } // // public VectoSettings getVectoSettings() { // return rawVectoFilter.getVectoSettings(); // } // } // // Path: src/main/java/com/orange/dgil/trail/core/vecto/vecto/VectoFilterListener.java // public interface VectoFilterListener { // void onNewVectoPointAvailable(int x, int y); // void onLastVectoPointAvailable(int x, int y); // } // Path: src/main/java/com/orange/dgil/trail/core/quad/QuadCurve.java import com.orange.dgil.trail.core.common.TrailPoint; import com.orange.dgil.trail.core.vecto.vecto.VectoFilter; import com.orange.dgil.trail.core.vecto.vecto.VectoFilterListener; import com.orange.dgil.trail.core.vecto.vecto.VectoSettings; import lombok.Getter; /** * Trail drawing library * Copyright (C) 2014 Orange * Authors: christophe.maldivi@orange.com, eric.petit@orange.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.orange.dgil.trail.core.quad; public class QuadCurve implements VectoFilterListener { @Getter
private final TrailPoint lastVectoPoint = new TrailPoint();
Orange-OpenSource/android-trail-drawing
src/main/java/com/orange/dgil/trail/core/quad/QuadCurve.java
// Path: src/main/java/com/orange/dgil/trail/core/common/TrailPoint.java // @Getter // @NoArgsConstructor // public class TrailPoint { // private int x = -1; // private int y = -1; // // public TrailPoint(int x, int y) { // set(x, y); // } // // public void set(int x, int y) { // this.x = x; // this.y = y; // } // // public boolean isSameAs(TrailPoint point) { // return x == point.x && y == point.y; // } // // public double getDistanceTo(TrailPoint point) { // int dx = x - point.getX(); // int dy = y - point.getY(); // return Math.sqrt(dx * dx + dy * dy); // } // // public void deepCopy(TrailPoint point) { // x = point.x; // y = point.y; // } // } // // Path: src/main/java/com/orange/dgil/trail/core/vecto/vecto/VectoFilter.java // @RequiredArgsConstructor // public class VectoFilter implements LinearWindowFilterListener, VectoFilterListener { // // private final LinearWindowFilter linearWindowFilter = new LinearWindowFilter(this); // private final RawVectoFilter rawVectoFilter = new RawVectoFilter(this); // private final VectoFilterListener vectoFilterListener; // private final TrailPoint trailPoint = new TrailPoint(); // // public void reset() { // linearWindowFilter.reset(); // rawVectoFilter.reset(); // } // // public void addPoint(int x, int y) { // trailPoint.set(x, y); // linearWindowFilter.addPoint(trailPoint); // } // // public void epilogue() { // rawVectoFilter.addPoint(linearWindowFilter.getLastPoint()); // rawVectoFilter.epilogue(); // } // // @Override // public void onNewFilteredPointAvailable(int x, int y) { // trailPoint.set(x, y); // rawVectoFilter.addPoint(trailPoint); // } // // @Override // public void onNewVectoPointAvailable(int x, int y) { // vectoFilterListener.onNewVectoPointAvailable(x, y); // } // // @Override // public void onLastVectoPointAvailable(int x, int y) { // vectoFilterListener.onLastVectoPointAvailable(x, y); // } // // public VectoSettings getVectoSettings() { // return rawVectoFilter.getVectoSettings(); // } // } // // Path: src/main/java/com/orange/dgil/trail/core/vecto/vecto/VectoFilterListener.java // public interface VectoFilterListener { // void onNewVectoPointAvailable(int x, int y); // void onLastVectoPointAvailable(int x, int y); // }
import com.orange.dgil.trail.core.common.TrailPoint; import com.orange.dgil.trail.core.vecto.vecto.VectoFilter; import com.orange.dgil.trail.core.vecto.vecto.VectoFilterListener; import com.orange.dgil.trail.core.vecto.vecto.VectoSettings; import lombok.Getter;
/** * Trail drawing library * Copyright (C) 2014 Orange * Authors: christophe.maldivi@orange.com, eric.petit@orange.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.orange.dgil.trail.core.quad; public class QuadCurve implements VectoFilterListener { @Getter private final TrailPoint lastVectoPoint = new TrailPoint(); private final boolean vectoEnabled; private QuadInterpolator quadInterpolator;
// Path: src/main/java/com/orange/dgil/trail/core/common/TrailPoint.java // @Getter // @NoArgsConstructor // public class TrailPoint { // private int x = -1; // private int y = -1; // // public TrailPoint(int x, int y) { // set(x, y); // } // // public void set(int x, int y) { // this.x = x; // this.y = y; // } // // public boolean isSameAs(TrailPoint point) { // return x == point.x && y == point.y; // } // // public double getDistanceTo(TrailPoint point) { // int dx = x - point.getX(); // int dy = y - point.getY(); // return Math.sqrt(dx * dx + dy * dy); // } // // public void deepCopy(TrailPoint point) { // x = point.x; // y = point.y; // } // } // // Path: src/main/java/com/orange/dgil/trail/core/vecto/vecto/VectoFilter.java // @RequiredArgsConstructor // public class VectoFilter implements LinearWindowFilterListener, VectoFilterListener { // // private final LinearWindowFilter linearWindowFilter = new LinearWindowFilter(this); // private final RawVectoFilter rawVectoFilter = new RawVectoFilter(this); // private final VectoFilterListener vectoFilterListener; // private final TrailPoint trailPoint = new TrailPoint(); // // public void reset() { // linearWindowFilter.reset(); // rawVectoFilter.reset(); // } // // public void addPoint(int x, int y) { // trailPoint.set(x, y); // linearWindowFilter.addPoint(trailPoint); // } // // public void epilogue() { // rawVectoFilter.addPoint(linearWindowFilter.getLastPoint()); // rawVectoFilter.epilogue(); // } // // @Override // public void onNewFilteredPointAvailable(int x, int y) { // trailPoint.set(x, y); // rawVectoFilter.addPoint(trailPoint); // } // // @Override // public void onNewVectoPointAvailable(int x, int y) { // vectoFilterListener.onNewVectoPointAvailable(x, y); // } // // @Override // public void onLastVectoPointAvailable(int x, int y) { // vectoFilterListener.onLastVectoPointAvailable(x, y); // } // // public VectoSettings getVectoSettings() { // return rawVectoFilter.getVectoSettings(); // } // } // // Path: src/main/java/com/orange/dgil/trail/core/vecto/vecto/VectoFilterListener.java // public interface VectoFilterListener { // void onNewVectoPointAvailable(int x, int y); // void onLastVectoPointAvailable(int x, int y); // } // Path: src/main/java/com/orange/dgil/trail/core/quad/QuadCurve.java import com.orange.dgil.trail.core.common.TrailPoint; import com.orange.dgil.trail.core.vecto.vecto.VectoFilter; import com.orange.dgil.trail.core.vecto.vecto.VectoFilterListener; import com.orange.dgil.trail.core.vecto.vecto.VectoSettings; import lombok.Getter; /** * Trail drawing library * Copyright (C) 2014 Orange * Authors: christophe.maldivi@orange.com, eric.petit@orange.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.orange.dgil.trail.core.quad; public class QuadCurve implements VectoFilterListener { @Getter private final TrailPoint lastVectoPoint = new TrailPoint(); private final boolean vectoEnabled; private QuadInterpolator quadInterpolator;
private VectoFilter vectoFilter = new VectoFilter(this);
Orange-OpenSource/android-trail-drawing
src/main/java/com/orange/dgil/trail/core/vecto/vecto/VectoFilter.java
// Path: src/main/java/com/orange/dgil/trail/core/common/TrailPoint.java // @Getter // @NoArgsConstructor // public class TrailPoint { // private int x = -1; // private int y = -1; // // public TrailPoint(int x, int y) { // set(x, y); // } // // public void set(int x, int y) { // this.x = x; // this.y = y; // } // // public boolean isSameAs(TrailPoint point) { // return x == point.x && y == point.y; // } // // public double getDistanceTo(TrailPoint point) { // int dx = x - point.getX(); // int dy = y - point.getY(); // return Math.sqrt(dx * dx + dy * dy); // } // // public void deepCopy(TrailPoint point) { // x = point.x; // y = point.y; // } // } // // Path: src/main/java/com/orange/dgil/trail/core/vecto/linearwindowfilter/LinearWindowFilter.java // public class LinearWindowFilter { // // /** window elements weight */ // private final int[] windowWeights = {1, 2, 1}; // // /** window elements */ // private final SlidingWindow slidingWindow = new SlidingWindow(windowWeights.length); // // private final LinearWindowFilterListener linearWindowFilterListener; // // private int weightsSum; // // // public LinearWindowFilter(LinearWindowFilterListener linearWindowFilterListener) { // this.linearWindowFilterListener = linearWindowFilterListener; // initProperties(); // } // // void initProperties() { // weightsSum = getWeightsSum(); // } // // int getWeightsSum() { // int sum = 0; // for (int weight : windowWeights) { // sum+= weight; // } // return sum; // } // // // public void reset() { // slidingWindow.reset(); // } // // public TrailPoint getLastPoint() { // return slidingWindow.getLastElement(); // } // // public void addPoint(TrailPoint point) { // if (!slidingWindow.isSameAsLast(point)) { // doAddPoint(point); // } // } // // void doAddPoint(TrailPoint point) { // slidingWindow.add(point); // if (isNewPointAvailable()) { // computeNewPointAndNotifyListener(); // } // } // // boolean isNewPointAvailable() { // return slidingWindow.getAddedElementsNumber() == 1 || slidingWindow.isFull(); // } // // void computeNewPointAndNotifyListener() { // int x; // int y; // if (slidingWindow.getAddedElementsNumber() == 1) { // x = slidingWindow.getX(0); // y = slidingWindow.getY(0); // } else { // x = getMeanX(); // y = getMeanY(); // } // linearWindowFilterListener.onNewFilteredPointAvailable(x, y); // } // // int getMeanX() { // int sumX = 0; // for (int i = 0; i < windowWeights.length; i++) { // sumX += slidingWindow.getX(i) * windowWeights[i]; // } // return (sumX + weightsSum/2) / weightsSum; // } // int getMeanY() { // int sumY = 0; // for (int i = 0; i < windowWeights.length; i++) { // sumY += slidingWindow.getY(i) * windowWeights[i]; // } // return (sumY + weightsSum/2) / weightsSum; // } // } // // Path: src/main/java/com/orange/dgil/trail/core/vecto/linearwindowfilter/LinearWindowFilterListener.java // public interface LinearWindowFilterListener { // void onNewFilteredPointAvailable(int x, int y); // }
import com.orange.dgil.trail.core.common.TrailPoint; import com.orange.dgil.trail.core.vecto.linearwindowfilter.LinearWindowFilter; import com.orange.dgil.trail.core.vecto.linearwindowfilter.LinearWindowFilterListener; import lombok.RequiredArgsConstructor;
/** * Trail drawing library * Copyright (C) 2014 Orange * Authors: christophe.maldivi@orange.com, eric.petit@orange.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.orange.dgil.trail.core.vecto.vecto; @RequiredArgsConstructor public class VectoFilter implements LinearWindowFilterListener, VectoFilterListener {
// Path: src/main/java/com/orange/dgil/trail/core/common/TrailPoint.java // @Getter // @NoArgsConstructor // public class TrailPoint { // private int x = -1; // private int y = -1; // // public TrailPoint(int x, int y) { // set(x, y); // } // // public void set(int x, int y) { // this.x = x; // this.y = y; // } // // public boolean isSameAs(TrailPoint point) { // return x == point.x && y == point.y; // } // // public double getDistanceTo(TrailPoint point) { // int dx = x - point.getX(); // int dy = y - point.getY(); // return Math.sqrt(dx * dx + dy * dy); // } // // public void deepCopy(TrailPoint point) { // x = point.x; // y = point.y; // } // } // // Path: src/main/java/com/orange/dgil/trail/core/vecto/linearwindowfilter/LinearWindowFilter.java // public class LinearWindowFilter { // // /** window elements weight */ // private final int[] windowWeights = {1, 2, 1}; // // /** window elements */ // private final SlidingWindow slidingWindow = new SlidingWindow(windowWeights.length); // // private final LinearWindowFilterListener linearWindowFilterListener; // // private int weightsSum; // // // public LinearWindowFilter(LinearWindowFilterListener linearWindowFilterListener) { // this.linearWindowFilterListener = linearWindowFilterListener; // initProperties(); // } // // void initProperties() { // weightsSum = getWeightsSum(); // } // // int getWeightsSum() { // int sum = 0; // for (int weight : windowWeights) { // sum+= weight; // } // return sum; // } // // // public void reset() { // slidingWindow.reset(); // } // // public TrailPoint getLastPoint() { // return slidingWindow.getLastElement(); // } // // public void addPoint(TrailPoint point) { // if (!slidingWindow.isSameAsLast(point)) { // doAddPoint(point); // } // } // // void doAddPoint(TrailPoint point) { // slidingWindow.add(point); // if (isNewPointAvailable()) { // computeNewPointAndNotifyListener(); // } // } // // boolean isNewPointAvailable() { // return slidingWindow.getAddedElementsNumber() == 1 || slidingWindow.isFull(); // } // // void computeNewPointAndNotifyListener() { // int x; // int y; // if (slidingWindow.getAddedElementsNumber() == 1) { // x = slidingWindow.getX(0); // y = slidingWindow.getY(0); // } else { // x = getMeanX(); // y = getMeanY(); // } // linearWindowFilterListener.onNewFilteredPointAvailable(x, y); // } // // int getMeanX() { // int sumX = 0; // for (int i = 0; i < windowWeights.length; i++) { // sumX += slidingWindow.getX(i) * windowWeights[i]; // } // return (sumX + weightsSum/2) / weightsSum; // } // int getMeanY() { // int sumY = 0; // for (int i = 0; i < windowWeights.length; i++) { // sumY += slidingWindow.getY(i) * windowWeights[i]; // } // return (sumY + weightsSum/2) / weightsSum; // } // } // // Path: src/main/java/com/orange/dgil/trail/core/vecto/linearwindowfilter/LinearWindowFilterListener.java // public interface LinearWindowFilterListener { // void onNewFilteredPointAvailable(int x, int y); // } // Path: src/main/java/com/orange/dgil/trail/core/vecto/vecto/VectoFilter.java import com.orange.dgil.trail.core.common.TrailPoint; import com.orange.dgil.trail.core.vecto.linearwindowfilter.LinearWindowFilter; import com.orange.dgil.trail.core.vecto.linearwindowfilter.LinearWindowFilterListener; import lombok.RequiredArgsConstructor; /** * Trail drawing library * Copyright (C) 2014 Orange * Authors: christophe.maldivi@orange.com, eric.petit@orange.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.orange.dgil.trail.core.vecto.vecto; @RequiredArgsConstructor public class VectoFilter implements LinearWindowFilterListener, VectoFilterListener {
private final LinearWindowFilter linearWindowFilter = new LinearWindowFilter(this);
Orange-OpenSource/android-trail-drawing
src/main/java/com/orange/dgil/trail/core/vecto/vecto/VectoFilter.java
// Path: src/main/java/com/orange/dgil/trail/core/common/TrailPoint.java // @Getter // @NoArgsConstructor // public class TrailPoint { // private int x = -1; // private int y = -1; // // public TrailPoint(int x, int y) { // set(x, y); // } // // public void set(int x, int y) { // this.x = x; // this.y = y; // } // // public boolean isSameAs(TrailPoint point) { // return x == point.x && y == point.y; // } // // public double getDistanceTo(TrailPoint point) { // int dx = x - point.getX(); // int dy = y - point.getY(); // return Math.sqrt(dx * dx + dy * dy); // } // // public void deepCopy(TrailPoint point) { // x = point.x; // y = point.y; // } // } // // Path: src/main/java/com/orange/dgil/trail/core/vecto/linearwindowfilter/LinearWindowFilter.java // public class LinearWindowFilter { // // /** window elements weight */ // private final int[] windowWeights = {1, 2, 1}; // // /** window elements */ // private final SlidingWindow slidingWindow = new SlidingWindow(windowWeights.length); // // private final LinearWindowFilterListener linearWindowFilterListener; // // private int weightsSum; // // // public LinearWindowFilter(LinearWindowFilterListener linearWindowFilterListener) { // this.linearWindowFilterListener = linearWindowFilterListener; // initProperties(); // } // // void initProperties() { // weightsSum = getWeightsSum(); // } // // int getWeightsSum() { // int sum = 0; // for (int weight : windowWeights) { // sum+= weight; // } // return sum; // } // // // public void reset() { // slidingWindow.reset(); // } // // public TrailPoint getLastPoint() { // return slidingWindow.getLastElement(); // } // // public void addPoint(TrailPoint point) { // if (!slidingWindow.isSameAsLast(point)) { // doAddPoint(point); // } // } // // void doAddPoint(TrailPoint point) { // slidingWindow.add(point); // if (isNewPointAvailable()) { // computeNewPointAndNotifyListener(); // } // } // // boolean isNewPointAvailable() { // return slidingWindow.getAddedElementsNumber() == 1 || slidingWindow.isFull(); // } // // void computeNewPointAndNotifyListener() { // int x; // int y; // if (slidingWindow.getAddedElementsNumber() == 1) { // x = slidingWindow.getX(0); // y = slidingWindow.getY(0); // } else { // x = getMeanX(); // y = getMeanY(); // } // linearWindowFilterListener.onNewFilteredPointAvailable(x, y); // } // // int getMeanX() { // int sumX = 0; // for (int i = 0; i < windowWeights.length; i++) { // sumX += slidingWindow.getX(i) * windowWeights[i]; // } // return (sumX + weightsSum/2) / weightsSum; // } // int getMeanY() { // int sumY = 0; // for (int i = 0; i < windowWeights.length; i++) { // sumY += slidingWindow.getY(i) * windowWeights[i]; // } // return (sumY + weightsSum/2) / weightsSum; // } // } // // Path: src/main/java/com/orange/dgil/trail/core/vecto/linearwindowfilter/LinearWindowFilterListener.java // public interface LinearWindowFilterListener { // void onNewFilteredPointAvailable(int x, int y); // }
import com.orange.dgil.trail.core.common.TrailPoint; import com.orange.dgil.trail.core.vecto.linearwindowfilter.LinearWindowFilter; import com.orange.dgil.trail.core.vecto.linearwindowfilter.LinearWindowFilterListener; import lombok.RequiredArgsConstructor;
/** * Trail drawing library * Copyright (C) 2014 Orange * Authors: christophe.maldivi@orange.com, eric.petit@orange.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.orange.dgil.trail.core.vecto.vecto; @RequiredArgsConstructor public class VectoFilter implements LinearWindowFilterListener, VectoFilterListener { private final LinearWindowFilter linearWindowFilter = new LinearWindowFilter(this); private final RawVectoFilter rawVectoFilter = new RawVectoFilter(this); private final VectoFilterListener vectoFilterListener;
// Path: src/main/java/com/orange/dgil/trail/core/common/TrailPoint.java // @Getter // @NoArgsConstructor // public class TrailPoint { // private int x = -1; // private int y = -1; // // public TrailPoint(int x, int y) { // set(x, y); // } // // public void set(int x, int y) { // this.x = x; // this.y = y; // } // // public boolean isSameAs(TrailPoint point) { // return x == point.x && y == point.y; // } // // public double getDistanceTo(TrailPoint point) { // int dx = x - point.getX(); // int dy = y - point.getY(); // return Math.sqrt(dx * dx + dy * dy); // } // // public void deepCopy(TrailPoint point) { // x = point.x; // y = point.y; // } // } // // Path: src/main/java/com/orange/dgil/trail/core/vecto/linearwindowfilter/LinearWindowFilter.java // public class LinearWindowFilter { // // /** window elements weight */ // private final int[] windowWeights = {1, 2, 1}; // // /** window elements */ // private final SlidingWindow slidingWindow = new SlidingWindow(windowWeights.length); // // private final LinearWindowFilterListener linearWindowFilterListener; // // private int weightsSum; // // // public LinearWindowFilter(LinearWindowFilterListener linearWindowFilterListener) { // this.linearWindowFilterListener = linearWindowFilterListener; // initProperties(); // } // // void initProperties() { // weightsSum = getWeightsSum(); // } // // int getWeightsSum() { // int sum = 0; // for (int weight : windowWeights) { // sum+= weight; // } // return sum; // } // // // public void reset() { // slidingWindow.reset(); // } // // public TrailPoint getLastPoint() { // return slidingWindow.getLastElement(); // } // // public void addPoint(TrailPoint point) { // if (!slidingWindow.isSameAsLast(point)) { // doAddPoint(point); // } // } // // void doAddPoint(TrailPoint point) { // slidingWindow.add(point); // if (isNewPointAvailable()) { // computeNewPointAndNotifyListener(); // } // } // // boolean isNewPointAvailable() { // return slidingWindow.getAddedElementsNumber() == 1 || slidingWindow.isFull(); // } // // void computeNewPointAndNotifyListener() { // int x; // int y; // if (slidingWindow.getAddedElementsNumber() == 1) { // x = slidingWindow.getX(0); // y = slidingWindow.getY(0); // } else { // x = getMeanX(); // y = getMeanY(); // } // linearWindowFilterListener.onNewFilteredPointAvailable(x, y); // } // // int getMeanX() { // int sumX = 0; // for (int i = 0; i < windowWeights.length; i++) { // sumX += slidingWindow.getX(i) * windowWeights[i]; // } // return (sumX + weightsSum/2) / weightsSum; // } // int getMeanY() { // int sumY = 0; // for (int i = 0; i < windowWeights.length; i++) { // sumY += slidingWindow.getY(i) * windowWeights[i]; // } // return (sumY + weightsSum/2) / weightsSum; // } // } // // Path: src/main/java/com/orange/dgil/trail/core/vecto/linearwindowfilter/LinearWindowFilterListener.java // public interface LinearWindowFilterListener { // void onNewFilteredPointAvailable(int x, int y); // } // Path: src/main/java/com/orange/dgil/trail/core/vecto/vecto/VectoFilter.java import com.orange.dgil.trail.core.common.TrailPoint; import com.orange.dgil.trail.core.vecto.linearwindowfilter.LinearWindowFilter; import com.orange.dgil.trail.core.vecto.linearwindowfilter.LinearWindowFilterListener; import lombok.RequiredArgsConstructor; /** * Trail drawing library * Copyright (C) 2014 Orange * Authors: christophe.maldivi@orange.com, eric.petit@orange.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.orange.dgil.trail.core.vecto.vecto; @RequiredArgsConstructor public class VectoFilter implements LinearWindowFilterListener, VectoFilterListener { private final LinearWindowFilter linearWindowFilter = new LinearWindowFilter(this); private final RawVectoFilter rawVectoFilter = new RawVectoFilter(this); private final VectoFilterListener vectoFilterListener;
private final TrailPoint trailPoint = new TrailPoint();
Orange-OpenSource/android-trail-drawing
src/test/java/com/orange/dgil/trail/core/vecto/SlidingWindowIsSameAsLastTest.java
// Path: src/main/java/com/orange/dgil/trail/core/common/TrailPoint.java // @Getter // @NoArgsConstructor // public class TrailPoint { // private int x = -1; // private int y = -1; // // public TrailPoint(int x, int y) { // set(x, y); // } // // public void set(int x, int y) { // this.x = x; // this.y = y; // } // // public boolean isSameAs(TrailPoint point) { // return x == point.x && y == point.y; // } // // public double getDistanceTo(TrailPoint point) { // int dx = x - point.getX(); // int dy = y - point.getY(); // return Math.sqrt(dx * dx + dy * dy); // } // // public void deepCopy(TrailPoint point) { // x = point.x; // y = point.y; // } // }
import com.orange.dgil.trail.TestTools; import com.orange.dgil.trail.core.common.TrailPoint; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito;
/** * Trail drawing library * Copyright (C) 2014 Orange * Authors: christophe.maldivi@orange.com, eric.petit@orange.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.orange.dgil.trail.core.vecto; public class SlidingWindowIsSameAsLastTest { private SlidingWindow slidingWindow; @Before public void setUp() { slidingWindow = Mockito.mock(SlidingWindow.class); } @Test public void shouldReturnFalseWhenNoPoints() throws IllegalAccessException { // given
// Path: src/main/java/com/orange/dgil/trail/core/common/TrailPoint.java // @Getter // @NoArgsConstructor // public class TrailPoint { // private int x = -1; // private int y = -1; // // public TrailPoint(int x, int y) { // set(x, y); // } // // public void set(int x, int y) { // this.x = x; // this.y = y; // } // // public boolean isSameAs(TrailPoint point) { // return x == point.x && y == point.y; // } // // public double getDistanceTo(TrailPoint point) { // int dx = x - point.getX(); // int dy = y - point.getY(); // return Math.sqrt(dx * dx + dy * dy); // } // // public void deepCopy(TrailPoint point) { // x = point.x; // y = point.y; // } // } // Path: src/test/java/com/orange/dgil/trail/core/vecto/SlidingWindowIsSameAsLastTest.java import com.orange.dgil.trail.TestTools; import com.orange.dgil.trail.core.common.TrailPoint; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; /** * Trail drawing library * Copyright (C) 2014 Orange * Authors: christophe.maldivi@orange.com, eric.petit@orange.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.orange.dgil.trail.core.vecto; public class SlidingWindowIsSameAsLastTest { private SlidingWindow slidingWindow; @Before public void setUp() { slidingWindow = Mockito.mock(SlidingWindow.class); } @Test public void shouldReturnFalseWhenNoPoints() throws IllegalAccessException { // given
TrailPoint point = new TrailPoint();
Orange-OpenSource/android-trail-drawing
src/test/java/com/orange/dgil/trail/core/vecto/linearwindowfilter/LinearWindowFilterIsNewPointAvailableTest.java
// Path: src/main/java/com/orange/dgil/trail/core/vecto/SlidingWindow.java // public class SlidingWindow { // // private TrailPoint[] points; // // @Getter // private int addedElementsNumber; // // public SlidingWindow(int windowSize) { // setWindowSize(windowSize); // } // // public void setWindowSize(int windowSize) { // points = new TrailPoint[windowSize]; // allocatePoints(); // } // // public int getWindowSize() { // return points.length; // } // // private void allocatePoints() { // for (int i = 0; i < points.length; i++) { // points[i] = new TrailPoint(); // } // } // // public void reset() { // addedElementsNumber = 0; // } // // public void add(int x, int y) { // if (isFull()) { // slidePointsToTheLeft(); // } // doAdd(x, y); // } // // public void add(TrailPoint point) { // add(point.getX(), point.getY()); // } // // public int getX(int index) { // if (isIndexValid(index)) { // return points[index].getX(); // } else { // throw new SlidingWindowIndexException(String.format("Invalid index '%d' (max index %d)", index, getMaxIndex())); // } // } // // public int getY(int index) { // if (isIndexValid(index)) { // return points[index].getY(); // } else { // throw getInvalidIndexException(index); // } // } // // boolean isIndexValid(int index) { // return index >= 0 && index <= getMaxIndex(); // } // // int getMaxIndex() { // return Math.min(addedElementsNumber, points.length) - 1; // } // // void slidePointsToTheLeft() { // TrailPoint p0 = points[0]; // for (int i = 0; i < points.length-1; i++) { // points[i] = points[i+1]; // } // points[points.length-1] = p0; // } // // void doAdd(int x, int y) { // points[getInsertIndex()].set(x, y); // addedElementsNumber++; // } // // public TrailPoint getElementAt(int index) { // if (isIndexValid(index)) { // return points[index]; // } else { // throw getInvalidIndexException(index); // } // } // // public TrailPoint getLastElement() { // return getElementAt(getLastElementIndex()); // } // // public boolean isSameAsLast(TrailPoint p) { // if (addedElementsNumber == 0) { // return false; // } else { // return p.isSameAs(points[getLastElementIndex()]); // } // } // // int getInsertIndex() { // return Math.min(addedElementsNumber, points.length - 1); // } // // public int getLastElementIndex() { // return Math.min(addedElementsNumber - 1, points.length - 1); // } // // public boolean isFull() { // return addedElementsNumber >= points.length; // } // // public void removeElementsAtLeftOf(int index) { // if (isIndexValid(index)) { // doRemoveElementsAtLeftOf(index); // } else { // throw getInvalidIndexException(index); // } // } // // private void doRemoveElementsAtLeftOf(int index) { // for (int i = 0; i <= getLastElementIndex()-index; i++) { // int sourceIndex = index + i; // shiftPoint(i, sourceIndex); // } // addedElementsNumber -= index; // } // // private void shiftPoint(int destIndex, int sourceIndex) { // if (sourceIndex < points.length) { // TrailPoint source = points[sourceIndex]; // points[destIndex].set(source.getX(), source.getY()); // } // } // // private SlidingWindowIndexException getInvalidIndexException(int index) { // return new SlidingWindowIndexException(String.format("Invalid index '%d' (max index %d)", index, getMaxIndex())); // } // }
import com.orange.dgil.trail.TestTools; import com.orange.dgil.trail.core.vecto.SlidingWindow; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito;
/** * Trail drawing library * Copyright (C) 2014 Orange * Authors: christophe.maldivi@orange.com, eric.petit@orange.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.orange.dgil.trail.core.vecto.linearwindowfilter; public class LinearWindowFilterIsNewPointAvailableTest { private LinearWindowFilter filter; @Before public void setUp() { filter = Mockito.mock(LinearWindowFilter.class); } @Test public void shouldUpdateHasNewPointAvailableWhenNotFirstPointAndWindowNotFull() throws IllegalAccessException { // given int addedElementsNumber = 2; boolean isFull = false;
// Path: src/main/java/com/orange/dgil/trail/core/vecto/SlidingWindow.java // public class SlidingWindow { // // private TrailPoint[] points; // // @Getter // private int addedElementsNumber; // // public SlidingWindow(int windowSize) { // setWindowSize(windowSize); // } // // public void setWindowSize(int windowSize) { // points = new TrailPoint[windowSize]; // allocatePoints(); // } // // public int getWindowSize() { // return points.length; // } // // private void allocatePoints() { // for (int i = 0; i < points.length; i++) { // points[i] = new TrailPoint(); // } // } // // public void reset() { // addedElementsNumber = 0; // } // // public void add(int x, int y) { // if (isFull()) { // slidePointsToTheLeft(); // } // doAdd(x, y); // } // // public void add(TrailPoint point) { // add(point.getX(), point.getY()); // } // // public int getX(int index) { // if (isIndexValid(index)) { // return points[index].getX(); // } else { // throw new SlidingWindowIndexException(String.format("Invalid index '%d' (max index %d)", index, getMaxIndex())); // } // } // // public int getY(int index) { // if (isIndexValid(index)) { // return points[index].getY(); // } else { // throw getInvalidIndexException(index); // } // } // // boolean isIndexValid(int index) { // return index >= 0 && index <= getMaxIndex(); // } // // int getMaxIndex() { // return Math.min(addedElementsNumber, points.length) - 1; // } // // void slidePointsToTheLeft() { // TrailPoint p0 = points[0]; // for (int i = 0; i < points.length-1; i++) { // points[i] = points[i+1]; // } // points[points.length-1] = p0; // } // // void doAdd(int x, int y) { // points[getInsertIndex()].set(x, y); // addedElementsNumber++; // } // // public TrailPoint getElementAt(int index) { // if (isIndexValid(index)) { // return points[index]; // } else { // throw getInvalidIndexException(index); // } // } // // public TrailPoint getLastElement() { // return getElementAt(getLastElementIndex()); // } // // public boolean isSameAsLast(TrailPoint p) { // if (addedElementsNumber == 0) { // return false; // } else { // return p.isSameAs(points[getLastElementIndex()]); // } // } // // int getInsertIndex() { // return Math.min(addedElementsNumber, points.length - 1); // } // // public int getLastElementIndex() { // return Math.min(addedElementsNumber - 1, points.length - 1); // } // // public boolean isFull() { // return addedElementsNumber >= points.length; // } // // public void removeElementsAtLeftOf(int index) { // if (isIndexValid(index)) { // doRemoveElementsAtLeftOf(index); // } else { // throw getInvalidIndexException(index); // } // } // // private void doRemoveElementsAtLeftOf(int index) { // for (int i = 0; i <= getLastElementIndex()-index; i++) { // int sourceIndex = index + i; // shiftPoint(i, sourceIndex); // } // addedElementsNumber -= index; // } // // private void shiftPoint(int destIndex, int sourceIndex) { // if (sourceIndex < points.length) { // TrailPoint source = points[sourceIndex]; // points[destIndex].set(source.getX(), source.getY()); // } // } // // private SlidingWindowIndexException getInvalidIndexException(int index) { // return new SlidingWindowIndexException(String.format("Invalid index '%d' (max index %d)", index, getMaxIndex())); // } // } // Path: src/test/java/com/orange/dgil/trail/core/vecto/linearwindowfilter/LinearWindowFilterIsNewPointAvailableTest.java import com.orange.dgil.trail.TestTools; import com.orange.dgil.trail.core.vecto.SlidingWindow; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; /** * Trail drawing library * Copyright (C) 2014 Orange * Authors: christophe.maldivi@orange.com, eric.petit@orange.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.orange.dgil.trail.core.vecto.linearwindowfilter; public class LinearWindowFilterIsNewPointAvailableTest { private LinearWindowFilter filter; @Before public void setUp() { filter = Mockito.mock(LinearWindowFilter.class); } @Test public void shouldUpdateHasNewPointAvailableWhenNotFirstPointAndWindowNotFull() throws IllegalAccessException { // given int addedElementsNumber = 2; boolean isFull = false;
SlidingWindow slidingWindow = Mockito.mock(SlidingWindow.class);
Orange-OpenSource/android-trail-drawing
src/test/java/com/orange/dgil/trail/core/vecto/linearwindowfilter/LinearWindowFilterDoAddPointTest.java
// Path: src/main/java/com/orange/dgil/trail/core/common/TrailPoint.java // @Getter // @NoArgsConstructor // public class TrailPoint { // private int x = -1; // private int y = -1; // // public TrailPoint(int x, int y) { // set(x, y); // } // // public void set(int x, int y) { // this.x = x; // this.y = y; // } // // public boolean isSameAs(TrailPoint point) { // return x == point.x && y == point.y; // } // // public double getDistanceTo(TrailPoint point) { // int dx = x - point.getX(); // int dy = y - point.getY(); // return Math.sqrt(dx * dx + dy * dy); // } // // public void deepCopy(TrailPoint point) { // x = point.x; // y = point.y; // } // } // // Path: src/main/java/com/orange/dgil/trail/core/vecto/SlidingWindow.java // public class SlidingWindow { // // private TrailPoint[] points; // // @Getter // private int addedElementsNumber; // // public SlidingWindow(int windowSize) { // setWindowSize(windowSize); // } // // public void setWindowSize(int windowSize) { // points = new TrailPoint[windowSize]; // allocatePoints(); // } // // public int getWindowSize() { // return points.length; // } // // private void allocatePoints() { // for (int i = 0; i < points.length; i++) { // points[i] = new TrailPoint(); // } // } // // public void reset() { // addedElementsNumber = 0; // } // // public void add(int x, int y) { // if (isFull()) { // slidePointsToTheLeft(); // } // doAdd(x, y); // } // // public void add(TrailPoint point) { // add(point.getX(), point.getY()); // } // // public int getX(int index) { // if (isIndexValid(index)) { // return points[index].getX(); // } else { // throw new SlidingWindowIndexException(String.format("Invalid index '%d' (max index %d)", index, getMaxIndex())); // } // } // // public int getY(int index) { // if (isIndexValid(index)) { // return points[index].getY(); // } else { // throw getInvalidIndexException(index); // } // } // // boolean isIndexValid(int index) { // return index >= 0 && index <= getMaxIndex(); // } // // int getMaxIndex() { // return Math.min(addedElementsNumber, points.length) - 1; // } // // void slidePointsToTheLeft() { // TrailPoint p0 = points[0]; // for (int i = 0; i < points.length-1; i++) { // points[i] = points[i+1]; // } // points[points.length-1] = p0; // } // // void doAdd(int x, int y) { // points[getInsertIndex()].set(x, y); // addedElementsNumber++; // } // // public TrailPoint getElementAt(int index) { // if (isIndexValid(index)) { // return points[index]; // } else { // throw getInvalidIndexException(index); // } // } // // public TrailPoint getLastElement() { // return getElementAt(getLastElementIndex()); // } // // public boolean isSameAsLast(TrailPoint p) { // if (addedElementsNumber == 0) { // return false; // } else { // return p.isSameAs(points[getLastElementIndex()]); // } // } // // int getInsertIndex() { // return Math.min(addedElementsNumber, points.length - 1); // } // // public int getLastElementIndex() { // return Math.min(addedElementsNumber - 1, points.length - 1); // } // // public boolean isFull() { // return addedElementsNumber >= points.length; // } // // public void removeElementsAtLeftOf(int index) { // if (isIndexValid(index)) { // doRemoveElementsAtLeftOf(index); // } else { // throw getInvalidIndexException(index); // } // } // // private void doRemoveElementsAtLeftOf(int index) { // for (int i = 0; i <= getLastElementIndex()-index; i++) { // int sourceIndex = index + i; // shiftPoint(i, sourceIndex); // } // addedElementsNumber -= index; // } // // private void shiftPoint(int destIndex, int sourceIndex) { // if (sourceIndex < points.length) { // TrailPoint source = points[sourceIndex]; // points[destIndex].set(source.getX(), source.getY()); // } // } // // private SlidingWindowIndexException getInvalidIndexException(int index) { // return new SlidingWindowIndexException(String.format("Invalid index '%d' (max index %d)", index, getMaxIndex())); // } // }
import com.orange.dgil.trail.TestTools; import com.orange.dgil.trail.core.common.TrailPoint; import com.orange.dgil.trail.core.vecto.SlidingWindow; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito;
/** * Trail drawing library * Copyright (C) 2014 Orange * Authors: christophe.maldivi@orange.com, eric.petit@orange.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.orange.dgil.trail.core.vecto.linearwindowfilter; public class LinearWindowFilterDoAddPointTest { private LinearWindowFilter filter; @Before public void setUp() { filter = Mockito.mock(LinearWindowFilter.class); } @Test public void shouldDoAddPointWhenNewPointAvailable() throws IllegalAccessException { // given
// Path: src/main/java/com/orange/dgil/trail/core/common/TrailPoint.java // @Getter // @NoArgsConstructor // public class TrailPoint { // private int x = -1; // private int y = -1; // // public TrailPoint(int x, int y) { // set(x, y); // } // // public void set(int x, int y) { // this.x = x; // this.y = y; // } // // public boolean isSameAs(TrailPoint point) { // return x == point.x && y == point.y; // } // // public double getDistanceTo(TrailPoint point) { // int dx = x - point.getX(); // int dy = y - point.getY(); // return Math.sqrt(dx * dx + dy * dy); // } // // public void deepCopy(TrailPoint point) { // x = point.x; // y = point.y; // } // } // // Path: src/main/java/com/orange/dgil/trail/core/vecto/SlidingWindow.java // public class SlidingWindow { // // private TrailPoint[] points; // // @Getter // private int addedElementsNumber; // // public SlidingWindow(int windowSize) { // setWindowSize(windowSize); // } // // public void setWindowSize(int windowSize) { // points = new TrailPoint[windowSize]; // allocatePoints(); // } // // public int getWindowSize() { // return points.length; // } // // private void allocatePoints() { // for (int i = 0; i < points.length; i++) { // points[i] = new TrailPoint(); // } // } // // public void reset() { // addedElementsNumber = 0; // } // // public void add(int x, int y) { // if (isFull()) { // slidePointsToTheLeft(); // } // doAdd(x, y); // } // // public void add(TrailPoint point) { // add(point.getX(), point.getY()); // } // // public int getX(int index) { // if (isIndexValid(index)) { // return points[index].getX(); // } else { // throw new SlidingWindowIndexException(String.format("Invalid index '%d' (max index %d)", index, getMaxIndex())); // } // } // // public int getY(int index) { // if (isIndexValid(index)) { // return points[index].getY(); // } else { // throw getInvalidIndexException(index); // } // } // // boolean isIndexValid(int index) { // return index >= 0 && index <= getMaxIndex(); // } // // int getMaxIndex() { // return Math.min(addedElementsNumber, points.length) - 1; // } // // void slidePointsToTheLeft() { // TrailPoint p0 = points[0]; // for (int i = 0; i < points.length-1; i++) { // points[i] = points[i+1]; // } // points[points.length-1] = p0; // } // // void doAdd(int x, int y) { // points[getInsertIndex()].set(x, y); // addedElementsNumber++; // } // // public TrailPoint getElementAt(int index) { // if (isIndexValid(index)) { // return points[index]; // } else { // throw getInvalidIndexException(index); // } // } // // public TrailPoint getLastElement() { // return getElementAt(getLastElementIndex()); // } // // public boolean isSameAsLast(TrailPoint p) { // if (addedElementsNumber == 0) { // return false; // } else { // return p.isSameAs(points[getLastElementIndex()]); // } // } // // int getInsertIndex() { // return Math.min(addedElementsNumber, points.length - 1); // } // // public int getLastElementIndex() { // return Math.min(addedElementsNumber - 1, points.length - 1); // } // // public boolean isFull() { // return addedElementsNumber >= points.length; // } // // public void removeElementsAtLeftOf(int index) { // if (isIndexValid(index)) { // doRemoveElementsAtLeftOf(index); // } else { // throw getInvalidIndexException(index); // } // } // // private void doRemoveElementsAtLeftOf(int index) { // for (int i = 0; i <= getLastElementIndex()-index; i++) { // int sourceIndex = index + i; // shiftPoint(i, sourceIndex); // } // addedElementsNumber -= index; // } // // private void shiftPoint(int destIndex, int sourceIndex) { // if (sourceIndex < points.length) { // TrailPoint source = points[sourceIndex]; // points[destIndex].set(source.getX(), source.getY()); // } // } // // private SlidingWindowIndexException getInvalidIndexException(int index) { // return new SlidingWindowIndexException(String.format("Invalid index '%d' (max index %d)", index, getMaxIndex())); // } // } // Path: src/test/java/com/orange/dgil/trail/core/vecto/linearwindowfilter/LinearWindowFilterDoAddPointTest.java import com.orange.dgil.trail.TestTools; import com.orange.dgil.trail.core.common.TrailPoint; import com.orange.dgil.trail.core.vecto.SlidingWindow; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; /** * Trail drawing library * Copyright (C) 2014 Orange * Authors: christophe.maldivi@orange.com, eric.petit@orange.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.orange.dgil.trail.core.vecto.linearwindowfilter; public class LinearWindowFilterDoAddPointTest { private LinearWindowFilter filter; @Before public void setUp() { filter = Mockito.mock(LinearWindowFilter.class); } @Test public void shouldDoAddPointWhenNewPointAvailable() throws IllegalAccessException { // given
SlidingWindow slidingWindow = Mockito.mock(SlidingWindow.class);
Orange-OpenSource/android-trail-drawing
src/test/java/com/orange/dgil/trail/core/vecto/linearwindowfilter/LinearWindowFilterDoAddPointTest.java
// Path: src/main/java/com/orange/dgil/trail/core/common/TrailPoint.java // @Getter // @NoArgsConstructor // public class TrailPoint { // private int x = -1; // private int y = -1; // // public TrailPoint(int x, int y) { // set(x, y); // } // // public void set(int x, int y) { // this.x = x; // this.y = y; // } // // public boolean isSameAs(TrailPoint point) { // return x == point.x && y == point.y; // } // // public double getDistanceTo(TrailPoint point) { // int dx = x - point.getX(); // int dy = y - point.getY(); // return Math.sqrt(dx * dx + dy * dy); // } // // public void deepCopy(TrailPoint point) { // x = point.x; // y = point.y; // } // } // // Path: src/main/java/com/orange/dgil/trail/core/vecto/SlidingWindow.java // public class SlidingWindow { // // private TrailPoint[] points; // // @Getter // private int addedElementsNumber; // // public SlidingWindow(int windowSize) { // setWindowSize(windowSize); // } // // public void setWindowSize(int windowSize) { // points = new TrailPoint[windowSize]; // allocatePoints(); // } // // public int getWindowSize() { // return points.length; // } // // private void allocatePoints() { // for (int i = 0; i < points.length; i++) { // points[i] = new TrailPoint(); // } // } // // public void reset() { // addedElementsNumber = 0; // } // // public void add(int x, int y) { // if (isFull()) { // slidePointsToTheLeft(); // } // doAdd(x, y); // } // // public void add(TrailPoint point) { // add(point.getX(), point.getY()); // } // // public int getX(int index) { // if (isIndexValid(index)) { // return points[index].getX(); // } else { // throw new SlidingWindowIndexException(String.format("Invalid index '%d' (max index %d)", index, getMaxIndex())); // } // } // // public int getY(int index) { // if (isIndexValid(index)) { // return points[index].getY(); // } else { // throw getInvalidIndexException(index); // } // } // // boolean isIndexValid(int index) { // return index >= 0 && index <= getMaxIndex(); // } // // int getMaxIndex() { // return Math.min(addedElementsNumber, points.length) - 1; // } // // void slidePointsToTheLeft() { // TrailPoint p0 = points[0]; // for (int i = 0; i < points.length-1; i++) { // points[i] = points[i+1]; // } // points[points.length-1] = p0; // } // // void doAdd(int x, int y) { // points[getInsertIndex()].set(x, y); // addedElementsNumber++; // } // // public TrailPoint getElementAt(int index) { // if (isIndexValid(index)) { // return points[index]; // } else { // throw getInvalidIndexException(index); // } // } // // public TrailPoint getLastElement() { // return getElementAt(getLastElementIndex()); // } // // public boolean isSameAsLast(TrailPoint p) { // if (addedElementsNumber == 0) { // return false; // } else { // return p.isSameAs(points[getLastElementIndex()]); // } // } // // int getInsertIndex() { // return Math.min(addedElementsNumber, points.length - 1); // } // // public int getLastElementIndex() { // return Math.min(addedElementsNumber - 1, points.length - 1); // } // // public boolean isFull() { // return addedElementsNumber >= points.length; // } // // public void removeElementsAtLeftOf(int index) { // if (isIndexValid(index)) { // doRemoveElementsAtLeftOf(index); // } else { // throw getInvalidIndexException(index); // } // } // // private void doRemoveElementsAtLeftOf(int index) { // for (int i = 0; i <= getLastElementIndex()-index; i++) { // int sourceIndex = index + i; // shiftPoint(i, sourceIndex); // } // addedElementsNumber -= index; // } // // private void shiftPoint(int destIndex, int sourceIndex) { // if (sourceIndex < points.length) { // TrailPoint source = points[sourceIndex]; // points[destIndex].set(source.getX(), source.getY()); // } // } // // private SlidingWindowIndexException getInvalidIndexException(int index) { // return new SlidingWindowIndexException(String.format("Invalid index '%d' (max index %d)", index, getMaxIndex())); // } // }
import com.orange.dgil.trail.TestTools; import com.orange.dgil.trail.core.common.TrailPoint; import com.orange.dgil.trail.core.vecto.SlidingWindow; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito;
/** * Trail drawing library * Copyright (C) 2014 Orange * Authors: christophe.maldivi@orange.com, eric.petit@orange.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.orange.dgil.trail.core.vecto.linearwindowfilter; public class LinearWindowFilterDoAddPointTest { private LinearWindowFilter filter; @Before public void setUp() { filter = Mockito.mock(LinearWindowFilter.class); } @Test public void shouldDoAddPointWhenNewPointAvailable() throws IllegalAccessException { // given SlidingWindow slidingWindow = Mockito.mock(SlidingWindow.class);
// Path: src/main/java/com/orange/dgil/trail/core/common/TrailPoint.java // @Getter // @NoArgsConstructor // public class TrailPoint { // private int x = -1; // private int y = -1; // // public TrailPoint(int x, int y) { // set(x, y); // } // // public void set(int x, int y) { // this.x = x; // this.y = y; // } // // public boolean isSameAs(TrailPoint point) { // return x == point.x && y == point.y; // } // // public double getDistanceTo(TrailPoint point) { // int dx = x - point.getX(); // int dy = y - point.getY(); // return Math.sqrt(dx * dx + dy * dy); // } // // public void deepCopy(TrailPoint point) { // x = point.x; // y = point.y; // } // } // // Path: src/main/java/com/orange/dgil/trail/core/vecto/SlidingWindow.java // public class SlidingWindow { // // private TrailPoint[] points; // // @Getter // private int addedElementsNumber; // // public SlidingWindow(int windowSize) { // setWindowSize(windowSize); // } // // public void setWindowSize(int windowSize) { // points = new TrailPoint[windowSize]; // allocatePoints(); // } // // public int getWindowSize() { // return points.length; // } // // private void allocatePoints() { // for (int i = 0; i < points.length; i++) { // points[i] = new TrailPoint(); // } // } // // public void reset() { // addedElementsNumber = 0; // } // // public void add(int x, int y) { // if (isFull()) { // slidePointsToTheLeft(); // } // doAdd(x, y); // } // // public void add(TrailPoint point) { // add(point.getX(), point.getY()); // } // // public int getX(int index) { // if (isIndexValid(index)) { // return points[index].getX(); // } else { // throw new SlidingWindowIndexException(String.format("Invalid index '%d' (max index %d)", index, getMaxIndex())); // } // } // // public int getY(int index) { // if (isIndexValid(index)) { // return points[index].getY(); // } else { // throw getInvalidIndexException(index); // } // } // // boolean isIndexValid(int index) { // return index >= 0 && index <= getMaxIndex(); // } // // int getMaxIndex() { // return Math.min(addedElementsNumber, points.length) - 1; // } // // void slidePointsToTheLeft() { // TrailPoint p0 = points[0]; // for (int i = 0; i < points.length-1; i++) { // points[i] = points[i+1]; // } // points[points.length-1] = p0; // } // // void doAdd(int x, int y) { // points[getInsertIndex()].set(x, y); // addedElementsNumber++; // } // // public TrailPoint getElementAt(int index) { // if (isIndexValid(index)) { // return points[index]; // } else { // throw getInvalidIndexException(index); // } // } // // public TrailPoint getLastElement() { // return getElementAt(getLastElementIndex()); // } // // public boolean isSameAsLast(TrailPoint p) { // if (addedElementsNumber == 0) { // return false; // } else { // return p.isSameAs(points[getLastElementIndex()]); // } // } // // int getInsertIndex() { // return Math.min(addedElementsNumber, points.length - 1); // } // // public int getLastElementIndex() { // return Math.min(addedElementsNumber - 1, points.length - 1); // } // // public boolean isFull() { // return addedElementsNumber >= points.length; // } // // public void removeElementsAtLeftOf(int index) { // if (isIndexValid(index)) { // doRemoveElementsAtLeftOf(index); // } else { // throw getInvalidIndexException(index); // } // } // // private void doRemoveElementsAtLeftOf(int index) { // for (int i = 0; i <= getLastElementIndex()-index; i++) { // int sourceIndex = index + i; // shiftPoint(i, sourceIndex); // } // addedElementsNumber -= index; // } // // private void shiftPoint(int destIndex, int sourceIndex) { // if (sourceIndex < points.length) { // TrailPoint source = points[sourceIndex]; // points[destIndex].set(source.getX(), source.getY()); // } // } // // private SlidingWindowIndexException getInvalidIndexException(int index) { // return new SlidingWindowIndexException(String.format("Invalid index '%d' (max index %d)", index, getMaxIndex())); // } // } // Path: src/test/java/com/orange/dgil/trail/core/vecto/linearwindowfilter/LinearWindowFilterDoAddPointTest.java import com.orange.dgil.trail.TestTools; import com.orange.dgil.trail.core.common.TrailPoint; import com.orange.dgil.trail.core.vecto.SlidingWindow; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; /** * Trail drawing library * Copyright (C) 2014 Orange * Authors: christophe.maldivi@orange.com, eric.petit@orange.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.orange.dgil.trail.core.vecto.linearwindowfilter; public class LinearWindowFilterDoAddPointTest { private LinearWindowFilter filter; @Before public void setUp() { filter = Mockito.mock(LinearWindowFilter.class); } @Test public void shouldDoAddPointWhenNewPointAvailable() throws IllegalAccessException { // given SlidingWindow slidingWindow = Mockito.mock(SlidingWindow.class);
TrailPoint point = new TrailPoint();