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
eroshenkoam/htmlelements
src/main/java/io/qameta/htmlelements/extension/FilterMethod.java
// Path: src/main/java/io/qameta/htmlelements/context/Context.java // public class Context { // // public static final String DESCRIPTION_KEY = "description"; // // public static final String LISTENERS_KEY = "listeners"; // // public static final String PROPERTIES_KEY = "properties"; // // public static final String PARAMETERS_KEY = "parameters"; // // public static final String DRIVER_KEY = "driver"; // // private Context parent; // // private Store store; // // private ExtensionRegistry registry; // // private Context() { // this.store = new DefaultStore(); // } // // public Optional<Context> getParent() { // return Optional.ofNullable(parent); // } // // private void setParent(Context parent) { // this.parent = parent; // } // // public Store getStore() { // return store; // } // // public ExtensionRegistry getRegistry() { // return registry; // } // // private void setRegistry(ExtensionRegistry registry) { // this.registry = registry; // } // // public Context newChildContext(Method method, Class<?> proxyClass) { // Context childContext = new Context(); // childContext.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(method, null)); // childContext.setRegistry(ExtensionRegistry.create(proxyClass)); // childContext.getRegistry().registerExtensions(method); // childContext.setParent(this); // //extension // getStore().get(PROPERTIES_KEY, Properties.class).ifPresent(properties -> { // Properties child = new Properties(); // child.putAll(properties); // childContext.getStore().put(PROPERTIES_KEY, child); // }); // getStore().get(PARAMETERS_KEY, Properties.class).ifPresent(properties -> { // Properties child = new Properties(); // child.putAll(properties); // childContext.getStore().put(PARAMETERS_KEY, child); // }); // getStore().get(LISTENERS_KEY, List.class).ifPresent(listeners -> { // childContext.getStore().put(LISTENERS_KEY, listeners); // }); // getStore().get(DRIVER_KEY, WebDriver.class).ifPresent(driver -> { // childContext.getStore().put(DRIVER_KEY, driver); // }); // return childContext; // } // // public static Context newWebPageContext(Class<?> webPageClass, WebDriver driver) { // Context context = new Context(); // context.setRegistry(ExtensionRegistry.create(webPageClass)); // context.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(webPageClass)); // context.getStore().put(DRIVER_KEY, driver); // return context; // } // // // }
import io.qameta.htmlelements.context.Context; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Method; import java.util.List; import java.util.function.Predicate; import java.util.stream.Collectors;
package io.qameta.htmlelements.extension; @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @HandleWith(FilterMethod.Extension.class) @ExtendWith(FilterMethod.Extension.class) public @interface FilterMethod { class Extension implements TargetModifier<List>, MethodHandler<Object> { private static final String FILTER_KEY = "filter"; @Override @SuppressWarnings("unchecked")
// Path: src/main/java/io/qameta/htmlelements/context/Context.java // public class Context { // // public static final String DESCRIPTION_KEY = "description"; // // public static final String LISTENERS_KEY = "listeners"; // // public static final String PROPERTIES_KEY = "properties"; // // public static final String PARAMETERS_KEY = "parameters"; // // public static final String DRIVER_KEY = "driver"; // // private Context parent; // // private Store store; // // private ExtensionRegistry registry; // // private Context() { // this.store = new DefaultStore(); // } // // public Optional<Context> getParent() { // return Optional.ofNullable(parent); // } // // private void setParent(Context parent) { // this.parent = parent; // } // // public Store getStore() { // return store; // } // // public ExtensionRegistry getRegistry() { // return registry; // } // // private void setRegistry(ExtensionRegistry registry) { // this.registry = registry; // } // // public Context newChildContext(Method method, Class<?> proxyClass) { // Context childContext = new Context(); // childContext.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(method, null)); // childContext.setRegistry(ExtensionRegistry.create(proxyClass)); // childContext.getRegistry().registerExtensions(method); // childContext.setParent(this); // //extension // getStore().get(PROPERTIES_KEY, Properties.class).ifPresent(properties -> { // Properties child = new Properties(); // child.putAll(properties); // childContext.getStore().put(PROPERTIES_KEY, child); // }); // getStore().get(PARAMETERS_KEY, Properties.class).ifPresent(properties -> { // Properties child = new Properties(); // child.putAll(properties); // childContext.getStore().put(PARAMETERS_KEY, child); // }); // getStore().get(LISTENERS_KEY, List.class).ifPresent(listeners -> { // childContext.getStore().put(LISTENERS_KEY, listeners); // }); // getStore().get(DRIVER_KEY, WebDriver.class).ifPresent(driver -> { // childContext.getStore().put(DRIVER_KEY, driver); // }); // return childContext; // } // // public static Context newWebPageContext(Class<?> webPageClass, WebDriver driver) { // Context context = new Context(); // context.setRegistry(ExtensionRegistry.create(webPageClass)); // context.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(webPageClass)); // context.getStore().put(DRIVER_KEY, driver); // return context; // } // // // } // Path: src/main/java/io/qameta/htmlelements/extension/FilterMethod.java import io.qameta.htmlelements.context.Context; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Method; import java.util.List; import java.util.function.Predicate; import java.util.stream.Collectors; package io.qameta.htmlelements.extension; @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @HandleWith(FilterMethod.Extension.class) @ExtendWith(FilterMethod.Extension.class) public @interface FilterMethod { class Extension implements TargetModifier<List>, MethodHandler<Object> { private static final String FILTER_KEY = "filter"; @Override @SuppressWarnings("unchecked")
public Object handle(Context context, Object proxy, Method method, Object[] args) throws Throwable {
eroshenkoam/htmlelements
src/main/java/io/qameta/htmlelements/extension/DriverProvider.java
// Path: src/main/java/io/qameta/htmlelements/context/Context.java // public class Context { // // public static final String DESCRIPTION_KEY = "description"; // // public static final String LISTENERS_KEY = "listeners"; // // public static final String PROPERTIES_KEY = "properties"; // // public static final String PARAMETERS_KEY = "parameters"; // // public static final String DRIVER_KEY = "driver"; // // private Context parent; // // private Store store; // // private ExtensionRegistry registry; // // private Context() { // this.store = new DefaultStore(); // } // // public Optional<Context> getParent() { // return Optional.ofNullable(parent); // } // // private void setParent(Context parent) { // this.parent = parent; // } // // public Store getStore() { // return store; // } // // public ExtensionRegistry getRegistry() { // return registry; // } // // private void setRegistry(ExtensionRegistry registry) { // this.registry = registry; // } // // public Context newChildContext(Method method, Class<?> proxyClass) { // Context childContext = new Context(); // childContext.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(method, null)); // childContext.setRegistry(ExtensionRegistry.create(proxyClass)); // childContext.getRegistry().registerExtensions(method); // childContext.setParent(this); // //extension // getStore().get(PROPERTIES_KEY, Properties.class).ifPresent(properties -> { // Properties child = new Properties(); // child.putAll(properties); // childContext.getStore().put(PROPERTIES_KEY, child); // }); // getStore().get(PARAMETERS_KEY, Properties.class).ifPresent(properties -> { // Properties child = new Properties(); // child.putAll(properties); // childContext.getStore().put(PARAMETERS_KEY, child); // }); // getStore().get(LISTENERS_KEY, List.class).ifPresent(listeners -> { // childContext.getStore().put(LISTENERS_KEY, listeners); // }); // getStore().get(DRIVER_KEY, WebDriver.class).ifPresent(driver -> { // childContext.getStore().put(DRIVER_KEY, driver); // }); // return childContext; // } // // public static Context newWebPageContext(Class<?> webPageClass, WebDriver driver) { // Context context = new Context(); // context.setRegistry(ExtensionRegistry.create(webPageClass)); // context.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(webPageClass)); // context.getStore().put(DRIVER_KEY, driver); // return context; // } // // // } // // Path: src/main/java/io/qameta/htmlelements/exception/WebPageException.java // public class WebPageException extends RuntimeException { // // public WebPageException(String message) { // super(message); // } // }
import io.qameta.htmlelements.context.Context; import io.qameta.htmlelements.exception.WebPageException; import org.openqa.selenium.WebDriver; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Method; import static io.qameta.htmlelements.context.Store.DRIVER_KEY;
package io.qameta.htmlelements.extension; @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @HandleWith(DriverProvider.Extension.class) @ExtendWith(DriverProvider.Extension.class) public @interface DriverProvider { class Extension implements ContextEnricher, MethodHandler<WebDriver> { @Override
// Path: src/main/java/io/qameta/htmlelements/context/Context.java // public class Context { // // public static final String DESCRIPTION_KEY = "description"; // // public static final String LISTENERS_KEY = "listeners"; // // public static final String PROPERTIES_KEY = "properties"; // // public static final String PARAMETERS_KEY = "parameters"; // // public static final String DRIVER_KEY = "driver"; // // private Context parent; // // private Store store; // // private ExtensionRegistry registry; // // private Context() { // this.store = new DefaultStore(); // } // // public Optional<Context> getParent() { // return Optional.ofNullable(parent); // } // // private void setParent(Context parent) { // this.parent = parent; // } // // public Store getStore() { // return store; // } // // public ExtensionRegistry getRegistry() { // return registry; // } // // private void setRegistry(ExtensionRegistry registry) { // this.registry = registry; // } // // public Context newChildContext(Method method, Class<?> proxyClass) { // Context childContext = new Context(); // childContext.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(method, null)); // childContext.setRegistry(ExtensionRegistry.create(proxyClass)); // childContext.getRegistry().registerExtensions(method); // childContext.setParent(this); // //extension // getStore().get(PROPERTIES_KEY, Properties.class).ifPresent(properties -> { // Properties child = new Properties(); // child.putAll(properties); // childContext.getStore().put(PROPERTIES_KEY, child); // }); // getStore().get(PARAMETERS_KEY, Properties.class).ifPresent(properties -> { // Properties child = new Properties(); // child.putAll(properties); // childContext.getStore().put(PARAMETERS_KEY, child); // }); // getStore().get(LISTENERS_KEY, List.class).ifPresent(listeners -> { // childContext.getStore().put(LISTENERS_KEY, listeners); // }); // getStore().get(DRIVER_KEY, WebDriver.class).ifPresent(driver -> { // childContext.getStore().put(DRIVER_KEY, driver); // }); // return childContext; // } // // public static Context newWebPageContext(Class<?> webPageClass, WebDriver driver) { // Context context = new Context(); // context.setRegistry(ExtensionRegistry.create(webPageClass)); // context.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(webPageClass)); // context.getStore().put(DRIVER_KEY, driver); // return context; // } // // // } // // Path: src/main/java/io/qameta/htmlelements/exception/WebPageException.java // public class WebPageException extends RuntimeException { // // public WebPageException(String message) { // super(message); // } // } // Path: src/main/java/io/qameta/htmlelements/extension/DriverProvider.java import io.qameta.htmlelements.context.Context; import io.qameta.htmlelements.exception.WebPageException; import org.openqa.selenium.WebDriver; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Method; import static io.qameta.htmlelements.context.Store.DRIVER_KEY; package io.qameta.htmlelements.extension; @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @HandleWith(DriverProvider.Extension.class) @ExtendWith(DriverProvider.Extension.class) public @interface DriverProvider { class Extension implements ContextEnricher, MethodHandler<WebDriver> { @Override
public void enrich(Context context, Method method, Object[] args) {
eroshenkoam/htmlelements
src/main/java/io/qameta/htmlelements/extension/DriverProvider.java
// Path: src/main/java/io/qameta/htmlelements/context/Context.java // public class Context { // // public static final String DESCRIPTION_KEY = "description"; // // public static final String LISTENERS_KEY = "listeners"; // // public static final String PROPERTIES_KEY = "properties"; // // public static final String PARAMETERS_KEY = "parameters"; // // public static final String DRIVER_KEY = "driver"; // // private Context parent; // // private Store store; // // private ExtensionRegistry registry; // // private Context() { // this.store = new DefaultStore(); // } // // public Optional<Context> getParent() { // return Optional.ofNullable(parent); // } // // private void setParent(Context parent) { // this.parent = parent; // } // // public Store getStore() { // return store; // } // // public ExtensionRegistry getRegistry() { // return registry; // } // // private void setRegistry(ExtensionRegistry registry) { // this.registry = registry; // } // // public Context newChildContext(Method method, Class<?> proxyClass) { // Context childContext = new Context(); // childContext.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(method, null)); // childContext.setRegistry(ExtensionRegistry.create(proxyClass)); // childContext.getRegistry().registerExtensions(method); // childContext.setParent(this); // //extension // getStore().get(PROPERTIES_KEY, Properties.class).ifPresent(properties -> { // Properties child = new Properties(); // child.putAll(properties); // childContext.getStore().put(PROPERTIES_KEY, child); // }); // getStore().get(PARAMETERS_KEY, Properties.class).ifPresent(properties -> { // Properties child = new Properties(); // child.putAll(properties); // childContext.getStore().put(PARAMETERS_KEY, child); // }); // getStore().get(LISTENERS_KEY, List.class).ifPresent(listeners -> { // childContext.getStore().put(LISTENERS_KEY, listeners); // }); // getStore().get(DRIVER_KEY, WebDriver.class).ifPresent(driver -> { // childContext.getStore().put(DRIVER_KEY, driver); // }); // return childContext; // } // // public static Context newWebPageContext(Class<?> webPageClass, WebDriver driver) { // Context context = new Context(); // context.setRegistry(ExtensionRegistry.create(webPageClass)); // context.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(webPageClass)); // context.getStore().put(DRIVER_KEY, driver); // return context; // } // // // } // // Path: src/main/java/io/qameta/htmlelements/exception/WebPageException.java // public class WebPageException extends RuntimeException { // // public WebPageException(String message) { // super(message); // } // }
import io.qameta.htmlelements.context.Context; import io.qameta.htmlelements.exception.WebPageException; import org.openqa.selenium.WebDriver; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Method; import static io.qameta.htmlelements.context.Store.DRIVER_KEY;
package io.qameta.htmlelements.extension; @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @HandleWith(DriverProvider.Extension.class) @ExtendWith(DriverProvider.Extension.class) public @interface DriverProvider { class Extension implements ContextEnricher, MethodHandler<WebDriver> { @Override public void enrich(Context context, Method method, Object[] args) { context.getParent().ifPresent(parent -> { parent.getStore().get(DRIVER_KEY, WebDriver.class).ifPresent(driver -> { context.getStore().put(DRIVER_KEY, driver); }); }); } @Override public WebDriver handle(Context context, Object proxy, Method method, Object[] args) throws Throwable { return context.getStore().get(DRIVER_KEY, WebDriver.class)
// Path: src/main/java/io/qameta/htmlelements/context/Context.java // public class Context { // // public static final String DESCRIPTION_KEY = "description"; // // public static final String LISTENERS_KEY = "listeners"; // // public static final String PROPERTIES_KEY = "properties"; // // public static final String PARAMETERS_KEY = "parameters"; // // public static final String DRIVER_KEY = "driver"; // // private Context parent; // // private Store store; // // private ExtensionRegistry registry; // // private Context() { // this.store = new DefaultStore(); // } // // public Optional<Context> getParent() { // return Optional.ofNullable(parent); // } // // private void setParent(Context parent) { // this.parent = parent; // } // // public Store getStore() { // return store; // } // // public ExtensionRegistry getRegistry() { // return registry; // } // // private void setRegistry(ExtensionRegistry registry) { // this.registry = registry; // } // // public Context newChildContext(Method method, Class<?> proxyClass) { // Context childContext = new Context(); // childContext.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(method, null)); // childContext.setRegistry(ExtensionRegistry.create(proxyClass)); // childContext.getRegistry().registerExtensions(method); // childContext.setParent(this); // //extension // getStore().get(PROPERTIES_KEY, Properties.class).ifPresent(properties -> { // Properties child = new Properties(); // child.putAll(properties); // childContext.getStore().put(PROPERTIES_KEY, child); // }); // getStore().get(PARAMETERS_KEY, Properties.class).ifPresent(properties -> { // Properties child = new Properties(); // child.putAll(properties); // childContext.getStore().put(PARAMETERS_KEY, child); // }); // getStore().get(LISTENERS_KEY, List.class).ifPresent(listeners -> { // childContext.getStore().put(LISTENERS_KEY, listeners); // }); // getStore().get(DRIVER_KEY, WebDriver.class).ifPresent(driver -> { // childContext.getStore().put(DRIVER_KEY, driver); // }); // return childContext; // } // // public static Context newWebPageContext(Class<?> webPageClass, WebDriver driver) { // Context context = new Context(); // context.setRegistry(ExtensionRegistry.create(webPageClass)); // context.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(webPageClass)); // context.getStore().put(DRIVER_KEY, driver); // return context; // } // // // } // // Path: src/main/java/io/qameta/htmlelements/exception/WebPageException.java // public class WebPageException extends RuntimeException { // // public WebPageException(String message) { // super(message); // } // } // Path: src/main/java/io/qameta/htmlelements/extension/DriverProvider.java import io.qameta.htmlelements.context.Context; import io.qameta.htmlelements.exception.WebPageException; import org.openqa.selenium.WebDriver; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Method; import static io.qameta.htmlelements.context.Store.DRIVER_KEY; package io.qameta.htmlelements.extension; @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @HandleWith(DriverProvider.Extension.class) @ExtendWith(DriverProvider.Extension.class) public @interface DriverProvider { class Extension implements ContextEnricher, MethodHandler<WebDriver> { @Override public void enrich(Context context, Method method, Object[] args) { context.getParent().ifPresent(parent -> { parent.getStore().get(DRIVER_KEY, WebDriver.class).ifPresent(driver -> { context.getStore().put(DRIVER_KEY, driver); }); }); } @Override public WebDriver handle(Context context, Object proxy, Method method, Object[] args) throws Throwable { return context.getStore().get(DRIVER_KEY, WebDriver.class)
.orElseThrow(() -> new WebPageException("WebDriver is missing"));
eroshenkoam/htmlelements
src/main/java/io/qameta/htmlelements/util/WebDriverUtils.java
// Path: src/main/java/io/qameta/htmlelements/exception/WebPageException.java // public class WebPageException extends RuntimeException { // // public WebPageException(String message) { // super(message); // } // }
import io.qameta.htmlelements.exception.WebPageException; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver;
package io.qameta.htmlelements.util; /** * @author ehborisov */ public class WebDriverUtils { public static boolean pageIsLoaded(WebDriver webDriver) { if (webDriver instanceof JavascriptExecutor) { Object result = ((JavascriptExecutor) webDriver) .executeScript("if (document.readyState) return document.readyState;"); return result != null && "complete".equals(result); } else {
// Path: src/main/java/io/qameta/htmlelements/exception/WebPageException.java // public class WebPageException extends RuntimeException { // // public WebPageException(String message) { // super(message); // } // } // Path: src/main/java/io/qameta/htmlelements/util/WebDriverUtils.java import io.qameta.htmlelements.exception.WebPageException; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; package io.qameta.htmlelements.util; /** * @author ehborisov */ public class WebDriverUtils { public static boolean pageIsLoaded(WebDriver webDriver) { if (webDriver instanceof JavascriptExecutor) { Object result = ((JavascriptExecutor) webDriver) .executeScript("if (document.readyState) return document.readyState;"); return result != null && "complete".equals(result); } else {
throw new WebPageException("Driver must support javascript execution");
eroshenkoam/htmlelements
src/main/java/io/qameta/htmlelements/extension/ExtensionRegistry.java
// Path: src/main/java/io/qameta/htmlelements/util/ReflectionUtils.java // public class ReflectionUtils { // // public static <T> T newInstance(Class<T> clazz) { // try { // return ConstructorUtils.invokeConstructor(clazz); // } catch (Exception e) { // throw new RuntimeException(e); // } // } // // private static List<Class<?>> getAllInterfaces(Class<?>[] classes) { // List<Class<?>> result = new ArrayList<>(); // Arrays.stream(classes).forEach(clazz -> { // result.addAll(ClassUtils.getAllInterfaces(clazz)); // result.add(clazz); // }); // return result; // } // // public static List<Method> getMethods(Class<?>... clazz) { // // return getAllInterfaces(clazz).stream() // .flatMap(m -> stream(m.getDeclaredMethods())) // .collect(Collectors.toList()); // } // // public static List<String> getMethodsNames(Class<?>[] clazz, String... additional) { // return Stream.concat( // Arrays.stream(additional), // getAllInterfaces(clazz).stream() // .flatMap(m -> stream(m.getDeclaredMethods())) // .map(Method::getName) // ).collect(Collectors.toList()); // } // // public static Map<String, String> getLocalParameters(Method method, Object[] args) { // Map<String, String> parameters = new HashMap<>(); // if (args == null) { // return parameters; // } // // for (int i = 0; i < args.length; i++) { // parameters.put(method.getParameters()[i].getAnnotation(Param.class).value(), args[i].toString()); // } // return parameters; // } // // public static String getDescription(Class<?> clazz) { // return splitCamelCase(clazz.getSimpleName()); // } // // public static String getSelector(Method method, Object[] args, Map<String, String> globalParameters) { // Map<String, String> parameters = new HashMap<>(); // parameters.putAll(globalParameters); // parameters.putAll(getLocalParameters(method, args)); // // String selector = method.getAnnotation(FindBy.class).value(); // for (String key : parameters.keySet()) { // selector = selector.replaceAll("\\{\\{ " + key + " \\}\\}", parameters.get(key)); // } // return selector; // } // // public static String getDescription(Method method, Object[] args) { // if (method.isAnnotationPresent(Description.class)) { // Map<String, String> parameters = getLocalParameters(method, args); // String name = method.getAnnotation(Description.class).value(); // for (String key : parameters.keySet()) { // name = name.replaceAll("\\{\\{ " + key + " \\}\\}", parameters.get(key)); // } // return name; // } else { // return splitCamelCase(method.getName()); // } // } // // private static String splitCamelCase(String text) { // return Joiner.on(" ").join(StringUtils.splitByCharacterTypeCamelCase(text)); // } // // }
import io.qameta.htmlelements.annotation.Description; import io.qameta.htmlelements.util.ReflectionUtils; import java.lang.reflect.AnnotatedElement; import java.lang.reflect.Method; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors;
package io.qameta.htmlelements.extension; public class ExtensionRegistry { public static ExtensionRegistry create(Class<?> extensionClass) { ExtensionRegistry registry = new ExtensionRegistry();
// Path: src/main/java/io/qameta/htmlelements/util/ReflectionUtils.java // public class ReflectionUtils { // // public static <T> T newInstance(Class<T> clazz) { // try { // return ConstructorUtils.invokeConstructor(clazz); // } catch (Exception e) { // throw new RuntimeException(e); // } // } // // private static List<Class<?>> getAllInterfaces(Class<?>[] classes) { // List<Class<?>> result = new ArrayList<>(); // Arrays.stream(classes).forEach(clazz -> { // result.addAll(ClassUtils.getAllInterfaces(clazz)); // result.add(clazz); // }); // return result; // } // // public static List<Method> getMethods(Class<?>... clazz) { // // return getAllInterfaces(clazz).stream() // .flatMap(m -> stream(m.getDeclaredMethods())) // .collect(Collectors.toList()); // } // // public static List<String> getMethodsNames(Class<?>[] clazz, String... additional) { // return Stream.concat( // Arrays.stream(additional), // getAllInterfaces(clazz).stream() // .flatMap(m -> stream(m.getDeclaredMethods())) // .map(Method::getName) // ).collect(Collectors.toList()); // } // // public static Map<String, String> getLocalParameters(Method method, Object[] args) { // Map<String, String> parameters = new HashMap<>(); // if (args == null) { // return parameters; // } // // for (int i = 0; i < args.length; i++) { // parameters.put(method.getParameters()[i].getAnnotation(Param.class).value(), args[i].toString()); // } // return parameters; // } // // public static String getDescription(Class<?> clazz) { // return splitCamelCase(clazz.getSimpleName()); // } // // public static String getSelector(Method method, Object[] args, Map<String, String> globalParameters) { // Map<String, String> parameters = new HashMap<>(); // parameters.putAll(globalParameters); // parameters.putAll(getLocalParameters(method, args)); // // String selector = method.getAnnotation(FindBy.class).value(); // for (String key : parameters.keySet()) { // selector = selector.replaceAll("\\{\\{ " + key + " \\}\\}", parameters.get(key)); // } // return selector; // } // // public static String getDescription(Method method, Object[] args) { // if (method.isAnnotationPresent(Description.class)) { // Map<String, String> parameters = getLocalParameters(method, args); // String name = method.getAnnotation(Description.class).value(); // for (String key : parameters.keySet()) { // name = name.replaceAll("\\{\\{ " + key + " \\}\\}", parameters.get(key)); // } // return name; // } else { // return splitCamelCase(method.getName()); // } // } // // private static String splitCamelCase(String text) { // return Joiner.on(" ").join(StringUtils.splitByCharacterTypeCamelCase(text)); // } // // } // Path: src/main/java/io/qameta/htmlelements/extension/ExtensionRegistry.java import io.qameta.htmlelements.annotation.Description; import io.qameta.htmlelements.util.ReflectionUtils; import java.lang.reflect.AnnotatedElement; import java.lang.reflect.Method; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; package io.qameta.htmlelements.extension; public class ExtensionRegistry { public static ExtensionRegistry create(Class<?> extensionClass) { ExtensionRegistry registry = new ExtensionRegistry();
ReflectionUtils.getMethods(extensionClass)
eroshenkoam/htmlelements
src/main/java/io/qameta/htmlelements/extension/elements/SetFileInputMethod.java
// Path: src/main/java/io/qameta/htmlelements/context/Context.java // public class Context { // // public static final String DESCRIPTION_KEY = "description"; // // public static final String LISTENERS_KEY = "listeners"; // // public static final String PROPERTIES_KEY = "properties"; // // public static final String PARAMETERS_KEY = "parameters"; // // public static final String DRIVER_KEY = "driver"; // // private Context parent; // // private Store store; // // private ExtensionRegistry registry; // // private Context() { // this.store = new DefaultStore(); // } // // public Optional<Context> getParent() { // return Optional.ofNullable(parent); // } // // private void setParent(Context parent) { // this.parent = parent; // } // // public Store getStore() { // return store; // } // // public ExtensionRegistry getRegistry() { // return registry; // } // // private void setRegistry(ExtensionRegistry registry) { // this.registry = registry; // } // // public Context newChildContext(Method method, Class<?> proxyClass) { // Context childContext = new Context(); // childContext.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(method, null)); // childContext.setRegistry(ExtensionRegistry.create(proxyClass)); // childContext.getRegistry().registerExtensions(method); // childContext.setParent(this); // //extension // getStore().get(PROPERTIES_KEY, Properties.class).ifPresent(properties -> { // Properties child = new Properties(); // child.putAll(properties); // childContext.getStore().put(PROPERTIES_KEY, child); // }); // getStore().get(PARAMETERS_KEY, Properties.class).ifPresent(properties -> { // Properties child = new Properties(); // child.putAll(properties); // childContext.getStore().put(PARAMETERS_KEY, child); // }); // getStore().get(LISTENERS_KEY, List.class).ifPresent(listeners -> { // childContext.getStore().put(LISTENERS_KEY, listeners); // }); // getStore().get(DRIVER_KEY, WebDriver.class).ifPresent(driver -> { // childContext.getStore().put(DRIVER_KEY, driver); // }); // return childContext; // } // // public static Context newWebPageContext(Class<?> webPageClass, WebDriver driver) { // Context context = new Context(); // context.setRegistry(ExtensionRegistry.create(webPageClass)); // context.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(webPageClass)); // context.getStore().put(DRIVER_KEY, driver); // return context; // } // // // } // // Path: src/main/java/io/qameta/htmlelements/exception/WebPageException.java // public class WebPageException extends RuntimeException { // // public WebPageException(String message) { // super(message); // } // } // // Path: src/main/java/io/qameta/htmlelements/extension/MethodHandler.java // public interface MethodHandler<R> { // // R handle(Context context, Object proxy, Method method, Object[] args) throws Throwable; // // }
import io.qameta.htmlelements.context.Context; import io.qameta.htmlelements.exception.WebPageException; import io.qameta.htmlelements.extension.HandleWith; import io.qameta.htmlelements.extension.MethodHandler; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.remote.LocalFileDetector; import org.openqa.selenium.remote.RemoteWebDriver; import org.openqa.selenium.remote.RemoteWebElement; import java.io.File; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Method; import java.net.URL; import java.util.Optional; import static io.qameta.htmlelements.context.Store.DRIVER_KEY;
package io.qameta.htmlelements.extension.elements; /** * @author ehborisov */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @HandleWith(SetFileInputMethod.Extension.class) public @interface SetFileInputMethod {
// Path: src/main/java/io/qameta/htmlelements/context/Context.java // public class Context { // // public static final String DESCRIPTION_KEY = "description"; // // public static final String LISTENERS_KEY = "listeners"; // // public static final String PROPERTIES_KEY = "properties"; // // public static final String PARAMETERS_KEY = "parameters"; // // public static final String DRIVER_KEY = "driver"; // // private Context parent; // // private Store store; // // private ExtensionRegistry registry; // // private Context() { // this.store = new DefaultStore(); // } // // public Optional<Context> getParent() { // return Optional.ofNullable(parent); // } // // private void setParent(Context parent) { // this.parent = parent; // } // // public Store getStore() { // return store; // } // // public ExtensionRegistry getRegistry() { // return registry; // } // // private void setRegistry(ExtensionRegistry registry) { // this.registry = registry; // } // // public Context newChildContext(Method method, Class<?> proxyClass) { // Context childContext = new Context(); // childContext.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(method, null)); // childContext.setRegistry(ExtensionRegistry.create(proxyClass)); // childContext.getRegistry().registerExtensions(method); // childContext.setParent(this); // //extension // getStore().get(PROPERTIES_KEY, Properties.class).ifPresent(properties -> { // Properties child = new Properties(); // child.putAll(properties); // childContext.getStore().put(PROPERTIES_KEY, child); // }); // getStore().get(PARAMETERS_KEY, Properties.class).ifPresent(properties -> { // Properties child = new Properties(); // child.putAll(properties); // childContext.getStore().put(PARAMETERS_KEY, child); // }); // getStore().get(LISTENERS_KEY, List.class).ifPresent(listeners -> { // childContext.getStore().put(LISTENERS_KEY, listeners); // }); // getStore().get(DRIVER_KEY, WebDriver.class).ifPresent(driver -> { // childContext.getStore().put(DRIVER_KEY, driver); // }); // return childContext; // } // // public static Context newWebPageContext(Class<?> webPageClass, WebDriver driver) { // Context context = new Context(); // context.setRegistry(ExtensionRegistry.create(webPageClass)); // context.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(webPageClass)); // context.getStore().put(DRIVER_KEY, driver); // return context; // } // // // } // // Path: src/main/java/io/qameta/htmlelements/exception/WebPageException.java // public class WebPageException extends RuntimeException { // // public WebPageException(String message) { // super(message); // } // } // // Path: src/main/java/io/qameta/htmlelements/extension/MethodHandler.java // public interface MethodHandler<R> { // // R handle(Context context, Object proxy, Method method, Object[] args) throws Throwable; // // } // Path: src/main/java/io/qameta/htmlelements/extension/elements/SetFileInputMethod.java import io.qameta.htmlelements.context.Context; import io.qameta.htmlelements.exception.WebPageException; import io.qameta.htmlelements.extension.HandleWith; import io.qameta.htmlelements.extension.MethodHandler; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.remote.LocalFileDetector; import org.openqa.selenium.remote.RemoteWebDriver; import org.openqa.selenium.remote.RemoteWebElement; import java.io.File; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Method; import java.net.URL; import java.util.Optional; import static io.qameta.htmlelements.context.Store.DRIVER_KEY; package io.qameta.htmlelements.extension.elements; /** * @author ehborisov */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @HandleWith(SetFileInputMethod.Extension.class) public @interface SetFileInputMethod {
class Extension implements MethodHandler {
eroshenkoam/htmlelements
src/main/java/io/qameta/htmlelements/extension/elements/SetFileInputMethod.java
// Path: src/main/java/io/qameta/htmlelements/context/Context.java // public class Context { // // public static final String DESCRIPTION_KEY = "description"; // // public static final String LISTENERS_KEY = "listeners"; // // public static final String PROPERTIES_KEY = "properties"; // // public static final String PARAMETERS_KEY = "parameters"; // // public static final String DRIVER_KEY = "driver"; // // private Context parent; // // private Store store; // // private ExtensionRegistry registry; // // private Context() { // this.store = new DefaultStore(); // } // // public Optional<Context> getParent() { // return Optional.ofNullable(parent); // } // // private void setParent(Context parent) { // this.parent = parent; // } // // public Store getStore() { // return store; // } // // public ExtensionRegistry getRegistry() { // return registry; // } // // private void setRegistry(ExtensionRegistry registry) { // this.registry = registry; // } // // public Context newChildContext(Method method, Class<?> proxyClass) { // Context childContext = new Context(); // childContext.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(method, null)); // childContext.setRegistry(ExtensionRegistry.create(proxyClass)); // childContext.getRegistry().registerExtensions(method); // childContext.setParent(this); // //extension // getStore().get(PROPERTIES_KEY, Properties.class).ifPresent(properties -> { // Properties child = new Properties(); // child.putAll(properties); // childContext.getStore().put(PROPERTIES_KEY, child); // }); // getStore().get(PARAMETERS_KEY, Properties.class).ifPresent(properties -> { // Properties child = new Properties(); // child.putAll(properties); // childContext.getStore().put(PARAMETERS_KEY, child); // }); // getStore().get(LISTENERS_KEY, List.class).ifPresent(listeners -> { // childContext.getStore().put(LISTENERS_KEY, listeners); // }); // getStore().get(DRIVER_KEY, WebDriver.class).ifPresent(driver -> { // childContext.getStore().put(DRIVER_KEY, driver); // }); // return childContext; // } // // public static Context newWebPageContext(Class<?> webPageClass, WebDriver driver) { // Context context = new Context(); // context.setRegistry(ExtensionRegistry.create(webPageClass)); // context.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(webPageClass)); // context.getStore().put(DRIVER_KEY, driver); // return context; // } // // // } // // Path: src/main/java/io/qameta/htmlelements/exception/WebPageException.java // public class WebPageException extends RuntimeException { // // public WebPageException(String message) { // super(message); // } // } // // Path: src/main/java/io/qameta/htmlelements/extension/MethodHandler.java // public interface MethodHandler<R> { // // R handle(Context context, Object proxy, Method method, Object[] args) throws Throwable; // // }
import io.qameta.htmlelements.context.Context; import io.qameta.htmlelements.exception.WebPageException; import io.qameta.htmlelements.extension.HandleWith; import io.qameta.htmlelements.extension.MethodHandler; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.remote.LocalFileDetector; import org.openqa.selenium.remote.RemoteWebDriver; import org.openqa.selenium.remote.RemoteWebElement; import java.io.File; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Method; import java.net.URL; import java.util.Optional; import static io.qameta.htmlelements.context.Store.DRIVER_KEY;
package io.qameta.htmlelements.extension.elements; /** * @author ehborisov */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @HandleWith(SetFileInputMethod.Extension.class) public @interface SetFileInputMethod { class Extension implements MethodHandler { @Override @SuppressWarnings("unchecked")
// Path: src/main/java/io/qameta/htmlelements/context/Context.java // public class Context { // // public static final String DESCRIPTION_KEY = "description"; // // public static final String LISTENERS_KEY = "listeners"; // // public static final String PROPERTIES_KEY = "properties"; // // public static final String PARAMETERS_KEY = "parameters"; // // public static final String DRIVER_KEY = "driver"; // // private Context parent; // // private Store store; // // private ExtensionRegistry registry; // // private Context() { // this.store = new DefaultStore(); // } // // public Optional<Context> getParent() { // return Optional.ofNullable(parent); // } // // private void setParent(Context parent) { // this.parent = parent; // } // // public Store getStore() { // return store; // } // // public ExtensionRegistry getRegistry() { // return registry; // } // // private void setRegistry(ExtensionRegistry registry) { // this.registry = registry; // } // // public Context newChildContext(Method method, Class<?> proxyClass) { // Context childContext = new Context(); // childContext.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(method, null)); // childContext.setRegistry(ExtensionRegistry.create(proxyClass)); // childContext.getRegistry().registerExtensions(method); // childContext.setParent(this); // //extension // getStore().get(PROPERTIES_KEY, Properties.class).ifPresent(properties -> { // Properties child = new Properties(); // child.putAll(properties); // childContext.getStore().put(PROPERTIES_KEY, child); // }); // getStore().get(PARAMETERS_KEY, Properties.class).ifPresent(properties -> { // Properties child = new Properties(); // child.putAll(properties); // childContext.getStore().put(PARAMETERS_KEY, child); // }); // getStore().get(LISTENERS_KEY, List.class).ifPresent(listeners -> { // childContext.getStore().put(LISTENERS_KEY, listeners); // }); // getStore().get(DRIVER_KEY, WebDriver.class).ifPresent(driver -> { // childContext.getStore().put(DRIVER_KEY, driver); // }); // return childContext; // } // // public static Context newWebPageContext(Class<?> webPageClass, WebDriver driver) { // Context context = new Context(); // context.setRegistry(ExtensionRegistry.create(webPageClass)); // context.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(webPageClass)); // context.getStore().put(DRIVER_KEY, driver); // return context; // } // // // } // // Path: src/main/java/io/qameta/htmlelements/exception/WebPageException.java // public class WebPageException extends RuntimeException { // // public WebPageException(String message) { // super(message); // } // } // // Path: src/main/java/io/qameta/htmlelements/extension/MethodHandler.java // public interface MethodHandler<R> { // // R handle(Context context, Object proxy, Method method, Object[] args) throws Throwable; // // } // Path: src/main/java/io/qameta/htmlelements/extension/elements/SetFileInputMethod.java import io.qameta.htmlelements.context.Context; import io.qameta.htmlelements.exception.WebPageException; import io.qameta.htmlelements.extension.HandleWith; import io.qameta.htmlelements.extension.MethodHandler; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.remote.LocalFileDetector; import org.openqa.selenium.remote.RemoteWebDriver; import org.openqa.selenium.remote.RemoteWebElement; import java.io.File; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Method; import java.net.URL; import java.util.Optional; import static io.qameta.htmlelements.context.Store.DRIVER_KEY; package io.qameta.htmlelements.extension.elements; /** * @author ehborisov */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @HandleWith(SetFileInputMethod.Extension.class) public @interface SetFileInputMethod { class Extension implements MethodHandler { @Override @SuppressWarnings("unchecked")
public Object handle(Context context, Object proxy, Method method, Object[] args) throws Throwable {
eroshenkoam/htmlelements
src/main/java/io/qameta/htmlelements/extension/elements/SetFileInputMethod.java
// Path: src/main/java/io/qameta/htmlelements/context/Context.java // public class Context { // // public static final String DESCRIPTION_KEY = "description"; // // public static final String LISTENERS_KEY = "listeners"; // // public static final String PROPERTIES_KEY = "properties"; // // public static final String PARAMETERS_KEY = "parameters"; // // public static final String DRIVER_KEY = "driver"; // // private Context parent; // // private Store store; // // private ExtensionRegistry registry; // // private Context() { // this.store = new DefaultStore(); // } // // public Optional<Context> getParent() { // return Optional.ofNullable(parent); // } // // private void setParent(Context parent) { // this.parent = parent; // } // // public Store getStore() { // return store; // } // // public ExtensionRegistry getRegistry() { // return registry; // } // // private void setRegistry(ExtensionRegistry registry) { // this.registry = registry; // } // // public Context newChildContext(Method method, Class<?> proxyClass) { // Context childContext = new Context(); // childContext.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(method, null)); // childContext.setRegistry(ExtensionRegistry.create(proxyClass)); // childContext.getRegistry().registerExtensions(method); // childContext.setParent(this); // //extension // getStore().get(PROPERTIES_KEY, Properties.class).ifPresent(properties -> { // Properties child = new Properties(); // child.putAll(properties); // childContext.getStore().put(PROPERTIES_KEY, child); // }); // getStore().get(PARAMETERS_KEY, Properties.class).ifPresent(properties -> { // Properties child = new Properties(); // child.putAll(properties); // childContext.getStore().put(PARAMETERS_KEY, child); // }); // getStore().get(LISTENERS_KEY, List.class).ifPresent(listeners -> { // childContext.getStore().put(LISTENERS_KEY, listeners); // }); // getStore().get(DRIVER_KEY, WebDriver.class).ifPresent(driver -> { // childContext.getStore().put(DRIVER_KEY, driver); // }); // return childContext; // } // // public static Context newWebPageContext(Class<?> webPageClass, WebDriver driver) { // Context context = new Context(); // context.setRegistry(ExtensionRegistry.create(webPageClass)); // context.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(webPageClass)); // context.getStore().put(DRIVER_KEY, driver); // return context; // } // // // } // // Path: src/main/java/io/qameta/htmlelements/exception/WebPageException.java // public class WebPageException extends RuntimeException { // // public WebPageException(String message) { // super(message); // } // } // // Path: src/main/java/io/qameta/htmlelements/extension/MethodHandler.java // public interface MethodHandler<R> { // // R handle(Context context, Object proxy, Method method, Object[] args) throws Throwable; // // }
import io.qameta.htmlelements.context.Context; import io.qameta.htmlelements.exception.WebPageException; import io.qameta.htmlelements.extension.HandleWith; import io.qameta.htmlelements.extension.MethodHandler; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.remote.LocalFileDetector; import org.openqa.selenium.remote.RemoteWebDriver; import org.openqa.selenium.remote.RemoteWebElement; import java.io.File; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Method; import java.net.URL; import java.util.Optional; import static io.qameta.htmlelements.context.Store.DRIVER_KEY;
package io.qameta.htmlelements.extension.elements; /** * @author ehborisov */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @HandleWith(SetFileInputMethod.Extension.class) public @interface SetFileInputMethod { class Extension implements MethodHandler { @Override @SuppressWarnings("unchecked") public Object handle(Context context, Object proxy, Method method, Object[] args) throws Throwable { String fileName = (String) args[0]; WebDriver driver = context.getStore().get(DRIVER_KEY, WebDriver.class)
// Path: src/main/java/io/qameta/htmlelements/context/Context.java // public class Context { // // public static final String DESCRIPTION_KEY = "description"; // // public static final String LISTENERS_KEY = "listeners"; // // public static final String PROPERTIES_KEY = "properties"; // // public static final String PARAMETERS_KEY = "parameters"; // // public static final String DRIVER_KEY = "driver"; // // private Context parent; // // private Store store; // // private ExtensionRegistry registry; // // private Context() { // this.store = new DefaultStore(); // } // // public Optional<Context> getParent() { // return Optional.ofNullable(parent); // } // // private void setParent(Context parent) { // this.parent = parent; // } // // public Store getStore() { // return store; // } // // public ExtensionRegistry getRegistry() { // return registry; // } // // private void setRegistry(ExtensionRegistry registry) { // this.registry = registry; // } // // public Context newChildContext(Method method, Class<?> proxyClass) { // Context childContext = new Context(); // childContext.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(method, null)); // childContext.setRegistry(ExtensionRegistry.create(proxyClass)); // childContext.getRegistry().registerExtensions(method); // childContext.setParent(this); // //extension // getStore().get(PROPERTIES_KEY, Properties.class).ifPresent(properties -> { // Properties child = new Properties(); // child.putAll(properties); // childContext.getStore().put(PROPERTIES_KEY, child); // }); // getStore().get(PARAMETERS_KEY, Properties.class).ifPresent(properties -> { // Properties child = new Properties(); // child.putAll(properties); // childContext.getStore().put(PARAMETERS_KEY, child); // }); // getStore().get(LISTENERS_KEY, List.class).ifPresent(listeners -> { // childContext.getStore().put(LISTENERS_KEY, listeners); // }); // getStore().get(DRIVER_KEY, WebDriver.class).ifPresent(driver -> { // childContext.getStore().put(DRIVER_KEY, driver); // }); // return childContext; // } // // public static Context newWebPageContext(Class<?> webPageClass, WebDriver driver) { // Context context = new Context(); // context.setRegistry(ExtensionRegistry.create(webPageClass)); // context.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(webPageClass)); // context.getStore().put(DRIVER_KEY, driver); // return context; // } // // // } // // Path: src/main/java/io/qameta/htmlelements/exception/WebPageException.java // public class WebPageException extends RuntimeException { // // public WebPageException(String message) { // super(message); // } // } // // Path: src/main/java/io/qameta/htmlelements/extension/MethodHandler.java // public interface MethodHandler<R> { // // R handle(Context context, Object proxy, Method method, Object[] args) throws Throwable; // // } // Path: src/main/java/io/qameta/htmlelements/extension/elements/SetFileInputMethod.java import io.qameta.htmlelements.context.Context; import io.qameta.htmlelements.exception.WebPageException; import io.qameta.htmlelements.extension.HandleWith; import io.qameta.htmlelements.extension.MethodHandler; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.remote.LocalFileDetector; import org.openqa.selenium.remote.RemoteWebDriver; import org.openqa.selenium.remote.RemoteWebElement; import java.io.File; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Method; import java.net.URL; import java.util.Optional; import static io.qameta.htmlelements.context.Store.DRIVER_KEY; package io.qameta.htmlelements.extension.elements; /** * @author ehborisov */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @HandleWith(SetFileInputMethod.Extension.class) public @interface SetFileInputMethod { class Extension implements MethodHandler { @Override @SuppressWarnings("unchecked") public Object handle(Context context, Object proxy, Method method, Object[] args) throws Throwable { String fileName = (String) args[0]; WebDriver driver = context.getStore().get(DRIVER_KEY, WebDriver.class)
.orElseThrow(() -> new WebPageException("WebDriver is missing"));
eroshenkoam/htmlelements
src/main/java/io/qameta/htmlelements/extension/ConvertMethod.java
// Path: src/main/java/io/qameta/htmlelements/context/Context.java // public class Context { // // public static final String DESCRIPTION_KEY = "description"; // // public static final String LISTENERS_KEY = "listeners"; // // public static final String PROPERTIES_KEY = "properties"; // // public static final String PARAMETERS_KEY = "parameters"; // // public static final String DRIVER_KEY = "driver"; // // private Context parent; // // private Store store; // // private ExtensionRegistry registry; // // private Context() { // this.store = new DefaultStore(); // } // // public Optional<Context> getParent() { // return Optional.ofNullable(parent); // } // // private void setParent(Context parent) { // this.parent = parent; // } // // public Store getStore() { // return store; // } // // public ExtensionRegistry getRegistry() { // return registry; // } // // private void setRegistry(ExtensionRegistry registry) { // this.registry = registry; // } // // public Context newChildContext(Method method, Class<?> proxyClass) { // Context childContext = new Context(); // childContext.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(method, null)); // childContext.setRegistry(ExtensionRegistry.create(proxyClass)); // childContext.getRegistry().registerExtensions(method); // childContext.setParent(this); // //extension // getStore().get(PROPERTIES_KEY, Properties.class).ifPresent(properties -> { // Properties child = new Properties(); // child.putAll(properties); // childContext.getStore().put(PROPERTIES_KEY, child); // }); // getStore().get(PARAMETERS_KEY, Properties.class).ifPresent(properties -> { // Properties child = new Properties(); // child.putAll(properties); // childContext.getStore().put(PARAMETERS_KEY, child); // }); // getStore().get(LISTENERS_KEY, List.class).ifPresent(listeners -> { // childContext.getStore().put(LISTENERS_KEY, listeners); // }); // getStore().get(DRIVER_KEY, WebDriver.class).ifPresent(driver -> { // childContext.getStore().put(DRIVER_KEY, driver); // }); // return childContext; // } // // public static Context newWebPageContext(Class<?> webPageClass, WebDriver driver) { // Context context = new Context(); // context.setRegistry(ExtensionRegistry.create(webPageClass)); // context.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(webPageClass)); // context.getStore().put(DRIVER_KEY, driver); // return context; // } // // // }
import io.qameta.htmlelements.context.Context; import org.openqa.selenium.WebDriver; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Method; import java.util.List; import java.util.function.Function; import java.util.stream.Collectors;
package io.qameta.htmlelements.extension; @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @HandleWith(ConvertMethod.Extension.class) @ExtendWith(ConvertMethod.Extension.class) public @interface ConvertMethod { class Extension implements TargetModifier<List>, MethodHandler { static final String CONVERTER_KEY = "convert"; @Override @SuppressWarnings("unchecked")
// Path: src/main/java/io/qameta/htmlelements/context/Context.java // public class Context { // // public static final String DESCRIPTION_KEY = "description"; // // public static final String LISTENERS_KEY = "listeners"; // // public static final String PROPERTIES_KEY = "properties"; // // public static final String PARAMETERS_KEY = "parameters"; // // public static final String DRIVER_KEY = "driver"; // // private Context parent; // // private Store store; // // private ExtensionRegistry registry; // // private Context() { // this.store = new DefaultStore(); // } // // public Optional<Context> getParent() { // return Optional.ofNullable(parent); // } // // private void setParent(Context parent) { // this.parent = parent; // } // // public Store getStore() { // return store; // } // // public ExtensionRegistry getRegistry() { // return registry; // } // // private void setRegistry(ExtensionRegistry registry) { // this.registry = registry; // } // // public Context newChildContext(Method method, Class<?> proxyClass) { // Context childContext = new Context(); // childContext.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(method, null)); // childContext.setRegistry(ExtensionRegistry.create(proxyClass)); // childContext.getRegistry().registerExtensions(method); // childContext.setParent(this); // //extension // getStore().get(PROPERTIES_KEY, Properties.class).ifPresent(properties -> { // Properties child = new Properties(); // child.putAll(properties); // childContext.getStore().put(PROPERTIES_KEY, child); // }); // getStore().get(PARAMETERS_KEY, Properties.class).ifPresent(properties -> { // Properties child = new Properties(); // child.putAll(properties); // childContext.getStore().put(PARAMETERS_KEY, child); // }); // getStore().get(LISTENERS_KEY, List.class).ifPresent(listeners -> { // childContext.getStore().put(LISTENERS_KEY, listeners); // }); // getStore().get(DRIVER_KEY, WebDriver.class).ifPresent(driver -> { // childContext.getStore().put(DRIVER_KEY, driver); // }); // return childContext; // } // // public static Context newWebPageContext(Class<?> webPageClass, WebDriver driver) { // Context context = new Context(); // context.setRegistry(ExtensionRegistry.create(webPageClass)); // context.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(webPageClass)); // context.getStore().put(DRIVER_KEY, driver); // return context; // } // // // } // Path: src/main/java/io/qameta/htmlelements/extension/ConvertMethod.java import io.qameta.htmlelements.context.Context; import org.openqa.selenium.WebDriver; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Method; import java.util.List; import java.util.function.Function; import java.util.stream.Collectors; package io.qameta.htmlelements.extension; @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @HandleWith(ConvertMethod.Extension.class) @ExtendWith(ConvertMethod.Extension.class) public @interface ConvertMethod { class Extension implements TargetModifier<List>, MethodHandler { static final String CONVERTER_KEY = "convert"; @Override @SuppressWarnings("unchecked")
public Object handle(Context context, Object proxy, Method method, Object[] args) throws Throwable {
eroshenkoam/htmlelements
src/main/java/io/qameta/htmlelements/extension/WaitUntilMethod.java
// Path: src/main/java/io/qameta/htmlelements/context/Context.java // public class Context { // // public static final String DESCRIPTION_KEY = "description"; // // public static final String LISTENERS_KEY = "listeners"; // // public static final String PROPERTIES_KEY = "properties"; // // public static final String PARAMETERS_KEY = "parameters"; // // public static final String DRIVER_KEY = "driver"; // // private Context parent; // // private Store store; // // private ExtensionRegistry registry; // // private Context() { // this.store = new DefaultStore(); // } // // public Optional<Context> getParent() { // return Optional.ofNullable(parent); // } // // private void setParent(Context parent) { // this.parent = parent; // } // // public Store getStore() { // return store; // } // // public ExtensionRegistry getRegistry() { // return registry; // } // // private void setRegistry(ExtensionRegistry registry) { // this.registry = registry; // } // // public Context newChildContext(Method method, Class<?> proxyClass) { // Context childContext = new Context(); // childContext.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(method, null)); // childContext.setRegistry(ExtensionRegistry.create(proxyClass)); // childContext.getRegistry().registerExtensions(method); // childContext.setParent(this); // //extension // getStore().get(PROPERTIES_KEY, Properties.class).ifPresent(properties -> { // Properties child = new Properties(); // child.putAll(properties); // childContext.getStore().put(PROPERTIES_KEY, child); // }); // getStore().get(PARAMETERS_KEY, Properties.class).ifPresent(properties -> { // Properties child = new Properties(); // child.putAll(properties); // childContext.getStore().put(PARAMETERS_KEY, child); // }); // getStore().get(LISTENERS_KEY, List.class).ifPresent(listeners -> { // childContext.getStore().put(LISTENERS_KEY, listeners); // }); // getStore().get(DRIVER_KEY, WebDriver.class).ifPresent(driver -> { // childContext.getStore().put(DRIVER_KEY, driver); // }); // return childContext; // } // // public static Context newWebPageContext(Class<?> webPageClass, WebDriver driver) { // Context context = new Context(); // context.setRegistry(ExtensionRegistry.create(webPageClass)); // context.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(webPageClass)); // context.getStore().put(DRIVER_KEY, driver); // return context; // } // // // } // // Path: src/main/java/io/qameta/htmlelements/exception/WaitUntilException.java // public class WaitUntilException extends WebDriverException { // // public WaitUntilException(String message) { // super(message); // } // // }
import io.qameta.htmlelements.context.Context; import io.qameta.htmlelements.exception.WaitUntilException; import org.hamcrest.Matcher; import org.hamcrest.StringDescription; import org.openqa.selenium.WebDriverException; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Method;
package io.qameta.htmlelements.extension; @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @HandleWith(WaitUntilMethod.Extension.class) public @interface WaitUntilMethod { class Extension implements MethodHandler<Object> { @Override @SuppressWarnings("unchecked")
// Path: src/main/java/io/qameta/htmlelements/context/Context.java // public class Context { // // public static final String DESCRIPTION_KEY = "description"; // // public static final String LISTENERS_KEY = "listeners"; // // public static final String PROPERTIES_KEY = "properties"; // // public static final String PARAMETERS_KEY = "parameters"; // // public static final String DRIVER_KEY = "driver"; // // private Context parent; // // private Store store; // // private ExtensionRegistry registry; // // private Context() { // this.store = new DefaultStore(); // } // // public Optional<Context> getParent() { // return Optional.ofNullable(parent); // } // // private void setParent(Context parent) { // this.parent = parent; // } // // public Store getStore() { // return store; // } // // public ExtensionRegistry getRegistry() { // return registry; // } // // private void setRegistry(ExtensionRegistry registry) { // this.registry = registry; // } // // public Context newChildContext(Method method, Class<?> proxyClass) { // Context childContext = new Context(); // childContext.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(method, null)); // childContext.setRegistry(ExtensionRegistry.create(proxyClass)); // childContext.getRegistry().registerExtensions(method); // childContext.setParent(this); // //extension // getStore().get(PROPERTIES_KEY, Properties.class).ifPresent(properties -> { // Properties child = new Properties(); // child.putAll(properties); // childContext.getStore().put(PROPERTIES_KEY, child); // }); // getStore().get(PARAMETERS_KEY, Properties.class).ifPresent(properties -> { // Properties child = new Properties(); // child.putAll(properties); // childContext.getStore().put(PARAMETERS_KEY, child); // }); // getStore().get(LISTENERS_KEY, List.class).ifPresent(listeners -> { // childContext.getStore().put(LISTENERS_KEY, listeners); // }); // getStore().get(DRIVER_KEY, WebDriver.class).ifPresent(driver -> { // childContext.getStore().put(DRIVER_KEY, driver); // }); // return childContext; // } // // public static Context newWebPageContext(Class<?> webPageClass, WebDriver driver) { // Context context = new Context(); // context.setRegistry(ExtensionRegistry.create(webPageClass)); // context.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(webPageClass)); // context.getStore().put(DRIVER_KEY, driver); // return context; // } // // // } // // Path: src/main/java/io/qameta/htmlelements/exception/WaitUntilException.java // public class WaitUntilException extends WebDriverException { // // public WaitUntilException(String message) { // super(message); // } // // } // Path: src/main/java/io/qameta/htmlelements/extension/WaitUntilMethod.java import io.qameta.htmlelements.context.Context; import io.qameta.htmlelements.exception.WaitUntilException; import org.hamcrest.Matcher; import org.hamcrest.StringDescription; import org.openqa.selenium.WebDriverException; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Method; package io.qameta.htmlelements.extension; @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @HandleWith(WaitUntilMethod.Extension.class) public @interface WaitUntilMethod { class Extension implements MethodHandler<Object> { @Override @SuppressWarnings("unchecked")
public Object handle(Context context, Object proxy, Method method, Object[] args) throws Throwable {
eroshenkoam/htmlelements
src/main/java/io/qameta/htmlelements/extension/WaitUntilMethod.java
// Path: src/main/java/io/qameta/htmlelements/context/Context.java // public class Context { // // public static final String DESCRIPTION_KEY = "description"; // // public static final String LISTENERS_KEY = "listeners"; // // public static final String PROPERTIES_KEY = "properties"; // // public static final String PARAMETERS_KEY = "parameters"; // // public static final String DRIVER_KEY = "driver"; // // private Context parent; // // private Store store; // // private ExtensionRegistry registry; // // private Context() { // this.store = new DefaultStore(); // } // // public Optional<Context> getParent() { // return Optional.ofNullable(parent); // } // // private void setParent(Context parent) { // this.parent = parent; // } // // public Store getStore() { // return store; // } // // public ExtensionRegistry getRegistry() { // return registry; // } // // private void setRegistry(ExtensionRegistry registry) { // this.registry = registry; // } // // public Context newChildContext(Method method, Class<?> proxyClass) { // Context childContext = new Context(); // childContext.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(method, null)); // childContext.setRegistry(ExtensionRegistry.create(proxyClass)); // childContext.getRegistry().registerExtensions(method); // childContext.setParent(this); // //extension // getStore().get(PROPERTIES_KEY, Properties.class).ifPresent(properties -> { // Properties child = new Properties(); // child.putAll(properties); // childContext.getStore().put(PROPERTIES_KEY, child); // }); // getStore().get(PARAMETERS_KEY, Properties.class).ifPresent(properties -> { // Properties child = new Properties(); // child.putAll(properties); // childContext.getStore().put(PARAMETERS_KEY, child); // }); // getStore().get(LISTENERS_KEY, List.class).ifPresent(listeners -> { // childContext.getStore().put(LISTENERS_KEY, listeners); // }); // getStore().get(DRIVER_KEY, WebDriver.class).ifPresent(driver -> { // childContext.getStore().put(DRIVER_KEY, driver); // }); // return childContext; // } // // public static Context newWebPageContext(Class<?> webPageClass, WebDriver driver) { // Context context = new Context(); // context.setRegistry(ExtensionRegistry.create(webPageClass)); // context.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(webPageClass)); // context.getStore().put(DRIVER_KEY, driver); // return context; // } // // // } // // Path: src/main/java/io/qameta/htmlelements/exception/WaitUntilException.java // public class WaitUntilException extends WebDriverException { // // public WaitUntilException(String message) { // super(message); // } // // }
import io.qameta.htmlelements.context.Context; import io.qameta.htmlelements.exception.WaitUntilException; import org.hamcrest.Matcher; import org.hamcrest.StringDescription; import org.openqa.selenium.WebDriverException; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Method;
package io.qameta.htmlelements.extension; @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @HandleWith(WaitUntilMethod.Extension.class) public @interface WaitUntilMethod { class Extension implements MethodHandler<Object> { @Override @SuppressWarnings("unchecked") public Object handle(Context context, Object proxy, Method method, Object[] args) throws Throwable { String message = (String) args[0]; Matcher matcher = (Matcher) args[1]; if (!matcher.matches(proxy)) { StringDescription description = new StringDescription(); description.appendText(message).appendText("\nExpected: ").appendDescriptionOf(matcher).appendText("\n but: "); matcher.describeMismatch(proxy, description);
// Path: src/main/java/io/qameta/htmlelements/context/Context.java // public class Context { // // public static final String DESCRIPTION_KEY = "description"; // // public static final String LISTENERS_KEY = "listeners"; // // public static final String PROPERTIES_KEY = "properties"; // // public static final String PARAMETERS_KEY = "parameters"; // // public static final String DRIVER_KEY = "driver"; // // private Context parent; // // private Store store; // // private ExtensionRegistry registry; // // private Context() { // this.store = new DefaultStore(); // } // // public Optional<Context> getParent() { // return Optional.ofNullable(parent); // } // // private void setParent(Context parent) { // this.parent = parent; // } // // public Store getStore() { // return store; // } // // public ExtensionRegistry getRegistry() { // return registry; // } // // private void setRegistry(ExtensionRegistry registry) { // this.registry = registry; // } // // public Context newChildContext(Method method, Class<?> proxyClass) { // Context childContext = new Context(); // childContext.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(method, null)); // childContext.setRegistry(ExtensionRegistry.create(proxyClass)); // childContext.getRegistry().registerExtensions(method); // childContext.setParent(this); // //extension // getStore().get(PROPERTIES_KEY, Properties.class).ifPresent(properties -> { // Properties child = new Properties(); // child.putAll(properties); // childContext.getStore().put(PROPERTIES_KEY, child); // }); // getStore().get(PARAMETERS_KEY, Properties.class).ifPresent(properties -> { // Properties child = new Properties(); // child.putAll(properties); // childContext.getStore().put(PARAMETERS_KEY, child); // }); // getStore().get(LISTENERS_KEY, List.class).ifPresent(listeners -> { // childContext.getStore().put(LISTENERS_KEY, listeners); // }); // getStore().get(DRIVER_KEY, WebDriver.class).ifPresent(driver -> { // childContext.getStore().put(DRIVER_KEY, driver); // }); // return childContext; // } // // public static Context newWebPageContext(Class<?> webPageClass, WebDriver driver) { // Context context = new Context(); // context.setRegistry(ExtensionRegistry.create(webPageClass)); // context.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(webPageClass)); // context.getStore().put(DRIVER_KEY, driver); // return context; // } // // // } // // Path: src/main/java/io/qameta/htmlelements/exception/WaitUntilException.java // public class WaitUntilException extends WebDriverException { // // public WaitUntilException(String message) { // super(message); // } // // } // Path: src/main/java/io/qameta/htmlelements/extension/WaitUntilMethod.java import io.qameta.htmlelements.context.Context; import io.qameta.htmlelements.exception.WaitUntilException; import org.hamcrest.Matcher; import org.hamcrest.StringDescription; import org.openqa.selenium.WebDriverException; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Method; package io.qameta.htmlelements.extension; @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @HandleWith(WaitUntilMethod.Extension.class) public @interface WaitUntilMethod { class Extension implements MethodHandler<Object> { @Override @SuppressWarnings("unchecked") public Object handle(Context context, Object proxy, Method method, Object[] args) throws Throwable { String message = (String) args[0]; Matcher matcher = (Matcher) args[1]; if (!matcher.matches(proxy)) { StringDescription description = new StringDescription(); description.appendText(message).appendText("\nExpected: ").appendDescriptionOf(matcher).appendText("\n but: "); matcher.describeMismatch(proxy, description);
throw new WaitUntilException(description.toString());
eroshenkoam/htmlelements
src/main/java/io/qameta/htmlelements/extension/HoverMethod.java
// Path: src/main/java/io/qameta/htmlelements/context/Context.java // public class Context { // // public static final String DESCRIPTION_KEY = "description"; // // public static final String LISTENERS_KEY = "listeners"; // // public static final String PROPERTIES_KEY = "properties"; // // public static final String PARAMETERS_KEY = "parameters"; // // public static final String DRIVER_KEY = "driver"; // // private Context parent; // // private Store store; // // private ExtensionRegistry registry; // // private Context() { // this.store = new DefaultStore(); // } // // public Optional<Context> getParent() { // return Optional.ofNullable(parent); // } // // private void setParent(Context parent) { // this.parent = parent; // } // // public Store getStore() { // return store; // } // // public ExtensionRegistry getRegistry() { // return registry; // } // // private void setRegistry(ExtensionRegistry registry) { // this.registry = registry; // } // // public Context newChildContext(Method method, Class<?> proxyClass) { // Context childContext = new Context(); // childContext.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(method, null)); // childContext.setRegistry(ExtensionRegistry.create(proxyClass)); // childContext.getRegistry().registerExtensions(method); // childContext.setParent(this); // //extension // getStore().get(PROPERTIES_KEY, Properties.class).ifPresent(properties -> { // Properties child = new Properties(); // child.putAll(properties); // childContext.getStore().put(PROPERTIES_KEY, child); // }); // getStore().get(PARAMETERS_KEY, Properties.class).ifPresent(properties -> { // Properties child = new Properties(); // child.putAll(properties); // childContext.getStore().put(PARAMETERS_KEY, child); // }); // getStore().get(LISTENERS_KEY, List.class).ifPresent(listeners -> { // childContext.getStore().put(LISTENERS_KEY, listeners); // }); // getStore().get(DRIVER_KEY, WebDriver.class).ifPresent(driver -> { // childContext.getStore().put(DRIVER_KEY, driver); // }); // return childContext; // } // // public static Context newWebPageContext(Class<?> webPageClass, WebDriver driver) { // Context context = new Context(); // context.setRegistry(ExtensionRegistry.create(webPageClass)); // context.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(webPageClass)); // context.getStore().put(DRIVER_KEY, driver); // return context; // } // // // } // // Path: src/main/java/io/qameta/htmlelements/exception/WebPageException.java // public class WebPageException extends RuntimeException { // // public WebPageException(String message) { // super(message); // } // }
import io.qameta.htmlelements.context.Context; import io.qameta.htmlelements.exception.WebPageException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.interactions.Actions; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Method; import static io.qameta.htmlelements.context.Store.DRIVER_KEY;
package io.qameta.htmlelements.extension; @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @HandleWith(HoverMethod.Extension.class) public @interface HoverMethod { class Extension implements MethodHandler { @Override
// Path: src/main/java/io/qameta/htmlelements/context/Context.java // public class Context { // // public static final String DESCRIPTION_KEY = "description"; // // public static final String LISTENERS_KEY = "listeners"; // // public static final String PROPERTIES_KEY = "properties"; // // public static final String PARAMETERS_KEY = "parameters"; // // public static final String DRIVER_KEY = "driver"; // // private Context parent; // // private Store store; // // private ExtensionRegistry registry; // // private Context() { // this.store = new DefaultStore(); // } // // public Optional<Context> getParent() { // return Optional.ofNullable(parent); // } // // private void setParent(Context parent) { // this.parent = parent; // } // // public Store getStore() { // return store; // } // // public ExtensionRegistry getRegistry() { // return registry; // } // // private void setRegistry(ExtensionRegistry registry) { // this.registry = registry; // } // // public Context newChildContext(Method method, Class<?> proxyClass) { // Context childContext = new Context(); // childContext.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(method, null)); // childContext.setRegistry(ExtensionRegistry.create(proxyClass)); // childContext.getRegistry().registerExtensions(method); // childContext.setParent(this); // //extension // getStore().get(PROPERTIES_KEY, Properties.class).ifPresent(properties -> { // Properties child = new Properties(); // child.putAll(properties); // childContext.getStore().put(PROPERTIES_KEY, child); // }); // getStore().get(PARAMETERS_KEY, Properties.class).ifPresent(properties -> { // Properties child = new Properties(); // child.putAll(properties); // childContext.getStore().put(PARAMETERS_KEY, child); // }); // getStore().get(LISTENERS_KEY, List.class).ifPresent(listeners -> { // childContext.getStore().put(LISTENERS_KEY, listeners); // }); // getStore().get(DRIVER_KEY, WebDriver.class).ifPresent(driver -> { // childContext.getStore().put(DRIVER_KEY, driver); // }); // return childContext; // } // // public static Context newWebPageContext(Class<?> webPageClass, WebDriver driver) { // Context context = new Context(); // context.setRegistry(ExtensionRegistry.create(webPageClass)); // context.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(webPageClass)); // context.getStore().put(DRIVER_KEY, driver); // return context; // } // // // } // // Path: src/main/java/io/qameta/htmlelements/exception/WebPageException.java // public class WebPageException extends RuntimeException { // // public WebPageException(String message) { // super(message); // } // } // Path: src/main/java/io/qameta/htmlelements/extension/HoverMethod.java import io.qameta.htmlelements.context.Context; import io.qameta.htmlelements.exception.WebPageException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.interactions.Actions; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Method; import static io.qameta.htmlelements.context.Store.DRIVER_KEY; package io.qameta.htmlelements.extension; @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @HandleWith(HoverMethod.Extension.class) public @interface HoverMethod { class Extension implements MethodHandler { @Override
public Object handle(Context context, Object proxy, Method method, Object[] args) throws Throwable {
eroshenkoam/htmlelements
src/main/java/io/qameta/htmlelements/extension/HoverMethod.java
// Path: src/main/java/io/qameta/htmlelements/context/Context.java // public class Context { // // public static final String DESCRIPTION_KEY = "description"; // // public static final String LISTENERS_KEY = "listeners"; // // public static final String PROPERTIES_KEY = "properties"; // // public static final String PARAMETERS_KEY = "parameters"; // // public static final String DRIVER_KEY = "driver"; // // private Context parent; // // private Store store; // // private ExtensionRegistry registry; // // private Context() { // this.store = new DefaultStore(); // } // // public Optional<Context> getParent() { // return Optional.ofNullable(parent); // } // // private void setParent(Context parent) { // this.parent = parent; // } // // public Store getStore() { // return store; // } // // public ExtensionRegistry getRegistry() { // return registry; // } // // private void setRegistry(ExtensionRegistry registry) { // this.registry = registry; // } // // public Context newChildContext(Method method, Class<?> proxyClass) { // Context childContext = new Context(); // childContext.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(method, null)); // childContext.setRegistry(ExtensionRegistry.create(proxyClass)); // childContext.getRegistry().registerExtensions(method); // childContext.setParent(this); // //extension // getStore().get(PROPERTIES_KEY, Properties.class).ifPresent(properties -> { // Properties child = new Properties(); // child.putAll(properties); // childContext.getStore().put(PROPERTIES_KEY, child); // }); // getStore().get(PARAMETERS_KEY, Properties.class).ifPresent(properties -> { // Properties child = new Properties(); // child.putAll(properties); // childContext.getStore().put(PARAMETERS_KEY, child); // }); // getStore().get(LISTENERS_KEY, List.class).ifPresent(listeners -> { // childContext.getStore().put(LISTENERS_KEY, listeners); // }); // getStore().get(DRIVER_KEY, WebDriver.class).ifPresent(driver -> { // childContext.getStore().put(DRIVER_KEY, driver); // }); // return childContext; // } // // public static Context newWebPageContext(Class<?> webPageClass, WebDriver driver) { // Context context = new Context(); // context.setRegistry(ExtensionRegistry.create(webPageClass)); // context.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(webPageClass)); // context.getStore().put(DRIVER_KEY, driver); // return context; // } // // // } // // Path: src/main/java/io/qameta/htmlelements/exception/WebPageException.java // public class WebPageException extends RuntimeException { // // public WebPageException(String message) { // super(message); // } // }
import io.qameta.htmlelements.context.Context; import io.qameta.htmlelements.exception.WebPageException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.interactions.Actions; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Method; import static io.qameta.htmlelements.context.Store.DRIVER_KEY;
package io.qameta.htmlelements.extension; @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @HandleWith(HoverMethod.Extension.class) public @interface HoverMethod { class Extension implements MethodHandler { @Override public Object handle(Context context, Object proxy, Method method, Object[] args) throws Throwable { WebDriver driver = context.getStore().get(DRIVER_KEY, WebDriver.class)
// Path: src/main/java/io/qameta/htmlelements/context/Context.java // public class Context { // // public static final String DESCRIPTION_KEY = "description"; // // public static final String LISTENERS_KEY = "listeners"; // // public static final String PROPERTIES_KEY = "properties"; // // public static final String PARAMETERS_KEY = "parameters"; // // public static final String DRIVER_KEY = "driver"; // // private Context parent; // // private Store store; // // private ExtensionRegistry registry; // // private Context() { // this.store = new DefaultStore(); // } // // public Optional<Context> getParent() { // return Optional.ofNullable(parent); // } // // private void setParent(Context parent) { // this.parent = parent; // } // // public Store getStore() { // return store; // } // // public ExtensionRegistry getRegistry() { // return registry; // } // // private void setRegistry(ExtensionRegistry registry) { // this.registry = registry; // } // // public Context newChildContext(Method method, Class<?> proxyClass) { // Context childContext = new Context(); // childContext.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(method, null)); // childContext.setRegistry(ExtensionRegistry.create(proxyClass)); // childContext.getRegistry().registerExtensions(method); // childContext.setParent(this); // //extension // getStore().get(PROPERTIES_KEY, Properties.class).ifPresent(properties -> { // Properties child = new Properties(); // child.putAll(properties); // childContext.getStore().put(PROPERTIES_KEY, child); // }); // getStore().get(PARAMETERS_KEY, Properties.class).ifPresent(properties -> { // Properties child = new Properties(); // child.putAll(properties); // childContext.getStore().put(PARAMETERS_KEY, child); // }); // getStore().get(LISTENERS_KEY, List.class).ifPresent(listeners -> { // childContext.getStore().put(LISTENERS_KEY, listeners); // }); // getStore().get(DRIVER_KEY, WebDriver.class).ifPresent(driver -> { // childContext.getStore().put(DRIVER_KEY, driver); // }); // return childContext; // } // // public static Context newWebPageContext(Class<?> webPageClass, WebDriver driver) { // Context context = new Context(); // context.setRegistry(ExtensionRegistry.create(webPageClass)); // context.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(webPageClass)); // context.getStore().put(DRIVER_KEY, driver); // return context; // } // // // } // // Path: src/main/java/io/qameta/htmlelements/exception/WebPageException.java // public class WebPageException extends RuntimeException { // // public WebPageException(String message) { // super(message); // } // } // Path: src/main/java/io/qameta/htmlelements/extension/HoverMethod.java import io.qameta.htmlelements.context.Context; import io.qameta.htmlelements.exception.WebPageException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.interactions.Actions; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Method; import static io.qameta.htmlelements.context.Store.DRIVER_KEY; package io.qameta.htmlelements.extension; @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @HandleWith(HoverMethod.Extension.class) public @interface HoverMethod { class Extension implements MethodHandler { @Override public Object handle(Context context, Object proxy, Method method, Object[] args) throws Throwable { WebDriver driver = context.getStore().get(DRIVER_KEY, WebDriver.class)
.orElseThrow(() -> new WebPageException("WebDriver is missing"));
eroshenkoam/htmlelements
src/test/java/io/qameta/htmlelements/WebPageTest.java
// Path: src/test/java/io/qameta/htmlelements/example/page/SearchPage.java // @BaseUrl("http://www.base.url") // public interface SearchPage extends WebPage { // // @Description("Поисковая строка") // @FindBy(TestData.SEARCH_ARROW_XPATH) // SearchArrow searchArrow(); // // }
import io.qameta.htmlelements.example.page.SearchPage; import org.junit.Before; import org.junit.Test; import org.openqa.selenium.By; import org.openqa.selenium.TimeoutException; import org.openqa.selenium.WebDriver; import static java.lang.String.format; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify;
package io.qameta.htmlelements; public class WebPageTest { private WebPageFactory factory; private WebDriver driver; @Before public void initFactory() { this.driver = mock(WebDriver.class); this.factory = new WebPageFactory(); } @Test public void webPageShouldHaveWrappedDriver() { WebPage page = factory.get(driver, WebPage.class); assertThat(page.getWrappedDriver(), equalTo(driver)); } @Test public void webPageShouldProxySearchContextMethodsToDriver () { By searchCriteria = By.xpath("some-value"); WebPage page = factory.get(driver, WebPage.class); page.findElement(searchCriteria); verify(driver).findElement(searchCriteria); } @Test() public void webPageShouldGoToBaseUrl() { String pageUrl = "http://www.base.url"; try{
// Path: src/test/java/io/qameta/htmlelements/example/page/SearchPage.java // @BaseUrl("http://www.base.url") // public interface SearchPage extends WebPage { // // @Description("Поисковая строка") // @FindBy(TestData.SEARCH_ARROW_XPATH) // SearchArrow searchArrow(); // // } // Path: src/test/java/io/qameta/htmlelements/WebPageTest.java import io.qameta.htmlelements.example.page.SearchPage; import org.junit.Before; import org.junit.Test; import org.openqa.selenium.By; import org.openqa.selenium.TimeoutException; import org.openqa.selenium.WebDriver; import static java.lang.String.format; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; package io.qameta.htmlelements; public class WebPageTest { private WebPageFactory factory; private WebDriver driver; @Before public void initFactory() { this.driver = mock(WebDriver.class); this.factory = new WebPageFactory(); } @Test public void webPageShouldHaveWrappedDriver() { WebPage page = factory.get(driver, WebPage.class); assertThat(page.getWrappedDriver(), equalTo(driver)); } @Test public void webPageShouldProxySearchContextMethodsToDriver () { By searchCriteria = By.xpath("some-value"); WebPage page = factory.get(driver, WebPage.class); page.findElement(searchCriteria); verify(driver).findElement(searchCriteria); } @Test() public void webPageShouldGoToBaseUrl() { String pageUrl = "http://www.base.url"; try{
SearchPage page = factory.get(driver, SearchPage.class);
eroshenkoam/htmlelements
src/test/java/io/qameta/htmlelements/example/scroll/WikiMainPage.java
// Path: src/main/java/io/qameta/htmlelements/WebPage.java // public interface WebPage extends WrapsDriver, SearchContext { // // @DriverProvider // WebDriver getWrappedDriver(); // // @GoMethod // void go(); // // @IsAtMethod // void isAt(Matcher<String> url); // // default void open(String url) { // getWrappedDriver().get(url); // } // // @ToStringMethod // String toString(); // // } // // Path: src/main/java/io/qameta/htmlelements/element/ScrollableElement.java // public interface ScrollableElement extends ExtendedWebElement { // // @ScrollMethod // void scrollToElement(); // }
import io.qameta.htmlelements.WebPage; import io.qameta.htmlelements.annotation.FindBy; import io.qameta.htmlelements.element.ScrollableElement; import io.qameta.htmlelements.extension.page.BaseUrl;
package io.qameta.htmlelements.example.scroll; /** * @author ehborisov */ @BaseUrl("https://en.wikipedia.org/wiki/Main_Page") public interface WikiMainPage extends WebPage { @FindBy("//a[.='Complete list of Wikipedias']")
// Path: src/main/java/io/qameta/htmlelements/WebPage.java // public interface WebPage extends WrapsDriver, SearchContext { // // @DriverProvider // WebDriver getWrappedDriver(); // // @GoMethod // void go(); // // @IsAtMethod // void isAt(Matcher<String> url); // // default void open(String url) { // getWrappedDriver().get(url); // } // // @ToStringMethod // String toString(); // // } // // Path: src/main/java/io/qameta/htmlelements/element/ScrollableElement.java // public interface ScrollableElement extends ExtendedWebElement { // // @ScrollMethod // void scrollToElement(); // } // Path: src/test/java/io/qameta/htmlelements/example/scroll/WikiMainPage.java import io.qameta.htmlelements.WebPage; import io.qameta.htmlelements.annotation.FindBy; import io.qameta.htmlelements.element.ScrollableElement; import io.qameta.htmlelements.extension.page.BaseUrl; package io.qameta.htmlelements.example.scroll; /** * @author ehborisov */ @BaseUrl("https://en.wikipedia.org/wiki/Main_Page") public interface WikiMainPage extends WebPage { @FindBy("//a[.='Complete list of Wikipedias']")
ScrollableElement wikiList();
eroshenkoam/htmlelements
src/test/java/io/qameta/htmlelements/example/element/SuggestItem.java
// Path: src/main/java/io/qameta/htmlelements/element/ExtendedWebElement.java // public interface ExtendedWebElement<FluentType> extends WebElement, Locatable { // // @HoverMethod // FluentType hover(); // // @WaitUntilMethod // FluentType waitUntil(String message, Matcher matcher); // // @WaitUntilMethod // FluentType waitUntil(String message, Matcher matcher, @Timeout long timeout); // // default FluentType waitUntil(Matcher matcher) { // return waitUntil("", matcher); // } // // default FluentType waitUntil(Predicate<FluentType> predicate) { // return waitUntil("", predicate); // } // // default FluentType waitUntil(String description, Predicate<FluentType> predicate) { // return waitUntil(description, new PredicateMatcher<>(predicate)); // } // // @ShouldMethod // FluentType should(String message, Matcher matcher, @Timeout long timeout); // // @ShouldMethod // FluentType should(String message, Matcher matcher); // // default FluentType should(Matcher matcher) { // return should("", matcher); // } // // @ToStringMethod // String toString(); // // } // // Path: src/main/java/io/qameta/htmlelements/element/HtmlElement.java // public interface HtmlElement extends ExtendedWebElement<HtmlElement> { // // // } // // Path: src/test/java/io/qameta/htmlelements/example/TestData.java // public class TestData { // // public static final String SEARCH_ARROW_XPATH = "//form[contains(@class, 'search2 suggest2-form')]"; // // public static final String SUGGEST_XPATH = "//div[@class='suggest']"; // // public static final String SUGGEST_ITEM_XPATH = "//a"; // // public static final String SEARCH_FORM_XPATH = "//div[@class='form']"; // // public static final String SEARCH_FORM_TEMPLATE = "//div[@class='{{ className }}']"; // // public static final String REQUEST_INPUT_XPATH = "//div[@class='input']"; // // // public static WebDriver mockDriver() { // // WebElement textInput = mockWebElement() // .withText("text input") // .withDisplayed(true) // .build(); // // List<WebElement> suggest = Arrays.asList( // mockWebElement() // .withChildElement(SUGGEST_ITEM_XPATH, mockWebElement().withText("first suggest item").build()) // .withText("first suggest") // .withDisplayed(false, true) // .build(), // mockWebElement() // .withChildElement(SUGGEST_ITEM_XPATH, mockWebElement().withText("second suggest item").build()) // .withText("second suggest") // .withDisplayed(false, false, false, true) // .build() // ); // // WebElement searchForm = mockWebElement() // .withChildElement(REQUEST_INPUT_XPATH, textInput) // .withText("searchForm") // .build(); // // WebElement searchArrow = mockWebElement() // .withChildElements(SUGGEST_XPATH, suggest) // .withChildElement(SEARCH_FORM_XPATH, searchForm) // .withText("search-arro", "search", "search-arrow") // .withDisplayed(true) // .build(); // // // WebDriver driver = mock(WebDriver.class); // when(driver.findElement(By.xpath(SEARCH_ARROW_XPATH))).thenReturn(searchArrow); // // return driver; // } // // private static WebElement createWebElement(String text, Boolean displayed, Boolean... displayedNext) { // WebElement webElement = mock(WebElement.class); // when(webElement.getText()).thenReturn(text); // when(webElement.toString()).thenReturn(text); // when(webElement.isDisplayed()).thenReturn(displayed, displayedNext); // return webElement; // } // // public static class WebElementBuilder { // // public static WebElementBuilder mockWebElement() { // return new WebElementBuilder(); // } // // private final WebElement element; // // public WebElementBuilder() { // this.element = mock(WebElement.class); // } // // public WebElementBuilder withText(String text, String... other) { // when(getElement().getText()).thenReturn(text, other); // return this; // } // // public WebElementBuilder withDisplayed(boolean displayed, Boolean... other) { // when(getElement().isDisplayed()).thenReturn(displayed, other); // return this; // } // // public WebElementBuilder withChildElement(String xpath, WebElement element) { // when(getElement().findElement(By.xpath(xpath))).thenReturn(element); // return this; // } // // public WebElementBuilder withChildElements(String xpath, List<WebElement> elements) { // when(getElement().findElements(By.xpath(xpath))).thenReturn(elements); // return this; // } // // private WebElement getElement() { // return element; // } // // public WebElement build() { // return getElement(); // } // // } // }
import io.qameta.htmlelements.annotation.FindBy; import io.qameta.htmlelements.element.ExtendedWebElement; import io.qameta.htmlelements.element.HtmlElement; import io.qameta.htmlelements.example.TestData;
package io.qameta.htmlelements.example.element; public interface SuggestItem extends ExtendedWebElement<SuggestItem>{ @FindBy(TestData.SUGGEST_ITEM_XPATH)
// Path: src/main/java/io/qameta/htmlelements/element/ExtendedWebElement.java // public interface ExtendedWebElement<FluentType> extends WebElement, Locatable { // // @HoverMethod // FluentType hover(); // // @WaitUntilMethod // FluentType waitUntil(String message, Matcher matcher); // // @WaitUntilMethod // FluentType waitUntil(String message, Matcher matcher, @Timeout long timeout); // // default FluentType waitUntil(Matcher matcher) { // return waitUntil("", matcher); // } // // default FluentType waitUntil(Predicate<FluentType> predicate) { // return waitUntil("", predicate); // } // // default FluentType waitUntil(String description, Predicate<FluentType> predicate) { // return waitUntil(description, new PredicateMatcher<>(predicate)); // } // // @ShouldMethod // FluentType should(String message, Matcher matcher, @Timeout long timeout); // // @ShouldMethod // FluentType should(String message, Matcher matcher); // // default FluentType should(Matcher matcher) { // return should("", matcher); // } // // @ToStringMethod // String toString(); // // } // // Path: src/main/java/io/qameta/htmlelements/element/HtmlElement.java // public interface HtmlElement extends ExtendedWebElement<HtmlElement> { // // // } // // Path: src/test/java/io/qameta/htmlelements/example/TestData.java // public class TestData { // // public static final String SEARCH_ARROW_XPATH = "//form[contains(@class, 'search2 suggest2-form')]"; // // public static final String SUGGEST_XPATH = "//div[@class='suggest']"; // // public static final String SUGGEST_ITEM_XPATH = "//a"; // // public static final String SEARCH_FORM_XPATH = "//div[@class='form']"; // // public static final String SEARCH_FORM_TEMPLATE = "//div[@class='{{ className }}']"; // // public static final String REQUEST_INPUT_XPATH = "//div[@class='input']"; // // // public static WebDriver mockDriver() { // // WebElement textInput = mockWebElement() // .withText("text input") // .withDisplayed(true) // .build(); // // List<WebElement> suggest = Arrays.asList( // mockWebElement() // .withChildElement(SUGGEST_ITEM_XPATH, mockWebElement().withText("first suggest item").build()) // .withText("first suggest") // .withDisplayed(false, true) // .build(), // mockWebElement() // .withChildElement(SUGGEST_ITEM_XPATH, mockWebElement().withText("second suggest item").build()) // .withText("second suggest") // .withDisplayed(false, false, false, true) // .build() // ); // // WebElement searchForm = mockWebElement() // .withChildElement(REQUEST_INPUT_XPATH, textInput) // .withText("searchForm") // .build(); // // WebElement searchArrow = mockWebElement() // .withChildElements(SUGGEST_XPATH, suggest) // .withChildElement(SEARCH_FORM_XPATH, searchForm) // .withText("search-arro", "search", "search-arrow") // .withDisplayed(true) // .build(); // // // WebDriver driver = mock(WebDriver.class); // when(driver.findElement(By.xpath(SEARCH_ARROW_XPATH))).thenReturn(searchArrow); // // return driver; // } // // private static WebElement createWebElement(String text, Boolean displayed, Boolean... displayedNext) { // WebElement webElement = mock(WebElement.class); // when(webElement.getText()).thenReturn(text); // when(webElement.toString()).thenReturn(text); // when(webElement.isDisplayed()).thenReturn(displayed, displayedNext); // return webElement; // } // // public static class WebElementBuilder { // // public static WebElementBuilder mockWebElement() { // return new WebElementBuilder(); // } // // private final WebElement element; // // public WebElementBuilder() { // this.element = mock(WebElement.class); // } // // public WebElementBuilder withText(String text, String... other) { // when(getElement().getText()).thenReturn(text, other); // return this; // } // // public WebElementBuilder withDisplayed(boolean displayed, Boolean... other) { // when(getElement().isDisplayed()).thenReturn(displayed, other); // return this; // } // // public WebElementBuilder withChildElement(String xpath, WebElement element) { // when(getElement().findElement(By.xpath(xpath))).thenReturn(element); // return this; // } // // public WebElementBuilder withChildElements(String xpath, List<WebElement> elements) { // when(getElement().findElements(By.xpath(xpath))).thenReturn(elements); // return this; // } // // private WebElement getElement() { // return element; // } // // public WebElement build() { // return getElement(); // } // // } // } // Path: src/test/java/io/qameta/htmlelements/example/element/SuggestItem.java import io.qameta.htmlelements.annotation.FindBy; import io.qameta.htmlelements.element.ExtendedWebElement; import io.qameta.htmlelements.element.HtmlElement; import io.qameta.htmlelements.example.TestData; package io.qameta.htmlelements.example.element; public interface SuggestItem extends ExtendedWebElement<SuggestItem>{ @FindBy(TestData.SUGGEST_ITEM_XPATH)
HtmlElement title();
eroshenkoam/htmlelements
src/test/java/io/qameta/htmlelements/example/TestData.java
// Path: src/test/java/io/qameta/htmlelements/example/TestData.java // public static WebElementBuilder mockWebElement() { // return new WebElementBuilder(); // }
import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import java.util.Arrays; import java.util.List; import java.util.NoSuchElementException; import static io.qameta.htmlelements.example.TestData.WebElementBuilder.mockWebElement; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when;
package io.qameta.htmlelements.example; /** * @author Artem Eroshenko <[email protected]> */ public class TestData { public static final String SEARCH_ARROW_XPATH = "//form[contains(@class, 'search2 suggest2-form')]"; public static final String SUGGEST_XPATH = "//div[@class='suggest']"; public static final String SUGGEST_ITEM_XPATH = "//a"; public static final String SEARCH_FORM_XPATH = "//div[@class='form']"; public static final String SEARCH_FORM_TEMPLATE = "//div[@class='{{ className }}']"; public static final String REQUEST_INPUT_XPATH = "//div[@class='input']"; public static WebDriver mockDriver() {
// Path: src/test/java/io/qameta/htmlelements/example/TestData.java // public static WebElementBuilder mockWebElement() { // return new WebElementBuilder(); // } // Path: src/test/java/io/qameta/htmlelements/example/TestData.java import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import java.util.Arrays; import java.util.List; import java.util.NoSuchElementException; import static io.qameta.htmlelements.example.TestData.WebElementBuilder.mockWebElement; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; package io.qameta.htmlelements.example; /** * @author Artem Eroshenko <[email protected]> */ public class TestData { public static final String SEARCH_ARROW_XPATH = "//form[contains(@class, 'search2 suggest2-form')]"; public static final String SUGGEST_XPATH = "//div[@class='suggest']"; public static final String SUGGEST_ITEM_XPATH = "//a"; public static final String SEARCH_FORM_XPATH = "//div[@class='form']"; public static final String SEARCH_FORM_TEMPLATE = "//div[@class='{{ className }}']"; public static final String REQUEST_INPUT_XPATH = "//div[@class='input']"; public static WebDriver mockDriver() {
WebElement textInput = mockWebElement()
eroshenkoam/htmlelements
src/test/java/io/qameta/htmlelements/GlobalParametersTest.java
// Path: src/main/java/io/qameta/htmlelements/element/HtmlElement.java // public interface HtmlElement extends ExtendedWebElement<HtmlElement> { // // // } // // Path: src/test/java/io/qameta/htmlelements/example/TestData.java // public class TestData { // // public static final String SEARCH_ARROW_XPATH = "//form[contains(@class, 'search2 suggest2-form')]"; // // public static final String SUGGEST_XPATH = "//div[@class='suggest']"; // // public static final String SUGGEST_ITEM_XPATH = "//a"; // // public static final String SEARCH_FORM_XPATH = "//div[@class='form']"; // // public static final String SEARCH_FORM_TEMPLATE = "//div[@class='{{ className }}']"; // // public static final String REQUEST_INPUT_XPATH = "//div[@class='input']"; // // // public static WebDriver mockDriver() { // // WebElement textInput = mockWebElement() // .withText("text input") // .withDisplayed(true) // .build(); // // List<WebElement> suggest = Arrays.asList( // mockWebElement() // .withChildElement(SUGGEST_ITEM_XPATH, mockWebElement().withText("first suggest item").build()) // .withText("first suggest") // .withDisplayed(false, true) // .build(), // mockWebElement() // .withChildElement(SUGGEST_ITEM_XPATH, mockWebElement().withText("second suggest item").build()) // .withText("second suggest") // .withDisplayed(false, false, false, true) // .build() // ); // // WebElement searchForm = mockWebElement() // .withChildElement(REQUEST_INPUT_XPATH, textInput) // .withText("searchForm") // .build(); // // WebElement searchArrow = mockWebElement() // .withChildElements(SUGGEST_XPATH, suggest) // .withChildElement(SEARCH_FORM_XPATH, searchForm) // .withText("search-arro", "search", "search-arrow") // .withDisplayed(true) // .build(); // // // WebDriver driver = mock(WebDriver.class); // when(driver.findElement(By.xpath(SEARCH_ARROW_XPATH))).thenReturn(searchArrow); // // return driver; // } // // private static WebElement createWebElement(String text, Boolean displayed, Boolean... displayedNext) { // WebElement webElement = mock(WebElement.class); // when(webElement.getText()).thenReturn(text); // when(webElement.toString()).thenReturn(text); // when(webElement.isDisplayed()).thenReturn(displayed, displayedNext); // return webElement; // } // // public static class WebElementBuilder { // // public static WebElementBuilder mockWebElement() { // return new WebElementBuilder(); // } // // private final WebElement element; // // public WebElementBuilder() { // this.element = mock(WebElement.class); // } // // public WebElementBuilder withText(String text, String... other) { // when(getElement().getText()).thenReturn(text, other); // return this; // } // // public WebElementBuilder withDisplayed(boolean displayed, Boolean... other) { // when(getElement().isDisplayed()).thenReturn(displayed, other); // return this; // } // // public WebElementBuilder withChildElement(String xpath, WebElement element) { // when(getElement().findElement(By.xpath(xpath))).thenReturn(element); // return this; // } // // public WebElementBuilder withChildElements(String xpath, List<WebElement> elements) { // when(getElement().findElements(By.xpath(xpath))).thenReturn(elements); // return this; // } // // private WebElement getElement() { // return element; // } // // public WebElement build() { // return getElement(); // } // // } // } // // Path: src/main/java/io/qameta/htmlelements/matcher/DisplayedMatcher.java // public class DisplayedMatcher extends TypeSafeMatcher<WebElement> { // // private DisplayedMatcher() { // } // // @Override // protected boolean matchesSafely(WebElement element) { // try { // return element.isDisplayed(); // } catch (WebDriverException e) { // return false; // } // } // // @Override // public void describeTo(Description description) { // description.appendText("element is displayed"); // } // // @Override // public void describeMismatchSafely(WebElement element, Description mismatchDescription) { // mismatchDescription.appendText("element ").appendValue(element).appendText(" is not displayed"); // } // // /** // * Creates matcher that checks if element is currently displayed on page. // */ // @Factory // public static Matcher<WebElement> displayed() { // return new DisplayedMatcher(); // } // }
import io.qameta.htmlelements.annotation.FindBy; import io.qameta.htmlelements.element.HtmlElement; import io.qameta.htmlelements.example.TestData; import io.qameta.htmlelements.matcher.DisplayedMatcher; import org.junit.Test; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.Mockito.when;
package io.qameta.htmlelements; /** * eroshenkoam * 05.07.17 */ public class GlobalParametersTest { @Test public void globalParametersTest() {
// Path: src/main/java/io/qameta/htmlelements/element/HtmlElement.java // public interface HtmlElement extends ExtendedWebElement<HtmlElement> { // // // } // // Path: src/test/java/io/qameta/htmlelements/example/TestData.java // public class TestData { // // public static final String SEARCH_ARROW_XPATH = "//form[contains(@class, 'search2 suggest2-form')]"; // // public static final String SUGGEST_XPATH = "//div[@class='suggest']"; // // public static final String SUGGEST_ITEM_XPATH = "//a"; // // public static final String SEARCH_FORM_XPATH = "//div[@class='form']"; // // public static final String SEARCH_FORM_TEMPLATE = "//div[@class='{{ className }}']"; // // public static final String REQUEST_INPUT_XPATH = "//div[@class='input']"; // // // public static WebDriver mockDriver() { // // WebElement textInput = mockWebElement() // .withText("text input") // .withDisplayed(true) // .build(); // // List<WebElement> suggest = Arrays.asList( // mockWebElement() // .withChildElement(SUGGEST_ITEM_XPATH, mockWebElement().withText("first suggest item").build()) // .withText("first suggest") // .withDisplayed(false, true) // .build(), // mockWebElement() // .withChildElement(SUGGEST_ITEM_XPATH, mockWebElement().withText("second suggest item").build()) // .withText("second suggest") // .withDisplayed(false, false, false, true) // .build() // ); // // WebElement searchForm = mockWebElement() // .withChildElement(REQUEST_INPUT_XPATH, textInput) // .withText("searchForm") // .build(); // // WebElement searchArrow = mockWebElement() // .withChildElements(SUGGEST_XPATH, suggest) // .withChildElement(SEARCH_FORM_XPATH, searchForm) // .withText("search-arro", "search", "search-arrow") // .withDisplayed(true) // .build(); // // // WebDriver driver = mock(WebDriver.class); // when(driver.findElement(By.xpath(SEARCH_ARROW_XPATH))).thenReturn(searchArrow); // // return driver; // } // // private static WebElement createWebElement(String text, Boolean displayed, Boolean... displayedNext) { // WebElement webElement = mock(WebElement.class); // when(webElement.getText()).thenReturn(text); // when(webElement.toString()).thenReturn(text); // when(webElement.isDisplayed()).thenReturn(displayed, displayedNext); // return webElement; // } // // public static class WebElementBuilder { // // public static WebElementBuilder mockWebElement() { // return new WebElementBuilder(); // } // // private final WebElement element; // // public WebElementBuilder() { // this.element = mock(WebElement.class); // } // // public WebElementBuilder withText(String text, String... other) { // when(getElement().getText()).thenReturn(text, other); // return this; // } // // public WebElementBuilder withDisplayed(boolean displayed, Boolean... other) { // when(getElement().isDisplayed()).thenReturn(displayed, other); // return this; // } // // public WebElementBuilder withChildElement(String xpath, WebElement element) { // when(getElement().findElement(By.xpath(xpath))).thenReturn(element); // return this; // } // // public WebElementBuilder withChildElements(String xpath, List<WebElement> elements) { // when(getElement().findElements(By.xpath(xpath))).thenReturn(elements); // return this; // } // // private WebElement getElement() { // return element; // } // // public WebElement build() { // return getElement(); // } // // } // } // // Path: src/main/java/io/qameta/htmlelements/matcher/DisplayedMatcher.java // public class DisplayedMatcher extends TypeSafeMatcher<WebElement> { // // private DisplayedMatcher() { // } // // @Override // protected boolean matchesSafely(WebElement element) { // try { // return element.isDisplayed(); // } catch (WebDriverException e) { // return false; // } // } // // @Override // public void describeTo(Description description) { // description.appendText("element is displayed"); // } // // @Override // public void describeMismatchSafely(WebElement element, Description mismatchDescription) { // mismatchDescription.appendText("element ").appendValue(element).appendText(" is not displayed"); // } // // /** // * Creates matcher that checks if element is currently displayed on page. // */ // @Factory // public static Matcher<WebElement> displayed() { // return new DisplayedMatcher(); // } // } // Path: src/test/java/io/qameta/htmlelements/GlobalParametersTest.java import io.qameta.htmlelements.annotation.FindBy; import io.qameta.htmlelements.element.HtmlElement; import io.qameta.htmlelements.example.TestData; import io.qameta.htmlelements.matcher.DisplayedMatcher; import org.junit.Test; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.Mockito.when; package io.qameta.htmlelements; /** * eroshenkoam * 05.07.17 */ public class GlobalParametersTest { @Test public void globalParametersTest() {
WebDriver driver = TestData.mockDriver();
eroshenkoam/htmlelements
src/test/java/io/qameta/htmlelements/GlobalParametersTest.java
// Path: src/main/java/io/qameta/htmlelements/element/HtmlElement.java // public interface HtmlElement extends ExtendedWebElement<HtmlElement> { // // // } // // Path: src/test/java/io/qameta/htmlelements/example/TestData.java // public class TestData { // // public static final String SEARCH_ARROW_XPATH = "//form[contains(@class, 'search2 suggest2-form')]"; // // public static final String SUGGEST_XPATH = "//div[@class='suggest']"; // // public static final String SUGGEST_ITEM_XPATH = "//a"; // // public static final String SEARCH_FORM_XPATH = "//div[@class='form']"; // // public static final String SEARCH_FORM_TEMPLATE = "//div[@class='{{ className }}']"; // // public static final String REQUEST_INPUT_XPATH = "//div[@class='input']"; // // // public static WebDriver mockDriver() { // // WebElement textInput = mockWebElement() // .withText("text input") // .withDisplayed(true) // .build(); // // List<WebElement> suggest = Arrays.asList( // mockWebElement() // .withChildElement(SUGGEST_ITEM_XPATH, mockWebElement().withText("first suggest item").build()) // .withText("first suggest") // .withDisplayed(false, true) // .build(), // mockWebElement() // .withChildElement(SUGGEST_ITEM_XPATH, mockWebElement().withText("second suggest item").build()) // .withText("second suggest") // .withDisplayed(false, false, false, true) // .build() // ); // // WebElement searchForm = mockWebElement() // .withChildElement(REQUEST_INPUT_XPATH, textInput) // .withText("searchForm") // .build(); // // WebElement searchArrow = mockWebElement() // .withChildElements(SUGGEST_XPATH, suggest) // .withChildElement(SEARCH_FORM_XPATH, searchForm) // .withText("search-arro", "search", "search-arrow") // .withDisplayed(true) // .build(); // // // WebDriver driver = mock(WebDriver.class); // when(driver.findElement(By.xpath(SEARCH_ARROW_XPATH))).thenReturn(searchArrow); // // return driver; // } // // private static WebElement createWebElement(String text, Boolean displayed, Boolean... displayedNext) { // WebElement webElement = mock(WebElement.class); // when(webElement.getText()).thenReturn(text); // when(webElement.toString()).thenReturn(text); // when(webElement.isDisplayed()).thenReturn(displayed, displayedNext); // return webElement; // } // // public static class WebElementBuilder { // // public static WebElementBuilder mockWebElement() { // return new WebElementBuilder(); // } // // private final WebElement element; // // public WebElementBuilder() { // this.element = mock(WebElement.class); // } // // public WebElementBuilder withText(String text, String... other) { // when(getElement().getText()).thenReturn(text, other); // return this; // } // // public WebElementBuilder withDisplayed(boolean displayed, Boolean... other) { // when(getElement().isDisplayed()).thenReturn(displayed, other); // return this; // } // // public WebElementBuilder withChildElement(String xpath, WebElement element) { // when(getElement().findElement(By.xpath(xpath))).thenReturn(element); // return this; // } // // public WebElementBuilder withChildElements(String xpath, List<WebElement> elements) { // when(getElement().findElements(By.xpath(xpath))).thenReturn(elements); // return this; // } // // private WebElement getElement() { // return element; // } // // public WebElement build() { // return getElement(); // } // // } // } // // Path: src/main/java/io/qameta/htmlelements/matcher/DisplayedMatcher.java // public class DisplayedMatcher extends TypeSafeMatcher<WebElement> { // // private DisplayedMatcher() { // } // // @Override // protected boolean matchesSafely(WebElement element) { // try { // return element.isDisplayed(); // } catch (WebDriverException e) { // return false; // } // } // // @Override // public void describeTo(Description description) { // description.appendText("element is displayed"); // } // // @Override // public void describeMismatchSafely(WebElement element, Description mismatchDescription) { // mismatchDescription.appendText("element ").appendValue(element).appendText(" is not displayed"); // } // // /** // * Creates matcher that checks if element is currently displayed on page. // */ // @Factory // public static Matcher<WebElement> displayed() { // return new DisplayedMatcher(); // } // }
import io.qameta.htmlelements.annotation.FindBy; import io.qameta.htmlelements.element.HtmlElement; import io.qameta.htmlelements.example.TestData; import io.qameta.htmlelements.matcher.DisplayedMatcher; import org.junit.Test; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.Mockito.when;
package io.qameta.htmlelements; /** * eroshenkoam * 05.07.17 */ public class GlobalParametersTest { @Test public void globalParametersTest() { WebDriver driver = TestData.mockDriver(); WebElement element = TestData.WebElementBuilder.mockWebElement().withDisplayed(true).build(); when(driver.findElement(By.xpath("//div[@class='value']"))).thenReturn(element); when(driver.findElement(By.xpath("//div[@class='simpleElement']"))).thenReturn(element); when(element.findElement(By.xpath(".//div[@class='childElement']"))).thenReturn(element); WebPageFactory factory = new WebPageFactory() .parameter("key", "value") .parameter("simple", "simpleElement") .parameter("child", "childElement"); SimplePage page = factory.get(driver, SimplePage.class);
// Path: src/main/java/io/qameta/htmlelements/element/HtmlElement.java // public interface HtmlElement extends ExtendedWebElement<HtmlElement> { // // // } // // Path: src/test/java/io/qameta/htmlelements/example/TestData.java // public class TestData { // // public static final String SEARCH_ARROW_XPATH = "//form[contains(@class, 'search2 suggest2-form')]"; // // public static final String SUGGEST_XPATH = "//div[@class='suggest']"; // // public static final String SUGGEST_ITEM_XPATH = "//a"; // // public static final String SEARCH_FORM_XPATH = "//div[@class='form']"; // // public static final String SEARCH_FORM_TEMPLATE = "//div[@class='{{ className }}']"; // // public static final String REQUEST_INPUT_XPATH = "//div[@class='input']"; // // // public static WebDriver mockDriver() { // // WebElement textInput = mockWebElement() // .withText("text input") // .withDisplayed(true) // .build(); // // List<WebElement> suggest = Arrays.asList( // mockWebElement() // .withChildElement(SUGGEST_ITEM_XPATH, mockWebElement().withText("first suggest item").build()) // .withText("first suggest") // .withDisplayed(false, true) // .build(), // mockWebElement() // .withChildElement(SUGGEST_ITEM_XPATH, mockWebElement().withText("second suggest item").build()) // .withText("second suggest") // .withDisplayed(false, false, false, true) // .build() // ); // // WebElement searchForm = mockWebElement() // .withChildElement(REQUEST_INPUT_XPATH, textInput) // .withText("searchForm") // .build(); // // WebElement searchArrow = mockWebElement() // .withChildElements(SUGGEST_XPATH, suggest) // .withChildElement(SEARCH_FORM_XPATH, searchForm) // .withText("search-arro", "search", "search-arrow") // .withDisplayed(true) // .build(); // // // WebDriver driver = mock(WebDriver.class); // when(driver.findElement(By.xpath(SEARCH_ARROW_XPATH))).thenReturn(searchArrow); // // return driver; // } // // private static WebElement createWebElement(String text, Boolean displayed, Boolean... displayedNext) { // WebElement webElement = mock(WebElement.class); // when(webElement.getText()).thenReturn(text); // when(webElement.toString()).thenReturn(text); // when(webElement.isDisplayed()).thenReturn(displayed, displayedNext); // return webElement; // } // // public static class WebElementBuilder { // // public static WebElementBuilder mockWebElement() { // return new WebElementBuilder(); // } // // private final WebElement element; // // public WebElementBuilder() { // this.element = mock(WebElement.class); // } // // public WebElementBuilder withText(String text, String... other) { // when(getElement().getText()).thenReturn(text, other); // return this; // } // // public WebElementBuilder withDisplayed(boolean displayed, Boolean... other) { // when(getElement().isDisplayed()).thenReturn(displayed, other); // return this; // } // // public WebElementBuilder withChildElement(String xpath, WebElement element) { // when(getElement().findElement(By.xpath(xpath))).thenReturn(element); // return this; // } // // public WebElementBuilder withChildElements(String xpath, List<WebElement> elements) { // when(getElement().findElements(By.xpath(xpath))).thenReturn(elements); // return this; // } // // private WebElement getElement() { // return element; // } // // public WebElement build() { // return getElement(); // } // // } // } // // Path: src/main/java/io/qameta/htmlelements/matcher/DisplayedMatcher.java // public class DisplayedMatcher extends TypeSafeMatcher<WebElement> { // // private DisplayedMatcher() { // } // // @Override // protected boolean matchesSafely(WebElement element) { // try { // return element.isDisplayed(); // } catch (WebDriverException e) { // return false; // } // } // // @Override // public void describeTo(Description description) { // description.appendText("element is displayed"); // } // // @Override // public void describeMismatchSafely(WebElement element, Description mismatchDescription) { // mismatchDescription.appendText("element ").appendValue(element).appendText(" is not displayed"); // } // // /** // * Creates matcher that checks if element is currently displayed on page. // */ // @Factory // public static Matcher<WebElement> displayed() { // return new DisplayedMatcher(); // } // } // Path: src/test/java/io/qameta/htmlelements/GlobalParametersTest.java import io.qameta.htmlelements.annotation.FindBy; import io.qameta.htmlelements.element.HtmlElement; import io.qameta.htmlelements.example.TestData; import io.qameta.htmlelements.matcher.DisplayedMatcher; import org.junit.Test; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.Mockito.when; package io.qameta.htmlelements; /** * eroshenkoam * 05.07.17 */ public class GlobalParametersTest { @Test public void globalParametersTest() { WebDriver driver = TestData.mockDriver(); WebElement element = TestData.WebElementBuilder.mockWebElement().withDisplayed(true).build(); when(driver.findElement(By.xpath("//div[@class='value']"))).thenReturn(element); when(driver.findElement(By.xpath("//div[@class='simpleElement']"))).thenReturn(element); when(element.findElement(By.xpath(".//div[@class='childElement']"))).thenReturn(element); WebPageFactory factory = new WebPageFactory() .parameter("key", "value") .parameter("simple", "simpleElement") .parameter("child", "childElement"); SimplePage page = factory.get(driver, SimplePage.class);
page.input().should(DisplayedMatcher.displayed());
eroshenkoam/htmlelements
src/main/java/io/qameta/htmlelements/extension/ShouldMethod.java
// Path: src/main/java/io/qameta/htmlelements/context/Context.java // public class Context { // // public static final String DESCRIPTION_KEY = "description"; // // public static final String LISTENERS_KEY = "listeners"; // // public static final String PROPERTIES_KEY = "properties"; // // public static final String PARAMETERS_KEY = "parameters"; // // public static final String DRIVER_KEY = "driver"; // // private Context parent; // // private Store store; // // private ExtensionRegistry registry; // // private Context() { // this.store = new DefaultStore(); // } // // public Optional<Context> getParent() { // return Optional.ofNullable(parent); // } // // private void setParent(Context parent) { // this.parent = parent; // } // // public Store getStore() { // return store; // } // // public ExtensionRegistry getRegistry() { // return registry; // } // // private void setRegistry(ExtensionRegistry registry) { // this.registry = registry; // } // // public Context newChildContext(Method method, Class<?> proxyClass) { // Context childContext = new Context(); // childContext.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(method, null)); // childContext.setRegistry(ExtensionRegistry.create(proxyClass)); // childContext.getRegistry().registerExtensions(method); // childContext.setParent(this); // //extension // getStore().get(PROPERTIES_KEY, Properties.class).ifPresent(properties -> { // Properties child = new Properties(); // child.putAll(properties); // childContext.getStore().put(PROPERTIES_KEY, child); // }); // getStore().get(PARAMETERS_KEY, Properties.class).ifPresent(properties -> { // Properties child = new Properties(); // child.putAll(properties); // childContext.getStore().put(PARAMETERS_KEY, child); // }); // getStore().get(LISTENERS_KEY, List.class).ifPresent(listeners -> { // childContext.getStore().put(LISTENERS_KEY, listeners); // }); // getStore().get(DRIVER_KEY, WebDriver.class).ifPresent(driver -> { // childContext.getStore().put(DRIVER_KEY, driver); // }); // return childContext; // } // // public static Context newWebPageContext(Class<?> webPageClass, WebDriver driver) { // Context context = new Context(); // context.setRegistry(ExtensionRegistry.create(webPageClass)); // context.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(webPageClass)); // context.getStore().put(DRIVER_KEY, driver); // return context; // } // // // }
import io.qameta.htmlelements.context.Context; import org.hamcrest.Matcher; import org.hamcrest.StringDescription; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Method;
package io.qameta.htmlelements.extension; @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @HandleWith(ShouldMethod.Extension.class) public @interface ShouldMethod { class Extension implements MethodHandler<Object> { @Override @SuppressWarnings("unchecked")
// Path: src/main/java/io/qameta/htmlelements/context/Context.java // public class Context { // // public static final String DESCRIPTION_KEY = "description"; // // public static final String LISTENERS_KEY = "listeners"; // // public static final String PROPERTIES_KEY = "properties"; // // public static final String PARAMETERS_KEY = "parameters"; // // public static final String DRIVER_KEY = "driver"; // // private Context parent; // // private Store store; // // private ExtensionRegistry registry; // // private Context() { // this.store = new DefaultStore(); // } // // public Optional<Context> getParent() { // return Optional.ofNullable(parent); // } // // private void setParent(Context parent) { // this.parent = parent; // } // // public Store getStore() { // return store; // } // // public ExtensionRegistry getRegistry() { // return registry; // } // // private void setRegistry(ExtensionRegistry registry) { // this.registry = registry; // } // // public Context newChildContext(Method method, Class<?> proxyClass) { // Context childContext = new Context(); // childContext.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(method, null)); // childContext.setRegistry(ExtensionRegistry.create(proxyClass)); // childContext.getRegistry().registerExtensions(method); // childContext.setParent(this); // //extension // getStore().get(PROPERTIES_KEY, Properties.class).ifPresent(properties -> { // Properties child = new Properties(); // child.putAll(properties); // childContext.getStore().put(PROPERTIES_KEY, child); // }); // getStore().get(PARAMETERS_KEY, Properties.class).ifPresent(properties -> { // Properties child = new Properties(); // child.putAll(properties); // childContext.getStore().put(PARAMETERS_KEY, child); // }); // getStore().get(LISTENERS_KEY, List.class).ifPresent(listeners -> { // childContext.getStore().put(LISTENERS_KEY, listeners); // }); // getStore().get(DRIVER_KEY, WebDriver.class).ifPresent(driver -> { // childContext.getStore().put(DRIVER_KEY, driver); // }); // return childContext; // } // // public static Context newWebPageContext(Class<?> webPageClass, WebDriver driver) { // Context context = new Context(); // context.setRegistry(ExtensionRegistry.create(webPageClass)); // context.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(webPageClass)); // context.getStore().put(DRIVER_KEY, driver); // return context; // } // // // } // Path: src/main/java/io/qameta/htmlelements/extension/ShouldMethod.java import io.qameta.htmlelements.context.Context; import org.hamcrest.Matcher; import org.hamcrest.StringDescription; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Method; package io.qameta.htmlelements.extension; @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @HandleWith(ShouldMethod.Extension.class) public @interface ShouldMethod { class Extension implements MethodHandler<Object> { @Override @SuppressWarnings("unchecked")
public Object handle(Context context, Object proxy, Method method, Object[] args) throws Throwable {
eroshenkoam/htmlelements
src/main/java/io/qameta/htmlelements/extension/ToStringMethod.java
// Path: src/main/java/io/qameta/htmlelements/context/Context.java // public class Context { // // public static final String DESCRIPTION_KEY = "description"; // // public static final String LISTENERS_KEY = "listeners"; // // public static final String PROPERTIES_KEY = "properties"; // // public static final String PARAMETERS_KEY = "parameters"; // // public static final String DRIVER_KEY = "driver"; // // private Context parent; // // private Store store; // // private ExtensionRegistry registry; // // private Context() { // this.store = new DefaultStore(); // } // // public Optional<Context> getParent() { // return Optional.ofNullable(parent); // } // // private void setParent(Context parent) { // this.parent = parent; // } // // public Store getStore() { // return store; // } // // public ExtensionRegistry getRegistry() { // return registry; // } // // private void setRegistry(ExtensionRegistry registry) { // this.registry = registry; // } // // public Context newChildContext(Method method, Class<?> proxyClass) { // Context childContext = new Context(); // childContext.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(method, null)); // childContext.setRegistry(ExtensionRegistry.create(proxyClass)); // childContext.getRegistry().registerExtensions(method); // childContext.setParent(this); // //extension // getStore().get(PROPERTIES_KEY, Properties.class).ifPresent(properties -> { // Properties child = new Properties(); // child.putAll(properties); // childContext.getStore().put(PROPERTIES_KEY, child); // }); // getStore().get(PARAMETERS_KEY, Properties.class).ifPresent(properties -> { // Properties child = new Properties(); // child.putAll(properties); // childContext.getStore().put(PARAMETERS_KEY, child); // }); // getStore().get(LISTENERS_KEY, List.class).ifPresent(listeners -> { // childContext.getStore().put(LISTENERS_KEY, listeners); // }); // getStore().get(DRIVER_KEY, WebDriver.class).ifPresent(driver -> { // childContext.getStore().put(DRIVER_KEY, driver); // }); // return childContext; // } // // public static Context newWebPageContext(Class<?> webPageClass, WebDriver driver) { // Context context = new Context(); // context.setRegistry(ExtensionRegistry.create(webPageClass)); // context.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(webPageClass)); // context.getStore().put(DRIVER_KEY, driver); // return context; // } // // // }
import io.qameta.htmlelements.context.Context; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Method; import java.util.NoSuchElementException;
package io.qameta.htmlelements.extension; @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @HandleWith(ToStringMethod.Extension.class) public @interface ToStringMethod { class Extension implements MethodHandler<String>{ @Override
// Path: src/main/java/io/qameta/htmlelements/context/Context.java // public class Context { // // public static final String DESCRIPTION_KEY = "description"; // // public static final String LISTENERS_KEY = "listeners"; // // public static final String PROPERTIES_KEY = "properties"; // // public static final String PARAMETERS_KEY = "parameters"; // // public static final String DRIVER_KEY = "driver"; // // private Context parent; // // private Store store; // // private ExtensionRegistry registry; // // private Context() { // this.store = new DefaultStore(); // } // // public Optional<Context> getParent() { // return Optional.ofNullable(parent); // } // // private void setParent(Context parent) { // this.parent = parent; // } // // public Store getStore() { // return store; // } // // public ExtensionRegistry getRegistry() { // return registry; // } // // private void setRegistry(ExtensionRegistry registry) { // this.registry = registry; // } // // public Context newChildContext(Method method, Class<?> proxyClass) { // Context childContext = new Context(); // childContext.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(method, null)); // childContext.setRegistry(ExtensionRegistry.create(proxyClass)); // childContext.getRegistry().registerExtensions(method); // childContext.setParent(this); // //extension // getStore().get(PROPERTIES_KEY, Properties.class).ifPresent(properties -> { // Properties child = new Properties(); // child.putAll(properties); // childContext.getStore().put(PROPERTIES_KEY, child); // }); // getStore().get(PARAMETERS_KEY, Properties.class).ifPresent(properties -> { // Properties child = new Properties(); // child.putAll(properties); // childContext.getStore().put(PARAMETERS_KEY, child); // }); // getStore().get(LISTENERS_KEY, List.class).ifPresent(listeners -> { // childContext.getStore().put(LISTENERS_KEY, listeners); // }); // getStore().get(DRIVER_KEY, WebDriver.class).ifPresent(driver -> { // childContext.getStore().put(DRIVER_KEY, driver); // }); // return childContext; // } // // public static Context newWebPageContext(Class<?> webPageClass, WebDriver driver) { // Context context = new Context(); // context.setRegistry(ExtensionRegistry.create(webPageClass)); // context.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(webPageClass)); // context.getStore().put(DRIVER_KEY, driver); // return context; // } // // // } // Path: src/main/java/io/qameta/htmlelements/extension/ToStringMethod.java import io.qameta.htmlelements.context.Context; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Method; import java.util.NoSuchElementException; package io.qameta.htmlelements.extension; @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @HandleWith(ToStringMethod.Extension.class) public @interface ToStringMethod { class Extension implements MethodHandler<String>{ @Override
public String handle(Context context, Object proxy, Method method, Object[] args) throws Throwable {
eroshenkoam/htmlelements
src/main/java/io/qameta/htmlelements/element/ExtendedList.java
// Path: src/main/java/io/qameta/htmlelements/matcher/PredicateMatcher.java // public class PredicateMatcher<T> extends TypeSafeMatcher<T> { // // private final Predicate<T> predicate; // // public PredicateMatcher(Predicate<T> predicate) { // this.predicate = predicate; // } // // @Override // protected boolean matchesSafely(T t) { // return predicate.test(t); // } // // @Override // public void describeTo(Description description) { // // } // // }
import io.qameta.htmlelements.extension.ConvertMethod; import io.qameta.htmlelements.extension.DescriptionProvider; import io.qameta.htmlelements.extension.FilterMethod; import io.qameta.htmlelements.extension.SelectorProvider; import io.qameta.htmlelements.extension.ShouldMethod; import io.qameta.htmlelements.extension.Timeout; import io.qameta.htmlelements.extension.ToStringMethod; import io.qameta.htmlelements.extension.WaitUntilMethod; import io.qameta.htmlelements.matcher.PredicateMatcher; import org.hamcrest.Matcher; import java.util.List; import java.util.function.Function; import java.util.function.Predicate;
package io.qameta.htmlelements.element; public interface ExtendedList<ItemType> extends List<ItemType> { @SelectorProvider String getSelector(); @DescriptionProvider String getDescription(); @ConvertMethod <R> ExtendedList<R> convert(Function<ItemType, R> function); @FilterMethod ExtendedList<ItemType> filter(Predicate<ItemType> predicate); default ExtendedList<ItemType> filter(Matcher matcher) { return filter(matcher::matches); } default ExtendedList<ItemType> filter(String description, Predicate<ItemType> predicate) { return filter(predicate); } @WaitUntilMethod ExtendedList<ItemType> waitUntil(String message, Matcher matcher); @WaitUntilMethod ExtendedList<ItemType> waitUntil(String message, Matcher matcher, @Timeout long timeout); default ExtendedList<ItemType> waitUntil(Matcher matcher) { return waitUntil("", matcher); } default ExtendedList<ItemType> waitUntil(String message, Predicate<ExtendedList<ItemType>> predicate) {
// Path: src/main/java/io/qameta/htmlelements/matcher/PredicateMatcher.java // public class PredicateMatcher<T> extends TypeSafeMatcher<T> { // // private final Predicate<T> predicate; // // public PredicateMatcher(Predicate<T> predicate) { // this.predicate = predicate; // } // // @Override // protected boolean matchesSafely(T t) { // return predicate.test(t); // } // // @Override // public void describeTo(Description description) { // // } // // } // Path: src/main/java/io/qameta/htmlelements/element/ExtendedList.java import io.qameta.htmlelements.extension.ConvertMethod; import io.qameta.htmlelements.extension.DescriptionProvider; import io.qameta.htmlelements.extension.FilterMethod; import io.qameta.htmlelements.extension.SelectorProvider; import io.qameta.htmlelements.extension.ShouldMethod; import io.qameta.htmlelements.extension.Timeout; import io.qameta.htmlelements.extension.ToStringMethod; import io.qameta.htmlelements.extension.WaitUntilMethod; import io.qameta.htmlelements.matcher.PredicateMatcher; import org.hamcrest.Matcher; import java.util.List; import java.util.function.Function; import java.util.function.Predicate; package io.qameta.htmlelements.element; public interface ExtendedList<ItemType> extends List<ItemType> { @SelectorProvider String getSelector(); @DescriptionProvider String getDescription(); @ConvertMethod <R> ExtendedList<R> convert(Function<ItemType, R> function); @FilterMethod ExtendedList<ItemType> filter(Predicate<ItemType> predicate); default ExtendedList<ItemType> filter(Matcher matcher) { return filter(matcher::matches); } default ExtendedList<ItemType> filter(String description, Predicate<ItemType> predicate) { return filter(predicate); } @WaitUntilMethod ExtendedList<ItemType> waitUntil(String message, Matcher matcher); @WaitUntilMethod ExtendedList<ItemType> waitUntil(String message, Matcher matcher, @Timeout long timeout); default ExtendedList<ItemType> waitUntil(Matcher matcher) { return waitUntil("", matcher); } default ExtendedList<ItemType> waitUntil(String message, Predicate<ExtendedList<ItemType>> predicate) {
return waitUntil(message, new PredicateMatcher<>(predicate));
eroshenkoam/htmlelements
src/test/java/io/qameta/htmlelements/example/element/SearchArrow.java
// Path: src/test/java/io/qameta/htmlelements/example/TestData.java // public class TestData { // // public static final String SEARCH_ARROW_XPATH = "//form[contains(@class, 'search2 suggest2-form')]"; // // public static final String SUGGEST_XPATH = "//div[@class='suggest']"; // // public static final String SUGGEST_ITEM_XPATH = "//a"; // // public static final String SEARCH_FORM_XPATH = "//div[@class='form']"; // // public static final String SEARCH_FORM_TEMPLATE = "//div[@class='{{ className }}']"; // // public static final String REQUEST_INPUT_XPATH = "//div[@class='input']"; // // // public static WebDriver mockDriver() { // // WebElement textInput = mockWebElement() // .withText("text input") // .withDisplayed(true) // .build(); // // List<WebElement> suggest = Arrays.asList( // mockWebElement() // .withChildElement(SUGGEST_ITEM_XPATH, mockWebElement().withText("first suggest item").build()) // .withText("first suggest") // .withDisplayed(false, true) // .build(), // mockWebElement() // .withChildElement(SUGGEST_ITEM_XPATH, mockWebElement().withText("second suggest item").build()) // .withText("second suggest") // .withDisplayed(false, false, false, true) // .build() // ); // // WebElement searchForm = mockWebElement() // .withChildElement(REQUEST_INPUT_XPATH, textInput) // .withText("searchForm") // .build(); // // WebElement searchArrow = mockWebElement() // .withChildElements(SUGGEST_XPATH, suggest) // .withChildElement(SEARCH_FORM_XPATH, searchForm) // .withText("search-arro", "search", "search-arrow") // .withDisplayed(true) // .build(); // // // WebDriver driver = mock(WebDriver.class); // when(driver.findElement(By.xpath(SEARCH_ARROW_XPATH))).thenReturn(searchArrow); // // return driver; // } // // private static WebElement createWebElement(String text, Boolean displayed, Boolean... displayedNext) { // WebElement webElement = mock(WebElement.class); // when(webElement.getText()).thenReturn(text); // when(webElement.toString()).thenReturn(text); // when(webElement.isDisplayed()).thenReturn(displayed, displayedNext); // return webElement; // } // // public static class WebElementBuilder { // // public static WebElementBuilder mockWebElement() { // return new WebElementBuilder(); // } // // private final WebElement element; // // public WebElementBuilder() { // this.element = mock(WebElement.class); // } // // public WebElementBuilder withText(String text, String... other) { // when(getElement().getText()).thenReturn(text, other); // return this; // } // // public WebElementBuilder withDisplayed(boolean displayed, Boolean... other) { // when(getElement().isDisplayed()).thenReturn(displayed, other); // return this; // } // // public WebElementBuilder withChildElement(String xpath, WebElement element) { // when(getElement().findElement(By.xpath(xpath))).thenReturn(element); // return this; // } // // public WebElementBuilder withChildElements(String xpath, List<WebElement> elements) { // when(getElement().findElements(By.xpath(xpath))).thenReturn(elements); // return this; // } // // private WebElement getElement() { // return element; // } // // public WebElement build() { // return getElement(); // } // // } // }
import io.qameta.htmlelements.annotation.Description; import io.qameta.htmlelements.annotation.FindBy; import io.qameta.htmlelements.annotation.Name; import io.qameta.htmlelements.annotation.Param; import io.qameta.htmlelements.element.*; import io.qameta.htmlelements.example.TestData; import io.qameta.htmlelements.extension.DescriptionProvider;
package io.qameta.htmlelements.example.element; /** * @author Artem Eroshenko <[email protected]> */ public interface SearchArrow extends WithSuggest<SearchArrow>, ExtendedWebElement<SearchArrow> { @Description("Форма {{ className }}")
// Path: src/test/java/io/qameta/htmlelements/example/TestData.java // public class TestData { // // public static final String SEARCH_ARROW_XPATH = "//form[contains(@class, 'search2 suggest2-form')]"; // // public static final String SUGGEST_XPATH = "//div[@class='suggest']"; // // public static final String SUGGEST_ITEM_XPATH = "//a"; // // public static final String SEARCH_FORM_XPATH = "//div[@class='form']"; // // public static final String SEARCH_FORM_TEMPLATE = "//div[@class='{{ className }}']"; // // public static final String REQUEST_INPUT_XPATH = "//div[@class='input']"; // // // public static WebDriver mockDriver() { // // WebElement textInput = mockWebElement() // .withText("text input") // .withDisplayed(true) // .build(); // // List<WebElement> suggest = Arrays.asList( // mockWebElement() // .withChildElement(SUGGEST_ITEM_XPATH, mockWebElement().withText("first suggest item").build()) // .withText("first suggest") // .withDisplayed(false, true) // .build(), // mockWebElement() // .withChildElement(SUGGEST_ITEM_XPATH, mockWebElement().withText("second suggest item").build()) // .withText("second suggest") // .withDisplayed(false, false, false, true) // .build() // ); // // WebElement searchForm = mockWebElement() // .withChildElement(REQUEST_INPUT_XPATH, textInput) // .withText("searchForm") // .build(); // // WebElement searchArrow = mockWebElement() // .withChildElements(SUGGEST_XPATH, suggest) // .withChildElement(SEARCH_FORM_XPATH, searchForm) // .withText("search-arro", "search", "search-arrow") // .withDisplayed(true) // .build(); // // // WebDriver driver = mock(WebDriver.class); // when(driver.findElement(By.xpath(SEARCH_ARROW_XPATH))).thenReturn(searchArrow); // // return driver; // } // // private static WebElement createWebElement(String text, Boolean displayed, Boolean... displayedNext) { // WebElement webElement = mock(WebElement.class); // when(webElement.getText()).thenReturn(text); // when(webElement.toString()).thenReturn(text); // when(webElement.isDisplayed()).thenReturn(displayed, displayedNext); // return webElement; // } // // public static class WebElementBuilder { // // public static WebElementBuilder mockWebElement() { // return new WebElementBuilder(); // } // // private final WebElement element; // // public WebElementBuilder() { // this.element = mock(WebElement.class); // } // // public WebElementBuilder withText(String text, String... other) { // when(getElement().getText()).thenReturn(text, other); // return this; // } // // public WebElementBuilder withDisplayed(boolean displayed, Boolean... other) { // when(getElement().isDisplayed()).thenReturn(displayed, other); // return this; // } // // public WebElementBuilder withChildElement(String xpath, WebElement element) { // when(getElement().findElement(By.xpath(xpath))).thenReturn(element); // return this; // } // // public WebElementBuilder withChildElements(String xpath, List<WebElement> elements) { // when(getElement().findElements(By.xpath(xpath))).thenReturn(elements); // return this; // } // // private WebElement getElement() { // return element; // } // // public WebElement build() { // return getElement(); // } // // } // } // Path: src/test/java/io/qameta/htmlelements/example/element/SearchArrow.java import io.qameta.htmlelements.annotation.Description; import io.qameta.htmlelements.annotation.FindBy; import io.qameta.htmlelements.annotation.Name; import io.qameta.htmlelements.annotation.Param; import io.qameta.htmlelements.element.*; import io.qameta.htmlelements.example.TestData; import io.qameta.htmlelements.extension.DescriptionProvider; package io.qameta.htmlelements.example.element; /** * @author Artem Eroshenko <[email protected]> */ public interface SearchArrow extends WithSuggest<SearchArrow>, ExtendedWebElement<SearchArrow> { @Description("Форма {{ className }}")
@FindBy(TestData.SEARCH_FORM_TEMPLATE)
eroshenkoam/htmlelements
src/main/java/io/qameta/htmlelements/extension/DefaultMethod.java
// Path: src/main/java/io/qameta/htmlelements/context/Context.java // public class Context { // // public static final String DESCRIPTION_KEY = "description"; // // public static final String LISTENERS_KEY = "listeners"; // // public static final String PROPERTIES_KEY = "properties"; // // public static final String PARAMETERS_KEY = "parameters"; // // public static final String DRIVER_KEY = "driver"; // // private Context parent; // // private Store store; // // private ExtensionRegistry registry; // // private Context() { // this.store = new DefaultStore(); // } // // public Optional<Context> getParent() { // return Optional.ofNullable(parent); // } // // private void setParent(Context parent) { // this.parent = parent; // } // // public Store getStore() { // return store; // } // // public ExtensionRegistry getRegistry() { // return registry; // } // // private void setRegistry(ExtensionRegistry registry) { // this.registry = registry; // } // // public Context newChildContext(Method method, Class<?> proxyClass) { // Context childContext = new Context(); // childContext.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(method, null)); // childContext.setRegistry(ExtensionRegistry.create(proxyClass)); // childContext.getRegistry().registerExtensions(method); // childContext.setParent(this); // //extension // getStore().get(PROPERTIES_KEY, Properties.class).ifPresent(properties -> { // Properties child = new Properties(); // child.putAll(properties); // childContext.getStore().put(PROPERTIES_KEY, child); // }); // getStore().get(PARAMETERS_KEY, Properties.class).ifPresent(properties -> { // Properties child = new Properties(); // child.putAll(properties); // childContext.getStore().put(PARAMETERS_KEY, child); // }); // getStore().get(LISTENERS_KEY, List.class).ifPresent(listeners -> { // childContext.getStore().put(LISTENERS_KEY, listeners); // }); // getStore().get(DRIVER_KEY, WebDriver.class).ifPresent(driver -> { // childContext.getStore().put(DRIVER_KEY, driver); // }); // return childContext; // } // // public static Context newWebPageContext(Class<?> webPageClass, WebDriver driver) { // Context context = new Context(); // context.setRegistry(ExtensionRegistry.create(webPageClass)); // context.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(webPageClass)); // context.getStore().put(DRIVER_KEY, driver); // return context; // } // // // }
import io.qameta.htmlelements.context.Context; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.invoke.MethodHandles; import java.lang.reflect.Constructor; import java.lang.reflect.Method;
package io.qameta.htmlelements.extension; @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @HandleWith(DefaultMethod.Extension.class) public @interface DefaultMethod { class Extension implements MethodHandler { @Override
// Path: src/main/java/io/qameta/htmlelements/context/Context.java // public class Context { // // public static final String DESCRIPTION_KEY = "description"; // // public static final String LISTENERS_KEY = "listeners"; // // public static final String PROPERTIES_KEY = "properties"; // // public static final String PARAMETERS_KEY = "parameters"; // // public static final String DRIVER_KEY = "driver"; // // private Context parent; // // private Store store; // // private ExtensionRegistry registry; // // private Context() { // this.store = new DefaultStore(); // } // // public Optional<Context> getParent() { // return Optional.ofNullable(parent); // } // // private void setParent(Context parent) { // this.parent = parent; // } // // public Store getStore() { // return store; // } // // public ExtensionRegistry getRegistry() { // return registry; // } // // private void setRegistry(ExtensionRegistry registry) { // this.registry = registry; // } // // public Context newChildContext(Method method, Class<?> proxyClass) { // Context childContext = new Context(); // childContext.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(method, null)); // childContext.setRegistry(ExtensionRegistry.create(proxyClass)); // childContext.getRegistry().registerExtensions(method); // childContext.setParent(this); // //extension // getStore().get(PROPERTIES_KEY, Properties.class).ifPresent(properties -> { // Properties child = new Properties(); // child.putAll(properties); // childContext.getStore().put(PROPERTIES_KEY, child); // }); // getStore().get(PARAMETERS_KEY, Properties.class).ifPresent(properties -> { // Properties child = new Properties(); // child.putAll(properties); // childContext.getStore().put(PARAMETERS_KEY, child); // }); // getStore().get(LISTENERS_KEY, List.class).ifPresent(listeners -> { // childContext.getStore().put(LISTENERS_KEY, listeners); // }); // getStore().get(DRIVER_KEY, WebDriver.class).ifPresent(driver -> { // childContext.getStore().put(DRIVER_KEY, driver); // }); // return childContext; // } // // public static Context newWebPageContext(Class<?> webPageClass, WebDriver driver) { // Context context = new Context(); // context.setRegistry(ExtensionRegistry.create(webPageClass)); // context.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(webPageClass)); // context.getStore().put(DRIVER_KEY, driver); // return context; // } // // // } // Path: src/main/java/io/qameta/htmlelements/extension/DefaultMethod.java import io.qameta.htmlelements.context.Context; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.invoke.MethodHandles; import java.lang.reflect.Constructor; import java.lang.reflect.Method; package io.qameta.htmlelements.extension; @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @HandleWith(DefaultMethod.Extension.class) public @interface DefaultMethod { class Extension implements MethodHandler { @Override
public Object handle(Context context, Object proxy, Method method, Object[] args) throws Throwable {
eroshenkoam/htmlelements
src/test/java/io/qameta/htmlelements/example/page/SearchPage.java
// Path: src/main/java/io/qameta/htmlelements/WebPage.java // public interface WebPage extends WrapsDriver, SearchContext { // // @DriverProvider // WebDriver getWrappedDriver(); // // @GoMethod // void go(); // // @IsAtMethod // void isAt(Matcher<String> url); // // default void open(String url) { // getWrappedDriver().get(url); // } // // @ToStringMethod // String toString(); // // } // // Path: src/test/java/io/qameta/htmlelements/example/TestData.java // public class TestData { // // public static final String SEARCH_ARROW_XPATH = "//form[contains(@class, 'search2 suggest2-form')]"; // // public static final String SUGGEST_XPATH = "//div[@class='suggest']"; // // public static final String SUGGEST_ITEM_XPATH = "//a"; // // public static final String SEARCH_FORM_XPATH = "//div[@class='form']"; // // public static final String SEARCH_FORM_TEMPLATE = "//div[@class='{{ className }}']"; // // public static final String REQUEST_INPUT_XPATH = "//div[@class='input']"; // // // public static WebDriver mockDriver() { // // WebElement textInput = mockWebElement() // .withText("text input") // .withDisplayed(true) // .build(); // // List<WebElement> suggest = Arrays.asList( // mockWebElement() // .withChildElement(SUGGEST_ITEM_XPATH, mockWebElement().withText("first suggest item").build()) // .withText("first suggest") // .withDisplayed(false, true) // .build(), // mockWebElement() // .withChildElement(SUGGEST_ITEM_XPATH, mockWebElement().withText("second suggest item").build()) // .withText("second suggest") // .withDisplayed(false, false, false, true) // .build() // ); // // WebElement searchForm = mockWebElement() // .withChildElement(REQUEST_INPUT_XPATH, textInput) // .withText("searchForm") // .build(); // // WebElement searchArrow = mockWebElement() // .withChildElements(SUGGEST_XPATH, suggest) // .withChildElement(SEARCH_FORM_XPATH, searchForm) // .withText("search-arro", "search", "search-arrow") // .withDisplayed(true) // .build(); // // // WebDriver driver = mock(WebDriver.class); // when(driver.findElement(By.xpath(SEARCH_ARROW_XPATH))).thenReturn(searchArrow); // // return driver; // } // // private static WebElement createWebElement(String text, Boolean displayed, Boolean... displayedNext) { // WebElement webElement = mock(WebElement.class); // when(webElement.getText()).thenReturn(text); // when(webElement.toString()).thenReturn(text); // when(webElement.isDisplayed()).thenReturn(displayed, displayedNext); // return webElement; // } // // public static class WebElementBuilder { // // public static WebElementBuilder mockWebElement() { // return new WebElementBuilder(); // } // // private final WebElement element; // // public WebElementBuilder() { // this.element = mock(WebElement.class); // } // // public WebElementBuilder withText(String text, String... other) { // when(getElement().getText()).thenReturn(text, other); // return this; // } // // public WebElementBuilder withDisplayed(boolean displayed, Boolean... other) { // when(getElement().isDisplayed()).thenReturn(displayed, other); // return this; // } // // public WebElementBuilder withChildElement(String xpath, WebElement element) { // when(getElement().findElement(By.xpath(xpath))).thenReturn(element); // return this; // } // // public WebElementBuilder withChildElements(String xpath, List<WebElement> elements) { // when(getElement().findElements(By.xpath(xpath))).thenReturn(elements); // return this; // } // // private WebElement getElement() { // return element; // } // // public WebElement build() { // return getElement(); // } // // } // } // // Path: src/test/java/io/qameta/htmlelements/example/element/SearchArrow.java // public interface SearchArrow extends WithSuggest<SearchArrow>, ExtendedWebElement<SearchArrow> { // // @Description("Форма {{ className }}") // @FindBy(TestData.SEARCH_FORM_TEMPLATE) // SearchForm form(@Param("className") String className); // // }
import io.qameta.htmlelements.WebPage; import io.qameta.htmlelements.annotation.Description; import io.qameta.htmlelements.annotation.FindBy; import io.qameta.htmlelements.example.TestData; import io.qameta.htmlelements.example.element.SearchArrow; import io.qameta.htmlelements.extension.page.BaseUrl;
package io.qameta.htmlelements.example.page; /** * @author Artem Eroshenko <[email protected]> */ @BaseUrl("http://www.base.url") public interface SearchPage extends WebPage { @Description("Поисковая строка")
// Path: src/main/java/io/qameta/htmlelements/WebPage.java // public interface WebPage extends WrapsDriver, SearchContext { // // @DriverProvider // WebDriver getWrappedDriver(); // // @GoMethod // void go(); // // @IsAtMethod // void isAt(Matcher<String> url); // // default void open(String url) { // getWrappedDriver().get(url); // } // // @ToStringMethod // String toString(); // // } // // Path: src/test/java/io/qameta/htmlelements/example/TestData.java // public class TestData { // // public static final String SEARCH_ARROW_XPATH = "//form[contains(@class, 'search2 suggest2-form')]"; // // public static final String SUGGEST_XPATH = "//div[@class='suggest']"; // // public static final String SUGGEST_ITEM_XPATH = "//a"; // // public static final String SEARCH_FORM_XPATH = "//div[@class='form']"; // // public static final String SEARCH_FORM_TEMPLATE = "//div[@class='{{ className }}']"; // // public static final String REQUEST_INPUT_XPATH = "//div[@class='input']"; // // // public static WebDriver mockDriver() { // // WebElement textInput = mockWebElement() // .withText("text input") // .withDisplayed(true) // .build(); // // List<WebElement> suggest = Arrays.asList( // mockWebElement() // .withChildElement(SUGGEST_ITEM_XPATH, mockWebElement().withText("first suggest item").build()) // .withText("first suggest") // .withDisplayed(false, true) // .build(), // mockWebElement() // .withChildElement(SUGGEST_ITEM_XPATH, mockWebElement().withText("second suggest item").build()) // .withText("second suggest") // .withDisplayed(false, false, false, true) // .build() // ); // // WebElement searchForm = mockWebElement() // .withChildElement(REQUEST_INPUT_XPATH, textInput) // .withText("searchForm") // .build(); // // WebElement searchArrow = mockWebElement() // .withChildElements(SUGGEST_XPATH, suggest) // .withChildElement(SEARCH_FORM_XPATH, searchForm) // .withText("search-arro", "search", "search-arrow") // .withDisplayed(true) // .build(); // // // WebDriver driver = mock(WebDriver.class); // when(driver.findElement(By.xpath(SEARCH_ARROW_XPATH))).thenReturn(searchArrow); // // return driver; // } // // private static WebElement createWebElement(String text, Boolean displayed, Boolean... displayedNext) { // WebElement webElement = mock(WebElement.class); // when(webElement.getText()).thenReturn(text); // when(webElement.toString()).thenReturn(text); // when(webElement.isDisplayed()).thenReturn(displayed, displayedNext); // return webElement; // } // // public static class WebElementBuilder { // // public static WebElementBuilder mockWebElement() { // return new WebElementBuilder(); // } // // private final WebElement element; // // public WebElementBuilder() { // this.element = mock(WebElement.class); // } // // public WebElementBuilder withText(String text, String... other) { // when(getElement().getText()).thenReturn(text, other); // return this; // } // // public WebElementBuilder withDisplayed(boolean displayed, Boolean... other) { // when(getElement().isDisplayed()).thenReturn(displayed, other); // return this; // } // // public WebElementBuilder withChildElement(String xpath, WebElement element) { // when(getElement().findElement(By.xpath(xpath))).thenReturn(element); // return this; // } // // public WebElementBuilder withChildElements(String xpath, List<WebElement> elements) { // when(getElement().findElements(By.xpath(xpath))).thenReturn(elements); // return this; // } // // private WebElement getElement() { // return element; // } // // public WebElement build() { // return getElement(); // } // // } // } // // Path: src/test/java/io/qameta/htmlelements/example/element/SearchArrow.java // public interface SearchArrow extends WithSuggest<SearchArrow>, ExtendedWebElement<SearchArrow> { // // @Description("Форма {{ className }}") // @FindBy(TestData.SEARCH_FORM_TEMPLATE) // SearchForm form(@Param("className") String className); // // } // Path: src/test/java/io/qameta/htmlelements/example/page/SearchPage.java import io.qameta.htmlelements.WebPage; import io.qameta.htmlelements.annotation.Description; import io.qameta.htmlelements.annotation.FindBy; import io.qameta.htmlelements.example.TestData; import io.qameta.htmlelements.example.element.SearchArrow; import io.qameta.htmlelements.extension.page.BaseUrl; package io.qameta.htmlelements.example.page; /** * @author Artem Eroshenko <[email protected]> */ @BaseUrl("http://www.base.url") public interface SearchPage extends WebPage { @Description("Поисковая строка")
@FindBy(TestData.SEARCH_ARROW_XPATH)
eroshenkoam/htmlelements
src/test/java/io/qameta/htmlelements/example/page/SearchPage.java
// Path: src/main/java/io/qameta/htmlelements/WebPage.java // public interface WebPage extends WrapsDriver, SearchContext { // // @DriverProvider // WebDriver getWrappedDriver(); // // @GoMethod // void go(); // // @IsAtMethod // void isAt(Matcher<String> url); // // default void open(String url) { // getWrappedDriver().get(url); // } // // @ToStringMethod // String toString(); // // } // // Path: src/test/java/io/qameta/htmlelements/example/TestData.java // public class TestData { // // public static final String SEARCH_ARROW_XPATH = "//form[contains(@class, 'search2 suggest2-form')]"; // // public static final String SUGGEST_XPATH = "//div[@class='suggest']"; // // public static final String SUGGEST_ITEM_XPATH = "//a"; // // public static final String SEARCH_FORM_XPATH = "//div[@class='form']"; // // public static final String SEARCH_FORM_TEMPLATE = "//div[@class='{{ className }}']"; // // public static final String REQUEST_INPUT_XPATH = "//div[@class='input']"; // // // public static WebDriver mockDriver() { // // WebElement textInput = mockWebElement() // .withText("text input") // .withDisplayed(true) // .build(); // // List<WebElement> suggest = Arrays.asList( // mockWebElement() // .withChildElement(SUGGEST_ITEM_XPATH, mockWebElement().withText("first suggest item").build()) // .withText("first suggest") // .withDisplayed(false, true) // .build(), // mockWebElement() // .withChildElement(SUGGEST_ITEM_XPATH, mockWebElement().withText("second suggest item").build()) // .withText("second suggest") // .withDisplayed(false, false, false, true) // .build() // ); // // WebElement searchForm = mockWebElement() // .withChildElement(REQUEST_INPUT_XPATH, textInput) // .withText("searchForm") // .build(); // // WebElement searchArrow = mockWebElement() // .withChildElements(SUGGEST_XPATH, suggest) // .withChildElement(SEARCH_FORM_XPATH, searchForm) // .withText("search-arro", "search", "search-arrow") // .withDisplayed(true) // .build(); // // // WebDriver driver = mock(WebDriver.class); // when(driver.findElement(By.xpath(SEARCH_ARROW_XPATH))).thenReturn(searchArrow); // // return driver; // } // // private static WebElement createWebElement(String text, Boolean displayed, Boolean... displayedNext) { // WebElement webElement = mock(WebElement.class); // when(webElement.getText()).thenReturn(text); // when(webElement.toString()).thenReturn(text); // when(webElement.isDisplayed()).thenReturn(displayed, displayedNext); // return webElement; // } // // public static class WebElementBuilder { // // public static WebElementBuilder mockWebElement() { // return new WebElementBuilder(); // } // // private final WebElement element; // // public WebElementBuilder() { // this.element = mock(WebElement.class); // } // // public WebElementBuilder withText(String text, String... other) { // when(getElement().getText()).thenReturn(text, other); // return this; // } // // public WebElementBuilder withDisplayed(boolean displayed, Boolean... other) { // when(getElement().isDisplayed()).thenReturn(displayed, other); // return this; // } // // public WebElementBuilder withChildElement(String xpath, WebElement element) { // when(getElement().findElement(By.xpath(xpath))).thenReturn(element); // return this; // } // // public WebElementBuilder withChildElements(String xpath, List<WebElement> elements) { // when(getElement().findElements(By.xpath(xpath))).thenReturn(elements); // return this; // } // // private WebElement getElement() { // return element; // } // // public WebElement build() { // return getElement(); // } // // } // } // // Path: src/test/java/io/qameta/htmlelements/example/element/SearchArrow.java // public interface SearchArrow extends WithSuggest<SearchArrow>, ExtendedWebElement<SearchArrow> { // // @Description("Форма {{ className }}") // @FindBy(TestData.SEARCH_FORM_TEMPLATE) // SearchForm form(@Param("className") String className); // // }
import io.qameta.htmlelements.WebPage; import io.qameta.htmlelements.annotation.Description; import io.qameta.htmlelements.annotation.FindBy; import io.qameta.htmlelements.example.TestData; import io.qameta.htmlelements.example.element.SearchArrow; import io.qameta.htmlelements.extension.page.BaseUrl;
package io.qameta.htmlelements.example.page; /** * @author Artem Eroshenko <[email protected]> */ @BaseUrl("http://www.base.url") public interface SearchPage extends WebPage { @Description("Поисковая строка") @FindBy(TestData.SEARCH_ARROW_XPATH)
// Path: src/main/java/io/qameta/htmlelements/WebPage.java // public interface WebPage extends WrapsDriver, SearchContext { // // @DriverProvider // WebDriver getWrappedDriver(); // // @GoMethod // void go(); // // @IsAtMethod // void isAt(Matcher<String> url); // // default void open(String url) { // getWrappedDriver().get(url); // } // // @ToStringMethod // String toString(); // // } // // Path: src/test/java/io/qameta/htmlelements/example/TestData.java // public class TestData { // // public static final String SEARCH_ARROW_XPATH = "//form[contains(@class, 'search2 suggest2-form')]"; // // public static final String SUGGEST_XPATH = "//div[@class='suggest']"; // // public static final String SUGGEST_ITEM_XPATH = "//a"; // // public static final String SEARCH_FORM_XPATH = "//div[@class='form']"; // // public static final String SEARCH_FORM_TEMPLATE = "//div[@class='{{ className }}']"; // // public static final String REQUEST_INPUT_XPATH = "//div[@class='input']"; // // // public static WebDriver mockDriver() { // // WebElement textInput = mockWebElement() // .withText("text input") // .withDisplayed(true) // .build(); // // List<WebElement> suggest = Arrays.asList( // mockWebElement() // .withChildElement(SUGGEST_ITEM_XPATH, mockWebElement().withText("first suggest item").build()) // .withText("first suggest") // .withDisplayed(false, true) // .build(), // mockWebElement() // .withChildElement(SUGGEST_ITEM_XPATH, mockWebElement().withText("second suggest item").build()) // .withText("second suggest") // .withDisplayed(false, false, false, true) // .build() // ); // // WebElement searchForm = mockWebElement() // .withChildElement(REQUEST_INPUT_XPATH, textInput) // .withText("searchForm") // .build(); // // WebElement searchArrow = mockWebElement() // .withChildElements(SUGGEST_XPATH, suggest) // .withChildElement(SEARCH_FORM_XPATH, searchForm) // .withText("search-arro", "search", "search-arrow") // .withDisplayed(true) // .build(); // // // WebDriver driver = mock(WebDriver.class); // when(driver.findElement(By.xpath(SEARCH_ARROW_XPATH))).thenReturn(searchArrow); // // return driver; // } // // private static WebElement createWebElement(String text, Boolean displayed, Boolean... displayedNext) { // WebElement webElement = mock(WebElement.class); // when(webElement.getText()).thenReturn(text); // when(webElement.toString()).thenReturn(text); // when(webElement.isDisplayed()).thenReturn(displayed, displayedNext); // return webElement; // } // // public static class WebElementBuilder { // // public static WebElementBuilder mockWebElement() { // return new WebElementBuilder(); // } // // private final WebElement element; // // public WebElementBuilder() { // this.element = mock(WebElement.class); // } // // public WebElementBuilder withText(String text, String... other) { // when(getElement().getText()).thenReturn(text, other); // return this; // } // // public WebElementBuilder withDisplayed(boolean displayed, Boolean... other) { // when(getElement().isDisplayed()).thenReturn(displayed, other); // return this; // } // // public WebElementBuilder withChildElement(String xpath, WebElement element) { // when(getElement().findElement(By.xpath(xpath))).thenReturn(element); // return this; // } // // public WebElementBuilder withChildElements(String xpath, List<WebElement> elements) { // when(getElement().findElements(By.xpath(xpath))).thenReturn(elements); // return this; // } // // private WebElement getElement() { // return element; // } // // public WebElement build() { // return getElement(); // } // // } // } // // Path: src/test/java/io/qameta/htmlelements/example/element/SearchArrow.java // public interface SearchArrow extends WithSuggest<SearchArrow>, ExtendedWebElement<SearchArrow> { // // @Description("Форма {{ className }}") // @FindBy(TestData.SEARCH_FORM_TEMPLATE) // SearchForm form(@Param("className") String className); // // } // Path: src/test/java/io/qameta/htmlelements/example/page/SearchPage.java import io.qameta.htmlelements.WebPage; import io.qameta.htmlelements.annotation.Description; import io.qameta.htmlelements.annotation.FindBy; import io.qameta.htmlelements.example.TestData; import io.qameta.htmlelements.example.element.SearchArrow; import io.qameta.htmlelements.extension.page.BaseUrl; package io.qameta.htmlelements.example.page; /** * @author Artem Eroshenko <[email protected]> */ @BaseUrl("http://www.base.url") public interface SearchPage extends WebPage { @Description("Поисковая строка") @FindBy(TestData.SEARCH_ARROW_XPATH)
SearchArrow searchArrow();
eroshenkoam/htmlelements
src/main/java/io/qameta/htmlelements/extension/DescriptionProvider.java
// Path: src/main/java/io/qameta/htmlelements/context/Context.java // public class Context { // // public static final String DESCRIPTION_KEY = "description"; // // public static final String LISTENERS_KEY = "listeners"; // // public static final String PROPERTIES_KEY = "properties"; // // public static final String PARAMETERS_KEY = "parameters"; // // public static final String DRIVER_KEY = "driver"; // // private Context parent; // // private Store store; // // private ExtensionRegistry registry; // // private Context() { // this.store = new DefaultStore(); // } // // public Optional<Context> getParent() { // return Optional.ofNullable(parent); // } // // private void setParent(Context parent) { // this.parent = parent; // } // // public Store getStore() { // return store; // } // // public ExtensionRegistry getRegistry() { // return registry; // } // // private void setRegistry(ExtensionRegistry registry) { // this.registry = registry; // } // // public Context newChildContext(Method method, Class<?> proxyClass) { // Context childContext = new Context(); // childContext.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(method, null)); // childContext.setRegistry(ExtensionRegistry.create(proxyClass)); // childContext.getRegistry().registerExtensions(method); // childContext.setParent(this); // //extension // getStore().get(PROPERTIES_KEY, Properties.class).ifPresent(properties -> { // Properties child = new Properties(); // child.putAll(properties); // childContext.getStore().put(PROPERTIES_KEY, child); // }); // getStore().get(PARAMETERS_KEY, Properties.class).ifPresent(properties -> { // Properties child = new Properties(); // child.putAll(properties); // childContext.getStore().put(PARAMETERS_KEY, child); // }); // getStore().get(LISTENERS_KEY, List.class).ifPresent(listeners -> { // childContext.getStore().put(LISTENERS_KEY, listeners); // }); // getStore().get(DRIVER_KEY, WebDriver.class).ifPresent(driver -> { // childContext.getStore().put(DRIVER_KEY, driver); // }); // return childContext; // } // // public static Context newWebPageContext(Class<?> webPageClass, WebDriver driver) { // Context context = new Context(); // context.setRegistry(ExtensionRegistry.create(webPageClass)); // context.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(webPageClass)); // context.getStore().put(DRIVER_KEY, driver); // return context; // } // // // }
import io.qameta.htmlelements.context.Context; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Method; import java.util.NoSuchElementException;
package io.qameta.htmlelements.extension; @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @HandleWith(DescriptionProvider.Extension.class) public @interface DescriptionProvider { class Extension implements MethodHandler<String> { private static final String DESCRIPTION_KEY = "description"; @Override
// Path: src/main/java/io/qameta/htmlelements/context/Context.java // public class Context { // // public static final String DESCRIPTION_KEY = "description"; // // public static final String LISTENERS_KEY = "listeners"; // // public static final String PROPERTIES_KEY = "properties"; // // public static final String PARAMETERS_KEY = "parameters"; // // public static final String DRIVER_KEY = "driver"; // // private Context parent; // // private Store store; // // private ExtensionRegistry registry; // // private Context() { // this.store = new DefaultStore(); // } // // public Optional<Context> getParent() { // return Optional.ofNullable(parent); // } // // private void setParent(Context parent) { // this.parent = parent; // } // // public Store getStore() { // return store; // } // // public ExtensionRegistry getRegistry() { // return registry; // } // // private void setRegistry(ExtensionRegistry registry) { // this.registry = registry; // } // // public Context newChildContext(Method method, Class<?> proxyClass) { // Context childContext = new Context(); // childContext.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(method, null)); // childContext.setRegistry(ExtensionRegistry.create(proxyClass)); // childContext.getRegistry().registerExtensions(method); // childContext.setParent(this); // //extension // getStore().get(PROPERTIES_KEY, Properties.class).ifPresent(properties -> { // Properties child = new Properties(); // child.putAll(properties); // childContext.getStore().put(PROPERTIES_KEY, child); // }); // getStore().get(PARAMETERS_KEY, Properties.class).ifPresent(properties -> { // Properties child = new Properties(); // child.putAll(properties); // childContext.getStore().put(PARAMETERS_KEY, child); // }); // getStore().get(LISTENERS_KEY, List.class).ifPresent(listeners -> { // childContext.getStore().put(LISTENERS_KEY, listeners); // }); // getStore().get(DRIVER_KEY, WebDriver.class).ifPresent(driver -> { // childContext.getStore().put(DRIVER_KEY, driver); // }); // return childContext; // } // // public static Context newWebPageContext(Class<?> webPageClass, WebDriver driver) { // Context context = new Context(); // context.setRegistry(ExtensionRegistry.create(webPageClass)); // context.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(webPageClass)); // context.getStore().put(DRIVER_KEY, driver); // return context; // } // // // } // Path: src/main/java/io/qameta/htmlelements/extension/DescriptionProvider.java import io.qameta.htmlelements.context.Context; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Method; import java.util.NoSuchElementException; package io.qameta.htmlelements.extension; @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @HandleWith(DescriptionProvider.Extension.class) public @interface DescriptionProvider { class Extension implements MethodHandler<String> { private static final String DESCRIPTION_KEY = "description"; @Override
public String handle(Context context, Object proxy, Method method, Object[] args) throws Throwable {
eroshenkoam/htmlelements
src/main/java/io/qameta/htmlelements/element/ExtendedWebElement.java
// Path: src/main/java/io/qameta/htmlelements/matcher/PredicateMatcher.java // public class PredicateMatcher<T> extends TypeSafeMatcher<T> { // // private final Predicate<T> predicate; // // public PredicateMatcher(Predicate<T> predicate) { // this.predicate = predicate; // } // // @Override // protected boolean matchesSafely(T t) { // return predicate.test(t); // } // // @Override // public void describeTo(Description description) { // // } // // }
import io.qameta.htmlelements.extension.HoverMethod; import io.qameta.htmlelements.extension.ShouldMethod; import io.qameta.htmlelements.extension.Timeout; import io.qameta.htmlelements.extension.ToStringMethod; import io.qameta.htmlelements.extension.WaitUntilMethod; import io.qameta.htmlelements.matcher.PredicateMatcher; import org.hamcrest.Matcher; import org.openqa.selenium.WebElement; import org.openqa.selenium.internal.Locatable; import java.util.function.Predicate;
package io.qameta.htmlelements.element; public interface ExtendedWebElement<FluentType> extends WebElement, Locatable { @HoverMethod FluentType hover(); @WaitUntilMethod FluentType waitUntil(String message, Matcher matcher); @WaitUntilMethod FluentType waitUntil(String message, Matcher matcher, @Timeout long timeout); default FluentType waitUntil(Matcher matcher) { return waitUntil("", matcher); } default FluentType waitUntil(Predicate<FluentType> predicate) { return waitUntil("", predicate); } default FluentType waitUntil(String description, Predicate<FluentType> predicate) {
// Path: src/main/java/io/qameta/htmlelements/matcher/PredicateMatcher.java // public class PredicateMatcher<T> extends TypeSafeMatcher<T> { // // private final Predicate<T> predicate; // // public PredicateMatcher(Predicate<T> predicate) { // this.predicate = predicate; // } // // @Override // protected boolean matchesSafely(T t) { // return predicate.test(t); // } // // @Override // public void describeTo(Description description) { // // } // // } // Path: src/main/java/io/qameta/htmlelements/element/ExtendedWebElement.java import io.qameta.htmlelements.extension.HoverMethod; import io.qameta.htmlelements.extension.ShouldMethod; import io.qameta.htmlelements.extension.Timeout; import io.qameta.htmlelements.extension.ToStringMethod; import io.qameta.htmlelements.extension.WaitUntilMethod; import io.qameta.htmlelements.matcher.PredicateMatcher; import org.hamcrest.Matcher; import org.openqa.selenium.WebElement; import org.openqa.selenium.internal.Locatable; import java.util.function.Predicate; package io.qameta.htmlelements.element; public interface ExtendedWebElement<FluentType> extends WebElement, Locatable { @HoverMethod FluentType hover(); @WaitUntilMethod FluentType waitUntil(String message, Matcher matcher); @WaitUntilMethod FluentType waitUntil(String message, Matcher matcher, @Timeout long timeout); default FluentType waitUntil(Matcher matcher) { return waitUntil("", matcher); } default FluentType waitUntil(Predicate<FluentType> predicate) { return waitUntil("", predicate); } default FluentType waitUntil(String description, Predicate<FluentType> predicate) {
return waitUntil(description, new PredicateMatcher<>(predicate));
turn/camino
src/main/java/com/turn/camino/MetricDatum.java
// Path: src/main/java/com/turn/camino/config/Metric.java // public class Metric { // // private final String name; // private final String function; // private final String aggregate; // private final String aggFunction; // private final double defaultValue; // // /** // * Constructor // * // * @param name name of metric // * @param function function of metric // * @param aggregate aggregate of metric // */ // @JsonCreator // public Metric(@JsonProperty("name") String name, @JsonProperty("function") String function, // @JsonProperty("aggregate") String aggregate, // @JsonProperty("aggFunction") String aggFunction, // @JsonProperty("defaultValue") double defaultValue) { // this.name = name; // this.function = function; // this.aggregate = aggregate; // this.aggFunction = aggFunction; // this.defaultValue = defaultValue; // } // // /** // * Gets name of metric // * // * @return name of metric // */ // @Member("name") // public String getName() { // return name; // } // // /** // * Gets function of metric // * // * @return type of metric // */ // @Member("function") // public String getFunction() { // return function; // } // // /** // * Gets metric aggregate // * // * @return metric aggregate // */ // @Member("aggregate") // public String getAggregate() { // return aggregate; // } // // /** // * Gets custom aggregate function // * // * @return metric aggregate // */ // @Member("aggFunction") // public String getAggFunction() { // return aggFunction; // } // // /** // * Gets default value // * // * @return default value // */ // @Member("defaultValue") // public double getDefaultValue() { // return defaultValue; // } // // }
import com.turn.camino.config.Metric;
/* * Copyright (C) 2014-2018, Amobee Inc. All Rights Reserved. * * 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 */ package com.turn.camino; /** * Metric datum * * @author llo */ public class MetricDatum { private final MetricId metricId;
// Path: src/main/java/com/turn/camino/config/Metric.java // public class Metric { // // private final String name; // private final String function; // private final String aggregate; // private final String aggFunction; // private final double defaultValue; // // /** // * Constructor // * // * @param name name of metric // * @param function function of metric // * @param aggregate aggregate of metric // */ // @JsonCreator // public Metric(@JsonProperty("name") String name, @JsonProperty("function") String function, // @JsonProperty("aggregate") String aggregate, // @JsonProperty("aggFunction") String aggFunction, // @JsonProperty("defaultValue") double defaultValue) { // this.name = name; // this.function = function; // this.aggregate = aggregate; // this.aggFunction = aggFunction; // this.defaultValue = defaultValue; // } // // /** // * Gets name of metric // * // * @return name of metric // */ // @Member("name") // public String getName() { // return name; // } // // /** // * Gets function of metric // * // * @return type of metric // */ // @Member("function") // public String getFunction() { // return function; // } // // /** // * Gets metric aggregate // * // * @return metric aggregate // */ // @Member("aggregate") // public String getAggregate() { // return aggregate; // } // // /** // * Gets custom aggregate function // * // * @return metric aggregate // */ // @Member("aggFunction") // public String getAggFunction() { // return aggFunction; // } // // /** // * Gets default value // * // * @return default value // */ // @Member("defaultValue") // public double getDefaultValue() { // return defaultValue; // } // // } // Path: src/main/java/com/turn/camino/MetricDatum.java import com.turn.camino.config.Metric; /* * Copyright (C) 2014-2018, Amobee Inc. All Rights Reserved. * * 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 */ package com.turn.camino; /** * Metric datum * * @author llo */ public class MetricDatum { private final MetricId metricId;
private final Metric metric;
turn/camino
src/main/java/com/turn/camino/MetricId.java
// Path: src/main/java/com/turn/camino/config/Tag.java // public class Tag { // // private final String key; // private final String value; // // /** // * Constructor // * // * @param key key of tag // * @param value value of tag // */ // public Tag(String key, String value) { // Preconditions.checkNotNull(key, "Tag key cannot be null"); // Preconditions.checkNotNull(value, "Tag value cannot be null"); // this.key = key; // this.value = value; // } // // /** // * Gets key of tag // * // * @return key of tag // */ // @Member("key") // public String getKey() { // return key; // } // // /** // * Gets value of tag // * // * @return value of tag // */ // @Member("value") // public String getValue() { // return value; // } // // }
import com.turn.camino.config.Tag; import com.google.common.collect.ImmutableList; import java.util.List;
/* * Copyright (C) 2014-2018, Amobee Inc. All Rights Reserved. * * 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 */ package com.turn.camino; /** * Metric identifier * * @author llo */ public class MetricId { private final String name; private final String pathName;
// Path: src/main/java/com/turn/camino/config/Tag.java // public class Tag { // // private final String key; // private final String value; // // /** // * Constructor // * // * @param key key of tag // * @param value value of tag // */ // public Tag(String key, String value) { // Preconditions.checkNotNull(key, "Tag key cannot be null"); // Preconditions.checkNotNull(value, "Tag value cannot be null"); // this.key = key; // this.value = value; // } // // /** // * Gets key of tag // * // * @return key of tag // */ // @Member("key") // public String getKey() { // return key; // } // // /** // * Gets value of tag // * // * @return value of tag // */ // @Member("value") // public String getValue() { // return value; // } // // } // Path: src/main/java/com/turn/camino/MetricId.java import com.turn.camino.config.Tag; import com.google.common.collect.ImmutableList; import java.util.List; /* * Copyright (C) 2014-2018, Amobee Inc. All Rights Reserved. * * 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 */ package com.turn.camino; /** * Metric identifier * * @author llo */ public class MetricId { private final String name; private final String pathName;
private final List<Tag> tags;
turn/camino
src/main/java/com/turn/camino/PathStatus.java
// Path: src/main/java/com/turn/camino/config/Path.java // public class Path { // // private final String name; // private final String value; // private final List<Metric> metrics; // private final List<Tag> tags; // private final String expectedCreationTime; // // /** // * Constructor // * // * @param name name of path // * @param value value of path // * @param metrics metrics under this path // * @param tags tags of this path as ordered map of tag key/value pairs // * @param expectedCreationTime expression to calculate creation time of this path // */ // @JsonCreator // public Path(@JsonProperty("name") String name, @JsonProperty("value") String value, // @JsonProperty("metrics") @JsonDeserialize(contentAs = Metric.class) List<Metric> metrics, // @JsonProperty("tags") @JsonDeserialize(as = LinkedHashMap.class, keyAs = String.class, // contentAs = String.class) Map<String, String> tags, // @JsonProperty("expectedCreationTime") String expectedCreationTime) { // this(name, value, metrics, tags == null ? null : ConfigUtil.mapToList(tags, // Tag::new), expectedCreationTime); // } // // /** // * Constructor // * // * @param name name of path // * @param value value of path // * @param metrics metrics under this path // * @param tags tags of this path as list of Tag objects // * @param expectedCreationTime expression to calculate creation time of this path // */ // protected Path(String name, String value, List<Metric> metrics, List<Tag> tags, // String expectedCreationTime) { // Preconditions.checkNotNull(name, "Path name cannot be null"); // Preconditions.checkNotNull(value, "Path value cannot be null"); // this.name = name; // this.value = value; // this.metrics = ImmutableList.copyOf(metrics != null ? metrics : // Collections.emptyList()); // this.tags = ImmutableList.copyOf(tags != null ? tags : Collections.emptyList()); // this.expectedCreationTime = expectedCreationTime; // } // // /** // * Constructor // * // * @param name name of path // * @param value value of path // */ // public Path(String name, String value) { // this(name, value, null, (List<Tag>) null, null); // } // // /** // * Gets name of path // * // * @return name of path // */ // @Member("name") // public String getName() { // return name; // } // // /** // * Gets value of path // * // * @return value of path // */ // @Member("value") // public String getValue() { // return value; // } // // /** // * Returns metrics under this path // * // * Note that returned list is immutable // * // * @return immutable list of metrics // */ // @Member("metrics") // public List<Metric> getMetrics() { // return metrics; // } // // /** // * Gets tags of this path // * // * @return immutable list of tags (key and value pairs) // */ // @Member("tags") // public List<Tag> getTags() { return tags; } // // /** // * Gets expected creation time of this path // * // * @return expression to compute expected creation time // */ // @Member("expectedCreationTime") // public String getExpectedCreationTime() { // return expectedCreationTime; // } // } // // Path: src/main/java/com/turn/camino/render/TimeValue.java // public class TimeValue { // // public final static String DATE_FORMAT_STRING = "yyyy/MM/dd HH:mm:ss.SSS z"; // // private final TimeZone timeZone; // private final long time; // private final transient String stringValue; // // /** // * Constructor // * // * @param timeZone time zone // * @param time time in UTC milliseconds // */ // public TimeValue(TimeZone timeZone, long time) { // this.timeZone = timeZone; // this.time = time; // // // compute string representation // DateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT_STRING); // dateFormat.setTimeZone(timeZone); // this.stringValue = dateFormat.format(new Date(time)); // } // // public TimeZone getTimeZone() { // return timeZone; // } // // @Member("timeMillis") // public long getTime() { // return time; // } // // @Member("timeZone") // public String getTimeZoneId() { // return timeZone.getID(); // } // // @Override // public String toString() { // return this.stringValue; // } // }
import com.turn.camino.annotation.Member; import com.turn.camino.config.Path; import com.google.common.collect.ImmutableList; import com.turn.camino.render.TimeValue; import java.util.List;
/* * Copyright (C) 2014-2018, Amobee Inc. All Rights Reserved. * * 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 */ package com.turn.camino; /** * Path status * * Current status of a path * * @author llo */ public class PathStatus { private final String name; private final String value;
// Path: src/main/java/com/turn/camino/config/Path.java // public class Path { // // private final String name; // private final String value; // private final List<Metric> metrics; // private final List<Tag> tags; // private final String expectedCreationTime; // // /** // * Constructor // * // * @param name name of path // * @param value value of path // * @param metrics metrics under this path // * @param tags tags of this path as ordered map of tag key/value pairs // * @param expectedCreationTime expression to calculate creation time of this path // */ // @JsonCreator // public Path(@JsonProperty("name") String name, @JsonProperty("value") String value, // @JsonProperty("metrics") @JsonDeserialize(contentAs = Metric.class) List<Metric> metrics, // @JsonProperty("tags") @JsonDeserialize(as = LinkedHashMap.class, keyAs = String.class, // contentAs = String.class) Map<String, String> tags, // @JsonProperty("expectedCreationTime") String expectedCreationTime) { // this(name, value, metrics, tags == null ? null : ConfigUtil.mapToList(tags, // Tag::new), expectedCreationTime); // } // // /** // * Constructor // * // * @param name name of path // * @param value value of path // * @param metrics metrics under this path // * @param tags tags of this path as list of Tag objects // * @param expectedCreationTime expression to calculate creation time of this path // */ // protected Path(String name, String value, List<Metric> metrics, List<Tag> tags, // String expectedCreationTime) { // Preconditions.checkNotNull(name, "Path name cannot be null"); // Preconditions.checkNotNull(value, "Path value cannot be null"); // this.name = name; // this.value = value; // this.metrics = ImmutableList.copyOf(metrics != null ? metrics : // Collections.emptyList()); // this.tags = ImmutableList.copyOf(tags != null ? tags : Collections.emptyList()); // this.expectedCreationTime = expectedCreationTime; // } // // /** // * Constructor // * // * @param name name of path // * @param value value of path // */ // public Path(String name, String value) { // this(name, value, null, (List<Tag>) null, null); // } // // /** // * Gets name of path // * // * @return name of path // */ // @Member("name") // public String getName() { // return name; // } // // /** // * Gets value of path // * // * @return value of path // */ // @Member("value") // public String getValue() { // return value; // } // // /** // * Returns metrics under this path // * // * Note that returned list is immutable // * // * @return immutable list of metrics // */ // @Member("metrics") // public List<Metric> getMetrics() { // return metrics; // } // // /** // * Gets tags of this path // * // * @return immutable list of tags (key and value pairs) // */ // @Member("tags") // public List<Tag> getTags() { return tags; } // // /** // * Gets expected creation time of this path // * // * @return expression to compute expected creation time // */ // @Member("expectedCreationTime") // public String getExpectedCreationTime() { // return expectedCreationTime; // } // } // // Path: src/main/java/com/turn/camino/render/TimeValue.java // public class TimeValue { // // public final static String DATE_FORMAT_STRING = "yyyy/MM/dd HH:mm:ss.SSS z"; // // private final TimeZone timeZone; // private final long time; // private final transient String stringValue; // // /** // * Constructor // * // * @param timeZone time zone // * @param time time in UTC milliseconds // */ // public TimeValue(TimeZone timeZone, long time) { // this.timeZone = timeZone; // this.time = time; // // // compute string representation // DateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT_STRING); // dateFormat.setTimeZone(timeZone); // this.stringValue = dateFormat.format(new Date(time)); // } // // public TimeZone getTimeZone() { // return timeZone; // } // // @Member("timeMillis") // public long getTime() { // return time; // } // // @Member("timeZone") // public String getTimeZoneId() { // return timeZone.getID(); // } // // @Override // public String toString() { // return this.stringValue; // } // } // Path: src/main/java/com/turn/camino/PathStatus.java import com.turn.camino.annotation.Member; import com.turn.camino.config.Path; import com.google.common.collect.ImmutableList; import com.turn.camino.render.TimeValue; import java.util.List; /* * Copyright (C) 2014-2018, Amobee Inc. All Rights Reserved. * * 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 */ package com.turn.camino; /** * Path status * * Current status of a path * * @author llo */ public class PathStatus { private final String name; private final String value;
private final Path path;
turn/camino
src/main/java/com/turn/camino/PathStatus.java
// Path: src/main/java/com/turn/camino/config/Path.java // public class Path { // // private final String name; // private final String value; // private final List<Metric> metrics; // private final List<Tag> tags; // private final String expectedCreationTime; // // /** // * Constructor // * // * @param name name of path // * @param value value of path // * @param metrics metrics under this path // * @param tags tags of this path as ordered map of tag key/value pairs // * @param expectedCreationTime expression to calculate creation time of this path // */ // @JsonCreator // public Path(@JsonProperty("name") String name, @JsonProperty("value") String value, // @JsonProperty("metrics") @JsonDeserialize(contentAs = Metric.class) List<Metric> metrics, // @JsonProperty("tags") @JsonDeserialize(as = LinkedHashMap.class, keyAs = String.class, // contentAs = String.class) Map<String, String> tags, // @JsonProperty("expectedCreationTime") String expectedCreationTime) { // this(name, value, metrics, tags == null ? null : ConfigUtil.mapToList(tags, // Tag::new), expectedCreationTime); // } // // /** // * Constructor // * // * @param name name of path // * @param value value of path // * @param metrics metrics under this path // * @param tags tags of this path as list of Tag objects // * @param expectedCreationTime expression to calculate creation time of this path // */ // protected Path(String name, String value, List<Metric> metrics, List<Tag> tags, // String expectedCreationTime) { // Preconditions.checkNotNull(name, "Path name cannot be null"); // Preconditions.checkNotNull(value, "Path value cannot be null"); // this.name = name; // this.value = value; // this.metrics = ImmutableList.copyOf(metrics != null ? metrics : // Collections.emptyList()); // this.tags = ImmutableList.copyOf(tags != null ? tags : Collections.emptyList()); // this.expectedCreationTime = expectedCreationTime; // } // // /** // * Constructor // * // * @param name name of path // * @param value value of path // */ // public Path(String name, String value) { // this(name, value, null, (List<Tag>) null, null); // } // // /** // * Gets name of path // * // * @return name of path // */ // @Member("name") // public String getName() { // return name; // } // // /** // * Gets value of path // * // * @return value of path // */ // @Member("value") // public String getValue() { // return value; // } // // /** // * Returns metrics under this path // * // * Note that returned list is immutable // * // * @return immutable list of metrics // */ // @Member("metrics") // public List<Metric> getMetrics() { // return metrics; // } // // /** // * Gets tags of this path // * // * @return immutable list of tags (key and value pairs) // */ // @Member("tags") // public List<Tag> getTags() { return tags; } // // /** // * Gets expected creation time of this path // * // * @return expression to compute expected creation time // */ // @Member("expectedCreationTime") // public String getExpectedCreationTime() { // return expectedCreationTime; // } // } // // Path: src/main/java/com/turn/camino/render/TimeValue.java // public class TimeValue { // // public final static String DATE_FORMAT_STRING = "yyyy/MM/dd HH:mm:ss.SSS z"; // // private final TimeZone timeZone; // private final long time; // private final transient String stringValue; // // /** // * Constructor // * // * @param timeZone time zone // * @param time time in UTC milliseconds // */ // public TimeValue(TimeZone timeZone, long time) { // this.timeZone = timeZone; // this.time = time; // // // compute string representation // DateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT_STRING); // dateFormat.setTimeZone(timeZone); // this.stringValue = dateFormat.format(new Date(time)); // } // // public TimeZone getTimeZone() { // return timeZone; // } // // @Member("timeMillis") // public long getTime() { // return time; // } // // @Member("timeZone") // public String getTimeZoneId() { // return timeZone.getID(); // } // // @Override // public String toString() { // return this.stringValue; // } // }
import com.turn.camino.annotation.Member; import com.turn.camino.config.Path; import com.google.common.collect.ImmutableList; import com.turn.camino.render.TimeValue; import java.util.List;
/* * Copyright (C) 2014-2018, Amobee Inc. All Rights Reserved. * * 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 */ package com.turn.camino; /** * Path status * * Current status of a path * * @author llo */ public class PathStatus { private final String name; private final String value; private final Path path; private final List<PathDetail> pathDetails;
// Path: src/main/java/com/turn/camino/config/Path.java // public class Path { // // private final String name; // private final String value; // private final List<Metric> metrics; // private final List<Tag> tags; // private final String expectedCreationTime; // // /** // * Constructor // * // * @param name name of path // * @param value value of path // * @param metrics metrics under this path // * @param tags tags of this path as ordered map of tag key/value pairs // * @param expectedCreationTime expression to calculate creation time of this path // */ // @JsonCreator // public Path(@JsonProperty("name") String name, @JsonProperty("value") String value, // @JsonProperty("metrics") @JsonDeserialize(contentAs = Metric.class) List<Metric> metrics, // @JsonProperty("tags") @JsonDeserialize(as = LinkedHashMap.class, keyAs = String.class, // contentAs = String.class) Map<String, String> tags, // @JsonProperty("expectedCreationTime") String expectedCreationTime) { // this(name, value, metrics, tags == null ? null : ConfigUtil.mapToList(tags, // Tag::new), expectedCreationTime); // } // // /** // * Constructor // * // * @param name name of path // * @param value value of path // * @param metrics metrics under this path // * @param tags tags of this path as list of Tag objects // * @param expectedCreationTime expression to calculate creation time of this path // */ // protected Path(String name, String value, List<Metric> metrics, List<Tag> tags, // String expectedCreationTime) { // Preconditions.checkNotNull(name, "Path name cannot be null"); // Preconditions.checkNotNull(value, "Path value cannot be null"); // this.name = name; // this.value = value; // this.metrics = ImmutableList.copyOf(metrics != null ? metrics : // Collections.emptyList()); // this.tags = ImmutableList.copyOf(tags != null ? tags : Collections.emptyList()); // this.expectedCreationTime = expectedCreationTime; // } // // /** // * Constructor // * // * @param name name of path // * @param value value of path // */ // public Path(String name, String value) { // this(name, value, null, (List<Tag>) null, null); // } // // /** // * Gets name of path // * // * @return name of path // */ // @Member("name") // public String getName() { // return name; // } // // /** // * Gets value of path // * // * @return value of path // */ // @Member("value") // public String getValue() { // return value; // } // // /** // * Returns metrics under this path // * // * Note that returned list is immutable // * // * @return immutable list of metrics // */ // @Member("metrics") // public List<Metric> getMetrics() { // return metrics; // } // // /** // * Gets tags of this path // * // * @return immutable list of tags (key and value pairs) // */ // @Member("tags") // public List<Tag> getTags() { return tags; } // // /** // * Gets expected creation time of this path // * // * @return expression to compute expected creation time // */ // @Member("expectedCreationTime") // public String getExpectedCreationTime() { // return expectedCreationTime; // } // } // // Path: src/main/java/com/turn/camino/render/TimeValue.java // public class TimeValue { // // public final static String DATE_FORMAT_STRING = "yyyy/MM/dd HH:mm:ss.SSS z"; // // private final TimeZone timeZone; // private final long time; // private final transient String stringValue; // // /** // * Constructor // * // * @param timeZone time zone // * @param time time in UTC milliseconds // */ // public TimeValue(TimeZone timeZone, long time) { // this.timeZone = timeZone; // this.time = time; // // // compute string representation // DateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT_STRING); // dateFormat.setTimeZone(timeZone); // this.stringValue = dateFormat.format(new Date(time)); // } // // public TimeZone getTimeZone() { // return timeZone; // } // // @Member("timeMillis") // public long getTime() { // return time; // } // // @Member("timeZone") // public String getTimeZoneId() { // return timeZone.getID(); // } // // @Override // public String toString() { // return this.stringValue; // } // } // Path: src/main/java/com/turn/camino/PathStatus.java import com.turn.camino.annotation.Member; import com.turn.camino.config.Path; import com.google.common.collect.ImmutableList; import com.turn.camino.render.TimeValue; import java.util.List; /* * Copyright (C) 2014-2018, Amobee Inc. All Rights Reserved. * * 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 */ package com.turn.camino; /** * Path status * * Current status of a path * * @author llo */ public class PathStatus { private final String name; private final String value; private final Path path; private final List<PathDetail> pathDetails;
private final TimeValue expectedCreationTime;
turn/camino
src/test/java/com/turn/camino/MetricIdTest.java
// Path: src/main/java/com/turn/camino/config/Tag.java // public class Tag { // // private final String key; // private final String value; // // /** // * Constructor // * // * @param key key of tag // * @param value value of tag // */ // public Tag(String key, String value) { // Preconditions.checkNotNull(key, "Tag key cannot be null"); // Preconditions.checkNotNull(value, "Tag value cannot be null"); // this.key = key; // this.value = value; // } // // /** // * Gets key of tag // * // * @return key of tag // */ // @Member("key") // public String getKey() { // return key; // } // // /** // * Gets value of tag // * // * @return value of tag // */ // @Member("value") // public String getValue() { // return value; // } // // }
import com.google.common.collect.ImmutableList; import com.turn.camino.config.Tag; import org.testng.annotations.Test; import static org.testng.Assert.assertEquals;
/* * Copyright (C) 2014-2018, Amobee Inc. All Rights Reserved. * * 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 */ package com.turn.camino; /** * Unit test for MetricId * * @author llo */ @Test public class MetricIdTest { @Test public void testMetricId() {
// Path: src/main/java/com/turn/camino/config/Tag.java // public class Tag { // // private final String key; // private final String value; // // /** // * Constructor // * // * @param key key of tag // * @param value value of tag // */ // public Tag(String key, String value) { // Preconditions.checkNotNull(key, "Tag key cannot be null"); // Preconditions.checkNotNull(value, "Tag value cannot be null"); // this.key = key; // this.value = value; // } // // /** // * Gets key of tag // * // * @return key of tag // */ // @Member("key") // public String getKey() { // return key; // } // // /** // * Gets value of tag // * // * @return value of tag // */ // @Member("value") // public String getValue() { // return value; // } // // } // Path: src/test/java/com/turn/camino/MetricIdTest.java import com.google.common.collect.ImmutableList; import com.turn.camino.config.Tag; import org.testng.annotations.Test; import static org.testng.Assert.assertEquals; /* * Copyright (C) 2014-2018, Amobee Inc. All Rights Reserved. * * 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 */ package com.turn.camino; /** * Unit test for MetricId * * @author llo */ @Test public class MetricIdTest { @Test public void testMetricId() {
MetricId metricId = new MetricId("age", "myPath", ImmutableList.of(new Tag("pk", "x")));
turn/camino
src/main/java/com/turn/camino/Env.java
// Path: src/main/java/com/turn/camino/render/Renderer.java // public interface Renderer { // // /** // * Renders an expression // * // * @param expression expression to render // * @param context context // * @return rendered result // * @throws RenderException // */ // Object render(String expression, Context context) throws RenderException; // // }
import com.turn.camino.render.Renderer; import org.apache.hadoop.fs.FileSystem; import java.util.TimeZone; import java.util.concurrent.ExecutorService;
/* * Copyright (C) 2014-2018, Amobee Inc. All Rights Reserved. * * 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 */ package com.turn.camino; /** * System environment * * @author llo */ public interface Env { /** * Get current time * * @return current time in epoch milliseconds */ long getCurrentTime(); /** * Get default time zone * * @return default time zone */ TimeZone getTimeZone(); /** * Get file system * * @return Hadoop file system */ FileSystem getFileSystem(); /** * Creates new context * * @return new global context */ Context newContext(); /** * Get renderer * * @return new renderer */
// Path: src/main/java/com/turn/camino/render/Renderer.java // public interface Renderer { // // /** // * Renders an expression // * // * @param expression expression to render // * @param context context // * @return rendered result // * @throws RenderException // */ // Object render(String expression, Context context) throws RenderException; // // } // Path: src/main/java/com/turn/camino/Env.java import com.turn.camino.render.Renderer; import org.apache.hadoop.fs.FileSystem; import java.util.TimeZone; import java.util.concurrent.ExecutorService; /* * Copyright (C) 2014-2018, Amobee Inc. All Rights Reserved. * * 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 */ package com.turn.camino; /** * System environment * * @author llo */ public interface Env { /** * Get current time * * @return current time in epoch milliseconds */ long getCurrentTime(); /** * Get default time zone * * @return default time zone */ TimeZone getTimeZone(); /** * Get file system * * @return Hadoop file system */ FileSystem getFileSystem(); /** * Creates new context * * @return new global context */ Context newContext(); /** * Get renderer * * @return new renderer */
Renderer getRenderer();
turn/camino
src/test/java/com/turn/camino/EnvImplTest.java
// Path: src/main/java/com/turn/camino/render/Renderer.java // public interface Renderer { // // /** // * Renders an expression // * // * @param expression expression to render // * @param context context // * @return rendered result // * @throws RenderException // */ // Object render(String expression, Context context) throws RenderException; // // }
import com.turn.camino.render.Renderer; import java.util.TimeZone; import java.util.concurrent.ExecutorService; import org.apache.hadoop.fs.FileSystem; import org.testng.annotations.Test; import static org.mockito.Mockito.mock; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue;
/* * Copyright (C) 2014-2018, Amobee Inc. All Rights Reserved. * * 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 */ package com.turn.camino; /** * Unit test for EnvImpl * * @author llo */ @Test public class EnvImplTest { @Test public void testConstructor() { // create env TimeZone timeZone = TimeZone.getTimeZone("GMT"); FileSystem fileSystem = mock(FileSystem.class); ExecutorService executorService = mock(ExecutorService.class); ErrorHandler errorHandler = mock(ErrorHandler.class); EnvImpl env = new EnvImpl(timeZone, fileSystem, executorService, errorHandler); // test for current time long t0 = System.currentTimeMillis(); long currentTime = env.getCurrentTime(); long t1 = System.currentTimeMillis(); assertTrue(currentTime >= t0); assertTrue(currentTime <= t1); // test system services assertEquals(env.getTimeZone(), timeZone); assertEquals(env.getFileSystem(), fileSystem); Context context = env.newContext(); assertNotNull(context);
// Path: src/main/java/com/turn/camino/render/Renderer.java // public interface Renderer { // // /** // * Renders an expression // * // * @param expression expression to render // * @param context context // * @return rendered result // * @throws RenderException // */ // Object render(String expression, Context context) throws RenderException; // // } // Path: src/test/java/com/turn/camino/EnvImplTest.java import com.turn.camino.render.Renderer; import java.util.TimeZone; import java.util.concurrent.ExecutorService; import org.apache.hadoop.fs.FileSystem; import org.testng.annotations.Test; import static org.mockito.Mockito.mock; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; /* * Copyright (C) 2014-2018, Amobee Inc. All Rights Reserved. * * 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 */ package com.turn.camino; /** * Unit test for EnvImpl * * @author llo */ @Test public class EnvImplTest { @Test public void testConstructor() { // create env TimeZone timeZone = TimeZone.getTimeZone("GMT"); FileSystem fileSystem = mock(FileSystem.class); ExecutorService executorService = mock(ExecutorService.class); ErrorHandler errorHandler = mock(ErrorHandler.class); EnvImpl env = new EnvImpl(timeZone, fileSystem, executorService, errorHandler); // test for current time long t0 = System.currentTimeMillis(); long currentTime = env.getCurrentTime(); long t1 = System.currentTimeMillis(); assertTrue(currentTime >= t0); assertTrue(currentTime <= t1); // test system services assertEquals(env.getTimeZone(), timeZone); assertEquals(env.getFileSystem(), fileSystem); Context context = env.newContext(); assertNotNull(context);
Renderer renderer = env.getRenderer();
turn/camino
src/test/java/com/turn/camino/CaminoIntegrationTest.java
// Path: src/main/java/com/turn/camino/render/RenderException.java // public class RenderException extends Exception { // // /** // * Constructor // * // * @param message error message // */ // public RenderException(String message) { // super(message); // } // // /** // * Constructor // * // * @param message error message // * @param throwable underlying exception // */ // public RenderException(String message, Throwable throwable) { // super(message, throwable); // } // // /** // * Constructor // * // * @param throwable underlying exception // */ // public RenderException(Throwable throwable) { // super(throwable); // } // }
import org.testng.annotations.Test; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; import com.google.common.collect.ImmutableMap; import com.google.common.io.Files; import com.turn.camino.config.*; import com.turn.camino.render.RenderException; import java.io.*; import java.net.URL; import java.util.List; import java.util.TimeZone; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import com.google.common.collect.ImmutableList; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.testng.annotations.BeforeClass;
/* * Copyright (C) 2014-2018, Amobee Inc. All Rights Reserved. * * 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 */ package com.turn.camino; /** * Integration test for Camino * * Uses its own source code for test * * @author llo */ @Test public class CaminoIntegrationTest { private final static double EPSILON = 1e-6; private final static String CAMINO_CONFIG_TEMPLATE = "{\n" + " \"properties\": {" + " \"pkv\": \"readme.1\"\n" + " },\n" + " \"paths\": [\n" + " {\n" + " \"name\": \"readme\",\n" + " \"tags\": {\"pk\": \"<%%=pkv%%>\"},\n" + " \"value\": \"%s\"\n" + " }\n" + " ]\n" + "}"; private File root; private File readme; @BeforeClass public void setUp() { URL url = CaminoIntegrationTest.class.getProtectionDomain().getCodeSource().getLocation(); this.root = new File(url.getPath()).getParentFile().getParentFile(); this.readme = new File(root, "README.md"); } /** * Test camino * * @throws IOException * @throws WrongTypeException * @throws RenderException */ @Test
// Path: src/main/java/com/turn/camino/render/RenderException.java // public class RenderException extends Exception { // // /** // * Constructor // * // * @param message error message // */ // public RenderException(String message) { // super(message); // } // // /** // * Constructor // * // * @param message error message // * @param throwable underlying exception // */ // public RenderException(String message, Throwable throwable) { // super(message, throwable); // } // // /** // * Constructor // * // * @param throwable underlying exception // */ // public RenderException(Throwable throwable) { // super(throwable); // } // } // Path: src/test/java/com/turn/camino/CaminoIntegrationTest.java import org.testng.annotations.Test; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; import com.google.common.collect.ImmutableMap; import com.google.common.io.Files; import com.turn.camino.config.*; import com.turn.camino.render.RenderException; import java.io.*; import java.net.URL; import java.util.List; import java.util.TimeZone; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import com.google.common.collect.ImmutableList; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.testng.annotations.BeforeClass; /* * Copyright (C) 2014-2018, Amobee Inc. All Rights Reserved. * * 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 */ package com.turn.camino; /** * Integration test for Camino * * Uses its own source code for test * * @author llo */ @Test public class CaminoIntegrationTest { private final static double EPSILON = 1e-6; private final static String CAMINO_CONFIG_TEMPLATE = "{\n" + " \"properties\": {" + " \"pkv\": \"readme.1\"\n" + " },\n" + " \"paths\": [\n" + " {\n" + " \"name\": \"readme\",\n" + " \"tags\": {\"pk\": \"<%%=pkv%%>\"},\n" + " \"value\": \"%s\"\n" + " }\n" + " ]\n" + "}"; private File root; private File readme; @BeforeClass public void setUp() { URL url = CaminoIntegrationTest.class.getProtectionDomain().getCodeSource().getLocation(); this.root = new File(url.getPath()).getParentFile().getParentFile(); this.readme = new File(root, "README.md"); } /** * Test camino * * @throws IOException * @throws WrongTypeException * @throws RenderException */ @Test
public void testCamino() throws IOException, WrongTypeException, RenderException,
turn/camino
src/test/java/com/turn/camino/PathStatusTest.java
// Path: src/main/java/com/turn/camino/config/Path.java // public class Path { // // private final String name; // private final String value; // private final List<Metric> metrics; // private final List<Tag> tags; // private final String expectedCreationTime; // // /** // * Constructor // * // * @param name name of path // * @param value value of path // * @param metrics metrics under this path // * @param tags tags of this path as ordered map of tag key/value pairs // * @param expectedCreationTime expression to calculate creation time of this path // */ // @JsonCreator // public Path(@JsonProperty("name") String name, @JsonProperty("value") String value, // @JsonProperty("metrics") @JsonDeserialize(contentAs = Metric.class) List<Metric> metrics, // @JsonProperty("tags") @JsonDeserialize(as = LinkedHashMap.class, keyAs = String.class, // contentAs = String.class) Map<String, String> tags, // @JsonProperty("expectedCreationTime") String expectedCreationTime) { // this(name, value, metrics, tags == null ? null : ConfigUtil.mapToList(tags, // Tag::new), expectedCreationTime); // } // // /** // * Constructor // * // * @param name name of path // * @param value value of path // * @param metrics metrics under this path // * @param tags tags of this path as list of Tag objects // * @param expectedCreationTime expression to calculate creation time of this path // */ // protected Path(String name, String value, List<Metric> metrics, List<Tag> tags, // String expectedCreationTime) { // Preconditions.checkNotNull(name, "Path name cannot be null"); // Preconditions.checkNotNull(value, "Path value cannot be null"); // this.name = name; // this.value = value; // this.metrics = ImmutableList.copyOf(metrics != null ? metrics : // Collections.emptyList()); // this.tags = ImmutableList.copyOf(tags != null ? tags : Collections.emptyList()); // this.expectedCreationTime = expectedCreationTime; // } // // /** // * Constructor // * // * @param name name of path // * @param value value of path // */ // public Path(String name, String value) { // this(name, value, null, (List<Tag>) null, null); // } // // /** // * Gets name of path // * // * @return name of path // */ // @Member("name") // public String getName() { // return name; // } // // /** // * Gets value of path // * // * @return value of path // */ // @Member("value") // public String getValue() { // return value; // } // // /** // * Returns metrics under this path // * // * Note that returned list is immutable // * // * @return immutable list of metrics // */ // @Member("metrics") // public List<Metric> getMetrics() { // return metrics; // } // // /** // * Gets tags of this path // * // * @return immutable list of tags (key and value pairs) // */ // @Member("tags") // public List<Tag> getTags() { return tags; } // // /** // * Gets expected creation time of this path // * // * @return expression to compute expected creation time // */ // @Member("expectedCreationTime") // public String getExpectedCreationTime() { // return expectedCreationTime; // } // }
import com.turn.camino.config.Path; import java.util.List; import com.google.common.collect.Lists; import org.testng.annotations.Test; import static org.mockito.Mockito.*; import static org.testng.Assert.*;
/* * Copyright (C) 2014-2018, Amobee Inc. All Rights Reserved. * * 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 */ package com.turn.camino; /** * Unit test for PathStatus * * @author llo */ @Test public class PathStatusTest { @Test public void testConstructor() {
// Path: src/main/java/com/turn/camino/config/Path.java // public class Path { // // private final String name; // private final String value; // private final List<Metric> metrics; // private final List<Tag> tags; // private final String expectedCreationTime; // // /** // * Constructor // * // * @param name name of path // * @param value value of path // * @param metrics metrics under this path // * @param tags tags of this path as ordered map of tag key/value pairs // * @param expectedCreationTime expression to calculate creation time of this path // */ // @JsonCreator // public Path(@JsonProperty("name") String name, @JsonProperty("value") String value, // @JsonProperty("metrics") @JsonDeserialize(contentAs = Metric.class) List<Metric> metrics, // @JsonProperty("tags") @JsonDeserialize(as = LinkedHashMap.class, keyAs = String.class, // contentAs = String.class) Map<String, String> tags, // @JsonProperty("expectedCreationTime") String expectedCreationTime) { // this(name, value, metrics, tags == null ? null : ConfigUtil.mapToList(tags, // Tag::new), expectedCreationTime); // } // // /** // * Constructor // * // * @param name name of path // * @param value value of path // * @param metrics metrics under this path // * @param tags tags of this path as list of Tag objects // * @param expectedCreationTime expression to calculate creation time of this path // */ // protected Path(String name, String value, List<Metric> metrics, List<Tag> tags, // String expectedCreationTime) { // Preconditions.checkNotNull(name, "Path name cannot be null"); // Preconditions.checkNotNull(value, "Path value cannot be null"); // this.name = name; // this.value = value; // this.metrics = ImmutableList.copyOf(metrics != null ? metrics : // Collections.emptyList()); // this.tags = ImmutableList.copyOf(tags != null ? tags : Collections.emptyList()); // this.expectedCreationTime = expectedCreationTime; // } // // /** // * Constructor // * // * @param name name of path // * @param value value of path // */ // public Path(String name, String value) { // this(name, value, null, (List<Tag>) null, null); // } // // /** // * Gets name of path // * // * @return name of path // */ // @Member("name") // public String getName() { // return name; // } // // /** // * Gets value of path // * // * @return value of path // */ // @Member("value") // public String getValue() { // return value; // } // // /** // * Returns metrics under this path // * // * Note that returned list is immutable // * // * @return immutable list of metrics // */ // @Member("metrics") // public List<Metric> getMetrics() { // return metrics; // } // // /** // * Gets tags of this path // * // * @return immutable list of tags (key and value pairs) // */ // @Member("tags") // public List<Tag> getTags() { return tags; } // // /** // * Gets expected creation time of this path // * // * @return expression to compute expected creation time // */ // @Member("expectedCreationTime") // public String getExpectedCreationTime() { // return expectedCreationTime; // } // } // Path: src/test/java/com/turn/camino/PathStatusTest.java import com.turn.camino.config.Path; import java.util.List; import com.google.common.collect.Lists; import org.testng.annotations.Test; import static org.mockito.Mockito.*; import static org.testng.Assert.*; /* * Copyright (C) 2014-2018, Amobee Inc. All Rights Reserved. * * 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 */ package com.turn.camino; /** * Unit test for PathStatus * * @author llo */ @Test public class PathStatusTest { @Test public void testConstructor() {
Path path = mock(Path.class);
turn/camino
src/test/java/com/turn/camino/render/functions/StringFunctionsTest.java
// Path: src/main/java/com/turn/camino/Context.java // public interface Context { // // /** // * Get system environment // * // * @return system environment // */ // Env getEnv(); // // /** // * Creates child context // * // * @return new context // */ // Context createChild(); // // /** // * Gets parent context // * // * Returns a parent context, or null if current context is global // * // * @return parent context // */ // Context getParent(); // // /** // * Gets global context // * // * Returns the global (ancestral) context // * // * @return global context // */ // Context getGlobal(); // // /** // * Puts name and value of property into the current context // * // * @param name name of property // * @param value value of property // */ // void setProperty(String name, Object value); // // /** // * Gets a value of a property given a name // * // * Note that if name is not found in the current context, the expected behavior is to // * recursively search in paren context. Null is returned only if name is not found in // * any context. // * // * @param name name of property // * @return value of property // */ // Object getProperty(String name); // // /** // * Gets a value of a property given a name // * // * Note that if name is not found in the current context, the expected behavior is to // * recursively search in paren context. Null is returned only if name is not found in // * any context. // * // * @param name name of value // * @param type type of value // * @return value // * @throws WrongTypeException // */ // <T> T getProperty(String name, Class<T> type) throws WrongTypeException; // // /** // * Gets time the global instance was created // * // * The time supplied by Env.getCurrentTime() will become the value of global instance time // * when the global context is created from Env. All child contexts under this global context // * will inherit the same global instance time. // * // * @return UTC time in milliseconds // */ // long getGlobalInstanceTime(); // // } // // Path: src/main/java/com/turn/camino/Env.java // public interface Env { // // /** // * Get current time // * // * @return current time in epoch milliseconds // */ // long getCurrentTime(); // // /** // * Get default time zone // * // * @return default time zone // */ // TimeZone getTimeZone(); // // /** // * Get file system // * // * @return Hadoop file system // */ // FileSystem getFileSystem(); // // /** // * Creates new context // * // * @return new global context // */ // Context newContext(); // // /** // * Get renderer // * // * @return new renderer // */ // Renderer getRenderer(); // // /** // * Get executor service // * // * @return executor service // */ // ExecutorService getExecutorService(); // // /** // * Get error handler // * // * @return error handler // */ // ErrorHandler getErrorHandler(); // // } // // Path: src/main/java/com/turn/camino/render/Function.java // public interface Function { // // /** // * Invokes function with given parameters and context // * // * @param params actual parameters to function call // * @param context context in which the function operates // * @return return value of function // * @throws FunctionCallException // */ // Object invoke(List<?> params, Context context) throws FunctionCallException; // // } // // Path: src/main/java/com/turn/camino/render/FunctionCallException.java // public class FunctionCallException extends RenderException { // // public FunctionCallException(String message) { // super(message); // } // // public FunctionCallException(Throwable throwable) { // super(throwable); // } // // }
import static org.testng.Assert.assertTrue; import com.turn.camino.Context; import com.turn.camino.Env; import com.turn.camino.render.Function; import com.turn.camino.render.FunctionCallException; import com.google.common.collect.ImmutableList; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import java.util.List; import java.util.TimeZone; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse;
/* * Copyright (C) 2014-2018, Amobee Inc. All Rights Reserved. * * 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 */ package com.turn.camino.render.functions; /** * Tests for string functions * * @author llo */ @Test public class StringFunctionsTest {
// Path: src/main/java/com/turn/camino/Context.java // public interface Context { // // /** // * Get system environment // * // * @return system environment // */ // Env getEnv(); // // /** // * Creates child context // * // * @return new context // */ // Context createChild(); // // /** // * Gets parent context // * // * Returns a parent context, or null if current context is global // * // * @return parent context // */ // Context getParent(); // // /** // * Gets global context // * // * Returns the global (ancestral) context // * // * @return global context // */ // Context getGlobal(); // // /** // * Puts name and value of property into the current context // * // * @param name name of property // * @param value value of property // */ // void setProperty(String name, Object value); // // /** // * Gets a value of a property given a name // * // * Note that if name is not found in the current context, the expected behavior is to // * recursively search in paren context. Null is returned only if name is not found in // * any context. // * // * @param name name of property // * @return value of property // */ // Object getProperty(String name); // // /** // * Gets a value of a property given a name // * // * Note that if name is not found in the current context, the expected behavior is to // * recursively search in paren context. Null is returned only if name is not found in // * any context. // * // * @param name name of value // * @param type type of value // * @return value // * @throws WrongTypeException // */ // <T> T getProperty(String name, Class<T> type) throws WrongTypeException; // // /** // * Gets time the global instance was created // * // * The time supplied by Env.getCurrentTime() will become the value of global instance time // * when the global context is created from Env. All child contexts under this global context // * will inherit the same global instance time. // * // * @return UTC time in milliseconds // */ // long getGlobalInstanceTime(); // // } // // Path: src/main/java/com/turn/camino/Env.java // public interface Env { // // /** // * Get current time // * // * @return current time in epoch milliseconds // */ // long getCurrentTime(); // // /** // * Get default time zone // * // * @return default time zone // */ // TimeZone getTimeZone(); // // /** // * Get file system // * // * @return Hadoop file system // */ // FileSystem getFileSystem(); // // /** // * Creates new context // * // * @return new global context // */ // Context newContext(); // // /** // * Get renderer // * // * @return new renderer // */ // Renderer getRenderer(); // // /** // * Get executor service // * // * @return executor service // */ // ExecutorService getExecutorService(); // // /** // * Get error handler // * // * @return error handler // */ // ErrorHandler getErrorHandler(); // // } // // Path: src/main/java/com/turn/camino/render/Function.java // public interface Function { // // /** // * Invokes function with given parameters and context // * // * @param params actual parameters to function call // * @param context context in which the function operates // * @return return value of function // * @throws FunctionCallException // */ // Object invoke(List<?> params, Context context) throws FunctionCallException; // // } // // Path: src/main/java/com/turn/camino/render/FunctionCallException.java // public class FunctionCallException extends RenderException { // // public FunctionCallException(String message) { // super(message); // } // // public FunctionCallException(Throwable throwable) { // super(throwable); // } // // } // Path: src/test/java/com/turn/camino/render/functions/StringFunctionsTest.java import static org.testng.Assert.assertTrue; import com.turn.camino.Context; import com.turn.camino.Env; import com.turn.camino.render.Function; import com.turn.camino.render.FunctionCallException; import com.google.common.collect.ImmutableList; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import java.util.List; import java.util.TimeZone; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; /* * Copyright (C) 2014-2018, Amobee Inc. All Rights Reserved. * * 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 */ package com.turn.camino.render.functions; /** * Tests for string functions * * @author llo */ @Test public class StringFunctionsTest {
private Context context;
turn/camino
src/test/java/com/turn/camino/render/functions/StringFunctionsTest.java
// Path: src/main/java/com/turn/camino/Context.java // public interface Context { // // /** // * Get system environment // * // * @return system environment // */ // Env getEnv(); // // /** // * Creates child context // * // * @return new context // */ // Context createChild(); // // /** // * Gets parent context // * // * Returns a parent context, or null if current context is global // * // * @return parent context // */ // Context getParent(); // // /** // * Gets global context // * // * Returns the global (ancestral) context // * // * @return global context // */ // Context getGlobal(); // // /** // * Puts name and value of property into the current context // * // * @param name name of property // * @param value value of property // */ // void setProperty(String name, Object value); // // /** // * Gets a value of a property given a name // * // * Note that if name is not found in the current context, the expected behavior is to // * recursively search in paren context. Null is returned only if name is not found in // * any context. // * // * @param name name of property // * @return value of property // */ // Object getProperty(String name); // // /** // * Gets a value of a property given a name // * // * Note that if name is not found in the current context, the expected behavior is to // * recursively search in paren context. Null is returned only if name is not found in // * any context. // * // * @param name name of value // * @param type type of value // * @return value // * @throws WrongTypeException // */ // <T> T getProperty(String name, Class<T> type) throws WrongTypeException; // // /** // * Gets time the global instance was created // * // * The time supplied by Env.getCurrentTime() will become the value of global instance time // * when the global context is created from Env. All child contexts under this global context // * will inherit the same global instance time. // * // * @return UTC time in milliseconds // */ // long getGlobalInstanceTime(); // // } // // Path: src/main/java/com/turn/camino/Env.java // public interface Env { // // /** // * Get current time // * // * @return current time in epoch milliseconds // */ // long getCurrentTime(); // // /** // * Get default time zone // * // * @return default time zone // */ // TimeZone getTimeZone(); // // /** // * Get file system // * // * @return Hadoop file system // */ // FileSystem getFileSystem(); // // /** // * Creates new context // * // * @return new global context // */ // Context newContext(); // // /** // * Get renderer // * // * @return new renderer // */ // Renderer getRenderer(); // // /** // * Get executor service // * // * @return executor service // */ // ExecutorService getExecutorService(); // // /** // * Get error handler // * // * @return error handler // */ // ErrorHandler getErrorHandler(); // // } // // Path: src/main/java/com/turn/camino/render/Function.java // public interface Function { // // /** // * Invokes function with given parameters and context // * // * @param params actual parameters to function call // * @param context context in which the function operates // * @return return value of function // * @throws FunctionCallException // */ // Object invoke(List<?> params, Context context) throws FunctionCallException; // // } // // Path: src/main/java/com/turn/camino/render/FunctionCallException.java // public class FunctionCallException extends RenderException { // // public FunctionCallException(String message) { // super(message); // } // // public FunctionCallException(Throwable throwable) { // super(throwable); // } // // }
import static org.testng.Assert.assertTrue; import com.turn.camino.Context; import com.turn.camino.Env; import com.turn.camino.render.Function; import com.turn.camino.render.FunctionCallException; import com.google.common.collect.ImmutableList; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import java.util.List; import java.util.TimeZone; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse;
/* * Copyright (C) 2014-2018, Amobee Inc. All Rights Reserved. * * 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 */ package com.turn.camino.render.functions; /** * Tests for string functions * * @author llo */ @Test public class StringFunctionsTest { private Context context; private StringFunctions.Match match = new StringFunctions.Match(); private StringFunctions.Matcher matcher = new StringFunctions.Matcher(); private StringFunctions.Replace replace = new StringFunctions.Replace(); private StringFunctions.ReplaceRegex replaceRegex = new StringFunctions.ReplaceRegex(); private StringFunctions.Split split = new StringFunctions.Split(); private StringFunctions.Join join = new StringFunctions.Join(); private StringFunctions.Concat concat = new StringFunctions.Concat(); /** * Set up environment */ @BeforeClass public void setUp() { // mock environment context = mock(Context.class);
// Path: src/main/java/com/turn/camino/Context.java // public interface Context { // // /** // * Get system environment // * // * @return system environment // */ // Env getEnv(); // // /** // * Creates child context // * // * @return new context // */ // Context createChild(); // // /** // * Gets parent context // * // * Returns a parent context, or null if current context is global // * // * @return parent context // */ // Context getParent(); // // /** // * Gets global context // * // * Returns the global (ancestral) context // * // * @return global context // */ // Context getGlobal(); // // /** // * Puts name and value of property into the current context // * // * @param name name of property // * @param value value of property // */ // void setProperty(String name, Object value); // // /** // * Gets a value of a property given a name // * // * Note that if name is not found in the current context, the expected behavior is to // * recursively search in paren context. Null is returned only if name is not found in // * any context. // * // * @param name name of property // * @return value of property // */ // Object getProperty(String name); // // /** // * Gets a value of a property given a name // * // * Note that if name is not found in the current context, the expected behavior is to // * recursively search in paren context. Null is returned only if name is not found in // * any context. // * // * @param name name of value // * @param type type of value // * @return value // * @throws WrongTypeException // */ // <T> T getProperty(String name, Class<T> type) throws WrongTypeException; // // /** // * Gets time the global instance was created // * // * The time supplied by Env.getCurrentTime() will become the value of global instance time // * when the global context is created from Env. All child contexts under this global context // * will inherit the same global instance time. // * // * @return UTC time in milliseconds // */ // long getGlobalInstanceTime(); // // } // // Path: src/main/java/com/turn/camino/Env.java // public interface Env { // // /** // * Get current time // * // * @return current time in epoch milliseconds // */ // long getCurrentTime(); // // /** // * Get default time zone // * // * @return default time zone // */ // TimeZone getTimeZone(); // // /** // * Get file system // * // * @return Hadoop file system // */ // FileSystem getFileSystem(); // // /** // * Creates new context // * // * @return new global context // */ // Context newContext(); // // /** // * Get renderer // * // * @return new renderer // */ // Renderer getRenderer(); // // /** // * Get executor service // * // * @return executor service // */ // ExecutorService getExecutorService(); // // /** // * Get error handler // * // * @return error handler // */ // ErrorHandler getErrorHandler(); // // } // // Path: src/main/java/com/turn/camino/render/Function.java // public interface Function { // // /** // * Invokes function with given parameters and context // * // * @param params actual parameters to function call // * @param context context in which the function operates // * @return return value of function // * @throws FunctionCallException // */ // Object invoke(List<?> params, Context context) throws FunctionCallException; // // } // // Path: src/main/java/com/turn/camino/render/FunctionCallException.java // public class FunctionCallException extends RenderException { // // public FunctionCallException(String message) { // super(message); // } // // public FunctionCallException(Throwable throwable) { // super(throwable); // } // // } // Path: src/test/java/com/turn/camino/render/functions/StringFunctionsTest.java import static org.testng.Assert.assertTrue; import com.turn.camino.Context; import com.turn.camino.Env; import com.turn.camino.render.Function; import com.turn.camino.render.FunctionCallException; import com.google.common.collect.ImmutableList; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import java.util.List; import java.util.TimeZone; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; /* * Copyright (C) 2014-2018, Amobee Inc. All Rights Reserved. * * 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 */ package com.turn.camino.render.functions; /** * Tests for string functions * * @author llo */ @Test public class StringFunctionsTest { private Context context; private StringFunctions.Match match = new StringFunctions.Match(); private StringFunctions.Matcher matcher = new StringFunctions.Matcher(); private StringFunctions.Replace replace = new StringFunctions.Replace(); private StringFunctions.ReplaceRegex replaceRegex = new StringFunctions.ReplaceRegex(); private StringFunctions.Split split = new StringFunctions.Split(); private StringFunctions.Join join = new StringFunctions.Join(); private StringFunctions.Concat concat = new StringFunctions.Concat(); /** * Set up environment */ @BeforeClass public void setUp() { // mock environment context = mock(Context.class);
Env env = mock(Env.class);
turn/camino
src/test/java/com/turn/camino/render/functions/StringFunctionsTest.java
// Path: src/main/java/com/turn/camino/Context.java // public interface Context { // // /** // * Get system environment // * // * @return system environment // */ // Env getEnv(); // // /** // * Creates child context // * // * @return new context // */ // Context createChild(); // // /** // * Gets parent context // * // * Returns a parent context, or null if current context is global // * // * @return parent context // */ // Context getParent(); // // /** // * Gets global context // * // * Returns the global (ancestral) context // * // * @return global context // */ // Context getGlobal(); // // /** // * Puts name and value of property into the current context // * // * @param name name of property // * @param value value of property // */ // void setProperty(String name, Object value); // // /** // * Gets a value of a property given a name // * // * Note that if name is not found in the current context, the expected behavior is to // * recursively search in paren context. Null is returned only if name is not found in // * any context. // * // * @param name name of property // * @return value of property // */ // Object getProperty(String name); // // /** // * Gets a value of a property given a name // * // * Note that if name is not found in the current context, the expected behavior is to // * recursively search in paren context. Null is returned only if name is not found in // * any context. // * // * @param name name of value // * @param type type of value // * @return value // * @throws WrongTypeException // */ // <T> T getProperty(String name, Class<T> type) throws WrongTypeException; // // /** // * Gets time the global instance was created // * // * The time supplied by Env.getCurrentTime() will become the value of global instance time // * when the global context is created from Env. All child contexts under this global context // * will inherit the same global instance time. // * // * @return UTC time in milliseconds // */ // long getGlobalInstanceTime(); // // } // // Path: src/main/java/com/turn/camino/Env.java // public interface Env { // // /** // * Get current time // * // * @return current time in epoch milliseconds // */ // long getCurrentTime(); // // /** // * Get default time zone // * // * @return default time zone // */ // TimeZone getTimeZone(); // // /** // * Get file system // * // * @return Hadoop file system // */ // FileSystem getFileSystem(); // // /** // * Creates new context // * // * @return new global context // */ // Context newContext(); // // /** // * Get renderer // * // * @return new renderer // */ // Renderer getRenderer(); // // /** // * Get executor service // * // * @return executor service // */ // ExecutorService getExecutorService(); // // /** // * Get error handler // * // * @return error handler // */ // ErrorHandler getErrorHandler(); // // } // // Path: src/main/java/com/turn/camino/render/Function.java // public interface Function { // // /** // * Invokes function with given parameters and context // * // * @param params actual parameters to function call // * @param context context in which the function operates // * @return return value of function // * @throws FunctionCallException // */ // Object invoke(List<?> params, Context context) throws FunctionCallException; // // } // // Path: src/main/java/com/turn/camino/render/FunctionCallException.java // public class FunctionCallException extends RenderException { // // public FunctionCallException(String message) { // super(message); // } // // public FunctionCallException(Throwable throwable) { // super(throwable); // } // // }
import static org.testng.Assert.assertTrue; import com.turn.camino.Context; import com.turn.camino.Env; import com.turn.camino.render.Function; import com.turn.camino.render.FunctionCallException; import com.google.common.collect.ImmutableList; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import java.util.List; import java.util.TimeZone; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse;
private StringFunctions.Join join = new StringFunctions.Join(); private StringFunctions.Concat concat = new StringFunctions.Concat(); /** * Set up environment */ @BeforeClass public void setUp() { // mock environment context = mock(Context.class); Env env = mock(Env.class); when(context.getEnv()).thenReturn(env); when(env.getCurrentTime()).thenReturn(1409389256296L); when(env.getTimeZone()).thenReturn(TimeZone.getTimeZone("GMT")); } @Test public void testMatch() throws FunctionCallException { Object result = match.invoke(ImmutableList.of("hello person!", ".*erso.*"), context); assertEquals(result.getClass(), Boolean.class); assertTrue((Boolean) result); result = match.invoke(ImmutableList.of("hello person!", "dude"), context); assertFalse((Boolean) result); } @Test public void testMatcher() throws FunctionCallException { Object result = matcher.invoke(ImmutableList.of(".*erso.*"), context);
// Path: src/main/java/com/turn/camino/Context.java // public interface Context { // // /** // * Get system environment // * // * @return system environment // */ // Env getEnv(); // // /** // * Creates child context // * // * @return new context // */ // Context createChild(); // // /** // * Gets parent context // * // * Returns a parent context, or null if current context is global // * // * @return parent context // */ // Context getParent(); // // /** // * Gets global context // * // * Returns the global (ancestral) context // * // * @return global context // */ // Context getGlobal(); // // /** // * Puts name and value of property into the current context // * // * @param name name of property // * @param value value of property // */ // void setProperty(String name, Object value); // // /** // * Gets a value of a property given a name // * // * Note that if name is not found in the current context, the expected behavior is to // * recursively search in paren context. Null is returned only if name is not found in // * any context. // * // * @param name name of property // * @return value of property // */ // Object getProperty(String name); // // /** // * Gets a value of a property given a name // * // * Note that if name is not found in the current context, the expected behavior is to // * recursively search in paren context. Null is returned only if name is not found in // * any context. // * // * @param name name of value // * @param type type of value // * @return value // * @throws WrongTypeException // */ // <T> T getProperty(String name, Class<T> type) throws WrongTypeException; // // /** // * Gets time the global instance was created // * // * The time supplied by Env.getCurrentTime() will become the value of global instance time // * when the global context is created from Env. All child contexts under this global context // * will inherit the same global instance time. // * // * @return UTC time in milliseconds // */ // long getGlobalInstanceTime(); // // } // // Path: src/main/java/com/turn/camino/Env.java // public interface Env { // // /** // * Get current time // * // * @return current time in epoch milliseconds // */ // long getCurrentTime(); // // /** // * Get default time zone // * // * @return default time zone // */ // TimeZone getTimeZone(); // // /** // * Get file system // * // * @return Hadoop file system // */ // FileSystem getFileSystem(); // // /** // * Creates new context // * // * @return new global context // */ // Context newContext(); // // /** // * Get renderer // * // * @return new renderer // */ // Renderer getRenderer(); // // /** // * Get executor service // * // * @return executor service // */ // ExecutorService getExecutorService(); // // /** // * Get error handler // * // * @return error handler // */ // ErrorHandler getErrorHandler(); // // } // // Path: src/main/java/com/turn/camino/render/Function.java // public interface Function { // // /** // * Invokes function with given parameters and context // * // * @param params actual parameters to function call // * @param context context in which the function operates // * @return return value of function // * @throws FunctionCallException // */ // Object invoke(List<?> params, Context context) throws FunctionCallException; // // } // // Path: src/main/java/com/turn/camino/render/FunctionCallException.java // public class FunctionCallException extends RenderException { // // public FunctionCallException(String message) { // super(message); // } // // public FunctionCallException(Throwable throwable) { // super(throwable); // } // // } // Path: src/test/java/com/turn/camino/render/functions/StringFunctionsTest.java import static org.testng.Assert.assertTrue; import com.turn.camino.Context; import com.turn.camino.Env; import com.turn.camino.render.Function; import com.turn.camino.render.FunctionCallException; import com.google.common.collect.ImmutableList; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import java.util.List; import java.util.TimeZone; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; private StringFunctions.Join join = new StringFunctions.Join(); private StringFunctions.Concat concat = new StringFunctions.Concat(); /** * Set up environment */ @BeforeClass public void setUp() { // mock environment context = mock(Context.class); Env env = mock(Env.class); when(context.getEnv()).thenReturn(env); when(env.getCurrentTime()).thenReturn(1409389256296L); when(env.getTimeZone()).thenReturn(TimeZone.getTimeZone("GMT")); } @Test public void testMatch() throws FunctionCallException { Object result = match.invoke(ImmutableList.of("hello person!", ".*erso.*"), context); assertEquals(result.getClass(), Boolean.class); assertTrue((Boolean) result); result = match.invoke(ImmutableList.of("hello person!", "dude"), context); assertFalse((Boolean) result); } @Test public void testMatcher() throws FunctionCallException { Object result = matcher.invoke(ImmutableList.of(".*erso.*"), context);
assertTrue(result instanceof Function);
turn/camino
src/main/java/com/turn/camino/render/functions/FunctionEnum.java
// Path: src/main/java/com/turn/camino/render/Function.java // public interface Function { // // /** // * Invokes function with given parameters and context // * // * @param params actual parameters to function call // * @param context context in which the function operates // * @return return value of function // * @throws FunctionCallException // */ // Object invoke(List<?> params, Context context) throws FunctionCallException; // // }
import com.google.common.collect.Maps; import com.turn.camino.render.Function; import java.util.Map;
YESTERDAY("yesterday", new TimeFunctions.Yesterday()), TIME_ADD("timeAdd", new TimeFunctions.TimeAdd()), TIME_FORMAT("timeFormat", new TimeFunctions.TimeFormat()), TIME_PARSE("timeParse", new TimeFunctions.TimeParse()), TIME_TO_UNIX_DAY("timeToUnixDay", new TimeFunctions.TimeToUnixDay()), UNIX_DAY_TO_TIME("unixDayToTime", new TimeFunctions.UnixDayToTime()), // collection functions LIST("list", new CollectionFunctions.ListCreate()), LIST_GET("listGet", new CollectionFunctions.ListGet()), LIST_FIRST("listFirst", new CollectionFunctions.ListFirst()), LIST_LAST("listLast", new CollectionFunctions.ListLast()), DICT("dict", new CollectionFunctions.DictCreate()), DICT_GET("dictGet", new CollectionFunctions.DictGet()), SORT("sort", new CollectionFunctions.Sort()), // file system functions DIR_LIST("dirList", new FileSystemFunctions.DirList()), DIR_LIST_NAME("dirListName", new FileSystemFunctions.DirListName()), EXISTS("exists", new FileSystemFunctions.Exists()), IS_DIR("isDir", new FileSystemFunctions.IsDir()), // metric functions METRIC_AGG("metricAgg", new MetricFunctions.MetricAggregateFunction()), AGE("age", new MetricFunctions.Age()), COUNT("count", new MetricFunctions.Count()), SIZE("size", new MetricFunctions.Size()), CREATION_DELAY("creationDelay", new MetricFunctions.CreationDelay()); private final String name;
// Path: src/main/java/com/turn/camino/render/Function.java // public interface Function { // // /** // * Invokes function with given parameters and context // * // * @param params actual parameters to function call // * @param context context in which the function operates // * @return return value of function // * @throws FunctionCallException // */ // Object invoke(List<?> params, Context context) throws FunctionCallException; // // } // Path: src/main/java/com/turn/camino/render/functions/FunctionEnum.java import com.google.common.collect.Maps; import com.turn.camino.render.Function; import java.util.Map; YESTERDAY("yesterday", new TimeFunctions.Yesterday()), TIME_ADD("timeAdd", new TimeFunctions.TimeAdd()), TIME_FORMAT("timeFormat", new TimeFunctions.TimeFormat()), TIME_PARSE("timeParse", new TimeFunctions.TimeParse()), TIME_TO_UNIX_DAY("timeToUnixDay", new TimeFunctions.TimeToUnixDay()), UNIX_DAY_TO_TIME("unixDayToTime", new TimeFunctions.UnixDayToTime()), // collection functions LIST("list", new CollectionFunctions.ListCreate()), LIST_GET("listGet", new CollectionFunctions.ListGet()), LIST_FIRST("listFirst", new CollectionFunctions.ListFirst()), LIST_LAST("listLast", new CollectionFunctions.ListLast()), DICT("dict", new CollectionFunctions.DictCreate()), DICT_GET("dictGet", new CollectionFunctions.DictGet()), SORT("sort", new CollectionFunctions.Sort()), // file system functions DIR_LIST("dirList", new FileSystemFunctions.DirList()), DIR_LIST_NAME("dirListName", new FileSystemFunctions.DirListName()), EXISTS("exists", new FileSystemFunctions.Exists()), IS_DIR("isDir", new FileSystemFunctions.IsDir()), // metric functions METRIC_AGG("metricAgg", new MetricFunctions.MetricAggregateFunction()), AGE("age", new MetricFunctions.Age()), COUNT("count", new MetricFunctions.Count()), SIZE("size", new MetricFunctions.Size()), CREATION_DELAY("creationDelay", new MetricFunctions.CreationDelay()); private final String name;
private final Function function;
turn/camino
src/test/java/com/turn/camino/render/functions/CommonFunctionsTest.java
// Path: src/main/java/com/turn/camino/Context.java // public interface Context { // // /** // * Get system environment // * // * @return system environment // */ // Env getEnv(); // // /** // * Creates child context // * // * @return new context // */ // Context createChild(); // // /** // * Gets parent context // * // * Returns a parent context, or null if current context is global // * // * @return parent context // */ // Context getParent(); // // /** // * Gets global context // * // * Returns the global (ancestral) context // * // * @return global context // */ // Context getGlobal(); // // /** // * Puts name and value of property into the current context // * // * @param name name of property // * @param value value of property // */ // void setProperty(String name, Object value); // // /** // * Gets a value of a property given a name // * // * Note that if name is not found in the current context, the expected behavior is to // * recursively search in paren context. Null is returned only if name is not found in // * any context. // * // * @param name name of property // * @return value of property // */ // Object getProperty(String name); // // /** // * Gets a value of a property given a name // * // * Note that if name is not found in the current context, the expected behavior is to // * recursively search in paren context. Null is returned only if name is not found in // * any context. // * // * @param name name of value // * @param type type of value // * @return value // * @throws WrongTypeException // */ // <T> T getProperty(String name, Class<T> type) throws WrongTypeException; // // /** // * Gets time the global instance was created // * // * The time supplied by Env.getCurrentTime() will become the value of global instance time // * when the global context is created from Env. All child contexts under this global context // * will inherit the same global instance time. // * // * @return UTC time in milliseconds // */ // long getGlobalInstanceTime(); // // } // // Path: src/main/java/com/turn/camino/Env.java // public interface Env { // // /** // * Get current time // * // * @return current time in epoch milliseconds // */ // long getCurrentTime(); // // /** // * Get default time zone // * // * @return default time zone // */ // TimeZone getTimeZone(); // // /** // * Get file system // * // * @return Hadoop file system // */ // FileSystem getFileSystem(); // // /** // * Creates new context // * // * @return new global context // */ // Context newContext(); // // /** // * Get renderer // * // * @return new renderer // */ // Renderer getRenderer(); // // /** // * Get executor service // * // * @return executor service // */ // ExecutorService getExecutorService(); // // /** // * Get error handler // * // * @return error handler // */ // ErrorHandler getErrorHandler(); // // } // // Path: src/main/java/com/turn/camino/render/FunctionCallException.java // public class FunctionCallException extends RenderException { // // public FunctionCallException(String message) { // super(message); // } // // public FunctionCallException(Throwable throwable) { // super(throwable); // } // // }
import com.turn.camino.Context; import com.turn.camino.Env; import com.turn.camino.render.FunctionCallException; import com.google.common.collect.ImmutableList; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import java.util.TimeZone; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue;
/* * Copyright (C) 2014-2018, Amobee Inc. All Rights Reserved. * * 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 */ package com.turn.camino.render.functions; /** * Tests common functions * * @author llo */ public class CommonFunctionsTest { private Context context; private CommonFunctions.Compare compare = new CommonFunctions.Compare(); /** * Set up environment */ @BeforeClass public void setUp() { // mock environment context = mock(Context.class);
// Path: src/main/java/com/turn/camino/Context.java // public interface Context { // // /** // * Get system environment // * // * @return system environment // */ // Env getEnv(); // // /** // * Creates child context // * // * @return new context // */ // Context createChild(); // // /** // * Gets parent context // * // * Returns a parent context, or null if current context is global // * // * @return parent context // */ // Context getParent(); // // /** // * Gets global context // * // * Returns the global (ancestral) context // * // * @return global context // */ // Context getGlobal(); // // /** // * Puts name and value of property into the current context // * // * @param name name of property // * @param value value of property // */ // void setProperty(String name, Object value); // // /** // * Gets a value of a property given a name // * // * Note that if name is not found in the current context, the expected behavior is to // * recursively search in paren context. Null is returned only if name is not found in // * any context. // * // * @param name name of property // * @return value of property // */ // Object getProperty(String name); // // /** // * Gets a value of a property given a name // * // * Note that if name is not found in the current context, the expected behavior is to // * recursively search in paren context. Null is returned only if name is not found in // * any context. // * // * @param name name of value // * @param type type of value // * @return value // * @throws WrongTypeException // */ // <T> T getProperty(String name, Class<T> type) throws WrongTypeException; // // /** // * Gets time the global instance was created // * // * The time supplied by Env.getCurrentTime() will become the value of global instance time // * when the global context is created from Env. All child contexts under this global context // * will inherit the same global instance time. // * // * @return UTC time in milliseconds // */ // long getGlobalInstanceTime(); // // } // // Path: src/main/java/com/turn/camino/Env.java // public interface Env { // // /** // * Get current time // * // * @return current time in epoch milliseconds // */ // long getCurrentTime(); // // /** // * Get default time zone // * // * @return default time zone // */ // TimeZone getTimeZone(); // // /** // * Get file system // * // * @return Hadoop file system // */ // FileSystem getFileSystem(); // // /** // * Creates new context // * // * @return new global context // */ // Context newContext(); // // /** // * Get renderer // * // * @return new renderer // */ // Renderer getRenderer(); // // /** // * Get executor service // * // * @return executor service // */ // ExecutorService getExecutorService(); // // /** // * Get error handler // * // * @return error handler // */ // ErrorHandler getErrorHandler(); // // } // // Path: src/main/java/com/turn/camino/render/FunctionCallException.java // public class FunctionCallException extends RenderException { // // public FunctionCallException(String message) { // super(message); // } // // public FunctionCallException(Throwable throwable) { // super(throwable); // } // // } // Path: src/test/java/com/turn/camino/render/functions/CommonFunctionsTest.java import com.turn.camino.Context; import com.turn.camino.Env; import com.turn.camino.render.FunctionCallException; import com.google.common.collect.ImmutableList; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import java.util.TimeZone; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; /* * Copyright (C) 2014-2018, Amobee Inc. All Rights Reserved. * * 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 */ package com.turn.camino.render.functions; /** * Tests common functions * * @author llo */ public class CommonFunctionsTest { private Context context; private CommonFunctions.Compare compare = new CommonFunctions.Compare(); /** * Set up environment */ @BeforeClass public void setUp() { // mock environment context = mock(Context.class);
Env env = mock(Env.class);
turn/camino
src/test/java/com/turn/camino/render/functions/CommonFunctionsTest.java
// Path: src/main/java/com/turn/camino/Context.java // public interface Context { // // /** // * Get system environment // * // * @return system environment // */ // Env getEnv(); // // /** // * Creates child context // * // * @return new context // */ // Context createChild(); // // /** // * Gets parent context // * // * Returns a parent context, or null if current context is global // * // * @return parent context // */ // Context getParent(); // // /** // * Gets global context // * // * Returns the global (ancestral) context // * // * @return global context // */ // Context getGlobal(); // // /** // * Puts name and value of property into the current context // * // * @param name name of property // * @param value value of property // */ // void setProperty(String name, Object value); // // /** // * Gets a value of a property given a name // * // * Note that if name is not found in the current context, the expected behavior is to // * recursively search in paren context. Null is returned only if name is not found in // * any context. // * // * @param name name of property // * @return value of property // */ // Object getProperty(String name); // // /** // * Gets a value of a property given a name // * // * Note that if name is not found in the current context, the expected behavior is to // * recursively search in paren context. Null is returned only if name is not found in // * any context. // * // * @param name name of value // * @param type type of value // * @return value // * @throws WrongTypeException // */ // <T> T getProperty(String name, Class<T> type) throws WrongTypeException; // // /** // * Gets time the global instance was created // * // * The time supplied by Env.getCurrentTime() will become the value of global instance time // * when the global context is created from Env. All child contexts under this global context // * will inherit the same global instance time. // * // * @return UTC time in milliseconds // */ // long getGlobalInstanceTime(); // // } // // Path: src/main/java/com/turn/camino/Env.java // public interface Env { // // /** // * Get current time // * // * @return current time in epoch milliseconds // */ // long getCurrentTime(); // // /** // * Get default time zone // * // * @return default time zone // */ // TimeZone getTimeZone(); // // /** // * Get file system // * // * @return Hadoop file system // */ // FileSystem getFileSystem(); // // /** // * Creates new context // * // * @return new global context // */ // Context newContext(); // // /** // * Get renderer // * // * @return new renderer // */ // Renderer getRenderer(); // // /** // * Get executor service // * // * @return executor service // */ // ExecutorService getExecutorService(); // // /** // * Get error handler // * // * @return error handler // */ // ErrorHandler getErrorHandler(); // // } // // Path: src/main/java/com/turn/camino/render/FunctionCallException.java // public class FunctionCallException extends RenderException { // // public FunctionCallException(String message) { // super(message); // } // // public FunctionCallException(Throwable throwable) { // super(throwable); // } // // }
import com.turn.camino.Context; import com.turn.camino.Env; import com.turn.camino.render.FunctionCallException; import com.google.common.collect.ImmutableList; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import java.util.TimeZone; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue;
/* * Copyright (C) 2014-2018, Amobee Inc. All Rights Reserved. * * 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 */ package com.turn.camino.render.functions; /** * Tests common functions * * @author llo */ public class CommonFunctionsTest { private Context context; private CommonFunctions.Compare compare = new CommonFunctions.Compare(); /** * Set up environment */ @BeforeClass public void setUp() { // mock environment context = mock(Context.class); Env env = mock(Env.class); when(context.getEnv()).thenReturn(env); when(env.getCurrentTime()).thenReturn(1409389256296L); when(env.getTimeZone()).thenReturn(TimeZone.getTimeZone("GMT")); } @Test
// Path: src/main/java/com/turn/camino/Context.java // public interface Context { // // /** // * Get system environment // * // * @return system environment // */ // Env getEnv(); // // /** // * Creates child context // * // * @return new context // */ // Context createChild(); // // /** // * Gets parent context // * // * Returns a parent context, or null if current context is global // * // * @return parent context // */ // Context getParent(); // // /** // * Gets global context // * // * Returns the global (ancestral) context // * // * @return global context // */ // Context getGlobal(); // // /** // * Puts name and value of property into the current context // * // * @param name name of property // * @param value value of property // */ // void setProperty(String name, Object value); // // /** // * Gets a value of a property given a name // * // * Note that if name is not found in the current context, the expected behavior is to // * recursively search in paren context. Null is returned only if name is not found in // * any context. // * // * @param name name of property // * @return value of property // */ // Object getProperty(String name); // // /** // * Gets a value of a property given a name // * // * Note that if name is not found in the current context, the expected behavior is to // * recursively search in paren context. Null is returned only if name is not found in // * any context. // * // * @param name name of value // * @param type type of value // * @return value // * @throws WrongTypeException // */ // <T> T getProperty(String name, Class<T> type) throws WrongTypeException; // // /** // * Gets time the global instance was created // * // * The time supplied by Env.getCurrentTime() will become the value of global instance time // * when the global context is created from Env. All child contexts under this global context // * will inherit the same global instance time. // * // * @return UTC time in milliseconds // */ // long getGlobalInstanceTime(); // // } // // Path: src/main/java/com/turn/camino/Env.java // public interface Env { // // /** // * Get current time // * // * @return current time in epoch milliseconds // */ // long getCurrentTime(); // // /** // * Get default time zone // * // * @return default time zone // */ // TimeZone getTimeZone(); // // /** // * Get file system // * // * @return Hadoop file system // */ // FileSystem getFileSystem(); // // /** // * Creates new context // * // * @return new global context // */ // Context newContext(); // // /** // * Get renderer // * // * @return new renderer // */ // Renderer getRenderer(); // // /** // * Get executor service // * // * @return executor service // */ // ExecutorService getExecutorService(); // // /** // * Get error handler // * // * @return error handler // */ // ErrorHandler getErrorHandler(); // // } // // Path: src/main/java/com/turn/camino/render/FunctionCallException.java // public class FunctionCallException extends RenderException { // // public FunctionCallException(String message) { // super(message); // } // // public FunctionCallException(Throwable throwable) { // super(throwable); // } // // } // Path: src/test/java/com/turn/camino/render/functions/CommonFunctionsTest.java import com.turn.camino.Context; import com.turn.camino.Env; import com.turn.camino.render.FunctionCallException; import com.google.common.collect.ImmutableList; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import java.util.TimeZone; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; /* * Copyright (C) 2014-2018, Amobee Inc. All Rights Reserved. * * 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 */ package com.turn.camino.render.functions; /** * Tests common functions * * @author llo */ public class CommonFunctionsTest { private Context context; private CommonFunctions.Compare compare = new CommonFunctions.Compare(); /** * Set up environment */ @BeforeClass public void setUp() { // mock environment context = mock(Context.class); Env env = mock(Env.class); when(context.getEnv()).thenReturn(env); when(env.getCurrentTime()).thenReturn(1409389256296L); when(env.getTimeZone()).thenReturn(TimeZone.getTimeZone("GMT")); } @Test
public void testCompare() throws FunctionCallException {
turn/camino
src/test/java/com/turn/camino/render/functions/FileSystemFunctionsTest.java
// Path: src/main/java/com/turn/camino/Context.java // public interface Context { // // /** // * Get system environment // * // * @return system environment // */ // Env getEnv(); // // /** // * Creates child context // * // * @return new context // */ // Context createChild(); // // /** // * Gets parent context // * // * Returns a parent context, or null if current context is global // * // * @return parent context // */ // Context getParent(); // // /** // * Gets global context // * // * Returns the global (ancestral) context // * // * @return global context // */ // Context getGlobal(); // // /** // * Puts name and value of property into the current context // * // * @param name name of property // * @param value value of property // */ // void setProperty(String name, Object value); // // /** // * Gets a value of a property given a name // * // * Note that if name is not found in the current context, the expected behavior is to // * recursively search in paren context. Null is returned only if name is not found in // * any context. // * // * @param name name of property // * @return value of property // */ // Object getProperty(String name); // // /** // * Gets a value of a property given a name // * // * Note that if name is not found in the current context, the expected behavior is to // * recursively search in paren context. Null is returned only if name is not found in // * any context. // * // * @param name name of value // * @param type type of value // * @return value // * @throws WrongTypeException // */ // <T> T getProperty(String name, Class<T> type) throws WrongTypeException; // // /** // * Gets time the global instance was created // * // * The time supplied by Env.getCurrentTime() will become the value of global instance time // * when the global context is created from Env. All child contexts under this global context // * will inherit the same global instance time. // * // * @return UTC time in milliseconds // */ // long getGlobalInstanceTime(); // // } // // Path: src/main/java/com/turn/camino/Env.java // public interface Env { // // /** // * Get current time // * // * @return current time in epoch milliseconds // */ // long getCurrentTime(); // // /** // * Get default time zone // * // * @return default time zone // */ // TimeZone getTimeZone(); // // /** // * Get file system // * // * @return Hadoop file system // */ // FileSystem getFileSystem(); // // /** // * Creates new context // * // * @return new global context // */ // Context newContext(); // // /** // * Get renderer // * // * @return new renderer // */ // Renderer getRenderer(); // // /** // * Get executor service // * // * @return executor service // */ // ExecutorService getExecutorService(); // // /** // * Get error handler // * // * @return error handler // */ // ErrorHandler getErrorHandler(); // // } // // Path: src/main/java/com/turn/camino/render/Function.java // public interface Function { // // /** // * Invokes function with given parameters and context // * // * @param params actual parameters to function call // * @param context context in which the function operates // * @return return value of function // * @throws FunctionCallException // */ // Object invoke(List<?> params, Context context) throws FunctionCallException; // // } // // Path: src/main/java/com/turn/camino/render/FunctionCallException.java // public class FunctionCallException extends RenderException { // // public FunctionCallException(String message) { // super(message); // } // // public FunctionCallException(Throwable throwable) { // super(throwable); // } // // }
import static org.mockito.Mockito.*; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; import com.turn.camino.Context; import com.turn.camino.Env; import com.turn.camino.render.Function; import com.turn.camino.render.FunctionCallException; import com.google.common.collect.ImmutableList; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.PathFilter; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import java.io.IOException; import java.util.List; import java.util.TimeZone;
/* * Copyright (C) 2014-2018, Amobee Inc. All Rights Reserved. * * 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 */ package com.turn.camino.render.functions; /** * Tests file system functions * * @author llo */ @Test public class FileSystemFunctionsTest {
// Path: src/main/java/com/turn/camino/Context.java // public interface Context { // // /** // * Get system environment // * // * @return system environment // */ // Env getEnv(); // // /** // * Creates child context // * // * @return new context // */ // Context createChild(); // // /** // * Gets parent context // * // * Returns a parent context, or null if current context is global // * // * @return parent context // */ // Context getParent(); // // /** // * Gets global context // * // * Returns the global (ancestral) context // * // * @return global context // */ // Context getGlobal(); // // /** // * Puts name and value of property into the current context // * // * @param name name of property // * @param value value of property // */ // void setProperty(String name, Object value); // // /** // * Gets a value of a property given a name // * // * Note that if name is not found in the current context, the expected behavior is to // * recursively search in paren context. Null is returned only if name is not found in // * any context. // * // * @param name name of property // * @return value of property // */ // Object getProperty(String name); // // /** // * Gets a value of a property given a name // * // * Note that if name is not found in the current context, the expected behavior is to // * recursively search in paren context. Null is returned only if name is not found in // * any context. // * // * @param name name of value // * @param type type of value // * @return value // * @throws WrongTypeException // */ // <T> T getProperty(String name, Class<T> type) throws WrongTypeException; // // /** // * Gets time the global instance was created // * // * The time supplied by Env.getCurrentTime() will become the value of global instance time // * when the global context is created from Env. All child contexts under this global context // * will inherit the same global instance time. // * // * @return UTC time in milliseconds // */ // long getGlobalInstanceTime(); // // } // // Path: src/main/java/com/turn/camino/Env.java // public interface Env { // // /** // * Get current time // * // * @return current time in epoch milliseconds // */ // long getCurrentTime(); // // /** // * Get default time zone // * // * @return default time zone // */ // TimeZone getTimeZone(); // // /** // * Get file system // * // * @return Hadoop file system // */ // FileSystem getFileSystem(); // // /** // * Creates new context // * // * @return new global context // */ // Context newContext(); // // /** // * Get renderer // * // * @return new renderer // */ // Renderer getRenderer(); // // /** // * Get executor service // * // * @return executor service // */ // ExecutorService getExecutorService(); // // /** // * Get error handler // * // * @return error handler // */ // ErrorHandler getErrorHandler(); // // } // // Path: src/main/java/com/turn/camino/render/Function.java // public interface Function { // // /** // * Invokes function with given parameters and context // * // * @param params actual parameters to function call // * @param context context in which the function operates // * @return return value of function // * @throws FunctionCallException // */ // Object invoke(List<?> params, Context context) throws FunctionCallException; // // } // // Path: src/main/java/com/turn/camino/render/FunctionCallException.java // public class FunctionCallException extends RenderException { // // public FunctionCallException(String message) { // super(message); // } // // public FunctionCallException(Throwable throwable) { // super(throwable); // } // // } // Path: src/test/java/com/turn/camino/render/functions/FileSystemFunctionsTest.java import static org.mockito.Mockito.*; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; import com.turn.camino.Context; import com.turn.camino.Env; import com.turn.camino.render.Function; import com.turn.camino.render.FunctionCallException; import com.google.common.collect.ImmutableList; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.PathFilter; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import java.io.IOException; import java.util.List; import java.util.TimeZone; /* * Copyright (C) 2014-2018, Amobee Inc. All Rights Reserved. * * 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 */ package com.turn.camino.render.functions; /** * Tests file system functions * * @author llo */ @Test public class FileSystemFunctionsTest {
private Context context;
turn/camino
src/test/java/com/turn/camino/render/functions/FileSystemFunctionsTest.java
// Path: src/main/java/com/turn/camino/Context.java // public interface Context { // // /** // * Get system environment // * // * @return system environment // */ // Env getEnv(); // // /** // * Creates child context // * // * @return new context // */ // Context createChild(); // // /** // * Gets parent context // * // * Returns a parent context, or null if current context is global // * // * @return parent context // */ // Context getParent(); // // /** // * Gets global context // * // * Returns the global (ancestral) context // * // * @return global context // */ // Context getGlobal(); // // /** // * Puts name and value of property into the current context // * // * @param name name of property // * @param value value of property // */ // void setProperty(String name, Object value); // // /** // * Gets a value of a property given a name // * // * Note that if name is not found in the current context, the expected behavior is to // * recursively search in paren context. Null is returned only if name is not found in // * any context. // * // * @param name name of property // * @return value of property // */ // Object getProperty(String name); // // /** // * Gets a value of a property given a name // * // * Note that if name is not found in the current context, the expected behavior is to // * recursively search in paren context. Null is returned only if name is not found in // * any context. // * // * @param name name of value // * @param type type of value // * @return value // * @throws WrongTypeException // */ // <T> T getProperty(String name, Class<T> type) throws WrongTypeException; // // /** // * Gets time the global instance was created // * // * The time supplied by Env.getCurrentTime() will become the value of global instance time // * when the global context is created from Env. All child contexts under this global context // * will inherit the same global instance time. // * // * @return UTC time in milliseconds // */ // long getGlobalInstanceTime(); // // } // // Path: src/main/java/com/turn/camino/Env.java // public interface Env { // // /** // * Get current time // * // * @return current time in epoch milliseconds // */ // long getCurrentTime(); // // /** // * Get default time zone // * // * @return default time zone // */ // TimeZone getTimeZone(); // // /** // * Get file system // * // * @return Hadoop file system // */ // FileSystem getFileSystem(); // // /** // * Creates new context // * // * @return new global context // */ // Context newContext(); // // /** // * Get renderer // * // * @return new renderer // */ // Renderer getRenderer(); // // /** // * Get executor service // * // * @return executor service // */ // ExecutorService getExecutorService(); // // /** // * Get error handler // * // * @return error handler // */ // ErrorHandler getErrorHandler(); // // } // // Path: src/main/java/com/turn/camino/render/Function.java // public interface Function { // // /** // * Invokes function with given parameters and context // * // * @param params actual parameters to function call // * @param context context in which the function operates // * @return return value of function // * @throws FunctionCallException // */ // Object invoke(List<?> params, Context context) throws FunctionCallException; // // } // // Path: src/main/java/com/turn/camino/render/FunctionCallException.java // public class FunctionCallException extends RenderException { // // public FunctionCallException(String message) { // super(message); // } // // public FunctionCallException(Throwable throwable) { // super(throwable); // } // // }
import static org.mockito.Mockito.*; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; import com.turn.camino.Context; import com.turn.camino.Env; import com.turn.camino.render.Function; import com.turn.camino.render.FunctionCallException; import com.google.common.collect.ImmutableList; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.PathFilter; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import java.io.IOException; import java.util.List; import java.util.TimeZone;
doThrow(new IOException()).when(fileSystem).listStatus(new org.apache.hadoop.fs.Path("/foo")); context = mock(Context.class); Env env = mock(Env.class); when(context.getEnv()).thenReturn(env); when(env.getCurrentTime()).thenReturn(1409389256296L); when(env.getTimeZone()).thenReturn(TimeZone.getTimeZone("GMT")); when(env.getFileSystem()).thenReturn(fileSystem); } /** * Test directory listing */ @Test public void testDirList() throws FunctionCallException { Object result = dirList.invoke(ImmutableList.of("/a/b"), context); assertTrue(result instanceof List); List<?> list = (List<?>) result; assertEquals(list.size(), 3); assertEquals(list.get(0), "/a/b/1.dat"); assertEquals(list.get(1), "/a/b/2.dat"); assertEquals(list.get(2), "/a/b/3.dat"); } /** * Test directory listing with filter */ @Test public void testDirListWithFilter() throws FunctionCallException {
// Path: src/main/java/com/turn/camino/Context.java // public interface Context { // // /** // * Get system environment // * // * @return system environment // */ // Env getEnv(); // // /** // * Creates child context // * // * @return new context // */ // Context createChild(); // // /** // * Gets parent context // * // * Returns a parent context, or null if current context is global // * // * @return parent context // */ // Context getParent(); // // /** // * Gets global context // * // * Returns the global (ancestral) context // * // * @return global context // */ // Context getGlobal(); // // /** // * Puts name and value of property into the current context // * // * @param name name of property // * @param value value of property // */ // void setProperty(String name, Object value); // // /** // * Gets a value of a property given a name // * // * Note that if name is not found in the current context, the expected behavior is to // * recursively search in paren context. Null is returned only if name is not found in // * any context. // * // * @param name name of property // * @return value of property // */ // Object getProperty(String name); // // /** // * Gets a value of a property given a name // * // * Note that if name is not found in the current context, the expected behavior is to // * recursively search in paren context. Null is returned only if name is not found in // * any context. // * // * @param name name of value // * @param type type of value // * @return value // * @throws WrongTypeException // */ // <T> T getProperty(String name, Class<T> type) throws WrongTypeException; // // /** // * Gets time the global instance was created // * // * The time supplied by Env.getCurrentTime() will become the value of global instance time // * when the global context is created from Env. All child contexts under this global context // * will inherit the same global instance time. // * // * @return UTC time in milliseconds // */ // long getGlobalInstanceTime(); // // } // // Path: src/main/java/com/turn/camino/Env.java // public interface Env { // // /** // * Get current time // * // * @return current time in epoch milliseconds // */ // long getCurrentTime(); // // /** // * Get default time zone // * // * @return default time zone // */ // TimeZone getTimeZone(); // // /** // * Get file system // * // * @return Hadoop file system // */ // FileSystem getFileSystem(); // // /** // * Creates new context // * // * @return new global context // */ // Context newContext(); // // /** // * Get renderer // * // * @return new renderer // */ // Renderer getRenderer(); // // /** // * Get executor service // * // * @return executor service // */ // ExecutorService getExecutorService(); // // /** // * Get error handler // * // * @return error handler // */ // ErrorHandler getErrorHandler(); // // } // // Path: src/main/java/com/turn/camino/render/Function.java // public interface Function { // // /** // * Invokes function with given parameters and context // * // * @param params actual parameters to function call // * @param context context in which the function operates // * @return return value of function // * @throws FunctionCallException // */ // Object invoke(List<?> params, Context context) throws FunctionCallException; // // } // // Path: src/main/java/com/turn/camino/render/FunctionCallException.java // public class FunctionCallException extends RenderException { // // public FunctionCallException(String message) { // super(message); // } // // public FunctionCallException(Throwable throwable) { // super(throwable); // } // // } // Path: src/test/java/com/turn/camino/render/functions/FileSystemFunctionsTest.java import static org.mockito.Mockito.*; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; import com.turn.camino.Context; import com.turn.camino.Env; import com.turn.camino.render.Function; import com.turn.camino.render.FunctionCallException; import com.google.common.collect.ImmutableList; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.PathFilter; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import java.io.IOException; import java.util.List; import java.util.TimeZone; doThrow(new IOException()).when(fileSystem).listStatus(new org.apache.hadoop.fs.Path("/foo")); context = mock(Context.class); Env env = mock(Env.class); when(context.getEnv()).thenReturn(env); when(env.getCurrentTime()).thenReturn(1409389256296L); when(env.getTimeZone()).thenReturn(TimeZone.getTimeZone("GMT")); when(env.getFileSystem()).thenReturn(fileSystem); } /** * Test directory listing */ @Test public void testDirList() throws FunctionCallException { Object result = dirList.invoke(ImmutableList.of("/a/b"), context); assertTrue(result instanceof List); List<?> list = (List<?>) result; assertEquals(list.size(), 3); assertEquals(list.get(0), "/a/b/1.dat"); assertEquals(list.get(1), "/a/b/2.dat"); assertEquals(list.get(2), "/a/b/3.dat"); } /** * Test directory listing with filter */ @Test public void testDirListWithFilter() throws FunctionCallException {
Function predicate = (params, context) -> params.get(0).toString().endsWith("1.dat");
turn/camino
src/test/java/com/turn/camino/render/functions/MathFunctionsTest.java
// Path: src/main/java/com/turn/camino/Context.java // public interface Context { // // /** // * Get system environment // * // * @return system environment // */ // Env getEnv(); // // /** // * Creates child context // * // * @return new context // */ // Context createChild(); // // /** // * Gets parent context // * // * Returns a parent context, or null if current context is global // * // * @return parent context // */ // Context getParent(); // // /** // * Gets global context // * // * Returns the global (ancestral) context // * // * @return global context // */ // Context getGlobal(); // // /** // * Puts name and value of property into the current context // * // * @param name name of property // * @param value value of property // */ // void setProperty(String name, Object value); // // /** // * Gets a value of a property given a name // * // * Note that if name is not found in the current context, the expected behavior is to // * recursively search in paren context. Null is returned only if name is not found in // * any context. // * // * @param name name of property // * @return value of property // */ // Object getProperty(String name); // // /** // * Gets a value of a property given a name // * // * Note that if name is not found in the current context, the expected behavior is to // * recursively search in paren context. Null is returned only if name is not found in // * any context. // * // * @param name name of value // * @param type type of value // * @return value // * @throws WrongTypeException // */ // <T> T getProperty(String name, Class<T> type) throws WrongTypeException; // // /** // * Gets time the global instance was created // * // * The time supplied by Env.getCurrentTime() will become the value of global instance time // * when the global context is created from Env. All child contexts under this global context // * will inherit the same global instance time. // * // * @return UTC time in milliseconds // */ // long getGlobalInstanceTime(); // // } // // Path: src/main/java/com/turn/camino/Env.java // public interface Env { // // /** // * Get current time // * // * @return current time in epoch milliseconds // */ // long getCurrentTime(); // // /** // * Get default time zone // * // * @return default time zone // */ // TimeZone getTimeZone(); // // /** // * Get file system // * // * @return Hadoop file system // */ // FileSystem getFileSystem(); // // /** // * Creates new context // * // * @return new global context // */ // Context newContext(); // // /** // * Get renderer // * // * @return new renderer // */ // Renderer getRenderer(); // // /** // * Get executor service // * // * @return executor service // */ // ExecutorService getExecutorService(); // // /** // * Get error handler // * // * @return error handler // */ // ErrorHandler getErrorHandler(); // // } // // Path: src/main/java/com/turn/camino/render/FunctionCallException.java // public class FunctionCallException extends RenderException { // // public FunctionCallException(String message) { // super(message); // } // // public FunctionCallException(Throwable throwable) { // super(throwable); // } // // }
import com.turn.camino.Context; import com.turn.camino.Env; import com.turn.camino.render.FunctionCallException; import java.util.TimeZone; import com.google.common.collect.ImmutableList; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.testng.Assert.*;
/* * Copyright (C) 2014-2018, Amobee Inc. All Rights Reserved. * * 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 */ package com.turn.camino.render.functions; /** * Unit test for math functions * * @author llo */ @Test public class MathFunctionsTest {
// Path: src/main/java/com/turn/camino/Context.java // public interface Context { // // /** // * Get system environment // * // * @return system environment // */ // Env getEnv(); // // /** // * Creates child context // * // * @return new context // */ // Context createChild(); // // /** // * Gets parent context // * // * Returns a parent context, or null if current context is global // * // * @return parent context // */ // Context getParent(); // // /** // * Gets global context // * // * Returns the global (ancestral) context // * // * @return global context // */ // Context getGlobal(); // // /** // * Puts name and value of property into the current context // * // * @param name name of property // * @param value value of property // */ // void setProperty(String name, Object value); // // /** // * Gets a value of a property given a name // * // * Note that if name is not found in the current context, the expected behavior is to // * recursively search in paren context. Null is returned only if name is not found in // * any context. // * // * @param name name of property // * @return value of property // */ // Object getProperty(String name); // // /** // * Gets a value of a property given a name // * // * Note that if name is not found in the current context, the expected behavior is to // * recursively search in paren context. Null is returned only if name is not found in // * any context. // * // * @param name name of value // * @param type type of value // * @return value // * @throws WrongTypeException // */ // <T> T getProperty(String name, Class<T> type) throws WrongTypeException; // // /** // * Gets time the global instance was created // * // * The time supplied by Env.getCurrentTime() will become the value of global instance time // * when the global context is created from Env. All child contexts under this global context // * will inherit the same global instance time. // * // * @return UTC time in milliseconds // */ // long getGlobalInstanceTime(); // // } // // Path: src/main/java/com/turn/camino/Env.java // public interface Env { // // /** // * Get current time // * // * @return current time in epoch milliseconds // */ // long getCurrentTime(); // // /** // * Get default time zone // * // * @return default time zone // */ // TimeZone getTimeZone(); // // /** // * Get file system // * // * @return Hadoop file system // */ // FileSystem getFileSystem(); // // /** // * Creates new context // * // * @return new global context // */ // Context newContext(); // // /** // * Get renderer // * // * @return new renderer // */ // Renderer getRenderer(); // // /** // * Get executor service // * // * @return executor service // */ // ExecutorService getExecutorService(); // // /** // * Get error handler // * // * @return error handler // */ // ErrorHandler getErrorHandler(); // // } // // Path: src/main/java/com/turn/camino/render/FunctionCallException.java // public class FunctionCallException extends RenderException { // // public FunctionCallException(String message) { // super(message); // } // // public FunctionCallException(Throwable throwable) { // super(throwable); // } // // } // Path: src/test/java/com/turn/camino/render/functions/MathFunctionsTest.java import com.turn.camino.Context; import com.turn.camino.Env; import com.turn.camino.render.FunctionCallException; import java.util.TimeZone; import com.google.common.collect.ImmutableList; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.testng.Assert.*; /* * Copyright (C) 2014-2018, Amobee Inc. All Rights Reserved. * * 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 */ package com.turn.camino.render.functions; /** * Unit test for math functions * * @author llo */ @Test public class MathFunctionsTest {
private Context context;
turn/camino
src/test/java/com/turn/camino/render/functions/MathFunctionsTest.java
// Path: src/main/java/com/turn/camino/Context.java // public interface Context { // // /** // * Get system environment // * // * @return system environment // */ // Env getEnv(); // // /** // * Creates child context // * // * @return new context // */ // Context createChild(); // // /** // * Gets parent context // * // * Returns a parent context, or null if current context is global // * // * @return parent context // */ // Context getParent(); // // /** // * Gets global context // * // * Returns the global (ancestral) context // * // * @return global context // */ // Context getGlobal(); // // /** // * Puts name and value of property into the current context // * // * @param name name of property // * @param value value of property // */ // void setProperty(String name, Object value); // // /** // * Gets a value of a property given a name // * // * Note that if name is not found in the current context, the expected behavior is to // * recursively search in paren context. Null is returned only if name is not found in // * any context. // * // * @param name name of property // * @return value of property // */ // Object getProperty(String name); // // /** // * Gets a value of a property given a name // * // * Note that if name is not found in the current context, the expected behavior is to // * recursively search in paren context. Null is returned only if name is not found in // * any context. // * // * @param name name of value // * @param type type of value // * @return value // * @throws WrongTypeException // */ // <T> T getProperty(String name, Class<T> type) throws WrongTypeException; // // /** // * Gets time the global instance was created // * // * The time supplied by Env.getCurrentTime() will become the value of global instance time // * when the global context is created from Env. All child contexts under this global context // * will inherit the same global instance time. // * // * @return UTC time in milliseconds // */ // long getGlobalInstanceTime(); // // } // // Path: src/main/java/com/turn/camino/Env.java // public interface Env { // // /** // * Get current time // * // * @return current time in epoch milliseconds // */ // long getCurrentTime(); // // /** // * Get default time zone // * // * @return default time zone // */ // TimeZone getTimeZone(); // // /** // * Get file system // * // * @return Hadoop file system // */ // FileSystem getFileSystem(); // // /** // * Creates new context // * // * @return new global context // */ // Context newContext(); // // /** // * Get renderer // * // * @return new renderer // */ // Renderer getRenderer(); // // /** // * Get executor service // * // * @return executor service // */ // ExecutorService getExecutorService(); // // /** // * Get error handler // * // * @return error handler // */ // ErrorHandler getErrorHandler(); // // } // // Path: src/main/java/com/turn/camino/render/FunctionCallException.java // public class FunctionCallException extends RenderException { // // public FunctionCallException(String message) { // super(message); // } // // public FunctionCallException(Throwable throwable) { // super(throwable); // } // // }
import com.turn.camino.Context; import com.turn.camino.Env; import com.turn.camino.render.FunctionCallException; import java.util.TimeZone; import com.google.common.collect.ImmutableList; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.testng.Assert.*;
/* * Copyright (C) 2014-2018, Amobee Inc. All Rights Reserved. * * 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 */ package com.turn.camino.render.functions; /** * Unit test for math functions * * @author llo */ @Test public class MathFunctionsTest { private Context context; private final MathFunctions.Add add = new MathFunctions.Add(); private final MathFunctions.Subtract subtract = new MathFunctions.Subtract(); private final MathFunctions.Multiply multiply = new MathFunctions.Multiply(); private final MathFunctions.Divide divide = new MathFunctions.Divide(); /** * Set up environment */ @BeforeClass public void setUp() { // mock environment context = mock(Context.class);
// Path: src/main/java/com/turn/camino/Context.java // public interface Context { // // /** // * Get system environment // * // * @return system environment // */ // Env getEnv(); // // /** // * Creates child context // * // * @return new context // */ // Context createChild(); // // /** // * Gets parent context // * // * Returns a parent context, or null if current context is global // * // * @return parent context // */ // Context getParent(); // // /** // * Gets global context // * // * Returns the global (ancestral) context // * // * @return global context // */ // Context getGlobal(); // // /** // * Puts name and value of property into the current context // * // * @param name name of property // * @param value value of property // */ // void setProperty(String name, Object value); // // /** // * Gets a value of a property given a name // * // * Note that if name is not found in the current context, the expected behavior is to // * recursively search in paren context. Null is returned only if name is not found in // * any context. // * // * @param name name of property // * @return value of property // */ // Object getProperty(String name); // // /** // * Gets a value of a property given a name // * // * Note that if name is not found in the current context, the expected behavior is to // * recursively search in paren context. Null is returned only if name is not found in // * any context. // * // * @param name name of value // * @param type type of value // * @return value // * @throws WrongTypeException // */ // <T> T getProperty(String name, Class<T> type) throws WrongTypeException; // // /** // * Gets time the global instance was created // * // * The time supplied by Env.getCurrentTime() will become the value of global instance time // * when the global context is created from Env. All child contexts under this global context // * will inherit the same global instance time. // * // * @return UTC time in milliseconds // */ // long getGlobalInstanceTime(); // // } // // Path: src/main/java/com/turn/camino/Env.java // public interface Env { // // /** // * Get current time // * // * @return current time in epoch milliseconds // */ // long getCurrentTime(); // // /** // * Get default time zone // * // * @return default time zone // */ // TimeZone getTimeZone(); // // /** // * Get file system // * // * @return Hadoop file system // */ // FileSystem getFileSystem(); // // /** // * Creates new context // * // * @return new global context // */ // Context newContext(); // // /** // * Get renderer // * // * @return new renderer // */ // Renderer getRenderer(); // // /** // * Get executor service // * // * @return executor service // */ // ExecutorService getExecutorService(); // // /** // * Get error handler // * // * @return error handler // */ // ErrorHandler getErrorHandler(); // // } // // Path: src/main/java/com/turn/camino/render/FunctionCallException.java // public class FunctionCallException extends RenderException { // // public FunctionCallException(String message) { // super(message); // } // // public FunctionCallException(Throwable throwable) { // super(throwable); // } // // } // Path: src/test/java/com/turn/camino/render/functions/MathFunctionsTest.java import com.turn.camino.Context; import com.turn.camino.Env; import com.turn.camino.render.FunctionCallException; import java.util.TimeZone; import com.google.common.collect.ImmutableList; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.testng.Assert.*; /* * Copyright (C) 2014-2018, Amobee Inc. All Rights Reserved. * * 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 */ package com.turn.camino.render.functions; /** * Unit test for math functions * * @author llo */ @Test public class MathFunctionsTest { private Context context; private final MathFunctions.Add add = new MathFunctions.Add(); private final MathFunctions.Subtract subtract = new MathFunctions.Subtract(); private final MathFunctions.Multiply multiply = new MathFunctions.Multiply(); private final MathFunctions.Divide divide = new MathFunctions.Divide(); /** * Set up environment */ @BeforeClass public void setUp() { // mock environment context = mock(Context.class);
Env env = mock(Env.class);
turn/camino
src/test/java/com/turn/camino/render/functions/MathFunctionsTest.java
// Path: src/main/java/com/turn/camino/Context.java // public interface Context { // // /** // * Get system environment // * // * @return system environment // */ // Env getEnv(); // // /** // * Creates child context // * // * @return new context // */ // Context createChild(); // // /** // * Gets parent context // * // * Returns a parent context, or null if current context is global // * // * @return parent context // */ // Context getParent(); // // /** // * Gets global context // * // * Returns the global (ancestral) context // * // * @return global context // */ // Context getGlobal(); // // /** // * Puts name and value of property into the current context // * // * @param name name of property // * @param value value of property // */ // void setProperty(String name, Object value); // // /** // * Gets a value of a property given a name // * // * Note that if name is not found in the current context, the expected behavior is to // * recursively search in paren context. Null is returned only if name is not found in // * any context. // * // * @param name name of property // * @return value of property // */ // Object getProperty(String name); // // /** // * Gets a value of a property given a name // * // * Note that if name is not found in the current context, the expected behavior is to // * recursively search in paren context. Null is returned only if name is not found in // * any context. // * // * @param name name of value // * @param type type of value // * @return value // * @throws WrongTypeException // */ // <T> T getProperty(String name, Class<T> type) throws WrongTypeException; // // /** // * Gets time the global instance was created // * // * The time supplied by Env.getCurrentTime() will become the value of global instance time // * when the global context is created from Env. All child contexts under this global context // * will inherit the same global instance time. // * // * @return UTC time in milliseconds // */ // long getGlobalInstanceTime(); // // } // // Path: src/main/java/com/turn/camino/Env.java // public interface Env { // // /** // * Get current time // * // * @return current time in epoch milliseconds // */ // long getCurrentTime(); // // /** // * Get default time zone // * // * @return default time zone // */ // TimeZone getTimeZone(); // // /** // * Get file system // * // * @return Hadoop file system // */ // FileSystem getFileSystem(); // // /** // * Creates new context // * // * @return new global context // */ // Context newContext(); // // /** // * Get renderer // * // * @return new renderer // */ // Renderer getRenderer(); // // /** // * Get executor service // * // * @return executor service // */ // ExecutorService getExecutorService(); // // /** // * Get error handler // * // * @return error handler // */ // ErrorHandler getErrorHandler(); // // } // // Path: src/main/java/com/turn/camino/render/FunctionCallException.java // public class FunctionCallException extends RenderException { // // public FunctionCallException(String message) { // super(message); // } // // public FunctionCallException(Throwable throwable) { // super(throwable); // } // // }
import com.turn.camino.Context; import com.turn.camino.Env; import com.turn.camino.render.FunctionCallException; import java.util.TimeZone; import com.google.common.collect.ImmutableList; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.testng.Assert.*;
/* * Copyright (C) 2014-2018, Amobee Inc. All Rights Reserved. * * 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 */ package com.turn.camino.render.functions; /** * Unit test for math functions * * @author llo */ @Test public class MathFunctionsTest { private Context context; private final MathFunctions.Add add = new MathFunctions.Add(); private final MathFunctions.Subtract subtract = new MathFunctions.Subtract(); private final MathFunctions.Multiply multiply = new MathFunctions.Multiply(); private final MathFunctions.Divide divide = new MathFunctions.Divide(); /** * Set up environment */ @BeforeClass public void setUp() { // mock environment context = mock(Context.class); Env env = mock(Env.class); when(context.getEnv()).thenReturn(env); when(env.getCurrentTime()).thenReturn(1409389256296L); when(env.getTimeZone()).thenReturn(TimeZone.getTimeZone("GMT")); } /** * Test add function * * @throws FunctionCallException */ @Test
// Path: src/main/java/com/turn/camino/Context.java // public interface Context { // // /** // * Get system environment // * // * @return system environment // */ // Env getEnv(); // // /** // * Creates child context // * // * @return new context // */ // Context createChild(); // // /** // * Gets parent context // * // * Returns a parent context, or null if current context is global // * // * @return parent context // */ // Context getParent(); // // /** // * Gets global context // * // * Returns the global (ancestral) context // * // * @return global context // */ // Context getGlobal(); // // /** // * Puts name and value of property into the current context // * // * @param name name of property // * @param value value of property // */ // void setProperty(String name, Object value); // // /** // * Gets a value of a property given a name // * // * Note that if name is not found in the current context, the expected behavior is to // * recursively search in paren context. Null is returned only if name is not found in // * any context. // * // * @param name name of property // * @return value of property // */ // Object getProperty(String name); // // /** // * Gets a value of a property given a name // * // * Note that if name is not found in the current context, the expected behavior is to // * recursively search in paren context. Null is returned only if name is not found in // * any context. // * // * @param name name of value // * @param type type of value // * @return value // * @throws WrongTypeException // */ // <T> T getProperty(String name, Class<T> type) throws WrongTypeException; // // /** // * Gets time the global instance was created // * // * The time supplied by Env.getCurrentTime() will become the value of global instance time // * when the global context is created from Env. All child contexts under this global context // * will inherit the same global instance time. // * // * @return UTC time in milliseconds // */ // long getGlobalInstanceTime(); // // } // // Path: src/main/java/com/turn/camino/Env.java // public interface Env { // // /** // * Get current time // * // * @return current time in epoch milliseconds // */ // long getCurrentTime(); // // /** // * Get default time zone // * // * @return default time zone // */ // TimeZone getTimeZone(); // // /** // * Get file system // * // * @return Hadoop file system // */ // FileSystem getFileSystem(); // // /** // * Creates new context // * // * @return new global context // */ // Context newContext(); // // /** // * Get renderer // * // * @return new renderer // */ // Renderer getRenderer(); // // /** // * Get executor service // * // * @return executor service // */ // ExecutorService getExecutorService(); // // /** // * Get error handler // * // * @return error handler // */ // ErrorHandler getErrorHandler(); // // } // // Path: src/main/java/com/turn/camino/render/FunctionCallException.java // public class FunctionCallException extends RenderException { // // public FunctionCallException(String message) { // super(message); // } // // public FunctionCallException(Throwable throwable) { // super(throwable); // } // // } // Path: src/test/java/com/turn/camino/render/functions/MathFunctionsTest.java import com.turn.camino.Context; import com.turn.camino.Env; import com.turn.camino.render.FunctionCallException; import java.util.TimeZone; import com.google.common.collect.ImmutableList; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.testng.Assert.*; /* * Copyright (C) 2014-2018, Amobee Inc. All Rights Reserved. * * 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 */ package com.turn.camino.render.functions; /** * Unit test for math functions * * @author llo */ @Test public class MathFunctionsTest { private Context context; private final MathFunctions.Add add = new MathFunctions.Add(); private final MathFunctions.Subtract subtract = new MathFunctions.Subtract(); private final MathFunctions.Multiply multiply = new MathFunctions.Multiply(); private final MathFunctions.Divide divide = new MathFunctions.Divide(); /** * Set up environment */ @BeforeClass public void setUp() { // mock environment context = mock(Context.class); Env env = mock(Env.class); when(context.getEnv()).thenReturn(env); when(env.getCurrentTime()).thenReturn(1409389256296L); when(env.getTimeZone()).thenReturn(TimeZone.getTimeZone("GMT")); } /** * Test add function * * @throws FunctionCallException */ @Test
public void testAdd() throws FunctionCallException {
turn/camino
src/test/java/com/turn/camino/render/functions/LogicFunctionsTest.java
// Path: src/main/java/com/turn/camino/Context.java // public interface Context { // // /** // * Get system environment // * // * @return system environment // */ // Env getEnv(); // // /** // * Creates child context // * // * @return new context // */ // Context createChild(); // // /** // * Gets parent context // * // * Returns a parent context, or null if current context is global // * // * @return parent context // */ // Context getParent(); // // /** // * Gets global context // * // * Returns the global (ancestral) context // * // * @return global context // */ // Context getGlobal(); // // /** // * Puts name and value of property into the current context // * // * @param name name of property // * @param value value of property // */ // void setProperty(String name, Object value); // // /** // * Gets a value of a property given a name // * // * Note that if name is not found in the current context, the expected behavior is to // * recursively search in paren context. Null is returned only if name is not found in // * any context. // * // * @param name name of property // * @return value of property // */ // Object getProperty(String name); // // /** // * Gets a value of a property given a name // * // * Note that if name is not found in the current context, the expected behavior is to // * recursively search in paren context. Null is returned only if name is not found in // * any context. // * // * @param name name of value // * @param type type of value // * @return value // * @throws WrongTypeException // */ // <T> T getProperty(String name, Class<T> type) throws WrongTypeException; // // /** // * Gets time the global instance was created // * // * The time supplied by Env.getCurrentTime() will become the value of global instance time // * when the global context is created from Env. All child contexts under this global context // * will inherit the same global instance time. // * // * @return UTC time in milliseconds // */ // long getGlobalInstanceTime(); // // } // // Path: src/main/java/com/turn/camino/Env.java // public interface Env { // // /** // * Get current time // * // * @return current time in epoch milliseconds // */ // long getCurrentTime(); // // /** // * Get default time zone // * // * @return default time zone // */ // TimeZone getTimeZone(); // // /** // * Get file system // * // * @return Hadoop file system // */ // FileSystem getFileSystem(); // // /** // * Creates new context // * // * @return new global context // */ // Context newContext(); // // /** // * Get renderer // * // * @return new renderer // */ // Renderer getRenderer(); // // /** // * Get executor service // * // * @return executor service // */ // ExecutorService getExecutorService(); // // /** // * Get error handler // * // * @return error handler // */ // ErrorHandler getErrorHandler(); // // } // // Path: src/main/java/com/turn/camino/render/FunctionCallException.java // public class FunctionCallException extends RenderException { // // public FunctionCallException(String message) { // super(message); // } // // public FunctionCallException(Throwable throwable) { // super(throwable); // } // // }
import com.google.common.collect.ImmutableList; import com.turn.camino.Context; import com.turn.camino.Env; import com.turn.camino.render.FunctionCallException; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import java.util.TimeZone; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.testng.Assert.*;
/* * Copyright (C) 2014-2018, Amobee Inc. All Rights Reserved. * * 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 */ package com.turn.camino.render.functions; /** * Unit test for logic functions * * @author llo */ @Test public class LogicFunctionsTest {
// Path: src/main/java/com/turn/camino/Context.java // public interface Context { // // /** // * Get system environment // * // * @return system environment // */ // Env getEnv(); // // /** // * Creates child context // * // * @return new context // */ // Context createChild(); // // /** // * Gets parent context // * // * Returns a parent context, or null if current context is global // * // * @return parent context // */ // Context getParent(); // // /** // * Gets global context // * // * Returns the global (ancestral) context // * // * @return global context // */ // Context getGlobal(); // // /** // * Puts name and value of property into the current context // * // * @param name name of property // * @param value value of property // */ // void setProperty(String name, Object value); // // /** // * Gets a value of a property given a name // * // * Note that if name is not found in the current context, the expected behavior is to // * recursively search in paren context. Null is returned only if name is not found in // * any context. // * // * @param name name of property // * @return value of property // */ // Object getProperty(String name); // // /** // * Gets a value of a property given a name // * // * Note that if name is not found in the current context, the expected behavior is to // * recursively search in paren context. Null is returned only if name is not found in // * any context. // * // * @param name name of value // * @param type type of value // * @return value // * @throws WrongTypeException // */ // <T> T getProperty(String name, Class<T> type) throws WrongTypeException; // // /** // * Gets time the global instance was created // * // * The time supplied by Env.getCurrentTime() will become the value of global instance time // * when the global context is created from Env. All child contexts under this global context // * will inherit the same global instance time. // * // * @return UTC time in milliseconds // */ // long getGlobalInstanceTime(); // // } // // Path: src/main/java/com/turn/camino/Env.java // public interface Env { // // /** // * Get current time // * // * @return current time in epoch milliseconds // */ // long getCurrentTime(); // // /** // * Get default time zone // * // * @return default time zone // */ // TimeZone getTimeZone(); // // /** // * Get file system // * // * @return Hadoop file system // */ // FileSystem getFileSystem(); // // /** // * Creates new context // * // * @return new global context // */ // Context newContext(); // // /** // * Get renderer // * // * @return new renderer // */ // Renderer getRenderer(); // // /** // * Get executor service // * // * @return executor service // */ // ExecutorService getExecutorService(); // // /** // * Get error handler // * // * @return error handler // */ // ErrorHandler getErrorHandler(); // // } // // Path: src/main/java/com/turn/camino/render/FunctionCallException.java // public class FunctionCallException extends RenderException { // // public FunctionCallException(String message) { // super(message); // } // // public FunctionCallException(Throwable throwable) { // super(throwable); // } // // } // Path: src/test/java/com/turn/camino/render/functions/LogicFunctionsTest.java import com.google.common.collect.ImmutableList; import com.turn.camino.Context; import com.turn.camino.Env; import com.turn.camino.render.FunctionCallException; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import java.util.TimeZone; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.testng.Assert.*; /* * Copyright (C) 2014-2018, Amobee Inc. All Rights Reserved. * * 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 */ package com.turn.camino.render.functions; /** * Unit test for logic functions * * @author llo */ @Test public class LogicFunctionsTest {
private Context context;
turn/camino
src/test/java/com/turn/camino/render/functions/LogicFunctionsTest.java
// Path: src/main/java/com/turn/camino/Context.java // public interface Context { // // /** // * Get system environment // * // * @return system environment // */ // Env getEnv(); // // /** // * Creates child context // * // * @return new context // */ // Context createChild(); // // /** // * Gets parent context // * // * Returns a parent context, or null if current context is global // * // * @return parent context // */ // Context getParent(); // // /** // * Gets global context // * // * Returns the global (ancestral) context // * // * @return global context // */ // Context getGlobal(); // // /** // * Puts name and value of property into the current context // * // * @param name name of property // * @param value value of property // */ // void setProperty(String name, Object value); // // /** // * Gets a value of a property given a name // * // * Note that if name is not found in the current context, the expected behavior is to // * recursively search in paren context. Null is returned only if name is not found in // * any context. // * // * @param name name of property // * @return value of property // */ // Object getProperty(String name); // // /** // * Gets a value of a property given a name // * // * Note that if name is not found in the current context, the expected behavior is to // * recursively search in paren context. Null is returned only if name is not found in // * any context. // * // * @param name name of value // * @param type type of value // * @return value // * @throws WrongTypeException // */ // <T> T getProperty(String name, Class<T> type) throws WrongTypeException; // // /** // * Gets time the global instance was created // * // * The time supplied by Env.getCurrentTime() will become the value of global instance time // * when the global context is created from Env. All child contexts under this global context // * will inherit the same global instance time. // * // * @return UTC time in milliseconds // */ // long getGlobalInstanceTime(); // // } // // Path: src/main/java/com/turn/camino/Env.java // public interface Env { // // /** // * Get current time // * // * @return current time in epoch milliseconds // */ // long getCurrentTime(); // // /** // * Get default time zone // * // * @return default time zone // */ // TimeZone getTimeZone(); // // /** // * Get file system // * // * @return Hadoop file system // */ // FileSystem getFileSystem(); // // /** // * Creates new context // * // * @return new global context // */ // Context newContext(); // // /** // * Get renderer // * // * @return new renderer // */ // Renderer getRenderer(); // // /** // * Get executor service // * // * @return executor service // */ // ExecutorService getExecutorService(); // // /** // * Get error handler // * // * @return error handler // */ // ErrorHandler getErrorHandler(); // // } // // Path: src/main/java/com/turn/camino/render/FunctionCallException.java // public class FunctionCallException extends RenderException { // // public FunctionCallException(String message) { // super(message); // } // // public FunctionCallException(Throwable throwable) { // super(throwable); // } // // }
import com.google.common.collect.ImmutableList; import com.turn.camino.Context; import com.turn.camino.Env; import com.turn.camino.render.FunctionCallException; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import java.util.TimeZone; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.testng.Assert.*;
/* * Copyright (C) 2014-2018, Amobee Inc. All Rights Reserved. * * 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 */ package com.turn.camino.render.functions; /** * Unit test for logic functions * * @author llo */ @Test public class LogicFunctionsTest { private Context context; private final LogicFunctions.Eq eq = new LogicFunctions.Eq(); private final LogicFunctions.Ne ne = new LogicFunctions.Ne(); private final LogicFunctions.Lt lt = new LogicFunctions.Lt(); private final LogicFunctions.Gt gt = new LogicFunctions.Gt(); private final LogicFunctions.LtEq ltEq = new LogicFunctions.LtEq(); private final LogicFunctions.GtEq gtEq = new LogicFunctions.GtEq(); private final LogicFunctions.Not not = new LogicFunctions.Not(); /** * Set up environment */ @BeforeClass public void setUp() { // mock environment context = mock(Context.class);
// Path: src/main/java/com/turn/camino/Context.java // public interface Context { // // /** // * Get system environment // * // * @return system environment // */ // Env getEnv(); // // /** // * Creates child context // * // * @return new context // */ // Context createChild(); // // /** // * Gets parent context // * // * Returns a parent context, or null if current context is global // * // * @return parent context // */ // Context getParent(); // // /** // * Gets global context // * // * Returns the global (ancestral) context // * // * @return global context // */ // Context getGlobal(); // // /** // * Puts name and value of property into the current context // * // * @param name name of property // * @param value value of property // */ // void setProperty(String name, Object value); // // /** // * Gets a value of a property given a name // * // * Note that if name is not found in the current context, the expected behavior is to // * recursively search in paren context. Null is returned only if name is not found in // * any context. // * // * @param name name of property // * @return value of property // */ // Object getProperty(String name); // // /** // * Gets a value of a property given a name // * // * Note that if name is not found in the current context, the expected behavior is to // * recursively search in paren context. Null is returned only if name is not found in // * any context. // * // * @param name name of value // * @param type type of value // * @return value // * @throws WrongTypeException // */ // <T> T getProperty(String name, Class<T> type) throws WrongTypeException; // // /** // * Gets time the global instance was created // * // * The time supplied by Env.getCurrentTime() will become the value of global instance time // * when the global context is created from Env. All child contexts under this global context // * will inherit the same global instance time. // * // * @return UTC time in milliseconds // */ // long getGlobalInstanceTime(); // // } // // Path: src/main/java/com/turn/camino/Env.java // public interface Env { // // /** // * Get current time // * // * @return current time in epoch milliseconds // */ // long getCurrentTime(); // // /** // * Get default time zone // * // * @return default time zone // */ // TimeZone getTimeZone(); // // /** // * Get file system // * // * @return Hadoop file system // */ // FileSystem getFileSystem(); // // /** // * Creates new context // * // * @return new global context // */ // Context newContext(); // // /** // * Get renderer // * // * @return new renderer // */ // Renderer getRenderer(); // // /** // * Get executor service // * // * @return executor service // */ // ExecutorService getExecutorService(); // // /** // * Get error handler // * // * @return error handler // */ // ErrorHandler getErrorHandler(); // // } // // Path: src/main/java/com/turn/camino/render/FunctionCallException.java // public class FunctionCallException extends RenderException { // // public FunctionCallException(String message) { // super(message); // } // // public FunctionCallException(Throwable throwable) { // super(throwable); // } // // } // Path: src/test/java/com/turn/camino/render/functions/LogicFunctionsTest.java import com.google.common.collect.ImmutableList; import com.turn.camino.Context; import com.turn.camino.Env; import com.turn.camino.render.FunctionCallException; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import java.util.TimeZone; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.testng.Assert.*; /* * Copyright (C) 2014-2018, Amobee Inc. All Rights Reserved. * * 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 */ package com.turn.camino.render.functions; /** * Unit test for logic functions * * @author llo */ @Test public class LogicFunctionsTest { private Context context; private final LogicFunctions.Eq eq = new LogicFunctions.Eq(); private final LogicFunctions.Ne ne = new LogicFunctions.Ne(); private final LogicFunctions.Lt lt = new LogicFunctions.Lt(); private final LogicFunctions.Gt gt = new LogicFunctions.Gt(); private final LogicFunctions.LtEq ltEq = new LogicFunctions.LtEq(); private final LogicFunctions.GtEq gtEq = new LogicFunctions.GtEq(); private final LogicFunctions.Not not = new LogicFunctions.Not(); /** * Set up environment */ @BeforeClass public void setUp() { // mock environment context = mock(Context.class);
Env env = mock(Env.class);
turn/camino
src/test/java/com/turn/camino/render/functions/LogicFunctionsTest.java
// Path: src/main/java/com/turn/camino/Context.java // public interface Context { // // /** // * Get system environment // * // * @return system environment // */ // Env getEnv(); // // /** // * Creates child context // * // * @return new context // */ // Context createChild(); // // /** // * Gets parent context // * // * Returns a parent context, or null if current context is global // * // * @return parent context // */ // Context getParent(); // // /** // * Gets global context // * // * Returns the global (ancestral) context // * // * @return global context // */ // Context getGlobal(); // // /** // * Puts name and value of property into the current context // * // * @param name name of property // * @param value value of property // */ // void setProperty(String name, Object value); // // /** // * Gets a value of a property given a name // * // * Note that if name is not found in the current context, the expected behavior is to // * recursively search in paren context. Null is returned only if name is not found in // * any context. // * // * @param name name of property // * @return value of property // */ // Object getProperty(String name); // // /** // * Gets a value of a property given a name // * // * Note that if name is not found in the current context, the expected behavior is to // * recursively search in paren context. Null is returned only if name is not found in // * any context. // * // * @param name name of value // * @param type type of value // * @return value // * @throws WrongTypeException // */ // <T> T getProperty(String name, Class<T> type) throws WrongTypeException; // // /** // * Gets time the global instance was created // * // * The time supplied by Env.getCurrentTime() will become the value of global instance time // * when the global context is created from Env. All child contexts under this global context // * will inherit the same global instance time. // * // * @return UTC time in milliseconds // */ // long getGlobalInstanceTime(); // // } // // Path: src/main/java/com/turn/camino/Env.java // public interface Env { // // /** // * Get current time // * // * @return current time in epoch milliseconds // */ // long getCurrentTime(); // // /** // * Get default time zone // * // * @return default time zone // */ // TimeZone getTimeZone(); // // /** // * Get file system // * // * @return Hadoop file system // */ // FileSystem getFileSystem(); // // /** // * Creates new context // * // * @return new global context // */ // Context newContext(); // // /** // * Get renderer // * // * @return new renderer // */ // Renderer getRenderer(); // // /** // * Get executor service // * // * @return executor service // */ // ExecutorService getExecutorService(); // // /** // * Get error handler // * // * @return error handler // */ // ErrorHandler getErrorHandler(); // // } // // Path: src/main/java/com/turn/camino/render/FunctionCallException.java // public class FunctionCallException extends RenderException { // // public FunctionCallException(String message) { // super(message); // } // // public FunctionCallException(Throwable throwable) { // super(throwable); // } // // }
import com.google.common.collect.ImmutableList; import com.turn.camino.Context; import com.turn.camino.Env; import com.turn.camino.render.FunctionCallException; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import java.util.TimeZone; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.testng.Assert.*;
/* * Copyright (C) 2014-2018, Amobee Inc. All Rights Reserved. * * 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 */ package com.turn.camino.render.functions; /** * Unit test for logic functions * * @author llo */ @Test public class LogicFunctionsTest { private Context context; private final LogicFunctions.Eq eq = new LogicFunctions.Eq(); private final LogicFunctions.Ne ne = new LogicFunctions.Ne(); private final LogicFunctions.Lt lt = new LogicFunctions.Lt(); private final LogicFunctions.Gt gt = new LogicFunctions.Gt(); private final LogicFunctions.LtEq ltEq = new LogicFunctions.LtEq(); private final LogicFunctions.GtEq gtEq = new LogicFunctions.GtEq(); private final LogicFunctions.Not not = new LogicFunctions.Not(); /** * Set up environment */ @BeforeClass public void setUp() { // mock environment context = mock(Context.class); Env env = mock(Env.class); when(context.getEnv()).thenReturn(env); when(env.getCurrentTime()).thenReturn(1409389256296L); when(env.getTimeZone()).thenReturn(TimeZone.getTimeZone("GMT")); } /** * Test equal function * * @throws FunctionCallException */ @Test
// Path: src/main/java/com/turn/camino/Context.java // public interface Context { // // /** // * Get system environment // * // * @return system environment // */ // Env getEnv(); // // /** // * Creates child context // * // * @return new context // */ // Context createChild(); // // /** // * Gets parent context // * // * Returns a parent context, or null if current context is global // * // * @return parent context // */ // Context getParent(); // // /** // * Gets global context // * // * Returns the global (ancestral) context // * // * @return global context // */ // Context getGlobal(); // // /** // * Puts name and value of property into the current context // * // * @param name name of property // * @param value value of property // */ // void setProperty(String name, Object value); // // /** // * Gets a value of a property given a name // * // * Note that if name is not found in the current context, the expected behavior is to // * recursively search in paren context. Null is returned only if name is not found in // * any context. // * // * @param name name of property // * @return value of property // */ // Object getProperty(String name); // // /** // * Gets a value of a property given a name // * // * Note that if name is not found in the current context, the expected behavior is to // * recursively search in paren context. Null is returned only if name is not found in // * any context. // * // * @param name name of value // * @param type type of value // * @return value // * @throws WrongTypeException // */ // <T> T getProperty(String name, Class<T> type) throws WrongTypeException; // // /** // * Gets time the global instance was created // * // * The time supplied by Env.getCurrentTime() will become the value of global instance time // * when the global context is created from Env. All child contexts under this global context // * will inherit the same global instance time. // * // * @return UTC time in milliseconds // */ // long getGlobalInstanceTime(); // // } // // Path: src/main/java/com/turn/camino/Env.java // public interface Env { // // /** // * Get current time // * // * @return current time in epoch milliseconds // */ // long getCurrentTime(); // // /** // * Get default time zone // * // * @return default time zone // */ // TimeZone getTimeZone(); // // /** // * Get file system // * // * @return Hadoop file system // */ // FileSystem getFileSystem(); // // /** // * Creates new context // * // * @return new global context // */ // Context newContext(); // // /** // * Get renderer // * // * @return new renderer // */ // Renderer getRenderer(); // // /** // * Get executor service // * // * @return executor service // */ // ExecutorService getExecutorService(); // // /** // * Get error handler // * // * @return error handler // */ // ErrorHandler getErrorHandler(); // // } // // Path: src/main/java/com/turn/camino/render/FunctionCallException.java // public class FunctionCallException extends RenderException { // // public FunctionCallException(String message) { // super(message); // } // // public FunctionCallException(Throwable throwable) { // super(throwable); // } // // } // Path: src/test/java/com/turn/camino/render/functions/LogicFunctionsTest.java import com.google.common.collect.ImmutableList; import com.turn.camino.Context; import com.turn.camino.Env; import com.turn.camino.render.FunctionCallException; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import java.util.TimeZone; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.testng.Assert.*; /* * Copyright (C) 2014-2018, Amobee Inc. All Rights Reserved. * * 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 */ package com.turn.camino.render.functions; /** * Unit test for logic functions * * @author llo */ @Test public class LogicFunctionsTest { private Context context; private final LogicFunctions.Eq eq = new LogicFunctions.Eq(); private final LogicFunctions.Ne ne = new LogicFunctions.Ne(); private final LogicFunctions.Lt lt = new LogicFunctions.Lt(); private final LogicFunctions.Gt gt = new LogicFunctions.Gt(); private final LogicFunctions.LtEq ltEq = new LogicFunctions.LtEq(); private final LogicFunctions.GtEq gtEq = new LogicFunctions.GtEq(); private final LogicFunctions.Not not = new LogicFunctions.Not(); /** * Set up environment */ @BeforeClass public void setUp() { // mock environment context = mock(Context.class); Env env = mock(Env.class); when(context.getEnv()).thenReturn(env); when(env.getCurrentTime()).thenReturn(1409389256296L); when(env.getTimeZone()).thenReturn(TimeZone.getTimeZone("GMT")); } /** * Test equal function * * @throws FunctionCallException */ @Test
public void testEq() throws FunctionCallException {
turn/camino
src/test/java/com/turn/camino/render/functions/CollectionFunctionsTest.java
// Path: src/main/java/com/turn/camino/Context.java // public interface Context { // // /** // * Get system environment // * // * @return system environment // */ // Env getEnv(); // // /** // * Creates child context // * // * @return new context // */ // Context createChild(); // // /** // * Gets parent context // * // * Returns a parent context, or null if current context is global // * // * @return parent context // */ // Context getParent(); // // /** // * Gets global context // * // * Returns the global (ancestral) context // * // * @return global context // */ // Context getGlobal(); // // /** // * Puts name and value of property into the current context // * // * @param name name of property // * @param value value of property // */ // void setProperty(String name, Object value); // // /** // * Gets a value of a property given a name // * // * Note that if name is not found in the current context, the expected behavior is to // * recursively search in paren context. Null is returned only if name is not found in // * any context. // * // * @param name name of property // * @return value of property // */ // Object getProperty(String name); // // /** // * Gets a value of a property given a name // * // * Note that if name is not found in the current context, the expected behavior is to // * recursively search in paren context. Null is returned only if name is not found in // * any context. // * // * @param name name of value // * @param type type of value // * @return value // * @throws WrongTypeException // */ // <T> T getProperty(String name, Class<T> type) throws WrongTypeException; // // /** // * Gets time the global instance was created // * // * The time supplied by Env.getCurrentTime() will become the value of global instance time // * when the global context is created from Env. All child contexts under this global context // * will inherit the same global instance time. // * // * @return UTC time in milliseconds // */ // long getGlobalInstanceTime(); // // } // // Path: src/main/java/com/turn/camino/Env.java // public interface Env { // // /** // * Get current time // * // * @return current time in epoch milliseconds // */ // long getCurrentTime(); // // /** // * Get default time zone // * // * @return default time zone // */ // TimeZone getTimeZone(); // // /** // * Get file system // * // * @return Hadoop file system // */ // FileSystem getFileSystem(); // // /** // * Creates new context // * // * @return new global context // */ // Context newContext(); // // /** // * Get renderer // * // * @return new renderer // */ // Renderer getRenderer(); // // /** // * Get executor service // * // * @return executor service // */ // ExecutorService getExecutorService(); // // /** // * Get error handler // * // * @return error handler // */ // ErrorHandler getErrorHandler(); // // } // // Path: src/main/java/com/turn/camino/render/Function.java // public interface Function { // // /** // * Invokes function with given parameters and context // * // * @param params actual parameters to function call // * @param context context in which the function operates // * @return return value of function // * @throws FunctionCallException // */ // Object invoke(List<?> params, Context context) throws FunctionCallException; // // } // // Path: src/main/java/com/turn/camino/render/FunctionCallException.java // public class FunctionCallException extends RenderException { // // public FunctionCallException(String message) { // super(message); // } // // public FunctionCallException(Throwable throwable) { // super(throwable); // } // // }
import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; import com.google.common.collect.ImmutableMap; import com.turn.camino.Context; import com.turn.camino.Env; import com.turn.camino.render.Function; import com.turn.camino.render.FunctionCallException; import java.util.List; import java.util.Map; import java.util.TimeZone; import com.google.common.collect.ImmutableList; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when;
/* * Copyright (C) 2014-2018, Amobee Inc. All Rights Reserved. * * 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 */ package com.turn.camino.render.functions; /** * Unit test for CollectionFunctions * * @author llo */ @Test public class CollectionFunctionsTest {
// Path: src/main/java/com/turn/camino/Context.java // public interface Context { // // /** // * Get system environment // * // * @return system environment // */ // Env getEnv(); // // /** // * Creates child context // * // * @return new context // */ // Context createChild(); // // /** // * Gets parent context // * // * Returns a parent context, or null if current context is global // * // * @return parent context // */ // Context getParent(); // // /** // * Gets global context // * // * Returns the global (ancestral) context // * // * @return global context // */ // Context getGlobal(); // // /** // * Puts name and value of property into the current context // * // * @param name name of property // * @param value value of property // */ // void setProperty(String name, Object value); // // /** // * Gets a value of a property given a name // * // * Note that if name is not found in the current context, the expected behavior is to // * recursively search in paren context. Null is returned only if name is not found in // * any context. // * // * @param name name of property // * @return value of property // */ // Object getProperty(String name); // // /** // * Gets a value of a property given a name // * // * Note that if name is not found in the current context, the expected behavior is to // * recursively search in paren context. Null is returned only if name is not found in // * any context. // * // * @param name name of value // * @param type type of value // * @return value // * @throws WrongTypeException // */ // <T> T getProperty(String name, Class<T> type) throws WrongTypeException; // // /** // * Gets time the global instance was created // * // * The time supplied by Env.getCurrentTime() will become the value of global instance time // * when the global context is created from Env. All child contexts under this global context // * will inherit the same global instance time. // * // * @return UTC time in milliseconds // */ // long getGlobalInstanceTime(); // // } // // Path: src/main/java/com/turn/camino/Env.java // public interface Env { // // /** // * Get current time // * // * @return current time in epoch milliseconds // */ // long getCurrentTime(); // // /** // * Get default time zone // * // * @return default time zone // */ // TimeZone getTimeZone(); // // /** // * Get file system // * // * @return Hadoop file system // */ // FileSystem getFileSystem(); // // /** // * Creates new context // * // * @return new global context // */ // Context newContext(); // // /** // * Get renderer // * // * @return new renderer // */ // Renderer getRenderer(); // // /** // * Get executor service // * // * @return executor service // */ // ExecutorService getExecutorService(); // // /** // * Get error handler // * // * @return error handler // */ // ErrorHandler getErrorHandler(); // // } // // Path: src/main/java/com/turn/camino/render/Function.java // public interface Function { // // /** // * Invokes function with given parameters and context // * // * @param params actual parameters to function call // * @param context context in which the function operates // * @return return value of function // * @throws FunctionCallException // */ // Object invoke(List<?> params, Context context) throws FunctionCallException; // // } // // Path: src/main/java/com/turn/camino/render/FunctionCallException.java // public class FunctionCallException extends RenderException { // // public FunctionCallException(String message) { // super(message); // } // // public FunctionCallException(Throwable throwable) { // super(throwable); // } // // } // Path: src/test/java/com/turn/camino/render/functions/CollectionFunctionsTest.java import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; import com.google.common.collect.ImmutableMap; import com.turn.camino.Context; import com.turn.camino.Env; import com.turn.camino.render.Function; import com.turn.camino.render.FunctionCallException; import java.util.List; import java.util.Map; import java.util.TimeZone; import com.google.common.collect.ImmutableList; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /* * Copyright (C) 2014-2018, Amobee Inc. All Rights Reserved. * * 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 */ package com.turn.camino.render.functions; /** * Unit test for CollectionFunctions * * @author llo */ @Test public class CollectionFunctionsTest {
private Context context;
turn/camino
src/test/java/com/turn/camino/render/functions/CollectionFunctionsTest.java
// Path: src/main/java/com/turn/camino/Context.java // public interface Context { // // /** // * Get system environment // * // * @return system environment // */ // Env getEnv(); // // /** // * Creates child context // * // * @return new context // */ // Context createChild(); // // /** // * Gets parent context // * // * Returns a parent context, or null if current context is global // * // * @return parent context // */ // Context getParent(); // // /** // * Gets global context // * // * Returns the global (ancestral) context // * // * @return global context // */ // Context getGlobal(); // // /** // * Puts name and value of property into the current context // * // * @param name name of property // * @param value value of property // */ // void setProperty(String name, Object value); // // /** // * Gets a value of a property given a name // * // * Note that if name is not found in the current context, the expected behavior is to // * recursively search in paren context. Null is returned only if name is not found in // * any context. // * // * @param name name of property // * @return value of property // */ // Object getProperty(String name); // // /** // * Gets a value of a property given a name // * // * Note that if name is not found in the current context, the expected behavior is to // * recursively search in paren context. Null is returned only if name is not found in // * any context. // * // * @param name name of value // * @param type type of value // * @return value // * @throws WrongTypeException // */ // <T> T getProperty(String name, Class<T> type) throws WrongTypeException; // // /** // * Gets time the global instance was created // * // * The time supplied by Env.getCurrentTime() will become the value of global instance time // * when the global context is created from Env. All child contexts under this global context // * will inherit the same global instance time. // * // * @return UTC time in milliseconds // */ // long getGlobalInstanceTime(); // // } // // Path: src/main/java/com/turn/camino/Env.java // public interface Env { // // /** // * Get current time // * // * @return current time in epoch milliseconds // */ // long getCurrentTime(); // // /** // * Get default time zone // * // * @return default time zone // */ // TimeZone getTimeZone(); // // /** // * Get file system // * // * @return Hadoop file system // */ // FileSystem getFileSystem(); // // /** // * Creates new context // * // * @return new global context // */ // Context newContext(); // // /** // * Get renderer // * // * @return new renderer // */ // Renderer getRenderer(); // // /** // * Get executor service // * // * @return executor service // */ // ExecutorService getExecutorService(); // // /** // * Get error handler // * // * @return error handler // */ // ErrorHandler getErrorHandler(); // // } // // Path: src/main/java/com/turn/camino/render/Function.java // public interface Function { // // /** // * Invokes function with given parameters and context // * // * @param params actual parameters to function call // * @param context context in which the function operates // * @return return value of function // * @throws FunctionCallException // */ // Object invoke(List<?> params, Context context) throws FunctionCallException; // // } // // Path: src/main/java/com/turn/camino/render/FunctionCallException.java // public class FunctionCallException extends RenderException { // // public FunctionCallException(String message) { // super(message); // } // // public FunctionCallException(Throwable throwable) { // super(throwable); // } // // }
import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; import com.google.common.collect.ImmutableMap; import com.turn.camino.Context; import com.turn.camino.Env; import com.turn.camino.render.Function; import com.turn.camino.render.FunctionCallException; import java.util.List; import java.util.Map; import java.util.TimeZone; import com.google.common.collect.ImmutableList; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when;
/** * Test sort function * * @throws FunctionCallException */ @Test @SuppressWarnings("unchecked") public void testSort() throws FunctionCallException { List<String> list = ImmutableList.of("k", "n", "a", "v", "e"); Object result = sort.invoke(ImmutableList.of(list), context); assertTrue(result instanceof List); List<String> sortedList = (List<String>) result; assertEquals(sortedList.size(), 5); assertEquals(sortedList.get(0), "a"); assertEquals(sortedList.get(1), "e"); assertEquals(sortedList.get(2), "k"); assertEquals(sortedList.get(3), "n"); assertEquals(sortedList.get(4), "v"); } /** * Test sort function * * @throws FunctionCallException */ @Test @SuppressWarnings("unchecked") public void testSortWithComparator() throws FunctionCallException {
// Path: src/main/java/com/turn/camino/Context.java // public interface Context { // // /** // * Get system environment // * // * @return system environment // */ // Env getEnv(); // // /** // * Creates child context // * // * @return new context // */ // Context createChild(); // // /** // * Gets parent context // * // * Returns a parent context, or null if current context is global // * // * @return parent context // */ // Context getParent(); // // /** // * Gets global context // * // * Returns the global (ancestral) context // * // * @return global context // */ // Context getGlobal(); // // /** // * Puts name and value of property into the current context // * // * @param name name of property // * @param value value of property // */ // void setProperty(String name, Object value); // // /** // * Gets a value of a property given a name // * // * Note that if name is not found in the current context, the expected behavior is to // * recursively search in paren context. Null is returned only if name is not found in // * any context. // * // * @param name name of property // * @return value of property // */ // Object getProperty(String name); // // /** // * Gets a value of a property given a name // * // * Note that if name is not found in the current context, the expected behavior is to // * recursively search in paren context. Null is returned only if name is not found in // * any context. // * // * @param name name of value // * @param type type of value // * @return value // * @throws WrongTypeException // */ // <T> T getProperty(String name, Class<T> type) throws WrongTypeException; // // /** // * Gets time the global instance was created // * // * The time supplied by Env.getCurrentTime() will become the value of global instance time // * when the global context is created from Env. All child contexts under this global context // * will inherit the same global instance time. // * // * @return UTC time in milliseconds // */ // long getGlobalInstanceTime(); // // } // // Path: src/main/java/com/turn/camino/Env.java // public interface Env { // // /** // * Get current time // * // * @return current time in epoch milliseconds // */ // long getCurrentTime(); // // /** // * Get default time zone // * // * @return default time zone // */ // TimeZone getTimeZone(); // // /** // * Get file system // * // * @return Hadoop file system // */ // FileSystem getFileSystem(); // // /** // * Creates new context // * // * @return new global context // */ // Context newContext(); // // /** // * Get renderer // * // * @return new renderer // */ // Renderer getRenderer(); // // /** // * Get executor service // * // * @return executor service // */ // ExecutorService getExecutorService(); // // /** // * Get error handler // * // * @return error handler // */ // ErrorHandler getErrorHandler(); // // } // // Path: src/main/java/com/turn/camino/render/Function.java // public interface Function { // // /** // * Invokes function with given parameters and context // * // * @param params actual parameters to function call // * @param context context in which the function operates // * @return return value of function // * @throws FunctionCallException // */ // Object invoke(List<?> params, Context context) throws FunctionCallException; // // } // // Path: src/main/java/com/turn/camino/render/FunctionCallException.java // public class FunctionCallException extends RenderException { // // public FunctionCallException(String message) { // super(message); // } // // public FunctionCallException(Throwable throwable) { // super(throwable); // } // // } // Path: src/test/java/com/turn/camino/render/functions/CollectionFunctionsTest.java import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; import com.google.common.collect.ImmutableMap; import com.turn.camino.Context; import com.turn.camino.Env; import com.turn.camino.render.Function; import com.turn.camino.render.FunctionCallException; import java.util.List; import java.util.Map; import java.util.TimeZone; import com.google.common.collect.ImmutableList; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** * Test sort function * * @throws FunctionCallException */ @Test @SuppressWarnings("unchecked") public void testSort() throws FunctionCallException { List<String> list = ImmutableList.of("k", "n", "a", "v", "e"); Object result = sort.invoke(ImmutableList.of(list), context); assertTrue(result instanceof List); List<String> sortedList = (List<String>) result; assertEquals(sortedList.size(), 5); assertEquals(sortedList.get(0), "a"); assertEquals(sortedList.get(1), "e"); assertEquals(sortedList.get(2), "k"); assertEquals(sortedList.get(3), "n"); assertEquals(sortedList.get(4), "v"); } /** * Test sort function * * @throws FunctionCallException */ @Test @SuppressWarnings("unchecked") public void testSortWithComparator() throws FunctionCallException {
Function comparator = (params, context) -> -1 * ((Integer) FunctionEnum.COMPARE
qqq3/good-weather
app/src/main/java/org/asdtm/goodweather/utils/CityParser.java
// Path: app/src/main/java/org/asdtm/goodweather/model/CitySearch.java // public class CitySearch // { // private String mCityName; // private String mCountry; // private String mLatitude; // private String mLongitude; // private String mCountryCode; // // public CitySearch(){} // public CitySearch(String cityName, String countryCode, String latitude, String longitude) // { // mCityName = cityName; // mCountryCode = countryCode; // mLatitude = latitude; // mLongitude = longitude; // } // // public String getCityName() // { // return mCityName; // } // // public void setCityName(String cityName) // { // mCityName = cityName; // } // // public String getCountry() // { // return mCountry; // } // // public void setCountry(String country) // { // mCountry = country; // } // // public String getLatitude() // { // return mLatitude; // } // // public void setLatitude(String latitude) // { // mLatitude = latitude; // } // // public String getLongitude() // { // return mLongitude; // } // // public void setLongitude(String longitude) // { // mLongitude = longitude; // } // // public String getCountryCode() // { // return mCountryCode; // } // // public void setCountryCode(String countryCode) // { // mCountryCode = countryCode; // } // // @Override // public String toString() // { // return mCityName + ", " + mCountryCode; // } // }
import android.net.Uri; import org.asdtm.goodweather.model.CitySearch; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.List;
package org.asdtm.goodweather.utils; public class CityParser { private static final String TAG = "CityParser"; private static final String ENDPOINT = "http://api.openweathermap.org/data/2.5/find"; private static final String APPID = ApiKeys.OPEN_WEATHER_MAP_API_KEY;
// Path: app/src/main/java/org/asdtm/goodweather/model/CitySearch.java // public class CitySearch // { // private String mCityName; // private String mCountry; // private String mLatitude; // private String mLongitude; // private String mCountryCode; // // public CitySearch(){} // public CitySearch(String cityName, String countryCode, String latitude, String longitude) // { // mCityName = cityName; // mCountryCode = countryCode; // mLatitude = latitude; // mLongitude = longitude; // } // // public String getCityName() // { // return mCityName; // } // // public void setCityName(String cityName) // { // mCityName = cityName; // } // // public String getCountry() // { // return mCountry; // } // // public void setCountry(String country) // { // mCountry = country; // } // // public String getLatitude() // { // return mLatitude; // } // // public void setLatitude(String latitude) // { // mLatitude = latitude; // } // // public String getLongitude() // { // return mLongitude; // } // // public void setLongitude(String longitude) // { // mLongitude = longitude; // } // // public String getCountryCode() // { // return mCountryCode; // } // // public void setCountryCode(String countryCode) // { // mCountryCode = countryCode; // } // // @Override // public String toString() // { // return mCityName + ", " + mCountryCode; // } // } // Path: app/src/main/java/org/asdtm/goodweather/utils/CityParser.java import android.net.Uri; import org.asdtm.goodweather.model.CitySearch; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.List; package org.asdtm.goodweather.utils; public class CityParser { private static final String TAG = "CityParser"; private static final String ENDPOINT = "http://api.openweathermap.org/data/2.5/find"; private static final String APPID = ApiKeys.OPEN_WEATHER_MAP_API_KEY;
public static List<CitySearch> getCity(String query) {
qqq3/good-weather
app/src/main/java/org/asdtm/goodweather/adapter/WeatherForecastAdapter.java
// Path: app/src/main/java/org/asdtm/goodweather/model/WeatherForecast.java // public class WeatherForecast implements Serializable { // // private long dateTime; // private float temperatureMin; // private float temperatureMax; // private float temperatureMorning; // private float temperatureDay; // private float temperatureEvening; // private float temperatureNight; // private String pressure; // private String humidity; // private String icon; // private String description; // private String windSpeed; // private String windDegree; // private String cloudiness; // private String rain; // private String snow; // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description.substring(0, 1).toUpperCase() + description.substring(1); // } // // public long getDateTime() { // return dateTime; // } // // public void setDateTime(long dateTime) { // this.dateTime = dateTime; // } // // public String getHumidity() { // return humidity; // } // // public void setHumidity(String humidity) { // this.humidity = humidity; // } // // public String getIcon() { // return icon; // } // // public void setIcon(String icon) { // this.icon = icon; // } // // public String getPressure() { // return pressure; // } // // public void setPressure(String pressure) { // this.pressure = pressure; // } // // public String getRain() { // return rain; // } // // public void setRain(String rain) { // this.rain = rain; // } // // public String getSnow() { // return snow; // } // // public void setSnow(String snow) { // this.snow = snow; // } // // public String getWindDegree() { // return windDegree; // } // // public void setWindDegree(String windDegree) { // this.windDegree = windDegree; // } // // public String getWindSpeed() { // return windSpeed; // } // // public void setWindSpeed(String windSpeed) { // this.windSpeed = windSpeed; // } // // public String getCloudiness() { // return cloudiness; // } // // public void setCloudiness(String cloudiness) { // this.cloudiness = cloudiness; // } // // public float getTemperatureDay() { // return temperatureDay; // } // // public void setTemperatureDay(float temperatureDay) { // this.temperatureDay = temperatureDay; // } // // public float getTemperatureEvening() { // return temperatureEvening; // } // // public void setTemperatureEvening(float temperatureEvening) { // this.temperatureEvening = temperatureEvening; // } // // public float getTemperatureMax() { // return temperatureMax; // } // // public void setTemperatureMax(float temperatureMax) { // this.temperatureMax = temperatureMax; // } // // public float getTemperatureMin() { // return temperatureMin; // } // // public void setTemperatureMin(float temperatureMin) { // this.temperatureMin = temperatureMin; // } // // public float getTemperatureMorning() { // return temperatureMorning; // } // // public void setTemperatureMorning(float temperatureMorning) { // this.temperatureMorning = temperatureMorning; // } // // public float getTemperatureNight() { // return temperatureNight; // } // // public void setTemperatureNight(float temperatureNight) { // this.temperatureNight = temperatureNight; // } // }
import android.content.Context; import android.support.v4.app.FragmentManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import org.asdtm.goodweather.R; import org.asdtm.goodweather.model.WeatherForecast; import java.util.List;
package org.asdtm.goodweather.adapter; public class WeatherForecastAdapter extends RecyclerView.Adapter<WeatherForecastViewHolder> { private Context mContext;
// Path: app/src/main/java/org/asdtm/goodweather/model/WeatherForecast.java // public class WeatherForecast implements Serializable { // // private long dateTime; // private float temperatureMin; // private float temperatureMax; // private float temperatureMorning; // private float temperatureDay; // private float temperatureEvening; // private float temperatureNight; // private String pressure; // private String humidity; // private String icon; // private String description; // private String windSpeed; // private String windDegree; // private String cloudiness; // private String rain; // private String snow; // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description.substring(0, 1).toUpperCase() + description.substring(1); // } // // public long getDateTime() { // return dateTime; // } // // public void setDateTime(long dateTime) { // this.dateTime = dateTime; // } // // public String getHumidity() { // return humidity; // } // // public void setHumidity(String humidity) { // this.humidity = humidity; // } // // public String getIcon() { // return icon; // } // // public void setIcon(String icon) { // this.icon = icon; // } // // public String getPressure() { // return pressure; // } // // public void setPressure(String pressure) { // this.pressure = pressure; // } // // public String getRain() { // return rain; // } // // public void setRain(String rain) { // this.rain = rain; // } // // public String getSnow() { // return snow; // } // // public void setSnow(String snow) { // this.snow = snow; // } // // public String getWindDegree() { // return windDegree; // } // // public void setWindDegree(String windDegree) { // this.windDegree = windDegree; // } // // public String getWindSpeed() { // return windSpeed; // } // // public void setWindSpeed(String windSpeed) { // this.windSpeed = windSpeed; // } // // public String getCloudiness() { // return cloudiness; // } // // public void setCloudiness(String cloudiness) { // this.cloudiness = cloudiness; // } // // public float getTemperatureDay() { // return temperatureDay; // } // // public void setTemperatureDay(float temperatureDay) { // this.temperatureDay = temperatureDay; // } // // public float getTemperatureEvening() { // return temperatureEvening; // } // // public void setTemperatureEvening(float temperatureEvening) { // this.temperatureEvening = temperatureEvening; // } // // public float getTemperatureMax() { // return temperatureMax; // } // // public void setTemperatureMax(float temperatureMax) { // this.temperatureMax = temperatureMax; // } // // public float getTemperatureMin() { // return temperatureMin; // } // // public void setTemperatureMin(float temperatureMin) { // this.temperatureMin = temperatureMin; // } // // public float getTemperatureMorning() { // return temperatureMorning; // } // // public void setTemperatureMorning(float temperatureMorning) { // this.temperatureMorning = temperatureMorning; // } // // public float getTemperatureNight() { // return temperatureNight; // } // // public void setTemperatureNight(float temperatureNight) { // this.temperatureNight = temperatureNight; // } // } // Path: app/src/main/java/org/asdtm/goodweather/adapter/WeatherForecastAdapter.java import android.content.Context; import android.support.v4.app.FragmentManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import org.asdtm.goodweather.R; import org.asdtm.goodweather.model.WeatherForecast; import java.util.List; package org.asdtm.goodweather.adapter; public class WeatherForecastAdapter extends RecyclerView.Adapter<WeatherForecastViewHolder> { private Context mContext;
private List<WeatherForecast> mWeatherList;
qqq3/good-weather
app/src/main/java/org/asdtm/goodweather/WeatherJSONParser.java
// Path: app/src/main/java/org/asdtm/goodweather/model/CitySearch.java // public class CitySearch // { // private String mCityName; // private String mCountry; // private String mLatitude; // private String mLongitude; // private String mCountryCode; // // public CitySearch(){} // public CitySearch(String cityName, String countryCode, String latitude, String longitude) // { // mCityName = cityName; // mCountryCode = countryCode; // mLatitude = latitude; // mLongitude = longitude; // } // // public String getCityName() // { // return mCityName; // } // // public void setCityName(String cityName) // { // mCityName = cityName; // } // // public String getCountry() // { // return mCountry; // } // // public void setCountry(String country) // { // mCountry = country; // } // // public String getLatitude() // { // return mLatitude; // } // // public void setLatitude(String latitude) // { // mLatitude = latitude; // } // // public String getLongitude() // { // return mLongitude; // } // // public void setLongitude(String longitude) // { // mLongitude = longitude; // } // // public String getCountryCode() // { // return mCountryCode; // } // // public void setCountryCode(String countryCode) // { // mCountryCode = countryCode; // } // // @Override // public String toString() // { // return mCityName + ", " + mCountryCode; // } // } // // Path: app/src/main/java/org/asdtm/goodweather/model/Weather.java // public class Weather { // // public CitySearch location; // public Temperature temperature = new Temperature(); // public Wind wind = new Wind(); // public CurrentWeather currentWeather = new CurrentWeather(); // public CurrentCondition currentCondition = new CurrentCondition(); // public Cloud cloud = new Cloud(); // public Sys sys = new Sys(); // // public class Temperature { // // private float mTemp; // // public float getTemp() { // return mTemp; // } // // public void setTemp(float temp) { // mTemp = temp; // } // } // // public class Wind { // // private float mSpeed; // private float mDirection; // // public float getSpeed() { // return mSpeed; // } // // public void setSpeed(float speed) { // mSpeed = speed; // } // // public float getDirection() { // return mDirection; // } // // public void setDirection(float direction) { // mDirection = direction; // } // } // // public class CurrentWeather { // // private String mDescription; // private String mIdIcon; // // public String getDescription() { // return mDescription; // } // // public void setDescription(String description) { // mDescription = description.substring(0, 1).toUpperCase() + description.substring(1); // } // // public String getIdIcon() { // return mIdIcon; // } // // public void setIdIcon(String idIcon) { // mIdIcon = idIcon; // } // } // // public class CurrentCondition { // // private float mPressure; // private int mHumidity; // // public float getPressure() { // return mPressure; // } // // public void setPressure(float pressure) { // mPressure = pressure; // } // // public int getHumidity() { // return mHumidity; // } // // public void setHumidity(int humidity) { // mHumidity = humidity; // } // } // // public class Cloud { // // private int mClouds; // // public int getClouds() { // return mClouds; // } // // public void setClouds(int clouds) { // mClouds = clouds; // } // } // // public class Sys { // // private long mSunrise; // private long mSunset; // // public long getSunrise() { // return mSunrise; // } // // public void setSunrise(long sunrise) { // mSunrise = sunrise; // } // // public long getSunset() { // return mSunset; // } // // public void setSunset(long sunset) { // mSunset = sunset; // } // } // }
import org.asdtm.goodweather.model.CitySearch; import org.asdtm.goodweather.model.Weather; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject;
package org.asdtm.goodweather; public class WeatherJSONParser { private static final String TAG = "WeatherJSONParser";
// Path: app/src/main/java/org/asdtm/goodweather/model/CitySearch.java // public class CitySearch // { // private String mCityName; // private String mCountry; // private String mLatitude; // private String mLongitude; // private String mCountryCode; // // public CitySearch(){} // public CitySearch(String cityName, String countryCode, String latitude, String longitude) // { // mCityName = cityName; // mCountryCode = countryCode; // mLatitude = latitude; // mLongitude = longitude; // } // // public String getCityName() // { // return mCityName; // } // // public void setCityName(String cityName) // { // mCityName = cityName; // } // // public String getCountry() // { // return mCountry; // } // // public void setCountry(String country) // { // mCountry = country; // } // // public String getLatitude() // { // return mLatitude; // } // // public void setLatitude(String latitude) // { // mLatitude = latitude; // } // // public String getLongitude() // { // return mLongitude; // } // // public void setLongitude(String longitude) // { // mLongitude = longitude; // } // // public String getCountryCode() // { // return mCountryCode; // } // // public void setCountryCode(String countryCode) // { // mCountryCode = countryCode; // } // // @Override // public String toString() // { // return mCityName + ", " + mCountryCode; // } // } // // Path: app/src/main/java/org/asdtm/goodweather/model/Weather.java // public class Weather { // // public CitySearch location; // public Temperature temperature = new Temperature(); // public Wind wind = new Wind(); // public CurrentWeather currentWeather = new CurrentWeather(); // public CurrentCondition currentCondition = new CurrentCondition(); // public Cloud cloud = new Cloud(); // public Sys sys = new Sys(); // // public class Temperature { // // private float mTemp; // // public float getTemp() { // return mTemp; // } // // public void setTemp(float temp) { // mTemp = temp; // } // } // // public class Wind { // // private float mSpeed; // private float mDirection; // // public float getSpeed() { // return mSpeed; // } // // public void setSpeed(float speed) { // mSpeed = speed; // } // // public float getDirection() { // return mDirection; // } // // public void setDirection(float direction) { // mDirection = direction; // } // } // // public class CurrentWeather { // // private String mDescription; // private String mIdIcon; // // public String getDescription() { // return mDescription; // } // // public void setDescription(String description) { // mDescription = description.substring(0, 1).toUpperCase() + description.substring(1); // } // // public String getIdIcon() { // return mIdIcon; // } // // public void setIdIcon(String idIcon) { // mIdIcon = idIcon; // } // } // // public class CurrentCondition { // // private float mPressure; // private int mHumidity; // // public float getPressure() { // return mPressure; // } // // public void setPressure(float pressure) { // mPressure = pressure; // } // // public int getHumidity() { // return mHumidity; // } // // public void setHumidity(int humidity) { // mHumidity = humidity; // } // } // // public class Cloud { // // private int mClouds; // // public int getClouds() { // return mClouds; // } // // public void setClouds(int clouds) { // mClouds = clouds; // } // } // // public class Sys { // // private long mSunrise; // private long mSunset; // // public long getSunrise() { // return mSunrise; // } // // public void setSunrise(long sunrise) { // mSunrise = sunrise; // } // // public long getSunset() { // return mSunset; // } // // public void setSunset(long sunset) { // mSunset = sunset; // } // } // } // Path: app/src/main/java/org/asdtm/goodweather/WeatherJSONParser.java import org.asdtm.goodweather.model.CitySearch; import org.asdtm.goodweather.model.Weather; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; package org.asdtm.goodweather; public class WeatherJSONParser { private static final String TAG = "WeatherJSONParser";
public static Weather getWeather(String data) throws JSONException {
qqq3/good-weather
app/src/main/java/org/asdtm/goodweather/WeatherJSONParser.java
// Path: app/src/main/java/org/asdtm/goodweather/model/CitySearch.java // public class CitySearch // { // private String mCityName; // private String mCountry; // private String mLatitude; // private String mLongitude; // private String mCountryCode; // // public CitySearch(){} // public CitySearch(String cityName, String countryCode, String latitude, String longitude) // { // mCityName = cityName; // mCountryCode = countryCode; // mLatitude = latitude; // mLongitude = longitude; // } // // public String getCityName() // { // return mCityName; // } // // public void setCityName(String cityName) // { // mCityName = cityName; // } // // public String getCountry() // { // return mCountry; // } // // public void setCountry(String country) // { // mCountry = country; // } // // public String getLatitude() // { // return mLatitude; // } // // public void setLatitude(String latitude) // { // mLatitude = latitude; // } // // public String getLongitude() // { // return mLongitude; // } // // public void setLongitude(String longitude) // { // mLongitude = longitude; // } // // public String getCountryCode() // { // return mCountryCode; // } // // public void setCountryCode(String countryCode) // { // mCountryCode = countryCode; // } // // @Override // public String toString() // { // return mCityName + ", " + mCountryCode; // } // } // // Path: app/src/main/java/org/asdtm/goodweather/model/Weather.java // public class Weather { // // public CitySearch location; // public Temperature temperature = new Temperature(); // public Wind wind = new Wind(); // public CurrentWeather currentWeather = new CurrentWeather(); // public CurrentCondition currentCondition = new CurrentCondition(); // public Cloud cloud = new Cloud(); // public Sys sys = new Sys(); // // public class Temperature { // // private float mTemp; // // public float getTemp() { // return mTemp; // } // // public void setTemp(float temp) { // mTemp = temp; // } // } // // public class Wind { // // private float mSpeed; // private float mDirection; // // public float getSpeed() { // return mSpeed; // } // // public void setSpeed(float speed) { // mSpeed = speed; // } // // public float getDirection() { // return mDirection; // } // // public void setDirection(float direction) { // mDirection = direction; // } // } // // public class CurrentWeather { // // private String mDescription; // private String mIdIcon; // // public String getDescription() { // return mDescription; // } // // public void setDescription(String description) { // mDescription = description.substring(0, 1).toUpperCase() + description.substring(1); // } // // public String getIdIcon() { // return mIdIcon; // } // // public void setIdIcon(String idIcon) { // mIdIcon = idIcon; // } // } // // public class CurrentCondition { // // private float mPressure; // private int mHumidity; // // public float getPressure() { // return mPressure; // } // // public void setPressure(float pressure) { // mPressure = pressure; // } // // public int getHumidity() { // return mHumidity; // } // // public void setHumidity(int humidity) { // mHumidity = humidity; // } // } // // public class Cloud { // // private int mClouds; // // public int getClouds() { // return mClouds; // } // // public void setClouds(int clouds) { // mClouds = clouds; // } // } // // public class Sys { // // private long mSunrise; // private long mSunset; // // public long getSunrise() { // return mSunrise; // } // // public void setSunrise(long sunrise) { // mSunrise = sunrise; // } // // public long getSunset() { // return mSunset; // } // // public void setSunset(long sunset) { // mSunset = sunset; // } // } // }
import org.asdtm.goodweather.model.CitySearch; import org.asdtm.goodweather.model.Weather; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject;
package org.asdtm.goodweather; public class WeatherJSONParser { private static final String TAG = "WeatherJSONParser"; public static Weather getWeather(String data) throws JSONException { Weather weather = new Weather();
// Path: app/src/main/java/org/asdtm/goodweather/model/CitySearch.java // public class CitySearch // { // private String mCityName; // private String mCountry; // private String mLatitude; // private String mLongitude; // private String mCountryCode; // // public CitySearch(){} // public CitySearch(String cityName, String countryCode, String latitude, String longitude) // { // mCityName = cityName; // mCountryCode = countryCode; // mLatitude = latitude; // mLongitude = longitude; // } // // public String getCityName() // { // return mCityName; // } // // public void setCityName(String cityName) // { // mCityName = cityName; // } // // public String getCountry() // { // return mCountry; // } // // public void setCountry(String country) // { // mCountry = country; // } // // public String getLatitude() // { // return mLatitude; // } // // public void setLatitude(String latitude) // { // mLatitude = latitude; // } // // public String getLongitude() // { // return mLongitude; // } // // public void setLongitude(String longitude) // { // mLongitude = longitude; // } // // public String getCountryCode() // { // return mCountryCode; // } // // public void setCountryCode(String countryCode) // { // mCountryCode = countryCode; // } // // @Override // public String toString() // { // return mCityName + ", " + mCountryCode; // } // } // // Path: app/src/main/java/org/asdtm/goodweather/model/Weather.java // public class Weather { // // public CitySearch location; // public Temperature temperature = new Temperature(); // public Wind wind = new Wind(); // public CurrentWeather currentWeather = new CurrentWeather(); // public CurrentCondition currentCondition = new CurrentCondition(); // public Cloud cloud = new Cloud(); // public Sys sys = new Sys(); // // public class Temperature { // // private float mTemp; // // public float getTemp() { // return mTemp; // } // // public void setTemp(float temp) { // mTemp = temp; // } // } // // public class Wind { // // private float mSpeed; // private float mDirection; // // public float getSpeed() { // return mSpeed; // } // // public void setSpeed(float speed) { // mSpeed = speed; // } // // public float getDirection() { // return mDirection; // } // // public void setDirection(float direction) { // mDirection = direction; // } // } // // public class CurrentWeather { // // private String mDescription; // private String mIdIcon; // // public String getDescription() { // return mDescription; // } // // public void setDescription(String description) { // mDescription = description.substring(0, 1).toUpperCase() + description.substring(1); // } // // public String getIdIcon() { // return mIdIcon; // } // // public void setIdIcon(String idIcon) { // mIdIcon = idIcon; // } // } // // public class CurrentCondition { // // private float mPressure; // private int mHumidity; // // public float getPressure() { // return mPressure; // } // // public void setPressure(float pressure) { // mPressure = pressure; // } // // public int getHumidity() { // return mHumidity; // } // // public void setHumidity(int humidity) { // mHumidity = humidity; // } // } // // public class Cloud { // // private int mClouds; // // public int getClouds() { // return mClouds; // } // // public void setClouds(int clouds) { // mClouds = clouds; // } // } // // public class Sys { // // private long mSunrise; // private long mSunset; // // public long getSunrise() { // return mSunrise; // } // // public void setSunrise(long sunrise) { // mSunrise = sunrise; // } // // public long getSunset() { // return mSunset; // } // // public void setSunset(long sunset) { // mSunset = sunset; // } // } // } // Path: app/src/main/java/org/asdtm/goodweather/WeatherJSONParser.java import org.asdtm.goodweather.model.CitySearch; import org.asdtm.goodweather.model.Weather; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; package org.asdtm.goodweather; public class WeatherJSONParser { private static final String TAG = "WeatherJSONParser"; public static Weather getWeather(String data) throws JSONException { Weather weather = new Weather();
CitySearch location = new CitySearch();
qqq3/good-weather
app/src/main/java/org/asdtm/goodweather/GoodWeatherApp.java
// Path: app/src/main/java/org/asdtm/goodweather/utils/LanguageUtil.java // public class LanguageUtil { // // private static final String TAG = LanguageUtil.class.getSimpleName(); // // @TargetApi(17) // @SuppressWarnings("deprecation") // public static void setLanguage(final ContextWrapper contextWrapper, String locale) { // Locale sLocale; // if (TextUtils.isEmpty(locale)) { // sLocale = Locale.getDefault(); // } else { // String[] localeParts = locale.split("_"); // if (localeParts.length > 1) { // sLocale = new Locale(localeParts[0], localeParts[1]); // } else { // sLocale = new Locale(locale); // } // } // // Resources resources = contextWrapper.getBaseContext().getResources(); // Configuration configuration = resources.getConfiguration(); // Locale.setDefault(sLocale); // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { // configuration.setLocale(sLocale); // } else { // configuration.locale = sLocale; // } // // resources.updateConfiguration(configuration, resources.getDisplayMetrics()); // } // // public static void forceChangeLanguage(Activity activity) { // Intent intent = activity.getIntent(); // if (intent == null) { // return; // } // intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); // activity.finish(); // activity.overridePendingTransition(0, 15); // activity.startActivity(intent); // activity.overridePendingTransition(0, 0); // } // // public static String getLanguageName(String locale) { // if (TextUtils.isEmpty(locale)) { // locale = Locale.getDefault().toString(); // } // if (locale.contains("_")) { // return locale.split("_")[0]; // } // return locale; // } // } // // Path: app/src/main/java/org/asdtm/goodweather/utils/PreferenceUtil.java // public class PreferenceUtil { // // public enum Theme { // light, // dark, // } // // public static SharedPreferences getDefaultSharedPrefs(Context context) { // return PreferenceManager.getDefaultSharedPreferences(context); // } // // public static String getLanguage(Context context) { // return PreferenceManager.getDefaultSharedPreferences(context).getString(Constants.PREF_LANGUAGE, "en"); // } // // public static Theme getTheme(Context context) { // return Theme.valueOf(PreferenceManager.getDefaultSharedPreferences(context).getString(Constants.PREF_THEME, "light")); // } // } // // Path: app/src/main/java/org/asdtm/goodweather/utils/PreferenceUtil.java // public enum Theme { // light, // dark, // }
import android.app.Activity; import android.app.Application; import android.content.res.Configuration; import org.asdtm.goodweather.utils.LanguageUtil; import org.asdtm.goodweather.utils.PreferenceUtil; import org.asdtm.goodweather.utils.PreferenceUtil.Theme;
package org.asdtm.goodweather; public class GoodWeatherApp extends Application { private static final String TAG = "GoodWeatherApp";
// Path: app/src/main/java/org/asdtm/goodweather/utils/LanguageUtil.java // public class LanguageUtil { // // private static final String TAG = LanguageUtil.class.getSimpleName(); // // @TargetApi(17) // @SuppressWarnings("deprecation") // public static void setLanguage(final ContextWrapper contextWrapper, String locale) { // Locale sLocale; // if (TextUtils.isEmpty(locale)) { // sLocale = Locale.getDefault(); // } else { // String[] localeParts = locale.split("_"); // if (localeParts.length > 1) { // sLocale = new Locale(localeParts[0], localeParts[1]); // } else { // sLocale = new Locale(locale); // } // } // // Resources resources = contextWrapper.getBaseContext().getResources(); // Configuration configuration = resources.getConfiguration(); // Locale.setDefault(sLocale); // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { // configuration.setLocale(sLocale); // } else { // configuration.locale = sLocale; // } // // resources.updateConfiguration(configuration, resources.getDisplayMetrics()); // } // // public static void forceChangeLanguage(Activity activity) { // Intent intent = activity.getIntent(); // if (intent == null) { // return; // } // intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); // activity.finish(); // activity.overridePendingTransition(0, 15); // activity.startActivity(intent); // activity.overridePendingTransition(0, 0); // } // // public static String getLanguageName(String locale) { // if (TextUtils.isEmpty(locale)) { // locale = Locale.getDefault().toString(); // } // if (locale.contains("_")) { // return locale.split("_")[0]; // } // return locale; // } // } // // Path: app/src/main/java/org/asdtm/goodweather/utils/PreferenceUtil.java // public class PreferenceUtil { // // public enum Theme { // light, // dark, // } // // public static SharedPreferences getDefaultSharedPrefs(Context context) { // return PreferenceManager.getDefaultSharedPreferences(context); // } // // public static String getLanguage(Context context) { // return PreferenceManager.getDefaultSharedPreferences(context).getString(Constants.PREF_LANGUAGE, "en"); // } // // public static Theme getTheme(Context context) { // return Theme.valueOf(PreferenceManager.getDefaultSharedPreferences(context).getString(Constants.PREF_THEME, "light")); // } // } // // Path: app/src/main/java/org/asdtm/goodweather/utils/PreferenceUtil.java // public enum Theme { // light, // dark, // } // Path: app/src/main/java/org/asdtm/goodweather/GoodWeatherApp.java import android.app.Activity; import android.app.Application; import android.content.res.Configuration; import org.asdtm.goodweather.utils.LanguageUtil; import org.asdtm.goodweather.utils.PreferenceUtil; import org.asdtm.goodweather.utils.PreferenceUtil.Theme; package org.asdtm.goodweather; public class GoodWeatherApp extends Application { private static final String TAG = "GoodWeatherApp";
private static Theme sTheme = Theme.light;
qqq3/good-weather
app/src/main/java/org/asdtm/goodweather/GoodWeatherApp.java
// Path: app/src/main/java/org/asdtm/goodweather/utils/LanguageUtil.java // public class LanguageUtil { // // private static final String TAG = LanguageUtil.class.getSimpleName(); // // @TargetApi(17) // @SuppressWarnings("deprecation") // public static void setLanguage(final ContextWrapper contextWrapper, String locale) { // Locale sLocale; // if (TextUtils.isEmpty(locale)) { // sLocale = Locale.getDefault(); // } else { // String[] localeParts = locale.split("_"); // if (localeParts.length > 1) { // sLocale = new Locale(localeParts[0], localeParts[1]); // } else { // sLocale = new Locale(locale); // } // } // // Resources resources = contextWrapper.getBaseContext().getResources(); // Configuration configuration = resources.getConfiguration(); // Locale.setDefault(sLocale); // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { // configuration.setLocale(sLocale); // } else { // configuration.locale = sLocale; // } // // resources.updateConfiguration(configuration, resources.getDisplayMetrics()); // } // // public static void forceChangeLanguage(Activity activity) { // Intent intent = activity.getIntent(); // if (intent == null) { // return; // } // intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); // activity.finish(); // activity.overridePendingTransition(0, 15); // activity.startActivity(intent); // activity.overridePendingTransition(0, 0); // } // // public static String getLanguageName(String locale) { // if (TextUtils.isEmpty(locale)) { // locale = Locale.getDefault().toString(); // } // if (locale.contains("_")) { // return locale.split("_")[0]; // } // return locale; // } // } // // Path: app/src/main/java/org/asdtm/goodweather/utils/PreferenceUtil.java // public class PreferenceUtil { // // public enum Theme { // light, // dark, // } // // public static SharedPreferences getDefaultSharedPrefs(Context context) { // return PreferenceManager.getDefaultSharedPreferences(context); // } // // public static String getLanguage(Context context) { // return PreferenceManager.getDefaultSharedPreferences(context).getString(Constants.PREF_LANGUAGE, "en"); // } // // public static Theme getTheme(Context context) { // return Theme.valueOf(PreferenceManager.getDefaultSharedPreferences(context).getString(Constants.PREF_THEME, "light")); // } // } // // Path: app/src/main/java/org/asdtm/goodweather/utils/PreferenceUtil.java // public enum Theme { // light, // dark, // }
import android.app.Activity; import android.app.Application; import android.content.res.Configuration; import org.asdtm.goodweather.utils.LanguageUtil; import org.asdtm.goodweather.utils.PreferenceUtil; import org.asdtm.goodweather.utils.PreferenceUtil.Theme;
package org.asdtm.goodweather; public class GoodWeatherApp extends Application { private static final String TAG = "GoodWeatherApp"; private static Theme sTheme = Theme.light; @Override public void onCreate() { super.onCreate();
// Path: app/src/main/java/org/asdtm/goodweather/utils/LanguageUtil.java // public class LanguageUtil { // // private static final String TAG = LanguageUtil.class.getSimpleName(); // // @TargetApi(17) // @SuppressWarnings("deprecation") // public static void setLanguage(final ContextWrapper contextWrapper, String locale) { // Locale sLocale; // if (TextUtils.isEmpty(locale)) { // sLocale = Locale.getDefault(); // } else { // String[] localeParts = locale.split("_"); // if (localeParts.length > 1) { // sLocale = new Locale(localeParts[0], localeParts[1]); // } else { // sLocale = new Locale(locale); // } // } // // Resources resources = contextWrapper.getBaseContext().getResources(); // Configuration configuration = resources.getConfiguration(); // Locale.setDefault(sLocale); // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { // configuration.setLocale(sLocale); // } else { // configuration.locale = sLocale; // } // // resources.updateConfiguration(configuration, resources.getDisplayMetrics()); // } // // public static void forceChangeLanguage(Activity activity) { // Intent intent = activity.getIntent(); // if (intent == null) { // return; // } // intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); // activity.finish(); // activity.overridePendingTransition(0, 15); // activity.startActivity(intent); // activity.overridePendingTransition(0, 0); // } // // public static String getLanguageName(String locale) { // if (TextUtils.isEmpty(locale)) { // locale = Locale.getDefault().toString(); // } // if (locale.contains("_")) { // return locale.split("_")[0]; // } // return locale; // } // } // // Path: app/src/main/java/org/asdtm/goodweather/utils/PreferenceUtil.java // public class PreferenceUtil { // // public enum Theme { // light, // dark, // } // // public static SharedPreferences getDefaultSharedPrefs(Context context) { // return PreferenceManager.getDefaultSharedPreferences(context); // } // // public static String getLanguage(Context context) { // return PreferenceManager.getDefaultSharedPreferences(context).getString(Constants.PREF_LANGUAGE, "en"); // } // // public static Theme getTheme(Context context) { // return Theme.valueOf(PreferenceManager.getDefaultSharedPreferences(context).getString(Constants.PREF_THEME, "light")); // } // } // // Path: app/src/main/java/org/asdtm/goodweather/utils/PreferenceUtil.java // public enum Theme { // light, // dark, // } // Path: app/src/main/java/org/asdtm/goodweather/GoodWeatherApp.java import android.app.Activity; import android.app.Application; import android.content.res.Configuration; import org.asdtm.goodweather.utils.LanguageUtil; import org.asdtm.goodweather.utils.PreferenceUtil; import org.asdtm.goodweather.utils.PreferenceUtil.Theme; package org.asdtm.goodweather; public class GoodWeatherApp extends Application { private static final String TAG = "GoodWeatherApp"; private static Theme sTheme = Theme.light; @Override public void onCreate() { super.onCreate();
LanguageUtil.setLanguage(this, PreferenceUtil.getLanguage(this));
qqq3/good-weather
app/src/main/java/org/asdtm/goodweather/GoodWeatherApp.java
// Path: app/src/main/java/org/asdtm/goodweather/utils/LanguageUtil.java // public class LanguageUtil { // // private static final String TAG = LanguageUtil.class.getSimpleName(); // // @TargetApi(17) // @SuppressWarnings("deprecation") // public static void setLanguage(final ContextWrapper contextWrapper, String locale) { // Locale sLocale; // if (TextUtils.isEmpty(locale)) { // sLocale = Locale.getDefault(); // } else { // String[] localeParts = locale.split("_"); // if (localeParts.length > 1) { // sLocale = new Locale(localeParts[0], localeParts[1]); // } else { // sLocale = new Locale(locale); // } // } // // Resources resources = contextWrapper.getBaseContext().getResources(); // Configuration configuration = resources.getConfiguration(); // Locale.setDefault(sLocale); // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { // configuration.setLocale(sLocale); // } else { // configuration.locale = sLocale; // } // // resources.updateConfiguration(configuration, resources.getDisplayMetrics()); // } // // public static void forceChangeLanguage(Activity activity) { // Intent intent = activity.getIntent(); // if (intent == null) { // return; // } // intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); // activity.finish(); // activity.overridePendingTransition(0, 15); // activity.startActivity(intent); // activity.overridePendingTransition(0, 0); // } // // public static String getLanguageName(String locale) { // if (TextUtils.isEmpty(locale)) { // locale = Locale.getDefault().toString(); // } // if (locale.contains("_")) { // return locale.split("_")[0]; // } // return locale; // } // } // // Path: app/src/main/java/org/asdtm/goodweather/utils/PreferenceUtil.java // public class PreferenceUtil { // // public enum Theme { // light, // dark, // } // // public static SharedPreferences getDefaultSharedPrefs(Context context) { // return PreferenceManager.getDefaultSharedPreferences(context); // } // // public static String getLanguage(Context context) { // return PreferenceManager.getDefaultSharedPreferences(context).getString(Constants.PREF_LANGUAGE, "en"); // } // // public static Theme getTheme(Context context) { // return Theme.valueOf(PreferenceManager.getDefaultSharedPreferences(context).getString(Constants.PREF_THEME, "light")); // } // } // // Path: app/src/main/java/org/asdtm/goodweather/utils/PreferenceUtil.java // public enum Theme { // light, // dark, // }
import android.app.Activity; import android.app.Application; import android.content.res.Configuration; import org.asdtm.goodweather.utils.LanguageUtil; import org.asdtm.goodweather.utils.PreferenceUtil; import org.asdtm.goodweather.utils.PreferenceUtil.Theme;
package org.asdtm.goodweather; public class GoodWeatherApp extends Application { private static final String TAG = "GoodWeatherApp"; private static Theme sTheme = Theme.light; @Override public void onCreate() { super.onCreate();
// Path: app/src/main/java/org/asdtm/goodweather/utils/LanguageUtil.java // public class LanguageUtil { // // private static final String TAG = LanguageUtil.class.getSimpleName(); // // @TargetApi(17) // @SuppressWarnings("deprecation") // public static void setLanguage(final ContextWrapper contextWrapper, String locale) { // Locale sLocale; // if (TextUtils.isEmpty(locale)) { // sLocale = Locale.getDefault(); // } else { // String[] localeParts = locale.split("_"); // if (localeParts.length > 1) { // sLocale = new Locale(localeParts[0], localeParts[1]); // } else { // sLocale = new Locale(locale); // } // } // // Resources resources = contextWrapper.getBaseContext().getResources(); // Configuration configuration = resources.getConfiguration(); // Locale.setDefault(sLocale); // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { // configuration.setLocale(sLocale); // } else { // configuration.locale = sLocale; // } // // resources.updateConfiguration(configuration, resources.getDisplayMetrics()); // } // // public static void forceChangeLanguage(Activity activity) { // Intent intent = activity.getIntent(); // if (intent == null) { // return; // } // intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); // activity.finish(); // activity.overridePendingTransition(0, 15); // activity.startActivity(intent); // activity.overridePendingTransition(0, 0); // } // // public static String getLanguageName(String locale) { // if (TextUtils.isEmpty(locale)) { // locale = Locale.getDefault().toString(); // } // if (locale.contains("_")) { // return locale.split("_")[0]; // } // return locale; // } // } // // Path: app/src/main/java/org/asdtm/goodweather/utils/PreferenceUtil.java // public class PreferenceUtil { // // public enum Theme { // light, // dark, // } // // public static SharedPreferences getDefaultSharedPrefs(Context context) { // return PreferenceManager.getDefaultSharedPreferences(context); // } // // public static String getLanguage(Context context) { // return PreferenceManager.getDefaultSharedPreferences(context).getString(Constants.PREF_LANGUAGE, "en"); // } // // public static Theme getTheme(Context context) { // return Theme.valueOf(PreferenceManager.getDefaultSharedPreferences(context).getString(Constants.PREF_THEME, "light")); // } // } // // Path: app/src/main/java/org/asdtm/goodweather/utils/PreferenceUtil.java // public enum Theme { // light, // dark, // } // Path: app/src/main/java/org/asdtm/goodweather/GoodWeatherApp.java import android.app.Activity; import android.app.Application; import android.content.res.Configuration; import org.asdtm.goodweather.utils.LanguageUtil; import org.asdtm.goodweather.utils.PreferenceUtil; import org.asdtm.goodweather.utils.PreferenceUtil.Theme; package org.asdtm.goodweather; public class GoodWeatherApp extends Application { private static final String TAG = "GoodWeatherApp"; private static Theme sTheme = Theme.light; @Override public void onCreate() { super.onCreate();
LanguageUtil.setLanguage(this, PreferenceUtil.getLanguage(this));
mixi-inc/triaina
android/Commons/src/triaina/commons/utils/FileUtils.java
// Path: android/Commons/src/triaina/commons/exception/IORuntimeException.java // public class IORuntimeException extends CommonRuntimeException { // private static final long serialVersionUID = -8000893106100281337L; // // public IORuntimeException() { // } // // public IORuntimeException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // } // // public IORuntimeException(String detailMessage) { // super(detailMessage); // } // // public IORuntimeException(Throwable throwable) { // super(throwable); // } // }
import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.nio.channels.FileChannel; import triaina.commons.exception.IORuntimeException; import android.content.ContentResolver; import android.database.Cursor; import android.net.Uri; import android.provider.MediaStore;
* @param os the output stream * @return the number of bytes that were transferred * @throws IOException */ public static long copyFileStream(FileInputStream is, FileOutputStream os) throws IOException { FileChannel srcChannel = null; FileChannel destChannel = null; try { srcChannel = is.getChannel(); destChannel = os.getChannel(); return srcChannel.transferTo(0, srcChannel.size(), destChannel); } finally { CloseableUtils.close(srcChannel); CloseableUtils.close(destChannel); } } public static String getName(String path) { return new File(path).getName(); } public static String getName(Uri uri) { return new File(uri.toString()).getName(); } public static boolean createNewFile(File file) { try { return file.createNewFile(); } catch (IOException exp) {
// Path: android/Commons/src/triaina/commons/exception/IORuntimeException.java // public class IORuntimeException extends CommonRuntimeException { // private static final long serialVersionUID = -8000893106100281337L; // // public IORuntimeException() { // } // // public IORuntimeException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // } // // public IORuntimeException(String detailMessage) { // super(detailMessage); // } // // public IORuntimeException(Throwable throwable) { // super(throwable); // } // } // Path: android/Commons/src/triaina/commons/utils/FileUtils.java import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.nio.channels.FileChannel; import triaina.commons.exception.IORuntimeException; import android.content.ContentResolver; import android.database.Cursor; import android.net.Uri; import android.provider.MediaStore; * @param os the output stream * @return the number of bytes that were transferred * @throws IOException */ public static long copyFileStream(FileInputStream is, FileOutputStream os) throws IOException { FileChannel srcChannel = null; FileChannel destChannel = null; try { srcChannel = is.getChannel(); destChannel = os.getChannel(); return srcChannel.transferTo(0, srcChannel.size(), destChannel); } finally { CloseableUtils.close(srcChannel); CloseableUtils.close(destChannel); } } public static String getName(String path) { return new File(path).getName(); } public static String getName(Uri uri) { return new File(uri.toString()).getName(); } public static boolean createNewFile(File file) { try { return file.createNewFile(); } catch (IOException exp) {
throw new IORuntimeException(exp);
mixi-inc/triaina
android/Commons/src/triaina/commons/utils/InputStreamUtils.java
// Path: android/Commons/src/triaina/commons/exception/IORuntimeException.java // public class IORuntimeException extends CommonRuntimeException { // private static final long serialVersionUID = -8000893106100281337L; // // public IORuntimeException() { // } // // public IORuntimeException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // } // // public IORuntimeException(String detailMessage) { // super(detailMessage); // } // // public IORuntimeException(Throwable throwable) { // super(throwable); // } // }
import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import triaina.commons.exception.IORuntimeException;
package triaina.commons.utils; public final class InputStreamUtils { private InputStreamUtils() {} public static byte[] toByteArray(InputStream is) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] buffer = new byte[4096]; int len = 0; try { while ((len = is.read(buffer)) > 0) { bos.write(buffer, 0, len); } } catch (IOException exp) {
// Path: android/Commons/src/triaina/commons/exception/IORuntimeException.java // public class IORuntimeException extends CommonRuntimeException { // private static final long serialVersionUID = -8000893106100281337L; // // public IORuntimeException() { // } // // public IORuntimeException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // } // // public IORuntimeException(String detailMessage) { // super(detailMessage); // } // // public IORuntimeException(Throwable throwable) { // super(throwable); // } // } // Path: android/Commons/src/triaina/commons/utils/InputStreamUtils.java import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import triaina.commons.exception.IORuntimeException; package triaina.commons.utils; public final class InputStreamUtils { private InputStreamUtils() {} public static byte[] toByteArray(InputStream is) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] buffer = new byte[4096]; int len = 0; try { while ((len = is.read(buffer)) > 0) { bos.write(buffer, 0, len); } } catch (IOException exp) {
throw new IORuntimeException(exp);
mixi-inc/triaina
android/Commons/src/triaina/commons/workerservice/WorkerService.java
// Path: android/Commons/src/triaina/commons/exception/NotFoundRuntimeException.java // public class NotFoundRuntimeException extends CommonRuntimeException { // // private static final long serialVersionUID = 5486025835429632952L; // // public NotFoundRuntimeException() { // super(); // } // // public NotFoundRuntimeException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // } // // public NotFoundRuntimeException(String detailMessage) { // super(detailMessage); // } // // public NotFoundRuntimeException(Throwable throwable) { // super(throwable); // } // } // // Path: android/Commons/src/triaina/commons/utils/ClassUtils.java // public final class ClassUtils { // // private ClassUtils() { // } // // public static <T> T newInstance(Class<T> clazz) { // try { // return clazz.newInstance(); // } catch (IllegalAccessException exp) { // throw new IllegalAccessRuntimeException(exp); // } catch (InstantiationException exp) { // throw new InstantiationRuntimeException(exp); // } // } // // public static <T> T newInstance(Class<T> clazz, Object... args) { // Class<?>[] paramTypes = toClasses(args); // try { // return getConstructor(clazz, paramTypes).newInstance(args); // } catch (IllegalAccessException exp) { // throw new IllegalAccessRuntimeException(exp); // } catch (InstantiationException exp) { // throw new InstantiationRuntimeException(exp); // } catch (IllegalArgumentException exp) { // throw new IllegalArgumentRuntimeException(exp); // } catch (InvocationTargetException exp) { // throw new InvocationRuntimeException(exp); // } // } // // public static <T> Constructor<T> getConstructor(Class<T> clazz, // Class<?>[] paramTypes) { // try { // return clazz.getConstructor(paramTypes); // } catch (SecurityException exp) { // throw new SecurityRuntimeException(exp); // } catch (NoSuchMethodException exp) { // throw new NotFoundRuntimeException(exp); // } // } // // public static Class<?>[] toClasses(Object... args) { // List<Class<?>> list = new ArrayList<Class<?>>(args.length); // for (Object obj : args) // list.add(obj.getClass()); // return list.toArray(new Class[list.size()]); // } // // public static boolean isImplement(Class<?> clazz, Class<?> interfaceClazz) { // if (clazz.equals(interfaceClazz)) // return true; // // Class<?>[] ifs = clazz.getInterfaces(); // for (Class<?> i : ifs) { // if (i.equals(interfaceClazz)) // return true; // } // // Class<?> s = clazz.getSuperclass(); // if (s == null || clazz.equals(s.getClass())) // return false; // // return isImplement(s, interfaceClazz); // } // // public static Method[] getMethodsByName(Class<?> clazz, String name) { // Method[] methods = clazz.getMethods(); // List<Method> list = new ArrayList<Method>(); // // for (Method method : methods) { // if (method.getName().equals(name)) // list.add(method); // } // // return list.toArray(new Method[list.size()]); // } // // public static Field getFiled(Class<?> clazz, String name) { // try { // return clazz.getField(name); // } catch (NoSuchFieldException exp) { // throw new NotFoundRuntimeException(exp); // } // } // // public static Field getDeclaredField(Class<?> clazz, String name) { // try { // return clazz.getDeclaredField(name); // } catch (NoSuchFieldException exp) { // throw new NotFoundRuntimeException(exp); // } // } // // public static Type[] getGenericType(Class<?> clazz, Class<?> interfaceClazz) { // Type st = clazz.getGenericSuperclass(); // Type[] ret = getActualTypeArguments(interfaceClazz, st); // // if (ret != null) // return ret; // // for (Type t : clazz.getGenericInterfaces()) { // ret = getActualTypeArguments(interfaceClazz, t); // if (ret != null) // return ret; // } // // Class<?> s = clazz.getSuperclass(); // if (s == null || clazz.equals(s.getClass())) // return new Type[0]; // // return getGenericType(s, interfaceClazz); // } // // private static Type[] getActualTypeArguments(Class<?> type, Type t) { // if (t != null && t instanceof ParameterizedType) { // ParameterizedType pt = (ParameterizedType) t; // if (pt.getRawType().equals(type)) // return ((ParameterizedType) t).getActualTypeArguments(); // } // return null; // } // // }
import java.lang.reflect.Constructor; import java.util.concurrent.atomic.AtomicReference; import triaina.commons.exception.NotFoundRuntimeException; import triaina.commons.utils.ClassUtils; import triaina.commons.utils.ConstructorUtils; import triaina.commons.workerservice.annotation.Assign; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Handler; import android.os.ResultReceiver; import android.util.Log;
} } }; public WorkerService() { super(TAG); } @Override public void onCreate() { super.onCreate(); mHandler = new Handler(); registerReceiver(mCancelReceiver, new IntentFilter(ACTION_CANCEL_TASK)); } @Override public void onDestroy() { unregisterReceiver(mCancelReceiver); super.onDestroy(); } protected Handler getHandler() { return mHandler; } @SuppressWarnings("unchecked") protected Worker<?> getWorker(Job job) { Assign assign = job.getClass().getAnnotation(Assign.class); if (assign == null) { Log.w(TAG, "Worker is not assigned to " + job.toString());
// Path: android/Commons/src/triaina/commons/exception/NotFoundRuntimeException.java // public class NotFoundRuntimeException extends CommonRuntimeException { // // private static final long serialVersionUID = 5486025835429632952L; // // public NotFoundRuntimeException() { // super(); // } // // public NotFoundRuntimeException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // } // // public NotFoundRuntimeException(String detailMessage) { // super(detailMessage); // } // // public NotFoundRuntimeException(Throwable throwable) { // super(throwable); // } // } // // Path: android/Commons/src/triaina/commons/utils/ClassUtils.java // public final class ClassUtils { // // private ClassUtils() { // } // // public static <T> T newInstance(Class<T> clazz) { // try { // return clazz.newInstance(); // } catch (IllegalAccessException exp) { // throw new IllegalAccessRuntimeException(exp); // } catch (InstantiationException exp) { // throw new InstantiationRuntimeException(exp); // } // } // // public static <T> T newInstance(Class<T> clazz, Object... args) { // Class<?>[] paramTypes = toClasses(args); // try { // return getConstructor(clazz, paramTypes).newInstance(args); // } catch (IllegalAccessException exp) { // throw new IllegalAccessRuntimeException(exp); // } catch (InstantiationException exp) { // throw new InstantiationRuntimeException(exp); // } catch (IllegalArgumentException exp) { // throw new IllegalArgumentRuntimeException(exp); // } catch (InvocationTargetException exp) { // throw new InvocationRuntimeException(exp); // } // } // // public static <T> Constructor<T> getConstructor(Class<T> clazz, // Class<?>[] paramTypes) { // try { // return clazz.getConstructor(paramTypes); // } catch (SecurityException exp) { // throw new SecurityRuntimeException(exp); // } catch (NoSuchMethodException exp) { // throw new NotFoundRuntimeException(exp); // } // } // // public static Class<?>[] toClasses(Object... args) { // List<Class<?>> list = new ArrayList<Class<?>>(args.length); // for (Object obj : args) // list.add(obj.getClass()); // return list.toArray(new Class[list.size()]); // } // // public static boolean isImplement(Class<?> clazz, Class<?> interfaceClazz) { // if (clazz.equals(interfaceClazz)) // return true; // // Class<?>[] ifs = clazz.getInterfaces(); // for (Class<?> i : ifs) { // if (i.equals(interfaceClazz)) // return true; // } // // Class<?> s = clazz.getSuperclass(); // if (s == null || clazz.equals(s.getClass())) // return false; // // return isImplement(s, interfaceClazz); // } // // public static Method[] getMethodsByName(Class<?> clazz, String name) { // Method[] methods = clazz.getMethods(); // List<Method> list = new ArrayList<Method>(); // // for (Method method : methods) { // if (method.getName().equals(name)) // list.add(method); // } // // return list.toArray(new Method[list.size()]); // } // // public static Field getFiled(Class<?> clazz, String name) { // try { // return clazz.getField(name); // } catch (NoSuchFieldException exp) { // throw new NotFoundRuntimeException(exp); // } // } // // public static Field getDeclaredField(Class<?> clazz, String name) { // try { // return clazz.getDeclaredField(name); // } catch (NoSuchFieldException exp) { // throw new NotFoundRuntimeException(exp); // } // } // // public static Type[] getGenericType(Class<?> clazz, Class<?> interfaceClazz) { // Type st = clazz.getGenericSuperclass(); // Type[] ret = getActualTypeArguments(interfaceClazz, st); // // if (ret != null) // return ret; // // for (Type t : clazz.getGenericInterfaces()) { // ret = getActualTypeArguments(interfaceClazz, t); // if (ret != null) // return ret; // } // // Class<?> s = clazz.getSuperclass(); // if (s == null || clazz.equals(s.getClass())) // return new Type[0]; // // return getGenericType(s, interfaceClazz); // } // // private static Type[] getActualTypeArguments(Class<?> type, Type t) { // if (t != null && t instanceof ParameterizedType) { // ParameterizedType pt = (ParameterizedType) t; // if (pt.getRawType().equals(type)) // return ((ParameterizedType) t).getActualTypeArguments(); // } // return null; // } // // } // Path: android/Commons/src/triaina/commons/workerservice/WorkerService.java import java.lang.reflect.Constructor; import java.util.concurrent.atomic.AtomicReference; import triaina.commons.exception.NotFoundRuntimeException; import triaina.commons.utils.ClassUtils; import triaina.commons.utils.ConstructorUtils; import triaina.commons.workerservice.annotation.Assign; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Handler; import android.os.ResultReceiver; import android.util.Log; } } }; public WorkerService() { super(TAG); } @Override public void onCreate() { super.onCreate(); mHandler = new Handler(); registerReceiver(mCancelReceiver, new IntentFilter(ACTION_CANCEL_TASK)); } @Override public void onDestroy() { unregisterReceiver(mCancelReceiver); super.onDestroy(); } protected Handler getHandler() { return mHandler; } @SuppressWarnings("unchecked") protected Worker<?> getWorker(Job job) { Assign assign = job.getClass().getAnnotation(Assign.class); if (assign == null) { Log.w(TAG, "Worker is not assigned to " + job.toString());
throw new NotFoundRuntimeException("Not found assigned worker");
mixi-inc/triaina
android/Commons/src/triaina/commons/workerservice/WorkerService.java
// Path: android/Commons/src/triaina/commons/exception/NotFoundRuntimeException.java // public class NotFoundRuntimeException extends CommonRuntimeException { // // private static final long serialVersionUID = 5486025835429632952L; // // public NotFoundRuntimeException() { // super(); // } // // public NotFoundRuntimeException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // } // // public NotFoundRuntimeException(String detailMessage) { // super(detailMessage); // } // // public NotFoundRuntimeException(Throwable throwable) { // super(throwable); // } // } // // Path: android/Commons/src/triaina/commons/utils/ClassUtils.java // public final class ClassUtils { // // private ClassUtils() { // } // // public static <T> T newInstance(Class<T> clazz) { // try { // return clazz.newInstance(); // } catch (IllegalAccessException exp) { // throw new IllegalAccessRuntimeException(exp); // } catch (InstantiationException exp) { // throw new InstantiationRuntimeException(exp); // } // } // // public static <T> T newInstance(Class<T> clazz, Object... args) { // Class<?>[] paramTypes = toClasses(args); // try { // return getConstructor(clazz, paramTypes).newInstance(args); // } catch (IllegalAccessException exp) { // throw new IllegalAccessRuntimeException(exp); // } catch (InstantiationException exp) { // throw new InstantiationRuntimeException(exp); // } catch (IllegalArgumentException exp) { // throw new IllegalArgumentRuntimeException(exp); // } catch (InvocationTargetException exp) { // throw new InvocationRuntimeException(exp); // } // } // // public static <T> Constructor<T> getConstructor(Class<T> clazz, // Class<?>[] paramTypes) { // try { // return clazz.getConstructor(paramTypes); // } catch (SecurityException exp) { // throw new SecurityRuntimeException(exp); // } catch (NoSuchMethodException exp) { // throw new NotFoundRuntimeException(exp); // } // } // // public static Class<?>[] toClasses(Object... args) { // List<Class<?>> list = new ArrayList<Class<?>>(args.length); // for (Object obj : args) // list.add(obj.getClass()); // return list.toArray(new Class[list.size()]); // } // // public static boolean isImplement(Class<?> clazz, Class<?> interfaceClazz) { // if (clazz.equals(interfaceClazz)) // return true; // // Class<?>[] ifs = clazz.getInterfaces(); // for (Class<?> i : ifs) { // if (i.equals(interfaceClazz)) // return true; // } // // Class<?> s = clazz.getSuperclass(); // if (s == null || clazz.equals(s.getClass())) // return false; // // return isImplement(s, interfaceClazz); // } // // public static Method[] getMethodsByName(Class<?> clazz, String name) { // Method[] methods = clazz.getMethods(); // List<Method> list = new ArrayList<Method>(); // // for (Method method : methods) { // if (method.getName().equals(name)) // list.add(method); // } // // return list.toArray(new Method[list.size()]); // } // // public static Field getFiled(Class<?> clazz, String name) { // try { // return clazz.getField(name); // } catch (NoSuchFieldException exp) { // throw new NotFoundRuntimeException(exp); // } // } // // public static Field getDeclaredField(Class<?> clazz, String name) { // try { // return clazz.getDeclaredField(name); // } catch (NoSuchFieldException exp) { // throw new NotFoundRuntimeException(exp); // } // } // // public static Type[] getGenericType(Class<?> clazz, Class<?> interfaceClazz) { // Type st = clazz.getGenericSuperclass(); // Type[] ret = getActualTypeArguments(interfaceClazz, st); // // if (ret != null) // return ret; // // for (Type t : clazz.getGenericInterfaces()) { // ret = getActualTypeArguments(interfaceClazz, t); // if (ret != null) // return ret; // } // // Class<?> s = clazz.getSuperclass(); // if (s == null || clazz.equals(s.getClass())) // return new Type[0]; // // return getGenericType(s, interfaceClazz); // } // // private static Type[] getActualTypeArguments(Class<?> type, Type t) { // if (t != null && t instanceof ParameterizedType) { // ParameterizedType pt = (ParameterizedType) t; // if (pt.getRawType().equals(type)) // return ((ParameterizedType) t).getActualTypeArguments(); // } // return null; // } // // }
import java.lang.reflect.Constructor; import java.util.concurrent.atomic.AtomicReference; import triaina.commons.exception.NotFoundRuntimeException; import triaina.commons.utils.ClassUtils; import triaina.commons.utils.ConstructorUtils; import triaina.commons.workerservice.annotation.Assign; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Handler; import android.os.ResultReceiver; import android.util.Log;
public WorkerService() { super(TAG); } @Override public void onCreate() { super.onCreate(); mHandler = new Handler(); registerReceiver(mCancelReceiver, new IntentFilter(ACTION_CANCEL_TASK)); } @Override public void onDestroy() { unregisterReceiver(mCancelReceiver); super.onDestroy(); } protected Handler getHandler() { return mHandler; } @SuppressWarnings("unchecked") protected Worker<?> getWorker(Job job) { Assign assign = job.getClass().getAnnotation(Assign.class); if (assign == null) { Log.w(TAG, "Worker is not assigned to " + job.toString()); throw new NotFoundRuntimeException("Not found assigned worker"); }
// Path: android/Commons/src/triaina/commons/exception/NotFoundRuntimeException.java // public class NotFoundRuntimeException extends CommonRuntimeException { // // private static final long serialVersionUID = 5486025835429632952L; // // public NotFoundRuntimeException() { // super(); // } // // public NotFoundRuntimeException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // } // // public NotFoundRuntimeException(String detailMessage) { // super(detailMessage); // } // // public NotFoundRuntimeException(Throwable throwable) { // super(throwable); // } // } // // Path: android/Commons/src/triaina/commons/utils/ClassUtils.java // public final class ClassUtils { // // private ClassUtils() { // } // // public static <T> T newInstance(Class<T> clazz) { // try { // return clazz.newInstance(); // } catch (IllegalAccessException exp) { // throw new IllegalAccessRuntimeException(exp); // } catch (InstantiationException exp) { // throw new InstantiationRuntimeException(exp); // } // } // // public static <T> T newInstance(Class<T> clazz, Object... args) { // Class<?>[] paramTypes = toClasses(args); // try { // return getConstructor(clazz, paramTypes).newInstance(args); // } catch (IllegalAccessException exp) { // throw new IllegalAccessRuntimeException(exp); // } catch (InstantiationException exp) { // throw new InstantiationRuntimeException(exp); // } catch (IllegalArgumentException exp) { // throw new IllegalArgumentRuntimeException(exp); // } catch (InvocationTargetException exp) { // throw new InvocationRuntimeException(exp); // } // } // // public static <T> Constructor<T> getConstructor(Class<T> clazz, // Class<?>[] paramTypes) { // try { // return clazz.getConstructor(paramTypes); // } catch (SecurityException exp) { // throw new SecurityRuntimeException(exp); // } catch (NoSuchMethodException exp) { // throw new NotFoundRuntimeException(exp); // } // } // // public static Class<?>[] toClasses(Object... args) { // List<Class<?>> list = new ArrayList<Class<?>>(args.length); // for (Object obj : args) // list.add(obj.getClass()); // return list.toArray(new Class[list.size()]); // } // // public static boolean isImplement(Class<?> clazz, Class<?> interfaceClazz) { // if (clazz.equals(interfaceClazz)) // return true; // // Class<?>[] ifs = clazz.getInterfaces(); // for (Class<?> i : ifs) { // if (i.equals(interfaceClazz)) // return true; // } // // Class<?> s = clazz.getSuperclass(); // if (s == null || clazz.equals(s.getClass())) // return false; // // return isImplement(s, interfaceClazz); // } // // public static Method[] getMethodsByName(Class<?> clazz, String name) { // Method[] methods = clazz.getMethods(); // List<Method> list = new ArrayList<Method>(); // // for (Method method : methods) { // if (method.getName().equals(name)) // list.add(method); // } // // return list.toArray(new Method[list.size()]); // } // // public static Field getFiled(Class<?> clazz, String name) { // try { // return clazz.getField(name); // } catch (NoSuchFieldException exp) { // throw new NotFoundRuntimeException(exp); // } // } // // public static Field getDeclaredField(Class<?> clazz, String name) { // try { // return clazz.getDeclaredField(name); // } catch (NoSuchFieldException exp) { // throw new NotFoundRuntimeException(exp); // } // } // // public static Type[] getGenericType(Class<?> clazz, Class<?> interfaceClazz) { // Type st = clazz.getGenericSuperclass(); // Type[] ret = getActualTypeArguments(interfaceClazz, st); // // if (ret != null) // return ret; // // for (Type t : clazz.getGenericInterfaces()) { // ret = getActualTypeArguments(interfaceClazz, t); // if (ret != null) // return ret; // } // // Class<?> s = clazz.getSuperclass(); // if (s == null || clazz.equals(s.getClass())) // return new Type[0]; // // return getGenericType(s, interfaceClazz); // } // // private static Type[] getActualTypeArguments(Class<?> type, Type t) { // if (t != null && t instanceof ParameterizedType) { // ParameterizedType pt = (ParameterizedType) t; // if (pt.getRawType().equals(type)) // return ((ParameterizedType) t).getActualTypeArguments(); // } // return null; // } // // } // Path: android/Commons/src/triaina/commons/workerservice/WorkerService.java import java.lang.reflect.Constructor; import java.util.concurrent.atomic.AtomicReference; import triaina.commons.exception.NotFoundRuntimeException; import triaina.commons.utils.ClassUtils; import triaina.commons.utils.ConstructorUtils; import triaina.commons.workerservice.annotation.Assign; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Handler; import android.os.ResultReceiver; import android.util.Log; public WorkerService() { super(TAG); } @Override public void onCreate() { super.onCreate(); mHandler = new Handler(); registerReceiver(mCancelReceiver, new IntentFilter(ACTION_CANCEL_TASK)); } @Override public void onDestroy() { unregisterReceiver(mCancelReceiver); super.onDestroy(); } protected Handler getHandler() { return mHandler; } @SuppressWarnings("unchecked") protected Worker<?> getWorker(Job job) { Assign assign = job.getClass().getAnnotation(Assign.class); if (assign == null) { Log.w(TAG, "Worker is not assigned to " + job.toString()); throw new NotFoundRuntimeException("Not found assigned worker"); }
Worker<?> worker = ClassUtils.newInstance(assign.worker());
mixi-inc/triaina
android/Commons/src/triaina/commons/utils/ClassUtils.java
// Path: android/Commons/src/triaina/commons/exception/NotFoundRuntimeException.java // public class NotFoundRuntimeException extends CommonRuntimeException { // // private static final long serialVersionUID = 5486025835429632952L; // // public NotFoundRuntimeException() { // super(); // } // // public NotFoundRuntimeException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // } // // public NotFoundRuntimeException(String detailMessage) { // super(detailMessage); // } // // public NotFoundRuntimeException(Throwable throwable) { // super(throwable); // } // } // // Path: android/Commons/src/triaina/commons/exception/SecurityRuntimeException.java // public class SecurityRuntimeException extends CommonRuntimeException { // // private static final long serialVersionUID = 6244026068714272574L; // // private String mUrl; // // public SecurityRuntimeException() { // super(); // } // // public SecurityRuntimeException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // } // // public SecurityRuntimeException(String detailMessage) { // super(detailMessage); // } // // public SecurityRuntimeException(String detailMessage, String url) { // this(detailMessage); // mUrl = url; // } // // public SecurityRuntimeException(Throwable throwable) { // super(throwable); // } // // public SecurityRuntimeException(Throwable throwable, String url) { // this(throwable); // mUrl = url; // } // // public String getUrl(){ // return mUrl; // } // }
import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; import triaina.commons.exception.IllegalAccessRuntimeException; import triaina.commons.exception.IllegalArgumentRuntimeException; import triaina.commons.exception.InstantiationRuntimeException; import triaina.commons.exception.InvocationRuntimeException; import triaina.commons.exception.NotFoundRuntimeException; import triaina.commons.exception.SecurityRuntimeException;
public static <T> T newInstance(Class<T> clazz) { try { return clazz.newInstance(); } catch (IllegalAccessException exp) { throw new IllegalAccessRuntimeException(exp); } catch (InstantiationException exp) { throw new InstantiationRuntimeException(exp); } } public static <T> T newInstance(Class<T> clazz, Object... args) { Class<?>[] paramTypes = toClasses(args); try { return getConstructor(clazz, paramTypes).newInstance(args); } catch (IllegalAccessException exp) { throw new IllegalAccessRuntimeException(exp); } catch (InstantiationException exp) { throw new InstantiationRuntimeException(exp); } catch (IllegalArgumentException exp) { throw new IllegalArgumentRuntimeException(exp); } catch (InvocationTargetException exp) { throw new InvocationRuntimeException(exp); } } public static <T> Constructor<T> getConstructor(Class<T> clazz, Class<?>[] paramTypes) { try { return clazz.getConstructor(paramTypes); } catch (SecurityException exp) {
// Path: android/Commons/src/triaina/commons/exception/NotFoundRuntimeException.java // public class NotFoundRuntimeException extends CommonRuntimeException { // // private static final long serialVersionUID = 5486025835429632952L; // // public NotFoundRuntimeException() { // super(); // } // // public NotFoundRuntimeException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // } // // public NotFoundRuntimeException(String detailMessage) { // super(detailMessage); // } // // public NotFoundRuntimeException(Throwable throwable) { // super(throwable); // } // } // // Path: android/Commons/src/triaina/commons/exception/SecurityRuntimeException.java // public class SecurityRuntimeException extends CommonRuntimeException { // // private static final long serialVersionUID = 6244026068714272574L; // // private String mUrl; // // public SecurityRuntimeException() { // super(); // } // // public SecurityRuntimeException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // } // // public SecurityRuntimeException(String detailMessage) { // super(detailMessage); // } // // public SecurityRuntimeException(String detailMessage, String url) { // this(detailMessage); // mUrl = url; // } // // public SecurityRuntimeException(Throwable throwable) { // super(throwable); // } // // public SecurityRuntimeException(Throwable throwable, String url) { // this(throwable); // mUrl = url; // } // // public String getUrl(){ // return mUrl; // } // } // Path: android/Commons/src/triaina/commons/utils/ClassUtils.java import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; import triaina.commons.exception.IllegalAccessRuntimeException; import triaina.commons.exception.IllegalArgumentRuntimeException; import triaina.commons.exception.InstantiationRuntimeException; import triaina.commons.exception.InvocationRuntimeException; import triaina.commons.exception.NotFoundRuntimeException; import triaina.commons.exception.SecurityRuntimeException; public static <T> T newInstance(Class<T> clazz) { try { return clazz.newInstance(); } catch (IllegalAccessException exp) { throw new IllegalAccessRuntimeException(exp); } catch (InstantiationException exp) { throw new InstantiationRuntimeException(exp); } } public static <T> T newInstance(Class<T> clazz, Object... args) { Class<?>[] paramTypes = toClasses(args); try { return getConstructor(clazz, paramTypes).newInstance(args); } catch (IllegalAccessException exp) { throw new IllegalAccessRuntimeException(exp); } catch (InstantiationException exp) { throw new InstantiationRuntimeException(exp); } catch (IllegalArgumentException exp) { throw new IllegalArgumentRuntimeException(exp); } catch (InvocationTargetException exp) { throw new InvocationRuntimeException(exp); } } public static <T> Constructor<T> getConstructor(Class<T> clazz, Class<?>[] paramTypes) { try { return clazz.getConstructor(paramTypes); } catch (SecurityException exp) {
throw new SecurityRuntimeException(exp);
mixi-inc/triaina
android/Commons/src/triaina/commons/utils/ClassUtils.java
// Path: android/Commons/src/triaina/commons/exception/NotFoundRuntimeException.java // public class NotFoundRuntimeException extends CommonRuntimeException { // // private static final long serialVersionUID = 5486025835429632952L; // // public NotFoundRuntimeException() { // super(); // } // // public NotFoundRuntimeException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // } // // public NotFoundRuntimeException(String detailMessage) { // super(detailMessage); // } // // public NotFoundRuntimeException(Throwable throwable) { // super(throwable); // } // } // // Path: android/Commons/src/triaina/commons/exception/SecurityRuntimeException.java // public class SecurityRuntimeException extends CommonRuntimeException { // // private static final long serialVersionUID = 6244026068714272574L; // // private String mUrl; // // public SecurityRuntimeException() { // super(); // } // // public SecurityRuntimeException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // } // // public SecurityRuntimeException(String detailMessage) { // super(detailMessage); // } // // public SecurityRuntimeException(String detailMessage, String url) { // this(detailMessage); // mUrl = url; // } // // public SecurityRuntimeException(Throwable throwable) { // super(throwable); // } // // public SecurityRuntimeException(Throwable throwable, String url) { // this(throwable); // mUrl = url; // } // // public String getUrl(){ // return mUrl; // } // }
import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; import triaina.commons.exception.IllegalAccessRuntimeException; import triaina.commons.exception.IllegalArgumentRuntimeException; import triaina.commons.exception.InstantiationRuntimeException; import triaina.commons.exception.InvocationRuntimeException; import triaina.commons.exception.NotFoundRuntimeException; import triaina.commons.exception.SecurityRuntimeException;
return clazz.newInstance(); } catch (IllegalAccessException exp) { throw new IllegalAccessRuntimeException(exp); } catch (InstantiationException exp) { throw new InstantiationRuntimeException(exp); } } public static <T> T newInstance(Class<T> clazz, Object... args) { Class<?>[] paramTypes = toClasses(args); try { return getConstructor(clazz, paramTypes).newInstance(args); } catch (IllegalAccessException exp) { throw new IllegalAccessRuntimeException(exp); } catch (InstantiationException exp) { throw new InstantiationRuntimeException(exp); } catch (IllegalArgumentException exp) { throw new IllegalArgumentRuntimeException(exp); } catch (InvocationTargetException exp) { throw new InvocationRuntimeException(exp); } } public static <T> Constructor<T> getConstructor(Class<T> clazz, Class<?>[] paramTypes) { try { return clazz.getConstructor(paramTypes); } catch (SecurityException exp) { throw new SecurityRuntimeException(exp); } catch (NoSuchMethodException exp) {
// Path: android/Commons/src/triaina/commons/exception/NotFoundRuntimeException.java // public class NotFoundRuntimeException extends CommonRuntimeException { // // private static final long serialVersionUID = 5486025835429632952L; // // public NotFoundRuntimeException() { // super(); // } // // public NotFoundRuntimeException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // } // // public NotFoundRuntimeException(String detailMessage) { // super(detailMessage); // } // // public NotFoundRuntimeException(Throwable throwable) { // super(throwable); // } // } // // Path: android/Commons/src/triaina/commons/exception/SecurityRuntimeException.java // public class SecurityRuntimeException extends CommonRuntimeException { // // private static final long serialVersionUID = 6244026068714272574L; // // private String mUrl; // // public SecurityRuntimeException() { // super(); // } // // public SecurityRuntimeException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // } // // public SecurityRuntimeException(String detailMessage) { // super(detailMessage); // } // // public SecurityRuntimeException(String detailMessage, String url) { // this(detailMessage); // mUrl = url; // } // // public SecurityRuntimeException(Throwable throwable) { // super(throwable); // } // // public SecurityRuntimeException(Throwable throwable, String url) { // this(throwable); // mUrl = url; // } // // public String getUrl(){ // return mUrl; // } // } // Path: android/Commons/src/triaina/commons/utils/ClassUtils.java import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; import triaina.commons.exception.IllegalAccessRuntimeException; import triaina.commons.exception.IllegalArgumentRuntimeException; import triaina.commons.exception.InstantiationRuntimeException; import triaina.commons.exception.InvocationRuntimeException; import triaina.commons.exception.NotFoundRuntimeException; import triaina.commons.exception.SecurityRuntimeException; return clazz.newInstance(); } catch (IllegalAccessException exp) { throw new IllegalAccessRuntimeException(exp); } catch (InstantiationException exp) { throw new InstantiationRuntimeException(exp); } } public static <T> T newInstance(Class<T> clazz, Object... args) { Class<?>[] paramTypes = toClasses(args); try { return getConstructor(clazz, paramTypes).newInstance(args); } catch (IllegalAccessException exp) { throw new IllegalAccessRuntimeException(exp); } catch (InstantiationException exp) { throw new InstantiationRuntimeException(exp); } catch (IllegalArgumentException exp) { throw new IllegalArgumentRuntimeException(exp); } catch (InvocationTargetException exp) { throw new InvocationRuntimeException(exp); } } public static <T> Constructor<T> getConstructor(Class<T> clazz, Class<?>[] paramTypes) { try { return clazz.getConstructor(paramTypes); } catch (SecurityException exp) { throw new SecurityRuntimeException(exp); } catch (NoSuchMethodException exp) {
throw new NotFoundRuntimeException(exp);
mixi-inc/triaina
android/Injector/src/triaina/injector/fragment/TriainaDialogFragment.java
// Path: android/Injector/src/triaina/injector/TriainaInjectorFactory.java // public class TriainaInjectorFactory { // public static final Stage DEFAULT_STAGE = Stage.PRODUCTION; // // protected static WeakHashMap<Application,Injector> sInjectors = new WeakHashMap<Application,Injector>(); // protected static WeakHashMap<Application,ResourceListener> sResourceListeners = new WeakHashMap<Application, ResourceListener>(); // protected static WeakHashMap<Application,ViewListener> sViewListeners = new WeakHashMap<Application, ViewListener>(); // // private TriainaInjectorFactory() {} // // public static Injector getBaseApplicationInjector(Application application) { // Injector injector = sInjectors.get(application); // if(injector != null ) // return injector; // // synchronized (TriainaInjectorFactory.class) { // injector = sInjectors.get(application); // if(injector != null) // return injector; // // return setBaseApplicationInjector(application, DEFAULT_STAGE); // } // } // // public static Injector setBaseApplicationInjector(final Application application, Stage stage, Module... modules) { // for(Element element : Elements.getElements(modules)) { // element.acceptVisitor(new DefaultElementVisitor<Void>() { // @Override // public Void visit(StaticInjectionRequest element) { // getResourceListener(application).requestStaticInjection(element.getType()); // return null; // } // }); // } // // synchronized (TriainaInjectorFactory.class) { // final Injector injector = Guice.createInjector(stage, modules); // sInjectors.put(application, injector); // return injector; // } // } // // /** // * Return the cached Injector instance for this application, or create a new one if necessary. // */ // public static Injector setBaseApplicationInjector(Application application, Stage stage) { // synchronized (TriainaInjectorFactory.class) { // final int id = application.getResources().getIdentifier("triaina_modules", "array", application.getPackageName()); // final String[] moduleNames = id > 0 ? application.getResources().getStringArray(id) : new String[]{}; // final ArrayList<Module> modules = new ArrayList<Module>(); // final DefaultTriainaModule defaultRoboModule = newDefaultRoboModule(application); // // modules.add(defaultRoboModule); // // try { // for (String name : moduleNames) { // final Class<? extends Module> clazz = Class.forName(name).asSubclass(Module.class); // try { // modules.add(clazz.getDeclaredConstructor(Context.class).newInstance(application)); // } catch(final NoSuchMethodException noActivityConstructorException) { // modules.add(clazz.newInstance()); // } // } // } catch (Exception exp) { // throw new CommonRuntimeException(exp); // } // // final Injector injector = setBaseApplicationInjector(application, stage, modules.toArray(new Module[modules.size()])); // sInjectors.put(application, injector); // return injector; // } // } // // // public static TriainaInjector getInjector(Context context) { // final Application application = (Application)context.getApplicationContext(); // return new TriainaInjectorImpl(new ContextScopedRoboInjector(context, getBaseApplicationInjector(application), getViewListener(application))); // } // // public static <T> T injectMembers(Context context, T t) { // getInjector(context).injectMembers(t); // return t; // } // // public static DefaultTriainaModule newDefaultRoboModule(final Application application) { // return new DefaultTriainaModule(application, new ContextScope(), getViewListener(application), getResourceListener(application)); // } // // protected static ResourceListener getResourceListener(Application application ) { // ResourceListener resourceListener = sResourceListeners.get(application); // if(resourceListener == null) { // synchronized (TriainaInjectorFactory.class) { // if(resourceListener == null) { // resourceListener = new ResourceListener(application); // sResourceListeners.put(application,resourceListener); // } // } // } // return resourceListener; // } // // protected static ViewListener getViewListener(final Application application) { // ViewListener viewListener = sViewListeners.get(application); // if(viewListener == null) { // synchronized (TriainaInjectorFactory.class) { // if(viewListener==null) { // viewListener = new ViewListener(); // sViewListeners.put(application,viewListener); // } // } // } // // return viewListener; // } // // public static void destroyInjector(Context context) { // final TriainaInjector injector = getInjector(context); // injector.getInstance(EventManager.class).destroy(); // injector.getInstance(ContextScope.class).destroy(context); // sInjectors.remove(context); // } // }
import triaina.injector.TriainaInjector; import triaina.injector.TriainaInjectorFactory; import android.os.Bundle; import android.support.v4.app.DialogFragment; import android.view.View;
package triaina.injector.fragment; public abstract class TriainaDialogFragment extends DialogFragment { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
// Path: android/Injector/src/triaina/injector/TriainaInjectorFactory.java // public class TriainaInjectorFactory { // public static final Stage DEFAULT_STAGE = Stage.PRODUCTION; // // protected static WeakHashMap<Application,Injector> sInjectors = new WeakHashMap<Application,Injector>(); // protected static WeakHashMap<Application,ResourceListener> sResourceListeners = new WeakHashMap<Application, ResourceListener>(); // protected static WeakHashMap<Application,ViewListener> sViewListeners = new WeakHashMap<Application, ViewListener>(); // // private TriainaInjectorFactory() {} // // public static Injector getBaseApplicationInjector(Application application) { // Injector injector = sInjectors.get(application); // if(injector != null ) // return injector; // // synchronized (TriainaInjectorFactory.class) { // injector = sInjectors.get(application); // if(injector != null) // return injector; // // return setBaseApplicationInjector(application, DEFAULT_STAGE); // } // } // // public static Injector setBaseApplicationInjector(final Application application, Stage stage, Module... modules) { // for(Element element : Elements.getElements(modules)) { // element.acceptVisitor(new DefaultElementVisitor<Void>() { // @Override // public Void visit(StaticInjectionRequest element) { // getResourceListener(application).requestStaticInjection(element.getType()); // return null; // } // }); // } // // synchronized (TriainaInjectorFactory.class) { // final Injector injector = Guice.createInjector(stage, modules); // sInjectors.put(application, injector); // return injector; // } // } // // /** // * Return the cached Injector instance for this application, or create a new one if necessary. // */ // public static Injector setBaseApplicationInjector(Application application, Stage stage) { // synchronized (TriainaInjectorFactory.class) { // final int id = application.getResources().getIdentifier("triaina_modules", "array", application.getPackageName()); // final String[] moduleNames = id > 0 ? application.getResources().getStringArray(id) : new String[]{}; // final ArrayList<Module> modules = new ArrayList<Module>(); // final DefaultTriainaModule defaultRoboModule = newDefaultRoboModule(application); // // modules.add(defaultRoboModule); // // try { // for (String name : moduleNames) { // final Class<? extends Module> clazz = Class.forName(name).asSubclass(Module.class); // try { // modules.add(clazz.getDeclaredConstructor(Context.class).newInstance(application)); // } catch(final NoSuchMethodException noActivityConstructorException) { // modules.add(clazz.newInstance()); // } // } // } catch (Exception exp) { // throw new CommonRuntimeException(exp); // } // // final Injector injector = setBaseApplicationInjector(application, stage, modules.toArray(new Module[modules.size()])); // sInjectors.put(application, injector); // return injector; // } // } // // // public static TriainaInjector getInjector(Context context) { // final Application application = (Application)context.getApplicationContext(); // return new TriainaInjectorImpl(new ContextScopedRoboInjector(context, getBaseApplicationInjector(application), getViewListener(application))); // } // // public static <T> T injectMembers(Context context, T t) { // getInjector(context).injectMembers(t); // return t; // } // // public static DefaultTriainaModule newDefaultRoboModule(final Application application) { // return new DefaultTriainaModule(application, new ContextScope(), getViewListener(application), getResourceListener(application)); // } // // protected static ResourceListener getResourceListener(Application application ) { // ResourceListener resourceListener = sResourceListeners.get(application); // if(resourceListener == null) { // synchronized (TriainaInjectorFactory.class) { // if(resourceListener == null) { // resourceListener = new ResourceListener(application); // sResourceListeners.put(application,resourceListener); // } // } // } // return resourceListener; // } // // protected static ViewListener getViewListener(final Application application) { // ViewListener viewListener = sViewListeners.get(application); // if(viewListener == null) { // synchronized (TriainaInjectorFactory.class) { // if(viewListener==null) { // viewListener = new ViewListener(); // sViewListeners.put(application,viewListener); // } // } // } // // return viewListener; // } // // public static void destroyInjector(Context context) { // final TriainaInjector injector = getInjector(context); // injector.getInstance(EventManager.class).destroy(); // injector.getInstance(ContextScope.class).destroy(context); // sInjectors.remove(context); // } // } // Path: android/Injector/src/triaina/injector/fragment/TriainaDialogFragment.java import triaina.injector.TriainaInjector; import triaina.injector.TriainaInjectorFactory; import android.os.Bundle; import android.support.v4.app.DialogFragment; import android.view.View; package triaina.injector.fragment; public abstract class TriainaDialogFragment extends DialogFragment { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
TriainaInjector injector = TriainaInjectorFactory.getInjector(getActivity());
mixi-inc/triaina
android/Commons/src/triaina/commons/utils/CryptUtils.java
// Path: android/Commons/src/triaina/commons/exception/SecurityRuntimeException.java // public class SecurityRuntimeException extends CommonRuntimeException { // // private static final long serialVersionUID = 6244026068714272574L; // // private String mUrl; // // public SecurityRuntimeException() { // super(); // } // // public SecurityRuntimeException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // } // // public SecurityRuntimeException(String detailMessage) { // super(detailMessage); // } // // public SecurityRuntimeException(String detailMessage, String url) { // this(detailMessage); // mUrl = url; // } // // public SecurityRuntimeException(Throwable throwable) { // super(throwable); // } // // public SecurityRuntimeException(Throwable throwable, String url) { // this(throwable); // mUrl = url; // } // // public String getUrl(){ // return mUrl; // } // }
import java.security.GeneralSecurityException; import java.security.Key; import javax.crypto.Cipher; import triaina.commons.exception.SecurityRuntimeException;
package triaina.commons.utils; public final class CryptUtils { public static final String RSA_ECB_PKCS1_MODE = "RSA/ECB/PKCS1PADDING"; private CryptUtils() { } public static byte[] decrypt(String mode, byte[] soruce, Key key) { try { Cipher cipher = Cipher.getInstance(mode); cipher.init(Cipher.DECRYPT_MODE, key); return cipher.doFinal(soruce); } catch (GeneralSecurityException exp) {
// Path: android/Commons/src/triaina/commons/exception/SecurityRuntimeException.java // public class SecurityRuntimeException extends CommonRuntimeException { // // private static final long serialVersionUID = 6244026068714272574L; // // private String mUrl; // // public SecurityRuntimeException() { // super(); // } // // public SecurityRuntimeException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // } // // public SecurityRuntimeException(String detailMessage) { // super(detailMessage); // } // // public SecurityRuntimeException(String detailMessage, String url) { // this(detailMessage); // mUrl = url; // } // // public SecurityRuntimeException(Throwable throwable) { // super(throwable); // } // // public SecurityRuntimeException(Throwable throwable, String url) { // this(throwable); // mUrl = url; // } // // public String getUrl(){ // return mUrl; // } // } // Path: android/Commons/src/triaina/commons/utils/CryptUtils.java import java.security.GeneralSecurityException; import java.security.Key; import javax.crypto.Cipher; import triaina.commons.exception.SecurityRuntimeException; package triaina.commons.utils; public final class CryptUtils { public static final String RSA_ECB_PKCS1_MODE = "RSA/ECB/PKCS1PADDING"; private CryptUtils() { } public static byte[] decrypt(String mode, byte[] soruce, Key key) { try { Cipher cipher = Cipher.getInstance(mode); cipher.init(Cipher.DECRYPT_MODE, key); return cipher.doFinal(soruce); } catch (GeneralSecurityException exp) {
throw new SecurityRuntimeException(exp);
mixi-inc/triaina
android/Commons/tests/java/triaina/commons/test/utils/AsyncTaskUtilsTest.java
// Path: android/Commons/src/triaina/commons/utils/AsyncTaskUtils.java // public final class AsyncTaskUtils { // private AsyncTaskUtils() {} // // /** Returns whether the task specified as an argument is running or not. // * @param theTask {@link AsyncTask} to be checked. // * @return True if the task is running, false otherwise. // */ // public static boolean isRunning(final AsyncTask<?, ?, ?> theTask) { // return (theTask != null && // theTask.getStatus().equals(AsyncTask.Status.RUNNING)); // } // // /** // * Abort the running task. // * // * @param theTask // * @return True if the task has been successfully aborted. False otherwise. // */ // public static boolean abort(AsyncTask<?, ?, ?> theTask) { // if (!AsyncTaskUtils.isRunning(theTask)) { // return false; // } // theTask.cancel(true); // theTask = null; // return true; // } // }
import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import triaina.commons.utils.AsyncTaskUtils; import android.os.AsyncTask; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.test.AndroidTestCase;
} public void checkPoint() { checkLatch.countDown(); } public void waitForEnd() throws InterruptedException { endLatch.await(5000, TimeUnit.MILLISECONDS); } public boolean isEnded() { return endLatch.getCount() == 0; } private class TestTask extends AsyncTask<Void, Void, Void> { @Override protected Void doInBackground(Void... params) { startLatch.countDown(); try { checkLatch.await(5000, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { fail("interrupted"); } return null; } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); endLatch.countDown(); } }; } public void testIsRunning() {
// Path: android/Commons/src/triaina/commons/utils/AsyncTaskUtils.java // public final class AsyncTaskUtils { // private AsyncTaskUtils() {} // // /** Returns whether the task specified as an argument is running or not. // * @param theTask {@link AsyncTask} to be checked. // * @return True if the task is running, false otherwise. // */ // public static boolean isRunning(final AsyncTask<?, ?, ?> theTask) { // return (theTask != null && // theTask.getStatus().equals(AsyncTask.Status.RUNNING)); // } // // /** // * Abort the running task. // * // * @param theTask // * @return True if the task has been successfully aborted. False otherwise. // */ // public static boolean abort(AsyncTask<?, ?, ?> theTask) { // if (!AsyncTaskUtils.isRunning(theTask)) { // return false; // } // theTask.cancel(true); // theTask = null; // return true; // } // } // Path: android/Commons/tests/java/triaina/commons/test/utils/AsyncTaskUtilsTest.java import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import triaina.commons.utils.AsyncTaskUtils; import android.os.AsyncTask; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.test.AndroidTestCase; } public void checkPoint() { checkLatch.countDown(); } public void waitForEnd() throws InterruptedException { endLatch.await(5000, TimeUnit.MILLISECONDS); } public boolean isEnded() { return endLatch.getCount() == 0; } private class TestTask extends AsyncTask<Void, Void, Void> { @Override protected Void doInBackground(Void... params) { startLatch.countDown(); try { checkLatch.await(5000, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { fail("interrupted"); } return null; } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); endLatch.countDown(); } }; } public void testIsRunning() {
assertFalse("null is false", AsyncTaskUtils.isRunning(null));
mixi-inc/triaina
android/WebViewBridge/src/triaina/webview/CallbackHelper.java
// Path: android/Commons/src/triaina/commons/utils/ClassUtils.java // public final class ClassUtils { // // private ClassUtils() { // } // // public static <T> T newInstance(Class<T> clazz) { // try { // return clazz.newInstance(); // } catch (IllegalAccessException exp) { // throw new IllegalAccessRuntimeException(exp); // } catch (InstantiationException exp) { // throw new InstantiationRuntimeException(exp); // } // } // // public static <T> T newInstance(Class<T> clazz, Object... args) { // Class<?>[] paramTypes = toClasses(args); // try { // return getConstructor(clazz, paramTypes).newInstance(args); // } catch (IllegalAccessException exp) { // throw new IllegalAccessRuntimeException(exp); // } catch (InstantiationException exp) { // throw new InstantiationRuntimeException(exp); // } catch (IllegalArgumentException exp) { // throw new IllegalArgumentRuntimeException(exp); // } catch (InvocationTargetException exp) { // throw new InvocationRuntimeException(exp); // } // } // // public static <T> Constructor<T> getConstructor(Class<T> clazz, // Class<?>[] paramTypes) { // try { // return clazz.getConstructor(paramTypes); // } catch (SecurityException exp) { // throw new SecurityRuntimeException(exp); // } catch (NoSuchMethodException exp) { // throw new NotFoundRuntimeException(exp); // } // } // // public static Class<?>[] toClasses(Object... args) { // List<Class<?>> list = new ArrayList<Class<?>>(args.length); // for (Object obj : args) // list.add(obj.getClass()); // return list.toArray(new Class[list.size()]); // } // // public static boolean isImplement(Class<?> clazz, Class<?> interfaceClazz) { // if (clazz.equals(interfaceClazz)) // return true; // // Class<?>[] ifs = clazz.getInterfaces(); // for (Class<?> i : ifs) { // if (i.equals(interfaceClazz)) // return true; // } // // Class<?> s = clazz.getSuperclass(); // if (s == null || clazz.equals(s.getClass())) // return false; // // return isImplement(s, interfaceClazz); // } // // public static Method[] getMethodsByName(Class<?> clazz, String name) { // Method[] methods = clazz.getMethods(); // List<Method> list = new ArrayList<Method>(); // // for (Method method : methods) { // if (method.getName().equals(name)) // list.add(method); // } // // return list.toArray(new Method[list.size()]); // } // // public static Field getFiled(Class<?> clazz, String name) { // try { // return clazz.getField(name); // } catch (NoSuchFieldException exp) { // throw new NotFoundRuntimeException(exp); // } // } // // public static Field getDeclaredField(Class<?> clazz, String name) { // try { // return clazz.getDeclaredField(name); // } catch (NoSuchFieldException exp) { // throw new NotFoundRuntimeException(exp); // } // } // // public static Type[] getGenericType(Class<?> clazz, Class<?> interfaceClazz) { // Type st = clazz.getGenericSuperclass(); // Type[] ret = getActualTypeArguments(interfaceClazz, st); // // if (ret != null) // return ret; // // for (Type t : clazz.getGenericInterfaces()) { // ret = getActualTypeArguments(interfaceClazz, t); // if (ret != null) // return ret; // } // // Class<?> s = clazz.getSuperclass(); // if (s == null || clazz.equals(s.getClass())) // return new Type[0]; // // return getGenericType(s, interfaceClazz); // } // // private static Type[] getActualTypeArguments(Class<?> type, Type t) { // if (t != null && t instanceof ParameterizedType) { // ParameterizedType pt = (ParameterizedType) t; // if (pt.getRawType().equals(type)) // return ((ParameterizedType) t).getActualTypeArguments(); // } // return null; // } // // }
import java.lang.reflect.Method; import java.lang.reflect.Type; import triaina.commons.exception.JSONConvertException; import triaina.commons.exception.CommonRuntimeException; import triaina.commons.json.JSONConverter; import triaina.commons.utils.ClassUtils; import triaina.commons.utils.JSONObjectUtils; import triaina.webview.entity.Result; import org.json.JSONObject;
package triaina.webview; public class CallbackHelper { public void invokeSucceed(WebViewBridge bridge, Callback<Result> callback, JSONObject json) throws JSONConvertException { Class<?> resultClass = getResultClass(callback); Result result = (Result)JSONConverter.toObject(json, resultClass); callback.succeed(bridge, result); } public void invokeFail(WebViewBridge bridge, Callback<Result> callback, JSONObject json) { callback.fail(bridge, JSONObjectUtils.getString(json, "code"), JSONObjectUtils.getString(json, "message")); } public Class<?> getResultClass(Callback<?> callback) {
// Path: android/Commons/src/triaina/commons/utils/ClassUtils.java // public final class ClassUtils { // // private ClassUtils() { // } // // public static <T> T newInstance(Class<T> clazz) { // try { // return clazz.newInstance(); // } catch (IllegalAccessException exp) { // throw new IllegalAccessRuntimeException(exp); // } catch (InstantiationException exp) { // throw new InstantiationRuntimeException(exp); // } // } // // public static <T> T newInstance(Class<T> clazz, Object... args) { // Class<?>[] paramTypes = toClasses(args); // try { // return getConstructor(clazz, paramTypes).newInstance(args); // } catch (IllegalAccessException exp) { // throw new IllegalAccessRuntimeException(exp); // } catch (InstantiationException exp) { // throw new InstantiationRuntimeException(exp); // } catch (IllegalArgumentException exp) { // throw new IllegalArgumentRuntimeException(exp); // } catch (InvocationTargetException exp) { // throw new InvocationRuntimeException(exp); // } // } // // public static <T> Constructor<T> getConstructor(Class<T> clazz, // Class<?>[] paramTypes) { // try { // return clazz.getConstructor(paramTypes); // } catch (SecurityException exp) { // throw new SecurityRuntimeException(exp); // } catch (NoSuchMethodException exp) { // throw new NotFoundRuntimeException(exp); // } // } // // public static Class<?>[] toClasses(Object... args) { // List<Class<?>> list = new ArrayList<Class<?>>(args.length); // for (Object obj : args) // list.add(obj.getClass()); // return list.toArray(new Class[list.size()]); // } // // public static boolean isImplement(Class<?> clazz, Class<?> interfaceClazz) { // if (clazz.equals(interfaceClazz)) // return true; // // Class<?>[] ifs = clazz.getInterfaces(); // for (Class<?> i : ifs) { // if (i.equals(interfaceClazz)) // return true; // } // // Class<?> s = clazz.getSuperclass(); // if (s == null || clazz.equals(s.getClass())) // return false; // // return isImplement(s, interfaceClazz); // } // // public static Method[] getMethodsByName(Class<?> clazz, String name) { // Method[] methods = clazz.getMethods(); // List<Method> list = new ArrayList<Method>(); // // for (Method method : methods) { // if (method.getName().equals(name)) // list.add(method); // } // // return list.toArray(new Method[list.size()]); // } // // public static Field getFiled(Class<?> clazz, String name) { // try { // return clazz.getField(name); // } catch (NoSuchFieldException exp) { // throw new NotFoundRuntimeException(exp); // } // } // // public static Field getDeclaredField(Class<?> clazz, String name) { // try { // return clazz.getDeclaredField(name); // } catch (NoSuchFieldException exp) { // throw new NotFoundRuntimeException(exp); // } // } // // public static Type[] getGenericType(Class<?> clazz, Class<?> interfaceClazz) { // Type st = clazz.getGenericSuperclass(); // Type[] ret = getActualTypeArguments(interfaceClazz, st); // // if (ret != null) // return ret; // // for (Type t : clazz.getGenericInterfaces()) { // ret = getActualTypeArguments(interfaceClazz, t); // if (ret != null) // return ret; // } // // Class<?> s = clazz.getSuperclass(); // if (s == null || clazz.equals(s.getClass())) // return new Type[0]; // // return getGenericType(s, interfaceClazz); // } // // private static Type[] getActualTypeArguments(Class<?> type, Type t) { // if (t != null && t instanceof ParameterizedType) { // ParameterizedType pt = (ParameterizedType) t; // if (pt.getRawType().equals(type)) // return ((ParameterizedType) t).getActualTypeArguments(); // } // return null; // } // // } // Path: android/WebViewBridge/src/triaina/webview/CallbackHelper.java import java.lang.reflect.Method; import java.lang.reflect.Type; import triaina.commons.exception.JSONConvertException; import triaina.commons.exception.CommonRuntimeException; import triaina.commons.json.JSONConverter; import triaina.commons.utils.ClassUtils; import triaina.commons.utils.JSONObjectUtils; import triaina.webview.entity.Result; import org.json.JSONObject; package triaina.webview; public class CallbackHelper { public void invokeSucceed(WebViewBridge bridge, Callback<Result> callback, JSONObject json) throws JSONConvertException { Class<?> resultClass = getResultClass(callback); Result result = (Result)JSONConverter.toObject(json, resultClass); callback.succeed(bridge, result); } public void invokeFail(WebViewBridge bridge, Callback<Result> callback, JSONObject json) { callback.fail(bridge, JSONObjectUtils.getString(json, "code"), JSONObjectUtils.getString(json, "message")); } public Class<?> getResultClass(Callback<?> callback) {
Method[] methods = ClassUtils.getMethodsByName(callback.getClass(), "succeed");
mixi-inc/triaina
android/Commons/tests/java/triaina/commons/test/utils/SetUtilsTest.java
// Path: android/Commons/src/triaina/commons/utils/SetUtils.java // public final class SetUtils { // private SetUtils() {} // // @SuppressWarnings("unchecked") // public static <T> T[] toArray(Set<T> set, Class<?> clazz) { // return set.toArray((T[]) Array.newInstance(clazz, set.size())); // } // // public static <T> void addAll(Set<T> set, T[] arr) { // for (T t : arr) { // set.add(t); // } // } // }
import java.util.HashSet; import java.util.Set; import triaina.commons.utils.SetUtils; import junit.framework.TestCase;
package triaina.commons.test.utils; public class SetUtilsTest extends TestCase { public void testToArrayAndAddAll() { Set<String> set = new HashSet<String>(); set.add("a"); set.add("b"); set.add("c");
// Path: android/Commons/src/triaina/commons/utils/SetUtils.java // public final class SetUtils { // private SetUtils() {} // // @SuppressWarnings("unchecked") // public static <T> T[] toArray(Set<T> set, Class<?> clazz) { // return set.toArray((T[]) Array.newInstance(clazz, set.size())); // } // // public static <T> void addAll(Set<T> set, T[] arr) { // for (T t : arr) { // set.add(t); // } // } // } // Path: android/Commons/tests/java/triaina/commons/test/utils/SetUtilsTest.java import java.util.HashSet; import java.util.Set; import triaina.commons.utils.SetUtils; import junit.framework.TestCase; package triaina.commons.test.utils; public class SetUtilsTest extends TestCase { public void testToArrayAndAddAll() { Set<String> set = new HashSet<String>(); set.add("a"); set.add("b"); set.add("c");
String[] arr = SetUtils.toArray(set, String.class);
mixi-inc/triaina
android/WebViewBridge/src/triaina/webview/WebViewBridge.java
// Path: android/Commons/src/triaina/commons/exception/SecurityRuntimeException.java // public class SecurityRuntimeException extends CommonRuntimeException { // // private static final long serialVersionUID = 6244026068714272574L; // // private String mUrl; // // public SecurityRuntimeException() { // super(); // } // // public SecurityRuntimeException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // } // // public SecurityRuntimeException(String detailMessage) { // super(detailMessage); // } // // public SecurityRuntimeException(String detailMessage, String url) { // this(detailMessage); // mUrl = url; // } // // public SecurityRuntimeException(Throwable throwable) { // super(throwable); // } // // public SecurityRuntimeException(Throwable throwable, String url) { // this(throwable); // mUrl = url; // } // // public String getUrl(){ // return mUrl; // } // } // // Path: android/Commons/src/triaina/commons/utils/UriUtils.java // public final class UriUtils { // private UriUtils() { // } // // public static boolean compareDomain(Uri uri, String domain) { // if (domain == null) { // return false; // } // // //in case domain string contains port values we need to make sure we are getting right value // //we will need only host, so we only need scheme to parse url // Uri domainUri = Uri.parse("http://" + domain); // // String originialDomain = uri.getHost(); // String targetDomain = domainUri.getHost(); // if (originialDomain == null || targetDomain == null) return false; // // int diff = originialDomain.length() - targetDomain.length(); // // if (diff < 0) { //hosts do not match or originialDomain and targetDomain subdomains does not match // return false; // } else if (diff > 0) { // hosts do not match, but this might be because originialDomain might have a subdomain // if (hostHasMatchingSubdomain(diff, originialDomain)) // return false; // original domain does not have a subdomain or subdomains does not match // } // // return targetDomain.equals(originialDomain.substring(diff)); // } // // // private static boolean hostHasMatchingSubdomain(int diff, String originalDomain) { // return originalDomain.substring(diff - 1).charAt(0) != '.'; // } // // }
import android.content.Context; import android.graphics.Bitmap; import android.net.Uri; import android.net.http.SslError; import android.os.Build; import android.os.Handler; import android.os.Message; import android.text.TextUtils; import android.util.AttributeSet; import android.util.Log; import android.view.KeyEvent; import android.view.ViewGroup; import android.view.ViewParent; import android.webkit.HttpAuthHandler; import android.webkit.SslErrorHandler; import android.webkit.WebView; import android.webkit.WebViewClient; import org.json.JSONObject; import java.net.URLEncoder; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; import triaina.commons.exception.SecurityRuntimeException; import triaina.commons.json.JSONConverter; import triaina.commons.utils.JSONObjectUtils; import triaina.commons.utils.UriUtils; import triaina.webview.config.BridgeObjectConfig; import triaina.webview.config.DomainConfig; import triaina.webview.entity.Error; import triaina.webview.entity.Params; import triaina.webview.entity.Result; import triaina.webview.exception.SkipDomainCheckRuntimeException;
package triaina.webview; public class WebViewBridge extends WebView { public static final float VERSION = 1.2F; public static final double COMPATIBLE_VERSION = Math.floor(VERSION); private static final String TAG = WebViewBridge.class.getSimpleName(); private static final String JAVASCRIPT_INTERFACE_NAME = "DeviceBridge"; private Handler mHandler; private DomainConfig mDomainConfig; public static interface SecurityRuntimeExceptionResolver {
// Path: android/Commons/src/triaina/commons/exception/SecurityRuntimeException.java // public class SecurityRuntimeException extends CommonRuntimeException { // // private static final long serialVersionUID = 6244026068714272574L; // // private String mUrl; // // public SecurityRuntimeException() { // super(); // } // // public SecurityRuntimeException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // } // // public SecurityRuntimeException(String detailMessage) { // super(detailMessage); // } // // public SecurityRuntimeException(String detailMessage, String url) { // this(detailMessage); // mUrl = url; // } // // public SecurityRuntimeException(Throwable throwable) { // super(throwable); // } // // public SecurityRuntimeException(Throwable throwable, String url) { // this(throwable); // mUrl = url; // } // // public String getUrl(){ // return mUrl; // } // } // // Path: android/Commons/src/triaina/commons/utils/UriUtils.java // public final class UriUtils { // private UriUtils() { // } // // public static boolean compareDomain(Uri uri, String domain) { // if (domain == null) { // return false; // } // // //in case domain string contains port values we need to make sure we are getting right value // //we will need only host, so we only need scheme to parse url // Uri domainUri = Uri.parse("http://" + domain); // // String originialDomain = uri.getHost(); // String targetDomain = domainUri.getHost(); // if (originialDomain == null || targetDomain == null) return false; // // int diff = originialDomain.length() - targetDomain.length(); // // if (diff < 0) { //hosts do not match or originialDomain and targetDomain subdomains does not match // return false; // } else if (diff > 0) { // hosts do not match, but this might be because originialDomain might have a subdomain // if (hostHasMatchingSubdomain(diff, originialDomain)) // return false; // original domain does not have a subdomain or subdomains does not match // } // // return targetDomain.equals(originialDomain.substring(diff)); // } // // // private static boolean hostHasMatchingSubdomain(int diff, String originalDomain) { // return originalDomain.substring(diff - 1).charAt(0) != '.'; // } // // } // Path: android/WebViewBridge/src/triaina/webview/WebViewBridge.java import android.content.Context; import android.graphics.Bitmap; import android.net.Uri; import android.net.http.SslError; import android.os.Build; import android.os.Handler; import android.os.Message; import android.text.TextUtils; import android.util.AttributeSet; import android.util.Log; import android.view.KeyEvent; import android.view.ViewGroup; import android.view.ViewParent; import android.webkit.HttpAuthHandler; import android.webkit.SslErrorHandler; import android.webkit.WebView; import android.webkit.WebViewClient; import org.json.JSONObject; import java.net.URLEncoder; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; import triaina.commons.exception.SecurityRuntimeException; import triaina.commons.json.JSONConverter; import triaina.commons.utils.JSONObjectUtils; import triaina.commons.utils.UriUtils; import triaina.webview.config.BridgeObjectConfig; import triaina.webview.config.DomainConfig; import triaina.webview.entity.Error; import triaina.webview.entity.Params; import triaina.webview.entity.Result; import triaina.webview.exception.SkipDomainCheckRuntimeException; package triaina.webview; public class WebViewBridge extends WebView { public static final float VERSION = 1.2F; public static final double COMPATIBLE_VERSION = Math.floor(VERSION); private static final String TAG = WebViewBridge.class.getSimpleName(); private static final String JAVASCRIPT_INTERFACE_NAME = "DeviceBridge"; private Handler mHandler; private DomainConfig mDomainConfig; public static interface SecurityRuntimeExceptionResolver {
public void resolve(SecurityRuntimeException e);
mixi-inc/triaina
android/WebViewBridge/src/triaina/webview/WebViewBridge.java
// Path: android/Commons/src/triaina/commons/exception/SecurityRuntimeException.java // public class SecurityRuntimeException extends CommonRuntimeException { // // private static final long serialVersionUID = 6244026068714272574L; // // private String mUrl; // // public SecurityRuntimeException() { // super(); // } // // public SecurityRuntimeException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // } // // public SecurityRuntimeException(String detailMessage) { // super(detailMessage); // } // // public SecurityRuntimeException(String detailMessage, String url) { // this(detailMessage); // mUrl = url; // } // // public SecurityRuntimeException(Throwable throwable) { // super(throwable); // } // // public SecurityRuntimeException(Throwable throwable, String url) { // this(throwable); // mUrl = url; // } // // public String getUrl(){ // return mUrl; // } // } // // Path: android/Commons/src/triaina/commons/utils/UriUtils.java // public final class UriUtils { // private UriUtils() { // } // // public static boolean compareDomain(Uri uri, String domain) { // if (domain == null) { // return false; // } // // //in case domain string contains port values we need to make sure we are getting right value // //we will need only host, so we only need scheme to parse url // Uri domainUri = Uri.parse("http://" + domain); // // String originialDomain = uri.getHost(); // String targetDomain = domainUri.getHost(); // if (originialDomain == null || targetDomain == null) return false; // // int diff = originialDomain.length() - targetDomain.length(); // // if (diff < 0) { //hosts do not match or originialDomain and targetDomain subdomains does not match // return false; // } else if (diff > 0) { // hosts do not match, but this might be because originialDomain might have a subdomain // if (hostHasMatchingSubdomain(diff, originialDomain)) // return false; // original domain does not have a subdomain or subdomains does not match // } // // return targetDomain.equals(originialDomain.substring(diff)); // } // // // private static boolean hostHasMatchingSubdomain(int diff, String originalDomain) { // return originalDomain.substring(diff - 1).charAt(0) != '.'; // } // // }
import android.content.Context; import android.graphics.Bitmap; import android.net.Uri; import android.net.http.SslError; import android.os.Build; import android.os.Handler; import android.os.Message; import android.text.TextUtils; import android.util.AttributeSet; import android.util.Log; import android.view.KeyEvent; import android.view.ViewGroup; import android.view.ViewParent; import android.webkit.HttpAuthHandler; import android.webkit.SslErrorHandler; import android.webkit.WebView; import android.webkit.WebViewClient; import org.json.JSONObject; import java.net.URLEncoder; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; import triaina.commons.exception.SecurityRuntimeException; import triaina.commons.json.JSONConverter; import triaina.commons.utils.JSONObjectUtils; import triaina.commons.utils.UriUtils; import triaina.webview.config.BridgeObjectConfig; import triaina.webview.config.DomainConfig; import triaina.webview.entity.Error; import triaina.webview.entity.Params; import triaina.webview.entity.Result; import triaina.webview.exception.SkipDomainCheckRuntimeException;
public static class WebViewClientProxy extends WebViewClient { private WebViewClient mWebViewClient; private DomainConfig mDomainConfig; private SecurityRuntimeExceptionResolver mSecurityRuntimeExceptionResolver; public WebViewClientProxy(WebViewClient webViewClient, DomainConfig domainConfig) { this(webViewClient, domainConfig, null); } public WebViewClientProxy(WebViewClient webViewClient, DomainConfig domainConfig, SecurityRuntimeExceptionResolver resolver) { mWebViewClient = webViewClient; mDomainConfig = domainConfig; mSecurityRuntimeExceptionResolver = resolver; } public boolean shouldOverrideUrlLoading(WebView view, String url) { return mWebViewClient.shouldOverrideUrlLoading(view, url); } public void onPageStarted(WebView view, String url, Bitmap favicon) { try { // XXX ugly mWebViewClient.onPageStarted(view, url, favicon); } catch (SkipDomainCheckRuntimeException exp) { return; } Uri uri = Uri.parse(url); String[] domains = mDomainConfig.getDomains(); for (String domain : domains) {
// Path: android/Commons/src/triaina/commons/exception/SecurityRuntimeException.java // public class SecurityRuntimeException extends CommonRuntimeException { // // private static final long serialVersionUID = 6244026068714272574L; // // private String mUrl; // // public SecurityRuntimeException() { // super(); // } // // public SecurityRuntimeException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // } // // public SecurityRuntimeException(String detailMessage) { // super(detailMessage); // } // // public SecurityRuntimeException(String detailMessage, String url) { // this(detailMessage); // mUrl = url; // } // // public SecurityRuntimeException(Throwable throwable) { // super(throwable); // } // // public SecurityRuntimeException(Throwable throwable, String url) { // this(throwable); // mUrl = url; // } // // public String getUrl(){ // return mUrl; // } // } // // Path: android/Commons/src/triaina/commons/utils/UriUtils.java // public final class UriUtils { // private UriUtils() { // } // // public static boolean compareDomain(Uri uri, String domain) { // if (domain == null) { // return false; // } // // //in case domain string contains port values we need to make sure we are getting right value // //we will need only host, so we only need scheme to parse url // Uri domainUri = Uri.parse("http://" + domain); // // String originialDomain = uri.getHost(); // String targetDomain = domainUri.getHost(); // if (originialDomain == null || targetDomain == null) return false; // // int diff = originialDomain.length() - targetDomain.length(); // // if (diff < 0) { //hosts do not match or originialDomain and targetDomain subdomains does not match // return false; // } else if (diff > 0) { // hosts do not match, but this might be because originialDomain might have a subdomain // if (hostHasMatchingSubdomain(diff, originialDomain)) // return false; // original domain does not have a subdomain or subdomains does not match // } // // return targetDomain.equals(originialDomain.substring(diff)); // } // // // private static boolean hostHasMatchingSubdomain(int diff, String originalDomain) { // return originalDomain.substring(diff - 1).charAt(0) != '.'; // } // // } // Path: android/WebViewBridge/src/triaina/webview/WebViewBridge.java import android.content.Context; import android.graphics.Bitmap; import android.net.Uri; import android.net.http.SslError; import android.os.Build; import android.os.Handler; import android.os.Message; import android.text.TextUtils; import android.util.AttributeSet; import android.util.Log; import android.view.KeyEvent; import android.view.ViewGroup; import android.view.ViewParent; import android.webkit.HttpAuthHandler; import android.webkit.SslErrorHandler; import android.webkit.WebView; import android.webkit.WebViewClient; import org.json.JSONObject; import java.net.URLEncoder; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; import triaina.commons.exception.SecurityRuntimeException; import triaina.commons.json.JSONConverter; import triaina.commons.utils.JSONObjectUtils; import triaina.commons.utils.UriUtils; import triaina.webview.config.BridgeObjectConfig; import triaina.webview.config.DomainConfig; import triaina.webview.entity.Error; import triaina.webview.entity.Params; import triaina.webview.entity.Result; import triaina.webview.exception.SkipDomainCheckRuntimeException; public static class WebViewClientProxy extends WebViewClient { private WebViewClient mWebViewClient; private DomainConfig mDomainConfig; private SecurityRuntimeExceptionResolver mSecurityRuntimeExceptionResolver; public WebViewClientProxy(WebViewClient webViewClient, DomainConfig domainConfig) { this(webViewClient, domainConfig, null); } public WebViewClientProxy(WebViewClient webViewClient, DomainConfig domainConfig, SecurityRuntimeExceptionResolver resolver) { mWebViewClient = webViewClient; mDomainConfig = domainConfig; mSecurityRuntimeExceptionResolver = resolver; } public boolean shouldOverrideUrlLoading(WebView view, String url) { return mWebViewClient.shouldOverrideUrlLoading(view, url); } public void onPageStarted(WebView view, String url, Bitmap favicon) { try { // XXX ugly mWebViewClient.onPageStarted(view, url, favicon); } catch (SkipDomainCheckRuntimeException exp) { return; } Uri uri = Uri.parse(url); String[] domains = mDomainConfig.getDomains(); for (String domain : domains) {
if (UriUtils.compareDomain(uri, domain))
mixi-inc/triaina
android/Injector/src/triaina/injector/service/TriainaIntentService.java
// Path: android/Injector/src/triaina/injector/TriainaInjectorFactory.java // public class TriainaInjectorFactory { // public static final Stage DEFAULT_STAGE = Stage.PRODUCTION; // // protected static WeakHashMap<Application,Injector> sInjectors = new WeakHashMap<Application,Injector>(); // protected static WeakHashMap<Application,ResourceListener> sResourceListeners = new WeakHashMap<Application, ResourceListener>(); // protected static WeakHashMap<Application,ViewListener> sViewListeners = new WeakHashMap<Application, ViewListener>(); // // private TriainaInjectorFactory() {} // // public static Injector getBaseApplicationInjector(Application application) { // Injector injector = sInjectors.get(application); // if(injector != null ) // return injector; // // synchronized (TriainaInjectorFactory.class) { // injector = sInjectors.get(application); // if(injector != null) // return injector; // // return setBaseApplicationInjector(application, DEFAULT_STAGE); // } // } // // public static Injector setBaseApplicationInjector(final Application application, Stage stage, Module... modules) { // for(Element element : Elements.getElements(modules)) { // element.acceptVisitor(new DefaultElementVisitor<Void>() { // @Override // public Void visit(StaticInjectionRequest element) { // getResourceListener(application).requestStaticInjection(element.getType()); // return null; // } // }); // } // // synchronized (TriainaInjectorFactory.class) { // final Injector injector = Guice.createInjector(stage, modules); // sInjectors.put(application, injector); // return injector; // } // } // // /** // * Return the cached Injector instance for this application, or create a new one if necessary. // */ // public static Injector setBaseApplicationInjector(Application application, Stage stage) { // synchronized (TriainaInjectorFactory.class) { // final int id = application.getResources().getIdentifier("triaina_modules", "array", application.getPackageName()); // final String[] moduleNames = id > 0 ? application.getResources().getStringArray(id) : new String[]{}; // final ArrayList<Module> modules = new ArrayList<Module>(); // final DefaultTriainaModule defaultRoboModule = newDefaultRoboModule(application); // // modules.add(defaultRoboModule); // // try { // for (String name : moduleNames) { // final Class<? extends Module> clazz = Class.forName(name).asSubclass(Module.class); // try { // modules.add(clazz.getDeclaredConstructor(Context.class).newInstance(application)); // } catch(final NoSuchMethodException noActivityConstructorException) { // modules.add(clazz.newInstance()); // } // } // } catch (Exception exp) { // throw new CommonRuntimeException(exp); // } // // final Injector injector = setBaseApplicationInjector(application, stage, modules.toArray(new Module[modules.size()])); // sInjectors.put(application, injector); // return injector; // } // } // // // public static TriainaInjector getInjector(Context context) { // final Application application = (Application)context.getApplicationContext(); // return new TriainaInjectorImpl(new ContextScopedRoboInjector(context, getBaseApplicationInjector(application), getViewListener(application))); // } // // public static <T> T injectMembers(Context context, T t) { // getInjector(context).injectMembers(t); // return t; // } // // public static DefaultTriainaModule newDefaultRoboModule(final Application application) { // return new DefaultTriainaModule(application, new ContextScope(), getViewListener(application), getResourceListener(application)); // } // // protected static ResourceListener getResourceListener(Application application ) { // ResourceListener resourceListener = sResourceListeners.get(application); // if(resourceListener == null) { // synchronized (TriainaInjectorFactory.class) { // if(resourceListener == null) { // resourceListener = new ResourceListener(application); // sResourceListeners.put(application,resourceListener); // } // } // } // return resourceListener; // } // // protected static ViewListener getViewListener(final Application application) { // ViewListener viewListener = sViewListeners.get(application); // if(viewListener == null) { // synchronized (TriainaInjectorFactory.class) { // if(viewListener==null) { // viewListener = new ViewListener(); // sViewListeners.put(application,viewListener); // } // } // } // // return viewListener; // } // // public static void destroyInjector(Context context) { // final TriainaInjector injector = getInjector(context); // injector.getInstance(EventManager.class).destroy(); // injector.getInstance(ContextScope.class).destroy(context); // sInjectors.remove(context); // } // }
import triaina.injector.TriainaInjectorFactory; import android.app.IntentService;
package triaina.injector.service; public abstract class TriainaIntentService extends IntentService { public TriainaIntentService(String name) { super(name); } @Override public void onCreate() { super.onCreate();
// Path: android/Injector/src/triaina/injector/TriainaInjectorFactory.java // public class TriainaInjectorFactory { // public static final Stage DEFAULT_STAGE = Stage.PRODUCTION; // // protected static WeakHashMap<Application,Injector> sInjectors = new WeakHashMap<Application,Injector>(); // protected static WeakHashMap<Application,ResourceListener> sResourceListeners = new WeakHashMap<Application, ResourceListener>(); // protected static WeakHashMap<Application,ViewListener> sViewListeners = new WeakHashMap<Application, ViewListener>(); // // private TriainaInjectorFactory() {} // // public static Injector getBaseApplicationInjector(Application application) { // Injector injector = sInjectors.get(application); // if(injector != null ) // return injector; // // synchronized (TriainaInjectorFactory.class) { // injector = sInjectors.get(application); // if(injector != null) // return injector; // // return setBaseApplicationInjector(application, DEFAULT_STAGE); // } // } // // public static Injector setBaseApplicationInjector(final Application application, Stage stage, Module... modules) { // for(Element element : Elements.getElements(modules)) { // element.acceptVisitor(new DefaultElementVisitor<Void>() { // @Override // public Void visit(StaticInjectionRequest element) { // getResourceListener(application).requestStaticInjection(element.getType()); // return null; // } // }); // } // // synchronized (TriainaInjectorFactory.class) { // final Injector injector = Guice.createInjector(stage, modules); // sInjectors.put(application, injector); // return injector; // } // } // // /** // * Return the cached Injector instance for this application, or create a new one if necessary. // */ // public static Injector setBaseApplicationInjector(Application application, Stage stage) { // synchronized (TriainaInjectorFactory.class) { // final int id = application.getResources().getIdentifier("triaina_modules", "array", application.getPackageName()); // final String[] moduleNames = id > 0 ? application.getResources().getStringArray(id) : new String[]{}; // final ArrayList<Module> modules = new ArrayList<Module>(); // final DefaultTriainaModule defaultRoboModule = newDefaultRoboModule(application); // // modules.add(defaultRoboModule); // // try { // for (String name : moduleNames) { // final Class<? extends Module> clazz = Class.forName(name).asSubclass(Module.class); // try { // modules.add(clazz.getDeclaredConstructor(Context.class).newInstance(application)); // } catch(final NoSuchMethodException noActivityConstructorException) { // modules.add(clazz.newInstance()); // } // } // } catch (Exception exp) { // throw new CommonRuntimeException(exp); // } // // final Injector injector = setBaseApplicationInjector(application, stage, modules.toArray(new Module[modules.size()])); // sInjectors.put(application, injector); // return injector; // } // } // // // public static TriainaInjector getInjector(Context context) { // final Application application = (Application)context.getApplicationContext(); // return new TriainaInjectorImpl(new ContextScopedRoboInjector(context, getBaseApplicationInjector(application), getViewListener(application))); // } // // public static <T> T injectMembers(Context context, T t) { // getInjector(context).injectMembers(t); // return t; // } // // public static DefaultTriainaModule newDefaultRoboModule(final Application application) { // return new DefaultTriainaModule(application, new ContextScope(), getViewListener(application), getResourceListener(application)); // } // // protected static ResourceListener getResourceListener(Application application ) { // ResourceListener resourceListener = sResourceListeners.get(application); // if(resourceListener == null) { // synchronized (TriainaInjectorFactory.class) { // if(resourceListener == null) { // resourceListener = new ResourceListener(application); // sResourceListeners.put(application,resourceListener); // } // } // } // return resourceListener; // } // // protected static ViewListener getViewListener(final Application application) { // ViewListener viewListener = sViewListeners.get(application); // if(viewListener == null) { // synchronized (TriainaInjectorFactory.class) { // if(viewListener==null) { // viewListener = new ViewListener(); // sViewListeners.put(application,viewListener); // } // } // } // // return viewListener; // } // // public static void destroyInjector(Context context) { // final TriainaInjector injector = getInjector(context); // injector.getInstance(EventManager.class).destroy(); // injector.getInstance(ContextScope.class).destroy(context); // sInjectors.remove(context); // } // } // Path: android/Injector/src/triaina/injector/service/TriainaIntentService.java import triaina.injector.TriainaInjectorFactory; import android.app.IntentService; package triaina.injector.service; public abstract class TriainaIntentService extends IntentService { public TriainaIntentService(String name) { super(name); } @Override public void onCreate() { super.onCreate();
TriainaInjectorFactory.getInjector(this).injectMembersWithoutViews(this);
mixi-inc/triaina
android/WebViewBridge/tests/java/triaina/test/webview/WebViewClientProxyTest.java
// Path: android/Commons/src/triaina/commons/exception/SecurityRuntimeException.java // public class SecurityRuntimeException extends CommonRuntimeException { // // private static final long serialVersionUID = 6244026068714272574L; // // private String mUrl; // // public SecurityRuntimeException() { // super(); // } // // public SecurityRuntimeException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // } // // public SecurityRuntimeException(String detailMessage) { // super(detailMessage); // } // // public SecurityRuntimeException(String detailMessage, String url) { // this(detailMessage); // mUrl = url; // } // // public SecurityRuntimeException(Throwable throwable) { // super(throwable); // } // // public SecurityRuntimeException(Throwable throwable, String url) { // this(throwable); // mUrl = url; // } // // public String getUrl(){ // return mUrl; // } // } // // Path: android/WebViewBridge/src/triaina/webview/WebViewBridge.java // public static interface SecurityRuntimeExceptionResolver { // public void resolve(SecurityRuntimeException e); // } // // Path: android/WebViewBridge/src/triaina/webview/WebViewBridge.java // public static class WebViewClientProxy extends WebViewClient { // private WebViewClient mWebViewClient; // private DomainConfig mDomainConfig; // private SecurityRuntimeExceptionResolver mSecurityRuntimeExceptionResolver; // // public WebViewClientProxy(WebViewClient webViewClient, DomainConfig domainConfig) { // this(webViewClient, domainConfig, null); // } // // public WebViewClientProxy(WebViewClient webViewClient, DomainConfig domainConfig, SecurityRuntimeExceptionResolver resolver) { // mWebViewClient = webViewClient; // mDomainConfig = domainConfig; // mSecurityRuntimeExceptionResolver = resolver; // } // // public boolean shouldOverrideUrlLoading(WebView view, String url) { // return mWebViewClient.shouldOverrideUrlLoading(view, url); // } // // public void onPageStarted(WebView view, String url, Bitmap favicon) { // try { // // XXX ugly // mWebViewClient.onPageStarted(view, url, favicon); // } catch (SkipDomainCheckRuntimeException exp) { // return; // } // // Uri uri = Uri.parse(url); // String[] domains = mDomainConfig.getDomains(); // for (String domain : domains) { // if (UriUtils.compareDomain(uri, domain)) // return; // } // // SecurityRuntimeException exception = new SecurityRuntimeException("cannot load " + url, url); // if(mSecurityRuntimeExceptionResolver != null){ // mSecurityRuntimeExceptionResolver.resolve(exception); // } else { // throw exception; // } // } // // public void onPageFinished(WebView view, String url) { // mWebViewClient.onPageFinished(view, url); // } // // public void onLoadResource(WebView view, String url) { // mWebViewClient.onLoadResource(view, url); // } // // @SuppressWarnings("deprecation") // public void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg) { // mWebViewClient.onTooManyRedirects(view, cancelMsg, continueMsg); // } // // public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { // mWebViewClient.onReceivedError(view, errorCode, description, failingUrl); // } // // public boolean equals(Object o) { // return mWebViewClient.equals(o); // } // // public void onFormResubmission(WebView view, Message dontResend, Message resend) { // mWebViewClient.onFormResubmission(view, dontResend, resend); // } // // public void doUpdateVisitedHistory(WebView view, String url, boolean isReload) { // mWebViewClient.doUpdateVisitedHistory(view, url, isReload); // } // // public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) { // mWebViewClient.onReceivedSslError(view, handler, error); // } // // public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) { // mWebViewClient.onReceivedHttpAuthRequest(view, handler, host, realm); // } // // public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) { // return mWebViewClient.shouldOverrideKeyEvent(view, event); // } // // public int hashCode() { // return mWebViewClient.hashCode(); // } // // public void onUnhandledKeyEvent(WebView view, KeyEvent event) { // mWebViewClient.onUnhandledKeyEvent(view, event); // } // // public void onScaleChanged(WebView view, float oldScale, float newScale) { // mWebViewClient.onScaleChanged(view, oldScale, newScale); // } // // public String toString() { // return mWebViewClient.toString(); // } // }
import android.webkit.WebViewClient; import junit.framework.TestCase; import triaina.commons.exception.SecurityRuntimeException; import triaina.webview.WebViewBridge.SecurityRuntimeExceptionResolver; import triaina.webview.WebViewBridge.WebViewClientProxy; import triaina.webview.config.DomainConfig;
package triaina.test.webview; public class WebViewClientProxyTest extends TestCase { private DomainConfig mConfig; private static final String WRONG_URL = "http://mix.jp"; @Override protected void setUp() throws Exception { super.setUp(); mConfig = new DomainConfig(new String[]{"mixi.jp", "mixi.co.jp"}); } public void testOnPageStarted() {
// Path: android/Commons/src/triaina/commons/exception/SecurityRuntimeException.java // public class SecurityRuntimeException extends CommonRuntimeException { // // private static final long serialVersionUID = 6244026068714272574L; // // private String mUrl; // // public SecurityRuntimeException() { // super(); // } // // public SecurityRuntimeException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // } // // public SecurityRuntimeException(String detailMessage) { // super(detailMessage); // } // // public SecurityRuntimeException(String detailMessage, String url) { // this(detailMessage); // mUrl = url; // } // // public SecurityRuntimeException(Throwable throwable) { // super(throwable); // } // // public SecurityRuntimeException(Throwable throwable, String url) { // this(throwable); // mUrl = url; // } // // public String getUrl(){ // return mUrl; // } // } // // Path: android/WebViewBridge/src/triaina/webview/WebViewBridge.java // public static interface SecurityRuntimeExceptionResolver { // public void resolve(SecurityRuntimeException e); // } // // Path: android/WebViewBridge/src/triaina/webview/WebViewBridge.java // public static class WebViewClientProxy extends WebViewClient { // private WebViewClient mWebViewClient; // private DomainConfig mDomainConfig; // private SecurityRuntimeExceptionResolver mSecurityRuntimeExceptionResolver; // // public WebViewClientProxy(WebViewClient webViewClient, DomainConfig domainConfig) { // this(webViewClient, domainConfig, null); // } // // public WebViewClientProxy(WebViewClient webViewClient, DomainConfig domainConfig, SecurityRuntimeExceptionResolver resolver) { // mWebViewClient = webViewClient; // mDomainConfig = domainConfig; // mSecurityRuntimeExceptionResolver = resolver; // } // // public boolean shouldOverrideUrlLoading(WebView view, String url) { // return mWebViewClient.shouldOverrideUrlLoading(view, url); // } // // public void onPageStarted(WebView view, String url, Bitmap favicon) { // try { // // XXX ugly // mWebViewClient.onPageStarted(view, url, favicon); // } catch (SkipDomainCheckRuntimeException exp) { // return; // } // // Uri uri = Uri.parse(url); // String[] domains = mDomainConfig.getDomains(); // for (String domain : domains) { // if (UriUtils.compareDomain(uri, domain)) // return; // } // // SecurityRuntimeException exception = new SecurityRuntimeException("cannot load " + url, url); // if(mSecurityRuntimeExceptionResolver != null){ // mSecurityRuntimeExceptionResolver.resolve(exception); // } else { // throw exception; // } // } // // public void onPageFinished(WebView view, String url) { // mWebViewClient.onPageFinished(view, url); // } // // public void onLoadResource(WebView view, String url) { // mWebViewClient.onLoadResource(view, url); // } // // @SuppressWarnings("deprecation") // public void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg) { // mWebViewClient.onTooManyRedirects(view, cancelMsg, continueMsg); // } // // public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { // mWebViewClient.onReceivedError(view, errorCode, description, failingUrl); // } // // public boolean equals(Object o) { // return mWebViewClient.equals(o); // } // // public void onFormResubmission(WebView view, Message dontResend, Message resend) { // mWebViewClient.onFormResubmission(view, dontResend, resend); // } // // public void doUpdateVisitedHistory(WebView view, String url, boolean isReload) { // mWebViewClient.doUpdateVisitedHistory(view, url, isReload); // } // // public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) { // mWebViewClient.onReceivedSslError(view, handler, error); // } // // public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) { // mWebViewClient.onReceivedHttpAuthRequest(view, handler, host, realm); // } // // public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) { // return mWebViewClient.shouldOverrideKeyEvent(view, event); // } // // public int hashCode() { // return mWebViewClient.hashCode(); // } // // public void onUnhandledKeyEvent(WebView view, KeyEvent event) { // mWebViewClient.onUnhandledKeyEvent(view, event); // } // // public void onScaleChanged(WebView view, float oldScale, float newScale) { // mWebViewClient.onScaleChanged(view, oldScale, newScale); // } // // public String toString() { // return mWebViewClient.toString(); // } // } // Path: android/WebViewBridge/tests/java/triaina/test/webview/WebViewClientProxyTest.java import android.webkit.WebViewClient; import junit.framework.TestCase; import triaina.commons.exception.SecurityRuntimeException; import triaina.webview.WebViewBridge.SecurityRuntimeExceptionResolver; import triaina.webview.WebViewBridge.WebViewClientProxy; import triaina.webview.config.DomainConfig; package triaina.test.webview; public class WebViewClientProxyTest extends TestCase { private DomainConfig mConfig; private static final String WRONG_URL = "http://mix.jp"; @Override protected void setUp() throws Exception { super.setUp(); mConfig = new DomainConfig(new String[]{"mixi.jp", "mixi.co.jp"}); } public void testOnPageStarted() {
WebViewClient client = new WebViewClientProxy(new WebViewClient(), mConfig);
mixi-inc/triaina
android/WebViewBridge/tests/java/triaina/test/webview/WebViewClientProxyTest.java
// Path: android/Commons/src/triaina/commons/exception/SecurityRuntimeException.java // public class SecurityRuntimeException extends CommonRuntimeException { // // private static final long serialVersionUID = 6244026068714272574L; // // private String mUrl; // // public SecurityRuntimeException() { // super(); // } // // public SecurityRuntimeException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // } // // public SecurityRuntimeException(String detailMessage) { // super(detailMessage); // } // // public SecurityRuntimeException(String detailMessage, String url) { // this(detailMessage); // mUrl = url; // } // // public SecurityRuntimeException(Throwable throwable) { // super(throwable); // } // // public SecurityRuntimeException(Throwable throwable, String url) { // this(throwable); // mUrl = url; // } // // public String getUrl(){ // return mUrl; // } // } // // Path: android/WebViewBridge/src/triaina/webview/WebViewBridge.java // public static interface SecurityRuntimeExceptionResolver { // public void resolve(SecurityRuntimeException e); // } // // Path: android/WebViewBridge/src/triaina/webview/WebViewBridge.java // public static class WebViewClientProxy extends WebViewClient { // private WebViewClient mWebViewClient; // private DomainConfig mDomainConfig; // private SecurityRuntimeExceptionResolver mSecurityRuntimeExceptionResolver; // // public WebViewClientProxy(WebViewClient webViewClient, DomainConfig domainConfig) { // this(webViewClient, domainConfig, null); // } // // public WebViewClientProxy(WebViewClient webViewClient, DomainConfig domainConfig, SecurityRuntimeExceptionResolver resolver) { // mWebViewClient = webViewClient; // mDomainConfig = domainConfig; // mSecurityRuntimeExceptionResolver = resolver; // } // // public boolean shouldOverrideUrlLoading(WebView view, String url) { // return mWebViewClient.shouldOverrideUrlLoading(view, url); // } // // public void onPageStarted(WebView view, String url, Bitmap favicon) { // try { // // XXX ugly // mWebViewClient.onPageStarted(view, url, favicon); // } catch (SkipDomainCheckRuntimeException exp) { // return; // } // // Uri uri = Uri.parse(url); // String[] domains = mDomainConfig.getDomains(); // for (String domain : domains) { // if (UriUtils.compareDomain(uri, domain)) // return; // } // // SecurityRuntimeException exception = new SecurityRuntimeException("cannot load " + url, url); // if(mSecurityRuntimeExceptionResolver != null){ // mSecurityRuntimeExceptionResolver.resolve(exception); // } else { // throw exception; // } // } // // public void onPageFinished(WebView view, String url) { // mWebViewClient.onPageFinished(view, url); // } // // public void onLoadResource(WebView view, String url) { // mWebViewClient.onLoadResource(view, url); // } // // @SuppressWarnings("deprecation") // public void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg) { // mWebViewClient.onTooManyRedirects(view, cancelMsg, continueMsg); // } // // public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { // mWebViewClient.onReceivedError(view, errorCode, description, failingUrl); // } // // public boolean equals(Object o) { // return mWebViewClient.equals(o); // } // // public void onFormResubmission(WebView view, Message dontResend, Message resend) { // mWebViewClient.onFormResubmission(view, dontResend, resend); // } // // public void doUpdateVisitedHistory(WebView view, String url, boolean isReload) { // mWebViewClient.doUpdateVisitedHistory(view, url, isReload); // } // // public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) { // mWebViewClient.onReceivedSslError(view, handler, error); // } // // public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) { // mWebViewClient.onReceivedHttpAuthRequest(view, handler, host, realm); // } // // public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) { // return mWebViewClient.shouldOverrideKeyEvent(view, event); // } // // public int hashCode() { // return mWebViewClient.hashCode(); // } // // public void onUnhandledKeyEvent(WebView view, KeyEvent event) { // mWebViewClient.onUnhandledKeyEvent(view, event); // } // // public void onScaleChanged(WebView view, float oldScale, float newScale) { // mWebViewClient.onScaleChanged(view, oldScale, newScale); // } // // public String toString() { // return mWebViewClient.toString(); // } // }
import android.webkit.WebViewClient; import junit.framework.TestCase; import triaina.commons.exception.SecurityRuntimeException; import triaina.webview.WebViewBridge.SecurityRuntimeExceptionResolver; import triaina.webview.WebViewBridge.WebViewClientProxy; import triaina.webview.config.DomainConfig;
package triaina.test.webview; public class WebViewClientProxyTest extends TestCase { private DomainConfig mConfig; private static final String WRONG_URL = "http://mix.jp"; @Override protected void setUp() throws Exception { super.setUp(); mConfig = new DomainConfig(new String[]{"mixi.jp", "mixi.co.jp"}); } public void testOnPageStarted() { WebViewClient client = new WebViewClientProxy(new WebViewClient(), mConfig); client.onPageStarted(null, "http://mixi.jp", null); client.onPageStarted(null, "http://mixi.co.jp", null); client.onPageStarted(null, "http://t.mixi.jp", null); client.onPageStarted(null, "http://t.mixi.co.jp", null); } public void testOriginalOnPageStartedOnException() { try { WebViewClient client = new WebViewClientProxy(new WebViewClient(), mConfig); client.onPageStarted(null, WRONG_URL, null); fail();
// Path: android/Commons/src/triaina/commons/exception/SecurityRuntimeException.java // public class SecurityRuntimeException extends CommonRuntimeException { // // private static final long serialVersionUID = 6244026068714272574L; // // private String mUrl; // // public SecurityRuntimeException() { // super(); // } // // public SecurityRuntimeException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // } // // public SecurityRuntimeException(String detailMessage) { // super(detailMessage); // } // // public SecurityRuntimeException(String detailMessage, String url) { // this(detailMessage); // mUrl = url; // } // // public SecurityRuntimeException(Throwable throwable) { // super(throwable); // } // // public SecurityRuntimeException(Throwable throwable, String url) { // this(throwable); // mUrl = url; // } // // public String getUrl(){ // return mUrl; // } // } // // Path: android/WebViewBridge/src/triaina/webview/WebViewBridge.java // public static interface SecurityRuntimeExceptionResolver { // public void resolve(SecurityRuntimeException e); // } // // Path: android/WebViewBridge/src/triaina/webview/WebViewBridge.java // public static class WebViewClientProxy extends WebViewClient { // private WebViewClient mWebViewClient; // private DomainConfig mDomainConfig; // private SecurityRuntimeExceptionResolver mSecurityRuntimeExceptionResolver; // // public WebViewClientProxy(WebViewClient webViewClient, DomainConfig domainConfig) { // this(webViewClient, domainConfig, null); // } // // public WebViewClientProxy(WebViewClient webViewClient, DomainConfig domainConfig, SecurityRuntimeExceptionResolver resolver) { // mWebViewClient = webViewClient; // mDomainConfig = domainConfig; // mSecurityRuntimeExceptionResolver = resolver; // } // // public boolean shouldOverrideUrlLoading(WebView view, String url) { // return mWebViewClient.shouldOverrideUrlLoading(view, url); // } // // public void onPageStarted(WebView view, String url, Bitmap favicon) { // try { // // XXX ugly // mWebViewClient.onPageStarted(view, url, favicon); // } catch (SkipDomainCheckRuntimeException exp) { // return; // } // // Uri uri = Uri.parse(url); // String[] domains = mDomainConfig.getDomains(); // for (String domain : domains) { // if (UriUtils.compareDomain(uri, domain)) // return; // } // // SecurityRuntimeException exception = new SecurityRuntimeException("cannot load " + url, url); // if(mSecurityRuntimeExceptionResolver != null){ // mSecurityRuntimeExceptionResolver.resolve(exception); // } else { // throw exception; // } // } // // public void onPageFinished(WebView view, String url) { // mWebViewClient.onPageFinished(view, url); // } // // public void onLoadResource(WebView view, String url) { // mWebViewClient.onLoadResource(view, url); // } // // @SuppressWarnings("deprecation") // public void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg) { // mWebViewClient.onTooManyRedirects(view, cancelMsg, continueMsg); // } // // public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { // mWebViewClient.onReceivedError(view, errorCode, description, failingUrl); // } // // public boolean equals(Object o) { // return mWebViewClient.equals(o); // } // // public void onFormResubmission(WebView view, Message dontResend, Message resend) { // mWebViewClient.onFormResubmission(view, dontResend, resend); // } // // public void doUpdateVisitedHistory(WebView view, String url, boolean isReload) { // mWebViewClient.doUpdateVisitedHistory(view, url, isReload); // } // // public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) { // mWebViewClient.onReceivedSslError(view, handler, error); // } // // public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) { // mWebViewClient.onReceivedHttpAuthRequest(view, handler, host, realm); // } // // public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) { // return mWebViewClient.shouldOverrideKeyEvent(view, event); // } // // public int hashCode() { // return mWebViewClient.hashCode(); // } // // public void onUnhandledKeyEvent(WebView view, KeyEvent event) { // mWebViewClient.onUnhandledKeyEvent(view, event); // } // // public void onScaleChanged(WebView view, float oldScale, float newScale) { // mWebViewClient.onScaleChanged(view, oldScale, newScale); // } // // public String toString() { // return mWebViewClient.toString(); // } // } // Path: android/WebViewBridge/tests/java/triaina/test/webview/WebViewClientProxyTest.java import android.webkit.WebViewClient; import junit.framework.TestCase; import triaina.commons.exception.SecurityRuntimeException; import triaina.webview.WebViewBridge.SecurityRuntimeExceptionResolver; import triaina.webview.WebViewBridge.WebViewClientProxy; import triaina.webview.config.DomainConfig; package triaina.test.webview; public class WebViewClientProxyTest extends TestCase { private DomainConfig mConfig; private static final String WRONG_URL = "http://mix.jp"; @Override protected void setUp() throws Exception { super.setUp(); mConfig = new DomainConfig(new String[]{"mixi.jp", "mixi.co.jp"}); } public void testOnPageStarted() { WebViewClient client = new WebViewClientProxy(new WebViewClient(), mConfig); client.onPageStarted(null, "http://mixi.jp", null); client.onPageStarted(null, "http://mixi.co.jp", null); client.onPageStarted(null, "http://t.mixi.jp", null); client.onPageStarted(null, "http://t.mixi.co.jp", null); } public void testOriginalOnPageStartedOnException() { try { WebViewClient client = new WebViewClientProxy(new WebViewClient(), mConfig); client.onPageStarted(null, WRONG_URL, null); fail();
} catch (SecurityRuntimeException e) {
mixi-inc/triaina
android/WebViewBridge/tests/java/triaina/test/webview/WebViewClientProxyTest.java
// Path: android/Commons/src/triaina/commons/exception/SecurityRuntimeException.java // public class SecurityRuntimeException extends CommonRuntimeException { // // private static final long serialVersionUID = 6244026068714272574L; // // private String mUrl; // // public SecurityRuntimeException() { // super(); // } // // public SecurityRuntimeException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // } // // public SecurityRuntimeException(String detailMessage) { // super(detailMessage); // } // // public SecurityRuntimeException(String detailMessage, String url) { // this(detailMessage); // mUrl = url; // } // // public SecurityRuntimeException(Throwable throwable) { // super(throwable); // } // // public SecurityRuntimeException(Throwable throwable, String url) { // this(throwable); // mUrl = url; // } // // public String getUrl(){ // return mUrl; // } // } // // Path: android/WebViewBridge/src/triaina/webview/WebViewBridge.java // public static interface SecurityRuntimeExceptionResolver { // public void resolve(SecurityRuntimeException e); // } // // Path: android/WebViewBridge/src/triaina/webview/WebViewBridge.java // public static class WebViewClientProxy extends WebViewClient { // private WebViewClient mWebViewClient; // private DomainConfig mDomainConfig; // private SecurityRuntimeExceptionResolver mSecurityRuntimeExceptionResolver; // // public WebViewClientProxy(WebViewClient webViewClient, DomainConfig domainConfig) { // this(webViewClient, domainConfig, null); // } // // public WebViewClientProxy(WebViewClient webViewClient, DomainConfig domainConfig, SecurityRuntimeExceptionResolver resolver) { // mWebViewClient = webViewClient; // mDomainConfig = domainConfig; // mSecurityRuntimeExceptionResolver = resolver; // } // // public boolean shouldOverrideUrlLoading(WebView view, String url) { // return mWebViewClient.shouldOverrideUrlLoading(view, url); // } // // public void onPageStarted(WebView view, String url, Bitmap favicon) { // try { // // XXX ugly // mWebViewClient.onPageStarted(view, url, favicon); // } catch (SkipDomainCheckRuntimeException exp) { // return; // } // // Uri uri = Uri.parse(url); // String[] domains = mDomainConfig.getDomains(); // for (String domain : domains) { // if (UriUtils.compareDomain(uri, domain)) // return; // } // // SecurityRuntimeException exception = new SecurityRuntimeException("cannot load " + url, url); // if(mSecurityRuntimeExceptionResolver != null){ // mSecurityRuntimeExceptionResolver.resolve(exception); // } else { // throw exception; // } // } // // public void onPageFinished(WebView view, String url) { // mWebViewClient.onPageFinished(view, url); // } // // public void onLoadResource(WebView view, String url) { // mWebViewClient.onLoadResource(view, url); // } // // @SuppressWarnings("deprecation") // public void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg) { // mWebViewClient.onTooManyRedirects(view, cancelMsg, continueMsg); // } // // public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { // mWebViewClient.onReceivedError(view, errorCode, description, failingUrl); // } // // public boolean equals(Object o) { // return mWebViewClient.equals(o); // } // // public void onFormResubmission(WebView view, Message dontResend, Message resend) { // mWebViewClient.onFormResubmission(view, dontResend, resend); // } // // public void doUpdateVisitedHistory(WebView view, String url, boolean isReload) { // mWebViewClient.doUpdateVisitedHistory(view, url, isReload); // } // // public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) { // mWebViewClient.onReceivedSslError(view, handler, error); // } // // public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) { // mWebViewClient.onReceivedHttpAuthRequest(view, handler, host, realm); // } // // public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) { // return mWebViewClient.shouldOverrideKeyEvent(view, event); // } // // public int hashCode() { // return mWebViewClient.hashCode(); // } // // public void onUnhandledKeyEvent(WebView view, KeyEvent event) { // mWebViewClient.onUnhandledKeyEvent(view, event); // } // // public void onScaleChanged(WebView view, float oldScale, float newScale) { // mWebViewClient.onScaleChanged(view, oldScale, newScale); // } // // public String toString() { // return mWebViewClient.toString(); // } // }
import android.webkit.WebViewClient; import junit.framework.TestCase; import triaina.commons.exception.SecurityRuntimeException; import triaina.webview.WebViewBridge.SecurityRuntimeExceptionResolver; import triaina.webview.WebViewBridge.WebViewClientProxy; import triaina.webview.config.DomainConfig;
client.onPageStarted(null, "http://t.mixi.co.jp", null); } public void testOriginalOnPageStartedOnException() { try { WebViewClient client = new WebViewClientProxy(new WebViewClient(), mConfig); client.onPageStarted(null, WRONG_URL, null); fail(); } catch (SecurityRuntimeException e) { assertTrue(true); } catch (Exception e) { fail(); } } public void testOnPageStartedOnExceptionWithoutExceptionResolver() { try { WebViewClient client = new WebViewClientProxy(new WebViewClient(), mConfig, null); client.onPageStarted(null, WRONG_URL, null); fail(); } catch (SecurityRuntimeException e) { assertTrue(true); } catch (Exception e) { fail(); } } public void testOnPageStartedOnExceptionHandlingWithExceptionResolver() { try {
// Path: android/Commons/src/triaina/commons/exception/SecurityRuntimeException.java // public class SecurityRuntimeException extends CommonRuntimeException { // // private static final long serialVersionUID = 6244026068714272574L; // // private String mUrl; // // public SecurityRuntimeException() { // super(); // } // // public SecurityRuntimeException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // } // // public SecurityRuntimeException(String detailMessage) { // super(detailMessage); // } // // public SecurityRuntimeException(String detailMessage, String url) { // this(detailMessage); // mUrl = url; // } // // public SecurityRuntimeException(Throwable throwable) { // super(throwable); // } // // public SecurityRuntimeException(Throwable throwable, String url) { // this(throwable); // mUrl = url; // } // // public String getUrl(){ // return mUrl; // } // } // // Path: android/WebViewBridge/src/triaina/webview/WebViewBridge.java // public static interface SecurityRuntimeExceptionResolver { // public void resolve(SecurityRuntimeException e); // } // // Path: android/WebViewBridge/src/triaina/webview/WebViewBridge.java // public static class WebViewClientProxy extends WebViewClient { // private WebViewClient mWebViewClient; // private DomainConfig mDomainConfig; // private SecurityRuntimeExceptionResolver mSecurityRuntimeExceptionResolver; // // public WebViewClientProxy(WebViewClient webViewClient, DomainConfig domainConfig) { // this(webViewClient, domainConfig, null); // } // // public WebViewClientProxy(WebViewClient webViewClient, DomainConfig domainConfig, SecurityRuntimeExceptionResolver resolver) { // mWebViewClient = webViewClient; // mDomainConfig = domainConfig; // mSecurityRuntimeExceptionResolver = resolver; // } // // public boolean shouldOverrideUrlLoading(WebView view, String url) { // return mWebViewClient.shouldOverrideUrlLoading(view, url); // } // // public void onPageStarted(WebView view, String url, Bitmap favicon) { // try { // // XXX ugly // mWebViewClient.onPageStarted(view, url, favicon); // } catch (SkipDomainCheckRuntimeException exp) { // return; // } // // Uri uri = Uri.parse(url); // String[] domains = mDomainConfig.getDomains(); // for (String domain : domains) { // if (UriUtils.compareDomain(uri, domain)) // return; // } // // SecurityRuntimeException exception = new SecurityRuntimeException("cannot load " + url, url); // if(mSecurityRuntimeExceptionResolver != null){ // mSecurityRuntimeExceptionResolver.resolve(exception); // } else { // throw exception; // } // } // // public void onPageFinished(WebView view, String url) { // mWebViewClient.onPageFinished(view, url); // } // // public void onLoadResource(WebView view, String url) { // mWebViewClient.onLoadResource(view, url); // } // // @SuppressWarnings("deprecation") // public void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg) { // mWebViewClient.onTooManyRedirects(view, cancelMsg, continueMsg); // } // // public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { // mWebViewClient.onReceivedError(view, errorCode, description, failingUrl); // } // // public boolean equals(Object o) { // return mWebViewClient.equals(o); // } // // public void onFormResubmission(WebView view, Message dontResend, Message resend) { // mWebViewClient.onFormResubmission(view, dontResend, resend); // } // // public void doUpdateVisitedHistory(WebView view, String url, boolean isReload) { // mWebViewClient.doUpdateVisitedHistory(view, url, isReload); // } // // public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) { // mWebViewClient.onReceivedSslError(view, handler, error); // } // // public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) { // mWebViewClient.onReceivedHttpAuthRequest(view, handler, host, realm); // } // // public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) { // return mWebViewClient.shouldOverrideKeyEvent(view, event); // } // // public int hashCode() { // return mWebViewClient.hashCode(); // } // // public void onUnhandledKeyEvent(WebView view, KeyEvent event) { // mWebViewClient.onUnhandledKeyEvent(view, event); // } // // public void onScaleChanged(WebView view, float oldScale, float newScale) { // mWebViewClient.onScaleChanged(view, oldScale, newScale); // } // // public String toString() { // return mWebViewClient.toString(); // } // } // Path: android/WebViewBridge/tests/java/triaina/test/webview/WebViewClientProxyTest.java import android.webkit.WebViewClient; import junit.framework.TestCase; import triaina.commons.exception.SecurityRuntimeException; import triaina.webview.WebViewBridge.SecurityRuntimeExceptionResolver; import triaina.webview.WebViewBridge.WebViewClientProxy; import triaina.webview.config.DomainConfig; client.onPageStarted(null, "http://t.mixi.co.jp", null); } public void testOriginalOnPageStartedOnException() { try { WebViewClient client = new WebViewClientProxy(new WebViewClient(), mConfig); client.onPageStarted(null, WRONG_URL, null); fail(); } catch (SecurityRuntimeException e) { assertTrue(true); } catch (Exception e) { fail(); } } public void testOnPageStartedOnExceptionWithoutExceptionResolver() { try { WebViewClient client = new WebViewClientProxy(new WebViewClient(), mConfig, null); client.onPageStarted(null, WRONG_URL, null); fail(); } catch (SecurityRuntimeException e) { assertTrue(true); } catch (Exception e) { fail(); } } public void testOnPageStartedOnExceptionHandlingWithExceptionResolver() { try {
SecurityRuntimeExceptionResolver resolver = new SecurityRuntimeExceptionResolver() {
mixi-inc/triaina
android/Injector/src/triaina/injector/service/TriainaService.java
// Path: android/Injector/src/triaina/injector/TriainaInjectorFactory.java // public class TriainaInjectorFactory { // public static final Stage DEFAULT_STAGE = Stage.PRODUCTION; // // protected static WeakHashMap<Application,Injector> sInjectors = new WeakHashMap<Application,Injector>(); // protected static WeakHashMap<Application,ResourceListener> sResourceListeners = new WeakHashMap<Application, ResourceListener>(); // protected static WeakHashMap<Application,ViewListener> sViewListeners = new WeakHashMap<Application, ViewListener>(); // // private TriainaInjectorFactory() {} // // public static Injector getBaseApplicationInjector(Application application) { // Injector injector = sInjectors.get(application); // if(injector != null ) // return injector; // // synchronized (TriainaInjectorFactory.class) { // injector = sInjectors.get(application); // if(injector != null) // return injector; // // return setBaseApplicationInjector(application, DEFAULT_STAGE); // } // } // // public static Injector setBaseApplicationInjector(final Application application, Stage stage, Module... modules) { // for(Element element : Elements.getElements(modules)) { // element.acceptVisitor(new DefaultElementVisitor<Void>() { // @Override // public Void visit(StaticInjectionRequest element) { // getResourceListener(application).requestStaticInjection(element.getType()); // return null; // } // }); // } // // synchronized (TriainaInjectorFactory.class) { // final Injector injector = Guice.createInjector(stage, modules); // sInjectors.put(application, injector); // return injector; // } // } // // /** // * Return the cached Injector instance for this application, or create a new one if necessary. // */ // public static Injector setBaseApplicationInjector(Application application, Stage stage) { // synchronized (TriainaInjectorFactory.class) { // final int id = application.getResources().getIdentifier("triaina_modules", "array", application.getPackageName()); // final String[] moduleNames = id > 0 ? application.getResources().getStringArray(id) : new String[]{}; // final ArrayList<Module> modules = new ArrayList<Module>(); // final DefaultTriainaModule defaultRoboModule = newDefaultRoboModule(application); // // modules.add(defaultRoboModule); // // try { // for (String name : moduleNames) { // final Class<? extends Module> clazz = Class.forName(name).asSubclass(Module.class); // try { // modules.add(clazz.getDeclaredConstructor(Context.class).newInstance(application)); // } catch(final NoSuchMethodException noActivityConstructorException) { // modules.add(clazz.newInstance()); // } // } // } catch (Exception exp) { // throw new CommonRuntimeException(exp); // } // // final Injector injector = setBaseApplicationInjector(application, stage, modules.toArray(new Module[modules.size()])); // sInjectors.put(application, injector); // return injector; // } // } // // // public static TriainaInjector getInjector(Context context) { // final Application application = (Application)context.getApplicationContext(); // return new TriainaInjectorImpl(new ContextScopedRoboInjector(context, getBaseApplicationInjector(application), getViewListener(application))); // } // // public static <T> T injectMembers(Context context, T t) { // getInjector(context).injectMembers(t); // return t; // } // // public static DefaultTriainaModule newDefaultRoboModule(final Application application) { // return new DefaultTriainaModule(application, new ContextScope(), getViewListener(application), getResourceListener(application)); // } // // protected static ResourceListener getResourceListener(Application application ) { // ResourceListener resourceListener = sResourceListeners.get(application); // if(resourceListener == null) { // synchronized (TriainaInjectorFactory.class) { // if(resourceListener == null) { // resourceListener = new ResourceListener(application); // sResourceListeners.put(application,resourceListener); // } // } // } // return resourceListener; // } // // protected static ViewListener getViewListener(final Application application) { // ViewListener viewListener = sViewListeners.get(application); // if(viewListener == null) { // synchronized (TriainaInjectorFactory.class) { // if(viewListener==null) { // viewListener = new ViewListener(); // sViewListeners.put(application,viewListener); // } // } // } // // return viewListener; // } // // public static void destroyInjector(Context context) { // final TriainaInjector injector = getInjector(context); // injector.getInstance(EventManager.class).destroy(); // injector.getInstance(ContextScope.class).destroy(context); // sInjectors.remove(context); // } // }
import triaina.injector.TriainaInjectorFactory; import android.app.Service; import android.content.Intent; import android.os.IBinder;
package triaina.injector.service; public abstract class TriainaService extends Service { @Override public void onCreate() { super.onCreate();
// Path: android/Injector/src/triaina/injector/TriainaInjectorFactory.java // public class TriainaInjectorFactory { // public static final Stage DEFAULT_STAGE = Stage.PRODUCTION; // // protected static WeakHashMap<Application,Injector> sInjectors = new WeakHashMap<Application,Injector>(); // protected static WeakHashMap<Application,ResourceListener> sResourceListeners = new WeakHashMap<Application, ResourceListener>(); // protected static WeakHashMap<Application,ViewListener> sViewListeners = new WeakHashMap<Application, ViewListener>(); // // private TriainaInjectorFactory() {} // // public static Injector getBaseApplicationInjector(Application application) { // Injector injector = sInjectors.get(application); // if(injector != null ) // return injector; // // synchronized (TriainaInjectorFactory.class) { // injector = sInjectors.get(application); // if(injector != null) // return injector; // // return setBaseApplicationInjector(application, DEFAULT_STAGE); // } // } // // public static Injector setBaseApplicationInjector(final Application application, Stage stage, Module... modules) { // for(Element element : Elements.getElements(modules)) { // element.acceptVisitor(new DefaultElementVisitor<Void>() { // @Override // public Void visit(StaticInjectionRequest element) { // getResourceListener(application).requestStaticInjection(element.getType()); // return null; // } // }); // } // // synchronized (TriainaInjectorFactory.class) { // final Injector injector = Guice.createInjector(stage, modules); // sInjectors.put(application, injector); // return injector; // } // } // // /** // * Return the cached Injector instance for this application, or create a new one if necessary. // */ // public static Injector setBaseApplicationInjector(Application application, Stage stage) { // synchronized (TriainaInjectorFactory.class) { // final int id = application.getResources().getIdentifier("triaina_modules", "array", application.getPackageName()); // final String[] moduleNames = id > 0 ? application.getResources().getStringArray(id) : new String[]{}; // final ArrayList<Module> modules = new ArrayList<Module>(); // final DefaultTriainaModule defaultRoboModule = newDefaultRoboModule(application); // // modules.add(defaultRoboModule); // // try { // for (String name : moduleNames) { // final Class<? extends Module> clazz = Class.forName(name).asSubclass(Module.class); // try { // modules.add(clazz.getDeclaredConstructor(Context.class).newInstance(application)); // } catch(final NoSuchMethodException noActivityConstructorException) { // modules.add(clazz.newInstance()); // } // } // } catch (Exception exp) { // throw new CommonRuntimeException(exp); // } // // final Injector injector = setBaseApplicationInjector(application, stage, modules.toArray(new Module[modules.size()])); // sInjectors.put(application, injector); // return injector; // } // } // // // public static TriainaInjector getInjector(Context context) { // final Application application = (Application)context.getApplicationContext(); // return new TriainaInjectorImpl(new ContextScopedRoboInjector(context, getBaseApplicationInjector(application), getViewListener(application))); // } // // public static <T> T injectMembers(Context context, T t) { // getInjector(context).injectMembers(t); // return t; // } // // public static DefaultTriainaModule newDefaultRoboModule(final Application application) { // return new DefaultTriainaModule(application, new ContextScope(), getViewListener(application), getResourceListener(application)); // } // // protected static ResourceListener getResourceListener(Application application ) { // ResourceListener resourceListener = sResourceListeners.get(application); // if(resourceListener == null) { // synchronized (TriainaInjectorFactory.class) { // if(resourceListener == null) { // resourceListener = new ResourceListener(application); // sResourceListeners.put(application,resourceListener); // } // } // } // return resourceListener; // } // // protected static ViewListener getViewListener(final Application application) { // ViewListener viewListener = sViewListeners.get(application); // if(viewListener == null) { // synchronized (TriainaInjectorFactory.class) { // if(viewListener==null) { // viewListener = new ViewListener(); // sViewListeners.put(application,viewListener); // } // } // } // // return viewListener; // } // // public static void destroyInjector(Context context) { // final TriainaInjector injector = getInjector(context); // injector.getInstance(EventManager.class).destroy(); // injector.getInstance(ContextScope.class).destroy(context); // sInjectors.remove(context); // } // } // Path: android/Injector/src/triaina/injector/service/TriainaService.java import triaina.injector.TriainaInjectorFactory; import android.app.Service; import android.content.Intent; import android.os.IBinder; package triaina.injector.service; public abstract class TriainaService extends Service { @Override public void onCreate() { super.onCreate();
TriainaInjectorFactory.getInjector(this).injectMembersWithoutViews(this);
mixi-inc/triaina
android/Injector/tests/java/triaina/test/injector/binder/builder/DynamicLinkedBindingBuilderImplTest.java
// Path: android/Injector/src/triaina/injector/binder/builder/DynamicLinkedBindingBuilderImpl.java // public class DynamicLinkedBindingBuilderImpl<T> implements // DynamicLinkedBindingBuilder<T> { // private DynamicBinder mBinder; // // public DynamicLinkedBindingBuilderImpl(DynamicBinder binder) { // mBinder = binder; // } // // @Override // public void to(Class<? extends T> implementation) { // mBinder.to(implementation); // BinderContainer.put(mBinder); // } // }
import java.util.ArrayList; import triaina.injector.binder.DynamicBinder; import triaina.injector.binder.builder.DynamicLinkedBindingBuilderImpl; import junit.framework.TestCase;
package triaina.test.injector.binder.builder; public class DynamicLinkedBindingBuilderImplTest extends TestCase { @SuppressWarnings("unchecked") public void testTo() { DynamicBinder binder = new DynamicBinder("AAA", "aaa"); @SuppressWarnings("rawtypes")
// Path: android/Injector/src/triaina/injector/binder/builder/DynamicLinkedBindingBuilderImpl.java // public class DynamicLinkedBindingBuilderImpl<T> implements // DynamicLinkedBindingBuilder<T> { // private DynamicBinder mBinder; // // public DynamicLinkedBindingBuilderImpl(DynamicBinder binder) { // mBinder = binder; // } // // @Override // public void to(Class<? extends T> implementation) { // mBinder.to(implementation); // BinderContainer.put(mBinder); // } // } // Path: android/Injector/tests/java/triaina/test/injector/binder/builder/DynamicLinkedBindingBuilderImplTest.java import java.util.ArrayList; import triaina.injector.binder.DynamicBinder; import triaina.injector.binder.builder.DynamicLinkedBindingBuilderImpl; import junit.framework.TestCase; package triaina.test.injector.binder.builder; public class DynamicLinkedBindingBuilderImplTest extends TestCase { @SuppressWarnings("unchecked") public void testTo() { DynamicBinder binder = new DynamicBinder("AAA", "aaa"); @SuppressWarnings("rawtypes")
DynamicLinkedBindingBuilderImpl builder = new DynamicLinkedBindingBuilderImpl(binder);
mixi-inc/triaina
android/Commons/src/triaina/commons/collection/AbstractImmutableSet.java
// Path: android/Commons/src/triaina/commons/exception/UnsupportedRuntimeException.java // public class UnsupportedRuntimeException extends CommonRuntimeException { // // private static final long serialVersionUID = -490517655999458168L; // // public UnsupportedRuntimeException() { // super(); // } // // public UnsupportedRuntimeException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // } // // public UnsupportedRuntimeException(String detailMessage) { // super(detailMessage); // } // // public UnsupportedRuntimeException(Throwable throwable) { // super(throwable); // } // }
import java.util.Collection; import java.util.Iterator; import java.util.Set; import triaina.commons.exception.UnsupportedRuntimeException;
package triaina.commons.collection; public abstract class AbstractImmutableSet<E> implements Set<E> { private Set<E> mSet; public AbstractImmutableSet(Set<E> set) { mSet = set; } /** * @hide */ @Override public boolean add(E obj) {
// Path: android/Commons/src/triaina/commons/exception/UnsupportedRuntimeException.java // public class UnsupportedRuntimeException extends CommonRuntimeException { // // private static final long serialVersionUID = -490517655999458168L; // // public UnsupportedRuntimeException() { // super(); // } // // public UnsupportedRuntimeException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // } // // public UnsupportedRuntimeException(String detailMessage) { // super(detailMessage); // } // // public UnsupportedRuntimeException(Throwable throwable) { // super(throwable); // } // } // Path: android/Commons/src/triaina/commons/collection/AbstractImmutableSet.java import java.util.Collection; import java.util.Iterator; import java.util.Set; import triaina.commons.exception.UnsupportedRuntimeException; package triaina.commons.collection; public abstract class AbstractImmutableSet<E> implements Set<E> { private Set<E> mSet; public AbstractImmutableSet(Set<E> set) { mSet = set; } /** * @hide */ @Override public boolean add(E obj) {
throw new UnsupportedRuntimeException("this set is immutable");
mixi-inc/triaina
android/Commons/src/triaina/commons/utils/ThreadUtils.java
// Path: android/Commons/src/triaina/commons/exception/CalledFromWrongThreadRuntimeException.java // public class CalledFromWrongThreadRuntimeException extends CommonRuntimeException { // private static final long serialVersionUID = -7769875177893783855L; // // // public CalledFromWrongThreadRuntimeException() { // super(); // } // // public CalledFromWrongThreadRuntimeException(String detailMessage, // Throwable throwable) { // super(detailMessage, throwable); // } // // public CalledFromWrongThreadRuntimeException(String detailMessage) { // super(detailMessage); // } // // public CalledFromWrongThreadRuntimeException(Throwable throwable) { // super(throwable); // } // }
import triaina.commons.exception.CalledFromWrongThreadRuntimeException; import android.os.Looper;
package triaina.commons.utils; public final class ThreadUtils { private ThreadUtils() {} public static boolean isMainThread(Thread thread) { return Looper.getMainLooper().getThread() == thread; } public static boolean isMainThread() { return isMainThread(Thread.currentThread()); } public static void checkMainThread(Thread thread) { if (!isMainThread(thread))
// Path: android/Commons/src/triaina/commons/exception/CalledFromWrongThreadRuntimeException.java // public class CalledFromWrongThreadRuntimeException extends CommonRuntimeException { // private static final long serialVersionUID = -7769875177893783855L; // // // public CalledFromWrongThreadRuntimeException() { // super(); // } // // public CalledFromWrongThreadRuntimeException(String detailMessage, // Throwable throwable) { // super(detailMessage, throwable); // } // // public CalledFromWrongThreadRuntimeException(String detailMessage) { // super(detailMessage); // } // // public CalledFromWrongThreadRuntimeException(Throwable throwable) { // super(throwable); // } // } // Path: android/Commons/src/triaina/commons/utils/ThreadUtils.java import triaina.commons.exception.CalledFromWrongThreadRuntimeException; import android.os.Looper; package triaina.commons.utils; public final class ThreadUtils { private ThreadUtils() {} public static boolean isMainThread(Thread thread) { return Looper.getMainLooper().getThread() == thread; } public static boolean isMainThread() { return isMainThread(Thread.currentThread()); } public static void checkMainThread(Thread thread) { if (!isMainThread(thread))
throw new CalledFromWrongThreadRuntimeException("Don't touch without main thread!!");
shopzilla/catalog-api-client
client/src/main/java/com/shopzilla/api/client/model/ClassificationModelAdapter.java
// Path: client/src/main/java/com/shopzilla/api/client/model/response/Classification.java // public class Classification extends BaseResponse { // // private String originalKeyword; // private Long originalNumResults; // private Boolean mature; // private Boolean media; // private List<Suggestion> suggestions; // // public Classification() { // } // // public String getOriginalKeyword() { // return originalKeyword; // } // // public void setOriginalKeyword(String originalKeyword) { // this.originalKeyword = originalKeyword; // } // // public Long getOriginalNumResults() { // return originalNumResults; // } // // public void setOriginalNumResults(Long originalNumResults) { // this.originalNumResults = originalNumResults; // } // // public Boolean getMature() { // return mature; // } // // public void setMature(Boolean mature) { // this.mature = mature; // } // // public Boolean getMedia() { // return media; // } // // public void setMedia(Boolean media) { // this.media = media; // } // // public List<Suggestion> getSuggestions() { // if (suggestions == null) { // suggestions = new ArrayList<Suggestion>(); // } // return suggestions; // } // }
import java.util.List; import org.apache.commons.lang.BooleanUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.shopzilla.api.client.model.response.Classification; import com.shopzilla.services.catalog.ClassificationResponse; import com.shopzilla.services.catalog.QuerySuggestionType;
/** * Copyright (C) 2004 - 2012 Shopzilla, Inc. * All rights reserved. Unauthorized disclosure or distribution is prohibited. */ package com.shopzilla.api.client.model; /** * Convert service classification response into API response model. * * @author Tom Suthanurak * * @since Jan 3, 2012 */ public class ClassificationModelAdapter { private static final Log LOG = LogFactory.getLog(ClassificationModelAdapter.class);
// Path: client/src/main/java/com/shopzilla/api/client/model/response/Classification.java // public class Classification extends BaseResponse { // // private String originalKeyword; // private Long originalNumResults; // private Boolean mature; // private Boolean media; // private List<Suggestion> suggestions; // // public Classification() { // } // // public String getOriginalKeyword() { // return originalKeyword; // } // // public void setOriginalKeyword(String originalKeyword) { // this.originalKeyword = originalKeyword; // } // // public Long getOriginalNumResults() { // return originalNumResults; // } // // public void setOriginalNumResults(Long originalNumResults) { // this.originalNumResults = originalNumResults; // } // // public Boolean getMature() { // return mature; // } // // public void setMature(Boolean mature) { // this.mature = mature; // } // // public Boolean getMedia() { // return media; // } // // public void setMedia(Boolean media) { // this.media = media; // } // // public List<Suggestion> getSuggestions() { // if (suggestions == null) { // suggestions = new ArrayList<Suggestion>(); // } // return suggestions; // } // } // Path: client/src/main/java/com/shopzilla/api/client/model/ClassificationModelAdapter.java import java.util.List; import org.apache.commons.lang.BooleanUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.shopzilla.api.client.model.response.Classification; import com.shopzilla.services.catalog.ClassificationResponse; import com.shopzilla.services.catalog.QuerySuggestionType; /** * Copyright (C) 2004 - 2012 Shopzilla, Inc. * All rights reserved. Unauthorized disclosure or distribution is prohibited. */ package com.shopzilla.api.client.model; /** * Convert service classification response into API response model. * * @author Tom Suthanurak * * @since Jan 3, 2012 */ public class ClassificationModelAdapter { private static final Log LOG = LogFactory.getLog(ClassificationModelAdapter.class);
public static Classification fromCatalogAPI(ClassificationResponse response) {
shopzilla/catalog-api-client
client/src/test/java/com/shopzilla/api/client/model/MerchantModelAdapterTest.java
// Path: client/src/main/java/com/shopzilla/api/client/model/response/MerchantResponse.java // public class MerchantResponse extends BaseResponse { // // private List<MerchantInfo> merchants; // // public List<MerchantInfo> getMerchants() { // return merchants; // } // // public void setMerchants(List<MerchantInfo> merchants) { // this.merchants = merchants; // } // // }
import com.shopzilla.api.client.model.response.MerchantResponse; import com.shopzilla.services.catalog.*; import org.apache.commons.lang.StringUtils; import org.junit.Before; import org.junit.Test; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.*;
/** * Copyright (C) 2004 - 2011 Shopzilla, Inc. * All rights reserved. Unauthorized disclosure or distribution is prohibited. */ package com.shopzilla.api.client.model; /** * @author Emanuele Blanco * @since 07/03/12 */ public class MerchantModelAdapterTest { MerchantsResponse input;
// Path: client/src/main/java/com/shopzilla/api/client/model/response/MerchantResponse.java // public class MerchantResponse extends BaseResponse { // // private List<MerchantInfo> merchants; // // public List<MerchantInfo> getMerchants() { // return merchants; // } // // public void setMerchants(List<MerchantInfo> merchants) { // this.merchants = merchants; // } // // } // Path: client/src/test/java/com/shopzilla/api/client/model/MerchantModelAdapterTest.java import com.shopzilla.api.client.model.response.MerchantResponse; import com.shopzilla.services.catalog.*; import org.apache.commons.lang.StringUtils; import org.junit.Before; import org.junit.Test; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.*; /** * Copyright (C) 2004 - 2011 Shopzilla, Inc. * All rights reserved. Unauthorized disclosure or distribution is prohibited. */ package com.shopzilla.api.client.model; /** * @author Emanuele Blanco * @since 07/03/12 */ public class MerchantModelAdapterTest { MerchantsResponse input;
MerchantResponse expectedResponse;
shopzilla/catalog-api-client
client/src/main/java/com/shopzilla/api/driver/ProductServiceDriver.java
// Path: client/src/main/java/com/shopzilla/api/service/ProductService.java // public class ProductService { // // private Marshaller marshaller; // private Unmarshaller unmarshaller; // // public ProductResponse xmlInputStreamToJava(InputStream in) throws IOException, JAXBException { // try { // // ProductResponse productResponse = (ProductResponse) unmarshaller.unmarshal(new StreamSource(in)); // System.out.println("productResponse = " + productResponse); // return productResponse; // // } catch (XmlMappingException xme) { // xme.printStackTrace(); // } // return null; // } // // public void setMarshaller(Marshaller marshaller) { // this.marshaller = marshaller; // } // // public void setUnmarshaller(Unmarshaller unmarshaller) { // this.unmarshaller = unmarshaller; // } // }
import com.shopzilla.api.service.ProductService; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import javax.xml.bind.JAXBException; import java.io.IOException;
/** * Copyright 2011 Shopzilla.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 com.shopzilla.api.driver; /** * @author alook * @since 3/27/11 */ public class ProductServiceDriver { public static void main(String[] args) throws JAXBException, IOException { ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:applicationContext-client.xml");
// Path: client/src/main/java/com/shopzilla/api/service/ProductService.java // public class ProductService { // // private Marshaller marshaller; // private Unmarshaller unmarshaller; // // public ProductResponse xmlInputStreamToJava(InputStream in) throws IOException, JAXBException { // try { // // ProductResponse productResponse = (ProductResponse) unmarshaller.unmarshal(new StreamSource(in)); // System.out.println("productResponse = " + productResponse); // return productResponse; // // } catch (XmlMappingException xme) { // xme.printStackTrace(); // } // return null; // } // // public void setMarshaller(Marshaller marshaller) { // this.marshaller = marshaller; // } // // public void setUnmarshaller(Unmarshaller unmarshaller) { // this.unmarshaller = unmarshaller; // } // } // Path: client/src/main/java/com/shopzilla/api/driver/ProductServiceDriver.java import com.shopzilla.api.service.ProductService; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import javax.xml.bind.JAXBException; import java.io.IOException; /** * Copyright 2011 Shopzilla.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 com.shopzilla.api.driver; /** * @author alook * @since 3/27/11 */ public class ProductServiceDriver { public static void main(String[] args) throws JAXBException, IOException { ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:applicationContext-client.xml");
ProductService service = applicationContext.getBean("productService", ProductService.class);
shopzilla/catalog-api-client
client/src/main/java/com/shopzilla/api/client/model/response/Classification.java
// Path: client/src/main/java/com/shopzilla/api/client/model/Suggestion.java // public class Suggestion { // public static enum SuggestionType { // SCRUBBER, QUERY_SUGGESTION, QUERY_CLASSIFICATION, EXCLUDE_SCORCHING // }; // // private SuggestionType suggestionType; // private long numResults; // private String keyword; // private Offer offer; // private Product product; // private Category category; // // public SuggestionType getSuggestionType() { // return suggestionType; // } // // public void setSuggestionType(SuggestionType suggestionType) { // this.suggestionType = suggestionType; // } // // public long getNumResults() { // return numResults; // } // // public void setNumResults(long numResults) { // this.numResults = numResults; // } // // public String getKeyword() { // return keyword; // } // // public void setKeyword(String keyword) { // this.keyword = keyword; // } // // public Offer getOffer() { // return offer; // } // // public void setOffer(Offer offer) { // this.offer = offer; // } // // public Product getProduct() { // return product; // } // // public void setProduct(Product product) { // this.product = product; // } // // public Category getCategory() { // return category; // } // // public void setCategory(Category category) { // this.category = category; // } // }
import com.shopzilla.api.client.model.Suggestion; import java.util.ArrayList; import java.util.List;
/** * Copyright (C) 2004 - 2012 Shopzilla, Inc. * All rights reserved. Unauthorized disclosure or distribution is prohibited. */ package com.shopzilla.api.client.model.response; /** * * @author Tom Suthanurak * @author Swati Achar * @since Jan 3, 2012 */ public class Classification extends BaseResponse { private String originalKeyword; private Long originalNumResults; private Boolean mature; private Boolean media;
// Path: client/src/main/java/com/shopzilla/api/client/model/Suggestion.java // public class Suggestion { // public static enum SuggestionType { // SCRUBBER, QUERY_SUGGESTION, QUERY_CLASSIFICATION, EXCLUDE_SCORCHING // }; // // private SuggestionType suggestionType; // private long numResults; // private String keyword; // private Offer offer; // private Product product; // private Category category; // // public SuggestionType getSuggestionType() { // return suggestionType; // } // // public void setSuggestionType(SuggestionType suggestionType) { // this.suggestionType = suggestionType; // } // // public long getNumResults() { // return numResults; // } // // public void setNumResults(long numResults) { // this.numResults = numResults; // } // // public String getKeyword() { // return keyword; // } // // public void setKeyword(String keyword) { // this.keyword = keyword; // } // // public Offer getOffer() { // return offer; // } // // public void setOffer(Offer offer) { // this.offer = offer; // } // // public Product getProduct() { // return product; // } // // public void setProduct(Product product) { // this.product = product; // } // // public Category getCategory() { // return category; // } // // public void setCategory(Category category) { // this.category = category; // } // } // Path: client/src/main/java/com/shopzilla/api/client/model/response/Classification.java import com.shopzilla.api.client.model.Suggestion; import java.util.ArrayList; import java.util.List; /** * Copyright (C) 2004 - 2012 Shopzilla, Inc. * All rights reserved. Unauthorized disclosure or distribution is prohibited. */ package com.shopzilla.api.client.model.response; /** * * @author Tom Suthanurak * @author Swati Achar * @since Jan 3, 2012 */ public class Classification extends BaseResponse { private String originalKeyword; private Long originalNumResults; private Boolean mature; private Boolean media;
private List<Suggestion> suggestions;
shopzilla/catalog-api-client
client/src/main/java/com/shopzilla/api/client/model/request/AttributeSearchRequest.java
// Path: client/src/main/java/com/shopzilla/api/client/model/Attribute.java // public class Attribute { // // private String label; // private String id; // private List<AttributeValue> values = Collections.emptyList(); // // @Override // public int hashCode() { // return new HashCodeBuilder() // .append(id) // .toHashCode(); // } // // @Override // public boolean equals(Object o) { // // if (o == this) { // return true; // } // // if (o == null || !(o instanceof Attribute)) { // return false; // } // // Attribute rhs = (Attribute) o; // // return new EqualsBuilder() // .append(id, rhs.id) // .isEquals(); // } // // @Override // public String toString() { // return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE) // .append("id", id) // .append("label", label) // .append("values", values) // .toString(); // } // // public String getLabel() { // return label; // } // // public void setLabel(String label) { // this.label = label; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public List<AttributeValue> getValues() { // return values; // } // // public void setValues(List<AttributeValue> values) { // this.values = values; // } // // }
import java.util.List; import com.shopzilla.api.client.model.Attribute;
/** * Copyright 2011 Shopzilla.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 com.shopzilla.api.client.model.request; /** * Model object for invoking the Attribute Catalog API endpoint * * @author sscanlon * @author eblanco * @author nbajpai */ public class AttributeSearchRequest extends AbstractSearchRequest { private static final int DEFAULT_NUM_RESULTS = 20; private static final int DEFAULT_RESULTS_ATTRIBUTE_VALUES = 100; private String keyword; private Integer numResults = DEFAULT_NUM_RESULTS; private Integer resultsAttributeValues = DEFAULT_RESULTS_ATTRIBUTE_VALUES; private String attributeId;
// Path: client/src/main/java/com/shopzilla/api/client/model/Attribute.java // public class Attribute { // // private String label; // private String id; // private List<AttributeValue> values = Collections.emptyList(); // // @Override // public int hashCode() { // return new HashCodeBuilder() // .append(id) // .toHashCode(); // } // // @Override // public boolean equals(Object o) { // // if (o == this) { // return true; // } // // if (o == null || !(o instanceof Attribute)) { // return false; // } // // Attribute rhs = (Attribute) o; // // return new EqualsBuilder() // .append(id, rhs.id) // .isEquals(); // } // // @Override // public String toString() { // return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE) // .append("id", id) // .append("label", label) // .append("values", values) // .toString(); // } // // public String getLabel() { // return label; // } // // public void setLabel(String label) { // this.label = label; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public List<AttributeValue> getValues() { // return values; // } // // public void setValues(List<AttributeValue> values) { // this.values = values; // } // // } // Path: client/src/main/java/com/shopzilla/api/client/model/request/AttributeSearchRequest.java import java.util.List; import com.shopzilla.api.client.model.Attribute; /** * Copyright 2011 Shopzilla.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 com.shopzilla.api.client.model.request; /** * Model object for invoking the Attribute Catalog API endpoint * * @author sscanlon * @author eblanco * @author nbajpai */ public class AttributeSearchRequest extends AbstractSearchRequest { private static final int DEFAULT_NUM_RESULTS = 20; private static final int DEFAULT_RESULTS_ATTRIBUTE_VALUES = 100; private String keyword; private Integer numResults = DEFAULT_NUM_RESULTS; private Integer resultsAttributeValues = DEFAULT_RESULTS_ATTRIBUTE_VALUES; private String attributeId;
private List<Attribute> attributes;
shopzilla/catalog-api-client
client/src/main/java/com/shopzilla/api/client/TaxonomyClient.java
// Path: client/src/main/java/com/shopzilla/api/client/model/request/CategorySearchRequest.java // public class CategorySearchRequest extends AbstractSearchRequest { // // // private String keyword; // private Long categoryId; // private Boolean ancestors; // private Integer results; // private EnumSortOrder sortOrder; // private String attFilter; // // public Boolean getAncestors() { // return ancestors; // } // // public void setAncestors(Boolean ancestors) { // this.ancestors = ancestors; // } // // public String getAttFilter() { // return attFilter; // } // // public void setAttFilter(String attFilter) { // this.attFilter = attFilter; // } // // public Long getCategoryId() { // return categoryId; // } // // public void setCategoryId(Long categoryId) { // this.categoryId = categoryId; // } // // public String getKeyword() { // return keyword; // } // // public void setKeyword(String keyword) { // this.keyword = keyword; // } // // public Integer getResults() { // return results; // } // // public void setResults(Integer results) { // this.results = results; // } // // public EnumSortOrder getSortOrder() { // return sortOrder; // } // // public void setSortOrder(EnumSortOrder sortOrder) { // this.sortOrder = sortOrder; // } // // }
import org.springframework.beans.factory.annotation.Required; import org.springframework.web.client.RestOperations; import com.shopzilla.api.client.model.request.CategorySearchRequest; import com.shopzilla.services.catalog.TaxonomyResponse;
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.shopzilla.api.client; /** * * @author sachar */ public class TaxonomyClient { private RestOperations restTemplate; private UrlProvider urlProvider; /** * Wrapper for retrieveProductResponseList(), made for parsing sets of Products from searches * for a particular keyword. * * @param apiKey * @param publisherId * @param searchKeyword * @param numResults * * @return TaxonomyResponse */ public TaxonomyResponse doCategorySearch(String apiKey, String publisherId, String searchKeyword, Integer numResults) { try {
// Path: client/src/main/java/com/shopzilla/api/client/model/request/CategorySearchRequest.java // public class CategorySearchRequest extends AbstractSearchRequest { // // // private String keyword; // private Long categoryId; // private Boolean ancestors; // private Integer results; // private EnumSortOrder sortOrder; // private String attFilter; // // public Boolean getAncestors() { // return ancestors; // } // // public void setAncestors(Boolean ancestors) { // this.ancestors = ancestors; // } // // public String getAttFilter() { // return attFilter; // } // // public void setAttFilter(String attFilter) { // this.attFilter = attFilter; // } // // public Long getCategoryId() { // return categoryId; // } // // public void setCategoryId(Long categoryId) { // this.categoryId = categoryId; // } // // public String getKeyword() { // return keyword; // } // // public void setKeyword(String keyword) { // this.keyword = keyword; // } // // public Integer getResults() { // return results; // } // // public void setResults(Integer results) { // this.results = results; // } // // public EnumSortOrder getSortOrder() { // return sortOrder; // } // // public void setSortOrder(EnumSortOrder sortOrder) { // this.sortOrder = sortOrder; // } // // } // Path: client/src/main/java/com/shopzilla/api/client/TaxonomyClient.java import org.springframework.beans.factory.annotation.Required; import org.springframework.web.client.RestOperations; import com.shopzilla.api.client.model.request.CategorySearchRequest; import com.shopzilla.services.catalog.TaxonomyResponse; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.shopzilla.api.client; /** * * @author sachar */ public class TaxonomyClient { private RestOperations restTemplate; private UrlProvider urlProvider; /** * Wrapper for retrieveProductResponseList(), made for parsing sets of Products from searches * for a particular keyword. * * @param apiKey * @param publisherId * @param searchKeyword * @param numResults * * @return TaxonomyResponse */ public TaxonomyResponse doCategorySearch(String apiKey, String publisherId, String searchKeyword, Integer numResults) { try {
CategorySearchRequest request = new CategorySearchRequest();
shopzilla/catalog-api-client
client/src/test/java/com/shopzilla/api/client/ProductClientIntegrationTest.java
// Path: client/src/main/java/com/shopzilla/api/client/helper/CredentialFactory.java // public class CredentialFactory { // private String publisherId; // private String publisherApiKey; // // public CredentialFactory() { // String id = StringUtils.isNotBlank(System.getenv("PUBLISHER_ID")) ? System.getenv("PUBLISHER_ID") : System.getProperty("PUBLISHER_ID"); // String key = StringUtils.isNotBlank(System.getenv("PUBLISHER_API_KEY")) ? System.getenv("PUBLISHER_API_KEY") : System.getProperty("PUBLISHER_API_KEY"); // // if (key != null && id != null) { // this.publisherId = id; // this.publisherApiKey = key; // } else { // throw new IllegalArgumentException("No API credentials were provided! "+ // "Please set PUBLISHER_ID and PUBLISHER_API_KEY "); // } // } // // public String getPublisherId() { // return publisherId; // } // // public String getPublisherApiKey() { // return publisherApiKey; // } // }
import com.shopzilla.api.client.helper.CredentialFactory; import com.shopzilla.services.catalog.ProductResponse; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import static junit.framework.Assert.assertEquals;
/** * Copyright 2011 Shopzilla.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 com.shopzilla.api.client; /** * @author alook * @since 3/27/11 */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"classpath:spring/applicationContext-client-test.xml"}) public class ProductClientIntegrationTest { @Autowired ProductClient client; @Autowired
// Path: client/src/main/java/com/shopzilla/api/client/helper/CredentialFactory.java // public class CredentialFactory { // private String publisherId; // private String publisherApiKey; // // public CredentialFactory() { // String id = StringUtils.isNotBlank(System.getenv("PUBLISHER_ID")) ? System.getenv("PUBLISHER_ID") : System.getProperty("PUBLISHER_ID"); // String key = StringUtils.isNotBlank(System.getenv("PUBLISHER_API_KEY")) ? System.getenv("PUBLISHER_API_KEY") : System.getProperty("PUBLISHER_API_KEY"); // // if (key != null && id != null) { // this.publisherId = id; // this.publisherApiKey = key; // } else { // throw new IllegalArgumentException("No API credentials were provided! "+ // "Please set PUBLISHER_ID and PUBLISHER_API_KEY "); // } // } // // public String getPublisherId() { // return publisherId; // } // // public String getPublisherApiKey() { // return publisherApiKey; // } // } // Path: client/src/test/java/com/shopzilla/api/client/ProductClientIntegrationTest.java import com.shopzilla.api.client.helper.CredentialFactory; import com.shopzilla.services.catalog.ProductResponse; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import static junit.framework.Assert.assertEquals; /** * Copyright 2011 Shopzilla.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 com.shopzilla.api.client; /** * @author alook * @since 3/27/11 */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"classpath:spring/applicationContext-client-test.xml"}) public class ProductClientIntegrationTest { @Autowired ProductClient client; @Autowired
CredentialFactory credentialFactory;
shopzilla/catalog-api-client
client/src/test/java/com/shopzilla/api/client/model/AttributeModelAdapterTest.java
// Path: client/src/main/java/com/shopzilla/api/client/model/response/AttributeSearchResponse.java // public class AttributeSearchResponse extends BaseResponse implements SearchResponse { // // private Attributes attributes; // // private Integer includedResults; // // private String metaInfo; // // public Attributes getAttributes() { // return attributes; // } // // public void setAttributes(Attributes attributes) { // this.attributes = attributes; // } // // public Integer getIncludedResults() { // return includedResults; // } // // public void setIncludedResults(Integer includedResults) { // this.includedResults = includedResults; // } // // public String getMetaInfo() { // return metaInfo; // } // // public void setMetaInfo(String metaInfo) { // this.metaInfo = metaInfo; // } // // public Integer getTotalResults() { // return includedResults; // } // // public static class Attributes { // // protected List<AttributeType> attribute; // // public List<AttributeType> getAttribute() { // if (attribute == null) { // attribute = new ArrayList<AttributeType>(); // } // return this.attribute; // } // // } // }
import com.shopzilla.api.client.model.response.AttributeSearchResponse; import com.shopzilla.services.catalog.AttributeResponse; import com.shopzilla.services.catalog.AttributeType; import com.shopzilla.services.catalog.AttributeValueType; import org.apache.commons.lang.ObjectUtils; import org.apache.commons.lang.StringUtils; import org.junit.Test; import java.math.BigDecimal; import java.util.List; import static org.junit.Assert.assertTrue;
/** * Copyright (C) 2004 - 2011 Shopzilla, Inc. * All rights reserved. Unauthorized disclosure or distribution is prohibited. */ package com.shopzilla.api.client.model; /** * * @author Emanuele Blanco * @since 01/12/11 */ public class AttributeModelAdapterTest { @Test public void testWithNullInput() throws Exception {
// Path: client/src/main/java/com/shopzilla/api/client/model/response/AttributeSearchResponse.java // public class AttributeSearchResponse extends BaseResponse implements SearchResponse { // // private Attributes attributes; // // private Integer includedResults; // // private String metaInfo; // // public Attributes getAttributes() { // return attributes; // } // // public void setAttributes(Attributes attributes) { // this.attributes = attributes; // } // // public Integer getIncludedResults() { // return includedResults; // } // // public void setIncludedResults(Integer includedResults) { // this.includedResults = includedResults; // } // // public String getMetaInfo() { // return metaInfo; // } // // public void setMetaInfo(String metaInfo) { // this.metaInfo = metaInfo; // } // // public Integer getTotalResults() { // return includedResults; // } // // public static class Attributes { // // protected List<AttributeType> attribute; // // public List<AttributeType> getAttribute() { // if (attribute == null) { // attribute = new ArrayList<AttributeType>(); // } // return this.attribute; // } // // } // } // Path: client/src/test/java/com/shopzilla/api/client/model/AttributeModelAdapterTest.java import com.shopzilla.api.client.model.response.AttributeSearchResponse; import com.shopzilla.services.catalog.AttributeResponse; import com.shopzilla.services.catalog.AttributeType; import com.shopzilla.services.catalog.AttributeValueType; import org.apache.commons.lang.ObjectUtils; import org.apache.commons.lang.StringUtils; import org.junit.Test; import java.math.BigDecimal; import java.util.List; import static org.junit.Assert.assertTrue; /** * Copyright (C) 2004 - 2011 Shopzilla, Inc. * All rights reserved. Unauthorized disclosure or distribution is prohibited. */ package com.shopzilla.api.client.model; /** * * @author Emanuele Blanco * @since 01/12/11 */ public class AttributeModelAdapterTest { @Test public void testWithNullInput() throws Exception {
assertTrue(responsesAreEqual(new AttributeSearchResponse(), AttributeModelAdapter.fromCatalogAPI(null)));
shopzilla/catalog-api-client
client/src/main/java/com/shopzilla/api/driver/ProductClientDriver.java
// Path: client/src/main/java/com/shopzilla/api/client/ProductClient.java // public class ProductClient { // // private RestOperations restTemplate; // private ProductService productService; // // /** // * Wrapper for retrieveProductResponseList(), made for parsing sets of Products from searches // * for a particular keyword. // * // * @param apiKey // * @param publisherId // * @param searchKeyword // * @param numResults // * // * @return ProductResponse // */ // public ProductResponse doProductSearch(String apiKey, String publisherId, String searchKeyword, // Integer numResults) { // // ProductSearchRequest request = new ProductSearchRequest(); // request.setApiKey(apiKey); // request.setPublisherId(publisherId); // request.setKeyword(searchKeyword); // request.setNumResults(numResults); // // return retrieveProductResponseList(request); // // } // // /** // * Multi-purpose method for fetching + parsing ProductResponse XML from Shopzilla API // * // * @param ProductSearchRequest // * // * @return ProductResponse // */ // private ProductResponse retrieveProductResponseList(ProductSearchRequest request) { // // return restTemplate.getForObject(ProductUrl.PRODUCT_URL, // ProductResponse.class, // ProductUrl.makeParameterMap(request)); // } // // public void setRestTemplate(RestOperations restTemplate) { // this.restTemplate = restTemplate; // } // // public void setProductService(ProductService productService) { // this.productService = productService; // } // // } // // Path: client/src/main/java/com/shopzilla/api/client/helper/CredentialFactory.java // public class CredentialFactory { // private String publisherId; // private String publisherApiKey; // // public CredentialFactory() { // String id = StringUtils.isNotBlank(System.getenv("PUBLISHER_ID")) ? System.getenv("PUBLISHER_ID") : System.getProperty("PUBLISHER_ID"); // String key = StringUtils.isNotBlank(System.getenv("PUBLISHER_API_KEY")) ? System.getenv("PUBLISHER_API_KEY") : System.getProperty("PUBLISHER_API_KEY"); // // if (key != null && id != null) { // this.publisherId = id; // this.publisherApiKey = key; // } else { // throw new IllegalArgumentException("No API credentials were provided! "+ // "Please set PUBLISHER_ID and PUBLISHER_API_KEY "); // } // } // // public String getPublisherId() { // return publisherId; // } // // public String getPublisherApiKey() { // return publisherApiKey; // } // }
import com.shopzilla.api.client.ProductClient; import com.shopzilla.api.client.helper.CredentialFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext;
/* * Copyright 2011 Shopzilla.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 com.shopzilla.api.driver; public class ProductClientDriver { private static CredentialFactory credentialFactory; private static String apiKey; private static String publisherId; private static final String keyword = "nike+men%27s+shoes"; public static void main(String[] args) { ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:applicationContext-client.xml");
// Path: client/src/main/java/com/shopzilla/api/client/ProductClient.java // public class ProductClient { // // private RestOperations restTemplate; // private ProductService productService; // // /** // * Wrapper for retrieveProductResponseList(), made for parsing sets of Products from searches // * for a particular keyword. // * // * @param apiKey // * @param publisherId // * @param searchKeyword // * @param numResults // * // * @return ProductResponse // */ // public ProductResponse doProductSearch(String apiKey, String publisherId, String searchKeyword, // Integer numResults) { // // ProductSearchRequest request = new ProductSearchRequest(); // request.setApiKey(apiKey); // request.setPublisherId(publisherId); // request.setKeyword(searchKeyword); // request.setNumResults(numResults); // // return retrieveProductResponseList(request); // // } // // /** // * Multi-purpose method for fetching + parsing ProductResponse XML from Shopzilla API // * // * @param ProductSearchRequest // * // * @return ProductResponse // */ // private ProductResponse retrieveProductResponseList(ProductSearchRequest request) { // // return restTemplate.getForObject(ProductUrl.PRODUCT_URL, // ProductResponse.class, // ProductUrl.makeParameterMap(request)); // } // // public void setRestTemplate(RestOperations restTemplate) { // this.restTemplate = restTemplate; // } // // public void setProductService(ProductService productService) { // this.productService = productService; // } // // } // // Path: client/src/main/java/com/shopzilla/api/client/helper/CredentialFactory.java // public class CredentialFactory { // private String publisherId; // private String publisherApiKey; // // public CredentialFactory() { // String id = StringUtils.isNotBlank(System.getenv("PUBLISHER_ID")) ? System.getenv("PUBLISHER_ID") : System.getProperty("PUBLISHER_ID"); // String key = StringUtils.isNotBlank(System.getenv("PUBLISHER_API_KEY")) ? System.getenv("PUBLISHER_API_KEY") : System.getProperty("PUBLISHER_API_KEY"); // // if (key != null && id != null) { // this.publisherId = id; // this.publisherApiKey = key; // } else { // throw new IllegalArgumentException("No API credentials were provided! "+ // "Please set PUBLISHER_ID and PUBLISHER_API_KEY "); // } // } // // public String getPublisherId() { // return publisherId; // } // // public String getPublisherApiKey() { // return publisherApiKey; // } // } // Path: client/src/main/java/com/shopzilla/api/driver/ProductClientDriver.java import com.shopzilla.api.client.ProductClient; import com.shopzilla.api.client.helper.CredentialFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /* * Copyright 2011 Shopzilla.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 com.shopzilla.api.driver; public class ProductClientDriver { private static CredentialFactory credentialFactory; private static String apiKey; private static String publisherId; private static final String keyword = "nike+men%27s+shoes"; public static void main(String[] args) { ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:applicationContext-client.xml");
ProductClient client = applicationContext.getBean("productClient", ProductClient.class);
shopzilla/catalog-api-client
client/src/test/java/com/shopzilla/api/client/TaxonomyClientIntegrationTest.java
// Path: client/src/main/java/com/shopzilla/api/client/helper/CredentialFactory.java // public class CredentialFactory { // private String publisherId; // private String publisherApiKey; // // public CredentialFactory() { // String id = StringUtils.isNotBlank(System.getenv("PUBLISHER_ID")) ? System.getenv("PUBLISHER_ID") : System.getProperty("PUBLISHER_ID"); // String key = StringUtils.isNotBlank(System.getenv("PUBLISHER_API_KEY")) ? System.getenv("PUBLISHER_API_KEY") : System.getProperty("PUBLISHER_API_KEY"); // // if (key != null && id != null) { // this.publisherId = id; // this.publisherApiKey = key; // } else { // throw new IllegalArgumentException("No API credentials were provided! "+ // "Please set PUBLISHER_ID and PUBLISHER_API_KEY "); // } // } // // public String getPublisherId() { // return publisherId; // } // // public String getPublisherApiKey() { // return publisherApiKey; // } // }
import static junit.framework.Assert.assertEquals; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.shopzilla.api.client.helper.CredentialFactory; import com.shopzilla.services.catalog.TaxonomyResponse;
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.shopzilla.api.client; /** * * @author sachar */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"classpath:spring/applicationContext-client-test.xml"}) public class TaxonomyClientIntegrationTest { @Autowired TaxonomyClient client; @Autowired
// Path: client/src/main/java/com/shopzilla/api/client/helper/CredentialFactory.java // public class CredentialFactory { // private String publisherId; // private String publisherApiKey; // // public CredentialFactory() { // String id = StringUtils.isNotBlank(System.getenv("PUBLISHER_ID")) ? System.getenv("PUBLISHER_ID") : System.getProperty("PUBLISHER_ID"); // String key = StringUtils.isNotBlank(System.getenv("PUBLISHER_API_KEY")) ? System.getenv("PUBLISHER_API_KEY") : System.getProperty("PUBLISHER_API_KEY"); // // if (key != null && id != null) { // this.publisherId = id; // this.publisherApiKey = key; // } else { // throw new IllegalArgumentException("No API credentials were provided! "+ // "Please set PUBLISHER_ID and PUBLISHER_API_KEY "); // } // } // // public String getPublisherId() { // return publisherId; // } // // public String getPublisherApiKey() { // return publisherApiKey; // } // } // Path: client/src/test/java/com/shopzilla/api/client/TaxonomyClientIntegrationTest.java import static junit.framework.Assert.assertEquals; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.shopzilla.api.client.helper.CredentialFactory; import com.shopzilla.services.catalog.TaxonomyResponse; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.shopzilla.api.client; /** * * @author sachar */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"classpath:spring/applicationContext-client-test.xml"}) public class TaxonomyClientIntegrationTest { @Autowired TaxonomyClient client; @Autowired
CredentialFactory credentialFactory;
AleksanderMielczarek/Napkin
app/src/main/java/com/github/aleksandermielczarek/napkinexample/component/FragmentComponent.java
// Path: app/src/main/java/com/github/aleksandermielczarek/napkinexample/module/FragmentModule.java // @Module // @FragmentScope // public class FragmentModule extends NapkinFragmentModule { // // public FragmentModule(Fragment fragment) { // super(fragment); // } // // @Provides // @FragmentString // String provideNapkinString() { // return "Hello Napkin in Fragment!"; // } // } // // Path: app/src/main/java/com/github/aleksandermielczarek/napkinexample/ui/SecondaryFragment.java // public class SecondaryFragment extends Fragment { // // @Inject // protected SecondaryViewModel secondaryViewModel; // // @Override // public void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // // Napkin.<ActivityComponent>provideActivityComponent(this) // .with(new FragmentModule(this)) // .inject(this); // } // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // FragmentScondaryBinding binding = FragmentScondaryBinding.inflate(inflater, container, false); // binding.setViewModel(secondaryViewModel); // return binding.getRoot(); // } // }
import com.github.aleksandermielczarek.napkin.scope.FragmentScope; import com.github.aleksandermielczarek.napkinexample.module.FragmentModule; import com.github.aleksandermielczarek.napkinexample.ui.SecondaryFragment; import dagger.Subcomponent;
package com.github.aleksandermielczarek.napkinexample.component; /** * Created by Aleksander Mielczarek on 18.11.2016. */ @FragmentScope @Subcomponent(modules = FragmentModule.class) public interface FragmentComponent {
// Path: app/src/main/java/com/github/aleksandermielczarek/napkinexample/module/FragmentModule.java // @Module // @FragmentScope // public class FragmentModule extends NapkinFragmentModule { // // public FragmentModule(Fragment fragment) { // super(fragment); // } // // @Provides // @FragmentString // String provideNapkinString() { // return "Hello Napkin in Fragment!"; // } // } // // Path: app/src/main/java/com/github/aleksandermielczarek/napkinexample/ui/SecondaryFragment.java // public class SecondaryFragment extends Fragment { // // @Inject // protected SecondaryViewModel secondaryViewModel; // // @Override // public void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // // Napkin.<ActivityComponent>provideActivityComponent(this) // .with(new FragmentModule(this)) // .inject(this); // } // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // FragmentScondaryBinding binding = FragmentScondaryBinding.inflate(inflater, container, false); // binding.setViewModel(secondaryViewModel); // return binding.getRoot(); // } // } // Path: app/src/main/java/com/github/aleksandermielczarek/napkinexample/component/FragmentComponent.java import com.github.aleksandermielczarek.napkin.scope.FragmentScope; import com.github.aleksandermielczarek.napkinexample.module.FragmentModule; import com.github.aleksandermielczarek.napkinexample.ui.SecondaryFragment; import dagger.Subcomponent; package com.github.aleksandermielczarek.napkinexample.component; /** * Created by Aleksander Mielczarek on 18.11.2016. */ @FragmentScope @Subcomponent(modules = FragmentModule.class) public interface FragmentComponent {
void inject(SecondaryFragment secondaryFragment);
AleksanderMielczarek/Napkin
app/src/main/java/com/github/aleksandermielczarek/napkinexample/module/AppModule.java
// Path: module-scope-inverse-qualifier-inverse/src/main/java/com/github/aleksandermielczarek/napkin/module/NapkinAppModule.java // @Module // @ScopeApp // public class NapkinAppModule extends AbstractNapkinAppModule { // // public NapkinAppModule(Application application) { // super(application); // } // // @Override // @Provides // @ScopeApp // public Application provideApplication() { // return application; // } // // @Override // @Provides // @ScopeApp // @ContextApp // public Context provideContext() { // return application; // } // }
import android.app.Application; import com.github.aleksandermielczarek.napkin.module.NapkinAppModule; import com.github.aleksandermielczarek.napkin.scope.AppScope; import com.github.aleksandermielczarek.napkinexample.qualifier.AppString; import dagger.Module; import dagger.Provides;
package com.github.aleksandermielczarek.napkinexample.module; /** * Created by Aleksander Mielczarek on 13.05.2016. */ @Module @AppScope
// Path: module-scope-inverse-qualifier-inverse/src/main/java/com/github/aleksandermielczarek/napkin/module/NapkinAppModule.java // @Module // @ScopeApp // public class NapkinAppModule extends AbstractNapkinAppModule { // // public NapkinAppModule(Application application) { // super(application); // } // // @Override // @Provides // @ScopeApp // public Application provideApplication() { // return application; // } // // @Override // @Provides // @ScopeApp // @ContextApp // public Context provideContext() { // return application; // } // } // Path: app/src/main/java/com/github/aleksandermielczarek/napkinexample/module/AppModule.java import android.app.Application; import com.github.aleksandermielczarek.napkin.module.NapkinAppModule; import com.github.aleksandermielczarek.napkin.scope.AppScope; import com.github.aleksandermielczarek.napkinexample.qualifier.AppString; import dagger.Module; import dagger.Provides; package com.github.aleksandermielczarek.napkinexample.module; /** * Created by Aleksander Mielczarek on 13.05.2016. */ @Module @AppScope
public class AppModule extends NapkinAppModule {
AleksanderMielczarek/Napkin
app/src/main/java/com/github/aleksandermielczarek/napkinexample/ui/SecondaryFragment.java
// Path: napkin/src/main/java/com/github/aleksandermielczarek/napkin/Napkin.java // public class Napkin { // // private Napkin() { // // } // // @SuppressWarnings("unchecked") // public static <T> T provideComponent(Object object) { // ComponentProvider<T> componentProvider = (ComponentProvider<T>) object; // return componentProvider.provideComponent(); // } // // public static <T> T provideAppComponent(Context context) { // Context application = context.getApplicationContext(); // return provideComponent(application); // } // // public static <T> T provideAppComponent(Fragment fragment) { // Context context = fragment.getContext(); // return provideAppComponent(context); // } // // public static <T> T provideAppComponent(View view) { // Context context = view.getContext(); // return provideAppComponent(context); // } // // public static <T> T provideActivityComponent(Fragment fragment) { // Context activity = fragment.getActivity(); // return provideComponent(activity); // } // // public static <T> T provideActivityComponent(View view) { // Context activity = view.getContext(); // return provideComponent(activity); // } // } // // Path: app/src/main/java/com/github/aleksandermielczarek/napkinexample/component/ActivityComponent.java // @ActivityScope // @Subcomponent(modules = ActivityModule.class) // public interface ActivityComponent { // // FragmentComponent with(FragmentModule fragmentModule); // // void inject(MainActivity mainActivity); // } // // Path: app/src/main/java/com/github/aleksandermielczarek/napkinexample/module/FragmentModule.java // @Module // @FragmentScope // public class FragmentModule extends NapkinFragmentModule { // // public FragmentModule(Fragment fragment) { // super(fragment); // } // // @Provides // @FragmentString // String provideNapkinString() { // return "Hello Napkin in Fragment!"; // } // }
import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.github.aleksandermielczarek.napkin.Napkin; import com.github.aleksandermielczarek.napkinexample.component.ActivityComponent; import com.github.aleksandermielczarek.napkinexample.databinding.FragmentScondaryBinding; import com.github.aleksandermielczarek.napkinexample.module.FragmentModule; import javax.inject.Inject;
package com.github.aleksandermielczarek.napkinexample.ui; /** * Created by Aleksander Mielczarek on 18.11.2016. */ public class SecondaryFragment extends Fragment { @Inject protected SecondaryViewModel secondaryViewModel; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState);
// Path: napkin/src/main/java/com/github/aleksandermielczarek/napkin/Napkin.java // public class Napkin { // // private Napkin() { // // } // // @SuppressWarnings("unchecked") // public static <T> T provideComponent(Object object) { // ComponentProvider<T> componentProvider = (ComponentProvider<T>) object; // return componentProvider.provideComponent(); // } // // public static <T> T provideAppComponent(Context context) { // Context application = context.getApplicationContext(); // return provideComponent(application); // } // // public static <T> T provideAppComponent(Fragment fragment) { // Context context = fragment.getContext(); // return provideAppComponent(context); // } // // public static <T> T provideAppComponent(View view) { // Context context = view.getContext(); // return provideAppComponent(context); // } // // public static <T> T provideActivityComponent(Fragment fragment) { // Context activity = fragment.getActivity(); // return provideComponent(activity); // } // // public static <T> T provideActivityComponent(View view) { // Context activity = view.getContext(); // return provideComponent(activity); // } // } // // Path: app/src/main/java/com/github/aleksandermielczarek/napkinexample/component/ActivityComponent.java // @ActivityScope // @Subcomponent(modules = ActivityModule.class) // public interface ActivityComponent { // // FragmentComponent with(FragmentModule fragmentModule); // // void inject(MainActivity mainActivity); // } // // Path: app/src/main/java/com/github/aleksandermielczarek/napkinexample/module/FragmentModule.java // @Module // @FragmentScope // public class FragmentModule extends NapkinFragmentModule { // // public FragmentModule(Fragment fragment) { // super(fragment); // } // // @Provides // @FragmentString // String provideNapkinString() { // return "Hello Napkin in Fragment!"; // } // } // Path: app/src/main/java/com/github/aleksandermielczarek/napkinexample/ui/SecondaryFragment.java import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.github.aleksandermielczarek.napkin.Napkin; import com.github.aleksandermielczarek.napkinexample.component.ActivityComponent; import com.github.aleksandermielczarek.napkinexample.databinding.FragmentScondaryBinding; import com.github.aleksandermielczarek.napkinexample.module.FragmentModule; import javax.inject.Inject; package com.github.aleksandermielczarek.napkinexample.ui; /** * Created by Aleksander Mielczarek on 18.11.2016. */ public class SecondaryFragment extends Fragment { @Inject protected SecondaryViewModel secondaryViewModel; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState);
Napkin.<ActivityComponent>provideActivityComponent(this)
AleksanderMielczarek/Napkin
app/src/main/java/com/github/aleksandermielczarek/napkinexample/ui/SecondaryFragment.java
// Path: napkin/src/main/java/com/github/aleksandermielczarek/napkin/Napkin.java // public class Napkin { // // private Napkin() { // // } // // @SuppressWarnings("unchecked") // public static <T> T provideComponent(Object object) { // ComponentProvider<T> componentProvider = (ComponentProvider<T>) object; // return componentProvider.provideComponent(); // } // // public static <T> T provideAppComponent(Context context) { // Context application = context.getApplicationContext(); // return provideComponent(application); // } // // public static <T> T provideAppComponent(Fragment fragment) { // Context context = fragment.getContext(); // return provideAppComponent(context); // } // // public static <T> T provideAppComponent(View view) { // Context context = view.getContext(); // return provideAppComponent(context); // } // // public static <T> T provideActivityComponent(Fragment fragment) { // Context activity = fragment.getActivity(); // return provideComponent(activity); // } // // public static <T> T provideActivityComponent(View view) { // Context activity = view.getContext(); // return provideComponent(activity); // } // } // // Path: app/src/main/java/com/github/aleksandermielczarek/napkinexample/component/ActivityComponent.java // @ActivityScope // @Subcomponent(modules = ActivityModule.class) // public interface ActivityComponent { // // FragmentComponent with(FragmentModule fragmentModule); // // void inject(MainActivity mainActivity); // } // // Path: app/src/main/java/com/github/aleksandermielczarek/napkinexample/module/FragmentModule.java // @Module // @FragmentScope // public class FragmentModule extends NapkinFragmentModule { // // public FragmentModule(Fragment fragment) { // super(fragment); // } // // @Provides // @FragmentString // String provideNapkinString() { // return "Hello Napkin in Fragment!"; // } // }
import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.github.aleksandermielczarek.napkin.Napkin; import com.github.aleksandermielczarek.napkinexample.component.ActivityComponent; import com.github.aleksandermielczarek.napkinexample.databinding.FragmentScondaryBinding; import com.github.aleksandermielczarek.napkinexample.module.FragmentModule; import javax.inject.Inject;
package com.github.aleksandermielczarek.napkinexample.ui; /** * Created by Aleksander Mielczarek on 18.11.2016. */ public class SecondaryFragment extends Fragment { @Inject protected SecondaryViewModel secondaryViewModel; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState);
// Path: napkin/src/main/java/com/github/aleksandermielczarek/napkin/Napkin.java // public class Napkin { // // private Napkin() { // // } // // @SuppressWarnings("unchecked") // public static <T> T provideComponent(Object object) { // ComponentProvider<T> componentProvider = (ComponentProvider<T>) object; // return componentProvider.provideComponent(); // } // // public static <T> T provideAppComponent(Context context) { // Context application = context.getApplicationContext(); // return provideComponent(application); // } // // public static <T> T provideAppComponent(Fragment fragment) { // Context context = fragment.getContext(); // return provideAppComponent(context); // } // // public static <T> T provideAppComponent(View view) { // Context context = view.getContext(); // return provideAppComponent(context); // } // // public static <T> T provideActivityComponent(Fragment fragment) { // Context activity = fragment.getActivity(); // return provideComponent(activity); // } // // public static <T> T provideActivityComponent(View view) { // Context activity = view.getContext(); // return provideComponent(activity); // } // } // // Path: app/src/main/java/com/github/aleksandermielczarek/napkinexample/component/ActivityComponent.java // @ActivityScope // @Subcomponent(modules = ActivityModule.class) // public interface ActivityComponent { // // FragmentComponent with(FragmentModule fragmentModule); // // void inject(MainActivity mainActivity); // } // // Path: app/src/main/java/com/github/aleksandermielczarek/napkinexample/module/FragmentModule.java // @Module // @FragmentScope // public class FragmentModule extends NapkinFragmentModule { // // public FragmentModule(Fragment fragment) { // super(fragment); // } // // @Provides // @FragmentString // String provideNapkinString() { // return "Hello Napkin in Fragment!"; // } // } // Path: app/src/main/java/com/github/aleksandermielczarek/napkinexample/ui/SecondaryFragment.java import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.github.aleksandermielczarek.napkin.Napkin; import com.github.aleksandermielczarek.napkinexample.component.ActivityComponent; import com.github.aleksandermielczarek.napkinexample.databinding.FragmentScondaryBinding; import com.github.aleksandermielczarek.napkinexample.module.FragmentModule; import javax.inject.Inject; package com.github.aleksandermielczarek.napkinexample.ui; /** * Created by Aleksander Mielczarek on 18.11.2016. */ public class SecondaryFragment extends Fragment { @Inject protected SecondaryViewModel secondaryViewModel; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState);
Napkin.<ActivityComponent>provideActivityComponent(this)
AleksanderMielczarek/Napkin
app/src/main/java/com/github/aleksandermielczarek/napkinexample/ui/SecondaryFragment.java
// Path: napkin/src/main/java/com/github/aleksandermielczarek/napkin/Napkin.java // public class Napkin { // // private Napkin() { // // } // // @SuppressWarnings("unchecked") // public static <T> T provideComponent(Object object) { // ComponentProvider<T> componentProvider = (ComponentProvider<T>) object; // return componentProvider.provideComponent(); // } // // public static <T> T provideAppComponent(Context context) { // Context application = context.getApplicationContext(); // return provideComponent(application); // } // // public static <T> T provideAppComponent(Fragment fragment) { // Context context = fragment.getContext(); // return provideAppComponent(context); // } // // public static <T> T provideAppComponent(View view) { // Context context = view.getContext(); // return provideAppComponent(context); // } // // public static <T> T provideActivityComponent(Fragment fragment) { // Context activity = fragment.getActivity(); // return provideComponent(activity); // } // // public static <T> T provideActivityComponent(View view) { // Context activity = view.getContext(); // return provideComponent(activity); // } // } // // Path: app/src/main/java/com/github/aleksandermielczarek/napkinexample/component/ActivityComponent.java // @ActivityScope // @Subcomponent(modules = ActivityModule.class) // public interface ActivityComponent { // // FragmentComponent with(FragmentModule fragmentModule); // // void inject(MainActivity mainActivity); // } // // Path: app/src/main/java/com/github/aleksandermielczarek/napkinexample/module/FragmentModule.java // @Module // @FragmentScope // public class FragmentModule extends NapkinFragmentModule { // // public FragmentModule(Fragment fragment) { // super(fragment); // } // // @Provides // @FragmentString // String provideNapkinString() { // return "Hello Napkin in Fragment!"; // } // }
import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.github.aleksandermielczarek.napkin.Napkin; import com.github.aleksandermielczarek.napkinexample.component.ActivityComponent; import com.github.aleksandermielczarek.napkinexample.databinding.FragmentScondaryBinding; import com.github.aleksandermielczarek.napkinexample.module.FragmentModule; import javax.inject.Inject;
package com.github.aleksandermielczarek.napkinexample.ui; /** * Created by Aleksander Mielczarek on 18.11.2016. */ public class SecondaryFragment extends Fragment { @Inject protected SecondaryViewModel secondaryViewModel; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); Napkin.<ActivityComponent>provideActivityComponent(this)
// Path: napkin/src/main/java/com/github/aleksandermielczarek/napkin/Napkin.java // public class Napkin { // // private Napkin() { // // } // // @SuppressWarnings("unchecked") // public static <T> T provideComponent(Object object) { // ComponentProvider<T> componentProvider = (ComponentProvider<T>) object; // return componentProvider.provideComponent(); // } // // public static <T> T provideAppComponent(Context context) { // Context application = context.getApplicationContext(); // return provideComponent(application); // } // // public static <T> T provideAppComponent(Fragment fragment) { // Context context = fragment.getContext(); // return provideAppComponent(context); // } // // public static <T> T provideAppComponent(View view) { // Context context = view.getContext(); // return provideAppComponent(context); // } // // public static <T> T provideActivityComponent(Fragment fragment) { // Context activity = fragment.getActivity(); // return provideComponent(activity); // } // // public static <T> T provideActivityComponent(View view) { // Context activity = view.getContext(); // return provideComponent(activity); // } // } // // Path: app/src/main/java/com/github/aleksandermielczarek/napkinexample/component/ActivityComponent.java // @ActivityScope // @Subcomponent(modules = ActivityModule.class) // public interface ActivityComponent { // // FragmentComponent with(FragmentModule fragmentModule); // // void inject(MainActivity mainActivity); // } // // Path: app/src/main/java/com/github/aleksandermielczarek/napkinexample/module/FragmentModule.java // @Module // @FragmentScope // public class FragmentModule extends NapkinFragmentModule { // // public FragmentModule(Fragment fragment) { // super(fragment); // } // // @Provides // @FragmentString // String provideNapkinString() { // return "Hello Napkin in Fragment!"; // } // } // Path: app/src/main/java/com/github/aleksandermielczarek/napkinexample/ui/SecondaryFragment.java import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.github.aleksandermielczarek.napkin.Napkin; import com.github.aleksandermielczarek.napkinexample.component.ActivityComponent; import com.github.aleksandermielczarek.napkinexample.databinding.FragmentScondaryBinding; import com.github.aleksandermielczarek.napkinexample.module.FragmentModule; import javax.inject.Inject; package com.github.aleksandermielczarek.napkinexample.ui; /** * Created by Aleksander Mielczarek on 18.11.2016. */ public class SecondaryFragment extends Fragment { @Inject protected SecondaryViewModel secondaryViewModel; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); Napkin.<ActivityComponent>provideActivityComponent(this)
.with(new FragmentModule(this))
AleksanderMielczarek/Napkin
app/src/main/java/com/github/aleksandermielczarek/napkinexample/ui/MainActivity.java
// Path: napkin/src/main/java/com/github/aleksandermielczarek/napkin/ComponentProvider.java // public interface ComponentProvider<T> { // // T provideComponent(); // } // // Path: napkin/src/main/java/com/github/aleksandermielczarek/napkin/Napkin.java // public class Napkin { // // private Napkin() { // // } // // @SuppressWarnings("unchecked") // public static <T> T provideComponent(Object object) { // ComponentProvider<T> componentProvider = (ComponentProvider<T>) object; // return componentProvider.provideComponent(); // } // // public static <T> T provideAppComponent(Context context) { // Context application = context.getApplicationContext(); // return provideComponent(application); // } // // public static <T> T provideAppComponent(Fragment fragment) { // Context context = fragment.getContext(); // return provideAppComponent(context); // } // // public static <T> T provideAppComponent(View view) { // Context context = view.getContext(); // return provideAppComponent(context); // } // // public static <T> T provideActivityComponent(Fragment fragment) { // Context activity = fragment.getActivity(); // return provideComponent(activity); // } // // public static <T> T provideActivityComponent(View view) { // Context activity = view.getContext(); // return provideComponent(activity); // } // } // // Path: app/src/main/java/com/github/aleksandermielczarek/napkinexample/component/ActivityComponent.java // @ActivityScope // @Subcomponent(modules = ActivityModule.class) // public interface ActivityComponent { // // FragmentComponent with(FragmentModule fragmentModule); // // void inject(MainActivity mainActivity); // } // // Path: app/src/main/java/com/github/aleksandermielczarek/napkinexample/component/AppComponent.java // @Component(modules = AppModule.class) // @AppScope // public interface AppComponent { // // ActivityComponent with(ActivityModule activityModule); // } // // Path: app/src/main/java/com/github/aleksandermielczarek/napkinexample/module/ActivityModule.java // @Module // @ActivityScope // public class ActivityModule extends NapkinActivityModule { // // public ActivityModule(AppCompatActivity activity) { // super(activity); // } // // @Provides // @ActivityString // String provideNapkinString() { // return "Hello Napkin in Activity!"; // } // }
import android.databinding.DataBindingUtil; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import com.github.aleksandermielczarek.napkin.ComponentProvider; import com.github.aleksandermielczarek.napkin.Napkin; import com.github.aleksandermielczarek.napkinexample.R; import com.github.aleksandermielczarek.napkinexample.component.ActivityComponent; import com.github.aleksandermielczarek.napkinexample.component.AppComponent; import com.github.aleksandermielczarek.napkinexample.databinding.ActivityMainBinding; import com.github.aleksandermielczarek.napkinexample.module.ActivityModule; import javax.inject.Inject;
package com.github.aleksandermielczarek.napkinexample.ui; /** * Created by Aleksander Mielczarek on 13.05.2016. */ public class MainActivity extends AppCompatActivity implements ComponentProvider<ActivityComponent> { @Inject protected MainViewModel mainViewModel; private ActivityComponent activityComponent; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState);
// Path: napkin/src/main/java/com/github/aleksandermielczarek/napkin/ComponentProvider.java // public interface ComponentProvider<T> { // // T provideComponent(); // } // // Path: napkin/src/main/java/com/github/aleksandermielczarek/napkin/Napkin.java // public class Napkin { // // private Napkin() { // // } // // @SuppressWarnings("unchecked") // public static <T> T provideComponent(Object object) { // ComponentProvider<T> componentProvider = (ComponentProvider<T>) object; // return componentProvider.provideComponent(); // } // // public static <T> T provideAppComponent(Context context) { // Context application = context.getApplicationContext(); // return provideComponent(application); // } // // public static <T> T provideAppComponent(Fragment fragment) { // Context context = fragment.getContext(); // return provideAppComponent(context); // } // // public static <T> T provideAppComponent(View view) { // Context context = view.getContext(); // return provideAppComponent(context); // } // // public static <T> T provideActivityComponent(Fragment fragment) { // Context activity = fragment.getActivity(); // return provideComponent(activity); // } // // public static <T> T provideActivityComponent(View view) { // Context activity = view.getContext(); // return provideComponent(activity); // } // } // // Path: app/src/main/java/com/github/aleksandermielczarek/napkinexample/component/ActivityComponent.java // @ActivityScope // @Subcomponent(modules = ActivityModule.class) // public interface ActivityComponent { // // FragmentComponent with(FragmentModule fragmentModule); // // void inject(MainActivity mainActivity); // } // // Path: app/src/main/java/com/github/aleksandermielczarek/napkinexample/component/AppComponent.java // @Component(modules = AppModule.class) // @AppScope // public interface AppComponent { // // ActivityComponent with(ActivityModule activityModule); // } // // Path: app/src/main/java/com/github/aleksandermielczarek/napkinexample/module/ActivityModule.java // @Module // @ActivityScope // public class ActivityModule extends NapkinActivityModule { // // public ActivityModule(AppCompatActivity activity) { // super(activity); // } // // @Provides // @ActivityString // String provideNapkinString() { // return "Hello Napkin in Activity!"; // } // } // Path: app/src/main/java/com/github/aleksandermielczarek/napkinexample/ui/MainActivity.java import android.databinding.DataBindingUtil; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import com.github.aleksandermielczarek.napkin.ComponentProvider; import com.github.aleksandermielczarek.napkin.Napkin; import com.github.aleksandermielczarek.napkinexample.R; import com.github.aleksandermielczarek.napkinexample.component.ActivityComponent; import com.github.aleksandermielczarek.napkinexample.component.AppComponent; import com.github.aleksandermielczarek.napkinexample.databinding.ActivityMainBinding; import com.github.aleksandermielczarek.napkinexample.module.ActivityModule; import javax.inject.Inject; package com.github.aleksandermielczarek.napkinexample.ui; /** * Created by Aleksander Mielczarek on 13.05.2016. */ public class MainActivity extends AppCompatActivity implements ComponentProvider<ActivityComponent> { @Inject protected MainViewModel mainViewModel; private ActivityComponent activityComponent; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState);
activityComponent = Napkin.<AppComponent>provideAppComponent(this)
AleksanderMielczarek/Napkin
app/src/main/java/com/github/aleksandermielczarek/napkinexample/ui/MainActivity.java
// Path: napkin/src/main/java/com/github/aleksandermielczarek/napkin/ComponentProvider.java // public interface ComponentProvider<T> { // // T provideComponent(); // } // // Path: napkin/src/main/java/com/github/aleksandermielczarek/napkin/Napkin.java // public class Napkin { // // private Napkin() { // // } // // @SuppressWarnings("unchecked") // public static <T> T provideComponent(Object object) { // ComponentProvider<T> componentProvider = (ComponentProvider<T>) object; // return componentProvider.provideComponent(); // } // // public static <T> T provideAppComponent(Context context) { // Context application = context.getApplicationContext(); // return provideComponent(application); // } // // public static <T> T provideAppComponent(Fragment fragment) { // Context context = fragment.getContext(); // return provideAppComponent(context); // } // // public static <T> T provideAppComponent(View view) { // Context context = view.getContext(); // return provideAppComponent(context); // } // // public static <T> T provideActivityComponent(Fragment fragment) { // Context activity = fragment.getActivity(); // return provideComponent(activity); // } // // public static <T> T provideActivityComponent(View view) { // Context activity = view.getContext(); // return provideComponent(activity); // } // } // // Path: app/src/main/java/com/github/aleksandermielczarek/napkinexample/component/ActivityComponent.java // @ActivityScope // @Subcomponent(modules = ActivityModule.class) // public interface ActivityComponent { // // FragmentComponent with(FragmentModule fragmentModule); // // void inject(MainActivity mainActivity); // } // // Path: app/src/main/java/com/github/aleksandermielczarek/napkinexample/component/AppComponent.java // @Component(modules = AppModule.class) // @AppScope // public interface AppComponent { // // ActivityComponent with(ActivityModule activityModule); // } // // Path: app/src/main/java/com/github/aleksandermielczarek/napkinexample/module/ActivityModule.java // @Module // @ActivityScope // public class ActivityModule extends NapkinActivityModule { // // public ActivityModule(AppCompatActivity activity) { // super(activity); // } // // @Provides // @ActivityString // String provideNapkinString() { // return "Hello Napkin in Activity!"; // } // }
import android.databinding.DataBindingUtil; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import com.github.aleksandermielczarek.napkin.ComponentProvider; import com.github.aleksandermielczarek.napkin.Napkin; import com.github.aleksandermielczarek.napkinexample.R; import com.github.aleksandermielczarek.napkinexample.component.ActivityComponent; import com.github.aleksandermielczarek.napkinexample.component.AppComponent; import com.github.aleksandermielczarek.napkinexample.databinding.ActivityMainBinding; import com.github.aleksandermielczarek.napkinexample.module.ActivityModule; import javax.inject.Inject;
package com.github.aleksandermielczarek.napkinexample.ui; /** * Created by Aleksander Mielczarek on 13.05.2016. */ public class MainActivity extends AppCompatActivity implements ComponentProvider<ActivityComponent> { @Inject protected MainViewModel mainViewModel; private ActivityComponent activityComponent; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState);
// Path: napkin/src/main/java/com/github/aleksandermielczarek/napkin/ComponentProvider.java // public interface ComponentProvider<T> { // // T provideComponent(); // } // // Path: napkin/src/main/java/com/github/aleksandermielczarek/napkin/Napkin.java // public class Napkin { // // private Napkin() { // // } // // @SuppressWarnings("unchecked") // public static <T> T provideComponent(Object object) { // ComponentProvider<T> componentProvider = (ComponentProvider<T>) object; // return componentProvider.provideComponent(); // } // // public static <T> T provideAppComponent(Context context) { // Context application = context.getApplicationContext(); // return provideComponent(application); // } // // public static <T> T provideAppComponent(Fragment fragment) { // Context context = fragment.getContext(); // return provideAppComponent(context); // } // // public static <T> T provideAppComponent(View view) { // Context context = view.getContext(); // return provideAppComponent(context); // } // // public static <T> T provideActivityComponent(Fragment fragment) { // Context activity = fragment.getActivity(); // return provideComponent(activity); // } // // public static <T> T provideActivityComponent(View view) { // Context activity = view.getContext(); // return provideComponent(activity); // } // } // // Path: app/src/main/java/com/github/aleksandermielczarek/napkinexample/component/ActivityComponent.java // @ActivityScope // @Subcomponent(modules = ActivityModule.class) // public interface ActivityComponent { // // FragmentComponent with(FragmentModule fragmentModule); // // void inject(MainActivity mainActivity); // } // // Path: app/src/main/java/com/github/aleksandermielczarek/napkinexample/component/AppComponent.java // @Component(modules = AppModule.class) // @AppScope // public interface AppComponent { // // ActivityComponent with(ActivityModule activityModule); // } // // Path: app/src/main/java/com/github/aleksandermielczarek/napkinexample/module/ActivityModule.java // @Module // @ActivityScope // public class ActivityModule extends NapkinActivityModule { // // public ActivityModule(AppCompatActivity activity) { // super(activity); // } // // @Provides // @ActivityString // String provideNapkinString() { // return "Hello Napkin in Activity!"; // } // } // Path: app/src/main/java/com/github/aleksandermielczarek/napkinexample/ui/MainActivity.java import android.databinding.DataBindingUtil; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import com.github.aleksandermielczarek.napkin.ComponentProvider; import com.github.aleksandermielczarek.napkin.Napkin; import com.github.aleksandermielczarek.napkinexample.R; import com.github.aleksandermielczarek.napkinexample.component.ActivityComponent; import com.github.aleksandermielczarek.napkinexample.component.AppComponent; import com.github.aleksandermielczarek.napkinexample.databinding.ActivityMainBinding; import com.github.aleksandermielczarek.napkinexample.module.ActivityModule; import javax.inject.Inject; package com.github.aleksandermielczarek.napkinexample.ui; /** * Created by Aleksander Mielczarek on 13.05.2016. */ public class MainActivity extends AppCompatActivity implements ComponentProvider<ActivityComponent> { @Inject protected MainViewModel mainViewModel; private ActivityComponent activityComponent; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState);
activityComponent = Napkin.<AppComponent>provideAppComponent(this)
AleksanderMielczarek/Napkin
app/src/main/java/com/github/aleksandermielczarek/napkinexample/ui/MainActivity.java
// Path: napkin/src/main/java/com/github/aleksandermielczarek/napkin/ComponentProvider.java // public interface ComponentProvider<T> { // // T provideComponent(); // } // // Path: napkin/src/main/java/com/github/aleksandermielczarek/napkin/Napkin.java // public class Napkin { // // private Napkin() { // // } // // @SuppressWarnings("unchecked") // public static <T> T provideComponent(Object object) { // ComponentProvider<T> componentProvider = (ComponentProvider<T>) object; // return componentProvider.provideComponent(); // } // // public static <T> T provideAppComponent(Context context) { // Context application = context.getApplicationContext(); // return provideComponent(application); // } // // public static <T> T provideAppComponent(Fragment fragment) { // Context context = fragment.getContext(); // return provideAppComponent(context); // } // // public static <T> T provideAppComponent(View view) { // Context context = view.getContext(); // return provideAppComponent(context); // } // // public static <T> T provideActivityComponent(Fragment fragment) { // Context activity = fragment.getActivity(); // return provideComponent(activity); // } // // public static <T> T provideActivityComponent(View view) { // Context activity = view.getContext(); // return provideComponent(activity); // } // } // // Path: app/src/main/java/com/github/aleksandermielczarek/napkinexample/component/ActivityComponent.java // @ActivityScope // @Subcomponent(modules = ActivityModule.class) // public interface ActivityComponent { // // FragmentComponent with(FragmentModule fragmentModule); // // void inject(MainActivity mainActivity); // } // // Path: app/src/main/java/com/github/aleksandermielczarek/napkinexample/component/AppComponent.java // @Component(modules = AppModule.class) // @AppScope // public interface AppComponent { // // ActivityComponent with(ActivityModule activityModule); // } // // Path: app/src/main/java/com/github/aleksandermielczarek/napkinexample/module/ActivityModule.java // @Module // @ActivityScope // public class ActivityModule extends NapkinActivityModule { // // public ActivityModule(AppCompatActivity activity) { // super(activity); // } // // @Provides // @ActivityString // String provideNapkinString() { // return "Hello Napkin in Activity!"; // } // }
import android.databinding.DataBindingUtil; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import com.github.aleksandermielczarek.napkin.ComponentProvider; import com.github.aleksandermielczarek.napkin.Napkin; import com.github.aleksandermielczarek.napkinexample.R; import com.github.aleksandermielczarek.napkinexample.component.ActivityComponent; import com.github.aleksandermielczarek.napkinexample.component.AppComponent; import com.github.aleksandermielczarek.napkinexample.databinding.ActivityMainBinding; import com.github.aleksandermielczarek.napkinexample.module.ActivityModule; import javax.inject.Inject;
package com.github.aleksandermielczarek.napkinexample.ui; /** * Created by Aleksander Mielczarek on 13.05.2016. */ public class MainActivity extends AppCompatActivity implements ComponentProvider<ActivityComponent> { @Inject protected MainViewModel mainViewModel; private ActivityComponent activityComponent; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); activityComponent = Napkin.<AppComponent>provideAppComponent(this)
// Path: napkin/src/main/java/com/github/aleksandermielczarek/napkin/ComponentProvider.java // public interface ComponentProvider<T> { // // T provideComponent(); // } // // Path: napkin/src/main/java/com/github/aleksandermielczarek/napkin/Napkin.java // public class Napkin { // // private Napkin() { // // } // // @SuppressWarnings("unchecked") // public static <T> T provideComponent(Object object) { // ComponentProvider<T> componentProvider = (ComponentProvider<T>) object; // return componentProvider.provideComponent(); // } // // public static <T> T provideAppComponent(Context context) { // Context application = context.getApplicationContext(); // return provideComponent(application); // } // // public static <T> T provideAppComponent(Fragment fragment) { // Context context = fragment.getContext(); // return provideAppComponent(context); // } // // public static <T> T provideAppComponent(View view) { // Context context = view.getContext(); // return provideAppComponent(context); // } // // public static <T> T provideActivityComponent(Fragment fragment) { // Context activity = fragment.getActivity(); // return provideComponent(activity); // } // // public static <T> T provideActivityComponent(View view) { // Context activity = view.getContext(); // return provideComponent(activity); // } // } // // Path: app/src/main/java/com/github/aleksandermielczarek/napkinexample/component/ActivityComponent.java // @ActivityScope // @Subcomponent(modules = ActivityModule.class) // public interface ActivityComponent { // // FragmentComponent with(FragmentModule fragmentModule); // // void inject(MainActivity mainActivity); // } // // Path: app/src/main/java/com/github/aleksandermielczarek/napkinexample/component/AppComponent.java // @Component(modules = AppModule.class) // @AppScope // public interface AppComponent { // // ActivityComponent with(ActivityModule activityModule); // } // // Path: app/src/main/java/com/github/aleksandermielczarek/napkinexample/module/ActivityModule.java // @Module // @ActivityScope // public class ActivityModule extends NapkinActivityModule { // // public ActivityModule(AppCompatActivity activity) { // super(activity); // } // // @Provides // @ActivityString // String provideNapkinString() { // return "Hello Napkin in Activity!"; // } // } // Path: app/src/main/java/com/github/aleksandermielczarek/napkinexample/ui/MainActivity.java import android.databinding.DataBindingUtil; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import com.github.aleksandermielczarek.napkin.ComponentProvider; import com.github.aleksandermielczarek.napkin.Napkin; import com.github.aleksandermielczarek.napkinexample.R; import com.github.aleksandermielczarek.napkinexample.component.ActivityComponent; import com.github.aleksandermielczarek.napkinexample.component.AppComponent; import com.github.aleksandermielczarek.napkinexample.databinding.ActivityMainBinding; import com.github.aleksandermielczarek.napkinexample.module.ActivityModule; import javax.inject.Inject; package com.github.aleksandermielczarek.napkinexample.ui; /** * Created by Aleksander Mielczarek on 13.05.2016. */ public class MainActivity extends AppCompatActivity implements ComponentProvider<ActivityComponent> { @Inject protected MainViewModel mainViewModel; private ActivityComponent activityComponent; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); activityComponent = Napkin.<AppComponent>provideAppComponent(this)
.with(new ActivityModule(this));
AleksanderMielczarek/Napkin
app/src/main/java/com/github/aleksandermielczarek/napkinexample/component/AppComponent.java
// Path: app/src/main/java/com/github/aleksandermielczarek/napkinexample/module/ActivityModule.java // @Module // @ActivityScope // public class ActivityModule extends NapkinActivityModule { // // public ActivityModule(AppCompatActivity activity) { // super(activity); // } // // @Provides // @ActivityString // String provideNapkinString() { // return "Hello Napkin in Activity!"; // } // } // // Path: app/src/main/java/com/github/aleksandermielczarek/napkinexample/module/AppModule.java // @Module // @AppScope // public class AppModule extends NapkinAppModule { // // public AppModule(Application application) { // super(application); // } // // @Provides // @AppString // String provideNapkinString() { // return "Hello Napkin in App!"; // } // // }
import com.github.aleksandermielczarek.napkin.scope.AppScope; import com.github.aleksandermielczarek.napkinexample.module.ActivityModule; import com.github.aleksandermielczarek.napkinexample.module.AppModule; import dagger.Component;
package com.github.aleksandermielczarek.napkinexample.component; /** * Created by Aleksander Mielczarek on 13.05.2016. */ @Component(modules = AppModule.class) @AppScope public interface AppComponent {
// Path: app/src/main/java/com/github/aleksandermielczarek/napkinexample/module/ActivityModule.java // @Module // @ActivityScope // public class ActivityModule extends NapkinActivityModule { // // public ActivityModule(AppCompatActivity activity) { // super(activity); // } // // @Provides // @ActivityString // String provideNapkinString() { // return "Hello Napkin in Activity!"; // } // } // // Path: app/src/main/java/com/github/aleksandermielczarek/napkinexample/module/AppModule.java // @Module // @AppScope // public class AppModule extends NapkinAppModule { // // public AppModule(Application application) { // super(application); // } // // @Provides // @AppString // String provideNapkinString() { // return "Hello Napkin in App!"; // } // // } // Path: app/src/main/java/com/github/aleksandermielczarek/napkinexample/component/AppComponent.java import com.github.aleksandermielczarek.napkin.scope.AppScope; import com.github.aleksandermielczarek.napkinexample.module.ActivityModule; import com.github.aleksandermielczarek.napkinexample.module.AppModule; import dagger.Component; package com.github.aleksandermielczarek.napkinexample.component; /** * Created by Aleksander Mielczarek on 13.05.2016. */ @Component(modules = AppModule.class) @AppScope public interface AppComponent {
ActivityComponent with(ActivityModule activityModule);