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
mini2Dx/miniscript
gradle-plugin/src/main/java/org/mini2Dx/miniscript/gradle/compiler/LuaScriptCompiler.java
// Path: gradle-plugin/src/main/java/org/mini2Dx/miniscript/gradle/CompilerInputFile.java // public class CompilerInputFile { // private final File inputScriptFile; // private final String inputScriptFilename; // private final String inputScriptFileSuffix; // private final String inputScriptFilenameWithoutSuffix; // private final String inputScriptRelativeFilename; // private final String outputClassName; // // public CompilerInputFile(File scriptsRootDir, File scriptFile) { // super(); // this.inputScriptFile = scriptFile; // this.inputScriptFilename = inputScriptFile.getName(); // this.inputScriptFileSuffix = inputScriptFilename.substring(inputScriptFilename.lastIndexOf('.')).toLowerCase(); // this.inputScriptFilenameWithoutSuffix = inputScriptFile.getName().substring( 0, inputScriptFile.getName().lastIndexOf('.')); // final String inputScriptRelativeFilename = inputScriptFile.getAbsolutePath().replace(scriptsRootDir.getAbsolutePath(), ""); // // if(inputScriptRelativeFilename.startsWith("/") || inputScriptRelativeFilename.startsWith("\\")) { // this.inputScriptRelativeFilename = inputScriptRelativeFilename.substring(1); // } else { // this.inputScriptRelativeFilename = inputScriptRelativeFilename; // } // // this.outputClassName = inputScriptFilenameWithoutSuffix.replace('-', '_'); // } // // public File getInputScriptFile() { // return inputScriptFile; // } // // public String getInputScriptFilename() { // return inputScriptFilename; // } // // public String getInputScriptFileSuffix() { // return inputScriptFileSuffix; // } // // public String getInputScriptFilenameWithoutSuffix() { // return inputScriptFilenameWithoutSuffix; // } // // public String getInputScriptRelativeFilename() { // return inputScriptRelativeFilename; // } // // public String getOutputClassName() { // return outputClassName; // } // // public String getOutputPackageName(String rootScriptPackage) { // if(inputScriptRelativeFilename.indexOf('/') > 0 || inputScriptRelativeFilename.indexOf('\\') > 0) { // final String initialResult = rootScriptPackage + '.' + inputScriptRelativeFilename. // substring(0, inputScriptRelativeFilename.indexOf('/') > 0 ? // inputScriptRelativeFilename.lastIndexOf('/') : // inputScriptRelativeFilename.lastIndexOf('\\')). // replace('/', '.'). // replace('\\', '.'). // replace('-', '_'); // // final StringBuilder result = new StringBuilder(); // result.append(initialResult.charAt(0)); // for(int i = 1; i < initialResult.length(); i++) { // if(initialResult.charAt(i - 1) != '.') { // result.append(initialResult.charAt(i)); // continue; // } // if(Character.isJavaIdentifierStart(initialResult.charAt(i))) { // result.append(initialResult.charAt(i)); // continue; // } // result.append('_'); // result.append(initialResult.charAt(i)); // } // return result.toString(); // } // return rootScriptPackage; // } // }
import java.io.IOException; import java.util.Enumeration; import java.util.HashSet; import java.util.Hashtable; import java.util.Set; import org.gradle.api.GradleException; import org.gradle.api.Project; import org.luaj.vm2.lib.jse.JsePlatform; import org.mini2Dx.miniscript.gradle.CompilerInputFile; import java.io.FileInputStream; import java.io.FileOutputStream;
/** * The MIT License (MIT) * * Copyright (c) 2018 Thomas Cashman * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.mini2Dx.miniscript.gradle.compiler; public class LuaScriptCompiler implements ScriptCompiler { private final Project project; public LuaScriptCompiler(Project project) { super(); this.project = project; } @Override public Object compileFile(CompilerConfig compilerConfig) throws IOException {
// Path: gradle-plugin/src/main/java/org/mini2Dx/miniscript/gradle/CompilerInputFile.java // public class CompilerInputFile { // private final File inputScriptFile; // private final String inputScriptFilename; // private final String inputScriptFileSuffix; // private final String inputScriptFilenameWithoutSuffix; // private final String inputScriptRelativeFilename; // private final String outputClassName; // // public CompilerInputFile(File scriptsRootDir, File scriptFile) { // super(); // this.inputScriptFile = scriptFile; // this.inputScriptFilename = inputScriptFile.getName(); // this.inputScriptFileSuffix = inputScriptFilename.substring(inputScriptFilename.lastIndexOf('.')).toLowerCase(); // this.inputScriptFilenameWithoutSuffix = inputScriptFile.getName().substring( 0, inputScriptFile.getName().lastIndexOf('.')); // final String inputScriptRelativeFilename = inputScriptFile.getAbsolutePath().replace(scriptsRootDir.getAbsolutePath(), ""); // // if(inputScriptRelativeFilename.startsWith("/") || inputScriptRelativeFilename.startsWith("\\")) { // this.inputScriptRelativeFilename = inputScriptRelativeFilename.substring(1); // } else { // this.inputScriptRelativeFilename = inputScriptRelativeFilename; // } // // this.outputClassName = inputScriptFilenameWithoutSuffix.replace('-', '_'); // } // // public File getInputScriptFile() { // return inputScriptFile; // } // // public String getInputScriptFilename() { // return inputScriptFilename; // } // // public String getInputScriptFileSuffix() { // return inputScriptFileSuffix; // } // // public String getInputScriptFilenameWithoutSuffix() { // return inputScriptFilenameWithoutSuffix; // } // // public String getInputScriptRelativeFilename() { // return inputScriptRelativeFilename; // } // // public String getOutputClassName() { // return outputClassName; // } // // public String getOutputPackageName(String rootScriptPackage) { // if(inputScriptRelativeFilename.indexOf('/') > 0 || inputScriptRelativeFilename.indexOf('\\') > 0) { // final String initialResult = rootScriptPackage + '.' + inputScriptRelativeFilename. // substring(0, inputScriptRelativeFilename.indexOf('/') > 0 ? // inputScriptRelativeFilename.lastIndexOf('/') : // inputScriptRelativeFilename.lastIndexOf('\\')). // replace('/', '.'). // replace('\\', '.'). // replace('-', '_'); // // final StringBuilder result = new StringBuilder(); // result.append(initialResult.charAt(0)); // for(int i = 1; i < initialResult.length(); i++) { // if(initialResult.charAt(i - 1) != '.') { // result.append(initialResult.charAt(i)); // continue; // } // if(Character.isJavaIdentifierStart(initialResult.charAt(i))) { // result.append(initialResult.charAt(i)); // continue; // } // result.append('_'); // result.append(initialResult.charAt(i)); // } // return result.toString(); // } // return rootScriptPackage; // } // } // Path: gradle-plugin/src/main/java/org/mini2Dx/miniscript/gradle/compiler/LuaScriptCompiler.java import java.io.IOException; import java.util.Enumeration; import java.util.HashSet; import java.util.Hashtable; import java.util.Set; import org.gradle.api.GradleException; import org.gradle.api.Project; import org.luaj.vm2.lib.jse.JsePlatform; import org.mini2Dx.miniscript.gradle.CompilerInputFile; import java.io.FileInputStream; import java.io.FileOutputStream; /** * The MIT License (MIT) * * Copyright (c) 2018 Thomas Cashman * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.mini2Dx.miniscript.gradle.compiler; public class LuaScriptCompiler implements ScriptCompiler { private final Project project; public LuaScriptCompiler(Project project) { super(); this.project = project; } @Override public Object compileFile(CompilerConfig compilerConfig) throws IOException {
final CompilerInputFile inputFile = compilerConfig.getInputScriptFile();
mini2Dx/miniscript
core/src/test/java/org/mini2Dx/miniscript/core/util/ScheduledTaskQueueTest.java
// Path: core/src/main/java/org/mini2Dx/miniscript/core/threadpool/ScheduledTask.java // public class ScheduledTask implements Comparable<ScheduledTask> { // private static final ReadWriteArrayQueue<ScheduledTask> POOL = new ReadWriteArrayQueue<>(); // // private ScheduledTaskFuture future; // // private Runnable runnable; // private long scheduledStartTimeNanos; // // private long repeatInterval; // private TimeUnit repeatUnit; // // private boolean disposed = false; // // public void dispose() { // if(disposed) { // return; // } // // disposed = true; // // runnable = null; // scheduledStartTimeNanos = 0L; // // repeatUnit = null; // repeatInterval = 0L; // // future = null; // // POOL.add(this); // } // // public static ScheduledTask allocate(Runnable runnable, long scheduledStartTimeNanos) { // ScheduledTask task = POOL.poll(); // if(task == null) { // task = new ScheduledTask(); // } // task.disposed = false; // task.runnable = runnable; // task.scheduledStartTimeNanos = scheduledStartTimeNanos; // return task; // } // // public static ScheduledTask allocate(Runnable runnable, long scheduledStartTimeNanos, long repeatInterval, TimeUnit repeatUnit) { // ScheduledTask task = POOL.poll(); // if(task == null) { // task = new ScheduledTask(); // } // task.disposed = false; // task.runnable = runnable; // task.scheduledStartTimeNanos = scheduledStartTimeNanos; // task.repeatUnit = repeatUnit; // task.repeatInterval = repeatInterval; // return task; // } // // public Runnable getRunnable() { // return runnable; // } // // public long getScheduledStartTimeNanos() { // return scheduledStartTimeNanos; // } // // public boolean isRepeating() { // return repeatUnit != null; // } // // public long getRepeatInterval() { // return repeatInterval; // } // // public TimeUnit getRepeatUnit() { // return repeatUnit; // } // // @Override // public int compareTo(ScheduledTask o) { // return Long.compare(scheduledStartTimeNanos, o.scheduledStartTimeNanos); // } // // public ScheduledTaskFuture getFuture() { // return future; // } // // public void setFuture(ScheduledTaskFuture future) { // this.future = future; // } // }
import org.junit.Assert; import org.junit.Test; import org.mini2Dx.miniscript.core.threadpool.ScheduledTask; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong;
/** * Copyright 2021 Viridian Software Ltd. */ package org.mini2Dx.miniscript.core.util; public class ScheduledTaskQueueTest { private static final int MAX_CAPACITY = 5; @Test public void testDelay() { final ScheduledTaskQueue queue = new ScheduledTaskQueue(MAX_CAPACITY); final long expectedStartTimeNanos = System.nanoTime() + TimeUnit.SECONDS.toNanos(2L);
// Path: core/src/main/java/org/mini2Dx/miniscript/core/threadpool/ScheduledTask.java // public class ScheduledTask implements Comparable<ScheduledTask> { // private static final ReadWriteArrayQueue<ScheduledTask> POOL = new ReadWriteArrayQueue<>(); // // private ScheduledTaskFuture future; // // private Runnable runnable; // private long scheduledStartTimeNanos; // // private long repeatInterval; // private TimeUnit repeatUnit; // // private boolean disposed = false; // // public void dispose() { // if(disposed) { // return; // } // // disposed = true; // // runnable = null; // scheduledStartTimeNanos = 0L; // // repeatUnit = null; // repeatInterval = 0L; // // future = null; // // POOL.add(this); // } // // public static ScheduledTask allocate(Runnable runnable, long scheduledStartTimeNanos) { // ScheduledTask task = POOL.poll(); // if(task == null) { // task = new ScheduledTask(); // } // task.disposed = false; // task.runnable = runnable; // task.scheduledStartTimeNanos = scheduledStartTimeNanos; // return task; // } // // public static ScheduledTask allocate(Runnable runnable, long scheduledStartTimeNanos, long repeatInterval, TimeUnit repeatUnit) { // ScheduledTask task = POOL.poll(); // if(task == null) { // task = new ScheduledTask(); // } // task.disposed = false; // task.runnable = runnable; // task.scheduledStartTimeNanos = scheduledStartTimeNanos; // task.repeatUnit = repeatUnit; // task.repeatInterval = repeatInterval; // return task; // } // // public Runnable getRunnable() { // return runnable; // } // // public long getScheduledStartTimeNanos() { // return scheduledStartTimeNanos; // } // // public boolean isRepeating() { // return repeatUnit != null; // } // // public long getRepeatInterval() { // return repeatInterval; // } // // public TimeUnit getRepeatUnit() { // return repeatUnit; // } // // @Override // public int compareTo(ScheduledTask o) { // return Long.compare(scheduledStartTimeNanos, o.scheduledStartTimeNanos); // } // // public ScheduledTaskFuture getFuture() { // return future; // } // // public void setFuture(ScheduledTaskFuture future) { // this.future = future; // } // } // Path: core/src/test/java/org/mini2Dx/miniscript/core/util/ScheduledTaskQueueTest.java import org.junit.Assert; import org.junit.Test; import org.mini2Dx.miniscript.core.threadpool.ScheduledTask; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; /** * Copyright 2021 Viridian Software Ltd. */ package org.mini2Dx.miniscript.core.util; public class ScheduledTaskQueueTest { private static final int MAX_CAPACITY = 5; @Test public void testDelay() { final ScheduledTaskQueue queue = new ScheduledTaskQueue(MAX_CAPACITY); final long expectedStartTimeNanos = System.nanoTime() + TimeUnit.SECONDS.toNanos(2L);
queue.offer(ScheduledTask.allocate(() -> {
mini2Dx/miniscript
core/src/main/java/org/mini2Dx/miniscript/core/ScriptExecutorPool.java
// Path: core/src/main/java/org/mini2Dx/miniscript/core/exception/InsufficientCompilersException.java // public class InsufficientCompilersException extends Exception { // private static final long serialVersionUID = 2947579725300422095L; // // public InsufficientCompilersException() { // super("There were insufficient compilers available to compile the provided script"); // } // }
import org.mini2Dx.miniscript.core.exception.InsufficientCompilersException;
/** * The MIT License (MIT) * * Copyright (c) 2016 Thomas Cashman * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.mini2Dx.miniscript.core; /** * Common interface for language-specific {@link ScriptExecutor} pools. * * Manages resources for compilation and execution of scripts. */ public interface ScriptExecutorPool<S> { public int getCompiledScriptId(String filepath); public String getCompiledScriptPath(int scriptId);
// Path: core/src/main/java/org/mini2Dx/miniscript/core/exception/InsufficientCompilersException.java // public class InsufficientCompilersException extends Exception { // private static final long serialVersionUID = 2947579725300422095L; // // public InsufficientCompilersException() { // super("There were insufficient compilers available to compile the provided script"); // } // } // Path: core/src/main/java/org/mini2Dx/miniscript/core/ScriptExecutorPool.java import org.mini2Dx.miniscript.core.exception.InsufficientCompilersException; /** * The MIT License (MIT) * * Copyright (c) 2016 Thomas Cashman * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.mini2Dx.miniscript.core; /** * Common interface for language-specific {@link ScriptExecutor} pools. * * Manages resources for compilation and execution of scripts. */ public interface ScriptExecutorPool<S> { public int getCompiledScriptId(String filepath); public String getCompiledScriptPath(int scriptId);
public int preCompileScript(String filepath, String scriptContent) throws InsufficientCompilersException;
mini2Dx/miniscript
lua/src/main/java/org/mini2Dx/miniscript/lua/LuaScriptExecutor.java
// Path: core/src/main/java/org/mini2Dx/miniscript/core/exception/ScriptSkippedException.java // public class ScriptSkippedException extends RuntimeException { // private static final long serialVersionUID = -7901574884568506426L; // // }
import org.luaj.vm2.Globals; import org.luaj.vm2.LuaValue; import org.luaj.vm2.Varargs; import org.luaj.vm2.lib.jse.CoerceJavaToLua; import org.mini2Dx.miniscript.core.*; import org.mini2Dx.miniscript.core.exception.ScriptSkippedException;
/** * The MIT License (MIT) * * Copyright (c) 2016 Thomas Cashman * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.mini2Dx.miniscript.lua; /** * An implementation of {@link ScriptExecutor} for Lua scripts */ public class LuaScriptExecutor implements ScriptExecutor<LuaValue> { private final LuaScriptExecutorPool executorPool; public LuaScriptExecutor(LuaScriptExecutorPool executorPool) { this.executorPool = executorPool; } @Override public GameScript<LuaValue> compile(String script) { return new PerThreadGameScript<LuaValue>(script); } @Override public ScriptExecutionResult execute(int scriptId, GameScript<LuaValue> script, ScriptBindings bindings, boolean returnResult) throws Exception { final Globals globals = executorPool.getLocalGlobals(); final LuaEmbeddedScriptInvoker embeddedScriptInvoker = executorPool.getEmbeddedScriptInvokerPool().allocate(); embeddedScriptInvoker.setScriptBindings(bindings); embeddedScriptInvoker.setScriptExecutor(this); embeddedScriptInvoker.setParentScriptId(scriptId); for (String variableName : bindings.keySet()) { globals.set(variableName, CoerceJavaToLua.coerce(bindings.get(variableName))); } globals.set(ScriptBindings.SCRIPT_PARENT_ID_VAR, CoerceJavaToLua.coerce(-1)); globals.set(ScriptBindings.SCRIPT_ID_VAR, CoerceJavaToLua.coerce(scriptId)); globals.set(ScriptBindings.SCRIPT_INVOKE_VAR, CoerceJavaToLua.coerce(embeddedScriptInvoker)); if (!script.hasScript()) { script.setScript(executorPool.compileWithGlobals(globals, script)); } try { script.getScript().invoke(); } catch (Exception e) {
// Path: core/src/main/java/org/mini2Dx/miniscript/core/exception/ScriptSkippedException.java // public class ScriptSkippedException extends RuntimeException { // private static final long serialVersionUID = -7901574884568506426L; // // } // Path: lua/src/main/java/org/mini2Dx/miniscript/lua/LuaScriptExecutor.java import org.luaj.vm2.Globals; import org.luaj.vm2.LuaValue; import org.luaj.vm2.Varargs; import org.luaj.vm2.lib.jse.CoerceJavaToLua; import org.mini2Dx.miniscript.core.*; import org.mini2Dx.miniscript.core.exception.ScriptSkippedException; /** * The MIT License (MIT) * * Copyright (c) 2016 Thomas Cashman * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.mini2Dx.miniscript.lua; /** * An implementation of {@link ScriptExecutor} for Lua scripts */ public class LuaScriptExecutor implements ScriptExecutor<LuaValue> { private final LuaScriptExecutorPool executorPool; public LuaScriptExecutor(LuaScriptExecutorPool executorPool) { this.executorPool = executorPool; } @Override public GameScript<LuaValue> compile(String script) { return new PerThreadGameScript<LuaValue>(script); } @Override public ScriptExecutionResult execute(int scriptId, GameScript<LuaValue> script, ScriptBindings bindings, boolean returnResult) throws Exception { final Globals globals = executorPool.getLocalGlobals(); final LuaEmbeddedScriptInvoker embeddedScriptInvoker = executorPool.getEmbeddedScriptInvokerPool().allocate(); embeddedScriptInvoker.setScriptBindings(bindings); embeddedScriptInvoker.setScriptExecutor(this); embeddedScriptInvoker.setParentScriptId(scriptId); for (String variableName : bindings.keySet()) { globals.set(variableName, CoerceJavaToLua.coerce(bindings.get(variableName))); } globals.set(ScriptBindings.SCRIPT_PARENT_ID_VAR, CoerceJavaToLua.coerce(-1)); globals.set(ScriptBindings.SCRIPT_ID_VAR, CoerceJavaToLua.coerce(scriptId)); globals.set(ScriptBindings.SCRIPT_INVOKE_VAR, CoerceJavaToLua.coerce(embeddedScriptInvoker)); if (!script.hasScript()) { script.setScript(executorPool.compileWithGlobals(globals, script)); } try { script.getScript().invoke(); } catch (Exception e) {
if(e instanceof ScriptSkippedException || e.getCause() instanceof ScriptSkippedException) {
mini2Dx/miniscript
core/src/test/java/org/mini2Dx/miniscript/core/ScriptExecutionTaskTest.java
// Path: core/src/test/java/org/mini2Dx/miniscript/core/dummy/DummyGameScriptingEngine.java // public class DummyGameScriptingEngine extends GameScriptingEngine { // // @Override // protected ScriptExecutorPool<?> createScriptExecutorPool(ClasspathScriptProvider classpathScriptProvider, int poolSize, boolean sandboxing) { // return new DummyScriptExecutorPool(this, poolSize); // } // // @Override // public boolean isSandboxingSupported() { // return false; // } // // @Override // public boolean isEmbeddedSynchronousScriptSupported() { // return true; // } // } // // Path: core/src/test/java/org/mini2Dx/miniscript/core/dummy/DummyScript.java // public class DummyScript { // private final String scriptContent; // private boolean executed = false; // // public DummyScript(String scriptContent) { // this.scriptContent = scriptContent; // } // // public boolean isExecuted() { // return executed; // } // // public void setExecuted(boolean executed) { // this.executed = executed; // } // // public String getScriptContent() { // return scriptContent; // } // } // // Path: core/src/test/java/org/mini2Dx/miniscript/core/dummy/DummyScriptExecutor.java // public class DummyScriptExecutor implements ScriptExecutor<DummyScript> { // private final DummyScriptExecutorPool executorPool; // // public DummyScriptExecutor(DummyScriptExecutorPool executorPool) { // this.executorPool = executorPool; // } // // @Override // public GameScript<DummyScript> compile(String script) { // return new GlobalGameScript<DummyScript>(new DummyScript(script)); // } // // @Override // public ScriptExecutionResult execute(int scriptId, GameScript<DummyScript> script, ScriptBindings bindings, boolean returnResult) throws Exception { // script.getScript().setExecuted(true); // return returnResult ? new ScriptExecutionResult(new HashMap<String, Object>()) : null; // } // // @Override // public void executeEmbedded(int parentScriptId, int scriptId, GameScript<DummyScript> script, EmbeddedScriptInvoker embeddedScriptInvoker, ScriptBindings bindings) throws Exception { // script.getScript().setExecuted(true); // } // // @Override // public void release() { // executorPool.release(this); // } // // }
import org.junit.Assert; import org.junit.Test; import org.mini2Dx.miniscript.core.dummy.DummyGameScriptingEngine; import org.mini2Dx.miniscript.core.dummy.DummyScript; import org.mini2Dx.miniscript.core.dummy.DummyScriptExecutor;
/** * The MIT License (MIT) * * Copyright (c) 2016 Thomas Cashman * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.mini2Dx.miniscript.core; /** * Unit tests for {@link ScriptExecutionTask} */ public class ScriptExecutionTaskTest { @Test public void testRunExecutesScript() {
// Path: core/src/test/java/org/mini2Dx/miniscript/core/dummy/DummyGameScriptingEngine.java // public class DummyGameScriptingEngine extends GameScriptingEngine { // // @Override // protected ScriptExecutorPool<?> createScriptExecutorPool(ClasspathScriptProvider classpathScriptProvider, int poolSize, boolean sandboxing) { // return new DummyScriptExecutorPool(this, poolSize); // } // // @Override // public boolean isSandboxingSupported() { // return false; // } // // @Override // public boolean isEmbeddedSynchronousScriptSupported() { // return true; // } // } // // Path: core/src/test/java/org/mini2Dx/miniscript/core/dummy/DummyScript.java // public class DummyScript { // private final String scriptContent; // private boolean executed = false; // // public DummyScript(String scriptContent) { // this.scriptContent = scriptContent; // } // // public boolean isExecuted() { // return executed; // } // // public void setExecuted(boolean executed) { // this.executed = executed; // } // // public String getScriptContent() { // return scriptContent; // } // } // // Path: core/src/test/java/org/mini2Dx/miniscript/core/dummy/DummyScriptExecutor.java // public class DummyScriptExecutor implements ScriptExecutor<DummyScript> { // private final DummyScriptExecutorPool executorPool; // // public DummyScriptExecutor(DummyScriptExecutorPool executorPool) { // this.executorPool = executorPool; // } // // @Override // public GameScript<DummyScript> compile(String script) { // return new GlobalGameScript<DummyScript>(new DummyScript(script)); // } // // @Override // public ScriptExecutionResult execute(int scriptId, GameScript<DummyScript> script, ScriptBindings bindings, boolean returnResult) throws Exception { // script.getScript().setExecuted(true); // return returnResult ? new ScriptExecutionResult(new HashMap<String, Object>()) : null; // } // // @Override // public void executeEmbedded(int parentScriptId, int scriptId, GameScript<DummyScript> script, EmbeddedScriptInvoker embeddedScriptInvoker, ScriptBindings bindings) throws Exception { // script.getScript().setExecuted(true); // } // // @Override // public void release() { // executorPool.release(this); // } // // } // Path: core/src/test/java/org/mini2Dx/miniscript/core/ScriptExecutionTaskTest.java import org.junit.Assert; import org.junit.Test; import org.mini2Dx.miniscript.core.dummy.DummyGameScriptingEngine; import org.mini2Dx.miniscript.core.dummy.DummyScript; import org.mini2Dx.miniscript.core.dummy.DummyScriptExecutor; /** * The MIT License (MIT) * * Copyright (c) 2016 Thomas Cashman * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.mini2Dx.miniscript.core; /** * Unit tests for {@link ScriptExecutionTask} */ public class ScriptExecutionTaskTest { @Test public void testRunExecutesScript() {
DummyScript script = new DummyScript("");
mini2Dx/miniscript
core/src/test/java/org/mini2Dx/miniscript/core/ScriptExecutionTaskTest.java
// Path: core/src/test/java/org/mini2Dx/miniscript/core/dummy/DummyGameScriptingEngine.java // public class DummyGameScriptingEngine extends GameScriptingEngine { // // @Override // protected ScriptExecutorPool<?> createScriptExecutorPool(ClasspathScriptProvider classpathScriptProvider, int poolSize, boolean sandboxing) { // return new DummyScriptExecutorPool(this, poolSize); // } // // @Override // public boolean isSandboxingSupported() { // return false; // } // // @Override // public boolean isEmbeddedSynchronousScriptSupported() { // return true; // } // } // // Path: core/src/test/java/org/mini2Dx/miniscript/core/dummy/DummyScript.java // public class DummyScript { // private final String scriptContent; // private boolean executed = false; // // public DummyScript(String scriptContent) { // this.scriptContent = scriptContent; // } // // public boolean isExecuted() { // return executed; // } // // public void setExecuted(boolean executed) { // this.executed = executed; // } // // public String getScriptContent() { // return scriptContent; // } // } // // Path: core/src/test/java/org/mini2Dx/miniscript/core/dummy/DummyScriptExecutor.java // public class DummyScriptExecutor implements ScriptExecutor<DummyScript> { // private final DummyScriptExecutorPool executorPool; // // public DummyScriptExecutor(DummyScriptExecutorPool executorPool) { // this.executorPool = executorPool; // } // // @Override // public GameScript<DummyScript> compile(String script) { // return new GlobalGameScript<DummyScript>(new DummyScript(script)); // } // // @Override // public ScriptExecutionResult execute(int scriptId, GameScript<DummyScript> script, ScriptBindings bindings, boolean returnResult) throws Exception { // script.getScript().setExecuted(true); // return returnResult ? new ScriptExecutionResult(new HashMap<String, Object>()) : null; // } // // @Override // public void executeEmbedded(int parentScriptId, int scriptId, GameScript<DummyScript> script, EmbeddedScriptInvoker embeddedScriptInvoker, ScriptBindings bindings) throws Exception { // script.getScript().setExecuted(true); // } // // @Override // public void release() { // executorPool.release(this); // } // // }
import org.junit.Assert; import org.junit.Test; import org.mini2Dx.miniscript.core.dummy.DummyGameScriptingEngine; import org.mini2Dx.miniscript.core.dummy.DummyScript; import org.mini2Dx.miniscript.core.dummy.DummyScriptExecutor;
/** * The MIT License (MIT) * * Copyright (c) 2016 Thomas Cashman * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.mini2Dx.miniscript.core; /** * Unit tests for {@link ScriptExecutionTask} */ public class ScriptExecutionTaskTest { @Test public void testRunExecutesScript() { DummyScript script = new DummyScript("");
// Path: core/src/test/java/org/mini2Dx/miniscript/core/dummy/DummyGameScriptingEngine.java // public class DummyGameScriptingEngine extends GameScriptingEngine { // // @Override // protected ScriptExecutorPool<?> createScriptExecutorPool(ClasspathScriptProvider classpathScriptProvider, int poolSize, boolean sandboxing) { // return new DummyScriptExecutorPool(this, poolSize); // } // // @Override // public boolean isSandboxingSupported() { // return false; // } // // @Override // public boolean isEmbeddedSynchronousScriptSupported() { // return true; // } // } // // Path: core/src/test/java/org/mini2Dx/miniscript/core/dummy/DummyScript.java // public class DummyScript { // private final String scriptContent; // private boolean executed = false; // // public DummyScript(String scriptContent) { // this.scriptContent = scriptContent; // } // // public boolean isExecuted() { // return executed; // } // // public void setExecuted(boolean executed) { // this.executed = executed; // } // // public String getScriptContent() { // return scriptContent; // } // } // // Path: core/src/test/java/org/mini2Dx/miniscript/core/dummy/DummyScriptExecutor.java // public class DummyScriptExecutor implements ScriptExecutor<DummyScript> { // private final DummyScriptExecutorPool executorPool; // // public DummyScriptExecutor(DummyScriptExecutorPool executorPool) { // this.executorPool = executorPool; // } // // @Override // public GameScript<DummyScript> compile(String script) { // return new GlobalGameScript<DummyScript>(new DummyScript(script)); // } // // @Override // public ScriptExecutionResult execute(int scriptId, GameScript<DummyScript> script, ScriptBindings bindings, boolean returnResult) throws Exception { // script.getScript().setExecuted(true); // return returnResult ? new ScriptExecutionResult(new HashMap<String, Object>()) : null; // } // // @Override // public void executeEmbedded(int parentScriptId, int scriptId, GameScript<DummyScript> script, EmbeddedScriptInvoker embeddedScriptInvoker, ScriptBindings bindings) throws Exception { // script.getScript().setExecuted(true); // } // // @Override // public void release() { // executorPool.release(this); // } // // } // Path: core/src/test/java/org/mini2Dx/miniscript/core/ScriptExecutionTaskTest.java import org.junit.Assert; import org.junit.Test; import org.mini2Dx.miniscript.core.dummy.DummyGameScriptingEngine; import org.mini2Dx.miniscript.core.dummy.DummyScript; import org.mini2Dx.miniscript.core.dummy.DummyScriptExecutor; /** * The MIT License (MIT) * * Copyright (c) 2016 Thomas Cashman * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.mini2Dx.miniscript.core; /** * Unit tests for {@link ScriptExecutionTask} */ public class ScriptExecutionTaskTest { @Test public void testRunExecutesScript() { DummyScript script = new DummyScript("");
ScriptExecutionTask<DummyScript> task = new ScriptExecutionTask<DummyScript>(0, new DummyGameScriptingEngine(),
mini2Dx/miniscript
core/src/test/java/org/mini2Dx/miniscript/core/ScriptExecutionTaskTest.java
// Path: core/src/test/java/org/mini2Dx/miniscript/core/dummy/DummyGameScriptingEngine.java // public class DummyGameScriptingEngine extends GameScriptingEngine { // // @Override // protected ScriptExecutorPool<?> createScriptExecutorPool(ClasspathScriptProvider classpathScriptProvider, int poolSize, boolean sandboxing) { // return new DummyScriptExecutorPool(this, poolSize); // } // // @Override // public boolean isSandboxingSupported() { // return false; // } // // @Override // public boolean isEmbeddedSynchronousScriptSupported() { // return true; // } // } // // Path: core/src/test/java/org/mini2Dx/miniscript/core/dummy/DummyScript.java // public class DummyScript { // private final String scriptContent; // private boolean executed = false; // // public DummyScript(String scriptContent) { // this.scriptContent = scriptContent; // } // // public boolean isExecuted() { // return executed; // } // // public void setExecuted(boolean executed) { // this.executed = executed; // } // // public String getScriptContent() { // return scriptContent; // } // } // // Path: core/src/test/java/org/mini2Dx/miniscript/core/dummy/DummyScriptExecutor.java // public class DummyScriptExecutor implements ScriptExecutor<DummyScript> { // private final DummyScriptExecutorPool executorPool; // // public DummyScriptExecutor(DummyScriptExecutorPool executorPool) { // this.executorPool = executorPool; // } // // @Override // public GameScript<DummyScript> compile(String script) { // return new GlobalGameScript<DummyScript>(new DummyScript(script)); // } // // @Override // public ScriptExecutionResult execute(int scriptId, GameScript<DummyScript> script, ScriptBindings bindings, boolean returnResult) throws Exception { // script.getScript().setExecuted(true); // return returnResult ? new ScriptExecutionResult(new HashMap<String, Object>()) : null; // } // // @Override // public void executeEmbedded(int parentScriptId, int scriptId, GameScript<DummyScript> script, EmbeddedScriptInvoker embeddedScriptInvoker, ScriptBindings bindings) throws Exception { // script.getScript().setExecuted(true); // } // // @Override // public void release() { // executorPool.release(this); // } // // }
import org.junit.Assert; import org.junit.Test; import org.mini2Dx.miniscript.core.dummy.DummyGameScriptingEngine; import org.mini2Dx.miniscript.core.dummy.DummyScript; import org.mini2Dx.miniscript.core.dummy.DummyScriptExecutor;
/** * The MIT License (MIT) * * Copyright (c) 2016 Thomas Cashman * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.mini2Dx.miniscript.core; /** * Unit tests for {@link ScriptExecutionTask} */ public class ScriptExecutionTaskTest { @Test public void testRunExecutesScript() { DummyScript script = new DummyScript(""); ScriptExecutionTask<DummyScript> task = new ScriptExecutionTask<DummyScript>(0, new DummyGameScriptingEngine(),
// Path: core/src/test/java/org/mini2Dx/miniscript/core/dummy/DummyGameScriptingEngine.java // public class DummyGameScriptingEngine extends GameScriptingEngine { // // @Override // protected ScriptExecutorPool<?> createScriptExecutorPool(ClasspathScriptProvider classpathScriptProvider, int poolSize, boolean sandboxing) { // return new DummyScriptExecutorPool(this, poolSize); // } // // @Override // public boolean isSandboxingSupported() { // return false; // } // // @Override // public boolean isEmbeddedSynchronousScriptSupported() { // return true; // } // } // // Path: core/src/test/java/org/mini2Dx/miniscript/core/dummy/DummyScript.java // public class DummyScript { // private final String scriptContent; // private boolean executed = false; // // public DummyScript(String scriptContent) { // this.scriptContent = scriptContent; // } // // public boolean isExecuted() { // return executed; // } // // public void setExecuted(boolean executed) { // this.executed = executed; // } // // public String getScriptContent() { // return scriptContent; // } // } // // Path: core/src/test/java/org/mini2Dx/miniscript/core/dummy/DummyScriptExecutor.java // public class DummyScriptExecutor implements ScriptExecutor<DummyScript> { // private final DummyScriptExecutorPool executorPool; // // public DummyScriptExecutor(DummyScriptExecutorPool executorPool) { // this.executorPool = executorPool; // } // // @Override // public GameScript<DummyScript> compile(String script) { // return new GlobalGameScript<DummyScript>(new DummyScript(script)); // } // // @Override // public ScriptExecutionResult execute(int scriptId, GameScript<DummyScript> script, ScriptBindings bindings, boolean returnResult) throws Exception { // script.getScript().setExecuted(true); // return returnResult ? new ScriptExecutionResult(new HashMap<String, Object>()) : null; // } // // @Override // public void executeEmbedded(int parentScriptId, int scriptId, GameScript<DummyScript> script, EmbeddedScriptInvoker embeddedScriptInvoker, ScriptBindings bindings) throws Exception { // script.getScript().setExecuted(true); // } // // @Override // public void release() { // executorPool.release(this); // } // // } // Path: core/src/test/java/org/mini2Dx/miniscript/core/ScriptExecutionTaskTest.java import org.junit.Assert; import org.junit.Test; import org.mini2Dx.miniscript.core.dummy.DummyGameScriptingEngine; import org.mini2Dx.miniscript.core.dummy.DummyScript; import org.mini2Dx.miniscript.core.dummy.DummyScriptExecutor; /** * The MIT License (MIT) * * Copyright (c) 2016 Thomas Cashman * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.mini2Dx.miniscript.core; /** * Unit tests for {@link ScriptExecutionTask} */ public class ScriptExecutionTaskTest { @Test public void testRunExecutesScript() { DummyScript script = new DummyScript(""); ScriptExecutionTask<DummyScript> task = new ScriptExecutionTask<DummyScript>(0, new DummyGameScriptingEngine(),
new DummyScriptExecutor(null), 0, new GlobalGameScript<DummyScript>(script), new ScriptBindings(), null, true);
mini2Dx/miniscript
core/src/main/java/org/mini2Dx/miniscript/core/exception/ScriptExecutorUnavailableException.java
// Path: core/src/main/java/org/mini2Dx/miniscript/core/ScriptExecutor.java // public interface ScriptExecutor<S> { // // public GameScript<S> compile(String script); // // public ScriptExecutionResult execute(int scriptId, GameScript<S> script, ScriptBindings bindings, boolean returnResult) // throws Exception; // // public void executeEmbedded(int parentScriptId, int scriptId, GameScript<S> script, EmbeddedScriptInvoker embeddedScriptInvoker, ScriptBindings bindings) throws Exception; // // public void release(); // }
import org.mini2Dx.miniscript.core.ScriptExecutor;
/** * The MIT License (MIT) * * Copyright (c) 2016 Thomas Cashman * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.mini2Dx.miniscript.core.exception; /** * Called when a script is attempting to execute but a {@link ScriptExecutor} in * unavailable */ public class ScriptExecutorUnavailableException extends RuntimeException { private static final long serialVersionUID = -8409957449519524312L; public ScriptExecutorUnavailableException(int scriptId) {
// Path: core/src/main/java/org/mini2Dx/miniscript/core/ScriptExecutor.java // public interface ScriptExecutor<S> { // // public GameScript<S> compile(String script); // // public ScriptExecutionResult execute(int scriptId, GameScript<S> script, ScriptBindings bindings, boolean returnResult) // throws Exception; // // public void executeEmbedded(int parentScriptId, int scriptId, GameScript<S> script, EmbeddedScriptInvoker embeddedScriptInvoker, ScriptBindings bindings) throws Exception; // // public void release(); // } // Path: core/src/main/java/org/mini2Dx/miniscript/core/exception/ScriptExecutorUnavailableException.java import org.mini2Dx.miniscript.core.ScriptExecutor; /** * The MIT License (MIT) * * Copyright (c) 2016 Thomas Cashman * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.mini2Dx.miniscript.core.exception; /** * Called when a script is attempting to execute but a {@link ScriptExecutor} in * unavailable */ public class ScriptExecutorUnavailableException extends RuntimeException { private static final long serialVersionUID = -8409957449519524312L; public ScriptExecutorUnavailableException(int scriptId) {
super("Unable to execute script " + scriptId + " due to no available " + ScriptExecutor.class.getSimpleName());
mini2Dx/miniscript
core/src/main/java/org/mini2Dx/miniscript/core/threadpool/KavaThreadPoolProvider.java
// Path: core/src/main/java/org/mini2Dx/miniscript/core/ThreadPoolProvider.java // public interface ThreadPoolProvider { // // Future<?> submit(Runnable task); // // ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit); // // public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit); // // void shutdown(boolean interruptThreads); // // } // // Path: core/src/main/java/org/mini2Dx/miniscript/core/util/ScheduledTaskQueue.java // public class ScheduledTaskQueue extends ReadWritePriorityQueue<ScheduledTask> { // // public ScheduledTaskQueue() { // this(Integer.MAX_VALUE); // } // // public ScheduledTaskQueue(int maxCapacity) { // super(maxCapacity); // } // // @Override // public ScheduledTask take() throws InterruptedException { // ScheduledTask head = super.peek(); // while(head == null || head.getScheduledStartTimeNanos() > System.nanoTime()) { // if(head == null) { // synchronized(waitingForItemsMonitor) { // waitingForItemsMonitor.wait(); // } // } else { // long currentTimeNanos = System.nanoTime(); // long delayMillis = Math.max (0, (head.getScheduledStartTimeNanos() - currentTimeNanos) / TimeUnit.MILLISECONDS.toNanos(1)); // int delayNanos = Math.max (0, (int) ((head.getScheduledStartTimeNanos() - currentTimeNanos) % TimeUnit.MILLISECONDS.toNanos(1))); // // synchronized(waitingForItemsMonitor) { // waitingForItemsMonitor.wait(delayMillis, delayNanos); // } // } // // head = super.peek(); // } // // lock.lockWrite(); // ScheduledTask result = super.peek(); // while (isEmpty() || result == null || result.getScheduledStartTimeNanos() > System.nanoTime()) { // lock.unlockWrite(); // synchronized(waitingForItemsMonitor) { // if(result == null) { // waitingForItemsMonitor.wait(); // } else { // long currentTimeNanos = System.nanoTime(); // long delayMillis = Math.max (0, (head.getScheduledStartTimeNanos() - currentTimeNanos) / TimeUnit.MILLISECONDS.toNanos(1)); // int delayNanos = Math.max (0, (int) ((head.getScheduledStartTimeNanos() - currentTimeNanos) % TimeUnit.MILLISECONDS.toNanos(1))); // waitingForItemsMonitor.wait(delayMillis, delayNanos); // } // } // lock.lockWrite(); // result = super.peek(); // } // result = super.poll(); // lock.unlockWrite(); // // synchronized(waitingForRemovalMonitor) { // waitingForRemovalMonitor.notify(); // } // return result; // } // }
import org.mini2Dx.miniscript.core.ThreadPoolProvider; import org.mini2Dx.miniscript.core.util.ScheduledTaskQueue; import java.util.concurrent.Future; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean;
/** * The MIT License (MIT) * * Copyright (c) 2021 Thomas Cashman * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.mini2Dx.miniscript.core.threadpool; /** * {@link ThreadPoolProvider} implementation for Kava-based runtimes */ public class KavaThreadPoolProvider implements Runnable, ThreadPoolProvider { private final AtomicBoolean running = new AtomicBoolean(true); private final Thread [] threads;
// Path: core/src/main/java/org/mini2Dx/miniscript/core/ThreadPoolProvider.java // public interface ThreadPoolProvider { // // Future<?> submit(Runnable task); // // ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit); // // public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit); // // void shutdown(boolean interruptThreads); // // } // // Path: core/src/main/java/org/mini2Dx/miniscript/core/util/ScheduledTaskQueue.java // public class ScheduledTaskQueue extends ReadWritePriorityQueue<ScheduledTask> { // // public ScheduledTaskQueue() { // this(Integer.MAX_VALUE); // } // // public ScheduledTaskQueue(int maxCapacity) { // super(maxCapacity); // } // // @Override // public ScheduledTask take() throws InterruptedException { // ScheduledTask head = super.peek(); // while(head == null || head.getScheduledStartTimeNanos() > System.nanoTime()) { // if(head == null) { // synchronized(waitingForItemsMonitor) { // waitingForItemsMonitor.wait(); // } // } else { // long currentTimeNanos = System.nanoTime(); // long delayMillis = Math.max (0, (head.getScheduledStartTimeNanos() - currentTimeNanos) / TimeUnit.MILLISECONDS.toNanos(1)); // int delayNanos = Math.max (0, (int) ((head.getScheduledStartTimeNanos() - currentTimeNanos) % TimeUnit.MILLISECONDS.toNanos(1))); // // synchronized(waitingForItemsMonitor) { // waitingForItemsMonitor.wait(delayMillis, delayNanos); // } // } // // head = super.peek(); // } // // lock.lockWrite(); // ScheduledTask result = super.peek(); // while (isEmpty() || result == null || result.getScheduledStartTimeNanos() > System.nanoTime()) { // lock.unlockWrite(); // synchronized(waitingForItemsMonitor) { // if(result == null) { // waitingForItemsMonitor.wait(); // } else { // long currentTimeNanos = System.nanoTime(); // long delayMillis = Math.max (0, (head.getScheduledStartTimeNanos() - currentTimeNanos) / TimeUnit.MILLISECONDS.toNanos(1)); // int delayNanos = Math.max (0, (int) ((head.getScheduledStartTimeNanos() - currentTimeNanos) % TimeUnit.MILLISECONDS.toNanos(1))); // waitingForItemsMonitor.wait(delayMillis, delayNanos); // } // } // lock.lockWrite(); // result = super.peek(); // } // result = super.poll(); // lock.unlockWrite(); // // synchronized(waitingForRemovalMonitor) { // waitingForRemovalMonitor.notify(); // } // return result; // } // } // Path: core/src/main/java/org/mini2Dx/miniscript/core/threadpool/KavaThreadPoolProvider.java import org.mini2Dx.miniscript.core.ThreadPoolProvider; import org.mini2Dx.miniscript.core.util.ScheduledTaskQueue; import java.util.concurrent.Future; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; /** * The MIT License (MIT) * * Copyright (c) 2021 Thomas Cashman * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.mini2Dx.miniscript.core.threadpool; /** * {@link ThreadPoolProvider} implementation for Kava-based runtimes */ public class KavaThreadPoolProvider implements Runnable, ThreadPoolProvider { private final AtomicBoolean running = new AtomicBoolean(true); private final Thread [] threads;
private final ScheduledTaskQueue scheduledTaskQueue = new ScheduledTaskQueue();
mini2Dx/miniscript
core/src/main/java/org/mini2Dx/miniscript/core/ScriptInvocationPool.java
// Path: core/src/main/java/org/mini2Dx/miniscript/core/util/ReadWriteArrayQueue.java // public class ReadWriteArrayQueue<E> extends AbstractConcurrentQueue<E> { // // public ReadWriteArrayQueue() { // super(new ArrayDeque()); // } // }
import org.mini2Dx.miniscript.core.util.ReadWriteArrayQueue; import java.util.Queue; import java.util.concurrent.atomic.AtomicInteger;
/** * The MIT License (MIT) * * Copyright (c) 2016 Thomas Cashman * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.mini2Dx.miniscript.core; /** * Provides a pool of reusable {@link ScriptInvocation} instances to reduce * object allocation */ public class ScriptInvocationPool { private final AtomicInteger ID_GENERATOR = new AtomicInteger(0);
// Path: core/src/main/java/org/mini2Dx/miniscript/core/util/ReadWriteArrayQueue.java // public class ReadWriteArrayQueue<E> extends AbstractConcurrentQueue<E> { // // public ReadWriteArrayQueue() { // super(new ArrayDeque()); // } // } // Path: core/src/main/java/org/mini2Dx/miniscript/core/ScriptInvocationPool.java import org.mini2Dx.miniscript.core.util.ReadWriteArrayQueue; import java.util.Queue; import java.util.concurrent.atomic.AtomicInteger; /** * The MIT License (MIT) * * Copyright (c) 2016 Thomas Cashman * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.mini2Dx.miniscript.core; /** * Provides a pool of reusable {@link ScriptInvocation} instances to reduce * object allocation */ public class ScriptInvocationPool { private final AtomicInteger ID_GENERATOR = new AtomicInteger(0);
private final Queue<ScriptInvocation> pool = new ReadWriteArrayQueue<>();
mini2Dx/miniscript
core/src/main/java/org/mini2Dx/miniscript/core/EmbeddedScriptInvoker.java
// Path: core/src/main/java/org/mini2Dx/miniscript/core/exception/NoSuchScriptException.java // public class NoSuchScriptException extends RuntimeException { // // public NoSuchScriptException(int scriptId) { // super("No script with id " + scriptId + " exists"); // } // // public NoSuchScriptException(String filepath) { // super("No script " + filepath + " exists"); // } // }
import org.mini2Dx.miniscript.core.exception.NoSuchScriptException;
/** * The MIT License (MIT) * <p> * Copyright (c) 2020 Thomas Cashman * <p> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p> * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * <p> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.mini2Dx.miniscript.core; /** * Utility class for invoking scripts inside of other scripts */ public abstract class EmbeddedScriptInvoker { protected final GameScriptingEngine gameScriptingEngine; protected int parentScriptId; protected ScriptBindings scriptBindings; public EmbeddedScriptInvoker(GameScriptingEngine gameScriptingEngine) { this.gameScriptingEngine = gameScriptingEngine; } public int getScriptId(String filepath) { return gameScriptingEngine.getCompiledScriptId(filepath); } /** * Invokes a script during the execution of the current script. Equivalent to calling a function. * @param scriptId The script ID to invoke */ public abstract void invokeSync(int scriptId); /** * Invokes a script during the execution of the current script. Equivalent to calling a function. * @param filepath The filepath of the script to invoke */ public void invokeSync(String filepath) { final int scriptId = gameScriptingEngine.getCompiledScriptId(filepath); if (scriptId < 0) {
// Path: core/src/main/java/org/mini2Dx/miniscript/core/exception/NoSuchScriptException.java // public class NoSuchScriptException extends RuntimeException { // // public NoSuchScriptException(int scriptId) { // super("No script with id " + scriptId + " exists"); // } // // public NoSuchScriptException(String filepath) { // super("No script " + filepath + " exists"); // } // } // Path: core/src/main/java/org/mini2Dx/miniscript/core/EmbeddedScriptInvoker.java import org.mini2Dx.miniscript.core.exception.NoSuchScriptException; /** * The MIT License (MIT) * <p> * Copyright (c) 2020 Thomas Cashman * <p> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p> * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * <p> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.mini2Dx.miniscript.core; /** * Utility class for invoking scripts inside of other scripts */ public abstract class EmbeddedScriptInvoker { protected final GameScriptingEngine gameScriptingEngine; protected int parentScriptId; protected ScriptBindings scriptBindings; public EmbeddedScriptInvoker(GameScriptingEngine gameScriptingEngine) { this.gameScriptingEngine = gameScriptingEngine; } public int getScriptId(String filepath) { return gameScriptingEngine.getCompiledScriptId(filepath); } /** * Invokes a script during the execution of the current script. Equivalent to calling a function. * @param scriptId The script ID to invoke */ public abstract void invokeSync(int scriptId); /** * Invokes a script during the execution of the current script. Equivalent to calling a function. * @param filepath The filepath of the script to invoke */ public void invokeSync(String filepath) { final int scriptId = gameScriptingEngine.getCompiledScriptId(filepath); if (scriptId < 0) {
throw new NoSuchScriptException(filepath);
mini2Dx/miniscript
gradle-plugin/src/main/java/org/mini2Dx/miniscript/gradle/MiniscriptStubTask.java
// Path: core/src/main/java/org/mini2Dx/miniscript/core/GeneratedClasspathScriptProvider.java // public abstract class GeneratedClasspathScriptProvider implements ClasspathScriptProvider { // private final Map<String, Integer> scriptFilepathsToIds = new HashMap<String, Integer>(); // private final Map<Integer, String> scriptIdsToFilepaths = new HashMap<Integer, String>(); // private final Map<Integer, Object> idsToScripts = new HashMap<Integer, Object>(); // // public GeneratedClasspathScriptProvider() { // super(); // // final Map<String, Object> generatedScripts = getGeneratedScripts(); // // int count = 0; // for(String filepath : generatedScripts.keySet()) { // scriptFilepathsToIds.put(filepath, count); // scriptIdsToFilepaths.put(count, filepath); // idsToScripts.put(count, generatedScripts.get(filepath)); // count++; // } // } // // @Override // public <T> T getClasspathScript(int scriptId) { // return (T) idsToScripts.get(scriptId); // } // // @Override // public int getScriptId(String filepath) { // return scriptFilepathsToIds.get(filepath); // } // // @Override // public int getTotalScripts() { // return scriptFilepathsToIds.size(); // } // // @Override // public Set<String> getFilepaths() { // return scriptFilepathsToIds.keySet(); // } // // @Override // public String getFilepath(int scriptId) { // return scriptIdsToFilepaths.get(scriptId); // } // // public abstract Map getGeneratedScripts(); // }
import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.JavaFile; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.TypeSpec; import org.mini2Dx.miniscript.core.GeneratedClasspathScriptProvider; import javax.lang.model.element.Modifier;
.build(); javaFile.writeTo(outputDir); } private void generateScriptProvider(List<CompilerInputFile> inputFiles) throws IOException { final String outputClassName = outputClass.get().substring(outputClass.get().lastIndexOf('.') + 1); MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("getGeneratedScripts") .addModifiers(Modifier.PUBLIC) .returns(Map.class) .addStatement("final $T result = new $T()", Map.class, HashMap.class); for(CompilerInputFile inputFile : inputFiles) { final String scriptPackage = inputFile.getOutputPackageName(outputPackage); final ClassName scriptClassName = ClassName.get(scriptPackage, inputFile.getOutputClassName()); final String path; if(getPrefixWithRoot().getOrElse(false)) { path = scriptsDir.get().getAsFile().getName() + "/" + inputFile.getInputScriptRelativeFilename().replace('\\', '/'); } else { path = inputFile.getInputScriptRelativeFilename().replace('\\', '/'); } methodBuilder = methodBuilder.addStatement("result.put($S, new $T())", path, scriptClassName); } methodBuilder = methodBuilder.addStatement("return result"); final MethodSpec methodSpec = methodBuilder.build(); final TypeSpec classSpec = TypeSpec.classBuilder(outputClassName) .addModifiers(Modifier.PUBLIC)
// Path: core/src/main/java/org/mini2Dx/miniscript/core/GeneratedClasspathScriptProvider.java // public abstract class GeneratedClasspathScriptProvider implements ClasspathScriptProvider { // private final Map<String, Integer> scriptFilepathsToIds = new HashMap<String, Integer>(); // private final Map<Integer, String> scriptIdsToFilepaths = new HashMap<Integer, String>(); // private final Map<Integer, Object> idsToScripts = new HashMap<Integer, Object>(); // // public GeneratedClasspathScriptProvider() { // super(); // // final Map<String, Object> generatedScripts = getGeneratedScripts(); // // int count = 0; // for(String filepath : generatedScripts.keySet()) { // scriptFilepathsToIds.put(filepath, count); // scriptIdsToFilepaths.put(count, filepath); // idsToScripts.put(count, generatedScripts.get(filepath)); // count++; // } // } // // @Override // public <T> T getClasspathScript(int scriptId) { // return (T) idsToScripts.get(scriptId); // } // // @Override // public int getScriptId(String filepath) { // return scriptFilepathsToIds.get(filepath); // } // // @Override // public int getTotalScripts() { // return scriptFilepathsToIds.size(); // } // // @Override // public Set<String> getFilepaths() { // return scriptFilepathsToIds.keySet(); // } // // @Override // public String getFilepath(int scriptId) { // return scriptIdsToFilepaths.get(scriptId); // } // // public abstract Map getGeneratedScripts(); // } // Path: gradle-plugin/src/main/java/org/mini2Dx/miniscript/gradle/MiniscriptStubTask.java import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.JavaFile; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.TypeSpec; import org.mini2Dx.miniscript.core.GeneratedClasspathScriptProvider; import javax.lang.model.element.Modifier; .build(); javaFile.writeTo(outputDir); } private void generateScriptProvider(List<CompilerInputFile> inputFiles) throws IOException { final String outputClassName = outputClass.get().substring(outputClass.get().lastIndexOf('.') + 1); MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("getGeneratedScripts") .addModifiers(Modifier.PUBLIC) .returns(Map.class) .addStatement("final $T result = new $T()", Map.class, HashMap.class); for(CompilerInputFile inputFile : inputFiles) { final String scriptPackage = inputFile.getOutputPackageName(outputPackage); final ClassName scriptClassName = ClassName.get(scriptPackage, inputFile.getOutputClassName()); final String path; if(getPrefixWithRoot().getOrElse(false)) { path = scriptsDir.get().getAsFile().getName() + "/" + inputFile.getInputScriptRelativeFilename().replace('\\', '/'); } else { path = inputFile.getInputScriptRelativeFilename().replace('\\', '/'); } methodBuilder = methodBuilder.addStatement("result.put($S, new $T())", path, scriptClassName); } methodBuilder = methodBuilder.addStatement("return result"); final MethodSpec methodSpec = methodBuilder.build(); final TypeSpec classSpec = TypeSpec.classBuilder(outputClassName) .addModifiers(Modifier.PUBLIC)
.superclass(GeneratedClasspathScriptProvider.class)
mini2Dx/miniscript
ruby/src/main/java/org/mini2Dx/miniscript/ruby/RubyScriptExecutor.java
// Path: core/src/main/java/org/mini2Dx/miniscript/core/exception/ScriptSkippedException.java // public class ScriptSkippedException extends RuntimeException { // private static final long serialVersionUID = -7901574884568506426L; // // }
import org.jruby.embed.EmbedEvalUnit; import org.jruby.embed.ScriptingContainer; import org.mini2Dx.miniscript.core.*; import org.mini2Dx.miniscript.core.exception.ScriptSkippedException;
/** * The MIT License (MIT) * * Copyright (c) 2016 Thomas Cashman * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.mini2Dx.miniscript.ruby; /** * An implementation of {@link ScriptExecutor} for Ruby-based scripts */ public class RubyScriptExecutor implements ScriptExecutor<EmbedEvalUnit> { private final RubyScriptExecutorPool executorPool; public RubyScriptExecutor(RubyScriptExecutorPool executorPool) { this.executorPool = executorPool; } @Override public GameScript<EmbedEvalUnit> compile(String script) { return new PerThreadGameScript<EmbedEvalUnit>(script); } @Override public ScriptExecutionResult execute(int scriptId, GameScript<EmbedEvalUnit> s, ScriptBindings bindings, boolean returnResult) throws Exception { final PerThreadGameScript<EmbedEvalUnit> script = (PerThreadGameScript<EmbedEvalUnit>) s; final ScriptingContainer scriptingContainer = executorPool.getLocalScriptingContainer(); final RubyEmbeddedScriptInvoker embeddedScriptInvoker = executorPool.getEmbeddedScriptInvokerPool().allocate(); embeddedScriptInvoker.setScriptBindings(bindings); embeddedScriptInvoker.setScriptExecutor(this); embeddedScriptInvoker.setParentScriptId(scriptId); scriptingContainer.getVarMap().putAll(bindings); scriptingContainer.getVarMap().put(ScriptBindings.SCRIPT_PARENT_ID_VAR, -1); scriptingContainer.getVarMap().put(ScriptBindings.SCRIPT_ID_VAR, scriptId); scriptingContainer.getVarMap().put(ScriptBindings.SCRIPT_INVOKE_VAR, embeddedScriptInvoker); if (!script.hasScript()) { script.setScript(scriptingContainer.parse(script.getContent())); } try { EmbedEvalUnit embedEvalUnit = script.getScript(); embedEvalUnit.run(); } catch (Exception e) {
// Path: core/src/main/java/org/mini2Dx/miniscript/core/exception/ScriptSkippedException.java // public class ScriptSkippedException extends RuntimeException { // private static final long serialVersionUID = -7901574884568506426L; // // } // Path: ruby/src/main/java/org/mini2Dx/miniscript/ruby/RubyScriptExecutor.java import org.jruby.embed.EmbedEvalUnit; import org.jruby.embed.ScriptingContainer; import org.mini2Dx.miniscript.core.*; import org.mini2Dx.miniscript.core.exception.ScriptSkippedException; /** * The MIT License (MIT) * * Copyright (c) 2016 Thomas Cashman * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.mini2Dx.miniscript.ruby; /** * An implementation of {@link ScriptExecutor} for Ruby-based scripts */ public class RubyScriptExecutor implements ScriptExecutor<EmbedEvalUnit> { private final RubyScriptExecutorPool executorPool; public RubyScriptExecutor(RubyScriptExecutorPool executorPool) { this.executorPool = executorPool; } @Override public GameScript<EmbedEvalUnit> compile(String script) { return new PerThreadGameScript<EmbedEvalUnit>(script); } @Override public ScriptExecutionResult execute(int scriptId, GameScript<EmbedEvalUnit> s, ScriptBindings bindings, boolean returnResult) throws Exception { final PerThreadGameScript<EmbedEvalUnit> script = (PerThreadGameScript<EmbedEvalUnit>) s; final ScriptingContainer scriptingContainer = executorPool.getLocalScriptingContainer(); final RubyEmbeddedScriptInvoker embeddedScriptInvoker = executorPool.getEmbeddedScriptInvokerPool().allocate(); embeddedScriptInvoker.setScriptBindings(bindings); embeddedScriptInvoker.setScriptExecutor(this); embeddedScriptInvoker.setParentScriptId(scriptId); scriptingContainer.getVarMap().putAll(bindings); scriptingContainer.getVarMap().put(ScriptBindings.SCRIPT_PARENT_ID_VAR, -1); scriptingContainer.getVarMap().put(ScriptBindings.SCRIPT_ID_VAR, scriptId); scriptingContainer.getVarMap().put(ScriptBindings.SCRIPT_INVOKE_VAR, embeddedScriptInvoker); if (!script.hasScript()) { script.setScript(scriptingContainer.parse(script.getContent())); } try { EmbedEvalUnit embedEvalUnit = script.getScript(); embedEvalUnit.run(); } catch (Exception e) {
if(e instanceof ScriptSkippedException || e.getCause() instanceof ScriptSkippedException) {
mini2Dx/miniscript
core/src/main/java/org/mini2Dx/miniscript/core/GameFuture.java
// Path: core/src/main/java/org/mini2Dx/miniscript/core/exception/ScriptSkippedException.java // public class ScriptSkippedException extends RuntimeException { // private static final long serialVersionUID = -7901574884568506426L; // // }
import org.mini2Dx.miniscript.core.exception.ScriptSkippedException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger;
/** * The MIT License (MIT) * * Copyright (c) 2016 Thomas Cashman * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.mini2Dx.miniscript.core; /** * Represents a task that will complete in-game at a future time */ public abstract class GameFuture { private static final AtomicInteger ID_GENERATOR = new AtomicInteger(0); private static final int STATE_NONE = 0; private static final int STATE_FUTURE_SKIPPED = 1; private static final int STATE_FUTURE_SKIPPED_GC_READY = STATE_FUTURE_SKIPPED * 10; private static final int STATE_SCRIPT_SKIPPED = 2; private static final int STATE_SCRIPT_SKIPPED_GC_READY = STATE_SCRIPT_SKIPPED * 10; private static final int STATE_COMPLETED = 3; private static final int STATE_COMPLETED_GC_READY = STATE_COMPLETED * 10; private final int futureId; private final AtomicInteger state = new AtomicInteger(STATE_NONE); /** * Constructor using {@link GameScriptingEngine#MOST_RECENT_INSTANCE} */ public GameFuture() { this(GameScriptingEngine.MOST_RECENT_INSTANCE); } /** * Constructor * * @param gameScriptingEngine * The {@link GameScriptingEngine} this future belongs to */ public GameFuture(GameScriptingEngine gameScriptingEngine) { if(gameScriptingEngine == null) { throw new RuntimeException("Cannot pass null scripting engine to " + GameFuture.class.getSimpleName()); } futureId = ID_GENERATOR.incrementAndGet(); gameScriptingEngine.submitGameFuture(this); if (Thread.interrupted()) { state.compareAndSet(STATE_NONE, STATE_SCRIPT_SKIPPED);
// Path: core/src/main/java/org/mini2Dx/miniscript/core/exception/ScriptSkippedException.java // public class ScriptSkippedException extends RuntimeException { // private static final long serialVersionUID = -7901574884568506426L; // // } // Path: core/src/main/java/org/mini2Dx/miniscript/core/GameFuture.java import org.mini2Dx.miniscript.core.exception.ScriptSkippedException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; /** * The MIT License (MIT) * * Copyright (c) 2016 Thomas Cashman * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.mini2Dx.miniscript.core; /** * Represents a task that will complete in-game at a future time */ public abstract class GameFuture { private static final AtomicInteger ID_GENERATOR = new AtomicInteger(0); private static final int STATE_NONE = 0; private static final int STATE_FUTURE_SKIPPED = 1; private static final int STATE_FUTURE_SKIPPED_GC_READY = STATE_FUTURE_SKIPPED * 10; private static final int STATE_SCRIPT_SKIPPED = 2; private static final int STATE_SCRIPT_SKIPPED_GC_READY = STATE_SCRIPT_SKIPPED * 10; private static final int STATE_COMPLETED = 3; private static final int STATE_COMPLETED_GC_READY = STATE_COMPLETED * 10; private final int futureId; private final AtomicInteger state = new AtomicInteger(STATE_NONE); /** * Constructor using {@link GameScriptingEngine#MOST_RECENT_INSTANCE} */ public GameFuture() { this(GameScriptingEngine.MOST_RECENT_INSTANCE); } /** * Constructor * * @param gameScriptingEngine * The {@link GameScriptingEngine} this future belongs to */ public GameFuture(GameScriptingEngine gameScriptingEngine) { if(gameScriptingEngine == null) { throw new RuntimeException("Cannot pass null scripting engine to " + GameFuture.class.getSimpleName()); } futureId = ID_GENERATOR.incrementAndGet(); gameScriptingEngine.submitGameFuture(this); if (Thread.interrupted()) { state.compareAndSet(STATE_NONE, STATE_SCRIPT_SKIPPED);
throw new ScriptSkippedException();
mini2Dx/miniscript
kotlin/src/main/java/org/mini2Dx/miniscript/kotlin/KotlinScriptExecutor.java
// Path: core/src/main/java/org/mini2Dx/miniscript/core/exception/ScriptSkippedException.java // public class ScriptSkippedException extends RuntimeException { // private static final long serialVersionUID = -7901574884568506426L; // // }
import org.jetbrains.kotlin.cli.common.repl.KotlinJsr223JvmScriptEngineBase.CompiledKotlinScript; import org.jetbrains.kotlin.ir.expressions.IrConstKind.Char; import org.jetbrains.kotlin.script.jsr223.KotlinJsr223JvmLocalScriptEngine; import org.jetbrains.kotlin.script.jsr223.KotlinJsr223JvmLocalScriptEngineFactory; import org.jetbrains.kotlin.util.KotlinFrontEndException; import org.mini2Dx.miniscript.core.*; import org.mini2Dx.miniscript.core.exception.ScriptSkippedException;
/** * The MIT License (MIT) * * Copyright (c) 2017 Thomas Cashman * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.mini2Dx.miniscript.kotlin; /** * An implementation of {@link ScriptExecutor} for Kotlin-based scripts */ public class KotlinScriptExecutor implements ScriptExecutor<CompiledKotlinScript> { private final KotlinScriptExecutorPool executorPool; private final KotlinJsr223JvmLocalScriptEngine engine; public KotlinScriptExecutor(KotlinScriptExecutorPool executorPool) { this.executorPool = executorPool; engine = (KotlinJsr223JvmLocalScriptEngine) new KotlinJsr223JvmLocalScriptEngineFactory().getScriptEngine(); } @Override public GameScript<CompiledKotlinScript> compile(String script) { return new PerThreadGameScript<>(script); } @Override public ScriptExecutionResult execute(int scriptId, GameScript<CompiledKotlinScript> script, ScriptBindings bindings, boolean returnResult) throws Exception { final PerThreadGameScript<CompiledKotlinScript> threadScript = (PerThreadGameScript<CompiledKotlinScript>) script; final KotlinEmbeddedScriptInvoker embeddedScriptInvoker = executorPool.getEmbeddedScriptInvokerPool().allocate(); embeddedScriptInvoker.setScriptBindings(bindings); embeddedScriptInvoker.setScriptExecutor(this); embeddedScriptInvoker.setParentScriptId(scriptId); for (String variableName : bindings.keySet()) { engine.put(variableName, bindings.get(variableName)); } engine.put(ScriptBindings.SCRIPT_PARENT_ID_VAR, -1); engine.put(ScriptBindings.SCRIPT_ID_VAR, scriptId); engine.put(ScriptBindings.SCRIPT_INVOKE_VAR, embeddedScriptInvoker); try { engine.eval(threadScript.getContent()); } catch (Exception e) {
// Path: core/src/main/java/org/mini2Dx/miniscript/core/exception/ScriptSkippedException.java // public class ScriptSkippedException extends RuntimeException { // private static final long serialVersionUID = -7901574884568506426L; // // } // Path: kotlin/src/main/java/org/mini2Dx/miniscript/kotlin/KotlinScriptExecutor.java import org.jetbrains.kotlin.cli.common.repl.KotlinJsr223JvmScriptEngineBase.CompiledKotlinScript; import org.jetbrains.kotlin.ir.expressions.IrConstKind.Char; import org.jetbrains.kotlin.script.jsr223.KotlinJsr223JvmLocalScriptEngine; import org.jetbrains.kotlin.script.jsr223.KotlinJsr223JvmLocalScriptEngineFactory; import org.jetbrains.kotlin.util.KotlinFrontEndException; import org.mini2Dx.miniscript.core.*; import org.mini2Dx.miniscript.core.exception.ScriptSkippedException; /** * The MIT License (MIT) * * Copyright (c) 2017 Thomas Cashman * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.mini2Dx.miniscript.kotlin; /** * An implementation of {@link ScriptExecutor} for Kotlin-based scripts */ public class KotlinScriptExecutor implements ScriptExecutor<CompiledKotlinScript> { private final KotlinScriptExecutorPool executorPool; private final KotlinJsr223JvmLocalScriptEngine engine; public KotlinScriptExecutor(KotlinScriptExecutorPool executorPool) { this.executorPool = executorPool; engine = (KotlinJsr223JvmLocalScriptEngine) new KotlinJsr223JvmLocalScriptEngineFactory().getScriptEngine(); } @Override public GameScript<CompiledKotlinScript> compile(String script) { return new PerThreadGameScript<>(script); } @Override public ScriptExecutionResult execute(int scriptId, GameScript<CompiledKotlinScript> script, ScriptBindings bindings, boolean returnResult) throws Exception { final PerThreadGameScript<CompiledKotlinScript> threadScript = (PerThreadGameScript<CompiledKotlinScript>) script; final KotlinEmbeddedScriptInvoker embeddedScriptInvoker = executorPool.getEmbeddedScriptInvokerPool().allocate(); embeddedScriptInvoker.setScriptBindings(bindings); embeddedScriptInvoker.setScriptExecutor(this); embeddedScriptInvoker.setParentScriptId(scriptId); for (String variableName : bindings.keySet()) { engine.put(variableName, bindings.get(variableName)); } engine.put(ScriptBindings.SCRIPT_PARENT_ID_VAR, -1); engine.put(ScriptBindings.SCRIPT_ID_VAR, scriptId); engine.put(ScriptBindings.SCRIPT_INVOKE_VAR, embeddedScriptInvoker); try { engine.eval(threadScript.getContent()); } catch (Exception e) {
if(e.getMessage().contains(ScriptSkippedException.class.getName())) {
IPEldorado/RemoteResources
src/com/eldorado/remoteresources/ui/wizard/IWizardPage.java
// Path: src/com/eldorado/remoteresources/ui/wizard/IWizard.java // public enum WizardStatus { // OK, INFO, WARNING, ERROR // };
import java.util.List; import javax.swing.SwingWorker; import com.eldorado.remoteresources.ui.wizard.IWizard.WizardStatus;
/* * (C) Copyright 2014 Instituto de Pesquisas Eldorado (http://www.eldorado.org.br/). * * This file is part of the software Remote Resources * * All rights reserved. This file and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 3.0 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * This file is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ package com.eldorado.remoteresources.ui.wizard; /** * This interface defines a minimum wizard page * * @author Marcelo Marzola Bossoni * */ public interface IWizardPage { public boolean hasNextPage(); public boolean hasPreviousPage(); public boolean isPageValid(); public void setNextPage(IWizardPage page); public IWizardPage getNextPage(); public void setPreviousPage(IWizardPage page); public IWizardPage getPreviousPage(); public String getDescription(); public void setDescription(String description); public void setErrorMessage(String errorMessage); public String getErrorMessage();
// Path: src/com/eldorado/remoteresources/ui/wizard/IWizard.java // public enum WizardStatus { // OK, INFO, WARNING, ERROR // }; // Path: src/com/eldorado/remoteresources/ui/wizard/IWizardPage.java import java.util.List; import javax.swing.SwingWorker; import com.eldorado.remoteresources.ui.wizard.IWizard.WizardStatus; /* * (C) Copyright 2014 Instituto de Pesquisas Eldorado (http://www.eldorado.org.br/). * * This file is part of the software Remote Resources * * All rights reserved. This file and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 3.0 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * This file is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ package com.eldorado.remoteresources.ui.wizard; /** * This interface defines a minimum wizard page * * @author Marcelo Marzola Bossoni * */ public interface IWizardPage { public boolean hasNextPage(); public boolean hasPreviousPage(); public boolean isPageValid(); public void setNextPage(IWizardPage page); public IWizardPage getNextPage(); public void setPreviousPage(IWizardPage page); public IWizardPage getPreviousPage(); public String getDescription(); public void setDescription(String description); public void setErrorMessage(String errorMessage); public String getErrorMessage();
public void setErrorLevel(WizardStatus level);
IPEldorado/RemoteResources
src/com/eldorado/remoteresources/android/common/connection/messages/control/ControlRebootMessage.java
// Path: src/com/eldorado/remoteresources/utils/SubType.java // public enum SubType { // NONE, PULL, PUSH, INSTALL, UNINSTALL // }
import com.eldorado.remoteresources.utils.SubType;
/* * (C) Copyright 2014 Instituto de Pesquisas Eldorado (http://www.eldorado.org.br/). * * This file is part of the software Remote Resources * * All rights reserved. This file and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 3.0 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * This file is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ package com.eldorado.remoteresources.android.common.connection.messages.control; /** * Message with informations to handle files (pull/push/delete) * * @author Rafael Dias Santos * */ public class ControlRebootMessage extends CommandMessage { private static final long serialVersionUID = 5481207318846024671L; public ControlRebootMessage(int sequenceNumber, String serialNumber,
// Path: src/com/eldorado/remoteresources/utils/SubType.java // public enum SubType { // NONE, PULL, PUSH, INSTALL, UNINSTALL // } // Path: src/com/eldorado/remoteresources/android/common/connection/messages/control/ControlRebootMessage.java import com.eldorado.remoteresources.utils.SubType; /* * (C) Copyright 2014 Instituto de Pesquisas Eldorado (http://www.eldorado.org.br/). * * This file is part of the software Remote Resources * * All rights reserved. This file and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 3.0 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * This file is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ package com.eldorado.remoteresources.android.common.connection.messages.control; /** * Message with informations to handle files (pull/push/delete) * * @author Rafael Dias Santos * */ public class ControlRebootMessage extends CommandMessage { private static final long serialVersionUID = 5481207318846024671L; public ControlRebootMessage(int sequenceNumber, String serialNumber,
SubType subType, String[] params) {
IPEldorado/RemoteResources
src/com/eldorado/remoteresources/android/common/connection/messages/control/ControlPackageHandlingMessage.java
// Path: src/com/eldorado/remoteresources/utils/SubType.java // public enum SubType { // NONE, PULL, PUSH, INSTALL, UNINSTALL // }
import com.eldorado.remoteresources.utils.SubType;
/* * (C) Copyright 2014 Instituto de Pesquisas Eldorado (http://www.eldorado.org.br/). * * This file is part of the software Remote Resources * * All rights reserved. This file and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 3.0 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * This file is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ package com.eldorado.remoteresources.android.common.connection.messages.control; /** * Message with informations to handle files (pull/push/delete) * * @author Rafael Dias Santos * */ public class ControlPackageHandlingMessage extends CommandMessage { private static final long serialVersionUID = 5481207318846024671L; public ControlPackageHandlingMessage(int sequenceNumber,
// Path: src/com/eldorado/remoteresources/utils/SubType.java // public enum SubType { // NONE, PULL, PUSH, INSTALL, UNINSTALL // } // Path: src/com/eldorado/remoteresources/android/common/connection/messages/control/ControlPackageHandlingMessage.java import com.eldorado.remoteresources.utils.SubType; /* * (C) Copyright 2014 Instituto de Pesquisas Eldorado (http://www.eldorado.org.br/). * * This file is part of the software Remote Resources * * All rights reserved. This file and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 3.0 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * This file is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ package com.eldorado.remoteresources.android.common.connection.messages.control; /** * Message with informations to handle files (pull/push/delete) * * @author Rafael Dias Santos * */ public class ControlPackageHandlingMessage extends CommandMessage { private static final long serialVersionUID = 5481207318846024671L; public ControlPackageHandlingMessage(int sequenceNumber,
String serialNumber, SubType subType, String[] params) {
IPEldorado/RemoteResources
src/com/eldorado/remoteresources/android/server/AndroidDevice.java
// Path: src/com/eldorado/remoteresources/android/common/Keys.java // public enum Keys { // /** */ // HOME, // /** */ // BACK, // /** */ // VOLUME_UP, // /** */ // VOLUME_DOWN, // /** */ // POWER, // /** */ // CAMERA, // /** */ // CLEAR, // /** */ // DEL, // /** */ // FOCUS, // /** */ // MENU, // /** */ // SEARCH; // // @Override // public String toString() { // return "KEYCODE_" + super.toString(); // } // } // // Path: src/com/eldorado/remoteresources/utils/StringUtils.java // public class StringUtils { // /** // * // * @param str // * @return // */ // public static boolean isEmpty(String str) { // if (str == null) { // return true; // } // // return str.isEmpty(); // } // // public static byte[] compress(String log) throws IOException { // ByteArrayOutputStream xzOutput = new ByteArrayOutputStream(); // XZOutputStream xzStream = new XZOutputStream(xzOutput, // new LZMA2Options(LZMA2Options.PRESET_MAX)); // xzStream.write(log.getBytes()); // xzStream.close(); // return xzOutput.toByteArray(); // } // // public static String decompress(byte[] log) throws IOException { // XZInputStream xzInputStream = new XZInputStream( // new ByteArrayInputStream(log)); // byte firstByte = (byte) xzInputStream.read(); // byte[] buffer = new byte[xzInputStream.available()]; // buffer[0] = firstByte; // xzInputStream.read(buffer, 1, buffer.length - 2); // xzInputStream.close(); // return new String(buffer); // } // // }
import java.awt.Dimension; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.StringTokenizer; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.android.chimpchat.adb.AdbChimpDevice; import com.android.chimpchat.core.TouchPressType; import com.android.ddmlib.IDevice; import com.eldorado.remoteresources.android.common.Keys; import com.eldorado.remoteresources.utils.StringUtils;
/* * (C) Copyright 2014 Instituto de Pesquisas Eldorado (http://www.eldorado.org.br/). * * This file is part of the software Remote Resources * * All rights reserved. This file and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 3.0 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * This file is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ package com.eldorado.remoteresources.android.server; /** * * * */ public class AndroidDevice { /** * */ private IDevice device; /** * */ private AdbChimpDevice chimpDevice; /** * */ private final String serialNumber; /** * */ private String deviceModel; /** * */ private Dimension screenSize; /** * */ private static final String KEYCODE_SPACE = String.valueOf(62); /** * */ private static final Pattern[] DISPLAY_SIZE_PATTERNS = { Pattern.compile("\\scur=(?<width>\\d+)x(?<height>\\d+)\\s", Pattern.CASE_INSENSITIVE), Pattern.compile( "displaywidth\\s*\\=\\s*(?<width>\\d+).*displayheight\\s*\\=\\s*(?<height>\\d+)", Pattern.CASE_INSENSITIVE) }; /** * * @param device */ public AndroidDevice(IDevice device) { this.device = device; serialNumber = device.getSerialNumber(); chimpDevice = new AdbChimpDevice(device); getScreenSize(); } public IDevice getDevice() { return device; } public void setDevice(IDevice device) { this.device = device; } /** * * @return */ public String getDeviceModel() {
// Path: src/com/eldorado/remoteresources/android/common/Keys.java // public enum Keys { // /** */ // HOME, // /** */ // BACK, // /** */ // VOLUME_UP, // /** */ // VOLUME_DOWN, // /** */ // POWER, // /** */ // CAMERA, // /** */ // CLEAR, // /** */ // DEL, // /** */ // FOCUS, // /** */ // MENU, // /** */ // SEARCH; // // @Override // public String toString() { // return "KEYCODE_" + super.toString(); // } // } // // Path: src/com/eldorado/remoteresources/utils/StringUtils.java // public class StringUtils { // /** // * // * @param str // * @return // */ // public static boolean isEmpty(String str) { // if (str == null) { // return true; // } // // return str.isEmpty(); // } // // public static byte[] compress(String log) throws IOException { // ByteArrayOutputStream xzOutput = new ByteArrayOutputStream(); // XZOutputStream xzStream = new XZOutputStream(xzOutput, // new LZMA2Options(LZMA2Options.PRESET_MAX)); // xzStream.write(log.getBytes()); // xzStream.close(); // return xzOutput.toByteArray(); // } // // public static String decompress(byte[] log) throws IOException { // XZInputStream xzInputStream = new XZInputStream( // new ByteArrayInputStream(log)); // byte firstByte = (byte) xzInputStream.read(); // byte[] buffer = new byte[xzInputStream.available()]; // buffer[0] = firstByte; // xzInputStream.read(buffer, 1, buffer.length - 2); // xzInputStream.close(); // return new String(buffer); // } // // } // Path: src/com/eldorado/remoteresources/android/server/AndroidDevice.java import java.awt.Dimension; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.StringTokenizer; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.android.chimpchat.adb.AdbChimpDevice; import com.android.chimpchat.core.TouchPressType; import com.android.ddmlib.IDevice; import com.eldorado.remoteresources.android.common.Keys; import com.eldorado.remoteresources.utils.StringUtils; /* * (C) Copyright 2014 Instituto de Pesquisas Eldorado (http://www.eldorado.org.br/). * * This file is part of the software Remote Resources * * All rights reserved. This file and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 3.0 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * This file is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ package com.eldorado.remoteresources.android.server; /** * * * */ public class AndroidDevice { /** * */ private IDevice device; /** * */ private AdbChimpDevice chimpDevice; /** * */ private final String serialNumber; /** * */ private String deviceModel; /** * */ private Dimension screenSize; /** * */ private static final String KEYCODE_SPACE = String.valueOf(62); /** * */ private static final Pattern[] DISPLAY_SIZE_PATTERNS = { Pattern.compile("\\scur=(?<width>\\d+)x(?<height>\\d+)\\s", Pattern.CASE_INSENSITIVE), Pattern.compile( "displaywidth\\s*\\=\\s*(?<width>\\d+).*displayheight\\s*\\=\\s*(?<height>\\d+)", Pattern.CASE_INSENSITIVE) }; /** * * @param device */ public AndroidDevice(IDevice device) { this.device = device; serialNumber = device.getSerialNumber(); chimpDevice = new AdbChimpDevice(device); getScreenSize(); } public IDevice getDevice() { return device; } public void setDevice(IDevice device) { this.device = device; } /** * * @return */ public String getDeviceModel() {
if (StringUtils.isEmpty(deviceModel)) {
IPEldorado/RemoteResources
src/com/eldorado/remoteresources/android/server/AndroidDevice.java
// Path: src/com/eldorado/remoteresources/android/common/Keys.java // public enum Keys { // /** */ // HOME, // /** */ // BACK, // /** */ // VOLUME_UP, // /** */ // VOLUME_DOWN, // /** */ // POWER, // /** */ // CAMERA, // /** */ // CLEAR, // /** */ // DEL, // /** */ // FOCUS, // /** */ // MENU, // /** */ // SEARCH; // // @Override // public String toString() { // return "KEYCODE_" + super.toString(); // } // } // // Path: src/com/eldorado/remoteresources/utils/StringUtils.java // public class StringUtils { // /** // * // * @param str // * @return // */ // public static boolean isEmpty(String str) { // if (str == null) { // return true; // } // // return str.isEmpty(); // } // // public static byte[] compress(String log) throws IOException { // ByteArrayOutputStream xzOutput = new ByteArrayOutputStream(); // XZOutputStream xzStream = new XZOutputStream(xzOutput, // new LZMA2Options(LZMA2Options.PRESET_MAX)); // xzStream.write(log.getBytes()); // xzStream.close(); // return xzOutput.toByteArray(); // } // // public static String decompress(byte[] log) throws IOException { // XZInputStream xzInputStream = new XZInputStream( // new ByteArrayInputStream(log)); // byte firstByte = (byte) xzInputStream.read(); // byte[] buffer = new byte[xzInputStream.available()]; // buffer[0] = firstByte; // xzInputStream.read(buffer, 1, buffer.length - 2); // xzInputStream.close(); // return new String(buffer); // } // // }
import java.awt.Dimension; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.StringTokenizer; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.android.chimpchat.adb.AdbChimpDevice; import com.android.chimpchat.core.TouchPressType; import com.android.ddmlib.IDevice; import com.eldorado.remoteresources.android.common.Keys; import com.eldorado.remoteresources.utils.StringUtils;
chimpDevice.getManager().quit(); device = null; chimpDevice = null; } catch (Exception e) { // TODO: handle exception } } @Override public boolean equals(Object obj) { return obj instanceof AndroidDevice ? ((AndroidDevice) obj) .getSerialNumber().equalsIgnoreCase(serialNumber) : false; } /** * * @param key * @param pressType */ private void pressKey(String key, TouchPressType pressType) { if (isOnline()) { chimpDevice.press(key, pressType); } } /** * * @param key */
// Path: src/com/eldorado/remoteresources/android/common/Keys.java // public enum Keys { // /** */ // HOME, // /** */ // BACK, // /** */ // VOLUME_UP, // /** */ // VOLUME_DOWN, // /** */ // POWER, // /** */ // CAMERA, // /** */ // CLEAR, // /** */ // DEL, // /** */ // FOCUS, // /** */ // MENU, // /** */ // SEARCH; // // @Override // public String toString() { // return "KEYCODE_" + super.toString(); // } // } // // Path: src/com/eldorado/remoteresources/utils/StringUtils.java // public class StringUtils { // /** // * // * @param str // * @return // */ // public static boolean isEmpty(String str) { // if (str == null) { // return true; // } // // return str.isEmpty(); // } // // public static byte[] compress(String log) throws IOException { // ByteArrayOutputStream xzOutput = new ByteArrayOutputStream(); // XZOutputStream xzStream = new XZOutputStream(xzOutput, // new LZMA2Options(LZMA2Options.PRESET_MAX)); // xzStream.write(log.getBytes()); // xzStream.close(); // return xzOutput.toByteArray(); // } // // public static String decompress(byte[] log) throws IOException { // XZInputStream xzInputStream = new XZInputStream( // new ByteArrayInputStream(log)); // byte firstByte = (byte) xzInputStream.read(); // byte[] buffer = new byte[xzInputStream.available()]; // buffer[0] = firstByte; // xzInputStream.read(buffer, 1, buffer.length - 2); // xzInputStream.close(); // return new String(buffer); // } // // } // Path: src/com/eldorado/remoteresources/android/server/AndroidDevice.java import java.awt.Dimension; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.StringTokenizer; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.android.chimpchat.adb.AdbChimpDevice; import com.android.chimpchat.core.TouchPressType; import com.android.ddmlib.IDevice; import com.eldorado.remoteresources.android.common.Keys; import com.eldorado.remoteresources.utils.StringUtils; chimpDevice.getManager().quit(); device = null; chimpDevice = null; } catch (Exception e) { // TODO: handle exception } } @Override public boolean equals(Object obj) { return obj instanceof AndroidDevice ? ((AndroidDevice) obj) .getSerialNumber().equalsIgnoreCase(serialNumber) : false; } /** * * @param key * @param pressType */ private void pressKey(String key, TouchPressType pressType) { if (isOnline()) { chimpDevice.press(key, pressType); } } /** * * @param key */
public void keyDown(Keys key) {
IPEldorado/RemoteResources
src/com/eldorado/remoteresources/UpdateScriptFile.java
// Path: src/com/eldorado/remoteresources/ui/actions/ClientManipulationScript.java // public class ClientManipulationScript { // // private static final String DEFAULT_CLIENT_SCRIPT_DIR = RemoteResourcesConfiguration // .getRemoteResourcesDir() != null ? RemoteResourcesConfiguration // .getRemoteResourcesDir() + File.separator + "scripts" : System //$NON-NLS-1$ // .getProperty("user.home"); // // private static final String CLIENT_SCRIPT_FILENAME_EXTENSION = ".txt"; //$NON-NLS-1$ // // private static String outputFile = null; // private BufferedWriter out; // // private static String serialNumber; // private static String host; // private static String port; // // public boolean playGenerateScriptFile(String device, String host, // String port, String path, String name) { // // serialNumber = device; // ClientManipulationScript.host = host; // ClientManipulationScript.port = port; // // File fOutputDir = new File(path); // // if (!fOutputDir.exists()) { // fOutputDir.mkdirs(); // } // // outputFile = path + File.separator + name; // // File f = new File(outputFile); // if (!f.exists()) { // try { // out = new BufferedWriter(new FileWriter(outputFile)); // return true; // } catch (IOException e) { // e.printStackTrace(); // } // } // return false; // } // // public void stopGenerateScriptFile(Vector<String> actions) { // Iterator<String> it = actions.iterator(); // // try { // out.write(serialNumber); // out.newLine(); // while (it.hasNext()) { // System.out.println(); // out.write(it.next().toString()); // out.newLine(); // } // out.close(); // Script.clean(); // } catch (IOException e) { // // } // } // // public void createScriptFile(String device, String host, String port, // String path, String name, Vector<String> actions) { // if (playGenerateScriptFile(device, host, port, path, name)) { // stopGenerateScriptFile(actions); // } // Script.clean(); // } // // // ================== READ A SCRIPT ================== // public Vector<String> readScriptFile(File f) { // Vector<String> actions = null; // BufferedReader reader = null; // try { // if (f.canRead()) { // actions = new Vector<String>(); // reader = new BufferedReader(new FileReader(f)); // String line = reader.readLine(); // // while (line != null) { // actions.add(line); // line = reader.readLine(); // } // } // } catch (FileNotFoundException e) { // } catch (IOException e) { // } finally { // if (reader != null) { // try { // reader.close(); // } catch (IOException e) { // // do nothing // } // } // } // // return actions; // } // // // ================== UPDATE SCRIPT ================== // public void updateScriptFile(File f, Vector<String> actions) { // // BufferedWriter writer = null; // Iterator it = actions.iterator(); // // try { // if (f.canRead() && !it.equals(null)) { // writer = new BufferedWriter(new PrintWriter(new FileWriter(f))); // while (it.hasNext()) { // writer.write(it.next().toString()); // writer.newLine(); // } // } // // writer.close(); // } catch (FileNotFoundException e) { // } catch (IOException e) { // } finally { // if (writer != null) { // try { // writer.close(); // } catch (IOException e) { // // do nothing // } // } // } // // } // }
import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.File; import java.util.Iterator; import java.util.Vector; import javax.swing.AbstractButton; import javax.swing.ButtonGroup; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JRadioButton; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.ScrollPaneConstants; import com.eldorado.remoteresources.ui.actions.ClientManipulationScript;
/* * (C) Copyright 2014 Instituto de Pesquisas Eldorado (http://www.eldorado.org.br/). * * This file is part of the software Remote Resources * * All rights reserved. This file and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 3.0 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * This file is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ package com.eldorado.remoteresources; public class UpdateScriptFile extends JFrame { // TODO: remove me (this class) when I won't be useful anymore! =) private static String linha; private static String tempo; private static Vector<String> vetScript; private static final int OPCAO_SLEEP = 1; private static final int OPCAO_PAUSE = 2; private final static JTextArea actionsText = new JTextArea(); private final JButton saveButton = new JButton("Save"); private final JRadioButton sleepRadio = new JRadioButton("Tag Sleep", true); private final JRadioButton pauseRadio = new JRadioButton("Tag Pause");
// Path: src/com/eldorado/remoteresources/ui/actions/ClientManipulationScript.java // public class ClientManipulationScript { // // private static final String DEFAULT_CLIENT_SCRIPT_DIR = RemoteResourcesConfiguration // .getRemoteResourcesDir() != null ? RemoteResourcesConfiguration // .getRemoteResourcesDir() + File.separator + "scripts" : System //$NON-NLS-1$ // .getProperty("user.home"); // // private static final String CLIENT_SCRIPT_FILENAME_EXTENSION = ".txt"; //$NON-NLS-1$ // // private static String outputFile = null; // private BufferedWriter out; // // private static String serialNumber; // private static String host; // private static String port; // // public boolean playGenerateScriptFile(String device, String host, // String port, String path, String name) { // // serialNumber = device; // ClientManipulationScript.host = host; // ClientManipulationScript.port = port; // // File fOutputDir = new File(path); // // if (!fOutputDir.exists()) { // fOutputDir.mkdirs(); // } // // outputFile = path + File.separator + name; // // File f = new File(outputFile); // if (!f.exists()) { // try { // out = new BufferedWriter(new FileWriter(outputFile)); // return true; // } catch (IOException e) { // e.printStackTrace(); // } // } // return false; // } // // public void stopGenerateScriptFile(Vector<String> actions) { // Iterator<String> it = actions.iterator(); // // try { // out.write(serialNumber); // out.newLine(); // while (it.hasNext()) { // System.out.println(); // out.write(it.next().toString()); // out.newLine(); // } // out.close(); // Script.clean(); // } catch (IOException e) { // // } // } // // public void createScriptFile(String device, String host, String port, // String path, String name, Vector<String> actions) { // if (playGenerateScriptFile(device, host, port, path, name)) { // stopGenerateScriptFile(actions); // } // Script.clean(); // } // // // ================== READ A SCRIPT ================== // public Vector<String> readScriptFile(File f) { // Vector<String> actions = null; // BufferedReader reader = null; // try { // if (f.canRead()) { // actions = new Vector<String>(); // reader = new BufferedReader(new FileReader(f)); // String line = reader.readLine(); // // while (line != null) { // actions.add(line); // line = reader.readLine(); // } // } // } catch (FileNotFoundException e) { // } catch (IOException e) { // } finally { // if (reader != null) { // try { // reader.close(); // } catch (IOException e) { // // do nothing // } // } // } // // return actions; // } // // // ================== UPDATE SCRIPT ================== // public void updateScriptFile(File f, Vector<String> actions) { // // BufferedWriter writer = null; // Iterator it = actions.iterator(); // // try { // if (f.canRead() && !it.equals(null)) { // writer = new BufferedWriter(new PrintWriter(new FileWriter(f))); // while (it.hasNext()) { // writer.write(it.next().toString()); // writer.newLine(); // } // } // // writer.close(); // } catch (FileNotFoundException e) { // } catch (IOException e) { // } finally { // if (writer != null) { // try { // writer.close(); // } catch (IOException e) { // // do nothing // } // } // } // // } // } // Path: src/com/eldorado/remoteresources/UpdateScriptFile.java import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.File; import java.util.Iterator; import java.util.Vector; import javax.swing.AbstractButton; import javax.swing.ButtonGroup; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JRadioButton; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.ScrollPaneConstants; import com.eldorado.remoteresources.ui.actions.ClientManipulationScript; /* * (C) Copyright 2014 Instituto de Pesquisas Eldorado (http://www.eldorado.org.br/). * * This file is part of the software Remote Resources * * All rights reserved. This file and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 3.0 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * This file is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ package com.eldorado.remoteresources; public class UpdateScriptFile extends JFrame { // TODO: remove me (this class) when I won't be useful anymore! =) private static String linha; private static String tempo; private static Vector<String> vetScript; private static final int OPCAO_SLEEP = 1; private static final int OPCAO_PAUSE = 2; private final static JTextArea actionsText = new JTextArea(); private final JButton saveButton = new JButton("Save"); private final JRadioButton sleepRadio = new JRadioButton("Tag Sleep", true); private final JRadioButton pauseRadio = new JRadioButton("Tag Pause");
private final static ClientManipulationScript cScript = new ClientManipulationScript();
IPEldorado/RemoteResources
src/com/eldorado/remoteresources/android/common/connection/messages/control/CommandMessage.java
// Path: src/com/eldorado/remoteresources/utils/SubType.java // public enum SubType { // NONE, PULL, PUSH, INSTALL, UNINSTALL // }
import com.eldorado.remoteresources.utils.SubType;
/* * (C) Copyright 2014 Instituto de Pesquisas Eldorado (http://www.eldorado.org.br/). * * This file is part of the software Remote Resources * * All rights reserved. This file and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 3.0 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * This file is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ package com.eldorado.remoteresources.android.common.connection.messages.control; /** * Message with informations to run adb command * * @author Rafael Dias Santos * */ public abstract class CommandMessage extends ControlMessage { // TODO protected final String serialNumber; protected final String[] params;
// Path: src/com/eldorado/remoteresources/utils/SubType.java // public enum SubType { // NONE, PULL, PUSH, INSTALL, UNINSTALL // } // Path: src/com/eldorado/remoteresources/android/common/connection/messages/control/CommandMessage.java import com.eldorado.remoteresources.utils.SubType; /* * (C) Copyright 2014 Instituto de Pesquisas Eldorado (http://www.eldorado.org.br/). * * This file is part of the software Remote Resources * * All rights reserved. This file and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 3.0 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * This file is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ package com.eldorado.remoteresources.android.common.connection.messages.control; /** * Message with informations to run adb command * * @author Rafael Dias Santos * */ public abstract class CommandMessage extends ControlMessage { // TODO protected final String serialNumber; protected final String[] params;
protected final SubType subType;
IPEldorado/RemoteResources
src/com/eldorado/remoteresources/android/common/connection/messages/control/ControlFileHandlingMessage.java
// Path: src/com/eldorado/remoteresources/utils/SubType.java // public enum SubType { // NONE, PULL, PUSH, INSTALL, UNINSTALL // }
import com.eldorado.remoteresources.utils.SubType;
/* * (C) Copyright 2014 Instituto de Pesquisas Eldorado (http://www.eldorado.org.br/). * * This file is part of the software Remote Resources * * All rights reserved. This file and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 3.0 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * This file is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ package com.eldorado.remoteresources.android.common.connection.messages.control; /** * Message with informations to handle files (pull/push/delete) * * @author Rafael Dias Santos * */ public class ControlFileHandlingMessage extends CommandMessage { private static final long serialVersionUID = 5481207318846024671L; public ControlFileHandlingMessage(int sequenceNumber, String serialNumber,
// Path: src/com/eldorado/remoteresources/utils/SubType.java // public enum SubType { // NONE, PULL, PUSH, INSTALL, UNINSTALL // } // Path: src/com/eldorado/remoteresources/android/common/connection/messages/control/ControlFileHandlingMessage.java import com.eldorado.remoteresources.utils.SubType; /* * (C) Copyright 2014 Instituto de Pesquisas Eldorado (http://www.eldorado.org.br/). * * This file is part of the software Remote Resources * * All rights reserved. This file and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 3.0 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * This file is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ package com.eldorado.remoteresources.android.common.connection.messages.control; /** * Message with informations to handle files (pull/push/delete) * * @author Rafael Dias Santos * */ public class ControlFileHandlingMessage extends CommandMessage { private static final long serialVersionUID = 5481207318846024671L; public ControlFileHandlingMessage(int sequenceNumber, String serialNumber,
SubType subType, String[] params) {
IPEldorado/RemoteResources
src/com/eldorado/remoteresources/android/common/connection/messages/control/CommandMessageFactory.java
// Path: src/com/eldorado/remoteresources/utils/Command.java // public abstract class Command { // protected CommandType type; // protected SubType subType; // protected String[] params; // // public CommandType getCommandType() { // return type; // } // // public SubType getSubType() { // return subType; // } // // public abstract boolean areParametersValid(); // // public String[] getParams() { // return params; // } // }
import com.eldorado.remoteresources.utils.Command;
/* * (C) Copyright 2014 Instituto de Pesquisas Eldorado (http://www.eldorado.org.br/). * * This file is part of the software Remote Resources * * All rights reserved. This file and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 3.0 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * This file is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ package com.eldorado.remoteresources.android.common.connection.messages.control; /** * Message with informations to run shell command * * @author Rafael Dias Santos * */ public class CommandMessageFactory { /** * */ private static final long serialVersionUID = 1467637828016992406L;
// Path: src/com/eldorado/remoteresources/utils/Command.java // public abstract class Command { // protected CommandType type; // protected SubType subType; // protected String[] params; // // public CommandType getCommandType() { // return type; // } // // public SubType getSubType() { // return subType; // } // // public abstract boolean areParametersValid(); // // public String[] getParams() { // return params; // } // } // Path: src/com/eldorado/remoteresources/android/common/connection/messages/control/CommandMessageFactory.java import com.eldorado.remoteresources.utils.Command; /* * (C) Copyright 2014 Instituto de Pesquisas Eldorado (http://www.eldorado.org.br/). * * This file is part of the software Remote Resources * * All rights reserved. This file and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 3.0 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * This file is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ package com.eldorado.remoteresources.android.common.connection.messages.control; /** * Message with informations to run shell command * * @author Rafael Dias Santos * */ public class CommandMessageFactory { /** * */ private static final long serialVersionUID = 1467637828016992406L;
public static CommandMessage getCommandMessage(Command command,
IPEldorado/RemoteResources
src/com/eldorado/remoteresources/android/common/connection/messages/data/DataMessage.java
// Path: src/com/eldorado/remoteresources/android/common/connection/messages/Message.java // public abstract class Message implements Serializable { // // private static final long serialVersionUID = -1051009758389055769L; // // public static final int MAX_SEQUENCE_NUMBER = 1 << 16; // // /** // * The message type: check {@link MessageType} // */ // private final MessageType type; // // /** // * The message sequence number for the client/server connection // */ // private final int sequenceNumber; // // /** // * Create a new message with a sequence number and type // * // * @param sequenceNumber // * the sequence number // * @param type // * the message type // */ // public Message(int sequenceNumber, MessageType type) { // this.type = type; // this.sequenceNumber = sequenceNumber; // } // // /** // * Get this message type. // * // * @return the type of this message // * @see {@link MessageType} for available types // */ // public MessageType getMessageType() { // return type; // } // // /** // * Get this message sequence number // * // * @return this message sequence number // */ // public int getSequenceNumber() { // return sequenceNumber; // } // // } // // Path: src/com/eldorado/remoteresources/android/common/connection/messages/MessageType.java // public enum MessageType { // CONTROL_MESSAGE, DATA_MESSAGE; // }
import com.eldorado.remoteresources.android.common.connection.messages.Message; import com.eldorado.remoteresources.android.common.connection.messages.MessageType;
/* * (C) Copyright 2014 Instituto de Pesquisas Eldorado (http://www.eldorado.org.br/). * * This file is part of the software Remote Resources * * All rights reserved. This file and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 3.0 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * This file is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ package com.eldorado.remoteresources.android.common.connection.messages.data; /** * A data message * * @author Marcelo Marzola Bossoni * */ public abstract class DataMessage extends Message { private static final long serialVersionUID = 2991317175997003007L; private final DataMessageType messageType; /** * Create a new data message * * @param sequenceNumber * the message sequence number * @param messageType * the message type * @see {@link DataMessageType} for available types */ public DataMessage(int sequenceNumber, DataMessageType messageType) {
// Path: src/com/eldorado/remoteresources/android/common/connection/messages/Message.java // public abstract class Message implements Serializable { // // private static final long serialVersionUID = -1051009758389055769L; // // public static final int MAX_SEQUENCE_NUMBER = 1 << 16; // // /** // * The message type: check {@link MessageType} // */ // private final MessageType type; // // /** // * The message sequence number for the client/server connection // */ // private final int sequenceNumber; // // /** // * Create a new message with a sequence number and type // * // * @param sequenceNumber // * the sequence number // * @param type // * the message type // */ // public Message(int sequenceNumber, MessageType type) { // this.type = type; // this.sequenceNumber = sequenceNumber; // } // // /** // * Get this message type. // * // * @return the type of this message // * @see {@link MessageType} for available types // */ // public MessageType getMessageType() { // return type; // } // // /** // * Get this message sequence number // * // * @return this message sequence number // */ // public int getSequenceNumber() { // return sequenceNumber; // } // // } // // Path: src/com/eldorado/remoteresources/android/common/connection/messages/MessageType.java // public enum MessageType { // CONTROL_MESSAGE, DATA_MESSAGE; // } // Path: src/com/eldorado/remoteresources/android/common/connection/messages/data/DataMessage.java import com.eldorado.remoteresources.android.common.connection.messages.Message; import com.eldorado.remoteresources.android.common.connection.messages.MessageType; /* * (C) Copyright 2014 Instituto de Pesquisas Eldorado (http://www.eldorado.org.br/). * * This file is part of the software Remote Resources * * All rights reserved. This file and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 3.0 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * This file is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ package com.eldorado.remoteresources.android.common.connection.messages.data; /** * A data message * * @author Marcelo Marzola Bossoni * */ public abstract class DataMessage extends Message { private static final long serialVersionUID = 2991317175997003007L; private final DataMessageType messageType; /** * Create a new data message * * @param sequenceNumber * the message sequence number * @param messageType * the message type * @see {@link DataMessageType} for available types */ public DataMessage(int sequenceNumber, DataMessageType messageType) {
super(sequenceNumber, MessageType.DATA_MESSAGE);
IPEldorado/RemoteResources
src/com/eldorado/remoteresources/android/common/connection/messages/control/ControlRunShellCommandMessage.java
// Path: src/com/eldorado/remoteresources/utils/SubType.java // public enum SubType { // NONE, PULL, PUSH, INSTALL, UNINSTALL // }
import com.eldorado.remoteresources.utils.SubType;
/* * (C) Copyright 2014 Instituto de Pesquisas Eldorado (http://www.eldorado.org.br/). * * This file is part of the software Remote Resources * * All rights reserved. This file and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 3.0 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * This file is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ package com.eldorado.remoteresources.android.common.connection.messages.control; /** * Message with informations to run shell command * * @author Rafael Dias Santos * */ public class ControlRunShellCommandMessage extends CommandMessage { public ControlRunShellCommandMessage(int sequenceNumber,
// Path: src/com/eldorado/remoteresources/utils/SubType.java // public enum SubType { // NONE, PULL, PUSH, INSTALL, UNINSTALL // } // Path: src/com/eldorado/remoteresources/android/common/connection/messages/control/ControlRunShellCommandMessage.java import com.eldorado.remoteresources.utils.SubType; /* * (C) Copyright 2014 Instituto de Pesquisas Eldorado (http://www.eldorado.org.br/). * * This file is part of the software Remote Resources * * All rights reserved. This file and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 3.0 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * This file is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ package com.eldorado.remoteresources.android.common.connection.messages.control; /** * Message with informations to run shell command * * @author Rafael Dias Santos * */ public class ControlRunShellCommandMessage extends CommandMessage { public ControlRunShellCommandMessage(int sequenceNumber,
String serialNumber, SubType subType, String[] params) {
IPEldorado/RemoteResources
src/com/eldorado/remoteresources/android/common/connection/messages/control/KeyCommandMessage.java
// Path: src/com/eldorado/remoteresources/android/common/Keys.java // public enum Keys { // /** */ // HOME, // /** */ // BACK, // /** */ // VOLUME_UP, // /** */ // VOLUME_DOWN, // /** */ // POWER, // /** */ // CAMERA, // /** */ // CLEAR, // /** */ // DEL, // /** */ // FOCUS, // /** */ // MENU, // /** */ // SEARCH; // // @Override // public String toString() { // return "KEYCODE_" + super.toString(); // } // }
import com.eldorado.remoteresources.android.common.Keys;
/* * (C) Copyright 2014 Instituto de Pesquisas Eldorado (http://www.eldorado.org.br/). * * This file is part of the software Remote Resources * * All rights reserved. This file and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 3.0 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * This file is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ package com.eldorado.remoteresources.android.common.connection.messages.control; /** * This class represents a key command to be executed * * @author Marcelo Marzola Bossoni * */ public class KeyCommandMessage extends DeviceCommandMessage { private static final long serialVersionUID = 7784219670587270710L; public final KeyCommandMessageType keyCommandMessageType;
// Path: src/com/eldorado/remoteresources/android/common/Keys.java // public enum Keys { // /** */ // HOME, // /** */ // BACK, // /** */ // VOLUME_UP, // /** */ // VOLUME_DOWN, // /** */ // POWER, // /** */ // CAMERA, // /** */ // CLEAR, // /** */ // DEL, // /** */ // FOCUS, // /** */ // MENU, // /** */ // SEARCH; // // @Override // public String toString() { // return "KEYCODE_" + super.toString(); // } // } // Path: src/com/eldorado/remoteresources/android/common/connection/messages/control/KeyCommandMessage.java import com.eldorado.remoteresources.android.common.Keys; /* * (C) Copyright 2014 Instituto de Pesquisas Eldorado (http://www.eldorado.org.br/). * * This file is part of the software Remote Resources * * All rights reserved. This file and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 3.0 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * This file is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ package com.eldorado.remoteresources.android.common.connection.messages.control; /** * This class represents a key command to be executed * * @author Marcelo Marzola Bossoni * */ public class KeyCommandMessage extends DeviceCommandMessage { private static final long serialVersionUID = 7784219670587270710L; public final KeyCommandMessageType keyCommandMessageType;
private final Keys key;
IPEldorado/RemoteResources
src/com/eldorado/remoteresources/android/common/connection/messages/control/AcknowledgmentMessage.java
// Path: src/com/eldorado/remoteresources/android/common/Status.java // public enum Status { // OK, ERROR // }
import com.eldorado.remoteresources.android.common.Status;
/* * (C) Copyright 2014 Instituto de Pesquisas Eldorado (http://www.eldorado.org.br/). * * This file is part of the software Remote Resources * * All rights reserved. This file and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 3.0 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * This file is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ package com.eldorado.remoteresources.android.common.connection.messages.control; /** * This control message acknowledges a control message. If there are any need to * data to be sent to client, it can be done through data field. * * The ack message sequence number is the same of the message that originated * this ack * * @author Marcelo Marzola Bossoni * */ public class AcknowledgmentMessage extends ControlMessage { private static final long serialVersionUID = -2892553829246464532L;
// Path: src/com/eldorado/remoteresources/android/common/Status.java // public enum Status { // OK, ERROR // } // Path: src/com/eldorado/remoteresources/android/common/connection/messages/control/AcknowledgmentMessage.java import com.eldorado.remoteresources.android.common.Status; /* * (C) Copyright 2014 Instituto de Pesquisas Eldorado (http://www.eldorado.org.br/). * * This file is part of the software Remote Resources * * All rights reserved. This file and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 3.0 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * This file is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ package com.eldorado.remoteresources.android.common.connection.messages.control; /** * This control message acknowledges a control message. If there are any need to * data to be sent to client, it can be done through data field. * * The ack message sequence number is the same of the message that originated * this ack * * @author Marcelo Marzola Bossoni * */ public class AcknowledgmentMessage extends ControlMessage { private static final long serialVersionUID = -2892553829246464532L;
private final Status status;
IPEldorado/RemoteResources
src/com/eldorado/remoteresources/ui/KeyButton.java
// Path: src/com/eldorado/remoteresources/android/common/Keys.java // public enum Keys { // /** */ // HOME, // /** */ // BACK, // /** */ // VOLUME_UP, // /** */ // VOLUME_DOWN, // /** */ // POWER, // /** */ // CAMERA, // /** */ // CLEAR, // /** */ // DEL, // /** */ // FOCUS, // /** */ // MENU, // /** */ // SEARCH; // // @Override // public String toString() { // return "KEYCODE_" + super.toString(); // } // }
import javax.swing.JButton; import com.eldorado.remoteresources.android.common.Keys;
/* * (C) Copyright 2014 Instituto de Pesquisas Eldorado (http://www.eldorado.org.br/). * * This file is part of the software Remote Resources * * All rights reserved. This file and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 3.0 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * This file is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ package com.eldorado.remoteresources.ui; /** * * * */ public class KeyButton extends JButton { private static final long serialVersionUID = 8637146572121840078L;
// Path: src/com/eldorado/remoteresources/android/common/Keys.java // public enum Keys { // /** */ // HOME, // /** */ // BACK, // /** */ // VOLUME_UP, // /** */ // VOLUME_DOWN, // /** */ // POWER, // /** */ // CAMERA, // /** */ // CLEAR, // /** */ // DEL, // /** */ // FOCUS, // /** */ // MENU, // /** */ // SEARCH; // // @Override // public String toString() { // return "KEYCODE_" + super.toString(); // } // } // Path: src/com/eldorado/remoteresources/ui/KeyButton.java import javax.swing.JButton; import com.eldorado.remoteresources.android.common.Keys; /* * (C) Copyright 2014 Instituto de Pesquisas Eldorado (http://www.eldorado.org.br/). * * This file is part of the software Remote Resources * * All rights reserved. This file and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 3.0 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * This file is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ package com.eldorado.remoteresources.ui; /** * * * */ public class KeyButton extends JButton { private static final long serialVersionUID = 8637146572121840078L;
private final Keys key;
IPEldorado/RemoteResources
src/com/eldorado/remoteresources/android/common/connection/messages/control/ControlMessage.java
// Path: src/com/eldorado/remoteresources/android/common/connection/messages/Message.java // public abstract class Message implements Serializable { // // private static final long serialVersionUID = -1051009758389055769L; // // public static final int MAX_SEQUENCE_NUMBER = 1 << 16; // // /** // * The message type: check {@link MessageType} // */ // private final MessageType type; // // /** // * The message sequence number for the client/server connection // */ // private final int sequenceNumber; // // /** // * Create a new message with a sequence number and type // * // * @param sequenceNumber // * the sequence number // * @param type // * the message type // */ // public Message(int sequenceNumber, MessageType type) { // this.type = type; // this.sequenceNumber = sequenceNumber; // } // // /** // * Get this message type. // * // * @return the type of this message // * @see {@link MessageType} for available types // */ // public MessageType getMessageType() { // return type; // } // // /** // * Get this message sequence number // * // * @return this message sequence number // */ // public int getSequenceNumber() { // return sequenceNumber; // } // // } // // Path: src/com/eldorado/remoteresources/android/common/connection/messages/MessageType.java // public enum MessageType { // CONTROL_MESSAGE, DATA_MESSAGE; // }
import com.eldorado.remoteresources.android.common.connection.messages.Message; import com.eldorado.remoteresources.android.common.connection.messages.MessageType;
/* * (C) Copyright 2014 Instituto de Pesquisas Eldorado (http://www.eldorado.org.br/). * * This file is part of the software Remote Resources * * All rights reserved. This file and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 3.0 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * This file is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ package com.eldorado.remoteresources.android.common.connection.messages.control; /** * The base control message * * @author Marcelo Marzola Bossoni * */ public abstract class ControlMessage extends Message { private static final long serialVersionUID = 110689265311286266L; /** * Check {@link ControlMessageType} */ private final ControlMessageType messageType; /** * Create a new control message * * @param sequenceNumber * @param messageType */ public ControlMessage(int sequenceNumber, ControlMessageType messageType) {
// Path: src/com/eldorado/remoteresources/android/common/connection/messages/Message.java // public abstract class Message implements Serializable { // // private static final long serialVersionUID = -1051009758389055769L; // // public static final int MAX_SEQUENCE_NUMBER = 1 << 16; // // /** // * The message type: check {@link MessageType} // */ // private final MessageType type; // // /** // * The message sequence number for the client/server connection // */ // private final int sequenceNumber; // // /** // * Create a new message with a sequence number and type // * // * @param sequenceNumber // * the sequence number // * @param type // * the message type // */ // public Message(int sequenceNumber, MessageType type) { // this.type = type; // this.sequenceNumber = sequenceNumber; // } // // /** // * Get this message type. // * // * @return the type of this message // * @see {@link MessageType} for available types // */ // public MessageType getMessageType() { // return type; // } // // /** // * Get this message sequence number // * // * @return this message sequence number // */ // public int getSequenceNumber() { // return sequenceNumber; // } // // } // // Path: src/com/eldorado/remoteresources/android/common/connection/messages/MessageType.java // public enum MessageType { // CONTROL_MESSAGE, DATA_MESSAGE; // } // Path: src/com/eldorado/remoteresources/android/common/connection/messages/control/ControlMessage.java import com.eldorado.remoteresources.android.common.connection.messages.Message; import com.eldorado.remoteresources.android.common.connection.messages.MessageType; /* * (C) Copyright 2014 Instituto de Pesquisas Eldorado (http://www.eldorado.org.br/). * * This file is part of the software Remote Resources * * All rights reserved. This file and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 3.0 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * This file is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ package com.eldorado.remoteresources.android.common.connection.messages.control; /** * The base control message * * @author Marcelo Marzola Bossoni * */ public abstract class ControlMessage extends Message { private static final long serialVersionUID = 110689265311286266L; /** * Check {@link ControlMessageType} */ private final ControlMessageType messageType; /** * Create a new control message * * @param sequenceNumber * @param messageType */ public ControlMessage(int sequenceNumber, ControlMessageType messageType) {
super(sequenceNumber, MessageType.CONTROL_MESSAGE);
IPEldorado/RemoteResources
src/com/eldorado/remoteresources/ui/wizard/WizardPage.java
// Path: src/com/eldorado/remoteresources/ui/wizard/IWizard.java // public enum WizardStatus { // OK, INFO, WARNING, ERROR // };
import com.eldorado.remoteresources.ui.wizard.IWizard.WizardStatus; import java.util.List; import javax.swing.JPanel; import javax.swing.SwingWorker;
/* * (C) Copyright 2014 Instituto de Pesquisas Eldorado (http://www.eldorado.org.br/). * * This file is part of the software Remote Resources * * All rights reserved. This file and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 3.0 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * This file is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ package com.eldorado.remoteresources.ui.wizard; /** * This class is a basic implementation of the {@link IWizardPage} interface * * @author Marcelo Marzola Bossoni * */ public abstract class WizardPage extends JPanel implements IWizardPage { private static final long serialVersionUID = 7968343445732154001L; private IWizardPage nextPage = null; private IWizardPage previousPage = null; private String errorMessage = null; private String description = null;
// Path: src/com/eldorado/remoteresources/ui/wizard/IWizard.java // public enum WizardStatus { // OK, INFO, WARNING, ERROR // }; // Path: src/com/eldorado/remoteresources/ui/wizard/WizardPage.java import com.eldorado.remoteresources.ui.wizard.IWizard.WizardStatus; import java.util.List; import javax.swing.JPanel; import javax.swing.SwingWorker; /* * (C) Copyright 2014 Instituto de Pesquisas Eldorado (http://www.eldorado.org.br/). * * This file is part of the software Remote Resources * * All rights reserved. This file and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 3.0 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * This file is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ package com.eldorado.remoteresources.ui.wizard; /** * This class is a basic implementation of the {@link IWizardPage} interface * * @author Marcelo Marzola Bossoni * */ public abstract class WizardPage extends JPanel implements IWizardPage { private static final long serialVersionUID = 7968343445732154001L; private IWizardPage nextPage = null; private IWizardPage previousPage = null; private String errorMessage = null; private String description = null;
private WizardStatus errorLevel = WizardStatus.OK;
teiid/teiid-embedded-examples
embedded-portfolio/src/main/java/org/teiid/example/TeiidEmbeddedPortfolio.java
// Path: couchbase-as-a-datasource/src/main/java/org/teiid/example/JDBCUtils.java // public static void execute(Connection connection, String sql) throws Exception { // execute(connection, sql, false); // }
import org.teiid.translator.jdbc.h2.H2ExecutionFactory; import static org.teiid.example.JDBCUtils.execute; import java.io.InputStreamReader; import java.sql.Connection; import javax.sql.DataSource; import org.h2.tools.RunScript; import org.teiid.resource.adapter.file.FileManagedConnectionFactory; import org.teiid.runtime.EmbeddedConfiguration; import org.teiid.runtime.EmbeddedServer; import org.teiid.translator.file.FileExecutionFactory;
/* * Copyright Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags and * the COPYRIGHT.txt file distributed with this work. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.teiid.example; /** * This example is same as "Teiid Quick Start Example", you can find at http://jboss.org/teiid/quickstart * whereas the example shows how to use Dynamic VDB using a server based deployment, this below code shows to use same * example using Embedded Teiid. This uses a memory based H2 database and File source as sources and provides a * view layer using DDL. * * Note that this example shows how to integrate the traditional sources like jdbc, file, web-service etc, however you are * not limited to only those sources. As long as you can extended and provide implementations for * - ConnectionfactoryProvider * - Translator * - Metadata Repository * * you can integrate any kind of sources together, or provide a JDBC interface on a source or expose with with known schema. */ @SuppressWarnings("nls") public class TeiidEmbeddedPortfolio { public static void main(String[] args) throws Exception { DataSource ds = EmbeddedHelper.newDataSource("org.h2.Driver", "jdbc:h2:mem://localhost/~/account", "sa", "sa");
// Path: couchbase-as-a-datasource/src/main/java/org/teiid/example/JDBCUtils.java // public static void execute(Connection connection, String sql) throws Exception { // execute(connection, sql, false); // } // Path: embedded-portfolio/src/main/java/org/teiid/example/TeiidEmbeddedPortfolio.java import org.teiid.translator.jdbc.h2.H2ExecutionFactory; import static org.teiid.example.JDBCUtils.execute; import java.io.InputStreamReader; import java.sql.Connection; import javax.sql.DataSource; import org.h2.tools.RunScript; import org.teiid.resource.adapter.file.FileManagedConnectionFactory; import org.teiid.runtime.EmbeddedConfiguration; import org.teiid.runtime.EmbeddedServer; import org.teiid.translator.file.FileExecutionFactory; /* * Copyright Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags and * the COPYRIGHT.txt file distributed with this work. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.teiid.example; /** * This example is same as "Teiid Quick Start Example", you can find at http://jboss.org/teiid/quickstart * whereas the example shows how to use Dynamic VDB using a server based deployment, this below code shows to use same * example using Embedded Teiid. This uses a memory based H2 database and File source as sources and provides a * view layer using DDL. * * Note that this example shows how to integrate the traditional sources like jdbc, file, web-service etc, however you are * not limited to only those sources. As long as you can extended and provide implementations for * - ConnectionfactoryProvider * - Translator * - Metadata Repository * * you can integrate any kind of sources together, or provide a JDBC interface on a source or expose with with known schema. */ @SuppressWarnings("nls") public class TeiidEmbeddedPortfolio { public static void main(String[] args) throws Exception { DataSource ds = EmbeddedHelper.newDataSource("org.h2.Driver", "jdbc:h2:mem://localhost/~/account", "sa", "sa");
RunScript.execute(ds.getConnection(), new InputStreamReader(TeiidEmbeddedPortfolio.class.getClassLoader().getResourceAsStream("data/customer-schema.sql")));
teiid/teiid-embedded-examples
odataservice-as-a-datasource/src/main/java/org/teiid/example/TeiidEmbeddedODataServiceDataSource.java
// Path: couchbase-as-a-datasource/src/main/java/org/teiid/example/JDBCUtils.java // public static void execute(Connection connection, String sql) throws Exception { // execute(connection, sql, false); // }
import static org.teiid.example.JDBCUtils.execute; import java.sql.Connection; import org.teiid.resource.adapter.ws.WSManagedConnectionFactory; import org.teiid.runtime.EmbeddedConfiguration; import org.teiid.runtime.EmbeddedServer; import org.teiid.translator.odata.ODataExecutionFactory;
/* * Copyright Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags and * the COPYRIGHT.txt file distributed with this work. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.teiid.example; @SuppressWarnings("nls") public class TeiidEmbeddedODataServiceDataSource { public static void main(String[] args) throws Exception { EmbeddedServer server = new EmbeddedServer(); ODataExecutionFactory factory = new ODataExecutionFactory(); factory.start(); server.addTranslator("translator-odata", factory); WSManagedConnectionFactory managedconnectionFactory = new WSManagedConnectionFactory(); managedconnectionFactory.setEndPoint("http://services.odata.org/Northwind/Northwind.svc/"); server.addConnectionFactory("java:/ODataNorthwindDS", managedconnectionFactory.createConnectionFactory()); server.start(new EmbeddedConfiguration()); server.deployVDB(TeiidEmbeddedODataServiceDataSource.class.getClassLoader().getResourceAsStream("odataNorthwindservice-vdb.xml")); Connection c = server.getDriver().connect("jdbc:teiid:NorthwindVDB", null);
// Path: couchbase-as-a-datasource/src/main/java/org/teiid/example/JDBCUtils.java // public static void execute(Connection connection, String sql) throws Exception { // execute(connection, sql, false); // } // Path: odataservice-as-a-datasource/src/main/java/org/teiid/example/TeiidEmbeddedODataServiceDataSource.java import static org.teiid.example.JDBCUtils.execute; import java.sql.Connection; import org.teiid.resource.adapter.ws.WSManagedConnectionFactory; import org.teiid.runtime.EmbeddedConfiguration; import org.teiid.runtime.EmbeddedServer; import org.teiid.translator.odata.ODataExecutionFactory; /* * Copyright Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags and * the COPYRIGHT.txt file distributed with this work. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.teiid.example; @SuppressWarnings("nls") public class TeiidEmbeddedODataServiceDataSource { public static void main(String[] args) throws Exception { EmbeddedServer server = new EmbeddedServer(); ODataExecutionFactory factory = new ODataExecutionFactory(); factory.start(); server.addTranslator("translator-odata", factory); WSManagedConnectionFactory managedconnectionFactory = new WSManagedConnectionFactory(); managedconnectionFactory.setEndPoint("http://services.odata.org/Northwind/Northwind.svc/"); server.addConnectionFactory("java:/ODataNorthwindDS", managedconnectionFactory.createConnectionFactory()); server.start(new EmbeddedConfiguration()); server.deployVDB(TeiidEmbeddedODataServiceDataSource.class.getClassLoader().getResourceAsStream("odataNorthwindservice-vdb.xml")); Connection c = server.getDriver().connect("jdbc:teiid:NorthwindVDB", null);
execute(c, "SELECT * FROM Categories", false);
teiid/teiid-embedded-examples
loopback-example/src/main/java/org/teiid/example/LoopbackExample.java
// Path: couchbase-as-a-datasource/src/main/java/org/teiid/example/JDBCUtils.java // public static void execute(Connection connection, String sql) throws Exception { // execute(connection, sql, false); // }
import static org.teiid.example.JDBCUtils.execute; import java.sql.Connection; import org.teiid.runtime.EmbeddedConfiguration; import org.teiid.runtime.EmbeddedServer; import org.teiid.translator.loopback.LoopbackExecutionFactory;
/* * Copyright Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags and * the COPYRIGHT.txt file distributed with this work. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.teiid.example; @SuppressWarnings("nls") public class LoopbackExample { public static void main(String[] args) throws Exception { EmbeddedServer server = new EmbeddedServer(); LoopbackExecutionFactory factory = new LoopbackExecutionFactory(); factory.setWaitTime(1000); factory.setRowCount(9); factory.start(); server.addTranslator("translator-loopback", factory); server.start(new EmbeddedConfiguration()); server.deployVDB(LoopbackExample.class.getClassLoader().getResourceAsStream("loopback-vdb.xml")); Connection c = server.getDriver().connect("jdbc:teiid:LOOPBACKVDB", null);
// Path: couchbase-as-a-datasource/src/main/java/org/teiid/example/JDBCUtils.java // public static void execute(Connection connection, String sql) throws Exception { // execute(connection, sql, false); // } // Path: loopback-example/src/main/java/org/teiid/example/LoopbackExample.java import static org.teiid.example.JDBCUtils.execute; import java.sql.Connection; import org.teiid.runtime.EmbeddedConfiguration; import org.teiid.runtime.EmbeddedServer; import org.teiid.translator.loopback.LoopbackExecutionFactory; /* * Copyright Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags and * the COPYRIGHT.txt file distributed with this work. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.teiid.example; @SuppressWarnings("nls") public class LoopbackExample { public static void main(String[] args) throws Exception { EmbeddedServer server = new EmbeddedServer(); LoopbackExecutionFactory factory = new LoopbackExecutionFactory(); factory.setWaitTime(1000); factory.setRowCount(9); factory.start(); server.addTranslator("translator-loopback", factory); server.start(new EmbeddedConfiguration()); server.deployVDB(LoopbackExample.class.getClassLoader().getResourceAsStream("loopback-vdb.xml")); Connection c = server.getDriver().connect("jdbc:teiid:LOOPBACKVDB", null);
execute(c, "SELECT * FROM SampleTable", true);
teiid/teiid-embedded-examples
odata4service-as-a-datasource/src/main/java/org/teiid/example/TeiidEmbeddedOData4ServiceDataSource.java
// Path: couchbase-as-a-datasource/src/main/java/org/teiid/example/JDBCUtils.java // public static void execute(Connection connection, String sql) throws Exception { // execute(connection, sql, false); // }
import static org.teiid.example.JDBCUtils.execute; import java.sql.Connection; import org.teiid.resource.adapter.ws.WSManagedConnectionFactory; import org.teiid.runtime.EmbeddedConfiguration; import org.teiid.runtime.EmbeddedServer; import org.teiid.translator.odata4.ODataExecutionFactory;
/* * Copyright Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags and * the COPYRIGHT.txt file distributed with this work. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.teiid.example; @SuppressWarnings("nls") public class TeiidEmbeddedOData4ServiceDataSource { public static void main(String[] args) throws Exception { EmbeddedServer server = new EmbeddedServer(); ODataExecutionFactory factory = new ODataExecutionFactory(); factory.start(); server.addTranslator("odata4", factory); WSManagedConnectionFactory managedconnectionFactory = new WSManagedConnectionFactory(); managedconnectionFactory.setEndPoint("http://services.odata.org/V4/(S(va3tkzikqbtgu1ist44bbft5))/TripPinServiceRW"); server.addConnectionFactory("java:/tripDS", managedconnectionFactory.createConnectionFactory()); server.start(new EmbeddedConfiguration()); server.deployVDB(TeiidEmbeddedOData4ServiceDataSource.class.getClassLoader().getResourceAsStream("odata4-vdb.xml")); Connection c = server.getDriver().connect("jdbc:teiid:trippinVDB", null);
// Path: couchbase-as-a-datasource/src/main/java/org/teiid/example/JDBCUtils.java // public static void execute(Connection connection, String sql) throws Exception { // execute(connection, sql, false); // } // Path: odata4service-as-a-datasource/src/main/java/org/teiid/example/TeiidEmbeddedOData4ServiceDataSource.java import static org.teiid.example.JDBCUtils.execute; import java.sql.Connection; import org.teiid.resource.adapter.ws.WSManagedConnectionFactory; import org.teiid.runtime.EmbeddedConfiguration; import org.teiid.runtime.EmbeddedServer; import org.teiid.translator.odata4.ODataExecutionFactory; /* * Copyright Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags and * the COPYRIGHT.txt file distributed with this work. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.teiid.example; @SuppressWarnings("nls") public class TeiidEmbeddedOData4ServiceDataSource { public static void main(String[] args) throws Exception { EmbeddedServer server = new EmbeddedServer(); ODataExecutionFactory factory = new ODataExecutionFactory(); factory.start(); server.addTranslator("odata4", factory); WSManagedConnectionFactory managedconnectionFactory = new WSManagedConnectionFactory(); managedconnectionFactory.setEndPoint("http://services.odata.org/V4/(S(va3tkzikqbtgu1ist44bbft5))/TripPinServiceRW"); server.addConnectionFactory("java:/tripDS", managedconnectionFactory.createConnectionFactory()); server.start(new EmbeddedConfiguration()); server.deployVDB(TeiidEmbeddedOData4ServiceDataSource.class.getClassLoader().getResourceAsStream("odata4-vdb.xml")); Connection c = server.getDriver().connect("jdbc:teiid:trippinVDB", null);
execute(c, "SELECT * FROM trippin.People", false);
teiid/teiid-embedded-examples
mongodb-as-a-datasource/src/main/java/org/teiid/example/TeiidEmbeddedMongoDBDataSource.java
// Path: couchbase-as-a-datasource/src/main/java/org/teiid/example/JDBCUtils.java // public static void execute(Connection connection, String sql) throws Exception { // execute(connection, sql, false); // }
import static org.teiid.example.JDBCUtils.execute; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.util.Properties; import org.teiid.resource.adapter.mongodb.MongoDBManagedConnectionFactory; import org.teiid.runtime.EmbeddedConfiguration; import org.teiid.runtime.EmbeddedServer; import org.teiid.translator.mongodb.MongoDBExecutionFactory;
/* * Copyright Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags and * the COPYRIGHT.txt file distributed with this work. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.teiid.example; @SuppressWarnings("nls") public class TeiidEmbeddedMongoDBDataSource { private static String SERVERLIST = "127.0.0.1:27017" ; private static String DBNAME = "test" ; public static void main(String[] args) throws Exception { initMongoProperties(); EmbeddedServer server = new EmbeddedServer(); MongoDBExecutionFactory factory = new MongoDBExecutionFactory(); factory.start(); server.addTranslator("translator-mongodb", factory); MongoDBManagedConnectionFactory managedconnectionFactory = new MongoDBManagedConnectionFactory(); managedconnectionFactory.setRemoteServerList(SERVERLIST); managedconnectionFactory.setDatabase(DBNAME); server.addConnectionFactory("java:/mongoDS", managedconnectionFactory.createConnectionFactory()); server.start(new EmbeddedConfiguration()); server.deployVDB(TeiidEmbeddedMongoDBDataSource.class.getClassLoader().getResourceAsStream("mongodb-vdb.xml")); Connection c = server.getDriver().connect("jdbc:teiid:nothwind", null);
// Path: couchbase-as-a-datasource/src/main/java/org/teiid/example/JDBCUtils.java // public static void execute(Connection connection, String sql) throws Exception { // execute(connection, sql, false); // } // Path: mongodb-as-a-datasource/src/main/java/org/teiid/example/TeiidEmbeddedMongoDBDataSource.java import static org.teiid.example.JDBCUtils.execute; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.util.Properties; import org.teiid.resource.adapter.mongodb.MongoDBManagedConnectionFactory; import org.teiid.runtime.EmbeddedConfiguration; import org.teiid.runtime.EmbeddedServer; import org.teiid.translator.mongodb.MongoDBExecutionFactory; /* * Copyright Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags and * the COPYRIGHT.txt file distributed with this work. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.teiid.example; @SuppressWarnings("nls") public class TeiidEmbeddedMongoDBDataSource { private static String SERVERLIST = "127.0.0.1:27017" ; private static String DBNAME = "test" ; public static void main(String[] args) throws Exception { initMongoProperties(); EmbeddedServer server = new EmbeddedServer(); MongoDBExecutionFactory factory = new MongoDBExecutionFactory(); factory.start(); server.addTranslator("translator-mongodb", factory); MongoDBManagedConnectionFactory managedconnectionFactory = new MongoDBManagedConnectionFactory(); managedconnectionFactory.setRemoteServerList(SERVERLIST); managedconnectionFactory.setDatabase(DBNAME); server.addConnectionFactory("java:/mongoDS", managedconnectionFactory.createConnectionFactory()); server.start(new EmbeddedConfiguration()); server.deployVDB(TeiidEmbeddedMongoDBDataSource.class.getClassLoader().getResourceAsStream("mongodb-vdb.xml")); Connection c = server.getDriver().connect("jdbc:teiid:nothwind", null);
execute(c, "DELETE FROM Employee", false);
teiid/teiid-embedded-examples
embedded-portfolio-sockets/src/main/java/org/teiid/example/TeiidEmbeddedPortfolio.java
// Path: couchbase-as-a-datasource/src/main/java/org/teiid/example/JDBCUtils.java // public static void execute(Connection connection, String sql) throws Exception { // execute(connection, sql, false); // }
import org.teiid.translator.file.FileExecutionFactory; import org.teiid.translator.jdbc.h2.H2ExecutionFactory; import org.teiid.transport.SocketConfiguration; import org.teiid.transport.WireProtocol; import static org.teiid.example.JDBCUtils.execute; import java.io.InputStreamReader; import java.sql.Connection; import java.sql.DriverManager; import javax.sql.DataSource; import org.h2.tools.RunScript; import org.teiid.resource.adapter.file.FileManagedConnectionFactory; import org.teiid.runtime.EmbeddedConfiguration; import org.teiid.runtime.EmbeddedServer;
/* * Copyright Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags and * the COPYRIGHT.txt file distributed with this work. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.teiid.example; /** * This example is same as "embedded-portfolio" example, except this demonstrates exposing teiid embedded * using sockets, so that a client application running in another VM can connect. * * This example will start teiid embedded as the "Server" and then start a "Client" thread that will connect to * the server and issue the same queries issued in the "embedded-portfolio" example. */ @SuppressWarnings("nls") public class TeiidEmbeddedPortfolio { public static void main(String[] args) throws Exception { Server s = new Server(); new Thread(s).start(); Thread.sleep(10000); Client c = new Client(); new Thread(c).start(); } } final class Server implements Runnable { /** * {@inheritDoc} * * @see java.lang.Runnable#run() */ @Override public void run() { try { SocketConfiguration s = new SocketConfiguration(); s.setBindAddress("localhost"); s.setPortNumber(31000); s.setProtocol(WireProtocol.teiid); DataSource ds = EmbeddedHelper.newDataSource("org.h2.Driver", "jdbc:h2:mem://localhost/~/account", "sa", "sa");
// Path: couchbase-as-a-datasource/src/main/java/org/teiid/example/JDBCUtils.java // public static void execute(Connection connection, String sql) throws Exception { // execute(connection, sql, false); // } // Path: embedded-portfolio-sockets/src/main/java/org/teiid/example/TeiidEmbeddedPortfolio.java import org.teiid.translator.file.FileExecutionFactory; import org.teiid.translator.jdbc.h2.H2ExecutionFactory; import org.teiid.transport.SocketConfiguration; import org.teiid.transport.WireProtocol; import static org.teiid.example.JDBCUtils.execute; import java.io.InputStreamReader; import java.sql.Connection; import java.sql.DriverManager; import javax.sql.DataSource; import org.h2.tools.RunScript; import org.teiid.resource.adapter.file.FileManagedConnectionFactory; import org.teiid.runtime.EmbeddedConfiguration; import org.teiid.runtime.EmbeddedServer; /* * Copyright Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags and * the COPYRIGHT.txt file distributed with this work. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.teiid.example; /** * This example is same as "embedded-portfolio" example, except this demonstrates exposing teiid embedded * using sockets, so that a client application running in another VM can connect. * * This example will start teiid embedded as the "Server" and then start a "Client" thread that will connect to * the server and issue the same queries issued in the "embedded-portfolio" example. */ @SuppressWarnings("nls") public class TeiidEmbeddedPortfolio { public static void main(String[] args) throws Exception { Server s = new Server(); new Thread(s).start(); Thread.sleep(10000); Client c = new Client(); new Thread(c).start(); } } final class Server implements Runnable { /** * {@inheritDoc} * * @see java.lang.Runnable#run() */ @Override public void run() { try { SocketConfiguration s = new SocketConfiguration(); s.setBindAddress("localhost"); s.setPortNumber(31000); s.setProtocol(WireProtocol.teiid); DataSource ds = EmbeddedHelper.newDataSource("org.h2.Driver", "jdbc:h2:mem://localhost/~/account", "sa", "sa");
RunScript.execute(ds.getConnection(), new InputStreamReader(TeiidEmbeddedPortfolio.class.getClassLoader().getResourceAsStream("data/customer-schema.sql")));
teiid/teiid-embedded-examples
socialmedia-integration/weibo-as-a-datasource/src/main/java/org/teiid/example/TeiidEmbeddedWeiboDataSource.java
// Path: couchbase-as-a-datasource/src/main/java/org/teiid/example/JDBCUtils.java // public static void execute(Connection connection, String sql) throws Exception { // execute(connection, sql, false); // }
import static org.teiid.example.JDBCUtils.execute; import java.sql.Blob; import java.sql.CallableStatement; import java.sql.Connection; import javax.xml.ws.Service.Mode; import org.teiid.resource.adapter.ws.WSManagedConnectionFactory; import org.teiid.runtime.EmbeddedConfiguration; import org.teiid.runtime.EmbeddedServer; import org.teiid.translator.ws.WSExecutionFactory; import org.teiid.translator.ws.WSExecutionFactory.Binding;
/* * Copyright Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags and * the COPYRIGHT.txt file distributed with this work. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.teiid.example; public class TeiidEmbeddedWeiboDataSource { public static void main(String[] args) throws Exception { EmbeddedServer server = new EmbeddedServer(); WSExecutionFactory translator = new WSExecutionFactory(); translator.setDefaultBinding(Binding.HTTP); translator.setDefaultServiceMode(Mode.MESSAGE); translator.start(); server.addTranslator("rest", translator); WSManagedConnectionFactory mcf = new WSManagedConnectionFactory(); server.addConnectionFactory("java:/weiboDS", mcf.createConnectionFactory()); server.start(new EmbeddedConfiguration()); server.deployVDB(TeiidEmbeddedWeiboDataSource.class.getClassLoader().getResourceAsStream("weibo-vdb.xml")); Connection conn = server.getDriver().connect("jdbc:teiid:WeiboVDB", null);
// Path: couchbase-as-a-datasource/src/main/java/org/teiid/example/JDBCUtils.java // public static void execute(Connection connection, String sql) throws Exception { // execute(connection, sql, false); // } // Path: socialmedia-integration/weibo-as-a-datasource/src/main/java/org/teiid/example/TeiidEmbeddedWeiboDataSource.java import static org.teiid.example.JDBCUtils.execute; import java.sql.Blob; import java.sql.CallableStatement; import java.sql.Connection; import javax.xml.ws.Service.Mode; import org.teiid.resource.adapter.ws.WSManagedConnectionFactory; import org.teiid.runtime.EmbeddedConfiguration; import org.teiid.runtime.EmbeddedServer; import org.teiid.translator.ws.WSExecutionFactory; import org.teiid.translator.ws.WSExecutionFactory.Binding; /* * Copyright Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags and * the COPYRIGHT.txt file distributed with this work. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.teiid.example; public class TeiidEmbeddedWeiboDataSource { public static void main(String[] args) throws Exception { EmbeddedServer server = new EmbeddedServer(); WSExecutionFactory translator = new WSExecutionFactory(); translator.setDefaultBinding(Binding.HTTP); translator.setDefaultServiceMode(Mode.MESSAGE); translator.start(); server.addTranslator("rest", translator); WSManagedConnectionFactory mcf = new WSManagedConnectionFactory(); server.addConnectionFactory("java:/weiboDS", mcf.createConnectionFactory()); server.start(new EmbeddedConfiguration()); server.deployVDB(TeiidEmbeddedWeiboDataSource.class.getClassLoader().getResourceAsStream("weibo-vdb.xml")); Connection conn = server.getDriver().connect("jdbc:teiid:WeiboVDB", null);
execute(conn, "EXEC friendships_followers('https://api.weibo.com/2/friendships/followers.json?access_token=2.00JEVMVG6u_COCa5f58ca2ado84mtC&uid=5957842765')", true);
teiid/teiid-embedded-examples
vertica-as-a-datasource/src/main/java/org/teiid/example/TeiidEmbeddedVerticaDataSource.java
// Path: couchbase-as-a-datasource/src/main/java/org/teiid/example/JDBCUtils.java // public static void execute(Connection connection, String sql) throws Exception { // execute(connection, sql, false); // }
import static org.teiid.example.JDBCUtils.execute; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.util.Properties; import javax.sql.DataSource; import org.teiid.runtime.EmbeddedConfiguration; import org.teiid.runtime.EmbeddedServer; import org.teiid.translator.jdbc.vertica.VerticaExecutionFactory;
/* * Copyright Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags and * the COPYRIGHT.txt file distributed with this work. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.teiid.example; @SuppressWarnings("nls") public class TeiidEmbeddedVerticaDataSource { static String JDBC_DRIVER = "com.vertica.jdbc.Driver"; static String JDBC_URL = "jdbc:vertica://127.0.0.1:5433/VMart"; static String JDBC_USER = "dbadmin"; static String JDBC_PASS = "redhat"; public static void main(String[] args) throws Exception { initDBProperties(); DataSource ds = EmbeddedHelper.newDataSource(JDBC_DRIVER, JDBC_URL, JDBC_USER, JDBC_PASS); EmbeddedServer server = new EmbeddedServer(); VerticaExecutionFactory factory = new VerticaExecutionFactory(); factory.start(); server.addTranslator("translator-vertica", factory); server.addConnectionFactory("java:/verticaDS", ds); EmbeddedConfiguration config = new EmbeddedConfiguration(); config.setTransactionManager(EmbeddedHelper.getTransactionManager()); server.start(config); server.deployVDB(TeiidEmbeddedVerticaDataSource.class.getClassLoader().getResourceAsStream("vertica-vdb.xml")); Connection c = server.getDriver().connect("jdbc:teiid:VerticaVDB", null);
// Path: couchbase-as-a-datasource/src/main/java/org/teiid/example/JDBCUtils.java // public static void execute(Connection connection, String sql) throws Exception { // execute(connection, sql, false); // } // Path: vertica-as-a-datasource/src/main/java/org/teiid/example/TeiidEmbeddedVerticaDataSource.java import static org.teiid.example.JDBCUtils.execute; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.util.Properties; import javax.sql.DataSource; import org.teiid.runtime.EmbeddedConfiguration; import org.teiid.runtime.EmbeddedServer; import org.teiid.translator.jdbc.vertica.VerticaExecutionFactory; /* * Copyright Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags and * the COPYRIGHT.txt file distributed with this work. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.teiid.example; @SuppressWarnings("nls") public class TeiidEmbeddedVerticaDataSource { static String JDBC_DRIVER = "com.vertica.jdbc.Driver"; static String JDBC_URL = "jdbc:vertica://127.0.0.1:5433/VMart"; static String JDBC_USER = "dbadmin"; static String JDBC_PASS = "redhat"; public static void main(String[] args) throws Exception { initDBProperties(); DataSource ds = EmbeddedHelper.newDataSource(JDBC_DRIVER, JDBC_URL, JDBC_USER, JDBC_PASS); EmbeddedServer server = new EmbeddedServer(); VerticaExecutionFactory factory = new VerticaExecutionFactory(); factory.start(); server.addTranslator("translator-vertica", factory); server.addConnectionFactory("java:/verticaDS", ds); EmbeddedConfiguration config = new EmbeddedConfiguration(); config.setTransactionManager(EmbeddedHelper.getTransactionManager()); server.start(config); server.deployVDB(TeiidEmbeddedVerticaDataSource.class.getClassLoader().getResourceAsStream("vertica-vdb.xml")); Connection c = server.getDriver().connect("jdbc:teiid:VerticaVDB", null);
execute(c, "SELECT * FROM employee_dimension_view", true);
teiid/teiid-embedded-examples
cassandra-as-a-datasourse/src/main/java/org/teiid/example/TeiidEmbeddedCassandraDataSource.java
// Path: couchbase-as-a-datasource/src/main/java/org/teiid/example/JDBCUtils.java // public static void execute(Connection connection, String sql) throws Exception { // execute(connection, sql, false); // }
import static org.teiid.example.JDBCUtils.execute; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.util.Properties; import org.teiid.resource.adapter.cassandra.CassandraManagedConnectionFactory; import org.teiid.runtime.EmbeddedConfiguration; import org.teiid.runtime.EmbeddedServer; import org.teiid.translator.cassandra.CassandraExecutionFactory;
/* * Copyright Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags and * the COPYRIGHT.txt file distributed with this work. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.teiid.example; @SuppressWarnings("nls") public class TeiidEmbeddedCassandraDataSource { private static String ADDRESS = "127.0.0.1"; private static String KEYSPACE = "demo"; public static void main(String[] args) throws Exception { initCassandraProperties(); EmbeddedServer server = new EmbeddedServer(); CassandraExecutionFactory factory = new CassandraExecutionFactory(); factory.start(); server.addTranslator("translator-cassandra", factory); CassandraManagedConnectionFactory managedconnectionFactory = new CassandraManagedConnectionFactory(); managedconnectionFactory.setAddress(ADDRESS); managedconnectionFactory.setKeyspace(KEYSPACE); server.addConnectionFactory("java:/demoCassandra", managedconnectionFactory.createConnectionFactory()); server.start(new EmbeddedConfiguration()); server.deployVDB(TeiidEmbeddedCassandraDataSource.class.getClassLoader().getResourceAsStream("cassandra-vdb.xml")); Connection c = server.getDriver().connect("jdbc:teiid:users", null);
// Path: couchbase-as-a-datasource/src/main/java/org/teiid/example/JDBCUtils.java // public static void execute(Connection connection, String sql) throws Exception { // execute(connection, sql, false); // } // Path: cassandra-as-a-datasourse/src/main/java/org/teiid/example/TeiidEmbeddedCassandraDataSource.java import static org.teiid.example.JDBCUtils.execute; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.util.Properties; import org.teiid.resource.adapter.cassandra.CassandraManagedConnectionFactory; import org.teiid.runtime.EmbeddedConfiguration; import org.teiid.runtime.EmbeddedServer; import org.teiid.translator.cassandra.CassandraExecutionFactory; /* * Copyright Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags and * the COPYRIGHT.txt file distributed with this work. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.teiid.example; @SuppressWarnings("nls") public class TeiidEmbeddedCassandraDataSource { private static String ADDRESS = "127.0.0.1"; private static String KEYSPACE = "demo"; public static void main(String[] args) throws Exception { initCassandraProperties(); EmbeddedServer server = new EmbeddedServer(); CassandraExecutionFactory factory = new CassandraExecutionFactory(); factory.start(); server.addTranslator("translator-cassandra", factory); CassandraManagedConnectionFactory managedconnectionFactory = new CassandraManagedConnectionFactory(); managedconnectionFactory.setAddress(ADDRESS); managedconnectionFactory.setKeyspace(KEYSPACE); server.addConnectionFactory("java:/demoCassandra", managedconnectionFactory.createConnectionFactory()); server.start(new EmbeddedConfiguration()); server.deployVDB(TeiidEmbeddedCassandraDataSource.class.getClassLoader().getResourceAsStream("cassandra-vdb.xml")); Connection c = server.getDriver().connect("jdbc:teiid:users", null);
execute(c, "SELECT * FROM UsersView", true);
teiid/teiid-embedded-examples
bigdata-integration/hadoop-integration-hive/src/main/java/org/teiid/example/TeiidEmbeddedHadoopDataSource.java
// Path: couchbase-as-a-datasource/src/main/java/org/teiid/example/JDBCUtils.java // public static void execute(Connection connection, String sql) throws Exception { // execute(connection, sql, false); // }
import static org.teiid.example.JDBCUtils.execute; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.util.Properties; import javax.sql.DataSource; import org.teiid.runtime.EmbeddedConfiguration; import org.teiid.runtime.EmbeddedServer; import org.teiid.translator.hive.HiveExecutionFactory;
/* * Copyright Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags and * the COPYRIGHT.txt file distributed with this work. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.teiid.example; public class TeiidEmbeddedHadoopDataSource { static String JDBC_DRIVER = "org.apache.hive.jdbc.HiveDriver"; static String JDBC_URL = "jdbc:hive2://127.0.0.1:10000/default"; static String JDBC_USER = "hive"; static String JDBC_PASS = ""; public static void main(String[] args) throws Exception { initDBProperties(); DataSource ds = EmbeddedHelper.newDataSource(JDBC_DRIVER, JDBC_URL, JDBC_USER, JDBC_PASS); EmbeddedServer server = new EmbeddedServer(); HiveExecutionFactory factory = new HiveExecutionFactory(); factory.start(); server.addTranslator("translator-hive", factory); server.addConnectionFactory("java:/hiveDS", ds); EmbeddedConfiguration config = new EmbeddedConfiguration(); config.setTransactionManager(EmbeddedHelper.getTransactionManager()); server.start(config); server.deployVDB(TeiidEmbeddedHadoopDataSource.class.getClassLoader().getResourceAsStream("hive-vdb.xml")); Connection c = server.getDriver().connect("jdbc:teiid:hivevdb", null);
// Path: couchbase-as-a-datasource/src/main/java/org/teiid/example/JDBCUtils.java // public static void execute(Connection connection, String sql) throws Exception { // execute(connection, sql, false); // } // Path: bigdata-integration/hadoop-integration-hive/src/main/java/org/teiid/example/TeiidEmbeddedHadoopDataSource.java import static org.teiid.example.JDBCUtils.execute; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.util.Properties; import javax.sql.DataSource; import org.teiid.runtime.EmbeddedConfiguration; import org.teiid.runtime.EmbeddedServer; import org.teiid.translator.hive.HiveExecutionFactory; /* * Copyright Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags and * the COPYRIGHT.txt file distributed with this work. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.teiid.example; public class TeiidEmbeddedHadoopDataSource { static String JDBC_DRIVER = "org.apache.hive.jdbc.HiveDriver"; static String JDBC_URL = "jdbc:hive2://127.0.0.1:10000/default"; static String JDBC_USER = "hive"; static String JDBC_PASS = ""; public static void main(String[] args) throws Exception { initDBProperties(); DataSource ds = EmbeddedHelper.newDataSource(JDBC_DRIVER, JDBC_URL, JDBC_USER, JDBC_PASS); EmbeddedServer server = new EmbeddedServer(); HiveExecutionFactory factory = new HiveExecutionFactory(); factory.start(); server.addTranslator("translator-hive", factory); server.addConnectionFactory("java:/hiveDS", ds); EmbeddedConfiguration config = new EmbeddedConfiguration(); config.setTransactionManager(EmbeddedHelper.getTransactionManager()); server.start(config); server.deployVDB(TeiidEmbeddedHadoopDataSource.class.getClassLoader().getResourceAsStream("hive-vdb.xml")); Connection c = server.getDriver().connect("jdbc:teiid:hivevdb", null);
execute(c, "SELECT * FROM EMPLOYEEVIEW", true);
teiid/teiid-embedded-examples
embedded-portfolio-logging/src/main/java/org/teiid/example/TeiidEmbeddedPortfolio.java
// Path: couchbase-as-a-datasource/src/main/java/org/teiid/example/JDBCUtils.java // public static void execute(Connection connection, String sql) throws Exception { // execute(connection, sql, false); // }
import org.teiid.runtime.JBossLogger; import org.teiid.translator.file.FileExecutionFactory; import org.teiid.translator.jdbc.h2.H2ExecutionFactory; import static org.teiid.example.JDBCUtils.execute; import java.io.InputStreamReader; import java.sql.Connection; import javax.sql.DataSource; import org.h2.tools.RunScript; import org.teiid.logging.LogManager; import org.teiid.resource.adapter.file.FileManagedConnectionFactory; import org.teiid.runtime.EmbeddedConfiguration; import org.teiid.runtime.EmbeddedServer;
/* * Copyright Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags and * the COPYRIGHT.txt file distributed with this work. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.teiid.example; @SuppressWarnings("nls") public class TeiidEmbeddedPortfolio { static { LogManager.setLogListener(new JBossLogger()); System.setProperty("java.util.logging.manager", "org.jboss.logmanager.LogManager"); //Optional // String propUrl = TeiidEmbeddedLogging.class.getClassLoader().getResource("logging.properties").toString(); // System.setProperty("logging.configuration", propUrl); } public static void main(String[] args) throws Exception { DataSource ds = EmbeddedHelper.newDataSource("org.h2.Driver", "jdbc:h2:mem://localhost/~/account", "sa", "sa");
// Path: couchbase-as-a-datasource/src/main/java/org/teiid/example/JDBCUtils.java // public static void execute(Connection connection, String sql) throws Exception { // execute(connection, sql, false); // } // Path: embedded-portfolio-logging/src/main/java/org/teiid/example/TeiidEmbeddedPortfolio.java import org.teiid.runtime.JBossLogger; import org.teiid.translator.file.FileExecutionFactory; import org.teiid.translator.jdbc.h2.H2ExecutionFactory; import static org.teiid.example.JDBCUtils.execute; import java.io.InputStreamReader; import java.sql.Connection; import javax.sql.DataSource; import org.h2.tools.RunScript; import org.teiid.logging.LogManager; import org.teiid.resource.adapter.file.FileManagedConnectionFactory; import org.teiid.runtime.EmbeddedConfiguration; import org.teiid.runtime.EmbeddedServer; /* * Copyright Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags and * the COPYRIGHT.txt file distributed with this work. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.teiid.example; @SuppressWarnings("nls") public class TeiidEmbeddedPortfolio { static { LogManager.setLogListener(new JBossLogger()); System.setProperty("java.util.logging.manager", "org.jboss.logmanager.LogManager"); //Optional // String propUrl = TeiidEmbeddedLogging.class.getClassLoader().getResource("logging.properties").toString(); // System.setProperty("logging.configuration", propUrl); } public static void main(String[] args) throws Exception { DataSource ds = EmbeddedHelper.newDataSource("org.h2.Driver", "jdbc:h2:mem://localhost/~/account", "sa", "sa");
RunScript.execute(ds.getConnection(), new InputStreamReader(TeiidEmbeddedPortfolio.class.getClassLoader().getResourceAsStream("data/customer-schema.sql")));
teiid/teiid-embedded-examples
socialmedia-integration/twitter-as-a-datasource/src/main/java/org/teiid/example/TeiidEmbeddedTwitterDataSource.java
// Path: couchbase-as-a-datasource/src/main/java/org/teiid/example/JDBCUtils.java // public static void execute(Connection connection, String sql) throws Exception { // execute(connection, sql, false); // }
import static org.teiid.example.JDBCUtils.execute; import java.sql.Connection; import javax.resource.spi.ConnectionManager; import javax.xml.ws.Service.Mode; import org.teiid.resource.adapter.ws.WSManagedConnectionFactory; import org.teiid.runtime.EmbeddedConfiguration; import org.teiid.runtime.EmbeddedServer; import org.teiid.translator.ws.WSExecutionFactory; import org.teiid.translator.ws.WSExecutionFactory.Binding;
/* * Copyright Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags and * the COPYRIGHT.txt file distributed with this work. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.teiid.example; public class TeiidEmbeddedTwitterDataSource { static { System.setProperty("http.proxyHost", "squid.apac.redhat.com"); System.setProperty("http.proxyPort", "3128"); } public static void main(String[] args) throws Exception { EmbeddedServer server = new EmbeddedServer(); WSExecutionFactory translator = new WSExecutionFactory(); translator.setDefaultBinding(Binding.HTTP); translator.setDefaultServiceMode(Mode.MESSAGE); translator.start(); server.addTranslator("rest", translator); WSManagedConnectionFactory mcf = new WSManagedConnectionFactory(); mcf.setSecurityType("OAuth"); ConnectionManager cm = EmbeddedHelper.createConnectionFactory("picketbox/authentication.conf", "teiid-security-twitter", mcf); server.addConnectionFactory("java:/twitterDS", mcf.createConnectionFactory(cm)); server.start(new EmbeddedConfiguration()); server.deployVDB(TeiidEmbeddedTwitterDataSource.class.getClassLoader().getResourceAsStream("twitter-vdb.xml")); Connection c = server.getDriver().connect("jdbc:teiid:twitter", null);
// Path: couchbase-as-a-datasource/src/main/java/org/teiid/example/JDBCUtils.java // public static void execute(Connection connection, String sql) throws Exception { // execute(connection, sql, false); // } // Path: socialmedia-integration/twitter-as-a-datasource/src/main/java/org/teiid/example/TeiidEmbeddedTwitterDataSource.java import static org.teiid.example.JDBCUtils.execute; import java.sql.Connection; import javax.resource.spi.ConnectionManager; import javax.xml.ws.Service.Mode; import org.teiid.resource.adapter.ws.WSManagedConnectionFactory; import org.teiid.runtime.EmbeddedConfiguration; import org.teiid.runtime.EmbeddedServer; import org.teiid.translator.ws.WSExecutionFactory; import org.teiid.translator.ws.WSExecutionFactory.Binding; /* * Copyright Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags and * the COPYRIGHT.txt file distributed with this work. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.teiid.example; public class TeiidEmbeddedTwitterDataSource { static { System.setProperty("http.proxyHost", "squid.apac.redhat.com"); System.setProperty("http.proxyPort", "3128"); } public static void main(String[] args) throws Exception { EmbeddedServer server = new EmbeddedServer(); WSExecutionFactory translator = new WSExecutionFactory(); translator.setDefaultBinding(Binding.HTTP); translator.setDefaultServiceMode(Mode.MESSAGE); translator.start(); server.addTranslator("rest", translator); WSManagedConnectionFactory mcf = new WSManagedConnectionFactory(); mcf.setSecurityType("OAuth"); ConnectionManager cm = EmbeddedHelper.createConnectionFactory("picketbox/authentication.conf", "teiid-security-twitter", mcf); server.addConnectionFactory("java:/twitterDS", mcf.createConnectionFactory(cm)); server.start(new EmbeddedConfiguration()); server.deployVDB(TeiidEmbeddedTwitterDataSource.class.getClassLoader().getResourceAsStream("twitter-vdb.xml")); Connection c = server.getDriver().connect("jdbc:teiid:twitter", null);
execute(c, "select * from TwitterUserTimelineView", true);
teiid/teiid-embedded-examples
soapservice-as-a-datasource/src/main/java/org/teiid/example/TeiidEmbeddedGenericSoap.java
// Path: couchbase-as-a-datasource/src/main/java/org/teiid/example/JDBCUtils.java // public static void execute(Connection connection, String sql) throws Exception { // execute(connection, sql, false); // }
import static org.teiid.example.JDBCUtils.execute; import java.sql.Connection; import org.teiid.resource.adapter.ws.WSManagedConnectionFactory; import org.teiid.runtime.EmbeddedConfiguration; import org.teiid.runtime.EmbeddedServer; import org.teiid.translator.ws.WSExecutionFactory;
/* * Copyright Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags and * the COPYRIGHT.txt file distributed with this work. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.teiid.example; /** * This example shows invoking a generic soap service. * */ @SuppressWarnings("nls") public class TeiidEmbeddedGenericSoap { public static void main(String[] args) throws Exception { EmbeddedServer es = new EmbeddedServer(); WSExecutionFactory ef = new WSExecutionFactory(); ef.start(); es.addTranslator("translator-ws", ef); //add a connection factory WSManagedConnectionFactory wsmcf = new WSManagedConnectionFactory(); es.addConnectionFactory("java:/StateServiceWebSvcSource", wsmcf.createConnectionFactory()); es.start(new EmbeddedConfiguration()); es.deployVDB(TeiidEmbeddedGenericSoap.class.getClassLoader().getResourceAsStream("webservice-vdb.xml")); Connection c = es.getDriver().connect("jdbc:teiid:StateServiceVDB", null); //This assume 'stateService' run on localhost
// Path: couchbase-as-a-datasource/src/main/java/org/teiid/example/JDBCUtils.java // public static void execute(Connection connection, String sql) throws Exception { // execute(connection, sql, false); // } // Path: soapservice-as-a-datasource/src/main/java/org/teiid/example/TeiidEmbeddedGenericSoap.java import static org.teiid.example.JDBCUtils.execute; import java.sql.Connection; import org.teiid.resource.adapter.ws.WSManagedConnectionFactory; import org.teiid.runtime.EmbeddedConfiguration; import org.teiid.runtime.EmbeddedServer; import org.teiid.translator.ws.WSExecutionFactory; /* * Copyright Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags and * the COPYRIGHT.txt file distributed with this work. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.teiid.example; /** * This example shows invoking a generic soap service. * */ @SuppressWarnings("nls") public class TeiidEmbeddedGenericSoap { public static void main(String[] args) throws Exception { EmbeddedServer es = new EmbeddedServer(); WSExecutionFactory ef = new WSExecutionFactory(); ef.start(); es.addTranslator("translator-ws", ef); //add a connection factory WSManagedConnectionFactory wsmcf = new WSManagedConnectionFactory(); es.addConnectionFactory("java:/StateServiceWebSvcSource", wsmcf.createConnectionFactory()); es.start(new EmbeddedConfiguration()); es.deployVDB(TeiidEmbeddedGenericSoap.class.getClassLoader().getResourceAsStream("webservice-vdb.xml")); Connection c = es.getDriver().connect("jdbc:teiid:StateServiceVDB", null); //This assume 'stateService' run on localhost
execute(c, "EXEC GetStateInfo('CA', 'http://localhost:8080/stateService?wsdl')", false);
teiid/teiid-embedded-examples
restservice-as-a-datasource/src/main/java/org/teiid/example/TeiidEmbeddedRestWebServiceDataSource.java
// Path: couchbase-as-a-datasource/src/main/java/org/teiid/example/JDBCUtils.java // public static void execute(Connection connection, String sql) throws Exception { // execute(connection, sql, false); // }
import static org.teiid.example.JDBCUtils.execute; import java.sql.Connection; import org.teiid.resource.adapter.ws.WSManagedConnectionFactory; import org.teiid.runtime.EmbeddedConfiguration; import org.teiid.runtime.EmbeddedServer; import org.teiid.translator.ws.WSExecutionFactory;
/* * Copyright Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags and * the COPYRIGHT.txt file distributed with this work. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.teiid.example; @SuppressWarnings("nls") public class TeiidEmbeddedRestWebServiceDataSource { public static void main(String[] args) throws Exception { EmbeddedServer server = new EmbeddedServer(); WSExecutionFactory factory = new WSExecutionFactory(); factory.start(); server.addTranslator("translator-rest", factory); WSManagedConnectionFactory managedconnectionFactory = new WSManagedConnectionFactory(); server.addConnectionFactory("java:/CustomerRESTWebSvcSource", managedconnectionFactory.createConnectionFactory()); server.start(new EmbeddedConfiguration()); server.deployVDB(TeiidEmbeddedRestWebServiceDataSource.class.getClassLoader().getResourceAsStream("restwebservice-vdb.xml")); Connection c = server.getDriver().connect("jdbc:teiid:restwebservice", null);
// Path: couchbase-as-a-datasource/src/main/java/org/teiid/example/JDBCUtils.java // public static void execute(Connection connection, String sql) throws Exception { // execute(connection, sql, false); // } // Path: restservice-as-a-datasource/src/main/java/org/teiid/example/TeiidEmbeddedRestWebServiceDataSource.java import static org.teiid.example.JDBCUtils.execute; import java.sql.Connection; import org.teiid.resource.adapter.ws.WSManagedConnectionFactory; import org.teiid.runtime.EmbeddedConfiguration; import org.teiid.runtime.EmbeddedServer; import org.teiid.translator.ws.WSExecutionFactory; /* * Copyright Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags and * the COPYRIGHT.txt file distributed with this work. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.teiid.example; @SuppressWarnings("nls") public class TeiidEmbeddedRestWebServiceDataSource { public static void main(String[] args) throws Exception { EmbeddedServer server = new EmbeddedServer(); WSExecutionFactory factory = new WSExecutionFactory(); factory.start(); server.addTranslator("translator-rest", factory); WSManagedConnectionFactory managedconnectionFactory = new WSManagedConnectionFactory(); server.addConnectionFactory("java:/CustomerRESTWebSvcSource", managedconnectionFactory.createConnectionFactory()); server.start(new EmbeddedConfiguration()); server.deployVDB(TeiidEmbeddedRestWebServiceDataSource.class.getClassLoader().getResourceAsStream("restwebservice-vdb.xml")); Connection c = server.getDriver().connect("jdbc:teiid:restwebservice", null);
execute(c, "EXEC getCustomer('http://localhost:8080/customer/customerList')", false);
teiid/teiid-embedded-examples
drools-integration/src/main/java/org/teiid/example/TeiidEmbeddedDroolsIntegration.java
// Path: couchbase-as-a-datasource/src/main/java/org/teiid/example/JDBCUtils.java // public static void execute(Connection connection, String sql) throws Exception { // execute(connection, sql, false); // }
import org.teiid.runtime.EmbeddedServer; import static org.teiid.example.JDBCUtils.execute; import java.sql.Connection; import org.teiid.runtime.EmbeddedConfiguration;
/* * Copyright Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags and * the COPYRIGHT.txt file distributed with this work. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.teiid.example; public class TeiidEmbeddedDroolsIntegration { public static void main(String[] args) throws Exception { EmbeddedServer server = new EmbeddedServer(); server.start(new EmbeddedConfiguration()); server.deployVDB(TeiidEmbeddedDroolsIntegration.class.getClassLoader().getResourceAsStream("drools-vdb.xml")); Connection c = server.getDriver().connect("jdbc:teiid:droolsVDB", null);
// Path: couchbase-as-a-datasource/src/main/java/org/teiid/example/JDBCUtils.java // public static void execute(Connection connection, String sql) throws Exception { // execute(connection, sql, false); // } // Path: drools-integration/src/main/java/org/teiid/example/TeiidEmbeddedDroolsIntegration.java import org.teiid.runtime.EmbeddedServer; import static org.teiid.example.JDBCUtils.execute; import java.sql.Connection; import org.teiid.runtime.EmbeddedConfiguration; /* * Copyright Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags and * the COPYRIGHT.txt file distributed with this work. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.teiid.example; public class TeiidEmbeddedDroolsIntegration { public static void main(String[] args) throws Exception { EmbeddedServer server = new EmbeddedServer(); server.start(new EmbeddedConfiguration()); server.deployVDB(TeiidEmbeddedDroolsIntegration.class.getClassLoader().getResourceAsStream("drools-vdb.xml")); Connection c = server.getDriver().connect("jdbc:teiid:droolsVDB", null);
execute(c, "SELECT performRuleOnData('org.teiid.example.drools.Message', 'Hello World', 0)", true);
teiid/teiid-embedded-examples
embedded-portfolio-security/src/main/java/org/teiid/example/TeiidEmbeddedPortfolioSecurity.java
// Path: couchbase-as-a-datasource/src/main/java/org/teiid/example/JDBCUtils.java // public static void execute(Connection connection, String sql) throws Exception { // execute(connection, sql, false); // }
import org.teiid.runtime.EmbeddedConfiguration; import org.teiid.runtime.EmbeddedServer; import org.teiid.translator.file.FileExecutionFactory; import org.teiid.translator.jdbc.h2.H2ExecutionFactory; import static org.teiid.example.JDBCUtils.execute; import java.io.InputStreamReader; import java.sql.Connection; import java.util.Properties; import java.util.logging.Level; import javax.sql.DataSource; import org.h2.tools.RunScript; import org.teiid.jdbc.TeiidSQLException; import org.teiid.resource.adapter.file.FileManagedConnectionFactory;
/* * Copyright Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags and * the COPYRIGHT.txt file distributed with this work. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.teiid.example; /** * This example is show security authentication in Teiid Embedded */ @SuppressWarnings("nls") public class TeiidEmbeddedPortfolioSecurity { public static void main(String[] args) throws Exception { EmbeddedHelper.enableLogger(Level.OFF); DataSource ds = EmbeddedHelper.newDataSource("org.h2.Driver", "jdbc:h2:mem://localhost/~/account", "sa", "sa");
// Path: couchbase-as-a-datasource/src/main/java/org/teiid/example/JDBCUtils.java // public static void execute(Connection connection, String sql) throws Exception { // execute(connection, sql, false); // } // Path: embedded-portfolio-security/src/main/java/org/teiid/example/TeiidEmbeddedPortfolioSecurity.java import org.teiid.runtime.EmbeddedConfiguration; import org.teiid.runtime.EmbeddedServer; import org.teiid.translator.file.FileExecutionFactory; import org.teiid.translator.jdbc.h2.H2ExecutionFactory; import static org.teiid.example.JDBCUtils.execute; import java.io.InputStreamReader; import java.sql.Connection; import java.util.Properties; import java.util.logging.Level; import javax.sql.DataSource; import org.h2.tools.RunScript; import org.teiid.jdbc.TeiidSQLException; import org.teiid.resource.adapter.file.FileManagedConnectionFactory; /* * Copyright Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags and * the COPYRIGHT.txt file distributed with this work. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.teiid.example; /** * This example is show security authentication in Teiid Embedded */ @SuppressWarnings("nls") public class TeiidEmbeddedPortfolioSecurity { public static void main(String[] args) throws Exception { EmbeddedHelper.enableLogger(Level.OFF); DataSource ds = EmbeddedHelper.newDataSource("org.h2.Driver", "jdbc:h2:mem://localhost/~/account", "sa", "sa");
RunScript.execute(ds.getConnection(), new InputStreamReader(TeiidEmbeddedPortfolioSecurity.class.getClassLoader().getResourceAsStream("data/customer-schema.sql")));
teiid/teiid-embedded-examples
embedded-caching/src/main/java/org/teiid/example/TeiidEmbeddedCaching.java
// Path: embedded-caching/src/main/java/org/teiid/example/H2PERFTESTClient.java // public static final int MB = 1<<20;
import static org.teiid.example.H2PERFTESTClient.MB; import java.util.logging.Level;
/* * Copyright Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags and * the COPYRIGHT.txt file distributed with this work. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.teiid.example; @SuppressWarnings("nls") public class TeiidEmbeddedCaching { public static void main(String[] args) throws Exception { EmbeddedHelper.enableLogger(Level.OFF);
// Path: embedded-caching/src/main/java/org/teiid/example/H2PERFTESTClient.java // public static final int MB = 1<<20; // Path: embedded-caching/src/main/java/org/teiid/example/TeiidEmbeddedCaching.java import static org.teiid.example.H2PERFTESTClient.MB; import java.util.logging.Level; /* * Copyright Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags and * the COPYRIGHT.txt file distributed with this work. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.teiid.example; @SuppressWarnings("nls") public class TeiidEmbeddedCaching { public static void main(String[] args) throws Exception { EmbeddedHelper.enableLogger(Level.OFF);
H2PERFTESTClient.insert(MB);
teiid/teiid-embedded-examples
excel-as-a-datasource/src/main/java/org/teiid/example/TeiidEmbeddedExcelDataSource.java
// Path: couchbase-as-a-datasource/src/main/java/org/teiid/example/JDBCUtils.java // public static void execute(Connection connection, String sql) throws Exception { // execute(connection, sql, false); // }
import static org.teiid.example.JDBCUtils.execute; import java.sql.Connection; import org.teiid.resource.adapter.file.FileManagedConnectionFactory; import org.teiid.runtime.EmbeddedConfiguration; import org.teiid.runtime.EmbeddedServer; import org.teiid.translator.excel.ExcelExecutionFactory;
/* * Copyright Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags and * the COPYRIGHT.txt file distributed with this work. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.teiid.example; @SuppressWarnings("nls") public class TeiidEmbeddedExcelDataSource { public static void main(String[] args) throws Exception { EmbeddedServer server = new EmbeddedServer(); ExcelExecutionFactory factory = new ExcelExecutionFactory(); factory.start(); factory.setSupportsDirectQueryProcedure(true); server.addTranslator("excel", factory); FileManagedConnectionFactory managedconnectionFactory = new FileManagedConnectionFactory(); managedconnectionFactory.setParentDirectory("src/main/resources/data"); server.addConnectionFactory("java:/excel-file", managedconnectionFactory.createConnectionFactory()); server.start(new EmbeddedConfiguration()); server.deployVDB(TeiidEmbeddedExcelDataSource.class.getClassLoader().getResourceAsStream("excel-vdb.xml")); Connection c = server.getDriver().connect("jdbc:teiid:ExcelVDB", null);
// Path: couchbase-as-a-datasource/src/main/java/org/teiid/example/JDBCUtils.java // public static void execute(Connection connection, String sql) throws Exception { // execute(connection, sql, false); // } // Path: excel-as-a-datasource/src/main/java/org/teiid/example/TeiidEmbeddedExcelDataSource.java import static org.teiid.example.JDBCUtils.execute; import java.sql.Connection; import org.teiid.resource.adapter.file.FileManagedConnectionFactory; import org.teiid.runtime.EmbeddedConfiguration; import org.teiid.runtime.EmbeddedServer; import org.teiid.translator.excel.ExcelExecutionFactory; /* * Copyright Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags and * the COPYRIGHT.txt file distributed with this work. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.teiid.example; @SuppressWarnings("nls") public class TeiidEmbeddedExcelDataSource { public static void main(String[] args) throws Exception { EmbeddedServer server = new EmbeddedServer(); ExcelExecutionFactory factory = new ExcelExecutionFactory(); factory.start(); factory.setSupportsDirectQueryProcedure(true); server.addTranslator("excel", factory); FileManagedConnectionFactory managedconnectionFactory = new FileManagedConnectionFactory(); managedconnectionFactory.setParentDirectory("src/main/resources/data"); server.addConnectionFactory("java:/excel-file", managedconnectionFactory.createConnectionFactory()); server.start(new EmbeddedConfiguration()); server.deployVDB(TeiidEmbeddedExcelDataSource.class.getClassLoader().getResourceAsStream("excel-vdb.xml")); Connection c = server.getDriver().connect("jdbc:teiid:ExcelVDB", null);
execute(c, "SELECT * FROM Sheet1", false);
teiid/teiid-embedded-examples
bigdata-integration/hbase-as-a-datasource/src/main/java/org/teiid/example/TeiidEmbeddedHBaseDataSource.java
// Path: couchbase-as-a-datasource/src/main/java/org/teiid/example/JDBCUtils.java // public static void execute(Connection connection, String sql) throws Exception { // execute(connection, sql, false); // }
import static org.teiid.example.JDBCUtils.execute; import java.sql.Connection; import javax.sql.DataSource; import org.teiid.runtime.EmbeddedConfiguration; import org.teiid.runtime.EmbeddedServer; import org.teiid.translator.phoenix.PhoenixExecutionFactory;
/* * Copyright Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags and * the COPYRIGHT.txt file distributed with this work. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.teiid.example; @SuppressWarnings("nls") public class TeiidEmbeddedHBaseDataSource { public static void main(String[] args) throws Exception { DataSource ds = EmbeddedHelper.newDataSource(JDBC_DRIVER, JDBC_URL, JDBC_USER, JDBC_PASS, "phoenix.connection.autoCommit=true"); initSamplesData(ds); EmbeddedServer server = new EmbeddedServer(); PhoenixExecutionFactory factory = new PhoenixExecutionFactory(); factory.start(); server.addTranslator("translator-hbase", factory); server.addConnectionFactory("java:/hbaseDS", ds); EmbeddedConfiguration config = new EmbeddedConfiguration(); config.setTransactionManager(EmbeddedHelper.getTransactionManager()); server.start(config); server.deployVDB(TeiidEmbeddedHBaseDataSource.class.getClassLoader().getResourceAsStream("hbase-vdb.xml")); Connection c = server.getDriver().connect("jdbc:teiid:hbasevdb", null);
// Path: couchbase-as-a-datasource/src/main/java/org/teiid/example/JDBCUtils.java // public static void execute(Connection connection, String sql) throws Exception { // execute(connection, sql, false); // } // Path: bigdata-integration/hbase-as-a-datasource/src/main/java/org/teiid/example/TeiidEmbeddedHBaseDataSource.java import static org.teiid.example.JDBCUtils.execute; import java.sql.Connection; import javax.sql.DataSource; import org.teiid.runtime.EmbeddedConfiguration; import org.teiid.runtime.EmbeddedServer; import org.teiid.translator.phoenix.PhoenixExecutionFactory; /* * Copyright Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags and * the COPYRIGHT.txt file distributed with this work. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.teiid.example; @SuppressWarnings("nls") public class TeiidEmbeddedHBaseDataSource { public static void main(String[] args) throws Exception { DataSource ds = EmbeddedHelper.newDataSource(JDBC_DRIVER, JDBC_URL, JDBC_USER, JDBC_PASS, "phoenix.connection.autoCommit=true"); initSamplesData(ds); EmbeddedServer server = new EmbeddedServer(); PhoenixExecutionFactory factory = new PhoenixExecutionFactory(); factory.start(); server.addTranslator("translator-hbase", factory); server.addConnectionFactory("java:/hbaseDS", ds); EmbeddedConfiguration config = new EmbeddedConfiguration(); config.setTransactionManager(EmbeddedHelper.getTransactionManager()); server.start(config); server.deployVDB(TeiidEmbeddedHBaseDataSource.class.getClassLoader().getResourceAsStream("hbase-vdb.xml")); Connection c = server.getDriver().connect("jdbc:teiid:hbasevdb", null);
execute(c, "SELECT * FROM Customer", false);
teiid/teiid-embedded-examples
soapservice-as-a-datasource/stateService/src/main/java/org/teiid/stateservice/StateServiceImpl.java
// Path: soapservice-as-a-datasource/stateService/src/main/java/org/teiid/stateservice/StateService.java // @WebService(targetNamespace = "http://www.teiid.org/stateService/", name = "stateService") // @XmlSeeAlso({ObjectFactory.class}) // public interface StateService { // // @WebResult(name = "AllStateInfo", targetNamespace = "") // @RequestWrapper(localName = "GetAllStateInfo", targetNamespace = "http://www.teiid.org/stateService/", className = "org.teiid.stateservice.GetAllStateInfo") // @ResponseWrapper(localName = "GetAllStateInfoResponse", targetNamespace = "http://www.teiid.org/stateService/", className = "org.teiid.stateservice.GetAllStateInfoResponse") // @WebMethod(operationName = "GetAllStateInfo", action = "http://www.teiid.org/stateService/GetStateInfo") // public java.util.List<org.teiid.stateservice.jaxb.StateInfo> getAllStateInfo(); // // @WebResult(name = "StateInfo", targetNamespace = "") // @RequestWrapper(localName = "GetStateInfo", targetNamespace = "http://www.teiid.org/stateService/", className = "org.teiid.stateservice.GetStateInfo") // @ResponseWrapper(localName = "GetStateInfoResponse", targetNamespace = "http://www.teiid.org/stateService/", className = "org.teiid.stateservice.GetStateInfoResponse") // @WebMethod(operationName = "GetStateInfo", action = "http://www.teiid.org/stateService/GetStateInfo") // public org.teiid.stateservice.jaxb.StateInfo getStateInfo( // @WebParam(name = "stateCode", targetNamespace = "") // java.lang.String stateCode // ) throws GetStateInfoFault_Exception; // } // // Path: soapservice-as-a-datasource/stateService/src/main/java/org/teiid/stateservice/jaxb/StateInfo.java // @XmlAccessorType(XmlAccessType.FIELD) // @XmlType(name = "StateInfo", propOrder = { // "name", // "abbreviation", // "capital", // "yearOfStatehood" // }) // public class StateInfo { // // @XmlElement(name = "Name", required = true) // protected String name; // @XmlElement(name = "Abbreviation", required = true) // protected String abbreviation; // @XmlElement(name = "Capital", required = true) // protected String capital; // @XmlElement(name = "YearOfStatehood", required = true) // protected BigInteger yearOfStatehood; // // public StateInfo(){ // } // // public StateInfo(String name, String abbrev, String year, String capital) { // setName(name); // setAbbreviation(abbrev); // setYearOfStatehood(new BigInteger(year)); // setCapital(capital); // } // // /** // * Gets the value of the name property. // * // * @return // * possible object is // * {@link String } // * // */ // public String getName() { // return name; // } // // /** // * Sets the value of the name property. // * // * @param value // * allowed object is // * {@link String } // * // */ // public void setName(String value) { // this.name = value; // } // // /** // * Gets the value of the abbreviation property. // * // * @return // * possible object is // * {@link String } // * // */ // public String getAbbreviation() { // return abbreviation; // } // // /** // * Sets the value of the abbreviation property. // * // * @param value // * allowed object is // * {@link String } // * // */ // public void setAbbreviation(String value) { // this.abbreviation = value; // } // // /** // * Gets the value of the capital property. // * // * @return // * possible object is // * {@link String } // * // */ // public String getCapital() { // return capital; // } // // /** // * Sets the value of the capital property. // * // * @param value // * allowed object is // * {@link String } // * // */ // public void setCapital(String value) { // this.capital = value; // } // // /** // * Gets the value of the yearOfStatehood property. // * // * @return // * possible object is // * {@link BigInteger } // * // */ // public BigInteger getYearOfStatehood() { // return yearOfStatehood; // } // // /** // * Sets the value of the yearOfStatehood property. // * // * @param value // * allowed object is // * {@link BigInteger } // * // */ // public void setYearOfStatehood(BigInteger value) { // this.yearOfStatehood = value; // } // // }
import org.teiid.stateservice.StateService; import org.teiid.stateservice.jaxb.StateInfo; import javax.jws.WebService;
/* * Copyright Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags and * the COPYRIGHT.txt file distributed with this work. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.teiid.stateservice; @WebService(serviceName = "stateService", endpointInterface = "org.teiid.stateservice.StateService", targetNamespace = "http://www.teiid.org/stateService/") public class StateServiceImpl implements StateService { StateData stateData = new StateData();
// Path: soapservice-as-a-datasource/stateService/src/main/java/org/teiid/stateservice/StateService.java // @WebService(targetNamespace = "http://www.teiid.org/stateService/", name = "stateService") // @XmlSeeAlso({ObjectFactory.class}) // public interface StateService { // // @WebResult(name = "AllStateInfo", targetNamespace = "") // @RequestWrapper(localName = "GetAllStateInfo", targetNamespace = "http://www.teiid.org/stateService/", className = "org.teiid.stateservice.GetAllStateInfo") // @ResponseWrapper(localName = "GetAllStateInfoResponse", targetNamespace = "http://www.teiid.org/stateService/", className = "org.teiid.stateservice.GetAllStateInfoResponse") // @WebMethod(operationName = "GetAllStateInfo", action = "http://www.teiid.org/stateService/GetStateInfo") // public java.util.List<org.teiid.stateservice.jaxb.StateInfo> getAllStateInfo(); // // @WebResult(name = "StateInfo", targetNamespace = "") // @RequestWrapper(localName = "GetStateInfo", targetNamespace = "http://www.teiid.org/stateService/", className = "org.teiid.stateservice.GetStateInfo") // @ResponseWrapper(localName = "GetStateInfoResponse", targetNamespace = "http://www.teiid.org/stateService/", className = "org.teiid.stateservice.GetStateInfoResponse") // @WebMethod(operationName = "GetStateInfo", action = "http://www.teiid.org/stateService/GetStateInfo") // public org.teiid.stateservice.jaxb.StateInfo getStateInfo( // @WebParam(name = "stateCode", targetNamespace = "") // java.lang.String stateCode // ) throws GetStateInfoFault_Exception; // } // // Path: soapservice-as-a-datasource/stateService/src/main/java/org/teiid/stateservice/jaxb/StateInfo.java // @XmlAccessorType(XmlAccessType.FIELD) // @XmlType(name = "StateInfo", propOrder = { // "name", // "abbreviation", // "capital", // "yearOfStatehood" // }) // public class StateInfo { // // @XmlElement(name = "Name", required = true) // protected String name; // @XmlElement(name = "Abbreviation", required = true) // protected String abbreviation; // @XmlElement(name = "Capital", required = true) // protected String capital; // @XmlElement(name = "YearOfStatehood", required = true) // protected BigInteger yearOfStatehood; // // public StateInfo(){ // } // // public StateInfo(String name, String abbrev, String year, String capital) { // setName(name); // setAbbreviation(abbrev); // setYearOfStatehood(new BigInteger(year)); // setCapital(capital); // } // // /** // * Gets the value of the name property. // * // * @return // * possible object is // * {@link String } // * // */ // public String getName() { // return name; // } // // /** // * Sets the value of the name property. // * // * @param value // * allowed object is // * {@link String } // * // */ // public void setName(String value) { // this.name = value; // } // // /** // * Gets the value of the abbreviation property. // * // * @return // * possible object is // * {@link String } // * // */ // public String getAbbreviation() { // return abbreviation; // } // // /** // * Sets the value of the abbreviation property. // * // * @param value // * allowed object is // * {@link String } // * // */ // public void setAbbreviation(String value) { // this.abbreviation = value; // } // // /** // * Gets the value of the capital property. // * // * @return // * possible object is // * {@link String } // * // */ // public String getCapital() { // return capital; // } // // /** // * Sets the value of the capital property. // * // * @param value // * allowed object is // * {@link String } // * // */ // public void setCapital(String value) { // this.capital = value; // } // // /** // * Gets the value of the yearOfStatehood property. // * // * @return // * possible object is // * {@link BigInteger } // * // */ // public BigInteger getYearOfStatehood() { // return yearOfStatehood; // } // // /** // * Sets the value of the yearOfStatehood property. // * // * @param value // * allowed object is // * {@link BigInteger } // * // */ // public void setYearOfStatehood(BigInteger value) { // this.yearOfStatehood = value; // } // // } // Path: soapservice-as-a-datasource/stateService/src/main/java/org/teiid/stateservice/StateServiceImpl.java import org.teiid.stateservice.StateService; import org.teiid.stateservice.jaxb.StateInfo; import javax.jws.WebService; /* * Copyright Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags and * the COPYRIGHT.txt file distributed with this work. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.teiid.stateservice; @WebService(serviceName = "stateService", endpointInterface = "org.teiid.stateservice.StateService", targetNamespace = "http://www.teiid.org/stateService/") public class StateServiceImpl implements StateService { StateData stateData = new StateData();
public java.util.List<org.teiid.stateservice.jaxb.StateInfo> getAllStateInfo() {
teiid/teiid-embedded-examples
bigdata-integration/spark-integration-hive/src/main/java/org/teiid/example/TeiidEmbeddedSparkDataSource.java
// Path: couchbase-as-a-datasource/src/main/java/org/teiid/example/JDBCUtils.java // public static void execute(Connection connection, String sql) throws Exception { // execute(connection, sql, false); // }
import static org.teiid.example.JDBCUtils.execute; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.util.Properties; import javax.sql.DataSource; import org.teiid.runtime.EmbeddedConfiguration; import org.teiid.runtime.EmbeddedServer; import org.teiid.translator.hive.HiveExecutionFactory;
/* * Copyright Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags and * the COPYRIGHT.txt file distributed with this work. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.teiid.example; public class TeiidEmbeddedSparkDataSource { static String JDBC_DRIVER = "org.apache.hive.jdbc.HiveDriver"; static String JDBC_URL = "jdbc:hive2://127.0.0.1:10000/default"; static String JDBC_USER = "hive"; static String JDBC_PASS = ""; public static void main(String[] args) throws Exception { initDBProperties(); DataSource ds = EmbeddedHelper.newDataSource(JDBC_DRIVER, JDBC_URL, JDBC_USER, JDBC_PASS); EmbeddedServer server = new EmbeddedServer(); HiveExecutionFactory factory = new HiveExecutionFactory(); factory.start(); server.addTranslator("translator-hive", factory); server.addConnectionFactory("java:/hiveDS", ds); EmbeddedConfiguration config = new EmbeddedConfiguration(); config.setTransactionManager(EmbeddedHelper.getTransactionManager()); server.start(config); server.deployVDB(TeiidEmbeddedSparkDataSource.class.getClassLoader().getResourceAsStream("hive-vdb.xml")); Connection c = server.getDriver().connect("jdbc:teiid:hivevdb", null);
// Path: couchbase-as-a-datasource/src/main/java/org/teiid/example/JDBCUtils.java // public static void execute(Connection connection, String sql) throws Exception { // execute(connection, sql, false); // } // Path: bigdata-integration/spark-integration-hive/src/main/java/org/teiid/example/TeiidEmbeddedSparkDataSource.java import static org.teiid.example.JDBCUtils.execute; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.util.Properties; import javax.sql.DataSource; import org.teiid.runtime.EmbeddedConfiguration; import org.teiid.runtime.EmbeddedServer; import org.teiid.translator.hive.HiveExecutionFactory; /* * Copyright Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags and * the COPYRIGHT.txt file distributed with this work. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.teiid.example; public class TeiidEmbeddedSparkDataSource { static String JDBC_DRIVER = "org.apache.hive.jdbc.HiveDriver"; static String JDBC_URL = "jdbc:hive2://127.0.0.1:10000/default"; static String JDBC_USER = "hive"; static String JDBC_PASS = ""; public static void main(String[] args) throws Exception { initDBProperties(); DataSource ds = EmbeddedHelper.newDataSource(JDBC_DRIVER, JDBC_URL, JDBC_USER, JDBC_PASS); EmbeddedServer server = new EmbeddedServer(); HiveExecutionFactory factory = new HiveExecutionFactory(); factory.start(); server.addTranslator("translator-hive", factory); server.addConnectionFactory("java:/hiveDS", ds); EmbeddedConfiguration config = new EmbeddedConfiguration(); config.setTransactionManager(EmbeddedHelper.getTransactionManager()); server.start(config); server.deployVDB(TeiidEmbeddedSparkDataSource.class.getClassLoader().getResourceAsStream("hive-vdb.xml")); Connection c = server.getDriver().connect("jdbc:teiid:hivevdb", null);
execute(c, "SELECT * FROM FOO", false);
teiid/teiid-embedded-examples
ldap-as-a-datasource/src/main/java/org/teiid/example/TeiidEmbeddedLDAPDataSource.java
// Path: couchbase-as-a-datasource/src/main/java/org/teiid/example/JDBCUtils.java // public static void execute(Connection connection, String sql) throws Exception { // execute(connection, sql, false); // }
import static org.teiid.example.JDBCUtils.execute; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.util.Properties; import org.teiid.resource.adapter.ldap.LDAPManagedConnectionFactory; import org.teiid.runtime.EmbeddedConfiguration; import org.teiid.runtime.EmbeddedServer; import org.teiid.translator.ldap.LDAPExecutionFactory;
/* * Copyright Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags and * the COPYRIGHT.txt file distributed with this work. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.teiid.example; @SuppressWarnings("nls") public class TeiidEmbeddedLDAPDataSource { private static String ldapUrl = "ldap://127.0.0.1:389"; private static String ldapAdminUserDN = "cn=Manager,dc=example,dc=com"; private static String ldapAdminPassword = "redhat"; public static void main(String[] args) throws Exception { initLDAPProperties(); EmbeddedServer server = new EmbeddedServer(); LDAPExecutionFactory factory = new LDAPExecutionFactory(); factory.start(); server.addTranslator("translator-ldap", factory); LDAPManagedConnectionFactory managedconnectionFactory = new LDAPManagedConnectionFactory(); managedconnectionFactory.setLdapUrl(ldapUrl); managedconnectionFactory.setLdapAdminUserDN(ldapAdminUserDN); managedconnectionFactory.setLdapAdminUserPassword(ldapAdminPassword); server.addConnectionFactory("java:/ldapDS", managedconnectionFactory.createConnectionFactory()); server.start(new EmbeddedConfiguration()); server.deployVDB(TeiidEmbeddedLDAPDataSource.class.getClassLoader().getResourceAsStream("ldap-vdb.xml")); Connection c = server.getDriver().connect("jdbc:teiid:ldapVDB", null);
// Path: couchbase-as-a-datasource/src/main/java/org/teiid/example/JDBCUtils.java // public static void execute(Connection connection, String sql) throws Exception { // execute(connection, sql, false); // } // Path: ldap-as-a-datasource/src/main/java/org/teiid/example/TeiidEmbeddedLDAPDataSource.java import static org.teiid.example.JDBCUtils.execute; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.util.Properties; import org.teiid.resource.adapter.ldap.LDAPManagedConnectionFactory; import org.teiid.runtime.EmbeddedConfiguration; import org.teiid.runtime.EmbeddedServer; import org.teiid.translator.ldap.LDAPExecutionFactory; /* * Copyright Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags and * the COPYRIGHT.txt file distributed with this work. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.teiid.example; @SuppressWarnings("nls") public class TeiidEmbeddedLDAPDataSource { private static String ldapUrl = "ldap://127.0.0.1:389"; private static String ldapAdminUserDN = "cn=Manager,dc=example,dc=com"; private static String ldapAdminPassword = "redhat"; public static void main(String[] args) throws Exception { initLDAPProperties(); EmbeddedServer server = new EmbeddedServer(); LDAPExecutionFactory factory = new LDAPExecutionFactory(); factory.start(); server.addTranslator("translator-ldap", factory); LDAPManagedConnectionFactory managedconnectionFactory = new LDAPManagedConnectionFactory(); managedconnectionFactory.setLdapUrl(ldapUrl); managedconnectionFactory.setLdapAdminUserDN(ldapAdminUserDN); managedconnectionFactory.setLdapAdminUserPassword(ldapAdminPassword); server.addConnectionFactory("java:/ldapDS", managedconnectionFactory.createConnectionFactory()); server.start(new EmbeddedConfiguration()); server.deployVDB(TeiidEmbeddedLDAPDataSource.class.getClassLoader().getResourceAsStream("ldap-vdb.xml")); Connection c = server.getDriver().connect("jdbc:teiid:ldapVDB", null);
execute(c, "SELECT * FROM HR_Group", true);
TheFinestArtist/Royal-Android
library/src/androidTest/java/com/thefinestartist/royal/databases/SecondaryDatabase.java
// Path: library/src/main/java/com/thefinestartist/royal/RoyalDatabase.java // public abstract class RoyalDatabase implements RealmMigration { // // public String getFileName() { // return "default"; // } // // public boolean forCache() { // return false; // } // // public byte[] getEncryptionKey() { // return null; // } // // public int getVersion() { // return 0; // } // // public boolean shouldDeleteIfMigrationNeeded() { // return false; // } // // // TODO: change it like getModels // public List<Object> getModules() { // List<Object> modules = new ArrayList<>(); // modules.add(Realm.getDefaultModule()); // return modules; // } // // @Override // public long execute(Realm realm, long version) { // return getVersion(); // } // } // // Path: library/src/androidTest/java/com/thefinestartist/royal/entities/Cat.java // public class Cat extends RealmObject { // private String name; // private long age; // private float height; // private double weight; // private boolean hasTail; // private Date birthday; // private Owner owner; // private DogPrimaryKey scaredOfDog; // // public Owner getOwner() { // return owner; // } // // public void setOwner(Owner owner) { // this.owner = owner; // } // // public Date getBirthday() { // return birthday; // } // // public void setBirthday(Date birthday) { // this.birthday = birthday; // } // // public boolean isHasTail() { // return hasTail; // } // // public void setHasTail(boolean hasTail) { // this.hasTail = hasTail; // } // // // public double getWeight() { // return weight; // } // // public void setWeight(double weight) { // this.weight = weight; // } // // public float getHeight() { // return height; // } // // public void setHeight(float height) { // this.height = height; // } // // public long getAge() { // return age; // } // // public void setAge(long age) { // this.age = age; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public DogPrimaryKey getScaredOfDog() { // return scaredOfDog; // } // // public void setScaredOfDog(DogPrimaryKey scaredOfDog) { // this.scaredOfDog = scaredOfDog; // } // } // // Path: library/src/androidTest/java/com/thefinestartist/royal/entities/Dog.java // public class Dog extends RealmObject { // // @Index // private String name; // private long age; // private float height; // private double weight; // private boolean hasTail; // private Date birthday; // private Owner owner; // // public Dog() { // } // // public Dog(String name) { // this.name = name; // } // // public Owner getOwner() { // return owner; // } // // public void setOwner(Owner owner) { // this.owner = owner; // } // // public Date getBirthday() { // return birthday; // } // // public void setBirthday(Date birthday) { // this.birthday = birthday; // } // // public boolean isHasTail() { // return hasTail; // } // // public void setHasTail(boolean hasTail) { // this.hasTail = hasTail; // } // // public double getWeight() { // return weight; // } // // public void setWeight(double weight) { // this.weight = weight; // } // // public float getHeight() { // return height; // } // // public void setHeight(float height) { // this.height = height; // } // // public long getAge() { // return age; // } // // public void setAge(long age) { // this.age = age; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public static String getStaticName(Dog dog) { // return dog.name; // } // } // // Path: library/src/androidTest/java/com/thefinestartist/royal/entities/Owner.java // public class Owner extends RealmObject { // private String name; // private RealmList<Dog> dogs; // private Cat cat; // // public Cat getCat() { // return cat; // } // // public void setCat(Cat cat) { // this.cat = cat; // } // // public RealmList<Dog> getDogs() { // return dogs; // } // // public void setDogs(RealmList<Dog> dogs) { // this.dogs = dogs; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // }
import com.thefinestartist.royal.RoyalDatabase; import com.thefinestartist.royal.entities.Cat; import com.thefinestartist.royal.entities.Dog; import com.thefinestartist.royal.entities.Owner; import java.util.HashSet; import java.util.Set; import io.realm.Realm; import io.realm.annotations.RealmModule;
package com.thefinestartist.royal.databases; /** * Created by TheFinestArtist on 7/12/15. */ public class SecondaryDatabase extends RoyalDatabase { public String getFileName() { return "secondary"; } public boolean forCache() { return false; } public byte[] getEncryptionKey() { return null; } public int getVersion() { return 0; } public boolean shouldDeleteIfMigrationNeeded() { return false; } public Set<Object> getModules() { Set<Object> set = new HashSet<>(); set.add(new SecondaryModule()); return set; } @Override public long execute(Realm realm, long version) { return getVersion(); }
// Path: library/src/main/java/com/thefinestartist/royal/RoyalDatabase.java // public abstract class RoyalDatabase implements RealmMigration { // // public String getFileName() { // return "default"; // } // // public boolean forCache() { // return false; // } // // public byte[] getEncryptionKey() { // return null; // } // // public int getVersion() { // return 0; // } // // public boolean shouldDeleteIfMigrationNeeded() { // return false; // } // // // TODO: change it like getModels // public List<Object> getModules() { // List<Object> modules = new ArrayList<>(); // modules.add(Realm.getDefaultModule()); // return modules; // } // // @Override // public long execute(Realm realm, long version) { // return getVersion(); // } // } // // Path: library/src/androidTest/java/com/thefinestartist/royal/entities/Cat.java // public class Cat extends RealmObject { // private String name; // private long age; // private float height; // private double weight; // private boolean hasTail; // private Date birthday; // private Owner owner; // private DogPrimaryKey scaredOfDog; // // public Owner getOwner() { // return owner; // } // // public void setOwner(Owner owner) { // this.owner = owner; // } // // public Date getBirthday() { // return birthday; // } // // public void setBirthday(Date birthday) { // this.birthday = birthday; // } // // public boolean isHasTail() { // return hasTail; // } // // public void setHasTail(boolean hasTail) { // this.hasTail = hasTail; // } // // // public double getWeight() { // return weight; // } // // public void setWeight(double weight) { // this.weight = weight; // } // // public float getHeight() { // return height; // } // // public void setHeight(float height) { // this.height = height; // } // // public long getAge() { // return age; // } // // public void setAge(long age) { // this.age = age; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public DogPrimaryKey getScaredOfDog() { // return scaredOfDog; // } // // public void setScaredOfDog(DogPrimaryKey scaredOfDog) { // this.scaredOfDog = scaredOfDog; // } // } // // Path: library/src/androidTest/java/com/thefinestartist/royal/entities/Dog.java // public class Dog extends RealmObject { // // @Index // private String name; // private long age; // private float height; // private double weight; // private boolean hasTail; // private Date birthday; // private Owner owner; // // public Dog() { // } // // public Dog(String name) { // this.name = name; // } // // public Owner getOwner() { // return owner; // } // // public void setOwner(Owner owner) { // this.owner = owner; // } // // public Date getBirthday() { // return birthday; // } // // public void setBirthday(Date birthday) { // this.birthday = birthday; // } // // public boolean isHasTail() { // return hasTail; // } // // public void setHasTail(boolean hasTail) { // this.hasTail = hasTail; // } // // public double getWeight() { // return weight; // } // // public void setWeight(double weight) { // this.weight = weight; // } // // public float getHeight() { // return height; // } // // public void setHeight(float height) { // this.height = height; // } // // public long getAge() { // return age; // } // // public void setAge(long age) { // this.age = age; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public static String getStaticName(Dog dog) { // return dog.name; // } // } // // Path: library/src/androidTest/java/com/thefinestartist/royal/entities/Owner.java // public class Owner extends RealmObject { // private String name; // private RealmList<Dog> dogs; // private Cat cat; // // public Cat getCat() { // return cat; // } // // public void setCat(Cat cat) { // this.cat = cat; // } // // public RealmList<Dog> getDogs() { // return dogs; // } // // public void setDogs(RealmList<Dog> dogs) { // this.dogs = dogs; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // } // Path: library/src/androidTest/java/com/thefinestartist/royal/databases/SecondaryDatabase.java import com.thefinestartist.royal.RoyalDatabase; import com.thefinestartist.royal.entities.Cat; import com.thefinestartist.royal.entities.Dog; import com.thefinestartist.royal.entities.Owner; import java.util.HashSet; import java.util.Set; import io.realm.Realm; import io.realm.annotations.RealmModule; package com.thefinestartist.royal.databases; /** * Created by TheFinestArtist on 7/12/15. */ public class SecondaryDatabase extends RoyalDatabase { public String getFileName() { return "secondary"; } public boolean forCache() { return false; } public byte[] getEncryptionKey() { return null; } public int getVersion() { return 0; } public boolean shouldDeleteIfMigrationNeeded() { return false; } public Set<Object> getModules() { Set<Object> set = new HashSet<>(); set.add(new SecondaryModule()); return set; } @Override public long execute(Realm realm, long version) { return getVersion(); }
@RealmModule(classes = {Dog.class, Cat.class, Owner.class})
TheFinestArtist/Royal-Android
library/src/androidTest/java/com/thefinestartist/royal/databases/SecondaryDatabase.java
// Path: library/src/main/java/com/thefinestartist/royal/RoyalDatabase.java // public abstract class RoyalDatabase implements RealmMigration { // // public String getFileName() { // return "default"; // } // // public boolean forCache() { // return false; // } // // public byte[] getEncryptionKey() { // return null; // } // // public int getVersion() { // return 0; // } // // public boolean shouldDeleteIfMigrationNeeded() { // return false; // } // // // TODO: change it like getModels // public List<Object> getModules() { // List<Object> modules = new ArrayList<>(); // modules.add(Realm.getDefaultModule()); // return modules; // } // // @Override // public long execute(Realm realm, long version) { // return getVersion(); // } // } // // Path: library/src/androidTest/java/com/thefinestartist/royal/entities/Cat.java // public class Cat extends RealmObject { // private String name; // private long age; // private float height; // private double weight; // private boolean hasTail; // private Date birthday; // private Owner owner; // private DogPrimaryKey scaredOfDog; // // public Owner getOwner() { // return owner; // } // // public void setOwner(Owner owner) { // this.owner = owner; // } // // public Date getBirthday() { // return birthday; // } // // public void setBirthday(Date birthday) { // this.birthday = birthday; // } // // public boolean isHasTail() { // return hasTail; // } // // public void setHasTail(boolean hasTail) { // this.hasTail = hasTail; // } // // // public double getWeight() { // return weight; // } // // public void setWeight(double weight) { // this.weight = weight; // } // // public float getHeight() { // return height; // } // // public void setHeight(float height) { // this.height = height; // } // // public long getAge() { // return age; // } // // public void setAge(long age) { // this.age = age; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public DogPrimaryKey getScaredOfDog() { // return scaredOfDog; // } // // public void setScaredOfDog(DogPrimaryKey scaredOfDog) { // this.scaredOfDog = scaredOfDog; // } // } // // Path: library/src/androidTest/java/com/thefinestartist/royal/entities/Dog.java // public class Dog extends RealmObject { // // @Index // private String name; // private long age; // private float height; // private double weight; // private boolean hasTail; // private Date birthday; // private Owner owner; // // public Dog() { // } // // public Dog(String name) { // this.name = name; // } // // public Owner getOwner() { // return owner; // } // // public void setOwner(Owner owner) { // this.owner = owner; // } // // public Date getBirthday() { // return birthday; // } // // public void setBirthday(Date birthday) { // this.birthday = birthday; // } // // public boolean isHasTail() { // return hasTail; // } // // public void setHasTail(boolean hasTail) { // this.hasTail = hasTail; // } // // public double getWeight() { // return weight; // } // // public void setWeight(double weight) { // this.weight = weight; // } // // public float getHeight() { // return height; // } // // public void setHeight(float height) { // this.height = height; // } // // public long getAge() { // return age; // } // // public void setAge(long age) { // this.age = age; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public static String getStaticName(Dog dog) { // return dog.name; // } // } // // Path: library/src/androidTest/java/com/thefinestartist/royal/entities/Owner.java // public class Owner extends RealmObject { // private String name; // private RealmList<Dog> dogs; // private Cat cat; // // public Cat getCat() { // return cat; // } // // public void setCat(Cat cat) { // this.cat = cat; // } // // public RealmList<Dog> getDogs() { // return dogs; // } // // public void setDogs(RealmList<Dog> dogs) { // this.dogs = dogs; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // }
import com.thefinestartist.royal.RoyalDatabase; import com.thefinestartist.royal.entities.Cat; import com.thefinestartist.royal.entities.Dog; import com.thefinestartist.royal.entities.Owner; import java.util.HashSet; import java.util.Set; import io.realm.Realm; import io.realm.annotations.RealmModule;
package com.thefinestartist.royal.databases; /** * Created by TheFinestArtist on 7/12/15. */ public class SecondaryDatabase extends RoyalDatabase { public String getFileName() { return "secondary"; } public boolean forCache() { return false; } public byte[] getEncryptionKey() { return null; } public int getVersion() { return 0; } public boolean shouldDeleteIfMigrationNeeded() { return false; } public Set<Object> getModules() { Set<Object> set = new HashSet<>(); set.add(new SecondaryModule()); return set; } @Override public long execute(Realm realm, long version) { return getVersion(); }
// Path: library/src/main/java/com/thefinestartist/royal/RoyalDatabase.java // public abstract class RoyalDatabase implements RealmMigration { // // public String getFileName() { // return "default"; // } // // public boolean forCache() { // return false; // } // // public byte[] getEncryptionKey() { // return null; // } // // public int getVersion() { // return 0; // } // // public boolean shouldDeleteIfMigrationNeeded() { // return false; // } // // // TODO: change it like getModels // public List<Object> getModules() { // List<Object> modules = new ArrayList<>(); // modules.add(Realm.getDefaultModule()); // return modules; // } // // @Override // public long execute(Realm realm, long version) { // return getVersion(); // } // } // // Path: library/src/androidTest/java/com/thefinestartist/royal/entities/Cat.java // public class Cat extends RealmObject { // private String name; // private long age; // private float height; // private double weight; // private boolean hasTail; // private Date birthday; // private Owner owner; // private DogPrimaryKey scaredOfDog; // // public Owner getOwner() { // return owner; // } // // public void setOwner(Owner owner) { // this.owner = owner; // } // // public Date getBirthday() { // return birthday; // } // // public void setBirthday(Date birthday) { // this.birthday = birthday; // } // // public boolean isHasTail() { // return hasTail; // } // // public void setHasTail(boolean hasTail) { // this.hasTail = hasTail; // } // // // public double getWeight() { // return weight; // } // // public void setWeight(double weight) { // this.weight = weight; // } // // public float getHeight() { // return height; // } // // public void setHeight(float height) { // this.height = height; // } // // public long getAge() { // return age; // } // // public void setAge(long age) { // this.age = age; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public DogPrimaryKey getScaredOfDog() { // return scaredOfDog; // } // // public void setScaredOfDog(DogPrimaryKey scaredOfDog) { // this.scaredOfDog = scaredOfDog; // } // } // // Path: library/src/androidTest/java/com/thefinestartist/royal/entities/Dog.java // public class Dog extends RealmObject { // // @Index // private String name; // private long age; // private float height; // private double weight; // private boolean hasTail; // private Date birthday; // private Owner owner; // // public Dog() { // } // // public Dog(String name) { // this.name = name; // } // // public Owner getOwner() { // return owner; // } // // public void setOwner(Owner owner) { // this.owner = owner; // } // // public Date getBirthday() { // return birthday; // } // // public void setBirthday(Date birthday) { // this.birthday = birthday; // } // // public boolean isHasTail() { // return hasTail; // } // // public void setHasTail(boolean hasTail) { // this.hasTail = hasTail; // } // // public double getWeight() { // return weight; // } // // public void setWeight(double weight) { // this.weight = weight; // } // // public float getHeight() { // return height; // } // // public void setHeight(float height) { // this.height = height; // } // // public long getAge() { // return age; // } // // public void setAge(long age) { // this.age = age; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public static String getStaticName(Dog dog) { // return dog.name; // } // } // // Path: library/src/androidTest/java/com/thefinestartist/royal/entities/Owner.java // public class Owner extends RealmObject { // private String name; // private RealmList<Dog> dogs; // private Cat cat; // // public Cat getCat() { // return cat; // } // // public void setCat(Cat cat) { // this.cat = cat; // } // // public RealmList<Dog> getDogs() { // return dogs; // } // // public void setDogs(RealmList<Dog> dogs) { // this.dogs = dogs; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // } // Path: library/src/androidTest/java/com/thefinestartist/royal/databases/SecondaryDatabase.java import com.thefinestartist.royal.RoyalDatabase; import com.thefinestartist.royal.entities.Cat; import com.thefinestartist.royal.entities.Dog; import com.thefinestartist.royal.entities.Owner; import java.util.HashSet; import java.util.Set; import io.realm.Realm; import io.realm.annotations.RealmModule; package com.thefinestartist.royal.databases; /** * Created by TheFinestArtist on 7/12/15. */ public class SecondaryDatabase extends RoyalDatabase { public String getFileName() { return "secondary"; } public boolean forCache() { return false; } public byte[] getEncryptionKey() { return null; } public int getVersion() { return 0; } public boolean shouldDeleteIfMigrationNeeded() { return false; } public Set<Object> getModules() { Set<Object> set = new HashSet<>(); set.add(new SecondaryModule()); return set; } @Override public long execute(Realm realm, long version) { return getVersion(); }
@RealmModule(classes = {Dog.class, Cat.class, Owner.class})
TheFinestArtist/Royal-Android
library/src/androidTest/java/com/thefinestartist/royal/databases/SecondaryDatabase.java
// Path: library/src/main/java/com/thefinestartist/royal/RoyalDatabase.java // public abstract class RoyalDatabase implements RealmMigration { // // public String getFileName() { // return "default"; // } // // public boolean forCache() { // return false; // } // // public byte[] getEncryptionKey() { // return null; // } // // public int getVersion() { // return 0; // } // // public boolean shouldDeleteIfMigrationNeeded() { // return false; // } // // // TODO: change it like getModels // public List<Object> getModules() { // List<Object> modules = new ArrayList<>(); // modules.add(Realm.getDefaultModule()); // return modules; // } // // @Override // public long execute(Realm realm, long version) { // return getVersion(); // } // } // // Path: library/src/androidTest/java/com/thefinestartist/royal/entities/Cat.java // public class Cat extends RealmObject { // private String name; // private long age; // private float height; // private double weight; // private boolean hasTail; // private Date birthday; // private Owner owner; // private DogPrimaryKey scaredOfDog; // // public Owner getOwner() { // return owner; // } // // public void setOwner(Owner owner) { // this.owner = owner; // } // // public Date getBirthday() { // return birthday; // } // // public void setBirthday(Date birthday) { // this.birthday = birthday; // } // // public boolean isHasTail() { // return hasTail; // } // // public void setHasTail(boolean hasTail) { // this.hasTail = hasTail; // } // // // public double getWeight() { // return weight; // } // // public void setWeight(double weight) { // this.weight = weight; // } // // public float getHeight() { // return height; // } // // public void setHeight(float height) { // this.height = height; // } // // public long getAge() { // return age; // } // // public void setAge(long age) { // this.age = age; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public DogPrimaryKey getScaredOfDog() { // return scaredOfDog; // } // // public void setScaredOfDog(DogPrimaryKey scaredOfDog) { // this.scaredOfDog = scaredOfDog; // } // } // // Path: library/src/androidTest/java/com/thefinestartist/royal/entities/Dog.java // public class Dog extends RealmObject { // // @Index // private String name; // private long age; // private float height; // private double weight; // private boolean hasTail; // private Date birthday; // private Owner owner; // // public Dog() { // } // // public Dog(String name) { // this.name = name; // } // // public Owner getOwner() { // return owner; // } // // public void setOwner(Owner owner) { // this.owner = owner; // } // // public Date getBirthday() { // return birthday; // } // // public void setBirthday(Date birthday) { // this.birthday = birthday; // } // // public boolean isHasTail() { // return hasTail; // } // // public void setHasTail(boolean hasTail) { // this.hasTail = hasTail; // } // // public double getWeight() { // return weight; // } // // public void setWeight(double weight) { // this.weight = weight; // } // // public float getHeight() { // return height; // } // // public void setHeight(float height) { // this.height = height; // } // // public long getAge() { // return age; // } // // public void setAge(long age) { // this.age = age; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public static String getStaticName(Dog dog) { // return dog.name; // } // } // // Path: library/src/androidTest/java/com/thefinestartist/royal/entities/Owner.java // public class Owner extends RealmObject { // private String name; // private RealmList<Dog> dogs; // private Cat cat; // // public Cat getCat() { // return cat; // } // // public void setCat(Cat cat) { // this.cat = cat; // } // // public RealmList<Dog> getDogs() { // return dogs; // } // // public void setDogs(RealmList<Dog> dogs) { // this.dogs = dogs; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // }
import com.thefinestartist.royal.RoyalDatabase; import com.thefinestartist.royal.entities.Cat; import com.thefinestartist.royal.entities.Dog; import com.thefinestartist.royal.entities.Owner; import java.util.HashSet; import java.util.Set; import io.realm.Realm; import io.realm.annotations.RealmModule;
package com.thefinestartist.royal.databases; /** * Created by TheFinestArtist on 7/12/15. */ public class SecondaryDatabase extends RoyalDatabase { public String getFileName() { return "secondary"; } public boolean forCache() { return false; } public byte[] getEncryptionKey() { return null; } public int getVersion() { return 0; } public boolean shouldDeleteIfMigrationNeeded() { return false; } public Set<Object> getModules() { Set<Object> set = new HashSet<>(); set.add(new SecondaryModule()); return set; } @Override public long execute(Realm realm, long version) { return getVersion(); }
// Path: library/src/main/java/com/thefinestartist/royal/RoyalDatabase.java // public abstract class RoyalDatabase implements RealmMigration { // // public String getFileName() { // return "default"; // } // // public boolean forCache() { // return false; // } // // public byte[] getEncryptionKey() { // return null; // } // // public int getVersion() { // return 0; // } // // public boolean shouldDeleteIfMigrationNeeded() { // return false; // } // // // TODO: change it like getModels // public List<Object> getModules() { // List<Object> modules = new ArrayList<>(); // modules.add(Realm.getDefaultModule()); // return modules; // } // // @Override // public long execute(Realm realm, long version) { // return getVersion(); // } // } // // Path: library/src/androidTest/java/com/thefinestartist/royal/entities/Cat.java // public class Cat extends RealmObject { // private String name; // private long age; // private float height; // private double weight; // private boolean hasTail; // private Date birthday; // private Owner owner; // private DogPrimaryKey scaredOfDog; // // public Owner getOwner() { // return owner; // } // // public void setOwner(Owner owner) { // this.owner = owner; // } // // public Date getBirthday() { // return birthday; // } // // public void setBirthday(Date birthday) { // this.birthday = birthday; // } // // public boolean isHasTail() { // return hasTail; // } // // public void setHasTail(boolean hasTail) { // this.hasTail = hasTail; // } // // // public double getWeight() { // return weight; // } // // public void setWeight(double weight) { // this.weight = weight; // } // // public float getHeight() { // return height; // } // // public void setHeight(float height) { // this.height = height; // } // // public long getAge() { // return age; // } // // public void setAge(long age) { // this.age = age; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public DogPrimaryKey getScaredOfDog() { // return scaredOfDog; // } // // public void setScaredOfDog(DogPrimaryKey scaredOfDog) { // this.scaredOfDog = scaredOfDog; // } // } // // Path: library/src/androidTest/java/com/thefinestartist/royal/entities/Dog.java // public class Dog extends RealmObject { // // @Index // private String name; // private long age; // private float height; // private double weight; // private boolean hasTail; // private Date birthday; // private Owner owner; // // public Dog() { // } // // public Dog(String name) { // this.name = name; // } // // public Owner getOwner() { // return owner; // } // // public void setOwner(Owner owner) { // this.owner = owner; // } // // public Date getBirthday() { // return birthday; // } // // public void setBirthday(Date birthday) { // this.birthday = birthday; // } // // public boolean isHasTail() { // return hasTail; // } // // public void setHasTail(boolean hasTail) { // this.hasTail = hasTail; // } // // public double getWeight() { // return weight; // } // // public void setWeight(double weight) { // this.weight = weight; // } // // public float getHeight() { // return height; // } // // public void setHeight(float height) { // this.height = height; // } // // public long getAge() { // return age; // } // // public void setAge(long age) { // this.age = age; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public static String getStaticName(Dog dog) { // return dog.name; // } // } // // Path: library/src/androidTest/java/com/thefinestartist/royal/entities/Owner.java // public class Owner extends RealmObject { // private String name; // private RealmList<Dog> dogs; // private Cat cat; // // public Cat getCat() { // return cat; // } // // public void setCat(Cat cat) { // this.cat = cat; // } // // public RealmList<Dog> getDogs() { // return dogs; // } // // public void setDogs(RealmList<Dog> dogs) { // this.dogs = dogs; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // } // Path: library/src/androidTest/java/com/thefinestartist/royal/databases/SecondaryDatabase.java import com.thefinestartist.royal.RoyalDatabase; import com.thefinestartist.royal.entities.Cat; import com.thefinestartist.royal.entities.Dog; import com.thefinestartist.royal.entities.Owner; import java.util.HashSet; import java.util.Set; import io.realm.Realm; import io.realm.annotations.RealmModule; package com.thefinestartist.royal.databases; /** * Created by TheFinestArtist on 7/12/15. */ public class SecondaryDatabase extends RoyalDatabase { public String getFileName() { return "secondary"; } public boolean forCache() { return false; } public byte[] getEncryptionKey() { return null; } public int getVersion() { return 0; } public boolean shouldDeleteIfMigrationNeeded() { return false; } public Set<Object> getModules() { Set<Object> set = new HashSet<>(); set.add(new SecondaryModule()); return set; } @Override public long execute(Realm realm, long version) { return getVersion(); }
@RealmModule(classes = {Dog.class, Cat.class, Owner.class})
TheFinestArtist/Royal-Android
library/src/androidTest/java/io/realm/RealmObjectTest.java
// Path: library/src/androidTest/java/com/thefinestartist/royal/entities/Dog.java // public class Dog extends RealmObject { // // @Index // private String name; // private long age; // private float height; // private double weight; // private boolean hasTail; // private Date birthday; // private Owner owner; // // public Dog() { // } // // public Dog(String name) { // this.name = name; // } // // public Owner getOwner() { // return owner; // } // // public void setOwner(Owner owner) { // this.owner = owner; // } // // public Date getBirthday() { // return birthday; // } // // public void setBirthday(Date birthday) { // this.birthday = birthday; // } // // public boolean isHasTail() { // return hasTail; // } // // public void setHasTail(boolean hasTail) { // this.hasTail = hasTail; // } // // public double getWeight() { // return weight; // } // // public void setWeight(double weight) { // this.weight = weight; // } // // public float getHeight() { // return height; // } // // public void setHeight(float height) { // this.height = height; // } // // public long getAge() { // return age; // } // // public void setAge(long age) { // this.age = age; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public static String getStaticName(Dog dog) { // return dog.name; // } // }
import android.test.AndroidTestCase; import com.thefinestartist.royal.entities.Dog;
package io.realm; /** * Created by TheFinestArtist on 7/8/15. */ public class RealmObjectTest extends AndroidTestCase { @Override protected void setUp() throws Exception { } @Override protected void tearDown() throws Exception { } public void testRealmObjectNull1() { // 1. Realm Setup RealmConfiguration realmConfig1 = new RealmConfiguration.Builder(getContext()).name("1testRealmObjectNull1.realm").build(); Realm.deleteRealm(realmConfig1); Realm realm1 = Realm.getInstance(realmConfig1); // 2. Object Setup realm1.beginTransaction();
// Path: library/src/androidTest/java/com/thefinestartist/royal/entities/Dog.java // public class Dog extends RealmObject { // // @Index // private String name; // private long age; // private float height; // private double weight; // private boolean hasTail; // private Date birthday; // private Owner owner; // // public Dog() { // } // // public Dog(String name) { // this.name = name; // } // // public Owner getOwner() { // return owner; // } // // public void setOwner(Owner owner) { // this.owner = owner; // } // // public Date getBirthday() { // return birthday; // } // // public void setBirthday(Date birthday) { // this.birthday = birthday; // } // // public boolean isHasTail() { // return hasTail; // } // // public void setHasTail(boolean hasTail) { // this.hasTail = hasTail; // } // // public double getWeight() { // return weight; // } // // public void setWeight(double weight) { // this.weight = weight; // } // // public float getHeight() { // return height; // } // // public void setHeight(float height) { // this.height = height; // } // // public long getAge() { // return age; // } // // public void setAge(long age) { // this.age = age; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public static String getStaticName(Dog dog) { // return dog.name; // } // } // Path: library/src/androidTest/java/io/realm/RealmObjectTest.java import android.test.AndroidTestCase; import com.thefinestartist.royal.entities.Dog; package io.realm; /** * Created by TheFinestArtist on 7/8/15. */ public class RealmObjectTest extends AndroidTestCase { @Override protected void setUp() throws Exception { } @Override protected void tearDown() throws Exception { } public void testRealmObjectNull1() { // 1. Realm Setup RealmConfiguration realmConfig1 = new RealmConfiguration.Builder(getContext()).name("1testRealmObjectNull1.realm").build(); Realm.deleteRealm(realmConfig1); Realm realm1 = Realm.getInstance(realmConfig1); // 2. Object Setup realm1.beginTransaction();
Dog dog3 = realm1.createObject(Dog.class);
TheFinestArtist/Royal-Android
library/src/androidTest/java/com/thefinestartist/royal/RoyalTransactionTest.java
// Path: library/src/androidTest/java/com/thefinestartist/royal/entities/Dog.java // public class Dog extends RealmObject { // // @Index // private String name; // private long age; // private float height; // private double weight; // private boolean hasTail; // private Date birthday; // private Owner owner; // // public Dog() { // } // // public Dog(String name) { // this.name = name; // } // // public Owner getOwner() { // return owner; // } // // public void setOwner(Owner owner) { // this.owner = owner; // } // // public Date getBirthday() { // return birthday; // } // // public void setBirthday(Date birthday) { // this.birthday = birthday; // } // // public boolean isHasTail() { // return hasTail; // } // // public void setHasTail(boolean hasTail) { // this.hasTail = hasTail; // } // // public double getWeight() { // return weight; // } // // public void setWeight(double weight) { // this.weight = weight; // } // // public float getHeight() { // return height; // } // // public void setHeight(float height) { // this.height = height; // } // // public long getAge() { // return age; // } // // public void setAge(long age) { // this.age = age; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public static String getStaticName(Dog dog) { // return dog.name; // } // } // // Path: library/src/androidTest/java/com/thefinestartist/royal/entities/DogPrimaryKey.java // public class DogPrimaryKey extends RealmObject { // // @PrimaryKey // private long id; // private String name; // private long age; // private float height; // private double weight; // private boolean hasTail; // private Date birthday; // private Owner owner; // // public DogPrimaryKey() { // // } // // public DogPrimaryKey(long id, String name) { // this.id = id; // this.name = name; // } // // public DogPrimaryKey(String name) { // this.name = name; // } // // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public Owner getOwner() { // return owner; // } // // public void setOwner(Owner owner) { // this.owner = owner; // } // // public Date getBirthday() { // return birthday; // } // // public void setBirthday(Date birthday) { // this.birthday = birthday; // } // // public boolean isHasTail() { // return hasTail; // } // // public void setHasTail(boolean hasTail) { // this.hasTail = hasTail; // } // // public double getWeight() { // return weight; // } // // public void setWeight(double weight) { // this.weight = weight; // } // // public float getHeight() { // return height; // } // // public void setHeight(float height) { // this.height = height; // } // // public long getAge() { // return age; // } // // public void setAge(long age) { // this.age = age; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // }
import android.os.Handler; import android.os.Looper; import android.os.Message; import android.test.AndroidTestCase; import com.thefinestartist.royal.entities.Dog; import com.thefinestartist.royal.entities.DogPrimaryKey; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CountDownLatch; import io.realm.Realm; import io.realm.RealmConfiguration; import io.realm.RealmObject; import io.realm.RealmQuery; import io.realm.RealmResults;
package com.thefinestartist.royal; /** * Created by TheFinestArtist on 7/5/15. */ public class RoyalTransactionTest extends AndroidTestCase { @Override protected void setUp() throws Exception { Royal.joinWith(getContext()); } @Override protected void tearDown() throws Exception { } public void testSave1() { // 1. Realm Setup RealmConfiguration realmConfig1 = new RealmConfiguration.Builder(getContext()).name("1testSave1.realm").build(); Realm.deleteRealm(realmConfig1); Realm realm1 = Realm.getInstance(realmConfig1); // 2. Object Setup
// Path: library/src/androidTest/java/com/thefinestartist/royal/entities/Dog.java // public class Dog extends RealmObject { // // @Index // private String name; // private long age; // private float height; // private double weight; // private boolean hasTail; // private Date birthday; // private Owner owner; // // public Dog() { // } // // public Dog(String name) { // this.name = name; // } // // public Owner getOwner() { // return owner; // } // // public void setOwner(Owner owner) { // this.owner = owner; // } // // public Date getBirthday() { // return birthday; // } // // public void setBirthday(Date birthday) { // this.birthday = birthday; // } // // public boolean isHasTail() { // return hasTail; // } // // public void setHasTail(boolean hasTail) { // this.hasTail = hasTail; // } // // public double getWeight() { // return weight; // } // // public void setWeight(double weight) { // this.weight = weight; // } // // public float getHeight() { // return height; // } // // public void setHeight(float height) { // this.height = height; // } // // public long getAge() { // return age; // } // // public void setAge(long age) { // this.age = age; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public static String getStaticName(Dog dog) { // return dog.name; // } // } // // Path: library/src/androidTest/java/com/thefinestartist/royal/entities/DogPrimaryKey.java // public class DogPrimaryKey extends RealmObject { // // @PrimaryKey // private long id; // private String name; // private long age; // private float height; // private double weight; // private boolean hasTail; // private Date birthday; // private Owner owner; // // public DogPrimaryKey() { // // } // // public DogPrimaryKey(long id, String name) { // this.id = id; // this.name = name; // } // // public DogPrimaryKey(String name) { // this.name = name; // } // // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public Owner getOwner() { // return owner; // } // // public void setOwner(Owner owner) { // this.owner = owner; // } // // public Date getBirthday() { // return birthday; // } // // public void setBirthday(Date birthday) { // this.birthday = birthday; // } // // public boolean isHasTail() { // return hasTail; // } // // public void setHasTail(boolean hasTail) { // this.hasTail = hasTail; // } // // public double getWeight() { // return weight; // } // // public void setWeight(double weight) { // this.weight = weight; // } // // public float getHeight() { // return height; // } // // public void setHeight(float height) { // this.height = height; // } // // public long getAge() { // return age; // } // // public void setAge(long age) { // this.age = age; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // } // Path: library/src/androidTest/java/com/thefinestartist/royal/RoyalTransactionTest.java import android.os.Handler; import android.os.Looper; import android.os.Message; import android.test.AndroidTestCase; import com.thefinestartist.royal.entities.Dog; import com.thefinestartist.royal.entities.DogPrimaryKey; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CountDownLatch; import io.realm.Realm; import io.realm.RealmConfiguration; import io.realm.RealmObject; import io.realm.RealmQuery; import io.realm.RealmResults; package com.thefinestartist.royal; /** * Created by TheFinestArtist on 7/5/15. */ public class RoyalTransactionTest extends AndroidTestCase { @Override protected void setUp() throws Exception { Royal.joinWith(getContext()); } @Override protected void tearDown() throws Exception { } public void testSave1() { // 1. Realm Setup RealmConfiguration realmConfig1 = new RealmConfiguration.Builder(getContext()).name("1testSave1.realm").build(); Realm.deleteRealm(realmConfig1); Realm realm1 = Realm.getInstance(realmConfig1); // 2. Object Setup
Dog dog1 = new Dog();
TheFinestArtist/Royal-Android
library/src/androidTest/java/com/thefinestartist/royal/RoyalTransactionTest.java
// Path: library/src/androidTest/java/com/thefinestartist/royal/entities/Dog.java // public class Dog extends RealmObject { // // @Index // private String name; // private long age; // private float height; // private double weight; // private boolean hasTail; // private Date birthday; // private Owner owner; // // public Dog() { // } // // public Dog(String name) { // this.name = name; // } // // public Owner getOwner() { // return owner; // } // // public void setOwner(Owner owner) { // this.owner = owner; // } // // public Date getBirthday() { // return birthday; // } // // public void setBirthday(Date birthday) { // this.birthday = birthday; // } // // public boolean isHasTail() { // return hasTail; // } // // public void setHasTail(boolean hasTail) { // this.hasTail = hasTail; // } // // public double getWeight() { // return weight; // } // // public void setWeight(double weight) { // this.weight = weight; // } // // public float getHeight() { // return height; // } // // public void setHeight(float height) { // this.height = height; // } // // public long getAge() { // return age; // } // // public void setAge(long age) { // this.age = age; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public static String getStaticName(Dog dog) { // return dog.name; // } // } // // Path: library/src/androidTest/java/com/thefinestartist/royal/entities/DogPrimaryKey.java // public class DogPrimaryKey extends RealmObject { // // @PrimaryKey // private long id; // private String name; // private long age; // private float height; // private double weight; // private boolean hasTail; // private Date birthday; // private Owner owner; // // public DogPrimaryKey() { // // } // // public DogPrimaryKey(long id, String name) { // this.id = id; // this.name = name; // } // // public DogPrimaryKey(String name) { // this.name = name; // } // // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public Owner getOwner() { // return owner; // } // // public void setOwner(Owner owner) { // this.owner = owner; // } // // public Date getBirthday() { // return birthday; // } // // public void setBirthday(Date birthday) { // this.birthday = birthday; // } // // public boolean isHasTail() { // return hasTail; // } // // public void setHasTail(boolean hasTail) { // this.hasTail = hasTail; // } // // public double getWeight() { // return weight; // } // // public void setWeight(double weight) { // this.weight = weight; // } // // public float getHeight() { // return height; // } // // public void setHeight(float height) { // this.height = height; // } // // public long getAge() { // return age; // } // // public void setAge(long age) { // this.age = age; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // }
import android.os.Handler; import android.os.Looper; import android.os.Message; import android.test.AndroidTestCase; import com.thefinestartist.royal.entities.Dog; import com.thefinestartist.royal.entities.DogPrimaryKey; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CountDownLatch; import io.realm.Realm; import io.realm.RealmConfiguration; import io.realm.RealmObject; import io.realm.RealmQuery; import io.realm.RealmResults;
realm2.beginTransaction(); Dog dog2 = realm2.createObject(Dog.class); dog2.setName("Kitty2"); realm2.commitTransaction(); // 3. RoyalTransaction.save() RoyalTransaction.save(realm1, dog1, dog2); // 4. Query RealmQuery<Dog> query = realm1.where(Dog.class); RealmResults<Dog> dogs = query.findAll(); // 5. Assert assertNotNull(dogs); assertEquals(2, dogs.size()); assertEquals("Kitty1", dogs.get(0).getName()); assertEquals("Kitty2", dogs.get(1).getName()); // 6. Realm Close realm1.close(); } public void testSave4() { // 1. Realm Setup RealmConfiguration realmConfig1 = new RealmConfiguration.Builder(getContext()).name("1testSave4.realm").build(); Realm.deleteRealm(realmConfig1); Realm realm1 = Realm.getInstance(realmConfig1); // 2. Object Setup
// Path: library/src/androidTest/java/com/thefinestartist/royal/entities/Dog.java // public class Dog extends RealmObject { // // @Index // private String name; // private long age; // private float height; // private double weight; // private boolean hasTail; // private Date birthday; // private Owner owner; // // public Dog() { // } // // public Dog(String name) { // this.name = name; // } // // public Owner getOwner() { // return owner; // } // // public void setOwner(Owner owner) { // this.owner = owner; // } // // public Date getBirthday() { // return birthday; // } // // public void setBirthday(Date birthday) { // this.birthday = birthday; // } // // public boolean isHasTail() { // return hasTail; // } // // public void setHasTail(boolean hasTail) { // this.hasTail = hasTail; // } // // public double getWeight() { // return weight; // } // // public void setWeight(double weight) { // this.weight = weight; // } // // public float getHeight() { // return height; // } // // public void setHeight(float height) { // this.height = height; // } // // public long getAge() { // return age; // } // // public void setAge(long age) { // this.age = age; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public static String getStaticName(Dog dog) { // return dog.name; // } // } // // Path: library/src/androidTest/java/com/thefinestartist/royal/entities/DogPrimaryKey.java // public class DogPrimaryKey extends RealmObject { // // @PrimaryKey // private long id; // private String name; // private long age; // private float height; // private double weight; // private boolean hasTail; // private Date birthday; // private Owner owner; // // public DogPrimaryKey() { // // } // // public DogPrimaryKey(long id, String name) { // this.id = id; // this.name = name; // } // // public DogPrimaryKey(String name) { // this.name = name; // } // // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public Owner getOwner() { // return owner; // } // // public void setOwner(Owner owner) { // this.owner = owner; // } // // public Date getBirthday() { // return birthday; // } // // public void setBirthday(Date birthday) { // this.birthday = birthday; // } // // public boolean isHasTail() { // return hasTail; // } // // public void setHasTail(boolean hasTail) { // this.hasTail = hasTail; // } // // public double getWeight() { // return weight; // } // // public void setWeight(double weight) { // this.weight = weight; // } // // public float getHeight() { // return height; // } // // public void setHeight(float height) { // this.height = height; // } // // public long getAge() { // return age; // } // // public void setAge(long age) { // this.age = age; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // } // Path: library/src/androidTest/java/com/thefinestartist/royal/RoyalTransactionTest.java import android.os.Handler; import android.os.Looper; import android.os.Message; import android.test.AndroidTestCase; import com.thefinestartist.royal.entities.Dog; import com.thefinestartist.royal.entities.DogPrimaryKey; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CountDownLatch; import io.realm.Realm; import io.realm.RealmConfiguration; import io.realm.RealmObject; import io.realm.RealmQuery; import io.realm.RealmResults; realm2.beginTransaction(); Dog dog2 = realm2.createObject(Dog.class); dog2.setName("Kitty2"); realm2.commitTransaction(); // 3. RoyalTransaction.save() RoyalTransaction.save(realm1, dog1, dog2); // 4. Query RealmQuery<Dog> query = realm1.where(Dog.class); RealmResults<Dog> dogs = query.findAll(); // 5. Assert assertNotNull(dogs); assertEquals(2, dogs.size()); assertEquals("Kitty1", dogs.get(0).getName()); assertEquals("Kitty2", dogs.get(1).getName()); // 6. Realm Close realm1.close(); } public void testSave4() { // 1. Realm Setup RealmConfiguration realmConfig1 = new RealmConfiguration.Builder(getContext()).name("1testSave4.realm").build(); Realm.deleteRealm(realmConfig1); Realm realm1 = Realm.getInstance(realmConfig1); // 2. Object Setup
DogPrimaryKey dog1 = new DogPrimaryKey();
TheFinestArtist/Royal-Android
library/src/main/java/com/thefinestartist/royal/Rson.java
// Path: library/src/main/java/com/thefinestartist/royal/util/DateUtil.java // public class DateUtil { // // public static String DATE_FORMAT = "MMM d, yyyy h:mm:ss aa"; // Aug 6, 2015 1:23:33 AM // private static SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT, Locale.US); // // private DateUtil() { // } // // public static String getDateFormat(Date date) { // if (date == null) // return null; // return dateFormat.format(date); // } // } // // Path: library/src/main/java/io/realm/RoyalAccess.java // public class RoyalAccess { // // public static Realm getRealm(@NonNull RealmObject object) { // return object.realm; // } // // public static Row getRow(@NonNull RealmObject object) { // return object.row; // } // // public static Table getTable(@NonNull RealmObject object) { // return object.row == null ? null : object.row.getTable(); // } // // public static boolean isProxy(@NonNull RealmObject object) { // return object instanceof RealmObjectProxy; // } // // public static boolean hasPrimaryKey(@NonNull Realm realm, @NonNull RealmObject object) { // return realm.getTable(object.getClass()).hasPrimaryKey(); // } // // public static Class<? extends RealmObject> getClass(@NonNull Realm realm, @NonNull Table table) { // List<Class<? extends RealmObject>> classes = realm.getConfiguration().getSchemaMediator().getModelClasses(); // for (Class<? extends RealmObject> clazz : classes) // if (realm.getTable(clazz).getName().equals(table.getName())) // return clazz; // // return null; // } // // public static RealmObject get(@NonNull Realm realm, @NonNull Table table, long rowIndex) { // if (rowIndex < 0) // return null; // // UncheckedRow row = table.getUncheckedRow(rowIndex); // RealmObject result = realm.getConfiguration().getSchemaMediator().newInstance(getClass(realm, table)); // result.row = row; // result.realm = realm; // return result; // } // // // TODO: Free RealmObject from Realm // // // // TODO: Clone RealmObject without Realm information // // TODO: Problem #1 Serializing RealmObject has same speed of just committing it using Realm // // }
import android.support.annotation.NonNull; import com.google.gson.ExclusionStrategy; import com.google.gson.FieldAttributes; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.thefinestartist.royal.util.DateUtil; import java.util.Arrays; import java.util.Date; import io.realm.Realm; import io.realm.RealmObject; import io.realm.RoyalAccess; import io.realm.internal.ColumnType; import io.realm.internal.LinkView; import io.realm.internal.Row; import io.realm.internal.Table;
package com.thefinestartist.royal; /** * Created by TheFinestArtist on 7/8/15. */ public class Rson { private static final Object lock = new Object(); private static Gson gson; public static Gson getGson() { synchronized (lock) { if (gson != null) return gson; gson = new GsonBuilder() .setExclusionStrategies(new ExclusionStrategy() { @Override public boolean shouldSkipField(FieldAttributes f) { return f.getDeclaringClass().equals(RealmObject.class); } @Override public boolean shouldSkipClass(Class<?> clazz) { return false; } }) .create(); return gson; } } public static String toJsonString(@NonNull RealmObject object) { return toJsonString(object, 1); } @SuppressWarnings("ConstantConditions") public static String toJsonString(@NonNull RealmObject object, int depth) {
// Path: library/src/main/java/com/thefinestartist/royal/util/DateUtil.java // public class DateUtil { // // public static String DATE_FORMAT = "MMM d, yyyy h:mm:ss aa"; // Aug 6, 2015 1:23:33 AM // private static SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT, Locale.US); // // private DateUtil() { // } // // public static String getDateFormat(Date date) { // if (date == null) // return null; // return dateFormat.format(date); // } // } // // Path: library/src/main/java/io/realm/RoyalAccess.java // public class RoyalAccess { // // public static Realm getRealm(@NonNull RealmObject object) { // return object.realm; // } // // public static Row getRow(@NonNull RealmObject object) { // return object.row; // } // // public static Table getTable(@NonNull RealmObject object) { // return object.row == null ? null : object.row.getTable(); // } // // public static boolean isProxy(@NonNull RealmObject object) { // return object instanceof RealmObjectProxy; // } // // public static boolean hasPrimaryKey(@NonNull Realm realm, @NonNull RealmObject object) { // return realm.getTable(object.getClass()).hasPrimaryKey(); // } // // public static Class<? extends RealmObject> getClass(@NonNull Realm realm, @NonNull Table table) { // List<Class<? extends RealmObject>> classes = realm.getConfiguration().getSchemaMediator().getModelClasses(); // for (Class<? extends RealmObject> clazz : classes) // if (realm.getTable(clazz).getName().equals(table.getName())) // return clazz; // // return null; // } // // public static RealmObject get(@NonNull Realm realm, @NonNull Table table, long rowIndex) { // if (rowIndex < 0) // return null; // // UncheckedRow row = table.getUncheckedRow(rowIndex); // RealmObject result = realm.getConfiguration().getSchemaMediator().newInstance(getClass(realm, table)); // result.row = row; // result.realm = realm; // return result; // } // // // TODO: Free RealmObject from Realm // // // // TODO: Clone RealmObject without Realm information // // TODO: Problem #1 Serializing RealmObject has same speed of just committing it using Realm // // } // Path: library/src/main/java/com/thefinestartist/royal/Rson.java import android.support.annotation.NonNull; import com.google.gson.ExclusionStrategy; import com.google.gson.FieldAttributes; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.thefinestartist.royal.util.DateUtil; import java.util.Arrays; import java.util.Date; import io.realm.Realm; import io.realm.RealmObject; import io.realm.RoyalAccess; import io.realm.internal.ColumnType; import io.realm.internal.LinkView; import io.realm.internal.Row; import io.realm.internal.Table; package com.thefinestartist.royal; /** * Created by TheFinestArtist on 7/8/15. */ public class Rson { private static final Object lock = new Object(); private static Gson gson; public static Gson getGson() { synchronized (lock) { if (gson != null) return gson; gson = new GsonBuilder() .setExclusionStrategies(new ExclusionStrategy() { @Override public boolean shouldSkipField(FieldAttributes f) { return f.getDeclaringClass().equals(RealmObject.class); } @Override public boolean shouldSkipClass(Class<?> clazz) { return false; } }) .create(); return gson; } } public static String toJsonString(@NonNull RealmObject object) { return toJsonString(object, 1); } @SuppressWarnings("ConstantConditions") public static String toJsonString(@NonNull RealmObject object, int depth) {
if (!RoyalAccess.isProxy(object)) {
TheFinestArtist/Royal-Android
library/src/main/java/com/thefinestartist/royal/Rson.java
// Path: library/src/main/java/com/thefinestartist/royal/util/DateUtil.java // public class DateUtil { // // public static String DATE_FORMAT = "MMM d, yyyy h:mm:ss aa"; // Aug 6, 2015 1:23:33 AM // private static SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT, Locale.US); // // private DateUtil() { // } // // public static String getDateFormat(Date date) { // if (date == null) // return null; // return dateFormat.format(date); // } // } // // Path: library/src/main/java/io/realm/RoyalAccess.java // public class RoyalAccess { // // public static Realm getRealm(@NonNull RealmObject object) { // return object.realm; // } // // public static Row getRow(@NonNull RealmObject object) { // return object.row; // } // // public static Table getTable(@NonNull RealmObject object) { // return object.row == null ? null : object.row.getTable(); // } // // public static boolean isProxy(@NonNull RealmObject object) { // return object instanceof RealmObjectProxy; // } // // public static boolean hasPrimaryKey(@NonNull Realm realm, @NonNull RealmObject object) { // return realm.getTable(object.getClass()).hasPrimaryKey(); // } // // public static Class<? extends RealmObject> getClass(@NonNull Realm realm, @NonNull Table table) { // List<Class<? extends RealmObject>> classes = realm.getConfiguration().getSchemaMediator().getModelClasses(); // for (Class<? extends RealmObject> clazz : classes) // if (realm.getTable(clazz).getName().equals(table.getName())) // return clazz; // // return null; // } // // public static RealmObject get(@NonNull Realm realm, @NonNull Table table, long rowIndex) { // if (rowIndex < 0) // return null; // // UncheckedRow row = table.getUncheckedRow(rowIndex); // RealmObject result = realm.getConfiguration().getSchemaMediator().newInstance(getClass(realm, table)); // result.row = row; // result.realm = realm; // return result; // } // // // TODO: Free RealmObject from Realm // // // // TODO: Clone RealmObject without Realm information // // TODO: Problem #1 Serializing RealmObject has same speed of just committing it using Realm // // }
import android.support.annotation.NonNull; import com.google.gson.ExclusionStrategy; import com.google.gson.FieldAttributes; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.thefinestartist.royal.util.DateUtil; import java.util.Arrays; import java.util.Date; import io.realm.Realm; import io.realm.RealmObject; import io.realm.RoyalAccess; import io.realm.internal.ColumnType; import io.realm.internal.LinkView; import io.realm.internal.Row; import io.realm.internal.Table;
builder .append(prefix) .append("\"") .append(table.getColumnName(i)) .append("\":\"") .append(string).append("\""); prefix = ","; } break; case BINARY: builder .append(prefix) .append("\"") .append(table.getColumnName(i)) .append("\":") .append(Arrays.toString(row.getBinaryByteArray(i))); prefix = ","; break; case DATE: Date date = row.getDate(i); // TODO: date.getTime() != 0 to better option if (date != null && date.getTime() != 0) { // Gson gson = new GsonBuilder().setDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz").create(); // Gson gson = new GsonBuilder().setDateFormat(DateFormat.FULL, DateFormat.FULL).create(); // TODO: Current "Sun Jul 12 03:50:05 GMT+09:00 2015" builder .append(prefix) .append("\"") .append(table.getColumnName(i)) .append("\":\"")
// Path: library/src/main/java/com/thefinestartist/royal/util/DateUtil.java // public class DateUtil { // // public static String DATE_FORMAT = "MMM d, yyyy h:mm:ss aa"; // Aug 6, 2015 1:23:33 AM // private static SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT, Locale.US); // // private DateUtil() { // } // // public static String getDateFormat(Date date) { // if (date == null) // return null; // return dateFormat.format(date); // } // } // // Path: library/src/main/java/io/realm/RoyalAccess.java // public class RoyalAccess { // // public static Realm getRealm(@NonNull RealmObject object) { // return object.realm; // } // // public static Row getRow(@NonNull RealmObject object) { // return object.row; // } // // public static Table getTable(@NonNull RealmObject object) { // return object.row == null ? null : object.row.getTable(); // } // // public static boolean isProxy(@NonNull RealmObject object) { // return object instanceof RealmObjectProxy; // } // // public static boolean hasPrimaryKey(@NonNull Realm realm, @NonNull RealmObject object) { // return realm.getTable(object.getClass()).hasPrimaryKey(); // } // // public static Class<? extends RealmObject> getClass(@NonNull Realm realm, @NonNull Table table) { // List<Class<? extends RealmObject>> classes = realm.getConfiguration().getSchemaMediator().getModelClasses(); // for (Class<? extends RealmObject> clazz : classes) // if (realm.getTable(clazz).getName().equals(table.getName())) // return clazz; // // return null; // } // // public static RealmObject get(@NonNull Realm realm, @NonNull Table table, long rowIndex) { // if (rowIndex < 0) // return null; // // UncheckedRow row = table.getUncheckedRow(rowIndex); // RealmObject result = realm.getConfiguration().getSchemaMediator().newInstance(getClass(realm, table)); // result.row = row; // result.realm = realm; // return result; // } // // // TODO: Free RealmObject from Realm // // // // TODO: Clone RealmObject without Realm information // // TODO: Problem #1 Serializing RealmObject has same speed of just committing it using Realm // // } // Path: library/src/main/java/com/thefinestartist/royal/Rson.java import android.support.annotation.NonNull; import com.google.gson.ExclusionStrategy; import com.google.gson.FieldAttributes; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.thefinestartist.royal.util.DateUtil; import java.util.Arrays; import java.util.Date; import io.realm.Realm; import io.realm.RealmObject; import io.realm.RoyalAccess; import io.realm.internal.ColumnType; import io.realm.internal.LinkView; import io.realm.internal.Row; import io.realm.internal.Table; builder .append(prefix) .append("\"") .append(table.getColumnName(i)) .append("\":\"") .append(string).append("\""); prefix = ","; } break; case BINARY: builder .append(prefix) .append("\"") .append(table.getColumnName(i)) .append("\":") .append(Arrays.toString(row.getBinaryByteArray(i))); prefix = ","; break; case DATE: Date date = row.getDate(i); // TODO: date.getTime() != 0 to better option if (date != null && date.getTime() != 0) { // Gson gson = new GsonBuilder().setDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz").create(); // Gson gson = new GsonBuilder().setDateFormat(DateFormat.FULL, DateFormat.FULL).create(); // TODO: Current "Sun Jul 12 03:50:05 GMT+09:00 2015" builder .append(prefix) .append("\"") .append(table.getColumnName(i)) .append("\":\"")
.append(DateUtil.getDateFormat(date))
TheFinestArtist/Royal-Android
example/src/main/java/com/thefinestartist/royal/example/App.java
// Path: library/src/main/java/com/thefinestartist/royal/Royal.java // public class Royal { // // private static Context context; // // public static void joinWith(@NonNull Context context) { // Royal.context = context.getApplicationContext(); // Logger.init("Royal"); // } // // public static Context getApplicationContext() { // if (Royal.context == null) // throw new NullPointerException("Please call Royal.joinWith(context) within your Application onCreate() method."); // return Royal.context; // } // // public static Map<Class<? extends RoyalDatabase>, RealmConfiguration> configurationMap = new ConcurrentHashMap<>(); // public static Map<Class<? extends RoyalDatabase>, RoyalDatabase> databaseMap = new ConcurrentHashMap<>(); // // public static void addDatabase(@NonNull RoyalDatabase royalDatabase) { // Context context = Royal.getApplicationContext(); // RealmConfiguration.Builder builder = new RealmConfiguration.Builder(context); // builder.name(royalDatabase.getFileName() + ".realm"); // if (royalDatabase.forCache()) // builder.inMemory(); // if (royalDatabase.getEncryptionKey() != null) // builder.encryptionKey(royalDatabase.getEncryptionKey()); // if (royalDatabase.shouldDeleteIfMigrationNeeded()) // builder.deleteRealmIfMigrationNeeded(); // // List<Object> modules = royalDatabase.getModules(); // if (modules != null && modules.size() > 0) { // Object baseModule; // baseModule = modules.get(0); // modules.remove(0); // Object[] additionalModules = modules.toArray(new Object[modules.size()]); // builder.setModules(baseModule, additionalModules); // } // // builder.migration(royalDatabase); // RealmConfiguration configuration = builder.build(); // configurationMap.put(royalDatabase.getClass(), configuration); // databaseMap.put(royalDatabase.getClass(), royalDatabase); // } // // public static RealmConfiguration getConfigurationOf(Class<? extends RoyalDatabase> clazz) { // return configurationMap.get(clazz); // } // // public static Realm getRealmOf(Class<? extends RoyalDatabase> clazz) { // RealmConfiguration configuration = configurationMap.get(clazz); // return Realm.getInstance(configuration); // } // // public static RoyalDatabase getDatabaseOf(Class<? extends RoyalDatabase> clazz) { // return databaseMap.get(clazz); // } // // // public static Realm openRealm(Class<? extends RoyalDatabase> clazz) { // // RealmConfiguration configuration = configurationMap.get(clazz); // // return Realm.getInstance(configuration); // // } // // // // public static void closeRealm(Realm realm) { // // realm.close(); // // } // }
import android.app.Application; import com.thefinestartist.royal.Royal;
package com.thefinestartist.royal.example; /** * Created by TheFinestArtist on 8/3/15. */ public class App extends Application { @Override public void onCreate() { super.onCreate();
// Path: library/src/main/java/com/thefinestartist/royal/Royal.java // public class Royal { // // private static Context context; // // public static void joinWith(@NonNull Context context) { // Royal.context = context.getApplicationContext(); // Logger.init("Royal"); // } // // public static Context getApplicationContext() { // if (Royal.context == null) // throw new NullPointerException("Please call Royal.joinWith(context) within your Application onCreate() method."); // return Royal.context; // } // // public static Map<Class<? extends RoyalDatabase>, RealmConfiguration> configurationMap = new ConcurrentHashMap<>(); // public static Map<Class<? extends RoyalDatabase>, RoyalDatabase> databaseMap = new ConcurrentHashMap<>(); // // public static void addDatabase(@NonNull RoyalDatabase royalDatabase) { // Context context = Royal.getApplicationContext(); // RealmConfiguration.Builder builder = new RealmConfiguration.Builder(context); // builder.name(royalDatabase.getFileName() + ".realm"); // if (royalDatabase.forCache()) // builder.inMemory(); // if (royalDatabase.getEncryptionKey() != null) // builder.encryptionKey(royalDatabase.getEncryptionKey()); // if (royalDatabase.shouldDeleteIfMigrationNeeded()) // builder.deleteRealmIfMigrationNeeded(); // // List<Object> modules = royalDatabase.getModules(); // if (modules != null && modules.size() > 0) { // Object baseModule; // baseModule = modules.get(0); // modules.remove(0); // Object[] additionalModules = modules.toArray(new Object[modules.size()]); // builder.setModules(baseModule, additionalModules); // } // // builder.migration(royalDatabase); // RealmConfiguration configuration = builder.build(); // configurationMap.put(royalDatabase.getClass(), configuration); // databaseMap.put(royalDatabase.getClass(), royalDatabase); // } // // public static RealmConfiguration getConfigurationOf(Class<? extends RoyalDatabase> clazz) { // return configurationMap.get(clazz); // } // // public static Realm getRealmOf(Class<? extends RoyalDatabase> clazz) { // RealmConfiguration configuration = configurationMap.get(clazz); // return Realm.getInstance(configuration); // } // // public static RoyalDatabase getDatabaseOf(Class<? extends RoyalDatabase> clazz) { // return databaseMap.get(clazz); // } // // // public static Realm openRealm(Class<? extends RoyalDatabase> clazz) { // // RealmConfiguration configuration = configurationMap.get(clazz); // // return Realm.getInstance(configuration); // // } // // // // public static void closeRealm(Realm realm) { // // realm.close(); // // } // } // Path: example/src/main/java/com/thefinestartist/royal/example/App.java import android.app.Application; import com.thefinestartist.royal.Royal; package com.thefinestartist.royal.example; /** * Created by TheFinestArtist on 8/3/15. */ public class App extends Application { @Override public void onCreate() { super.onCreate();
Royal.joinWith(this);
TheFinestArtist/Royal-Android
library/src/androidTest/java/io/realm/RoyalAccessTest.java
// Path: library/src/androidTest/java/com/thefinestartist/royal/entities/Dog.java // public class Dog extends RealmObject { // // @Index // private String name; // private long age; // private float height; // private double weight; // private boolean hasTail; // private Date birthday; // private Owner owner; // // public Dog() { // } // // public Dog(String name) { // this.name = name; // } // // public Owner getOwner() { // return owner; // } // // public void setOwner(Owner owner) { // this.owner = owner; // } // // public Date getBirthday() { // return birthday; // } // // public void setBirthday(Date birthday) { // this.birthday = birthday; // } // // public boolean isHasTail() { // return hasTail; // } // // public void setHasTail(boolean hasTail) { // this.hasTail = hasTail; // } // // public double getWeight() { // return weight; // } // // public void setWeight(double weight) { // this.weight = weight; // } // // public float getHeight() { // return height; // } // // public void setHeight(float height) { // this.height = height; // } // // public long getAge() { // return age; // } // // public void setAge(long age) { // this.age = age; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public static String getStaticName(Dog dog) { // return dog.name; // } // } // // Path: library/src/androidTest/java/com/thefinestartist/royal/entities/DogPrimaryKey.java // public class DogPrimaryKey extends RealmObject { // // @PrimaryKey // private long id; // private String name; // private long age; // private float height; // private double weight; // private boolean hasTail; // private Date birthday; // private Owner owner; // // public DogPrimaryKey() { // // } // // public DogPrimaryKey(long id, String name) { // this.id = id; // this.name = name; // } // // public DogPrimaryKey(String name) { // this.name = name; // } // // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public Owner getOwner() { // return owner; // } // // public void setOwner(Owner owner) { // this.owner = owner; // } // // public Date getBirthday() { // return birthday; // } // // public void setBirthday(Date birthday) { // this.birthday = birthday; // } // // public boolean isHasTail() { // return hasTail; // } // // public void setHasTail(boolean hasTail) { // this.hasTail = hasTail; // } // // public double getWeight() { // return weight; // } // // public void setWeight(double weight) { // this.weight = weight; // } // // public float getHeight() { // return height; // } // // public void setHeight(float height) { // this.height = height; // } // // public long getAge() { // return age; // } // // public void setAge(long age) { // this.age = age; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // }
import android.test.AndroidTestCase; import com.orhanobut.logger.Logger; import com.thefinestartist.royal.entities.Dog; import com.thefinestartist.royal.entities.DogPrimaryKey; import io.realm.internal.Util;
package io.realm; /** * Created by TheFinestArtist on 7/7/15. */ public class RoyalAccessTest extends AndroidTestCase { @Override protected void setUp() throws Exception { } @Override protected void tearDown() throws Exception { } public void testGetRealm1() { // 1. Realm Setup RealmConfiguration realmConfig1 = new RealmConfiguration.Builder(getContext()).name("1testGetRealm1.realm").build(); Realm.deleteRealm(realmConfig1); Realm realm1 = Realm.getInstance(realmConfig1); RealmConfiguration realmConfig2 = new RealmConfiguration.Builder(getContext()).name("2testGetRealm1.realm").build(); Realm.deleteRealm(realmConfig2); Realm realm2 = Realm.getInstance(realmConfig2); // 2. Object Setup
// Path: library/src/androidTest/java/com/thefinestartist/royal/entities/Dog.java // public class Dog extends RealmObject { // // @Index // private String name; // private long age; // private float height; // private double weight; // private boolean hasTail; // private Date birthday; // private Owner owner; // // public Dog() { // } // // public Dog(String name) { // this.name = name; // } // // public Owner getOwner() { // return owner; // } // // public void setOwner(Owner owner) { // this.owner = owner; // } // // public Date getBirthday() { // return birthday; // } // // public void setBirthday(Date birthday) { // this.birthday = birthday; // } // // public boolean isHasTail() { // return hasTail; // } // // public void setHasTail(boolean hasTail) { // this.hasTail = hasTail; // } // // public double getWeight() { // return weight; // } // // public void setWeight(double weight) { // this.weight = weight; // } // // public float getHeight() { // return height; // } // // public void setHeight(float height) { // this.height = height; // } // // public long getAge() { // return age; // } // // public void setAge(long age) { // this.age = age; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public static String getStaticName(Dog dog) { // return dog.name; // } // } // // Path: library/src/androidTest/java/com/thefinestartist/royal/entities/DogPrimaryKey.java // public class DogPrimaryKey extends RealmObject { // // @PrimaryKey // private long id; // private String name; // private long age; // private float height; // private double weight; // private boolean hasTail; // private Date birthday; // private Owner owner; // // public DogPrimaryKey() { // // } // // public DogPrimaryKey(long id, String name) { // this.id = id; // this.name = name; // } // // public DogPrimaryKey(String name) { // this.name = name; // } // // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public Owner getOwner() { // return owner; // } // // public void setOwner(Owner owner) { // this.owner = owner; // } // // public Date getBirthday() { // return birthday; // } // // public void setBirthday(Date birthday) { // this.birthday = birthday; // } // // public boolean isHasTail() { // return hasTail; // } // // public void setHasTail(boolean hasTail) { // this.hasTail = hasTail; // } // // public double getWeight() { // return weight; // } // // public void setWeight(double weight) { // this.weight = weight; // } // // public float getHeight() { // return height; // } // // public void setHeight(float height) { // this.height = height; // } // // public long getAge() { // return age; // } // // public void setAge(long age) { // this.age = age; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // } // Path: library/src/androidTest/java/io/realm/RoyalAccessTest.java import android.test.AndroidTestCase; import com.orhanobut.logger.Logger; import com.thefinestartist.royal.entities.Dog; import com.thefinestartist.royal.entities.DogPrimaryKey; import io.realm.internal.Util; package io.realm; /** * Created by TheFinestArtist on 7/7/15. */ public class RoyalAccessTest extends AndroidTestCase { @Override protected void setUp() throws Exception { } @Override protected void tearDown() throws Exception { } public void testGetRealm1() { // 1. Realm Setup RealmConfiguration realmConfig1 = new RealmConfiguration.Builder(getContext()).name("1testGetRealm1.realm").build(); Realm.deleteRealm(realmConfig1); Realm realm1 = Realm.getInstance(realmConfig1); RealmConfiguration realmConfig2 = new RealmConfiguration.Builder(getContext()).name("2testGetRealm1.realm").build(); Realm.deleteRealm(realmConfig2); Realm realm2 = Realm.getInstance(realmConfig2); // 2. Object Setup
Dog dog1 = new Dog();
TheFinestArtist/Royal-Android
library/src/androidTest/java/io/realm/RoyalAccessTest.java
// Path: library/src/androidTest/java/com/thefinestartist/royal/entities/Dog.java // public class Dog extends RealmObject { // // @Index // private String name; // private long age; // private float height; // private double weight; // private boolean hasTail; // private Date birthday; // private Owner owner; // // public Dog() { // } // // public Dog(String name) { // this.name = name; // } // // public Owner getOwner() { // return owner; // } // // public void setOwner(Owner owner) { // this.owner = owner; // } // // public Date getBirthday() { // return birthday; // } // // public void setBirthday(Date birthday) { // this.birthday = birthday; // } // // public boolean isHasTail() { // return hasTail; // } // // public void setHasTail(boolean hasTail) { // this.hasTail = hasTail; // } // // public double getWeight() { // return weight; // } // // public void setWeight(double weight) { // this.weight = weight; // } // // public float getHeight() { // return height; // } // // public void setHeight(float height) { // this.height = height; // } // // public long getAge() { // return age; // } // // public void setAge(long age) { // this.age = age; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public static String getStaticName(Dog dog) { // return dog.name; // } // } // // Path: library/src/androidTest/java/com/thefinestartist/royal/entities/DogPrimaryKey.java // public class DogPrimaryKey extends RealmObject { // // @PrimaryKey // private long id; // private String name; // private long age; // private float height; // private double weight; // private boolean hasTail; // private Date birthday; // private Owner owner; // // public DogPrimaryKey() { // // } // // public DogPrimaryKey(long id, String name) { // this.id = id; // this.name = name; // } // // public DogPrimaryKey(String name) { // this.name = name; // } // // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public Owner getOwner() { // return owner; // } // // public void setOwner(Owner owner) { // this.owner = owner; // } // // public Date getBirthday() { // return birthday; // } // // public void setBirthday(Date birthday) { // this.birthday = birthday; // } // // public boolean isHasTail() { // return hasTail; // } // // public void setHasTail(boolean hasTail) { // this.hasTail = hasTail; // } // // public double getWeight() { // return weight; // } // // public void setWeight(double weight) { // this.weight = weight; // } // // public float getHeight() { // return height; // } // // public void setHeight(float height) { // this.height = height; // } // // public long getAge() { // return age; // } // // public void setAge(long age) { // this.age = age; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // }
import android.test.AndroidTestCase; import com.orhanobut.logger.Logger; import com.thefinestartist.royal.entities.Dog; import com.thefinestartist.royal.entities.DogPrimaryKey; import io.realm.internal.Util;
package io.realm; /** * Created by TheFinestArtist on 7/7/15. */ public class RoyalAccessTest extends AndroidTestCase { @Override protected void setUp() throws Exception { } @Override protected void tearDown() throws Exception { } public void testGetRealm1() { // 1. Realm Setup RealmConfiguration realmConfig1 = new RealmConfiguration.Builder(getContext()).name("1testGetRealm1.realm").build(); Realm.deleteRealm(realmConfig1); Realm realm1 = Realm.getInstance(realmConfig1); RealmConfiguration realmConfig2 = new RealmConfiguration.Builder(getContext()).name("2testGetRealm1.realm").build(); Realm.deleteRealm(realmConfig2); Realm realm2 = Realm.getInstance(realmConfig2); // 2. Object Setup Dog dog1 = new Dog(); dog1.setName("Kitty1");
// Path: library/src/androidTest/java/com/thefinestartist/royal/entities/Dog.java // public class Dog extends RealmObject { // // @Index // private String name; // private long age; // private float height; // private double weight; // private boolean hasTail; // private Date birthday; // private Owner owner; // // public Dog() { // } // // public Dog(String name) { // this.name = name; // } // // public Owner getOwner() { // return owner; // } // // public void setOwner(Owner owner) { // this.owner = owner; // } // // public Date getBirthday() { // return birthday; // } // // public void setBirthday(Date birthday) { // this.birthday = birthday; // } // // public boolean isHasTail() { // return hasTail; // } // // public void setHasTail(boolean hasTail) { // this.hasTail = hasTail; // } // // public double getWeight() { // return weight; // } // // public void setWeight(double weight) { // this.weight = weight; // } // // public float getHeight() { // return height; // } // // public void setHeight(float height) { // this.height = height; // } // // public long getAge() { // return age; // } // // public void setAge(long age) { // this.age = age; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public static String getStaticName(Dog dog) { // return dog.name; // } // } // // Path: library/src/androidTest/java/com/thefinestartist/royal/entities/DogPrimaryKey.java // public class DogPrimaryKey extends RealmObject { // // @PrimaryKey // private long id; // private String name; // private long age; // private float height; // private double weight; // private boolean hasTail; // private Date birthday; // private Owner owner; // // public DogPrimaryKey() { // // } // // public DogPrimaryKey(long id, String name) { // this.id = id; // this.name = name; // } // // public DogPrimaryKey(String name) { // this.name = name; // } // // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public Owner getOwner() { // return owner; // } // // public void setOwner(Owner owner) { // this.owner = owner; // } // // public Date getBirthday() { // return birthday; // } // // public void setBirthday(Date birthday) { // this.birthday = birthday; // } // // public boolean isHasTail() { // return hasTail; // } // // public void setHasTail(boolean hasTail) { // this.hasTail = hasTail; // } // // public double getWeight() { // return weight; // } // // public void setWeight(double weight) { // this.weight = weight; // } // // public float getHeight() { // return height; // } // // public void setHeight(float height) { // this.height = height; // } // // public long getAge() { // return age; // } // // public void setAge(long age) { // this.age = age; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // } // Path: library/src/androidTest/java/io/realm/RoyalAccessTest.java import android.test.AndroidTestCase; import com.orhanobut.logger.Logger; import com.thefinestartist.royal.entities.Dog; import com.thefinestartist.royal.entities.DogPrimaryKey; import io.realm.internal.Util; package io.realm; /** * Created by TheFinestArtist on 7/7/15. */ public class RoyalAccessTest extends AndroidTestCase { @Override protected void setUp() throws Exception { } @Override protected void tearDown() throws Exception { } public void testGetRealm1() { // 1. Realm Setup RealmConfiguration realmConfig1 = new RealmConfiguration.Builder(getContext()).name("1testGetRealm1.realm").build(); Realm.deleteRealm(realmConfig1); Realm realm1 = Realm.getInstance(realmConfig1); RealmConfiguration realmConfig2 = new RealmConfiguration.Builder(getContext()).name("2testGetRealm1.realm").build(); Realm.deleteRealm(realmConfig2); Realm realm2 = Realm.getInstance(realmConfig2); // 2. Object Setup Dog dog1 = new Dog(); dog1.setName("Kitty1");
DogPrimaryKey dog2 = new DogPrimaryKey();
TheFinestArtist/Royal-Android
library/src/androidTest/java/com/thefinestartist/royal/RoyalDatabaseTest.java
// Path: library/src/androidTest/java/com/thefinestartist/royal/databases/SecondaryDatabase.java // public class SecondaryDatabase extends RoyalDatabase { // // public String getFileName() { // return "secondary"; // } // // public boolean forCache() { // return false; // } // // public byte[] getEncryptionKey() { // return null; // } // // public int getVersion() { // return 0; // } // // public boolean shouldDeleteIfMigrationNeeded() { // return false; // } // // public Set<Object> getModules() { // Set<Object> set = new HashSet<>(); // set.add(new SecondaryModule()); // return set; // } // // @Override // public long execute(Realm realm, long version) { // return getVersion(); // } // // @RealmModule(classes = {Dog.class, Cat.class, Owner.class}) // public static class SecondaryModule { // } // }
import android.test.AndroidTestCase; import com.thefinestartist.royal.databases.SecondaryDatabase;
package com.thefinestartist.royal; /** * Created by TheFinestArtist on 7/12/15. */ public class RoyalDatabaseTest extends AndroidTestCase { @Override protected void setUp() throws Exception { Royal.joinWith(getContext());
// Path: library/src/androidTest/java/com/thefinestartist/royal/databases/SecondaryDatabase.java // public class SecondaryDatabase extends RoyalDatabase { // // public String getFileName() { // return "secondary"; // } // // public boolean forCache() { // return false; // } // // public byte[] getEncryptionKey() { // return null; // } // // public int getVersion() { // return 0; // } // // public boolean shouldDeleteIfMigrationNeeded() { // return false; // } // // public Set<Object> getModules() { // Set<Object> set = new HashSet<>(); // set.add(new SecondaryModule()); // return set; // } // // @Override // public long execute(Realm realm, long version) { // return getVersion(); // } // // @RealmModule(classes = {Dog.class, Cat.class, Owner.class}) // public static class SecondaryModule { // } // } // Path: library/src/androidTest/java/com/thefinestartist/royal/RoyalDatabaseTest.java import android.test.AndroidTestCase; import com.thefinestartist.royal.databases.SecondaryDatabase; package com.thefinestartist.royal; /** * Created by TheFinestArtist on 7/12/15. */ public class RoyalDatabaseTest extends AndroidTestCase { @Override protected void setUp() throws Exception { Royal.joinWith(getContext());
Royal.addDatabase(new SecondaryDatabase());
TheFinestArtist/Royal-Android
library/src/androidTest/java/io/realm/RealmTest.java
// Path: library/src/androidTest/java/com/thefinestartist/royal/entities/Dog.java // public class Dog extends RealmObject { // // @Index // private String name; // private long age; // private float height; // private double weight; // private boolean hasTail; // private Date birthday; // private Owner owner; // // public Dog() { // } // // public Dog(String name) { // this.name = name; // } // // public Owner getOwner() { // return owner; // } // // public void setOwner(Owner owner) { // this.owner = owner; // } // // public Date getBirthday() { // return birthday; // } // // public void setBirthday(Date birthday) { // this.birthday = birthday; // } // // public boolean isHasTail() { // return hasTail; // } // // public void setHasTail(boolean hasTail) { // this.hasTail = hasTail; // } // // public double getWeight() { // return weight; // } // // public void setWeight(double weight) { // this.weight = weight; // } // // public float getHeight() { // return height; // } // // public void setHeight(float height) { // this.height = height; // } // // public long getAge() { // return age; // } // // public void setAge(long age) { // this.age = age; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public static String getStaticName(Dog dog) { // return dog.name; // } // }
import android.os.Handler; import android.os.Looper; import android.os.Message; import android.test.AndroidTestCase; import com.orhanobut.logger.Logger; import com.thefinestartist.royal.entities.Dog;
package io.realm; /** * Created by TheFinestArtist on 7/7/15. */ public class RealmTest extends AndroidTestCase { @Override protected void setUp() throws Exception { } @Override protected void tearDown() throws Exception { } public void testClose1() { RealmConfiguration realmConfig1 = new RealmConfiguration.Builder(getContext()).name("1testClose1.realm").build(); Realm.deleteRealm(realmConfig1); Realm realm1 = Realm.getInstance(realmConfig1); realm1 = Realm.getInstance(realmConfig1); realm1.close(); realm1.beginTransaction();
// Path: library/src/androidTest/java/com/thefinestartist/royal/entities/Dog.java // public class Dog extends RealmObject { // // @Index // private String name; // private long age; // private float height; // private double weight; // private boolean hasTail; // private Date birthday; // private Owner owner; // // public Dog() { // } // // public Dog(String name) { // this.name = name; // } // // public Owner getOwner() { // return owner; // } // // public void setOwner(Owner owner) { // this.owner = owner; // } // // public Date getBirthday() { // return birthday; // } // // public void setBirthday(Date birthday) { // this.birthday = birthday; // } // // public boolean isHasTail() { // return hasTail; // } // // public void setHasTail(boolean hasTail) { // this.hasTail = hasTail; // } // // public double getWeight() { // return weight; // } // // public void setWeight(double weight) { // this.weight = weight; // } // // public float getHeight() { // return height; // } // // public void setHeight(float height) { // this.height = height; // } // // public long getAge() { // return age; // } // // public void setAge(long age) { // this.age = age; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public static String getStaticName(Dog dog) { // return dog.name; // } // } // Path: library/src/androidTest/java/io/realm/RealmTest.java import android.os.Handler; import android.os.Looper; import android.os.Message; import android.test.AndroidTestCase; import com.orhanobut.logger.Logger; import com.thefinestartist.royal.entities.Dog; package io.realm; /** * Created by TheFinestArtist on 7/7/15. */ public class RealmTest extends AndroidTestCase { @Override protected void setUp() throws Exception { } @Override protected void tearDown() throws Exception { } public void testClose1() { RealmConfiguration realmConfig1 = new RealmConfiguration.Builder(getContext()).name("1testClose1.realm").build(); Realm.deleteRealm(realmConfig1); Realm realm1 = Realm.getInstance(realmConfig1); realm1 = Realm.getInstance(realmConfig1); realm1.close(); realm1.beginTransaction();
Dog dog1 = new Dog();
TheFinestArtist/Royal-Android
library/src/main/java/com/thefinestartist/royal/RoyalTransaction.java
// Path: library/src/main/java/com/thefinestartist/royal/listener/OnRoyalListener.java // public abstract class OnRoyalListener { // public void onUpdated() {} // public void onDeleted() {} // } // // Path: library/src/main/java/io/realm/RoyalAccess.java // public class RoyalAccess { // // public static Realm getRealm(@NonNull RealmObject object) { // return object.realm; // } // // public static Row getRow(@NonNull RealmObject object) { // return object.row; // } // // public static Table getTable(@NonNull RealmObject object) { // return object.row == null ? null : object.row.getTable(); // } // // public static boolean isProxy(@NonNull RealmObject object) { // return object instanceof RealmObjectProxy; // } // // public static boolean hasPrimaryKey(@NonNull Realm realm, @NonNull RealmObject object) { // return realm.getTable(object.getClass()).hasPrimaryKey(); // } // // public static Class<? extends RealmObject> getClass(@NonNull Realm realm, @NonNull Table table) { // List<Class<? extends RealmObject>> classes = realm.getConfiguration().getSchemaMediator().getModelClasses(); // for (Class<? extends RealmObject> clazz : classes) // if (realm.getTable(clazz).getName().equals(table.getName())) // return clazz; // // return null; // } // // public static RealmObject get(@NonNull Realm realm, @NonNull Table table, long rowIndex) { // if (rowIndex < 0) // return null; // // UncheckedRow row = table.getUncheckedRow(rowIndex); // RealmObject result = realm.getConfiguration().getSchemaMediator().newInstance(getClass(realm, table)); // result.row = row; // result.realm = realm; // return result; // } // // // TODO: Free RealmObject from Realm // // // // TODO: Clone RealmObject without Realm information // // TODO: Problem #1 Serializing RealmObject has same speed of just committing it using Realm // // }
import android.os.AsyncTask; import android.support.annotation.NonNull; import com.thefinestartist.royal.listener.OnRoyalListener; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import io.realm.Realm; import io.realm.RealmConfiguration; import io.realm.RealmObject; import io.realm.RoyalAccess; import io.realm.exceptions.RealmException;
for (Object object : objects) { if (object instanceof RealmObject) { realmObjects.add((RealmObject) object); } else if (object instanceof List) { for (Object realmObject : (List) object) { if (realmObject instanceof RealmObject) realmObjects.add((RealmObject) realmObject); else if (realmObject != null) throw new IllegalArgumentException(realmObject.getClass().getName() + " is not allowed to save in Realm."); } } else if (object != null) throw new IllegalArgumentException(object.getClass().getName() + " is not allowed to save in Realm."); } boolean transactionStarted = false; try { realm.beginTransaction(); } catch (IllegalStateException e) { if (e.getMessage().contains("commitTransaction")) transactionStarted = true; } try { switch (type) { case CREATE: for (RealmObject realmObject : realmObjects) realm.copyToRealm(realmObject); break; case CREATE_OR_UPDATE: for (RealmObject realmObject : realmObjects) {
// Path: library/src/main/java/com/thefinestartist/royal/listener/OnRoyalListener.java // public abstract class OnRoyalListener { // public void onUpdated() {} // public void onDeleted() {} // } // // Path: library/src/main/java/io/realm/RoyalAccess.java // public class RoyalAccess { // // public static Realm getRealm(@NonNull RealmObject object) { // return object.realm; // } // // public static Row getRow(@NonNull RealmObject object) { // return object.row; // } // // public static Table getTable(@NonNull RealmObject object) { // return object.row == null ? null : object.row.getTable(); // } // // public static boolean isProxy(@NonNull RealmObject object) { // return object instanceof RealmObjectProxy; // } // // public static boolean hasPrimaryKey(@NonNull Realm realm, @NonNull RealmObject object) { // return realm.getTable(object.getClass()).hasPrimaryKey(); // } // // public static Class<? extends RealmObject> getClass(@NonNull Realm realm, @NonNull Table table) { // List<Class<? extends RealmObject>> classes = realm.getConfiguration().getSchemaMediator().getModelClasses(); // for (Class<? extends RealmObject> clazz : classes) // if (realm.getTable(clazz).getName().equals(table.getName())) // return clazz; // // return null; // } // // public static RealmObject get(@NonNull Realm realm, @NonNull Table table, long rowIndex) { // if (rowIndex < 0) // return null; // // UncheckedRow row = table.getUncheckedRow(rowIndex); // RealmObject result = realm.getConfiguration().getSchemaMediator().newInstance(getClass(realm, table)); // result.row = row; // result.realm = realm; // return result; // } // // // TODO: Free RealmObject from Realm // // // // TODO: Clone RealmObject without Realm information // // TODO: Problem #1 Serializing RealmObject has same speed of just committing it using Realm // // } // Path: library/src/main/java/com/thefinestartist/royal/RoyalTransaction.java import android.os.AsyncTask; import android.support.annotation.NonNull; import com.thefinestartist.royal.listener.OnRoyalListener; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import io.realm.Realm; import io.realm.RealmConfiguration; import io.realm.RealmObject; import io.realm.RoyalAccess; import io.realm.exceptions.RealmException; for (Object object : objects) { if (object instanceof RealmObject) { realmObjects.add((RealmObject) object); } else if (object instanceof List) { for (Object realmObject : (List) object) { if (realmObject instanceof RealmObject) realmObjects.add((RealmObject) realmObject); else if (realmObject != null) throw new IllegalArgumentException(realmObject.getClass().getName() + " is not allowed to save in Realm."); } } else if (object != null) throw new IllegalArgumentException(object.getClass().getName() + " is not allowed to save in Realm."); } boolean transactionStarted = false; try { realm.beginTransaction(); } catch (IllegalStateException e) { if (e.getMessage().contains("commitTransaction")) transactionStarted = true; } try { switch (type) { case CREATE: for (RealmObject realmObject : realmObjects) realm.copyToRealm(realmObject); break; case CREATE_OR_UPDATE: for (RealmObject realmObject : realmObjects) {
if (RoyalAccess.hasPrimaryKey(realm, realmObject))
TheFinestArtist/Royal-Android
library/src/main/java/com/thefinestartist/royal/RoyalTransaction.java
// Path: library/src/main/java/com/thefinestartist/royal/listener/OnRoyalListener.java // public abstract class OnRoyalListener { // public void onUpdated() {} // public void onDeleted() {} // } // // Path: library/src/main/java/io/realm/RoyalAccess.java // public class RoyalAccess { // // public static Realm getRealm(@NonNull RealmObject object) { // return object.realm; // } // // public static Row getRow(@NonNull RealmObject object) { // return object.row; // } // // public static Table getTable(@NonNull RealmObject object) { // return object.row == null ? null : object.row.getTable(); // } // // public static boolean isProxy(@NonNull RealmObject object) { // return object instanceof RealmObjectProxy; // } // // public static boolean hasPrimaryKey(@NonNull Realm realm, @NonNull RealmObject object) { // return realm.getTable(object.getClass()).hasPrimaryKey(); // } // // public static Class<? extends RealmObject> getClass(@NonNull Realm realm, @NonNull Table table) { // List<Class<? extends RealmObject>> classes = realm.getConfiguration().getSchemaMediator().getModelClasses(); // for (Class<? extends RealmObject> clazz : classes) // if (realm.getTable(clazz).getName().equals(table.getName())) // return clazz; // // return null; // } // // public static RealmObject get(@NonNull Realm realm, @NonNull Table table, long rowIndex) { // if (rowIndex < 0) // return null; // // UncheckedRow row = table.getUncheckedRow(rowIndex); // RealmObject result = realm.getConfiguration().getSchemaMediator().newInstance(getClass(realm, table)); // result.row = row; // result.realm = realm; // return result; // } // // // TODO: Free RealmObject from Realm // // // // TODO: Clone RealmObject without Realm information // // TODO: Problem #1 Serializing RealmObject has same speed of just committing it using Realm // // }
import android.os.AsyncTask; import android.support.annotation.NonNull; import com.thefinestartist.royal.listener.OnRoyalListener; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import io.realm.Realm; import io.realm.RealmConfiguration; import io.realm.RealmObject; import io.realm.RoyalAccess; import io.realm.exceptions.RealmException;
// // Set<Realm> realms = getRealms(objects); // new SaveTask(realm.getConfiguration(), realms, listener).execute(objects); // // new SaveTask(realm.getConfiguration(), null, listener).execute(objects); // } private static Set<Realm> getRealms(RealmObject[] objects) { Set<Realm> realms = new HashSet<>(); for (RealmObject object : objects) realms.add(RoyalAccess.getRealm(object)); realms.remove(null); return realms; } private static void incrementReferenceCount(Set<Realm> realms) { for (Realm realm : realms) { Realm newRealm = Realm.getInstance(realm.getConfiguration()); } } private static void decrementReferenceCount(Set<Realm> realms) { for (Realm realm : realms) realm.close(); } static class SaveTask extends AsyncTask<RealmObject, Void, Void> { RealmConfiguration configuration; Set<Realm> realms;
// Path: library/src/main/java/com/thefinestartist/royal/listener/OnRoyalListener.java // public abstract class OnRoyalListener { // public void onUpdated() {} // public void onDeleted() {} // } // // Path: library/src/main/java/io/realm/RoyalAccess.java // public class RoyalAccess { // // public static Realm getRealm(@NonNull RealmObject object) { // return object.realm; // } // // public static Row getRow(@NonNull RealmObject object) { // return object.row; // } // // public static Table getTable(@NonNull RealmObject object) { // return object.row == null ? null : object.row.getTable(); // } // // public static boolean isProxy(@NonNull RealmObject object) { // return object instanceof RealmObjectProxy; // } // // public static boolean hasPrimaryKey(@NonNull Realm realm, @NonNull RealmObject object) { // return realm.getTable(object.getClass()).hasPrimaryKey(); // } // // public static Class<? extends RealmObject> getClass(@NonNull Realm realm, @NonNull Table table) { // List<Class<? extends RealmObject>> classes = realm.getConfiguration().getSchemaMediator().getModelClasses(); // for (Class<? extends RealmObject> clazz : classes) // if (realm.getTable(clazz).getName().equals(table.getName())) // return clazz; // // return null; // } // // public static RealmObject get(@NonNull Realm realm, @NonNull Table table, long rowIndex) { // if (rowIndex < 0) // return null; // // UncheckedRow row = table.getUncheckedRow(rowIndex); // RealmObject result = realm.getConfiguration().getSchemaMediator().newInstance(getClass(realm, table)); // result.row = row; // result.realm = realm; // return result; // } // // // TODO: Free RealmObject from Realm // // // // TODO: Clone RealmObject without Realm information // // TODO: Problem #1 Serializing RealmObject has same speed of just committing it using Realm // // } // Path: library/src/main/java/com/thefinestartist/royal/RoyalTransaction.java import android.os.AsyncTask; import android.support.annotation.NonNull; import com.thefinestartist.royal.listener.OnRoyalListener; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import io.realm.Realm; import io.realm.RealmConfiguration; import io.realm.RealmObject; import io.realm.RoyalAccess; import io.realm.exceptions.RealmException; // // Set<Realm> realms = getRealms(objects); // new SaveTask(realm.getConfiguration(), realms, listener).execute(objects); // // new SaveTask(realm.getConfiguration(), null, listener).execute(objects); // } private static Set<Realm> getRealms(RealmObject[] objects) { Set<Realm> realms = new HashSet<>(); for (RealmObject object : objects) realms.add(RoyalAccess.getRealm(object)); realms.remove(null); return realms; } private static void incrementReferenceCount(Set<Realm> realms) { for (Realm realm : realms) { Realm newRealm = Realm.getInstance(realm.getConfiguration()); } } private static void decrementReferenceCount(Set<Realm> realms) { for (Realm realm : realms) realm.close(); } static class SaveTask extends AsyncTask<RealmObject, Void, Void> { RealmConfiguration configuration; Set<Realm> realms;
OnRoyalListener listener;
TheFinestArtist/Royal-Android
library/src/main/java/com/thefinestartist/royal/RoyalExport.java
// Path: library/src/main/java/com/thefinestartist/royal/util/ByteUtil.java // public class ByteUtil { // // public static int byteArrayToLeInt(byte[] b) { // final ByteBuffer bb = ByteBuffer.wrap(b); // bb.order(ByteOrder.LITTLE_ENDIAN); // return bb.getInt(); // } // // public static byte[] leIntToByteArray(int i) { // final ByteBuffer bb = ByteBuffer.allocate(Integer.SIZE / Byte.SIZE); // bb.order(ByteOrder.LITTLE_ENDIAN); // bb.putInt(i); // return bb.array(); // } // // // public static int byteArrayToLeInt(byte[] encodedValue) { // // int value = (encodedValue[3] << (Byte.SIZE * 3)); // // value |= (encodedValue[2] & 0xFF) << (Byte.SIZE * 2); // // value |= (encodedValue[1] & 0xFF) << (Byte.SIZE * 1); // // value |= (encodedValue[0] & 0xFF); // // return value; // // } // // // // public static byte[] leIntToByteArray(int value) { // // byte[] encodedValue = new byte[Integer.SIZE / Byte.SIZE]; // // encodedValue[3] = (byte) (value >> Byte.SIZE * 3); // // encodedValue[2] = (byte) (value >> Byte.SIZE * 2); // // encodedValue[1] = (byte) (value >> Byte.SIZE); // // encodedValue[0] = (byte) value; // // return encodedValue; // // } // // } // // Path: library/src/main/java/com/thefinestartist/royal/util/FileUtil.java // public class FileUtil { // // public static List<File> getFilesFrom(File parentDir, String extension) { // ArrayList<File> inFiles = new ArrayList<>(); // File[] files = parentDir.listFiles(); // for (File file : files) { // if (file.isDirectory()) { // inFiles.addAll(getFilesFrom(file, extension)); // } else { // if(file.getName().endsWith(extension)){ // inFiles.add(file); // } // } // } // return inFiles; // } // // public static void copy(File src, File dst) { // try { // InputStream in = new FileInputStream(src); // OutputStream out = new FileOutputStream(dst); // // // Transfer bytes from in to out // byte[] buf = new byte[1024]; // int len; // while ((len = in.read(buf)) > 0) { // out.write(buf, 0, len); // } // in.close(); // out.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // }
import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Environment; import com.thefinestartist.royal.util.ByteUtil; import com.thefinestartist.royal.util.FileUtil; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import io.realm.Realm; import io.realm.RealmConfiguration;
StringBuilder subject = new StringBuilder(); subject.append("[Royal] Exported "); subject.append(uris.size()); subject.append(" realm file"); if (uris.size() > 1) subject.append("s"); intent.putExtra(Intent.EXTRA_SUBJECT, subject.toString()); } // Message build if (intent.getStringExtra(Intent.EXTRA_TEXT) == null) { StringBuilder message = new StringBuilder(); for (Realm realm : realms) { RealmConfiguration configuration = realm.getConfiguration(); message.append("Name: "); message.append(configuration.getRealmFileName()); message.append("\n"); message.append("Version: "); message.append(configuration.getSchemaVersion()); message.append("\n"); message.append("Path: "); message.append(configuration.getPath()); message.append("\n"); message.append("Encryption Key: "); byte[] key = configuration.getEncryptionKey(); if (key != null) {
// Path: library/src/main/java/com/thefinestartist/royal/util/ByteUtil.java // public class ByteUtil { // // public static int byteArrayToLeInt(byte[] b) { // final ByteBuffer bb = ByteBuffer.wrap(b); // bb.order(ByteOrder.LITTLE_ENDIAN); // return bb.getInt(); // } // // public static byte[] leIntToByteArray(int i) { // final ByteBuffer bb = ByteBuffer.allocate(Integer.SIZE / Byte.SIZE); // bb.order(ByteOrder.LITTLE_ENDIAN); // bb.putInt(i); // return bb.array(); // } // // // public static int byteArrayToLeInt(byte[] encodedValue) { // // int value = (encodedValue[3] << (Byte.SIZE * 3)); // // value |= (encodedValue[2] & 0xFF) << (Byte.SIZE * 2); // // value |= (encodedValue[1] & 0xFF) << (Byte.SIZE * 1); // // value |= (encodedValue[0] & 0xFF); // // return value; // // } // // // // public static byte[] leIntToByteArray(int value) { // // byte[] encodedValue = new byte[Integer.SIZE / Byte.SIZE]; // // encodedValue[3] = (byte) (value >> Byte.SIZE * 3); // // encodedValue[2] = (byte) (value >> Byte.SIZE * 2); // // encodedValue[1] = (byte) (value >> Byte.SIZE); // // encodedValue[0] = (byte) value; // // return encodedValue; // // } // // } // // Path: library/src/main/java/com/thefinestartist/royal/util/FileUtil.java // public class FileUtil { // // public static List<File> getFilesFrom(File parentDir, String extension) { // ArrayList<File> inFiles = new ArrayList<>(); // File[] files = parentDir.listFiles(); // for (File file : files) { // if (file.isDirectory()) { // inFiles.addAll(getFilesFrom(file, extension)); // } else { // if(file.getName().endsWith(extension)){ // inFiles.add(file); // } // } // } // return inFiles; // } // // public static void copy(File src, File dst) { // try { // InputStream in = new FileInputStream(src); // OutputStream out = new FileOutputStream(dst); // // // Transfer bytes from in to out // byte[] buf = new byte[1024]; // int len; // while ((len = in.read(buf)) > 0) { // out.write(buf, 0, len); // } // in.close(); // out.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // Path: library/src/main/java/com/thefinestartist/royal/RoyalExport.java import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Environment; import com.thefinestartist.royal.util.ByteUtil; import com.thefinestartist.royal.util.FileUtil; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import io.realm.Realm; import io.realm.RealmConfiguration; StringBuilder subject = new StringBuilder(); subject.append("[Royal] Exported "); subject.append(uris.size()); subject.append(" realm file"); if (uris.size() > 1) subject.append("s"); intent.putExtra(Intent.EXTRA_SUBJECT, subject.toString()); } // Message build if (intent.getStringExtra(Intent.EXTRA_TEXT) == null) { StringBuilder message = new StringBuilder(); for (Realm realm : realms) { RealmConfiguration configuration = realm.getConfiguration(); message.append("Name: "); message.append(configuration.getRealmFileName()); message.append("\n"); message.append("Version: "); message.append(configuration.getSchemaVersion()); message.append("\n"); message.append("Path: "); message.append(configuration.getPath()); message.append("\n"); message.append("Encryption Key: "); byte[] key = configuration.getEncryptionKey(); if (key != null) {
message.append(ByteUtil.byteArrayToLeInt(key));
TheFinestArtist/Royal-Android
library/src/main/java/com/thefinestartist/royal/RoyalExport.java
// Path: library/src/main/java/com/thefinestartist/royal/util/ByteUtil.java // public class ByteUtil { // // public static int byteArrayToLeInt(byte[] b) { // final ByteBuffer bb = ByteBuffer.wrap(b); // bb.order(ByteOrder.LITTLE_ENDIAN); // return bb.getInt(); // } // // public static byte[] leIntToByteArray(int i) { // final ByteBuffer bb = ByteBuffer.allocate(Integer.SIZE / Byte.SIZE); // bb.order(ByteOrder.LITTLE_ENDIAN); // bb.putInt(i); // return bb.array(); // } // // // public static int byteArrayToLeInt(byte[] encodedValue) { // // int value = (encodedValue[3] << (Byte.SIZE * 3)); // // value |= (encodedValue[2] & 0xFF) << (Byte.SIZE * 2); // // value |= (encodedValue[1] & 0xFF) << (Byte.SIZE * 1); // // value |= (encodedValue[0] & 0xFF); // // return value; // // } // // // // public static byte[] leIntToByteArray(int value) { // // byte[] encodedValue = new byte[Integer.SIZE / Byte.SIZE]; // // encodedValue[3] = (byte) (value >> Byte.SIZE * 3); // // encodedValue[2] = (byte) (value >> Byte.SIZE * 2); // // encodedValue[1] = (byte) (value >> Byte.SIZE); // // encodedValue[0] = (byte) value; // // return encodedValue; // // } // // } // // Path: library/src/main/java/com/thefinestartist/royal/util/FileUtil.java // public class FileUtil { // // public static List<File> getFilesFrom(File parentDir, String extension) { // ArrayList<File> inFiles = new ArrayList<>(); // File[] files = parentDir.listFiles(); // for (File file : files) { // if (file.isDirectory()) { // inFiles.addAll(getFilesFrom(file, extension)); // } else { // if(file.getName().endsWith(extension)){ // inFiles.add(file); // } // } // } // return inFiles; // } // // public static void copy(File src, File dst) { // try { // InputStream in = new FileInputStream(src); // OutputStream out = new FileOutputStream(dst); // // // Transfer bytes from in to out // byte[] buf = new byte[1024]; // int len; // while ((len = in.read(buf)) > 0) { // out.write(buf, 0, len); // } // in.close(); // out.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // }
import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Environment; import com.thefinestartist.royal.util.ByteUtil; import com.thefinestartist.royal.util.FileUtil; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import io.realm.Realm; import io.realm.RealmConfiguration;
message.append(" "); } message.append(Arrays.toString(key)); message.append("\n"); message.append("\n"); } intent.putExtra(Intent.EXTRA_TEXT, message.toString()); } Intent chooser = Intent.createChooser(intent, "Choose Email Application").addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(chooser); } catch (IOException e) { e.printStackTrace(); } } public static void toEmailAsRawFile() { toEmailAsRawFile(null); } public static void toEmailAsRawFile(String email) { toEmailAsRawFile(email, null); } // No Decryption public static void toEmailAsRawFile(String email, Intent intent) { Context context = Royal.getApplicationContext();
// Path: library/src/main/java/com/thefinestartist/royal/util/ByteUtil.java // public class ByteUtil { // // public static int byteArrayToLeInt(byte[] b) { // final ByteBuffer bb = ByteBuffer.wrap(b); // bb.order(ByteOrder.LITTLE_ENDIAN); // return bb.getInt(); // } // // public static byte[] leIntToByteArray(int i) { // final ByteBuffer bb = ByteBuffer.allocate(Integer.SIZE / Byte.SIZE); // bb.order(ByteOrder.LITTLE_ENDIAN); // bb.putInt(i); // return bb.array(); // } // // // public static int byteArrayToLeInt(byte[] encodedValue) { // // int value = (encodedValue[3] << (Byte.SIZE * 3)); // // value |= (encodedValue[2] & 0xFF) << (Byte.SIZE * 2); // // value |= (encodedValue[1] & 0xFF) << (Byte.SIZE * 1); // // value |= (encodedValue[0] & 0xFF); // // return value; // // } // // // // public static byte[] leIntToByteArray(int value) { // // byte[] encodedValue = new byte[Integer.SIZE / Byte.SIZE]; // // encodedValue[3] = (byte) (value >> Byte.SIZE * 3); // // encodedValue[2] = (byte) (value >> Byte.SIZE * 2); // // encodedValue[1] = (byte) (value >> Byte.SIZE); // // encodedValue[0] = (byte) value; // // return encodedValue; // // } // // } // // Path: library/src/main/java/com/thefinestartist/royal/util/FileUtil.java // public class FileUtil { // // public static List<File> getFilesFrom(File parentDir, String extension) { // ArrayList<File> inFiles = new ArrayList<>(); // File[] files = parentDir.listFiles(); // for (File file : files) { // if (file.isDirectory()) { // inFiles.addAll(getFilesFrom(file, extension)); // } else { // if(file.getName().endsWith(extension)){ // inFiles.add(file); // } // } // } // return inFiles; // } // // public static void copy(File src, File dst) { // try { // InputStream in = new FileInputStream(src); // OutputStream out = new FileOutputStream(dst); // // // Transfer bytes from in to out // byte[] buf = new byte[1024]; // int len; // while ((len = in.read(buf)) > 0) { // out.write(buf, 0, len); // } // in.close(); // out.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // Path: library/src/main/java/com/thefinestartist/royal/RoyalExport.java import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Environment; import com.thefinestartist.royal.util.ByteUtil; import com.thefinestartist.royal.util.FileUtil; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import io.realm.Realm; import io.realm.RealmConfiguration; message.append(" "); } message.append(Arrays.toString(key)); message.append("\n"); message.append("\n"); } intent.putExtra(Intent.EXTRA_TEXT, message.toString()); } Intent chooser = Intent.createChooser(intent, "Choose Email Application").addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(chooser); } catch (IOException e) { e.printStackTrace(); } } public static void toEmailAsRawFile() { toEmailAsRawFile(null); } public static void toEmailAsRawFile(String email) { toEmailAsRawFile(email, null); } // No Decryption public static void toEmailAsRawFile(String email, Intent intent) { Context context = Royal.getApplicationContext();
List<File> files = FileUtil.getFilesFrom(context.getFilesDir(), ".realm");
ParaskP7/sample-code-posts
app/src/main/java/io/petros/posts/app/graph/modules/NetModule.java
// Path: app/src/main/java/io/petros/posts/service/retrofit/RetrofitService.java // public interface RetrofitService { // // @GET("/posts") // Observable<List<Post>> posts(); // // @GET("/users") // Observable<List<User>> users(); // // @GET("/comments") // Observable<List<Comment>> comments(@Query("postId") int postId); // // } // // Path: app/src/main/java/io/petros/posts/util/rx/RxSchedulers.java // public class RxSchedulers { // // /** // * A {@link Scheduler} intended for IO-bound work. The implementation is backed by an {@link java.util.concurrent.Executor} // * thread-pool that will grow as needed. This can be used for asynchronously performing blocking IO. // */ // private final Scheduler ioScheduler; // // /** // * A {@link Scheduler} intended for computational work. This can be used for event-loops, processing callbacks and other // * computational work. Unhandled errors will be delivered to the scheduler Thread's {@link Thread.UncaughtExceptionHandler}. // **/ // private final Scheduler computationScheduler; // // /** // * A {@link Scheduler} that queues work on the current thread to be executed after the current work completes. // */ // private final Scheduler trampolineScheduler; // // /** // * A {@link Scheduler} which executes actions on the Android UI thread. // */ // private final Scheduler androidMainThreadScheduler; // // public RxSchedulers(final Scheduler ioScheduler, final Scheduler computationScheduler, final Scheduler trampolineScheduler, // final Scheduler androidMainThreadScheduler) { // this.ioScheduler = ioScheduler; // this.computationScheduler = computationScheduler; // this.trampolineScheduler = trampolineScheduler; // this.androidMainThreadScheduler = androidMainThreadScheduler; // } // // public Scheduler getIoScheduler() { // return ioScheduler; // } // // public Scheduler getComputationScheduler() { // return computationScheduler; // } // // public Scheduler getTrampolineScheduler() { // return trampolineScheduler; // } // // public Scheduler getAndroidMainThreadScheduler() { // return androidMainThreadScheduler; // } // // }
import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import io.petros.posts.service.retrofit.RetrofitService; import io.petros.posts.util.rx.RxSchedulers; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.schedulers.Schedulers; import retrofit2.Retrofit; import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory;
package io.petros.posts.app.graph.modules; @Module public class NetModule { private final String baseUrl; public NetModule(final String baseUrl) { this.baseUrl = baseUrl; } @Provides @Singleton
// Path: app/src/main/java/io/petros/posts/service/retrofit/RetrofitService.java // public interface RetrofitService { // // @GET("/posts") // Observable<List<Post>> posts(); // // @GET("/users") // Observable<List<User>> users(); // // @GET("/comments") // Observable<List<Comment>> comments(@Query("postId") int postId); // // } // // Path: app/src/main/java/io/petros/posts/util/rx/RxSchedulers.java // public class RxSchedulers { // // /** // * A {@link Scheduler} intended for IO-bound work. The implementation is backed by an {@link java.util.concurrent.Executor} // * thread-pool that will grow as needed. This can be used for asynchronously performing blocking IO. // */ // private final Scheduler ioScheduler; // // /** // * A {@link Scheduler} intended for computational work. This can be used for event-loops, processing callbacks and other // * computational work. Unhandled errors will be delivered to the scheduler Thread's {@link Thread.UncaughtExceptionHandler}. // **/ // private final Scheduler computationScheduler; // // /** // * A {@link Scheduler} that queues work on the current thread to be executed after the current work completes. // */ // private final Scheduler trampolineScheduler; // // /** // * A {@link Scheduler} which executes actions on the Android UI thread. // */ // private final Scheduler androidMainThreadScheduler; // // public RxSchedulers(final Scheduler ioScheduler, final Scheduler computationScheduler, final Scheduler trampolineScheduler, // final Scheduler androidMainThreadScheduler) { // this.ioScheduler = ioScheduler; // this.computationScheduler = computationScheduler; // this.trampolineScheduler = trampolineScheduler; // this.androidMainThreadScheduler = androidMainThreadScheduler; // } // // public Scheduler getIoScheduler() { // return ioScheduler; // } // // public Scheduler getComputationScheduler() { // return computationScheduler; // } // // public Scheduler getTrampolineScheduler() { // return trampolineScheduler; // } // // public Scheduler getAndroidMainThreadScheduler() { // return androidMainThreadScheduler; // } // // } // Path: app/src/main/java/io/petros/posts/app/graph/modules/NetModule.java import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import io.petros.posts.service.retrofit.RetrofitService; import io.petros.posts.util.rx.RxSchedulers; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.schedulers.Schedulers; import retrofit2.Retrofit; import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; package io.petros.posts.app.graph.modules; @Module public class NetModule { private final String baseUrl; public NetModule(final String baseUrl) { this.baseUrl = baseUrl; } @Provides @Singleton
RxSchedulers providesRxSchedulers() {
ParaskP7/sample-code-posts
app/src/main/java/io/petros/posts/app/graph/modules/NetModule.java
// Path: app/src/main/java/io/petros/posts/service/retrofit/RetrofitService.java // public interface RetrofitService { // // @GET("/posts") // Observable<List<Post>> posts(); // // @GET("/users") // Observable<List<User>> users(); // // @GET("/comments") // Observable<List<Comment>> comments(@Query("postId") int postId); // // } // // Path: app/src/main/java/io/petros/posts/util/rx/RxSchedulers.java // public class RxSchedulers { // // /** // * A {@link Scheduler} intended for IO-bound work. The implementation is backed by an {@link java.util.concurrent.Executor} // * thread-pool that will grow as needed. This can be used for asynchronously performing blocking IO. // */ // private final Scheduler ioScheduler; // // /** // * A {@link Scheduler} intended for computational work. This can be used for event-loops, processing callbacks and other // * computational work. Unhandled errors will be delivered to the scheduler Thread's {@link Thread.UncaughtExceptionHandler}. // **/ // private final Scheduler computationScheduler; // // /** // * A {@link Scheduler} that queues work on the current thread to be executed after the current work completes. // */ // private final Scheduler trampolineScheduler; // // /** // * A {@link Scheduler} which executes actions on the Android UI thread. // */ // private final Scheduler androidMainThreadScheduler; // // public RxSchedulers(final Scheduler ioScheduler, final Scheduler computationScheduler, final Scheduler trampolineScheduler, // final Scheduler androidMainThreadScheduler) { // this.ioScheduler = ioScheduler; // this.computationScheduler = computationScheduler; // this.trampolineScheduler = trampolineScheduler; // this.androidMainThreadScheduler = androidMainThreadScheduler; // } // // public Scheduler getIoScheduler() { // return ioScheduler; // } // // public Scheduler getComputationScheduler() { // return computationScheduler; // } // // public Scheduler getTrampolineScheduler() { // return trampolineScheduler; // } // // public Scheduler getAndroidMainThreadScheduler() { // return androidMainThreadScheduler; // } // // }
import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import io.petros.posts.service.retrofit.RetrofitService; import io.petros.posts.util.rx.RxSchedulers; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.schedulers.Schedulers; import retrofit2.Retrofit; import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory;
package io.petros.posts.app.graph.modules; @Module public class NetModule { private final String baseUrl; public NetModule(final String baseUrl) { this.baseUrl = baseUrl; } @Provides @Singleton RxSchedulers providesRxSchedulers() { return new RxSchedulers(Schedulers.io(), Schedulers.computation(), Schedulers.trampoline(), AndroidSchedulers.mainThread()); } @Provides @Singleton
// Path: app/src/main/java/io/petros/posts/service/retrofit/RetrofitService.java // public interface RetrofitService { // // @GET("/posts") // Observable<List<Post>> posts(); // // @GET("/users") // Observable<List<User>> users(); // // @GET("/comments") // Observable<List<Comment>> comments(@Query("postId") int postId); // // } // // Path: app/src/main/java/io/petros/posts/util/rx/RxSchedulers.java // public class RxSchedulers { // // /** // * A {@link Scheduler} intended for IO-bound work. The implementation is backed by an {@link java.util.concurrent.Executor} // * thread-pool that will grow as needed. This can be used for asynchronously performing blocking IO. // */ // private final Scheduler ioScheduler; // // /** // * A {@link Scheduler} intended for computational work. This can be used for event-loops, processing callbacks and other // * computational work. Unhandled errors will be delivered to the scheduler Thread's {@link Thread.UncaughtExceptionHandler}. // **/ // private final Scheduler computationScheduler; // // /** // * A {@link Scheduler} that queues work on the current thread to be executed after the current work completes. // */ // private final Scheduler trampolineScheduler; // // /** // * A {@link Scheduler} which executes actions on the Android UI thread. // */ // private final Scheduler androidMainThreadScheduler; // // public RxSchedulers(final Scheduler ioScheduler, final Scheduler computationScheduler, final Scheduler trampolineScheduler, // final Scheduler androidMainThreadScheduler) { // this.ioScheduler = ioScheduler; // this.computationScheduler = computationScheduler; // this.trampolineScheduler = trampolineScheduler; // this.androidMainThreadScheduler = androidMainThreadScheduler; // } // // public Scheduler getIoScheduler() { // return ioScheduler; // } // // public Scheduler getComputationScheduler() { // return computationScheduler; // } // // public Scheduler getTrampolineScheduler() { // return trampolineScheduler; // } // // public Scheduler getAndroidMainThreadScheduler() { // return androidMainThreadScheduler; // } // // } // Path: app/src/main/java/io/petros/posts/app/graph/modules/NetModule.java import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import io.petros.posts.service.retrofit.RetrofitService; import io.petros.posts.util.rx.RxSchedulers; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.schedulers.Schedulers; import retrofit2.Retrofit; import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; package io.petros.posts.app.graph.modules; @Module public class NetModule { private final String baseUrl; public NetModule(final String baseUrl) { this.baseUrl = baseUrl; } @Provides @Singleton RxSchedulers providesRxSchedulers() { return new RxSchedulers(Schedulers.io(), Schedulers.computation(), Schedulers.trampoline(), AndroidSchedulers.mainThread()); } @Provides @Singleton
RetrofitService provideRetroService() {
ParaskP7/sample-code-posts
app/src/test/java/io/petros/posts/activity/post/view/PostActivityTest.java
// Path: app/src/test/java/io/petros/posts/PreconfiguredRobolectricTestRunner.java // public class PreconfiguredRobolectricTestRunner extends RobolectricTestRunner { // // private static final int SDK_API_LEVEL_TO_EMULATE = 25; // // /** // * Creates a runner to run {@code testClass}. Looks in your working directory for your AndroidManifest.xml file and res directory by // * default. Use the {@link Config} annotation to configure. // * // * @param testClass The test class to be run. // * @throws InitializationError If junit says so. // */ // public PreconfiguredRobolectricTestRunner(final Class<?> testClass) throws InitializationError { // super(testClass); // } // // @Override // protected Config buildGlobalConfig() { // return new Config.Builder() // .setSdk(SDK_API_LEVEL_TO_EMULATE) // .setManifest(Config.NONE) // .setApplication(TestPostsApplication.class) // .build(); // } // // } // // Path: app/src/test/java/io/petros/posts/RobolectricGeneralTestHelper.java // public class RobolectricGeneralTestHelper extends GeneralTestHelper { // // // Application specific fields. // protected final Context context = getTestContext(); // protected final PostsApplication application = getTestApplication(); // // // System specific fields. // @Mock protected ConnectivityManager connectivityManagerMock; // // // Activity specific fields. // @Mock protected PostsApplication applicationMock; // @Mock protected SnackbarActions snackbarActionsMock; // // // ROBOLECTRIC // ******************************************************************************************************* // // private Context getTestContext() { // return getShadowApplication().getApplicationContext(); // } // // private ShadowApplication getShadowApplication() { // return ShadowApplication.getInstance(); // } // // private PostsApplication getTestApplication() { // return (PostsApplication) RuntimeEnvironment.application; // } // // // MOCKS // ************************************************************************************************************* // // protected void setUpMocks() { // super.setUpMocks(); // setUpApplicationMocks(); // } // // private void setUpApplicationMocks() { // when(applicationMock.getSystemService(Context.CONNECTIVITY_SERVICE)).thenReturn(connectivityManagerMock); // when(applicationMock.snackbar()).thenReturn(snackbarActionsMock); // } // // // POST // ************************************************************************************************************** // // protected Bundle getExtras(final Post post) { // final Bundle extras = new Bundle(); // extras.putInt(Post.USER_ID, post.getUserId()); // extras.putInt(Post.ID, post.getId()); // extras.putString(Post.TITLE, post.getTitle()); // extras.putString(Post.BODY, post.getBody()); // return extras; // } // // }
import android.content.Intent; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.Robolectric; import org.robolectric.fakes.RoboMenuItem; import io.petros.posts.PreconfiguredRobolectricTestRunner; import io.petros.posts.RobolectricGeneralTestHelper; import static org.assertj.core.api.Assertions.assertThat;
package io.petros.posts.activity.post.view; /** * This test is ignored until a test Dagger graph is introduced, which will mock all the @Inject objects. */ @Ignore("Problem with Realm: The activity cannot start.") @RunWith(PreconfiguredRobolectricTestRunner.class)
// Path: app/src/test/java/io/petros/posts/PreconfiguredRobolectricTestRunner.java // public class PreconfiguredRobolectricTestRunner extends RobolectricTestRunner { // // private static final int SDK_API_LEVEL_TO_EMULATE = 25; // // /** // * Creates a runner to run {@code testClass}. Looks in your working directory for your AndroidManifest.xml file and res directory by // * default. Use the {@link Config} annotation to configure. // * // * @param testClass The test class to be run. // * @throws InitializationError If junit says so. // */ // public PreconfiguredRobolectricTestRunner(final Class<?> testClass) throws InitializationError { // super(testClass); // } // // @Override // protected Config buildGlobalConfig() { // return new Config.Builder() // .setSdk(SDK_API_LEVEL_TO_EMULATE) // .setManifest(Config.NONE) // .setApplication(TestPostsApplication.class) // .build(); // } // // } // // Path: app/src/test/java/io/petros/posts/RobolectricGeneralTestHelper.java // public class RobolectricGeneralTestHelper extends GeneralTestHelper { // // // Application specific fields. // protected final Context context = getTestContext(); // protected final PostsApplication application = getTestApplication(); // // // System specific fields. // @Mock protected ConnectivityManager connectivityManagerMock; // // // Activity specific fields. // @Mock protected PostsApplication applicationMock; // @Mock protected SnackbarActions snackbarActionsMock; // // // ROBOLECTRIC // ******************************************************************************************************* // // private Context getTestContext() { // return getShadowApplication().getApplicationContext(); // } // // private ShadowApplication getShadowApplication() { // return ShadowApplication.getInstance(); // } // // private PostsApplication getTestApplication() { // return (PostsApplication) RuntimeEnvironment.application; // } // // // MOCKS // ************************************************************************************************************* // // protected void setUpMocks() { // super.setUpMocks(); // setUpApplicationMocks(); // } // // private void setUpApplicationMocks() { // when(applicationMock.getSystemService(Context.CONNECTIVITY_SERVICE)).thenReturn(connectivityManagerMock); // when(applicationMock.snackbar()).thenReturn(snackbarActionsMock); // } // // // POST // ************************************************************************************************************** // // protected Bundle getExtras(final Post post) { // final Bundle extras = new Bundle(); // extras.putInt(Post.USER_ID, post.getUserId()); // extras.putInt(Post.ID, post.getId()); // extras.putString(Post.TITLE, post.getTitle()); // extras.putString(Post.BODY, post.getBody()); // return extras; // } // // } // Path: app/src/test/java/io/petros/posts/activity/post/view/PostActivityTest.java import android.content.Intent; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.Robolectric; import org.robolectric.fakes.RoboMenuItem; import io.petros.posts.PreconfiguredRobolectricTestRunner; import io.petros.posts.RobolectricGeneralTestHelper; import static org.assertj.core.api.Assertions.assertThat; package io.petros.posts.activity.post.view; /** * This test is ignored until a test Dagger graph is introduced, which will mock all the @Inject objects. */ @Ignore("Problem with Realm: The activity cannot start.") @RunWith(PreconfiguredRobolectricTestRunner.class)
public class PostActivityTest extends RobolectricGeneralTestHelper {
ParaskP7/sample-code-posts
app/src/test/java/io/petros/posts/activity/posts/view/PostsFragmentTest.java
// Path: app/src/test/java/io/petros/posts/PreconfiguredRobolectricTestRunner.java // public class PreconfiguredRobolectricTestRunner extends RobolectricTestRunner { // // private static final int SDK_API_LEVEL_TO_EMULATE = 25; // // /** // * Creates a runner to run {@code testClass}. Looks in your working directory for your AndroidManifest.xml file and res directory by // * default. Use the {@link Config} annotation to configure. // * // * @param testClass The test class to be run. // * @throws InitializationError If junit says so. // */ // public PreconfiguredRobolectricTestRunner(final Class<?> testClass) throws InitializationError { // super(testClass); // } // // @Override // protected Config buildGlobalConfig() { // return new Config.Builder() // .setSdk(SDK_API_LEVEL_TO_EMULATE) // .setManifest(Config.NONE) // .setApplication(TestPostsApplication.class) // .build(); // } // // } // // Path: app/src/test/java/io/petros/posts/RobolectricGeneralTestHelper.java // public class RobolectricGeneralTestHelper extends GeneralTestHelper { // // // Application specific fields. // protected final Context context = getTestContext(); // protected final PostsApplication application = getTestApplication(); // // // System specific fields. // @Mock protected ConnectivityManager connectivityManagerMock; // // // Activity specific fields. // @Mock protected PostsApplication applicationMock; // @Mock protected SnackbarActions snackbarActionsMock; // // // ROBOLECTRIC // ******************************************************************************************************* // // private Context getTestContext() { // return getShadowApplication().getApplicationContext(); // } // // private ShadowApplication getShadowApplication() { // return ShadowApplication.getInstance(); // } // // private PostsApplication getTestApplication() { // return (PostsApplication) RuntimeEnvironment.application; // } // // // MOCKS // ************************************************************************************************************* // // protected void setUpMocks() { // super.setUpMocks(); // setUpApplicationMocks(); // } // // private void setUpApplicationMocks() { // when(applicationMock.getSystemService(Context.CONNECTIVITY_SERVICE)).thenReturn(connectivityManagerMock); // when(applicationMock.snackbar()).thenReturn(snackbarActionsMock); // } // // // POST // ************************************************************************************************************** // // protected Bundle getExtras(final Post post) { // final Bundle extras = new Bundle(); // extras.putInt(Post.USER_ID, post.getUserId()); // extras.putInt(Post.ID, post.getId()); // extras.putString(Post.TITLE, post.getTitle()); // extras.putString(Post.BODY, post.getBody()); // return extras; // } // // } // // Path: app/src/main/java/io/petros/posts/activity/posts/presenter/PostsPresenter.java // public interface PostsPresenter extends MvpPresenter<PostsView> { // // void loadPosts(final boolean pullToRefresh); // // } // // Path: app/src/main/java/io/petros/posts/activity/posts/view/recycler/PostRecyclerViewAdapter.java // public class PostRecyclerViewAdapter extends RecyclerView.Adapter<PostViewHolder> implements RecyclerViewAdapter { // // private final OnViewClickListener onViewClickListener; // // @VisibleForTesting List<Post> allPosts; // // public PostRecyclerViewAdapter(final OnViewClickListener onViewClickListener) { // this.onViewClickListener = onViewClickListener; // allPosts = new ArrayList<>(); // } // // @Override // public PostViewHolder onCreateViewHolder(final ViewGroup parent, final int viewType) { // final View itemView = LayoutInflater.from(parent.getContext()) // .inflate(R.layout.item_view_post, parent, false); // return new PostViewHolder(itemView); // } // // @Override // public void onBindViewHolder(final PostViewHolder holder, final int position) { // holder.bind(getItem(position), onViewClickListener); // } // // @Override // public int getItemCount() { // return allPosts.size(); // } // // @Override // public void reloadAdapter(final List<Post> posts) { // Timber.d("Reloading post recycler view adapter."); // allPosts.clear(); // allPosts.addAll(posts); // notifyDataSetChanged(); // } // // @Override // public Post getItem(int position) { // return allPosts.get(position); // } // // }
import android.app.ProgressDialog; import android.support.v7.widget.RecyclerView; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.robolectric.shadows.support.v4.SupportFragmentTestUtil; import io.petros.posts.PreconfiguredRobolectricTestRunner; import io.petros.posts.RobolectricGeneralTestHelper; import io.petros.posts.activity.posts.presenter.PostsPresenter; import io.petros.posts.activity.posts.view.recycler.PostRecyclerViewAdapter; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions;
package io.petros.posts.activity.posts.view; @RunWith(PreconfiguredRobolectricTestRunner.class) public class PostsFragmentTest extends RobolectricGeneralTestHelper { private static final boolean PULL_TO_REFRESH = true; private PostsFragment postsFragment;
// Path: app/src/test/java/io/petros/posts/PreconfiguredRobolectricTestRunner.java // public class PreconfiguredRobolectricTestRunner extends RobolectricTestRunner { // // private static final int SDK_API_LEVEL_TO_EMULATE = 25; // // /** // * Creates a runner to run {@code testClass}. Looks in your working directory for your AndroidManifest.xml file and res directory by // * default. Use the {@link Config} annotation to configure. // * // * @param testClass The test class to be run. // * @throws InitializationError If junit says so. // */ // public PreconfiguredRobolectricTestRunner(final Class<?> testClass) throws InitializationError { // super(testClass); // } // // @Override // protected Config buildGlobalConfig() { // return new Config.Builder() // .setSdk(SDK_API_LEVEL_TO_EMULATE) // .setManifest(Config.NONE) // .setApplication(TestPostsApplication.class) // .build(); // } // // } // // Path: app/src/test/java/io/petros/posts/RobolectricGeneralTestHelper.java // public class RobolectricGeneralTestHelper extends GeneralTestHelper { // // // Application specific fields. // protected final Context context = getTestContext(); // protected final PostsApplication application = getTestApplication(); // // // System specific fields. // @Mock protected ConnectivityManager connectivityManagerMock; // // // Activity specific fields. // @Mock protected PostsApplication applicationMock; // @Mock protected SnackbarActions snackbarActionsMock; // // // ROBOLECTRIC // ******************************************************************************************************* // // private Context getTestContext() { // return getShadowApplication().getApplicationContext(); // } // // private ShadowApplication getShadowApplication() { // return ShadowApplication.getInstance(); // } // // private PostsApplication getTestApplication() { // return (PostsApplication) RuntimeEnvironment.application; // } // // // MOCKS // ************************************************************************************************************* // // protected void setUpMocks() { // super.setUpMocks(); // setUpApplicationMocks(); // } // // private void setUpApplicationMocks() { // when(applicationMock.getSystemService(Context.CONNECTIVITY_SERVICE)).thenReturn(connectivityManagerMock); // when(applicationMock.snackbar()).thenReturn(snackbarActionsMock); // } // // // POST // ************************************************************************************************************** // // protected Bundle getExtras(final Post post) { // final Bundle extras = new Bundle(); // extras.putInt(Post.USER_ID, post.getUserId()); // extras.putInt(Post.ID, post.getId()); // extras.putString(Post.TITLE, post.getTitle()); // extras.putString(Post.BODY, post.getBody()); // return extras; // } // // } // // Path: app/src/main/java/io/petros/posts/activity/posts/presenter/PostsPresenter.java // public interface PostsPresenter extends MvpPresenter<PostsView> { // // void loadPosts(final boolean pullToRefresh); // // } // // Path: app/src/main/java/io/petros/posts/activity/posts/view/recycler/PostRecyclerViewAdapter.java // public class PostRecyclerViewAdapter extends RecyclerView.Adapter<PostViewHolder> implements RecyclerViewAdapter { // // private final OnViewClickListener onViewClickListener; // // @VisibleForTesting List<Post> allPosts; // // public PostRecyclerViewAdapter(final OnViewClickListener onViewClickListener) { // this.onViewClickListener = onViewClickListener; // allPosts = new ArrayList<>(); // } // // @Override // public PostViewHolder onCreateViewHolder(final ViewGroup parent, final int viewType) { // final View itemView = LayoutInflater.from(parent.getContext()) // .inflate(R.layout.item_view_post, parent, false); // return new PostViewHolder(itemView); // } // // @Override // public void onBindViewHolder(final PostViewHolder holder, final int position) { // holder.bind(getItem(position), onViewClickListener); // } // // @Override // public int getItemCount() { // return allPosts.size(); // } // // @Override // public void reloadAdapter(final List<Post> posts) { // Timber.d("Reloading post recycler view adapter."); // allPosts.clear(); // allPosts.addAll(posts); // notifyDataSetChanged(); // } // // @Override // public Post getItem(int position) { // return allPosts.get(position); // } // // } // Path: app/src/test/java/io/petros/posts/activity/posts/view/PostsFragmentTest.java import android.app.ProgressDialog; import android.support.v7.widget.RecyclerView; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.robolectric.shadows.support.v4.SupportFragmentTestUtil; import io.petros.posts.PreconfiguredRobolectricTestRunner; import io.petros.posts.RobolectricGeneralTestHelper; import io.petros.posts.activity.posts.presenter.PostsPresenter; import io.petros.posts.activity.posts.view.recycler.PostRecyclerViewAdapter; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; package io.petros.posts.activity.posts.view; @RunWith(PreconfiguredRobolectricTestRunner.class) public class PostsFragmentTest extends RobolectricGeneralTestHelper { private static final boolean PULL_TO_REFRESH = true; private PostsFragment postsFragment;
@Mock private PostsPresenter postsPresenterMock;
ParaskP7/sample-code-posts
app/src/test/java/io/petros/posts/activity/posts/view/PostsFragmentTest.java
// Path: app/src/test/java/io/petros/posts/PreconfiguredRobolectricTestRunner.java // public class PreconfiguredRobolectricTestRunner extends RobolectricTestRunner { // // private static final int SDK_API_LEVEL_TO_EMULATE = 25; // // /** // * Creates a runner to run {@code testClass}. Looks in your working directory for your AndroidManifest.xml file and res directory by // * default. Use the {@link Config} annotation to configure. // * // * @param testClass The test class to be run. // * @throws InitializationError If junit says so. // */ // public PreconfiguredRobolectricTestRunner(final Class<?> testClass) throws InitializationError { // super(testClass); // } // // @Override // protected Config buildGlobalConfig() { // return new Config.Builder() // .setSdk(SDK_API_LEVEL_TO_EMULATE) // .setManifest(Config.NONE) // .setApplication(TestPostsApplication.class) // .build(); // } // // } // // Path: app/src/test/java/io/petros/posts/RobolectricGeneralTestHelper.java // public class RobolectricGeneralTestHelper extends GeneralTestHelper { // // // Application specific fields. // protected final Context context = getTestContext(); // protected final PostsApplication application = getTestApplication(); // // // System specific fields. // @Mock protected ConnectivityManager connectivityManagerMock; // // // Activity specific fields. // @Mock protected PostsApplication applicationMock; // @Mock protected SnackbarActions snackbarActionsMock; // // // ROBOLECTRIC // ******************************************************************************************************* // // private Context getTestContext() { // return getShadowApplication().getApplicationContext(); // } // // private ShadowApplication getShadowApplication() { // return ShadowApplication.getInstance(); // } // // private PostsApplication getTestApplication() { // return (PostsApplication) RuntimeEnvironment.application; // } // // // MOCKS // ************************************************************************************************************* // // protected void setUpMocks() { // super.setUpMocks(); // setUpApplicationMocks(); // } // // private void setUpApplicationMocks() { // when(applicationMock.getSystemService(Context.CONNECTIVITY_SERVICE)).thenReturn(connectivityManagerMock); // when(applicationMock.snackbar()).thenReturn(snackbarActionsMock); // } // // // POST // ************************************************************************************************************** // // protected Bundle getExtras(final Post post) { // final Bundle extras = new Bundle(); // extras.putInt(Post.USER_ID, post.getUserId()); // extras.putInt(Post.ID, post.getId()); // extras.putString(Post.TITLE, post.getTitle()); // extras.putString(Post.BODY, post.getBody()); // return extras; // } // // } // // Path: app/src/main/java/io/petros/posts/activity/posts/presenter/PostsPresenter.java // public interface PostsPresenter extends MvpPresenter<PostsView> { // // void loadPosts(final boolean pullToRefresh); // // } // // Path: app/src/main/java/io/petros/posts/activity/posts/view/recycler/PostRecyclerViewAdapter.java // public class PostRecyclerViewAdapter extends RecyclerView.Adapter<PostViewHolder> implements RecyclerViewAdapter { // // private final OnViewClickListener onViewClickListener; // // @VisibleForTesting List<Post> allPosts; // // public PostRecyclerViewAdapter(final OnViewClickListener onViewClickListener) { // this.onViewClickListener = onViewClickListener; // allPosts = new ArrayList<>(); // } // // @Override // public PostViewHolder onCreateViewHolder(final ViewGroup parent, final int viewType) { // final View itemView = LayoutInflater.from(parent.getContext()) // .inflate(R.layout.item_view_post, parent, false); // return new PostViewHolder(itemView); // } // // @Override // public void onBindViewHolder(final PostViewHolder holder, final int position) { // holder.bind(getItem(position), onViewClickListener); // } // // @Override // public int getItemCount() { // return allPosts.size(); // } // // @Override // public void reloadAdapter(final List<Post> posts) { // Timber.d("Reloading post recycler view adapter."); // allPosts.clear(); // allPosts.addAll(posts); // notifyDataSetChanged(); // } // // @Override // public Post getItem(int position) { // return allPosts.get(position); // } // // }
import android.app.ProgressDialog; import android.support.v7.widget.RecyclerView; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.robolectric.shadows.support.v4.SupportFragmentTestUtil; import io.petros.posts.PreconfiguredRobolectricTestRunner; import io.petros.posts.RobolectricGeneralTestHelper; import io.petros.posts.activity.posts.presenter.PostsPresenter; import io.petros.posts.activity.posts.view.recycler.PostRecyclerViewAdapter; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions;
package io.petros.posts.activity.posts.view; @RunWith(PreconfiguredRobolectricTestRunner.class) public class PostsFragmentTest extends RobolectricGeneralTestHelper { private static final boolean PULL_TO_REFRESH = true; private PostsFragment postsFragment; @Mock private PostsPresenter postsPresenterMock; @Mock private RecyclerView postsRecyclerViewMock;
// Path: app/src/test/java/io/petros/posts/PreconfiguredRobolectricTestRunner.java // public class PreconfiguredRobolectricTestRunner extends RobolectricTestRunner { // // private static final int SDK_API_LEVEL_TO_EMULATE = 25; // // /** // * Creates a runner to run {@code testClass}. Looks in your working directory for your AndroidManifest.xml file and res directory by // * default. Use the {@link Config} annotation to configure. // * // * @param testClass The test class to be run. // * @throws InitializationError If junit says so. // */ // public PreconfiguredRobolectricTestRunner(final Class<?> testClass) throws InitializationError { // super(testClass); // } // // @Override // protected Config buildGlobalConfig() { // return new Config.Builder() // .setSdk(SDK_API_LEVEL_TO_EMULATE) // .setManifest(Config.NONE) // .setApplication(TestPostsApplication.class) // .build(); // } // // } // // Path: app/src/test/java/io/petros/posts/RobolectricGeneralTestHelper.java // public class RobolectricGeneralTestHelper extends GeneralTestHelper { // // // Application specific fields. // protected final Context context = getTestContext(); // protected final PostsApplication application = getTestApplication(); // // // System specific fields. // @Mock protected ConnectivityManager connectivityManagerMock; // // // Activity specific fields. // @Mock protected PostsApplication applicationMock; // @Mock protected SnackbarActions snackbarActionsMock; // // // ROBOLECTRIC // ******************************************************************************************************* // // private Context getTestContext() { // return getShadowApplication().getApplicationContext(); // } // // private ShadowApplication getShadowApplication() { // return ShadowApplication.getInstance(); // } // // private PostsApplication getTestApplication() { // return (PostsApplication) RuntimeEnvironment.application; // } // // // MOCKS // ************************************************************************************************************* // // protected void setUpMocks() { // super.setUpMocks(); // setUpApplicationMocks(); // } // // private void setUpApplicationMocks() { // when(applicationMock.getSystemService(Context.CONNECTIVITY_SERVICE)).thenReturn(connectivityManagerMock); // when(applicationMock.snackbar()).thenReturn(snackbarActionsMock); // } // // // POST // ************************************************************************************************************** // // protected Bundle getExtras(final Post post) { // final Bundle extras = new Bundle(); // extras.putInt(Post.USER_ID, post.getUserId()); // extras.putInt(Post.ID, post.getId()); // extras.putString(Post.TITLE, post.getTitle()); // extras.putString(Post.BODY, post.getBody()); // return extras; // } // // } // // Path: app/src/main/java/io/petros/posts/activity/posts/presenter/PostsPresenter.java // public interface PostsPresenter extends MvpPresenter<PostsView> { // // void loadPosts(final boolean pullToRefresh); // // } // // Path: app/src/main/java/io/petros/posts/activity/posts/view/recycler/PostRecyclerViewAdapter.java // public class PostRecyclerViewAdapter extends RecyclerView.Adapter<PostViewHolder> implements RecyclerViewAdapter { // // private final OnViewClickListener onViewClickListener; // // @VisibleForTesting List<Post> allPosts; // // public PostRecyclerViewAdapter(final OnViewClickListener onViewClickListener) { // this.onViewClickListener = onViewClickListener; // allPosts = new ArrayList<>(); // } // // @Override // public PostViewHolder onCreateViewHolder(final ViewGroup parent, final int viewType) { // final View itemView = LayoutInflater.from(parent.getContext()) // .inflate(R.layout.item_view_post, parent, false); // return new PostViewHolder(itemView); // } // // @Override // public void onBindViewHolder(final PostViewHolder holder, final int position) { // holder.bind(getItem(position), onViewClickListener); // } // // @Override // public int getItemCount() { // return allPosts.size(); // } // // @Override // public void reloadAdapter(final List<Post> posts) { // Timber.d("Reloading post recycler view adapter."); // allPosts.clear(); // allPosts.addAll(posts); // notifyDataSetChanged(); // } // // @Override // public Post getItem(int position) { // return allPosts.get(position); // } // // } // Path: app/src/test/java/io/petros/posts/activity/posts/view/PostsFragmentTest.java import android.app.ProgressDialog; import android.support.v7.widget.RecyclerView; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.robolectric.shadows.support.v4.SupportFragmentTestUtil; import io.petros.posts.PreconfiguredRobolectricTestRunner; import io.petros.posts.RobolectricGeneralTestHelper; import io.petros.posts.activity.posts.presenter.PostsPresenter; import io.petros.posts.activity.posts.view.recycler.PostRecyclerViewAdapter; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; package io.petros.posts.activity.posts.view; @RunWith(PreconfiguredRobolectricTestRunner.class) public class PostsFragmentTest extends RobolectricGeneralTestHelper { private static final boolean PULL_TO_REFRESH = true; private PostsFragment postsFragment; @Mock private PostsPresenter postsPresenterMock; @Mock private RecyclerView postsRecyclerViewMock;
@Mock private PostRecyclerViewAdapter postRecyclerViewAdapterMock;
ParaskP7/sample-code-posts
app/src/main/java/io/petros/posts/datastore/DatastoreUpdateActions.java
// Path: app/src/main/java/io/petros/posts/model/User.java // public class User extends RealmObject { // // public static final String ID = "id"; // public static final String NAME = "name"; // public static final String USERNAME = "username"; // public static final String EMAIL = "email"; // // @SerializedName(ID) // @Expose // @PrimaryKey // private Integer id; // // @SerializedName(NAME) // @Expose // private String name; // // @SerializedName(USERNAME) // @Expose // private String username; // // @SerializedName(EMAIL) // @Expose // private String email; // // public Integer getId() { // return id; // } // // public void setId(final Integer id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(final String name) { // this.name = name; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getEmail() { // return email; // } // // public void setEmail(final String email) { // this.email = email; // } // // }
import io.petros.posts.model.User; import io.realm.Realm;
package io.petros.posts.datastore; public class DatastoreUpdateActions implements UpdateActions { private final Realm realm; public DatastoreUpdateActions(final Realm realm) { this.realm = realm; } @Override
// Path: app/src/main/java/io/petros/posts/model/User.java // public class User extends RealmObject { // // public static final String ID = "id"; // public static final String NAME = "name"; // public static final String USERNAME = "username"; // public static final String EMAIL = "email"; // // @SerializedName(ID) // @Expose // @PrimaryKey // private Integer id; // // @SerializedName(NAME) // @Expose // private String name; // // @SerializedName(USERNAME) // @Expose // private String username; // // @SerializedName(EMAIL) // @Expose // private String email; // // public Integer getId() { // return id; // } // // public void setId(final Integer id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(final String name) { // this.name = name; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getEmail() { // return email; // } // // public void setEmail(final String email) { // this.email = email; // } // // } // Path: app/src/main/java/io/petros/posts/datastore/DatastoreUpdateActions.java import io.petros.posts.model.User; import io.realm.Realm; package io.petros.posts.datastore; public class DatastoreUpdateActions implements UpdateActions { private final Realm realm; public DatastoreUpdateActions(final Realm realm) { this.realm = realm; } @Override
public boolean user(final User existingRealUser, final User user) {
ParaskP7/sample-code-posts
app/src/test/java/io/petros/posts/PreconfiguredRobolectricTestRunner.java
// Path: app/src/test/java/io/petros/posts/app/TestPostsApplication.java // public class TestPostsApplication extends PostsApplication { // // @Override // protected void initRealm() { // // Do nothing because during testing databaseRealm.setup() throws an java.lang.UnsatisfiedLinkError error. // } // // @Override // public Realm getDefaultRealmInstance() { // return Mockito.mock(Realm.class); // During testing return a mocked Realm instance instead. // } // // }
import org.junit.runners.model.InitializationError; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import io.petros.posts.app.TestPostsApplication;
package io.petros.posts; /** * A {@link RobolectricTestRunner} that allows us to set robolectric configuration in one place instead of setting it in each test class via * {@link Config}. */ public class PreconfiguredRobolectricTestRunner extends RobolectricTestRunner { private static final int SDK_API_LEVEL_TO_EMULATE = 25; /** * Creates a runner to run {@code testClass}. Looks in your working directory for your AndroidManifest.xml file and res directory by * default. Use the {@link Config} annotation to configure. * * @param testClass The test class to be run. * @throws InitializationError If junit says so. */ public PreconfiguredRobolectricTestRunner(final Class<?> testClass) throws InitializationError { super(testClass); } @Override protected Config buildGlobalConfig() { return new Config.Builder() .setSdk(SDK_API_LEVEL_TO_EMULATE) .setManifest(Config.NONE)
// Path: app/src/test/java/io/petros/posts/app/TestPostsApplication.java // public class TestPostsApplication extends PostsApplication { // // @Override // protected void initRealm() { // // Do nothing because during testing databaseRealm.setup() throws an java.lang.UnsatisfiedLinkError error. // } // // @Override // public Realm getDefaultRealmInstance() { // return Mockito.mock(Realm.class); // During testing return a mocked Realm instance instead. // } // // } // Path: app/src/test/java/io/petros/posts/PreconfiguredRobolectricTestRunner.java import org.junit.runners.model.InitializationError; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import io.petros.posts.app.TestPostsApplication; package io.petros.posts; /** * A {@link RobolectricTestRunner} that allows us to set robolectric configuration in one place instead of setting it in each test class via * {@link Config}. */ public class PreconfiguredRobolectricTestRunner extends RobolectricTestRunner { private static final int SDK_API_LEVEL_TO_EMULATE = 25; /** * Creates a runner to run {@code testClass}. Looks in your working directory for your AndroidManifest.xml file and res directory by * default. Use the {@link Config} annotation to configure. * * @param testClass The test class to be run. * @throws InitializationError If junit says so. */ public PreconfiguredRobolectricTestRunner(final Class<?> testClass) throws InitializationError { super(testClass); } @Override protected Config buildGlobalConfig() { return new Config.Builder() .setSdk(SDK_API_LEVEL_TO_EMULATE) .setManifest(Config.NONE)
.setApplication(TestPostsApplication.class)
ParaskP7/sample-code-posts
app/src/test/java/io/petros/posts/datastore/DatastoreUpdateActionsTest.java
// Path: app/src/test/java/io/petros/posts/PreconfiguredRobolectricTestRunner.java // public class PreconfiguredRobolectricTestRunner extends RobolectricTestRunner { // // private static final int SDK_API_LEVEL_TO_EMULATE = 25; // // /** // * Creates a runner to run {@code testClass}. Looks in your working directory for your AndroidManifest.xml file and res directory by // * default. Use the {@link Config} annotation to configure. // * // * @param testClass The test class to be run. // * @throws InitializationError If junit says so. // */ // public PreconfiguredRobolectricTestRunner(final Class<?> testClass) throws InitializationError { // super(testClass); // } // // @Override // protected Config buildGlobalConfig() { // return new Config.Builder() // .setSdk(SDK_API_LEVEL_TO_EMULATE) // .setManifest(Config.NONE) // .setApplication(TestPostsApplication.class) // .build(); // } // // } // // Path: app/src/test/java/io/petros/posts/RobolectricGeneralTestHelper.java // public class RobolectricGeneralTestHelper extends GeneralTestHelper { // // // Application specific fields. // protected final Context context = getTestContext(); // protected final PostsApplication application = getTestApplication(); // // // System specific fields. // @Mock protected ConnectivityManager connectivityManagerMock; // // // Activity specific fields. // @Mock protected PostsApplication applicationMock; // @Mock protected SnackbarActions snackbarActionsMock; // // // ROBOLECTRIC // ******************************************************************************************************* // // private Context getTestContext() { // return getShadowApplication().getApplicationContext(); // } // // private ShadowApplication getShadowApplication() { // return ShadowApplication.getInstance(); // } // // private PostsApplication getTestApplication() { // return (PostsApplication) RuntimeEnvironment.application; // } // // // MOCKS // ************************************************************************************************************* // // protected void setUpMocks() { // super.setUpMocks(); // setUpApplicationMocks(); // } // // private void setUpApplicationMocks() { // when(applicationMock.getSystemService(Context.CONNECTIVITY_SERVICE)).thenReturn(connectivityManagerMock); // when(applicationMock.snackbar()).thenReturn(snackbarActionsMock); // } // // // POST // ************************************************************************************************************** // // protected Bundle getExtras(final Post post) { // final Bundle extras = new Bundle(); // extras.putInt(Post.USER_ID, post.getUserId()); // extras.putInt(Post.ID, post.getId()); // extras.putString(Post.TITLE, post.getTitle()); // extras.putString(Post.BODY, post.getBody()); // return extras; // } // // } // // Path: app/src/main/java/io/petros/posts/model/User.java // public class User extends RealmObject { // // public static final String ID = "id"; // public static final String NAME = "name"; // public static final String USERNAME = "username"; // public static final String EMAIL = "email"; // // @SerializedName(ID) // @Expose // @PrimaryKey // private Integer id; // // @SerializedName(NAME) // @Expose // private String name; // // @SerializedName(USERNAME) // @Expose // private String username; // // @SerializedName(EMAIL) // @Expose // private String email; // // public Integer getId() { // return id; // } // // public void setId(final Integer id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(final String name) { // this.name = name; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getEmail() { // return email; // } // // public void setEmail(final String email) { // this.email = email; // } // // }
import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import io.petros.posts.PreconfiguredRobolectricTestRunner; import io.petros.posts.RobolectricGeneralTestHelper; import io.petros.posts.model.User; import io.realm.Realm; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions;
package io.petros.posts.datastore; /** * This test is ignored until PowerMock is introduced, which will mock all the Realm objects. */ @Ignore("java.lang.NullPointerException at io.realm.BaseRealm.beginTransaction") @RunWith(PreconfiguredRobolectricTestRunner.class)
// Path: app/src/test/java/io/petros/posts/PreconfiguredRobolectricTestRunner.java // public class PreconfiguredRobolectricTestRunner extends RobolectricTestRunner { // // private static final int SDK_API_LEVEL_TO_EMULATE = 25; // // /** // * Creates a runner to run {@code testClass}. Looks in your working directory for your AndroidManifest.xml file and res directory by // * default. Use the {@link Config} annotation to configure. // * // * @param testClass The test class to be run. // * @throws InitializationError If junit says so. // */ // public PreconfiguredRobolectricTestRunner(final Class<?> testClass) throws InitializationError { // super(testClass); // } // // @Override // protected Config buildGlobalConfig() { // return new Config.Builder() // .setSdk(SDK_API_LEVEL_TO_EMULATE) // .setManifest(Config.NONE) // .setApplication(TestPostsApplication.class) // .build(); // } // // } // // Path: app/src/test/java/io/petros/posts/RobolectricGeneralTestHelper.java // public class RobolectricGeneralTestHelper extends GeneralTestHelper { // // // Application specific fields. // protected final Context context = getTestContext(); // protected final PostsApplication application = getTestApplication(); // // // System specific fields. // @Mock protected ConnectivityManager connectivityManagerMock; // // // Activity specific fields. // @Mock protected PostsApplication applicationMock; // @Mock protected SnackbarActions snackbarActionsMock; // // // ROBOLECTRIC // ******************************************************************************************************* // // private Context getTestContext() { // return getShadowApplication().getApplicationContext(); // } // // private ShadowApplication getShadowApplication() { // return ShadowApplication.getInstance(); // } // // private PostsApplication getTestApplication() { // return (PostsApplication) RuntimeEnvironment.application; // } // // // MOCKS // ************************************************************************************************************* // // protected void setUpMocks() { // super.setUpMocks(); // setUpApplicationMocks(); // } // // private void setUpApplicationMocks() { // when(applicationMock.getSystemService(Context.CONNECTIVITY_SERVICE)).thenReturn(connectivityManagerMock); // when(applicationMock.snackbar()).thenReturn(snackbarActionsMock); // } // // // POST // ************************************************************************************************************** // // protected Bundle getExtras(final Post post) { // final Bundle extras = new Bundle(); // extras.putInt(Post.USER_ID, post.getUserId()); // extras.putInt(Post.ID, post.getId()); // extras.putString(Post.TITLE, post.getTitle()); // extras.putString(Post.BODY, post.getBody()); // return extras; // } // // } // // Path: app/src/main/java/io/petros/posts/model/User.java // public class User extends RealmObject { // // public static final String ID = "id"; // public static final String NAME = "name"; // public static final String USERNAME = "username"; // public static final String EMAIL = "email"; // // @SerializedName(ID) // @Expose // @PrimaryKey // private Integer id; // // @SerializedName(NAME) // @Expose // private String name; // // @SerializedName(USERNAME) // @Expose // private String username; // // @SerializedName(EMAIL) // @Expose // private String email; // // public Integer getId() { // return id; // } // // public void setId(final Integer id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(final String name) { // this.name = name; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getEmail() { // return email; // } // // public void setEmail(final String email) { // this.email = email; // } // // } // Path: app/src/test/java/io/petros/posts/datastore/DatastoreUpdateActionsTest.java import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import io.petros.posts.PreconfiguredRobolectricTestRunner; import io.petros.posts.RobolectricGeneralTestHelper; import io.petros.posts.model.User; import io.realm.Realm; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; package io.petros.posts.datastore; /** * This test is ignored until PowerMock is introduced, which will mock all the Realm objects. */ @Ignore("java.lang.NullPointerException at io.realm.BaseRealm.beginTransaction") @RunWith(PreconfiguredRobolectricTestRunner.class)
public class DatastoreUpdateActionsTest extends RobolectricGeneralTestHelper {
ParaskP7/sample-code-posts
app/src/test/java/io/petros/posts/datastore/DatastoreUpdateActionsTest.java
// Path: app/src/test/java/io/petros/posts/PreconfiguredRobolectricTestRunner.java // public class PreconfiguredRobolectricTestRunner extends RobolectricTestRunner { // // private static final int SDK_API_LEVEL_TO_EMULATE = 25; // // /** // * Creates a runner to run {@code testClass}. Looks in your working directory for your AndroidManifest.xml file and res directory by // * default. Use the {@link Config} annotation to configure. // * // * @param testClass The test class to be run. // * @throws InitializationError If junit says so. // */ // public PreconfiguredRobolectricTestRunner(final Class<?> testClass) throws InitializationError { // super(testClass); // } // // @Override // protected Config buildGlobalConfig() { // return new Config.Builder() // .setSdk(SDK_API_LEVEL_TO_EMULATE) // .setManifest(Config.NONE) // .setApplication(TestPostsApplication.class) // .build(); // } // // } // // Path: app/src/test/java/io/petros/posts/RobolectricGeneralTestHelper.java // public class RobolectricGeneralTestHelper extends GeneralTestHelper { // // // Application specific fields. // protected final Context context = getTestContext(); // protected final PostsApplication application = getTestApplication(); // // // System specific fields. // @Mock protected ConnectivityManager connectivityManagerMock; // // // Activity specific fields. // @Mock protected PostsApplication applicationMock; // @Mock protected SnackbarActions snackbarActionsMock; // // // ROBOLECTRIC // ******************************************************************************************************* // // private Context getTestContext() { // return getShadowApplication().getApplicationContext(); // } // // private ShadowApplication getShadowApplication() { // return ShadowApplication.getInstance(); // } // // private PostsApplication getTestApplication() { // return (PostsApplication) RuntimeEnvironment.application; // } // // // MOCKS // ************************************************************************************************************* // // protected void setUpMocks() { // super.setUpMocks(); // setUpApplicationMocks(); // } // // private void setUpApplicationMocks() { // when(applicationMock.getSystemService(Context.CONNECTIVITY_SERVICE)).thenReturn(connectivityManagerMock); // when(applicationMock.snackbar()).thenReturn(snackbarActionsMock); // } // // // POST // ************************************************************************************************************** // // protected Bundle getExtras(final Post post) { // final Bundle extras = new Bundle(); // extras.putInt(Post.USER_ID, post.getUserId()); // extras.putInt(Post.ID, post.getId()); // extras.putString(Post.TITLE, post.getTitle()); // extras.putString(Post.BODY, post.getBody()); // return extras; // } // // } // // Path: app/src/main/java/io/petros/posts/model/User.java // public class User extends RealmObject { // // public static final String ID = "id"; // public static final String NAME = "name"; // public static final String USERNAME = "username"; // public static final String EMAIL = "email"; // // @SerializedName(ID) // @Expose // @PrimaryKey // private Integer id; // // @SerializedName(NAME) // @Expose // private String name; // // @SerializedName(USERNAME) // @Expose // private String username; // // @SerializedName(EMAIL) // @Expose // private String email; // // public Integer getId() { // return id; // } // // public void setId(final Integer id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(final String name) { // this.name = name; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getEmail() { // return email; // } // // public void setEmail(final String email) { // this.email = email; // } // // }
import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import io.petros.posts.PreconfiguredRobolectricTestRunner; import io.petros.posts.RobolectricGeneralTestHelper; import io.petros.posts.model.User; import io.realm.Realm; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions;
package io.petros.posts.datastore; /** * This test is ignored until PowerMock is introduced, which will mock all the Realm objects. */ @Ignore("java.lang.NullPointerException at io.realm.BaseRealm.beginTransaction") @RunWith(PreconfiguredRobolectricTestRunner.class) public class DatastoreUpdateActionsTest extends RobolectricGeneralTestHelper { private DatastoreUpdateActions datastoreUpdateActions; @Mock private Realm realmMock;
// Path: app/src/test/java/io/petros/posts/PreconfiguredRobolectricTestRunner.java // public class PreconfiguredRobolectricTestRunner extends RobolectricTestRunner { // // private static final int SDK_API_LEVEL_TO_EMULATE = 25; // // /** // * Creates a runner to run {@code testClass}. Looks in your working directory for your AndroidManifest.xml file and res directory by // * default. Use the {@link Config} annotation to configure. // * // * @param testClass The test class to be run. // * @throws InitializationError If junit says so. // */ // public PreconfiguredRobolectricTestRunner(final Class<?> testClass) throws InitializationError { // super(testClass); // } // // @Override // protected Config buildGlobalConfig() { // return new Config.Builder() // .setSdk(SDK_API_LEVEL_TO_EMULATE) // .setManifest(Config.NONE) // .setApplication(TestPostsApplication.class) // .build(); // } // // } // // Path: app/src/test/java/io/petros/posts/RobolectricGeneralTestHelper.java // public class RobolectricGeneralTestHelper extends GeneralTestHelper { // // // Application specific fields. // protected final Context context = getTestContext(); // protected final PostsApplication application = getTestApplication(); // // // System specific fields. // @Mock protected ConnectivityManager connectivityManagerMock; // // // Activity specific fields. // @Mock protected PostsApplication applicationMock; // @Mock protected SnackbarActions snackbarActionsMock; // // // ROBOLECTRIC // ******************************************************************************************************* // // private Context getTestContext() { // return getShadowApplication().getApplicationContext(); // } // // private ShadowApplication getShadowApplication() { // return ShadowApplication.getInstance(); // } // // private PostsApplication getTestApplication() { // return (PostsApplication) RuntimeEnvironment.application; // } // // // MOCKS // ************************************************************************************************************* // // protected void setUpMocks() { // super.setUpMocks(); // setUpApplicationMocks(); // } // // private void setUpApplicationMocks() { // when(applicationMock.getSystemService(Context.CONNECTIVITY_SERVICE)).thenReturn(connectivityManagerMock); // when(applicationMock.snackbar()).thenReturn(snackbarActionsMock); // } // // // POST // ************************************************************************************************************** // // protected Bundle getExtras(final Post post) { // final Bundle extras = new Bundle(); // extras.putInt(Post.USER_ID, post.getUserId()); // extras.putInt(Post.ID, post.getId()); // extras.putString(Post.TITLE, post.getTitle()); // extras.putString(Post.BODY, post.getBody()); // return extras; // } // // } // // Path: app/src/main/java/io/petros/posts/model/User.java // public class User extends RealmObject { // // public static final String ID = "id"; // public static final String NAME = "name"; // public static final String USERNAME = "username"; // public static final String EMAIL = "email"; // // @SerializedName(ID) // @Expose // @PrimaryKey // private Integer id; // // @SerializedName(NAME) // @Expose // private String name; // // @SerializedName(USERNAME) // @Expose // private String username; // // @SerializedName(EMAIL) // @Expose // private String email; // // public Integer getId() { // return id; // } // // public void setId(final Integer id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(final String name) { // this.name = name; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getEmail() { // return email; // } // // public void setEmail(final String email) { // this.email = email; // } // // } // Path: app/src/test/java/io/petros/posts/datastore/DatastoreUpdateActionsTest.java import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import io.petros.posts.PreconfiguredRobolectricTestRunner; import io.petros.posts.RobolectricGeneralTestHelper; import io.petros.posts.model.User; import io.realm.Realm; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; package io.petros.posts.datastore; /** * This test is ignored until PowerMock is introduced, which will mock all the Realm objects. */ @Ignore("java.lang.NullPointerException at io.realm.BaseRealm.beginTransaction") @RunWith(PreconfiguredRobolectricTestRunner.class) public class DatastoreUpdateActionsTest extends RobolectricGeneralTestHelper { private DatastoreUpdateActions datastoreUpdateActions; @Mock private Realm realmMock;
@Mock private User realmUserMock;
ParaskP7/sample-code-posts
app/src/androidTest/java/io/petros/posts/util/MatcherEspressoUtilities.java
// Path: app/src/androidTest/java/io/petros/posts/util/matcher/RecyclerViewMatcher.java // public class RecyclerViewMatcher { // // private final int recyclerViewId; // // public RecyclerViewMatcher(final int recyclerViewId) { // this.recyclerViewId = recyclerViewId; // } // // public Matcher<View> atPosition(final int position) { // return atPositionOnView(position, -1); // } // // public Matcher<View> atPositionOnView(final int position, final int targetViewId) { // return new RecyclerTypeSafeMatcher(recyclerViewId, position, targetViewId); // } // // }
import io.petros.posts.util.matcher.RecyclerViewMatcher;
package io.petros.posts.util; /** * Showcasing how custom matcher can be utilised. */ public final class MatcherEspressoUtilities { private MatcherEspressoUtilities() { throw new AssertionError(); }
// Path: app/src/androidTest/java/io/petros/posts/util/matcher/RecyclerViewMatcher.java // public class RecyclerViewMatcher { // // private final int recyclerViewId; // // public RecyclerViewMatcher(final int recyclerViewId) { // this.recyclerViewId = recyclerViewId; // } // // public Matcher<View> atPosition(final int position) { // return atPositionOnView(position, -1); // } // // public Matcher<View> atPositionOnView(final int position, final int targetViewId) { // return new RecyclerTypeSafeMatcher(recyclerViewId, position, targetViewId); // } // // } // Path: app/src/androidTest/java/io/petros/posts/util/MatcherEspressoUtilities.java import io.petros.posts.util.matcher.RecyclerViewMatcher; package io.petros.posts.util; /** * Showcasing how custom matcher can be utilised. */ public final class MatcherEspressoUtilities { private MatcherEspressoUtilities() { throw new AssertionError(); }
public static RecyclerViewMatcher withRecyclerView(final int recyclerViewId) {
ParaskP7/sample-code-posts
app/src/main/java/io/petros/posts/activity/AbstractAppActivity.java
// Path: app/src/main/java/io/petros/posts/app/PostsApplication.java // @SuppressWarnings("checkstyle:overloadmethodsdeclarationorder") // public class PostsApplication extends Application { // // private static ApplicationComponent applicationComponent; // // static { // AppCompatDelegate.setCompatVectorFromResourcesEnabled(true); // NOTE: This enables the "proxy" trick on the vector images. // } // // @Inject AppSnackbarActions appSnackbarActions; // // // HELPER // ************************************************************************************************************ // // public static ApplicationComponent getApplicationComponent() { // return applicationComponent; // } // // public static SnackbarActions snackbar(final Activity activity) { // return ((PostsApplication) activity.getApplication()).snackbar(); // } // // // APPLICATION // ******************************************************************************************************* // // @Override // public void onCreate() { // super.onCreate(); // initDagger(); // initRealm(); // initTimber(); // Timber.i("Posts application created!"); // } // // private void initDagger() { // applicationComponent = DaggerApplicationComponent.builder() // .appModule(new AppModule(this)) // .netModule(new NetModule(BASE_URL)) // .dataModule(new DataModule()) // .serviceModule(new ServiceModule()) // .activityModule(new ActivityModule()).build(); // applicationComponent.inject(this); // } // // private void initTimber() { // Timber.plant(new Timber.DebugTree()); // } // // protected void initRealm() { // Realm.init(this); // } // // // GET // *************************************************************************************************************** // // public Realm getDefaultRealmInstance() { // return Realm.getDefaultInstance(); // } // // // ACTIONS // *********************************************************************************************************** // // public SnackbarActions snackbar() { // return appSnackbarActions; // } // // }
import android.annotation.SuppressLint; import android.app.Fragment; import android.app.FragmentManager; import android.app.FragmentTransaction; import android.os.Bundle; import android.support.annotation.CallSuper; import android.support.design.widget.CoordinatorLayout; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import javax.annotation.Nullable; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import io.petros.posts.app.PostsApplication; import timber.log.Timber;
@Override protected void onStop() { Timber.d("%s stopped.", getClass().getSimpleName()); super.onStop(); } @Override protected void onDestroy() { Timber.d("%s destroyed.", getClass().getSimpleName()); super.onDestroy(); } // TOOLBAR // *********************************************************************************************************** @SuppressFBWarnings("RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE") protected void setToolbar(final Toolbar toolbar) { setSupportActionBar(toolbar); @Nullable final ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayShowHomeEnabled(true); actionBar.setDisplayHomeAsUpEnabled(true); } else { Timber.w("Cannot get an action bar for this activity; verify that this activity has actually defined a toolbar."); } } // SNACKBAR // ********************************************************************************************************** protected void setSnackbar(final CoordinatorLayout coordinatorLayout) {
// Path: app/src/main/java/io/petros/posts/app/PostsApplication.java // @SuppressWarnings("checkstyle:overloadmethodsdeclarationorder") // public class PostsApplication extends Application { // // private static ApplicationComponent applicationComponent; // // static { // AppCompatDelegate.setCompatVectorFromResourcesEnabled(true); // NOTE: This enables the "proxy" trick on the vector images. // } // // @Inject AppSnackbarActions appSnackbarActions; // // // HELPER // ************************************************************************************************************ // // public static ApplicationComponent getApplicationComponent() { // return applicationComponent; // } // // public static SnackbarActions snackbar(final Activity activity) { // return ((PostsApplication) activity.getApplication()).snackbar(); // } // // // APPLICATION // ******************************************************************************************************* // // @Override // public void onCreate() { // super.onCreate(); // initDagger(); // initRealm(); // initTimber(); // Timber.i("Posts application created!"); // } // // private void initDagger() { // applicationComponent = DaggerApplicationComponent.builder() // .appModule(new AppModule(this)) // .netModule(new NetModule(BASE_URL)) // .dataModule(new DataModule()) // .serviceModule(new ServiceModule()) // .activityModule(new ActivityModule()).build(); // applicationComponent.inject(this); // } // // private void initTimber() { // Timber.plant(new Timber.DebugTree()); // } // // protected void initRealm() { // Realm.init(this); // } // // // GET // *************************************************************************************************************** // // public Realm getDefaultRealmInstance() { // return Realm.getDefaultInstance(); // } // // // ACTIONS // *********************************************************************************************************** // // public SnackbarActions snackbar() { // return appSnackbarActions; // } // // } // Path: app/src/main/java/io/petros/posts/activity/AbstractAppActivity.java import android.annotation.SuppressLint; import android.app.Fragment; import android.app.FragmentManager; import android.app.FragmentTransaction; import android.os.Bundle; import android.support.annotation.CallSuper; import android.support.design.widget.CoordinatorLayout; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import javax.annotation.Nullable; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import io.petros.posts.app.PostsApplication; import timber.log.Timber; @Override protected void onStop() { Timber.d("%s stopped.", getClass().getSimpleName()); super.onStop(); } @Override protected void onDestroy() { Timber.d("%s destroyed.", getClass().getSimpleName()); super.onDestroy(); } // TOOLBAR // *********************************************************************************************************** @SuppressFBWarnings("RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE") protected void setToolbar(final Toolbar toolbar) { setSupportActionBar(toolbar); @Nullable final ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayShowHomeEnabled(true); actionBar.setDisplayHomeAsUpEnabled(true); } else { Timber.w("Cannot get an action bar for this activity; verify that this activity has actually defined a toolbar."); } } // SNACKBAR // ********************************************************************************************************** protected void setSnackbar(final CoordinatorLayout coordinatorLayout) {
PostsApplication.snackbar(this).setCoordinatorLayout(coordinatorLayout);
ParaskP7/sample-code-posts
app/src/test/java/io/petros/posts/util/DeprecationUtilitiesTest.java
// Path: app/src/test/java/io/petros/posts/PreconfiguredRobolectricTestRunner.java // public class PreconfiguredRobolectricTestRunner extends RobolectricTestRunner { // // private static final int SDK_API_LEVEL_TO_EMULATE = 25; // // /** // * Creates a runner to run {@code testClass}. Looks in your working directory for your AndroidManifest.xml file and res directory by // * default. Use the {@link Config} annotation to configure. // * // * @param testClass The test class to be run. // * @throws InitializationError If junit says so. // */ // public PreconfiguredRobolectricTestRunner(final Class<?> testClass) throws InitializationError { // super(testClass); // } // // @Override // protected Config buildGlobalConfig() { // return new Config.Builder() // .setSdk(SDK_API_LEVEL_TO_EMULATE) // .setManifest(Config.NONE) // .setApplication(TestPostsApplication.class) // .build(); // } // // } // // Path: app/src/test/java/io/petros/posts/RobolectricGeneralTestHelper.java // public class RobolectricGeneralTestHelper extends GeneralTestHelper { // // // Application specific fields. // protected final Context context = getTestContext(); // protected final PostsApplication application = getTestApplication(); // // // System specific fields. // @Mock protected ConnectivityManager connectivityManagerMock; // // // Activity specific fields. // @Mock protected PostsApplication applicationMock; // @Mock protected SnackbarActions snackbarActionsMock; // // // ROBOLECTRIC // ******************************************************************************************************* // // private Context getTestContext() { // return getShadowApplication().getApplicationContext(); // } // // private ShadowApplication getShadowApplication() { // return ShadowApplication.getInstance(); // } // // private PostsApplication getTestApplication() { // return (PostsApplication) RuntimeEnvironment.application; // } // // // MOCKS // ************************************************************************************************************* // // protected void setUpMocks() { // super.setUpMocks(); // setUpApplicationMocks(); // } // // private void setUpApplicationMocks() { // when(applicationMock.getSystemService(Context.CONNECTIVITY_SERVICE)).thenReturn(connectivityManagerMock); // when(applicationMock.snackbar()).thenReturn(snackbarActionsMock); // } // // // POST // ************************************************************************************************************** // // protected Bundle getExtras(final Post post) { // final Bundle extras = new Bundle(); // extras.putInt(Post.USER_ID, post.getUserId()); // extras.putInt(Post.ID, post.getId()); // extras.putString(Post.TITLE, post.getTitle()); // extras.putString(Post.BODY, post.getBody()); // return extras; // } // // } // // Path: app/src/test/java/io/petros/posts/util/WhiteboxTestUtilities.java // public static final String SDK_INT = "SDK_INT";
import android.annotation.TargetApi; import android.graphics.drawable.Drawable; import android.os.Build; import android.view.View; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.robolectric.util.ReflectionHelpers; import io.petros.posts.PreconfiguredRobolectricTestRunner; import io.petros.posts.R; import io.petros.posts.RobolectricGeneralTestHelper; import static io.petros.posts.util.WhiteboxTestUtilities.SDK_INT; import static org.mockito.Matchers.any; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when;
package io.petros.posts.util; @RunWith(PreconfiguredRobolectricTestRunner.class) public class DeprecationUtilitiesTest extends RobolectricGeneralTestHelper { @Mock private View viewMock; @Before public void setUp() { setUpMocks(); setUpView(); } private void setUpView() { when(viewMock.getContext()).thenReturn(context); } @Test @TargetApi(Build.VERSION_CODES.JELLY_BEAN) public void setBackgroundTestForJellyBeanAndAfter() { DeprecationUtilities.setBackground(viewMock, R.drawable.snackbar__design_snackbar_background); verify(viewMock, times(1)).setBackground(any(Drawable.class)); verifyNoMoreInteractions(connectivityManagerMock); } @Test @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) @Ignore("android.content.res.Resources$NotFoundException: Unable to find resource ID #0x0 in packages") public void setBackgroundTestForPriorJellyBean() {
// Path: app/src/test/java/io/petros/posts/PreconfiguredRobolectricTestRunner.java // public class PreconfiguredRobolectricTestRunner extends RobolectricTestRunner { // // private static final int SDK_API_LEVEL_TO_EMULATE = 25; // // /** // * Creates a runner to run {@code testClass}. Looks in your working directory for your AndroidManifest.xml file and res directory by // * default. Use the {@link Config} annotation to configure. // * // * @param testClass The test class to be run. // * @throws InitializationError If junit says so. // */ // public PreconfiguredRobolectricTestRunner(final Class<?> testClass) throws InitializationError { // super(testClass); // } // // @Override // protected Config buildGlobalConfig() { // return new Config.Builder() // .setSdk(SDK_API_LEVEL_TO_EMULATE) // .setManifest(Config.NONE) // .setApplication(TestPostsApplication.class) // .build(); // } // // } // // Path: app/src/test/java/io/petros/posts/RobolectricGeneralTestHelper.java // public class RobolectricGeneralTestHelper extends GeneralTestHelper { // // // Application specific fields. // protected final Context context = getTestContext(); // protected final PostsApplication application = getTestApplication(); // // // System specific fields. // @Mock protected ConnectivityManager connectivityManagerMock; // // // Activity specific fields. // @Mock protected PostsApplication applicationMock; // @Mock protected SnackbarActions snackbarActionsMock; // // // ROBOLECTRIC // ******************************************************************************************************* // // private Context getTestContext() { // return getShadowApplication().getApplicationContext(); // } // // private ShadowApplication getShadowApplication() { // return ShadowApplication.getInstance(); // } // // private PostsApplication getTestApplication() { // return (PostsApplication) RuntimeEnvironment.application; // } // // // MOCKS // ************************************************************************************************************* // // protected void setUpMocks() { // super.setUpMocks(); // setUpApplicationMocks(); // } // // private void setUpApplicationMocks() { // when(applicationMock.getSystemService(Context.CONNECTIVITY_SERVICE)).thenReturn(connectivityManagerMock); // when(applicationMock.snackbar()).thenReturn(snackbarActionsMock); // } // // // POST // ************************************************************************************************************** // // protected Bundle getExtras(final Post post) { // final Bundle extras = new Bundle(); // extras.putInt(Post.USER_ID, post.getUserId()); // extras.putInt(Post.ID, post.getId()); // extras.putString(Post.TITLE, post.getTitle()); // extras.putString(Post.BODY, post.getBody()); // return extras; // } // // } // // Path: app/src/test/java/io/petros/posts/util/WhiteboxTestUtilities.java // public static final String SDK_INT = "SDK_INT"; // Path: app/src/test/java/io/petros/posts/util/DeprecationUtilitiesTest.java import android.annotation.TargetApi; import android.graphics.drawable.Drawable; import android.os.Build; import android.view.View; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.robolectric.util.ReflectionHelpers; import io.petros.posts.PreconfiguredRobolectricTestRunner; import io.petros.posts.R; import io.petros.posts.RobolectricGeneralTestHelper; import static io.petros.posts.util.WhiteboxTestUtilities.SDK_INT; import static org.mockito.Matchers.any; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; package io.petros.posts.util; @RunWith(PreconfiguredRobolectricTestRunner.class) public class DeprecationUtilitiesTest extends RobolectricGeneralTestHelper { @Mock private View viewMock; @Before public void setUp() { setUpMocks(); setUpView(); } private void setUpView() { when(viewMock.getContext()).thenReturn(context); } @Test @TargetApi(Build.VERSION_CODES.JELLY_BEAN) public void setBackgroundTestForJellyBeanAndAfter() { DeprecationUtilities.setBackground(viewMock, R.drawable.snackbar__design_snackbar_background); verify(viewMock, times(1)).setBackground(any(Drawable.class)); verifyNoMoreInteractions(connectivityManagerMock); } @Test @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) @Ignore("android.content.res.Resources$NotFoundException: Unable to find resource ID #0x0 in packages") public void setBackgroundTestForPriorJellyBean() {
ReflectionHelpers.setStaticField(Build.VERSION.class, SDK_INT, Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1);
ParaskP7/sample-code-posts
app/src/main/java/io/petros/posts/activity/posts/model/PostsModelImpl.java
// Path: app/src/main/java/io/petros/posts/datastore/Datastore.java // public class Datastore { // // private final DatastoreSaveActions datastoreSaveActions; // private final DatastoreAddActions datastoreAddActions; // private final DatastoreGetActions datastoreGetActions; // private final DatastoreUpdateActions datastoreUpdateActions; // // public Datastore(final DatastoreSaveActions datastoreSaveActions, final DatastoreAddActions datastoreAddActions, // final DatastoreGetActions datastoreGetActions, final DatastoreUpdateActions datastoreUpdateActions) { // this.datastoreSaveActions = datastoreSaveActions; // this.datastoreAddActions = datastoreAddActions; // this.datastoreGetActions = datastoreGetActions; // this.datastoreUpdateActions = datastoreUpdateActions; // } // // public SaveActions save() { // return datastoreSaveActions; // } // // public AddActions add() { // return datastoreAddActions; // } // // public GetActions get() { // return datastoreGetActions; // } // // public UpdateActions update() { // return datastoreUpdateActions; // } // // } // // Path: app/src/main/java/io/petros/posts/model/User.java // public class User extends RealmObject { // // public static final String ID = "id"; // public static final String NAME = "name"; // public static final String USERNAME = "username"; // public static final String EMAIL = "email"; // // @SerializedName(ID) // @Expose // @PrimaryKey // private Integer id; // // @SerializedName(NAME) // @Expose // private String name; // // @SerializedName(USERNAME) // @Expose // private String username; // // @SerializedName(EMAIL) // @Expose // private String email; // // public Integer getId() { // return id; // } // // public void setId(final Integer id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(final String name) { // this.name = name; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getEmail() { // return email; // } // // public void setEmail(final String email) { // this.email = email; // } // // }
import java.util.List; import io.petros.posts.datastore.Datastore; import io.petros.posts.model.User;
package io.petros.posts.activity.posts.model; public class PostsModelImpl implements PostsModel { private final Datastore datastore; public PostsModelImpl(final Datastore datastore) { this.datastore = datastore; } @Override
// Path: app/src/main/java/io/petros/posts/datastore/Datastore.java // public class Datastore { // // private final DatastoreSaveActions datastoreSaveActions; // private final DatastoreAddActions datastoreAddActions; // private final DatastoreGetActions datastoreGetActions; // private final DatastoreUpdateActions datastoreUpdateActions; // // public Datastore(final DatastoreSaveActions datastoreSaveActions, final DatastoreAddActions datastoreAddActions, // final DatastoreGetActions datastoreGetActions, final DatastoreUpdateActions datastoreUpdateActions) { // this.datastoreSaveActions = datastoreSaveActions; // this.datastoreAddActions = datastoreAddActions; // this.datastoreGetActions = datastoreGetActions; // this.datastoreUpdateActions = datastoreUpdateActions; // } // // public SaveActions save() { // return datastoreSaveActions; // } // // public AddActions add() { // return datastoreAddActions; // } // // public GetActions get() { // return datastoreGetActions; // } // // public UpdateActions update() { // return datastoreUpdateActions; // } // // } // // Path: app/src/main/java/io/petros/posts/model/User.java // public class User extends RealmObject { // // public static final String ID = "id"; // public static final String NAME = "name"; // public static final String USERNAME = "username"; // public static final String EMAIL = "email"; // // @SerializedName(ID) // @Expose // @PrimaryKey // private Integer id; // // @SerializedName(NAME) // @Expose // private String name; // // @SerializedName(USERNAME) // @Expose // private String username; // // @SerializedName(EMAIL) // @Expose // private String email; // // public Integer getId() { // return id; // } // // public void setId(final Integer id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(final String name) { // this.name = name; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getEmail() { // return email; // } // // public void setEmail(final String email) { // this.email = email; // } // // } // Path: app/src/main/java/io/petros/posts/activity/posts/model/PostsModelImpl.java import java.util.List; import io.petros.posts.datastore.Datastore; import io.petros.posts.model.User; package io.petros.posts.activity.posts.model; public class PostsModelImpl implements PostsModel { private final Datastore datastore; public PostsModelImpl(final Datastore datastore) { this.datastore = datastore; } @Override
public boolean saveUsers(final List<User> users) {
ParaskP7/sample-code-posts
app/src/main/java/io/petros/posts/activity/post/model/PostModel.java
// Path: app/src/main/java/io/petros/posts/model/User.java // public class User extends RealmObject { // // public static final String ID = "id"; // public static final String NAME = "name"; // public static final String USERNAME = "username"; // public static final String EMAIL = "email"; // // @SerializedName(ID) // @Expose // @PrimaryKey // private Integer id; // // @SerializedName(NAME) // @Expose // private String name; // // @SerializedName(USERNAME) // @Expose // private String username; // // @SerializedName(EMAIL) // @Expose // private String email; // // public Integer getId() { // return id; // } // // public void setId(final Integer id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(final String name) { // this.name = name; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getEmail() { // return email; // } // // public void setEmail(final String email) { // this.email = email; // } // // }
import javax.annotation.Nullable; import io.petros.posts.model.User;
package io.petros.posts.activity.post.model; public interface PostModel { @Nullable
// Path: app/src/main/java/io/petros/posts/model/User.java // public class User extends RealmObject { // // public static final String ID = "id"; // public static final String NAME = "name"; // public static final String USERNAME = "username"; // public static final String EMAIL = "email"; // // @SerializedName(ID) // @Expose // @PrimaryKey // private Integer id; // // @SerializedName(NAME) // @Expose // private String name; // // @SerializedName(USERNAME) // @Expose // private String username; // // @SerializedName(EMAIL) // @Expose // private String email; // // public Integer getId() { // return id; // } // // public void setId(final Integer id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(final String name) { // this.name = name; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getEmail() { // return email; // } // // public void setEmail(final String email) { // this.email = email; // } // // } // Path: app/src/main/java/io/petros/posts/activity/post/model/PostModel.java import javax.annotation.Nullable; import io.petros.posts.model.User; package io.petros.posts.activity.post.model; public interface PostModel { @Nullable
User getUser(final Integer userId);
ParaskP7/sample-code-posts
app/src/test/java/io/petros/posts/activity/posts/PostsActivityTest.java
// Path: app/src/test/java/io/petros/posts/PreconfiguredRobolectricTestRunner.java // public class PreconfiguredRobolectricTestRunner extends RobolectricTestRunner { // // private static final int SDK_API_LEVEL_TO_EMULATE = 25; // // /** // * Creates a runner to run {@code testClass}. Looks in your working directory for your AndroidManifest.xml file and res directory by // * default. Use the {@link Config} annotation to configure. // * // * @param testClass The test class to be run. // * @throws InitializationError If junit says so. // */ // public PreconfiguredRobolectricTestRunner(final Class<?> testClass) throws InitializationError { // super(testClass); // } // // @Override // protected Config buildGlobalConfig() { // return new Config.Builder() // .setSdk(SDK_API_LEVEL_TO_EMULATE) // .setManifest(Config.NONE) // .setApplication(TestPostsApplication.class) // .build(); // } // // } // // Path: app/src/test/java/io/petros/posts/RobolectricGeneralTestHelper.java // public class RobolectricGeneralTestHelper extends GeneralTestHelper { // // // Application specific fields. // protected final Context context = getTestContext(); // protected final PostsApplication application = getTestApplication(); // // // System specific fields. // @Mock protected ConnectivityManager connectivityManagerMock; // // // Activity specific fields. // @Mock protected PostsApplication applicationMock; // @Mock protected SnackbarActions snackbarActionsMock; // // // ROBOLECTRIC // ******************************************************************************************************* // // private Context getTestContext() { // return getShadowApplication().getApplicationContext(); // } // // private ShadowApplication getShadowApplication() { // return ShadowApplication.getInstance(); // } // // private PostsApplication getTestApplication() { // return (PostsApplication) RuntimeEnvironment.application; // } // // // MOCKS // ************************************************************************************************************* // // protected void setUpMocks() { // super.setUpMocks(); // setUpApplicationMocks(); // } // // private void setUpApplicationMocks() { // when(applicationMock.getSystemService(Context.CONNECTIVITY_SERVICE)).thenReturn(connectivityManagerMock); // when(applicationMock.snackbar()).thenReturn(snackbarActionsMock); // } // // // POST // ************************************************************************************************************** // // protected Bundle getExtras(final Post post) { // final Bundle extras = new Bundle(); // extras.putInt(Post.USER_ID, post.getUserId()); // extras.putInt(Post.ID, post.getId()); // extras.putString(Post.TITLE, post.getTitle()); // extras.putString(Post.BODY, post.getBody()); // return extras; // } // // }
import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.Robolectric; import io.petros.posts.PreconfiguredRobolectricTestRunner; import io.petros.posts.R; import io.petros.posts.RobolectricGeneralTestHelper; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions;
package io.petros.posts.activity.posts; @Ignore("Problem with RxJava: Attempted to consume batched input events but the input event receiver has already been disposed.") @RunWith(PreconfiguredRobolectricTestRunner.class)
// Path: app/src/test/java/io/petros/posts/PreconfiguredRobolectricTestRunner.java // public class PreconfiguredRobolectricTestRunner extends RobolectricTestRunner { // // private static final int SDK_API_LEVEL_TO_EMULATE = 25; // // /** // * Creates a runner to run {@code testClass}. Looks in your working directory for your AndroidManifest.xml file and res directory by // * default. Use the {@link Config} annotation to configure. // * // * @param testClass The test class to be run. // * @throws InitializationError If junit says so. // */ // public PreconfiguredRobolectricTestRunner(final Class<?> testClass) throws InitializationError { // super(testClass); // } // // @Override // protected Config buildGlobalConfig() { // return new Config.Builder() // .setSdk(SDK_API_LEVEL_TO_EMULATE) // .setManifest(Config.NONE) // .setApplication(TestPostsApplication.class) // .build(); // } // // } // // Path: app/src/test/java/io/petros/posts/RobolectricGeneralTestHelper.java // public class RobolectricGeneralTestHelper extends GeneralTestHelper { // // // Application specific fields. // protected final Context context = getTestContext(); // protected final PostsApplication application = getTestApplication(); // // // System specific fields. // @Mock protected ConnectivityManager connectivityManagerMock; // // // Activity specific fields. // @Mock protected PostsApplication applicationMock; // @Mock protected SnackbarActions snackbarActionsMock; // // // ROBOLECTRIC // ******************************************************************************************************* // // private Context getTestContext() { // return getShadowApplication().getApplicationContext(); // } // // private ShadowApplication getShadowApplication() { // return ShadowApplication.getInstance(); // } // // private PostsApplication getTestApplication() { // return (PostsApplication) RuntimeEnvironment.application; // } // // // MOCKS // ************************************************************************************************************* // // protected void setUpMocks() { // super.setUpMocks(); // setUpApplicationMocks(); // } // // private void setUpApplicationMocks() { // when(applicationMock.getSystemService(Context.CONNECTIVITY_SERVICE)).thenReturn(connectivityManagerMock); // when(applicationMock.snackbar()).thenReturn(snackbarActionsMock); // } // // // POST // ************************************************************************************************************** // // protected Bundle getExtras(final Post post) { // final Bundle extras = new Bundle(); // extras.putInt(Post.USER_ID, post.getUserId()); // extras.putInt(Post.ID, post.getId()); // extras.putString(Post.TITLE, post.getTitle()); // extras.putString(Post.BODY, post.getBody()); // return extras; // } // // } // Path: app/src/test/java/io/petros/posts/activity/posts/PostsActivityTest.java import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.Robolectric; import io.petros.posts.PreconfiguredRobolectricTestRunner; import io.petros.posts.R; import io.petros.posts.RobolectricGeneralTestHelper; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; package io.petros.posts.activity.posts; @Ignore("Problem with RxJava: Attempted to consume batched input events but the input event receiver has already been disposed.") @RunWith(PreconfiguredRobolectricTestRunner.class)
public class PostsActivityTest extends RobolectricGeneralTestHelper {
ParaskP7/sample-code-posts
app/src/main/java/io/petros/posts/activity/post/model/PostModelImpl.java
// Path: app/src/main/java/io/petros/posts/datastore/Datastore.java // public class Datastore { // // private final DatastoreSaveActions datastoreSaveActions; // private final DatastoreAddActions datastoreAddActions; // private final DatastoreGetActions datastoreGetActions; // private final DatastoreUpdateActions datastoreUpdateActions; // // public Datastore(final DatastoreSaveActions datastoreSaveActions, final DatastoreAddActions datastoreAddActions, // final DatastoreGetActions datastoreGetActions, final DatastoreUpdateActions datastoreUpdateActions) { // this.datastoreSaveActions = datastoreSaveActions; // this.datastoreAddActions = datastoreAddActions; // this.datastoreGetActions = datastoreGetActions; // this.datastoreUpdateActions = datastoreUpdateActions; // } // // public SaveActions save() { // return datastoreSaveActions; // } // // public AddActions add() { // return datastoreAddActions; // } // // public GetActions get() { // return datastoreGetActions; // } // // public UpdateActions update() { // return datastoreUpdateActions; // } // // } // // Path: app/src/main/java/io/petros/posts/model/User.java // public class User extends RealmObject { // // public static final String ID = "id"; // public static final String NAME = "name"; // public static final String USERNAME = "username"; // public static final String EMAIL = "email"; // // @SerializedName(ID) // @Expose // @PrimaryKey // private Integer id; // // @SerializedName(NAME) // @Expose // private String name; // // @SerializedName(USERNAME) // @Expose // private String username; // // @SerializedName(EMAIL) // @Expose // private String email; // // public Integer getId() { // return id; // } // // public void setId(final Integer id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(final String name) { // this.name = name; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getEmail() { // return email; // } // // public void setEmail(final String email) { // this.email = email; // } // // }
import javax.annotation.Nullable; import io.petros.posts.datastore.Datastore; import io.petros.posts.model.User;
package io.petros.posts.activity.post.model; public class PostModelImpl implements PostModel { private final Datastore datastore; public PostModelImpl(final Datastore datastore) { this.datastore = datastore; } @Nullable
// Path: app/src/main/java/io/petros/posts/datastore/Datastore.java // public class Datastore { // // private final DatastoreSaveActions datastoreSaveActions; // private final DatastoreAddActions datastoreAddActions; // private final DatastoreGetActions datastoreGetActions; // private final DatastoreUpdateActions datastoreUpdateActions; // // public Datastore(final DatastoreSaveActions datastoreSaveActions, final DatastoreAddActions datastoreAddActions, // final DatastoreGetActions datastoreGetActions, final DatastoreUpdateActions datastoreUpdateActions) { // this.datastoreSaveActions = datastoreSaveActions; // this.datastoreAddActions = datastoreAddActions; // this.datastoreGetActions = datastoreGetActions; // this.datastoreUpdateActions = datastoreUpdateActions; // } // // public SaveActions save() { // return datastoreSaveActions; // } // // public AddActions add() { // return datastoreAddActions; // } // // public GetActions get() { // return datastoreGetActions; // } // // public UpdateActions update() { // return datastoreUpdateActions; // } // // } // // Path: app/src/main/java/io/petros/posts/model/User.java // public class User extends RealmObject { // // public static final String ID = "id"; // public static final String NAME = "name"; // public static final String USERNAME = "username"; // public static final String EMAIL = "email"; // // @SerializedName(ID) // @Expose // @PrimaryKey // private Integer id; // // @SerializedName(NAME) // @Expose // private String name; // // @SerializedName(USERNAME) // @Expose // private String username; // // @SerializedName(EMAIL) // @Expose // private String email; // // public Integer getId() { // return id; // } // // public void setId(final Integer id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(final String name) { // this.name = name; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getEmail() { // return email; // } // // public void setEmail(final String email) { // this.email = email; // } // // } // Path: app/src/main/java/io/petros/posts/activity/post/model/PostModelImpl.java import javax.annotation.Nullable; import io.petros.posts.datastore.Datastore; import io.petros.posts.model.User; package io.petros.posts.activity.post.model; public class PostModelImpl implements PostModel { private final Datastore datastore; public PostModelImpl(final Datastore datastore) { this.datastore = datastore; } @Nullable
public User getUser(final Integer userId) {
ParaskP7/sample-code-posts
app/src/test/java/io/petros/posts/activity/post/presenter/PostPresenterImplTest.java
// Path: app/src/test/java/io/petros/posts/PreconfiguredRobolectricTestRunner.java // public class PreconfiguredRobolectricTestRunner extends RobolectricTestRunner { // // private static final int SDK_API_LEVEL_TO_EMULATE = 25; // // /** // * Creates a runner to run {@code testClass}. Looks in your working directory for your AndroidManifest.xml file and res directory by // * default. Use the {@link Config} annotation to configure. // * // * @param testClass The test class to be run. // * @throws InitializationError If junit says so. // */ // public PreconfiguredRobolectricTestRunner(final Class<?> testClass) throws InitializationError { // super(testClass); // } // // @Override // protected Config buildGlobalConfig() { // return new Config.Builder() // .setSdk(SDK_API_LEVEL_TO_EMULATE) // .setManifest(Config.NONE) // .setApplication(TestPostsApplication.class) // .build(); // } // // } // // Path: app/src/test/java/io/petros/posts/RobolectricGeneralTestHelper.java // public class RobolectricGeneralTestHelper extends GeneralTestHelper { // // // Application specific fields. // protected final Context context = getTestContext(); // protected final PostsApplication application = getTestApplication(); // // // System specific fields. // @Mock protected ConnectivityManager connectivityManagerMock; // // // Activity specific fields. // @Mock protected PostsApplication applicationMock; // @Mock protected SnackbarActions snackbarActionsMock; // // // ROBOLECTRIC // ******************************************************************************************************* // // private Context getTestContext() { // return getShadowApplication().getApplicationContext(); // } // // private ShadowApplication getShadowApplication() { // return ShadowApplication.getInstance(); // } // // private PostsApplication getTestApplication() { // return (PostsApplication) RuntimeEnvironment.application; // } // // // MOCKS // ************************************************************************************************************* // // protected void setUpMocks() { // super.setUpMocks(); // setUpApplicationMocks(); // } // // private void setUpApplicationMocks() { // when(applicationMock.getSystemService(Context.CONNECTIVITY_SERVICE)).thenReturn(connectivityManagerMock); // when(applicationMock.snackbar()).thenReturn(snackbarActionsMock); // } // // // POST // ************************************************************************************************************** // // protected Bundle getExtras(final Post post) { // final Bundle extras = new Bundle(); // extras.putInt(Post.USER_ID, post.getUserId()); // extras.putInt(Post.ID, post.getId()); // extras.putString(Post.TITLE, post.getTitle()); // extras.putString(Post.BODY, post.getBody()); // return extras; // } // // } // // Path: app/src/main/java/io/petros/posts/activity/post/model/PostModel.java // public interface PostModel { // // @Nullable // User getUser(final Integer userId); // // } // // Path: app/src/main/java/io/petros/posts/activity/post/view/PostView.java // public interface PostView { // // void loadPostUserAndPost(); // // void loadPostUser(final String userEmail, final String userName, final String userUsername); // // void notifyUserAboutUserUnavailability(); // // void notifyUserAboutInternetUnavailability(); // // void loadPost(final String postTitle, final String postBody, final String numberOfComments); // // void notifyUserAboutPostUnavailability(); // // void showError(); // // } // // Path: app/src/main/java/io/petros/posts/service/detector/InternetAvailabilityDetector.java // public class InternetAvailabilityDetector implements AvailabilityDetector { // // private final ConnectivityManager connectivityManager; // // public InternetAvailabilityDetector(final PostsApplication application) { // this.connectivityManager = (ConnectivityManager) application.getSystemService(Context.CONNECTIVITY_SERVICE); // } // // @Override // public boolean isAvailable() { // @Nullable final NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); // if (activeNetworkInfo != null) { // if (activeNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI) { // Timber.v("Internet connection is available; Connected to WiFi."); // return true; // } else if (activeNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE) { // Timber.v("Internet connection is available; Connected to the mobile provider's data plan."); // return true; // } else { // Timber.v("Internet connection is available. [Network Type: %d]", activeNetworkInfo.getType()); // return true; // } // } else { // Timber.d("Internet connection is not available at the moment."); // return false; // } // } // // } // // Path: app/src/main/java/io/petros/posts/service/retrofit/RetrofitService.java // public interface RetrofitService { // // @GET("/posts") // Observable<List<Post>> posts(); // // @GET("/users") // Observable<List<User>> users(); // // @GET("/comments") // Observable<List<Comment>> comments(@Query("postId") int postId); // // }
import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import io.petros.posts.PreconfiguredRobolectricTestRunner; import io.petros.posts.RobolectricGeneralTestHelper; import io.petros.posts.activity.post.model.PostModel; import io.petros.posts.activity.post.view.PostView; import io.petros.posts.service.detector.InternetAvailabilityDetector; import io.petros.posts.service.retrofit.RetrofitService; import io.reactivex.Observable; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when;
package io.petros.posts.activity.post.presenter; @RunWith(PreconfiguredRobolectricTestRunner.class) public class PostPresenterImplTest extends RobolectricGeneralTestHelper { private PostPresenterImpl postPresenter;
// Path: app/src/test/java/io/petros/posts/PreconfiguredRobolectricTestRunner.java // public class PreconfiguredRobolectricTestRunner extends RobolectricTestRunner { // // private static final int SDK_API_LEVEL_TO_EMULATE = 25; // // /** // * Creates a runner to run {@code testClass}. Looks in your working directory for your AndroidManifest.xml file and res directory by // * default. Use the {@link Config} annotation to configure. // * // * @param testClass The test class to be run. // * @throws InitializationError If junit says so. // */ // public PreconfiguredRobolectricTestRunner(final Class<?> testClass) throws InitializationError { // super(testClass); // } // // @Override // protected Config buildGlobalConfig() { // return new Config.Builder() // .setSdk(SDK_API_LEVEL_TO_EMULATE) // .setManifest(Config.NONE) // .setApplication(TestPostsApplication.class) // .build(); // } // // } // // Path: app/src/test/java/io/petros/posts/RobolectricGeneralTestHelper.java // public class RobolectricGeneralTestHelper extends GeneralTestHelper { // // // Application specific fields. // protected final Context context = getTestContext(); // protected final PostsApplication application = getTestApplication(); // // // System specific fields. // @Mock protected ConnectivityManager connectivityManagerMock; // // // Activity specific fields. // @Mock protected PostsApplication applicationMock; // @Mock protected SnackbarActions snackbarActionsMock; // // // ROBOLECTRIC // ******************************************************************************************************* // // private Context getTestContext() { // return getShadowApplication().getApplicationContext(); // } // // private ShadowApplication getShadowApplication() { // return ShadowApplication.getInstance(); // } // // private PostsApplication getTestApplication() { // return (PostsApplication) RuntimeEnvironment.application; // } // // // MOCKS // ************************************************************************************************************* // // protected void setUpMocks() { // super.setUpMocks(); // setUpApplicationMocks(); // } // // private void setUpApplicationMocks() { // when(applicationMock.getSystemService(Context.CONNECTIVITY_SERVICE)).thenReturn(connectivityManagerMock); // when(applicationMock.snackbar()).thenReturn(snackbarActionsMock); // } // // // POST // ************************************************************************************************************** // // protected Bundle getExtras(final Post post) { // final Bundle extras = new Bundle(); // extras.putInt(Post.USER_ID, post.getUserId()); // extras.putInt(Post.ID, post.getId()); // extras.putString(Post.TITLE, post.getTitle()); // extras.putString(Post.BODY, post.getBody()); // return extras; // } // // } // // Path: app/src/main/java/io/petros/posts/activity/post/model/PostModel.java // public interface PostModel { // // @Nullable // User getUser(final Integer userId); // // } // // Path: app/src/main/java/io/petros/posts/activity/post/view/PostView.java // public interface PostView { // // void loadPostUserAndPost(); // // void loadPostUser(final String userEmail, final String userName, final String userUsername); // // void notifyUserAboutUserUnavailability(); // // void notifyUserAboutInternetUnavailability(); // // void loadPost(final String postTitle, final String postBody, final String numberOfComments); // // void notifyUserAboutPostUnavailability(); // // void showError(); // // } // // Path: app/src/main/java/io/petros/posts/service/detector/InternetAvailabilityDetector.java // public class InternetAvailabilityDetector implements AvailabilityDetector { // // private final ConnectivityManager connectivityManager; // // public InternetAvailabilityDetector(final PostsApplication application) { // this.connectivityManager = (ConnectivityManager) application.getSystemService(Context.CONNECTIVITY_SERVICE); // } // // @Override // public boolean isAvailable() { // @Nullable final NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); // if (activeNetworkInfo != null) { // if (activeNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI) { // Timber.v("Internet connection is available; Connected to WiFi."); // return true; // } else if (activeNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE) { // Timber.v("Internet connection is available; Connected to the mobile provider's data plan."); // return true; // } else { // Timber.v("Internet connection is available. [Network Type: %d]", activeNetworkInfo.getType()); // return true; // } // } else { // Timber.d("Internet connection is not available at the moment."); // return false; // } // } // // } // // Path: app/src/main/java/io/petros/posts/service/retrofit/RetrofitService.java // public interface RetrofitService { // // @GET("/posts") // Observable<List<Post>> posts(); // // @GET("/users") // Observable<List<User>> users(); // // @GET("/comments") // Observable<List<Comment>> comments(@Query("postId") int postId); // // } // Path: app/src/test/java/io/petros/posts/activity/post/presenter/PostPresenterImplTest.java import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import io.petros.posts.PreconfiguredRobolectricTestRunner; import io.petros.posts.RobolectricGeneralTestHelper; import io.petros.posts.activity.post.model.PostModel; import io.petros.posts.activity.post.view.PostView; import io.petros.posts.service.detector.InternetAvailabilityDetector; import io.petros.posts.service.retrofit.RetrofitService; import io.reactivex.Observable; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; package io.petros.posts.activity.post.presenter; @RunWith(PreconfiguredRobolectricTestRunner.class) public class PostPresenterImplTest extends RobolectricGeneralTestHelper { private PostPresenterImpl postPresenter;
@Mock private PostModel postModelMock;
ParaskP7/sample-code-posts
app/src/test/java/io/petros/posts/activity/post/presenter/PostPresenterImplTest.java
// Path: app/src/test/java/io/petros/posts/PreconfiguredRobolectricTestRunner.java // public class PreconfiguredRobolectricTestRunner extends RobolectricTestRunner { // // private static final int SDK_API_LEVEL_TO_EMULATE = 25; // // /** // * Creates a runner to run {@code testClass}. Looks in your working directory for your AndroidManifest.xml file and res directory by // * default. Use the {@link Config} annotation to configure. // * // * @param testClass The test class to be run. // * @throws InitializationError If junit says so. // */ // public PreconfiguredRobolectricTestRunner(final Class<?> testClass) throws InitializationError { // super(testClass); // } // // @Override // protected Config buildGlobalConfig() { // return new Config.Builder() // .setSdk(SDK_API_LEVEL_TO_EMULATE) // .setManifest(Config.NONE) // .setApplication(TestPostsApplication.class) // .build(); // } // // } // // Path: app/src/test/java/io/petros/posts/RobolectricGeneralTestHelper.java // public class RobolectricGeneralTestHelper extends GeneralTestHelper { // // // Application specific fields. // protected final Context context = getTestContext(); // protected final PostsApplication application = getTestApplication(); // // // System specific fields. // @Mock protected ConnectivityManager connectivityManagerMock; // // // Activity specific fields. // @Mock protected PostsApplication applicationMock; // @Mock protected SnackbarActions snackbarActionsMock; // // // ROBOLECTRIC // ******************************************************************************************************* // // private Context getTestContext() { // return getShadowApplication().getApplicationContext(); // } // // private ShadowApplication getShadowApplication() { // return ShadowApplication.getInstance(); // } // // private PostsApplication getTestApplication() { // return (PostsApplication) RuntimeEnvironment.application; // } // // // MOCKS // ************************************************************************************************************* // // protected void setUpMocks() { // super.setUpMocks(); // setUpApplicationMocks(); // } // // private void setUpApplicationMocks() { // when(applicationMock.getSystemService(Context.CONNECTIVITY_SERVICE)).thenReturn(connectivityManagerMock); // when(applicationMock.snackbar()).thenReturn(snackbarActionsMock); // } // // // POST // ************************************************************************************************************** // // protected Bundle getExtras(final Post post) { // final Bundle extras = new Bundle(); // extras.putInt(Post.USER_ID, post.getUserId()); // extras.putInt(Post.ID, post.getId()); // extras.putString(Post.TITLE, post.getTitle()); // extras.putString(Post.BODY, post.getBody()); // return extras; // } // // } // // Path: app/src/main/java/io/petros/posts/activity/post/model/PostModel.java // public interface PostModel { // // @Nullable // User getUser(final Integer userId); // // } // // Path: app/src/main/java/io/petros/posts/activity/post/view/PostView.java // public interface PostView { // // void loadPostUserAndPost(); // // void loadPostUser(final String userEmail, final String userName, final String userUsername); // // void notifyUserAboutUserUnavailability(); // // void notifyUserAboutInternetUnavailability(); // // void loadPost(final String postTitle, final String postBody, final String numberOfComments); // // void notifyUserAboutPostUnavailability(); // // void showError(); // // } // // Path: app/src/main/java/io/petros/posts/service/detector/InternetAvailabilityDetector.java // public class InternetAvailabilityDetector implements AvailabilityDetector { // // private final ConnectivityManager connectivityManager; // // public InternetAvailabilityDetector(final PostsApplication application) { // this.connectivityManager = (ConnectivityManager) application.getSystemService(Context.CONNECTIVITY_SERVICE); // } // // @Override // public boolean isAvailable() { // @Nullable final NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); // if (activeNetworkInfo != null) { // if (activeNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI) { // Timber.v("Internet connection is available; Connected to WiFi."); // return true; // } else if (activeNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE) { // Timber.v("Internet connection is available; Connected to the mobile provider's data plan."); // return true; // } else { // Timber.v("Internet connection is available. [Network Type: %d]", activeNetworkInfo.getType()); // return true; // } // } else { // Timber.d("Internet connection is not available at the moment."); // return false; // } // } // // } // // Path: app/src/main/java/io/petros/posts/service/retrofit/RetrofitService.java // public interface RetrofitService { // // @GET("/posts") // Observable<List<Post>> posts(); // // @GET("/users") // Observable<List<User>> users(); // // @GET("/comments") // Observable<List<Comment>> comments(@Query("postId") int postId); // // }
import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import io.petros.posts.PreconfiguredRobolectricTestRunner; import io.petros.posts.RobolectricGeneralTestHelper; import io.petros.posts.activity.post.model.PostModel; import io.petros.posts.activity.post.view.PostView; import io.petros.posts.service.detector.InternetAvailabilityDetector; import io.petros.posts.service.retrofit.RetrofitService; import io.reactivex.Observable; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when;
package io.petros.posts.activity.post.presenter; @RunWith(PreconfiguredRobolectricTestRunner.class) public class PostPresenterImplTest extends RobolectricGeneralTestHelper { private PostPresenterImpl postPresenter; @Mock private PostModel postModelMock;
// Path: app/src/test/java/io/petros/posts/PreconfiguredRobolectricTestRunner.java // public class PreconfiguredRobolectricTestRunner extends RobolectricTestRunner { // // private static final int SDK_API_LEVEL_TO_EMULATE = 25; // // /** // * Creates a runner to run {@code testClass}. Looks in your working directory for your AndroidManifest.xml file and res directory by // * default. Use the {@link Config} annotation to configure. // * // * @param testClass The test class to be run. // * @throws InitializationError If junit says so. // */ // public PreconfiguredRobolectricTestRunner(final Class<?> testClass) throws InitializationError { // super(testClass); // } // // @Override // protected Config buildGlobalConfig() { // return new Config.Builder() // .setSdk(SDK_API_LEVEL_TO_EMULATE) // .setManifest(Config.NONE) // .setApplication(TestPostsApplication.class) // .build(); // } // // } // // Path: app/src/test/java/io/petros/posts/RobolectricGeneralTestHelper.java // public class RobolectricGeneralTestHelper extends GeneralTestHelper { // // // Application specific fields. // protected final Context context = getTestContext(); // protected final PostsApplication application = getTestApplication(); // // // System specific fields. // @Mock protected ConnectivityManager connectivityManagerMock; // // // Activity specific fields. // @Mock protected PostsApplication applicationMock; // @Mock protected SnackbarActions snackbarActionsMock; // // // ROBOLECTRIC // ******************************************************************************************************* // // private Context getTestContext() { // return getShadowApplication().getApplicationContext(); // } // // private ShadowApplication getShadowApplication() { // return ShadowApplication.getInstance(); // } // // private PostsApplication getTestApplication() { // return (PostsApplication) RuntimeEnvironment.application; // } // // // MOCKS // ************************************************************************************************************* // // protected void setUpMocks() { // super.setUpMocks(); // setUpApplicationMocks(); // } // // private void setUpApplicationMocks() { // when(applicationMock.getSystemService(Context.CONNECTIVITY_SERVICE)).thenReturn(connectivityManagerMock); // when(applicationMock.snackbar()).thenReturn(snackbarActionsMock); // } // // // POST // ************************************************************************************************************** // // protected Bundle getExtras(final Post post) { // final Bundle extras = new Bundle(); // extras.putInt(Post.USER_ID, post.getUserId()); // extras.putInt(Post.ID, post.getId()); // extras.putString(Post.TITLE, post.getTitle()); // extras.putString(Post.BODY, post.getBody()); // return extras; // } // // } // // Path: app/src/main/java/io/petros/posts/activity/post/model/PostModel.java // public interface PostModel { // // @Nullable // User getUser(final Integer userId); // // } // // Path: app/src/main/java/io/petros/posts/activity/post/view/PostView.java // public interface PostView { // // void loadPostUserAndPost(); // // void loadPostUser(final String userEmail, final String userName, final String userUsername); // // void notifyUserAboutUserUnavailability(); // // void notifyUserAboutInternetUnavailability(); // // void loadPost(final String postTitle, final String postBody, final String numberOfComments); // // void notifyUserAboutPostUnavailability(); // // void showError(); // // } // // Path: app/src/main/java/io/petros/posts/service/detector/InternetAvailabilityDetector.java // public class InternetAvailabilityDetector implements AvailabilityDetector { // // private final ConnectivityManager connectivityManager; // // public InternetAvailabilityDetector(final PostsApplication application) { // this.connectivityManager = (ConnectivityManager) application.getSystemService(Context.CONNECTIVITY_SERVICE); // } // // @Override // public boolean isAvailable() { // @Nullable final NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); // if (activeNetworkInfo != null) { // if (activeNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI) { // Timber.v("Internet connection is available; Connected to WiFi."); // return true; // } else if (activeNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE) { // Timber.v("Internet connection is available; Connected to the mobile provider's data plan."); // return true; // } else { // Timber.v("Internet connection is available. [Network Type: %d]", activeNetworkInfo.getType()); // return true; // } // } else { // Timber.d("Internet connection is not available at the moment."); // return false; // } // } // // } // // Path: app/src/main/java/io/petros/posts/service/retrofit/RetrofitService.java // public interface RetrofitService { // // @GET("/posts") // Observable<List<Post>> posts(); // // @GET("/users") // Observable<List<User>> users(); // // @GET("/comments") // Observable<List<Comment>> comments(@Query("postId") int postId); // // } // Path: app/src/test/java/io/petros/posts/activity/post/presenter/PostPresenterImplTest.java import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import io.petros.posts.PreconfiguredRobolectricTestRunner; import io.petros.posts.RobolectricGeneralTestHelper; import io.petros.posts.activity.post.model.PostModel; import io.petros.posts.activity.post.view.PostView; import io.petros.posts.service.detector.InternetAvailabilityDetector; import io.petros.posts.service.retrofit.RetrofitService; import io.reactivex.Observable; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; package io.petros.posts.activity.post.presenter; @RunWith(PreconfiguredRobolectricTestRunner.class) public class PostPresenterImplTest extends RobolectricGeneralTestHelper { private PostPresenterImpl postPresenter; @Mock private PostModel postModelMock;
@Mock private RetrofitService retrofitServiceMock;
ParaskP7/sample-code-posts
app/src/test/java/io/petros/posts/activity/post/presenter/PostPresenterImplTest.java
// Path: app/src/test/java/io/petros/posts/PreconfiguredRobolectricTestRunner.java // public class PreconfiguredRobolectricTestRunner extends RobolectricTestRunner { // // private static final int SDK_API_LEVEL_TO_EMULATE = 25; // // /** // * Creates a runner to run {@code testClass}. Looks in your working directory for your AndroidManifest.xml file and res directory by // * default. Use the {@link Config} annotation to configure. // * // * @param testClass The test class to be run. // * @throws InitializationError If junit says so. // */ // public PreconfiguredRobolectricTestRunner(final Class<?> testClass) throws InitializationError { // super(testClass); // } // // @Override // protected Config buildGlobalConfig() { // return new Config.Builder() // .setSdk(SDK_API_LEVEL_TO_EMULATE) // .setManifest(Config.NONE) // .setApplication(TestPostsApplication.class) // .build(); // } // // } // // Path: app/src/test/java/io/petros/posts/RobolectricGeneralTestHelper.java // public class RobolectricGeneralTestHelper extends GeneralTestHelper { // // // Application specific fields. // protected final Context context = getTestContext(); // protected final PostsApplication application = getTestApplication(); // // // System specific fields. // @Mock protected ConnectivityManager connectivityManagerMock; // // // Activity specific fields. // @Mock protected PostsApplication applicationMock; // @Mock protected SnackbarActions snackbarActionsMock; // // // ROBOLECTRIC // ******************************************************************************************************* // // private Context getTestContext() { // return getShadowApplication().getApplicationContext(); // } // // private ShadowApplication getShadowApplication() { // return ShadowApplication.getInstance(); // } // // private PostsApplication getTestApplication() { // return (PostsApplication) RuntimeEnvironment.application; // } // // // MOCKS // ************************************************************************************************************* // // protected void setUpMocks() { // super.setUpMocks(); // setUpApplicationMocks(); // } // // private void setUpApplicationMocks() { // when(applicationMock.getSystemService(Context.CONNECTIVITY_SERVICE)).thenReturn(connectivityManagerMock); // when(applicationMock.snackbar()).thenReturn(snackbarActionsMock); // } // // // POST // ************************************************************************************************************** // // protected Bundle getExtras(final Post post) { // final Bundle extras = new Bundle(); // extras.putInt(Post.USER_ID, post.getUserId()); // extras.putInt(Post.ID, post.getId()); // extras.putString(Post.TITLE, post.getTitle()); // extras.putString(Post.BODY, post.getBody()); // return extras; // } // // } // // Path: app/src/main/java/io/petros/posts/activity/post/model/PostModel.java // public interface PostModel { // // @Nullable // User getUser(final Integer userId); // // } // // Path: app/src/main/java/io/petros/posts/activity/post/view/PostView.java // public interface PostView { // // void loadPostUserAndPost(); // // void loadPostUser(final String userEmail, final String userName, final String userUsername); // // void notifyUserAboutUserUnavailability(); // // void notifyUserAboutInternetUnavailability(); // // void loadPost(final String postTitle, final String postBody, final String numberOfComments); // // void notifyUserAboutPostUnavailability(); // // void showError(); // // } // // Path: app/src/main/java/io/petros/posts/service/detector/InternetAvailabilityDetector.java // public class InternetAvailabilityDetector implements AvailabilityDetector { // // private final ConnectivityManager connectivityManager; // // public InternetAvailabilityDetector(final PostsApplication application) { // this.connectivityManager = (ConnectivityManager) application.getSystemService(Context.CONNECTIVITY_SERVICE); // } // // @Override // public boolean isAvailable() { // @Nullable final NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); // if (activeNetworkInfo != null) { // if (activeNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI) { // Timber.v("Internet connection is available; Connected to WiFi."); // return true; // } else if (activeNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE) { // Timber.v("Internet connection is available; Connected to the mobile provider's data plan."); // return true; // } else { // Timber.v("Internet connection is available. [Network Type: %d]", activeNetworkInfo.getType()); // return true; // } // } else { // Timber.d("Internet connection is not available at the moment."); // return false; // } // } // // } // // Path: app/src/main/java/io/petros/posts/service/retrofit/RetrofitService.java // public interface RetrofitService { // // @GET("/posts") // Observable<List<Post>> posts(); // // @GET("/users") // Observable<List<User>> users(); // // @GET("/comments") // Observable<List<Comment>> comments(@Query("postId") int postId); // // }
import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import io.petros.posts.PreconfiguredRobolectricTestRunner; import io.petros.posts.RobolectricGeneralTestHelper; import io.petros.posts.activity.post.model.PostModel; import io.petros.posts.activity.post.view.PostView; import io.petros.posts.service.detector.InternetAvailabilityDetector; import io.petros.posts.service.retrofit.RetrofitService; import io.reactivex.Observable; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when;
package io.petros.posts.activity.post.presenter; @RunWith(PreconfiguredRobolectricTestRunner.class) public class PostPresenterImplTest extends RobolectricGeneralTestHelper { private PostPresenterImpl postPresenter; @Mock private PostModel postModelMock; @Mock private RetrofitService retrofitServiceMock;
// Path: app/src/test/java/io/petros/posts/PreconfiguredRobolectricTestRunner.java // public class PreconfiguredRobolectricTestRunner extends RobolectricTestRunner { // // private static final int SDK_API_LEVEL_TO_EMULATE = 25; // // /** // * Creates a runner to run {@code testClass}. Looks in your working directory for your AndroidManifest.xml file and res directory by // * default. Use the {@link Config} annotation to configure. // * // * @param testClass The test class to be run. // * @throws InitializationError If junit says so. // */ // public PreconfiguredRobolectricTestRunner(final Class<?> testClass) throws InitializationError { // super(testClass); // } // // @Override // protected Config buildGlobalConfig() { // return new Config.Builder() // .setSdk(SDK_API_LEVEL_TO_EMULATE) // .setManifest(Config.NONE) // .setApplication(TestPostsApplication.class) // .build(); // } // // } // // Path: app/src/test/java/io/petros/posts/RobolectricGeneralTestHelper.java // public class RobolectricGeneralTestHelper extends GeneralTestHelper { // // // Application specific fields. // protected final Context context = getTestContext(); // protected final PostsApplication application = getTestApplication(); // // // System specific fields. // @Mock protected ConnectivityManager connectivityManagerMock; // // // Activity specific fields. // @Mock protected PostsApplication applicationMock; // @Mock protected SnackbarActions snackbarActionsMock; // // // ROBOLECTRIC // ******************************************************************************************************* // // private Context getTestContext() { // return getShadowApplication().getApplicationContext(); // } // // private ShadowApplication getShadowApplication() { // return ShadowApplication.getInstance(); // } // // private PostsApplication getTestApplication() { // return (PostsApplication) RuntimeEnvironment.application; // } // // // MOCKS // ************************************************************************************************************* // // protected void setUpMocks() { // super.setUpMocks(); // setUpApplicationMocks(); // } // // private void setUpApplicationMocks() { // when(applicationMock.getSystemService(Context.CONNECTIVITY_SERVICE)).thenReturn(connectivityManagerMock); // when(applicationMock.snackbar()).thenReturn(snackbarActionsMock); // } // // // POST // ************************************************************************************************************** // // protected Bundle getExtras(final Post post) { // final Bundle extras = new Bundle(); // extras.putInt(Post.USER_ID, post.getUserId()); // extras.putInt(Post.ID, post.getId()); // extras.putString(Post.TITLE, post.getTitle()); // extras.putString(Post.BODY, post.getBody()); // return extras; // } // // } // // Path: app/src/main/java/io/petros/posts/activity/post/model/PostModel.java // public interface PostModel { // // @Nullable // User getUser(final Integer userId); // // } // // Path: app/src/main/java/io/petros/posts/activity/post/view/PostView.java // public interface PostView { // // void loadPostUserAndPost(); // // void loadPostUser(final String userEmail, final String userName, final String userUsername); // // void notifyUserAboutUserUnavailability(); // // void notifyUserAboutInternetUnavailability(); // // void loadPost(final String postTitle, final String postBody, final String numberOfComments); // // void notifyUserAboutPostUnavailability(); // // void showError(); // // } // // Path: app/src/main/java/io/petros/posts/service/detector/InternetAvailabilityDetector.java // public class InternetAvailabilityDetector implements AvailabilityDetector { // // private final ConnectivityManager connectivityManager; // // public InternetAvailabilityDetector(final PostsApplication application) { // this.connectivityManager = (ConnectivityManager) application.getSystemService(Context.CONNECTIVITY_SERVICE); // } // // @Override // public boolean isAvailable() { // @Nullable final NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); // if (activeNetworkInfo != null) { // if (activeNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI) { // Timber.v("Internet connection is available; Connected to WiFi."); // return true; // } else if (activeNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE) { // Timber.v("Internet connection is available; Connected to the mobile provider's data plan."); // return true; // } else { // Timber.v("Internet connection is available. [Network Type: %d]", activeNetworkInfo.getType()); // return true; // } // } else { // Timber.d("Internet connection is not available at the moment."); // return false; // } // } // // } // // Path: app/src/main/java/io/petros/posts/service/retrofit/RetrofitService.java // public interface RetrofitService { // // @GET("/posts") // Observable<List<Post>> posts(); // // @GET("/users") // Observable<List<User>> users(); // // @GET("/comments") // Observable<List<Comment>> comments(@Query("postId") int postId); // // } // Path: app/src/test/java/io/petros/posts/activity/post/presenter/PostPresenterImplTest.java import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import io.petros.posts.PreconfiguredRobolectricTestRunner; import io.petros.posts.RobolectricGeneralTestHelper; import io.petros.posts.activity.post.model.PostModel; import io.petros.posts.activity.post.view.PostView; import io.petros.posts.service.detector.InternetAvailabilityDetector; import io.petros.posts.service.retrofit.RetrofitService; import io.reactivex.Observable; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; package io.petros.posts.activity.post.presenter; @RunWith(PreconfiguredRobolectricTestRunner.class) public class PostPresenterImplTest extends RobolectricGeneralTestHelper { private PostPresenterImpl postPresenter; @Mock private PostModel postModelMock; @Mock private RetrofitService retrofitServiceMock;
@Mock private InternetAvailabilityDetector internetAvailabilityDetectorMock;
ParaskP7/sample-code-posts
app/src/main/java/io/petros/posts/datastore/DatastoreSaveActions.java
// Path: app/src/main/java/io/petros/posts/model/User.java // public class User extends RealmObject { // // public static final String ID = "id"; // public static final String NAME = "name"; // public static final String USERNAME = "username"; // public static final String EMAIL = "email"; // // @SerializedName(ID) // @Expose // @PrimaryKey // private Integer id; // // @SerializedName(NAME) // @Expose // private String name; // // @SerializedName(USERNAME) // @Expose // private String username; // // @SerializedName(EMAIL) // @Expose // private String email; // // public Integer getId() { // return id; // } // // public void setId(final Integer id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(final String name) { // this.name = name; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getEmail() { // return email; // } // // public void setEmail(final String email) { // this.email = email; // } // // }
import java.util.List; import javax.annotation.Nullable; import io.petros.posts.model.User;
package io.petros.posts.datastore; public class DatastoreSaveActions implements SaveActions { private final DatastoreAddActions datastoreAddActions; private final DatastoreGetActions datastoreGetActions; private final DatastoreUpdateActions datastoreUpdateActions; public DatastoreSaveActions(final DatastoreAddActions datastoreAddActions, final DatastoreGetActions datastoreGetActions, final DatastoreUpdateActions datastoreUpdateActions) { this.datastoreAddActions = datastoreAddActions; this.datastoreGetActions = datastoreGetActions; this.datastoreUpdateActions = datastoreUpdateActions; } @Override
// Path: app/src/main/java/io/petros/posts/model/User.java // public class User extends RealmObject { // // public static final String ID = "id"; // public static final String NAME = "name"; // public static final String USERNAME = "username"; // public static final String EMAIL = "email"; // // @SerializedName(ID) // @Expose // @PrimaryKey // private Integer id; // // @SerializedName(NAME) // @Expose // private String name; // // @SerializedName(USERNAME) // @Expose // private String username; // // @SerializedName(EMAIL) // @Expose // private String email; // // public Integer getId() { // return id; // } // // public void setId(final Integer id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(final String name) { // this.name = name; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getEmail() { // return email; // } // // public void setEmail(final String email) { // this.email = email; // } // // } // Path: app/src/main/java/io/petros/posts/datastore/DatastoreSaveActions.java import java.util.List; import javax.annotation.Nullable; import io.petros.posts.model.User; package io.petros.posts.datastore; public class DatastoreSaveActions implements SaveActions { private final DatastoreAddActions datastoreAddActions; private final DatastoreGetActions datastoreGetActions; private final DatastoreUpdateActions datastoreUpdateActions; public DatastoreSaveActions(final DatastoreAddActions datastoreAddActions, final DatastoreGetActions datastoreGetActions, final DatastoreUpdateActions datastoreUpdateActions) { this.datastoreAddActions = datastoreAddActions; this.datastoreGetActions = datastoreGetActions; this.datastoreUpdateActions = datastoreUpdateActions; } @Override
public boolean users(final List<User> users) {
ParaskP7/sample-code-posts
app/src/test/java/io/petros/posts/RobolectricGeneralTestHelper.java
// Path: app/src/main/java/io/petros/posts/app/PostsApplication.java // @SuppressWarnings("checkstyle:overloadmethodsdeclarationorder") // public class PostsApplication extends Application { // // private static ApplicationComponent applicationComponent; // // static { // AppCompatDelegate.setCompatVectorFromResourcesEnabled(true); // NOTE: This enables the "proxy" trick on the vector images. // } // // @Inject AppSnackbarActions appSnackbarActions; // // // HELPER // ************************************************************************************************************ // // public static ApplicationComponent getApplicationComponent() { // return applicationComponent; // } // // public static SnackbarActions snackbar(final Activity activity) { // return ((PostsApplication) activity.getApplication()).snackbar(); // } // // // APPLICATION // ******************************************************************************************************* // // @Override // public void onCreate() { // super.onCreate(); // initDagger(); // initRealm(); // initTimber(); // Timber.i("Posts application created!"); // } // // private void initDagger() { // applicationComponent = DaggerApplicationComponent.builder() // .appModule(new AppModule(this)) // .netModule(new NetModule(BASE_URL)) // .dataModule(new DataModule()) // .serviceModule(new ServiceModule()) // .activityModule(new ActivityModule()).build(); // applicationComponent.inject(this); // } // // private void initTimber() { // Timber.plant(new Timber.DebugTree()); // } // // protected void initRealm() { // Realm.init(this); // } // // // GET // *************************************************************************************************************** // // public Realm getDefaultRealmInstance() { // return Realm.getDefaultInstance(); // } // // // ACTIONS // *********************************************************************************************************** // // public SnackbarActions snackbar() { // return appSnackbarActions; // } // // } // // Path: app/src/main/java/io/petros/posts/app/actions/SnackbarActions.java // public interface SnackbarActions { // // void setCoordinatorLayout(final CoordinatorLayout coordinatorLayout); // // void info(final int textResId); // // void warn(final int textResId); // // void error(final int textResId); // // } // // Path: app/src/main/java/io/petros/posts/model/Post.java // public class Post { // // public static final String USER_ID = "userId"; // public static final String ID = "id"; // public static final String TITLE = "title"; // public static final String BODY = "body"; // // @SerializedName(USER_ID) // @Expose // private Integer userId; // // @SerializedName(ID) // @Expose // private Integer id; // // @SerializedName(TITLE) // @Expose // private String title; // // @SerializedName(BODY) // @Expose // private String body; // // public Integer getUserId() { // return userId; // } // // public void setUserId(final Integer userId) { // this.userId = userId; // } // // public Integer getId() { // return id; // } // // public void setId(final Integer id) { // this.id = id; // } // // public String getTitle() { // return title; // } // // public void setTitle(final String title) { // this.title = title; // } // // public String getBody() { // return body; // } // // public void setBody(final String body) { // this.body = body; // } // // }
import android.content.Context; import android.net.ConnectivityManager; import android.os.Bundle; import org.mockito.Mock; import org.robolectric.RuntimeEnvironment; import org.robolectric.shadows.ShadowApplication; import io.petros.posts.app.PostsApplication; import io.petros.posts.app.actions.SnackbarActions; import io.petros.posts.model.Post; import static org.mockito.Mockito.when;
package io.petros.posts; public class RobolectricGeneralTestHelper extends GeneralTestHelper { // Application specific fields. protected final Context context = getTestContext();
// Path: app/src/main/java/io/petros/posts/app/PostsApplication.java // @SuppressWarnings("checkstyle:overloadmethodsdeclarationorder") // public class PostsApplication extends Application { // // private static ApplicationComponent applicationComponent; // // static { // AppCompatDelegate.setCompatVectorFromResourcesEnabled(true); // NOTE: This enables the "proxy" trick on the vector images. // } // // @Inject AppSnackbarActions appSnackbarActions; // // // HELPER // ************************************************************************************************************ // // public static ApplicationComponent getApplicationComponent() { // return applicationComponent; // } // // public static SnackbarActions snackbar(final Activity activity) { // return ((PostsApplication) activity.getApplication()).snackbar(); // } // // // APPLICATION // ******************************************************************************************************* // // @Override // public void onCreate() { // super.onCreate(); // initDagger(); // initRealm(); // initTimber(); // Timber.i("Posts application created!"); // } // // private void initDagger() { // applicationComponent = DaggerApplicationComponent.builder() // .appModule(new AppModule(this)) // .netModule(new NetModule(BASE_URL)) // .dataModule(new DataModule()) // .serviceModule(new ServiceModule()) // .activityModule(new ActivityModule()).build(); // applicationComponent.inject(this); // } // // private void initTimber() { // Timber.plant(new Timber.DebugTree()); // } // // protected void initRealm() { // Realm.init(this); // } // // // GET // *************************************************************************************************************** // // public Realm getDefaultRealmInstance() { // return Realm.getDefaultInstance(); // } // // // ACTIONS // *********************************************************************************************************** // // public SnackbarActions snackbar() { // return appSnackbarActions; // } // // } // // Path: app/src/main/java/io/petros/posts/app/actions/SnackbarActions.java // public interface SnackbarActions { // // void setCoordinatorLayout(final CoordinatorLayout coordinatorLayout); // // void info(final int textResId); // // void warn(final int textResId); // // void error(final int textResId); // // } // // Path: app/src/main/java/io/petros/posts/model/Post.java // public class Post { // // public static final String USER_ID = "userId"; // public static final String ID = "id"; // public static final String TITLE = "title"; // public static final String BODY = "body"; // // @SerializedName(USER_ID) // @Expose // private Integer userId; // // @SerializedName(ID) // @Expose // private Integer id; // // @SerializedName(TITLE) // @Expose // private String title; // // @SerializedName(BODY) // @Expose // private String body; // // public Integer getUserId() { // return userId; // } // // public void setUserId(final Integer userId) { // this.userId = userId; // } // // public Integer getId() { // return id; // } // // public void setId(final Integer id) { // this.id = id; // } // // public String getTitle() { // return title; // } // // public void setTitle(final String title) { // this.title = title; // } // // public String getBody() { // return body; // } // // public void setBody(final String body) { // this.body = body; // } // // } // Path: app/src/test/java/io/petros/posts/RobolectricGeneralTestHelper.java import android.content.Context; import android.net.ConnectivityManager; import android.os.Bundle; import org.mockito.Mock; import org.robolectric.RuntimeEnvironment; import org.robolectric.shadows.ShadowApplication; import io.petros.posts.app.PostsApplication; import io.petros.posts.app.actions.SnackbarActions; import io.petros.posts.model.Post; import static org.mockito.Mockito.when; package io.petros.posts; public class RobolectricGeneralTestHelper extends GeneralTestHelper { // Application specific fields. protected final Context context = getTestContext();
protected final PostsApplication application = getTestApplication();
ParaskP7/sample-code-posts
app/src/test/java/io/petros/posts/RobolectricGeneralTestHelper.java
// Path: app/src/main/java/io/petros/posts/app/PostsApplication.java // @SuppressWarnings("checkstyle:overloadmethodsdeclarationorder") // public class PostsApplication extends Application { // // private static ApplicationComponent applicationComponent; // // static { // AppCompatDelegate.setCompatVectorFromResourcesEnabled(true); // NOTE: This enables the "proxy" trick on the vector images. // } // // @Inject AppSnackbarActions appSnackbarActions; // // // HELPER // ************************************************************************************************************ // // public static ApplicationComponent getApplicationComponent() { // return applicationComponent; // } // // public static SnackbarActions snackbar(final Activity activity) { // return ((PostsApplication) activity.getApplication()).snackbar(); // } // // // APPLICATION // ******************************************************************************************************* // // @Override // public void onCreate() { // super.onCreate(); // initDagger(); // initRealm(); // initTimber(); // Timber.i("Posts application created!"); // } // // private void initDagger() { // applicationComponent = DaggerApplicationComponent.builder() // .appModule(new AppModule(this)) // .netModule(new NetModule(BASE_URL)) // .dataModule(new DataModule()) // .serviceModule(new ServiceModule()) // .activityModule(new ActivityModule()).build(); // applicationComponent.inject(this); // } // // private void initTimber() { // Timber.plant(new Timber.DebugTree()); // } // // protected void initRealm() { // Realm.init(this); // } // // // GET // *************************************************************************************************************** // // public Realm getDefaultRealmInstance() { // return Realm.getDefaultInstance(); // } // // // ACTIONS // *********************************************************************************************************** // // public SnackbarActions snackbar() { // return appSnackbarActions; // } // // } // // Path: app/src/main/java/io/petros/posts/app/actions/SnackbarActions.java // public interface SnackbarActions { // // void setCoordinatorLayout(final CoordinatorLayout coordinatorLayout); // // void info(final int textResId); // // void warn(final int textResId); // // void error(final int textResId); // // } // // Path: app/src/main/java/io/petros/posts/model/Post.java // public class Post { // // public static final String USER_ID = "userId"; // public static final String ID = "id"; // public static final String TITLE = "title"; // public static final String BODY = "body"; // // @SerializedName(USER_ID) // @Expose // private Integer userId; // // @SerializedName(ID) // @Expose // private Integer id; // // @SerializedName(TITLE) // @Expose // private String title; // // @SerializedName(BODY) // @Expose // private String body; // // public Integer getUserId() { // return userId; // } // // public void setUserId(final Integer userId) { // this.userId = userId; // } // // public Integer getId() { // return id; // } // // public void setId(final Integer id) { // this.id = id; // } // // public String getTitle() { // return title; // } // // public void setTitle(final String title) { // this.title = title; // } // // public String getBody() { // return body; // } // // public void setBody(final String body) { // this.body = body; // } // // }
import android.content.Context; import android.net.ConnectivityManager; import android.os.Bundle; import org.mockito.Mock; import org.robolectric.RuntimeEnvironment; import org.robolectric.shadows.ShadowApplication; import io.petros.posts.app.PostsApplication; import io.petros.posts.app.actions.SnackbarActions; import io.petros.posts.model.Post; import static org.mockito.Mockito.when;
package io.petros.posts; public class RobolectricGeneralTestHelper extends GeneralTestHelper { // Application specific fields. protected final Context context = getTestContext(); protected final PostsApplication application = getTestApplication(); // System specific fields. @Mock protected ConnectivityManager connectivityManagerMock; // Activity specific fields. @Mock protected PostsApplication applicationMock;
// Path: app/src/main/java/io/petros/posts/app/PostsApplication.java // @SuppressWarnings("checkstyle:overloadmethodsdeclarationorder") // public class PostsApplication extends Application { // // private static ApplicationComponent applicationComponent; // // static { // AppCompatDelegate.setCompatVectorFromResourcesEnabled(true); // NOTE: This enables the "proxy" trick on the vector images. // } // // @Inject AppSnackbarActions appSnackbarActions; // // // HELPER // ************************************************************************************************************ // // public static ApplicationComponent getApplicationComponent() { // return applicationComponent; // } // // public static SnackbarActions snackbar(final Activity activity) { // return ((PostsApplication) activity.getApplication()).snackbar(); // } // // // APPLICATION // ******************************************************************************************************* // // @Override // public void onCreate() { // super.onCreate(); // initDagger(); // initRealm(); // initTimber(); // Timber.i("Posts application created!"); // } // // private void initDagger() { // applicationComponent = DaggerApplicationComponent.builder() // .appModule(new AppModule(this)) // .netModule(new NetModule(BASE_URL)) // .dataModule(new DataModule()) // .serviceModule(new ServiceModule()) // .activityModule(new ActivityModule()).build(); // applicationComponent.inject(this); // } // // private void initTimber() { // Timber.plant(new Timber.DebugTree()); // } // // protected void initRealm() { // Realm.init(this); // } // // // GET // *************************************************************************************************************** // // public Realm getDefaultRealmInstance() { // return Realm.getDefaultInstance(); // } // // // ACTIONS // *********************************************************************************************************** // // public SnackbarActions snackbar() { // return appSnackbarActions; // } // // } // // Path: app/src/main/java/io/petros/posts/app/actions/SnackbarActions.java // public interface SnackbarActions { // // void setCoordinatorLayout(final CoordinatorLayout coordinatorLayout); // // void info(final int textResId); // // void warn(final int textResId); // // void error(final int textResId); // // } // // Path: app/src/main/java/io/petros/posts/model/Post.java // public class Post { // // public static final String USER_ID = "userId"; // public static final String ID = "id"; // public static final String TITLE = "title"; // public static final String BODY = "body"; // // @SerializedName(USER_ID) // @Expose // private Integer userId; // // @SerializedName(ID) // @Expose // private Integer id; // // @SerializedName(TITLE) // @Expose // private String title; // // @SerializedName(BODY) // @Expose // private String body; // // public Integer getUserId() { // return userId; // } // // public void setUserId(final Integer userId) { // this.userId = userId; // } // // public Integer getId() { // return id; // } // // public void setId(final Integer id) { // this.id = id; // } // // public String getTitle() { // return title; // } // // public void setTitle(final String title) { // this.title = title; // } // // public String getBody() { // return body; // } // // public void setBody(final String body) { // this.body = body; // } // // } // Path: app/src/test/java/io/petros/posts/RobolectricGeneralTestHelper.java import android.content.Context; import android.net.ConnectivityManager; import android.os.Bundle; import org.mockito.Mock; import org.robolectric.RuntimeEnvironment; import org.robolectric.shadows.ShadowApplication; import io.petros.posts.app.PostsApplication; import io.petros.posts.app.actions.SnackbarActions; import io.petros.posts.model.Post; import static org.mockito.Mockito.when; package io.petros.posts; public class RobolectricGeneralTestHelper extends GeneralTestHelper { // Application specific fields. protected final Context context = getTestContext(); protected final PostsApplication application = getTestApplication(); // System specific fields. @Mock protected ConnectivityManager connectivityManagerMock; // Activity specific fields. @Mock protected PostsApplication applicationMock;
@Mock protected SnackbarActions snackbarActionsMock;
ParaskP7/sample-code-posts
app/src/test/java/io/petros/posts/RobolectricGeneralTestHelper.java
// Path: app/src/main/java/io/petros/posts/app/PostsApplication.java // @SuppressWarnings("checkstyle:overloadmethodsdeclarationorder") // public class PostsApplication extends Application { // // private static ApplicationComponent applicationComponent; // // static { // AppCompatDelegate.setCompatVectorFromResourcesEnabled(true); // NOTE: This enables the "proxy" trick on the vector images. // } // // @Inject AppSnackbarActions appSnackbarActions; // // // HELPER // ************************************************************************************************************ // // public static ApplicationComponent getApplicationComponent() { // return applicationComponent; // } // // public static SnackbarActions snackbar(final Activity activity) { // return ((PostsApplication) activity.getApplication()).snackbar(); // } // // // APPLICATION // ******************************************************************************************************* // // @Override // public void onCreate() { // super.onCreate(); // initDagger(); // initRealm(); // initTimber(); // Timber.i("Posts application created!"); // } // // private void initDagger() { // applicationComponent = DaggerApplicationComponent.builder() // .appModule(new AppModule(this)) // .netModule(new NetModule(BASE_URL)) // .dataModule(new DataModule()) // .serviceModule(new ServiceModule()) // .activityModule(new ActivityModule()).build(); // applicationComponent.inject(this); // } // // private void initTimber() { // Timber.plant(new Timber.DebugTree()); // } // // protected void initRealm() { // Realm.init(this); // } // // // GET // *************************************************************************************************************** // // public Realm getDefaultRealmInstance() { // return Realm.getDefaultInstance(); // } // // // ACTIONS // *********************************************************************************************************** // // public SnackbarActions snackbar() { // return appSnackbarActions; // } // // } // // Path: app/src/main/java/io/petros/posts/app/actions/SnackbarActions.java // public interface SnackbarActions { // // void setCoordinatorLayout(final CoordinatorLayout coordinatorLayout); // // void info(final int textResId); // // void warn(final int textResId); // // void error(final int textResId); // // } // // Path: app/src/main/java/io/petros/posts/model/Post.java // public class Post { // // public static final String USER_ID = "userId"; // public static final String ID = "id"; // public static final String TITLE = "title"; // public static final String BODY = "body"; // // @SerializedName(USER_ID) // @Expose // private Integer userId; // // @SerializedName(ID) // @Expose // private Integer id; // // @SerializedName(TITLE) // @Expose // private String title; // // @SerializedName(BODY) // @Expose // private String body; // // public Integer getUserId() { // return userId; // } // // public void setUserId(final Integer userId) { // this.userId = userId; // } // // public Integer getId() { // return id; // } // // public void setId(final Integer id) { // this.id = id; // } // // public String getTitle() { // return title; // } // // public void setTitle(final String title) { // this.title = title; // } // // public String getBody() { // return body; // } // // public void setBody(final String body) { // this.body = body; // } // // }
import android.content.Context; import android.net.ConnectivityManager; import android.os.Bundle; import org.mockito.Mock; import org.robolectric.RuntimeEnvironment; import org.robolectric.shadows.ShadowApplication; import io.petros.posts.app.PostsApplication; import io.petros.posts.app.actions.SnackbarActions; import io.petros.posts.model.Post; import static org.mockito.Mockito.when;
package io.petros.posts; public class RobolectricGeneralTestHelper extends GeneralTestHelper { // Application specific fields. protected final Context context = getTestContext(); protected final PostsApplication application = getTestApplication(); // System specific fields. @Mock protected ConnectivityManager connectivityManagerMock; // Activity specific fields. @Mock protected PostsApplication applicationMock; @Mock protected SnackbarActions snackbarActionsMock; // ROBOLECTRIC // ******************************************************************************************************* private Context getTestContext() { return getShadowApplication().getApplicationContext(); } private ShadowApplication getShadowApplication() { return ShadowApplication.getInstance(); } private PostsApplication getTestApplication() { return (PostsApplication) RuntimeEnvironment.application; } // MOCKS // ************************************************************************************************************* protected void setUpMocks() { super.setUpMocks(); setUpApplicationMocks(); } private void setUpApplicationMocks() { when(applicationMock.getSystemService(Context.CONNECTIVITY_SERVICE)).thenReturn(connectivityManagerMock); when(applicationMock.snackbar()).thenReturn(snackbarActionsMock); } // POST // **************************************************************************************************************
// Path: app/src/main/java/io/petros/posts/app/PostsApplication.java // @SuppressWarnings("checkstyle:overloadmethodsdeclarationorder") // public class PostsApplication extends Application { // // private static ApplicationComponent applicationComponent; // // static { // AppCompatDelegate.setCompatVectorFromResourcesEnabled(true); // NOTE: This enables the "proxy" trick on the vector images. // } // // @Inject AppSnackbarActions appSnackbarActions; // // // HELPER // ************************************************************************************************************ // // public static ApplicationComponent getApplicationComponent() { // return applicationComponent; // } // // public static SnackbarActions snackbar(final Activity activity) { // return ((PostsApplication) activity.getApplication()).snackbar(); // } // // // APPLICATION // ******************************************************************************************************* // // @Override // public void onCreate() { // super.onCreate(); // initDagger(); // initRealm(); // initTimber(); // Timber.i("Posts application created!"); // } // // private void initDagger() { // applicationComponent = DaggerApplicationComponent.builder() // .appModule(new AppModule(this)) // .netModule(new NetModule(BASE_URL)) // .dataModule(new DataModule()) // .serviceModule(new ServiceModule()) // .activityModule(new ActivityModule()).build(); // applicationComponent.inject(this); // } // // private void initTimber() { // Timber.plant(new Timber.DebugTree()); // } // // protected void initRealm() { // Realm.init(this); // } // // // GET // *************************************************************************************************************** // // public Realm getDefaultRealmInstance() { // return Realm.getDefaultInstance(); // } // // // ACTIONS // *********************************************************************************************************** // // public SnackbarActions snackbar() { // return appSnackbarActions; // } // // } // // Path: app/src/main/java/io/petros/posts/app/actions/SnackbarActions.java // public interface SnackbarActions { // // void setCoordinatorLayout(final CoordinatorLayout coordinatorLayout); // // void info(final int textResId); // // void warn(final int textResId); // // void error(final int textResId); // // } // // Path: app/src/main/java/io/petros/posts/model/Post.java // public class Post { // // public static final String USER_ID = "userId"; // public static final String ID = "id"; // public static final String TITLE = "title"; // public static final String BODY = "body"; // // @SerializedName(USER_ID) // @Expose // private Integer userId; // // @SerializedName(ID) // @Expose // private Integer id; // // @SerializedName(TITLE) // @Expose // private String title; // // @SerializedName(BODY) // @Expose // private String body; // // public Integer getUserId() { // return userId; // } // // public void setUserId(final Integer userId) { // this.userId = userId; // } // // public Integer getId() { // return id; // } // // public void setId(final Integer id) { // this.id = id; // } // // public String getTitle() { // return title; // } // // public void setTitle(final String title) { // this.title = title; // } // // public String getBody() { // return body; // } // // public void setBody(final String body) { // this.body = body; // } // // } // Path: app/src/test/java/io/petros/posts/RobolectricGeneralTestHelper.java import android.content.Context; import android.net.ConnectivityManager; import android.os.Bundle; import org.mockito.Mock; import org.robolectric.RuntimeEnvironment; import org.robolectric.shadows.ShadowApplication; import io.petros.posts.app.PostsApplication; import io.petros.posts.app.actions.SnackbarActions; import io.petros.posts.model.Post; import static org.mockito.Mockito.when; package io.petros.posts; public class RobolectricGeneralTestHelper extends GeneralTestHelper { // Application specific fields. protected final Context context = getTestContext(); protected final PostsApplication application = getTestApplication(); // System specific fields. @Mock protected ConnectivityManager connectivityManagerMock; // Activity specific fields. @Mock protected PostsApplication applicationMock; @Mock protected SnackbarActions snackbarActionsMock; // ROBOLECTRIC // ******************************************************************************************************* private Context getTestContext() { return getShadowApplication().getApplicationContext(); } private ShadowApplication getShadowApplication() { return ShadowApplication.getInstance(); } private PostsApplication getTestApplication() { return (PostsApplication) RuntimeEnvironment.application; } // MOCKS // ************************************************************************************************************* protected void setUpMocks() { super.setUpMocks(); setUpApplicationMocks(); } private void setUpApplicationMocks() { when(applicationMock.getSystemService(Context.CONNECTIVITY_SERVICE)).thenReturn(connectivityManagerMock); when(applicationMock.snackbar()).thenReturn(snackbarActionsMock); } // POST // **************************************************************************************************************
protected Bundle getExtras(final Post post) {
ParaskP7/sample-code-posts
app/src/main/java/io/petros/posts/service/detector/InternetAvailabilityDetector.java
// Path: app/src/main/java/io/petros/posts/app/PostsApplication.java // @SuppressWarnings("checkstyle:overloadmethodsdeclarationorder") // public class PostsApplication extends Application { // // private static ApplicationComponent applicationComponent; // // static { // AppCompatDelegate.setCompatVectorFromResourcesEnabled(true); // NOTE: This enables the "proxy" trick on the vector images. // } // // @Inject AppSnackbarActions appSnackbarActions; // // // HELPER // ************************************************************************************************************ // // public static ApplicationComponent getApplicationComponent() { // return applicationComponent; // } // // public static SnackbarActions snackbar(final Activity activity) { // return ((PostsApplication) activity.getApplication()).snackbar(); // } // // // APPLICATION // ******************************************************************************************************* // // @Override // public void onCreate() { // super.onCreate(); // initDagger(); // initRealm(); // initTimber(); // Timber.i("Posts application created!"); // } // // private void initDagger() { // applicationComponent = DaggerApplicationComponent.builder() // .appModule(new AppModule(this)) // .netModule(new NetModule(BASE_URL)) // .dataModule(new DataModule()) // .serviceModule(new ServiceModule()) // .activityModule(new ActivityModule()).build(); // applicationComponent.inject(this); // } // // private void initTimber() { // Timber.plant(new Timber.DebugTree()); // } // // protected void initRealm() { // Realm.init(this); // } // // // GET // *************************************************************************************************************** // // public Realm getDefaultRealmInstance() { // return Realm.getDefaultInstance(); // } // // // ACTIONS // *********************************************************************************************************** // // public SnackbarActions snackbar() { // return appSnackbarActions; // } // // }
import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import javax.annotation.Nullable; import io.petros.posts.app.PostsApplication; import timber.log.Timber;
package io.petros.posts.service.detector; public class InternetAvailabilityDetector implements AvailabilityDetector { private final ConnectivityManager connectivityManager;
// Path: app/src/main/java/io/petros/posts/app/PostsApplication.java // @SuppressWarnings("checkstyle:overloadmethodsdeclarationorder") // public class PostsApplication extends Application { // // private static ApplicationComponent applicationComponent; // // static { // AppCompatDelegate.setCompatVectorFromResourcesEnabled(true); // NOTE: This enables the "proxy" trick on the vector images. // } // // @Inject AppSnackbarActions appSnackbarActions; // // // HELPER // ************************************************************************************************************ // // public static ApplicationComponent getApplicationComponent() { // return applicationComponent; // } // // public static SnackbarActions snackbar(final Activity activity) { // return ((PostsApplication) activity.getApplication()).snackbar(); // } // // // APPLICATION // ******************************************************************************************************* // // @Override // public void onCreate() { // super.onCreate(); // initDagger(); // initRealm(); // initTimber(); // Timber.i("Posts application created!"); // } // // private void initDagger() { // applicationComponent = DaggerApplicationComponent.builder() // .appModule(new AppModule(this)) // .netModule(new NetModule(BASE_URL)) // .dataModule(new DataModule()) // .serviceModule(new ServiceModule()) // .activityModule(new ActivityModule()).build(); // applicationComponent.inject(this); // } // // private void initTimber() { // Timber.plant(new Timber.DebugTree()); // } // // protected void initRealm() { // Realm.init(this); // } // // // GET // *************************************************************************************************************** // // public Realm getDefaultRealmInstance() { // return Realm.getDefaultInstance(); // } // // // ACTIONS // *********************************************************************************************************** // // public SnackbarActions snackbar() { // return appSnackbarActions; // } // // } // Path: app/src/main/java/io/petros/posts/service/detector/InternetAvailabilityDetector.java import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import javax.annotation.Nullable; import io.petros.posts.app.PostsApplication; import timber.log.Timber; package io.petros.posts.service.detector; public class InternetAvailabilityDetector implements AvailabilityDetector { private final ConnectivityManager connectivityManager;
public InternetAvailabilityDetector(final PostsApplication application) {
ParaskP7/sample-code-posts
app/src/main/java/io/petros/posts/datastore/GetActions.java
// Path: app/src/main/java/io/petros/posts/model/User.java // public class User extends RealmObject { // // public static final String ID = "id"; // public static final String NAME = "name"; // public static final String USERNAME = "username"; // public static final String EMAIL = "email"; // // @SerializedName(ID) // @Expose // @PrimaryKey // private Integer id; // // @SerializedName(NAME) // @Expose // private String name; // // @SerializedName(USERNAME) // @Expose // private String username; // // @SerializedName(EMAIL) // @Expose // private String email; // // public Integer getId() { // return id; // } // // public void setId(final Integer id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(final String name) { // this.name = name; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getEmail() { // return email; // } // // public void setEmail(final String email) { // this.email = email; // } // // }
import javax.annotation.Nullable; import io.petros.posts.model.User;
package io.petros.posts.datastore; public interface GetActions { @Nullable
// Path: app/src/main/java/io/petros/posts/model/User.java // public class User extends RealmObject { // // public static final String ID = "id"; // public static final String NAME = "name"; // public static final String USERNAME = "username"; // public static final String EMAIL = "email"; // // @SerializedName(ID) // @Expose // @PrimaryKey // private Integer id; // // @SerializedName(NAME) // @Expose // private String name; // // @SerializedName(USERNAME) // @Expose // private String username; // // @SerializedName(EMAIL) // @Expose // private String email; // // public Integer getId() { // return id; // } // // public void setId(final Integer id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(final String name) { // this.name = name; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getEmail() { // return email; // } // // public void setEmail(final String email) { // this.email = email; // } // // } // Path: app/src/main/java/io/petros/posts/datastore/GetActions.java import javax.annotation.Nullable; import io.petros.posts.model.User; package io.petros.posts.datastore; public interface GetActions { @Nullable
User user(final Integer userId);
ParaskP7/sample-code-posts
app/src/main/java/io/petros/posts/datastore/DatastoreGetActions.java
// Path: app/src/main/java/io/petros/posts/model/User.java // public class User extends RealmObject { // // public static final String ID = "id"; // public static final String NAME = "name"; // public static final String USERNAME = "username"; // public static final String EMAIL = "email"; // // @SerializedName(ID) // @Expose // @PrimaryKey // private Integer id; // // @SerializedName(NAME) // @Expose // private String name; // // @SerializedName(USERNAME) // @Expose // private String username; // // @SerializedName(EMAIL) // @Expose // private String email; // // public Integer getId() { // return id; // } // // public void setId(final Integer id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(final String name) { // this.name = name; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getEmail() { // return email; // } // // public void setEmail(final String email) { // this.email = email; // } // // }
import javax.annotation.Nullable; import io.petros.posts.model.User; import io.realm.Realm;
package io.petros.posts.datastore; public class DatastoreGetActions implements GetActions { private final Realm realm; public DatastoreGetActions(final Realm realm) { this.realm = realm; } @Nullable @Override
// Path: app/src/main/java/io/petros/posts/model/User.java // public class User extends RealmObject { // // public static final String ID = "id"; // public static final String NAME = "name"; // public static final String USERNAME = "username"; // public static final String EMAIL = "email"; // // @SerializedName(ID) // @Expose // @PrimaryKey // private Integer id; // // @SerializedName(NAME) // @Expose // private String name; // // @SerializedName(USERNAME) // @Expose // private String username; // // @SerializedName(EMAIL) // @Expose // private String email; // // public Integer getId() { // return id; // } // // public void setId(final Integer id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(final String name) { // this.name = name; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getEmail() { // return email; // } // // public void setEmail(final String email) { // this.email = email; // } // // } // Path: app/src/main/java/io/petros/posts/datastore/DatastoreGetActions.java import javax.annotation.Nullable; import io.petros.posts.model.User; import io.realm.Realm; package io.petros.posts.datastore; public class DatastoreGetActions implements GetActions { private final Realm realm; public DatastoreGetActions(final Realm realm) { this.realm = realm; } @Nullable @Override
public User user(final Integer userId) {
ParaskP7/sample-code-posts
app/src/main/java/io/petros/posts/datastore/DatastoreAddActions.java
// Path: app/src/main/java/io/petros/posts/model/User.java // public class User extends RealmObject { // // public static final String ID = "id"; // public static final String NAME = "name"; // public static final String USERNAME = "username"; // public static final String EMAIL = "email"; // // @SerializedName(ID) // @Expose // @PrimaryKey // private Integer id; // // @SerializedName(NAME) // @Expose // private String name; // // @SerializedName(USERNAME) // @Expose // private String username; // // @SerializedName(EMAIL) // @Expose // private String email; // // public Integer getId() { // return id; // } // // public void setId(final Integer id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(final String name) { // this.name = name; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getEmail() { // return email; // } // // public void setEmail(final String email) { // this.email = email; // } // // }
import io.petros.posts.model.User; import io.realm.Realm;
package io.petros.posts.datastore; public class DatastoreAddActions implements AddActions { private final Realm realm; public DatastoreAddActions(final Realm realm) { this.realm = realm; } @Override
// Path: app/src/main/java/io/petros/posts/model/User.java // public class User extends RealmObject { // // public static final String ID = "id"; // public static final String NAME = "name"; // public static final String USERNAME = "username"; // public static final String EMAIL = "email"; // // @SerializedName(ID) // @Expose // @PrimaryKey // private Integer id; // // @SerializedName(NAME) // @Expose // private String name; // // @SerializedName(USERNAME) // @Expose // private String username; // // @SerializedName(EMAIL) // @Expose // private String email; // // public Integer getId() { // return id; // } // // public void setId(final Integer id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(final String name) { // this.name = name; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getEmail() { // return email; // } // // public void setEmail(final String email) { // this.email = email; // } // // } // Path: app/src/main/java/io/petros/posts/datastore/DatastoreAddActions.java import io.petros.posts.model.User; import io.realm.Realm; package io.petros.posts.datastore; public class DatastoreAddActions implements AddActions { private final Realm realm; public DatastoreAddActions(final Realm realm) { this.realm = realm; } @Override
public boolean user(final User user) {
ParaskP7/sample-code-posts
app/src/androidTest/java/io/petros/posts/GeneralEspressoTestHelper.java
// Path: app/src/main/java/io/petros/posts/model/Post.java // public class Post { // // public static final String USER_ID = "userId"; // public static final String ID = "id"; // public static final String TITLE = "title"; // public static final String BODY = "body"; // // @SerializedName(USER_ID) // @Expose // private Integer userId; // // @SerializedName(ID) // @Expose // private Integer id; // // @SerializedName(TITLE) // @Expose // private String title; // // @SerializedName(BODY) // @Expose // private String body; // // public Integer getUserId() { // return userId; // } // // public void setUserId(final Integer userId) { // this.userId = userId; // } // // public Integer getId() { // return id; // } // // public void setId(final Integer id) { // this.id = id; // } // // public String getTitle() { // return title; // } // // public void setTitle(final String title) { // this.title = title; // } // // public String getBody() { // return body; // } // // public void setBody(final String body) { // this.body = body; // } // // } // // Path: app/src/main/java/io/petros/posts/model/User.java // public class User extends RealmObject { // // public static final String ID = "id"; // public static final String NAME = "name"; // public static final String USERNAME = "username"; // public static final String EMAIL = "email"; // // @SerializedName(ID) // @Expose // @PrimaryKey // private Integer id; // // @SerializedName(NAME) // @Expose // private String name; // // @SerializedName(USERNAME) // @Expose // private String username; // // @SerializedName(EMAIL) // @Expose // private String email; // // public Integer getId() { // return id; // } // // public void setId(final Integer id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(final String name) { // this.name = name; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getEmail() { // return email; // } // // public void setEmail(final String email) { // this.email = email; // } // // }
import android.content.Intent; import android.os.Bundle; import android.support.test.rule.ActivityTestRule; import io.petros.posts.model.Post; import io.petros.posts.model.User;
package io.petros.posts; public class GeneralEspressoTestHelper { protected static final String ANDROID_R_ID_HOME_CONTENT_DESCRIPTION = "Navigate up"; // Instead of: withId(android.R.id.home) // Model specific fields.
// Path: app/src/main/java/io/petros/posts/model/Post.java // public class Post { // // public static final String USER_ID = "userId"; // public static final String ID = "id"; // public static final String TITLE = "title"; // public static final String BODY = "body"; // // @SerializedName(USER_ID) // @Expose // private Integer userId; // // @SerializedName(ID) // @Expose // private Integer id; // // @SerializedName(TITLE) // @Expose // private String title; // // @SerializedName(BODY) // @Expose // private String body; // // public Integer getUserId() { // return userId; // } // // public void setUserId(final Integer userId) { // this.userId = userId; // } // // public Integer getId() { // return id; // } // // public void setId(final Integer id) { // this.id = id; // } // // public String getTitle() { // return title; // } // // public void setTitle(final String title) { // this.title = title; // } // // public String getBody() { // return body; // } // // public void setBody(final String body) { // this.body = body; // } // // } // // Path: app/src/main/java/io/petros/posts/model/User.java // public class User extends RealmObject { // // public static final String ID = "id"; // public static final String NAME = "name"; // public static final String USERNAME = "username"; // public static final String EMAIL = "email"; // // @SerializedName(ID) // @Expose // @PrimaryKey // private Integer id; // // @SerializedName(NAME) // @Expose // private String name; // // @SerializedName(USERNAME) // @Expose // private String username; // // @SerializedName(EMAIL) // @Expose // private String email; // // public Integer getId() { // return id; // } // // public void setId(final Integer id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(final String name) { // this.name = name; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getEmail() { // return email; // } // // public void setEmail(final String email) { // this.email = email; // } // // } // Path: app/src/androidTest/java/io/petros/posts/GeneralEspressoTestHelper.java import android.content.Intent; import android.os.Bundle; import android.support.test.rule.ActivityTestRule; import io.petros.posts.model.Post; import io.petros.posts.model.User; package io.petros.posts; public class GeneralEspressoTestHelper { protected static final String ANDROID_R_ID_HOME_CONTENT_DESCRIPTION = "Navigate up"; // Instead of: withId(android.R.id.home) // Model specific fields.
protected User user = getTestUser();
ParaskP7/sample-code-posts
app/src/androidTest/java/io/petros/posts/GeneralEspressoTestHelper.java
// Path: app/src/main/java/io/petros/posts/model/Post.java // public class Post { // // public static final String USER_ID = "userId"; // public static final String ID = "id"; // public static final String TITLE = "title"; // public static final String BODY = "body"; // // @SerializedName(USER_ID) // @Expose // private Integer userId; // // @SerializedName(ID) // @Expose // private Integer id; // // @SerializedName(TITLE) // @Expose // private String title; // // @SerializedName(BODY) // @Expose // private String body; // // public Integer getUserId() { // return userId; // } // // public void setUserId(final Integer userId) { // this.userId = userId; // } // // public Integer getId() { // return id; // } // // public void setId(final Integer id) { // this.id = id; // } // // public String getTitle() { // return title; // } // // public void setTitle(final String title) { // this.title = title; // } // // public String getBody() { // return body; // } // // public void setBody(final String body) { // this.body = body; // } // // } // // Path: app/src/main/java/io/petros/posts/model/User.java // public class User extends RealmObject { // // public static final String ID = "id"; // public static final String NAME = "name"; // public static final String USERNAME = "username"; // public static final String EMAIL = "email"; // // @SerializedName(ID) // @Expose // @PrimaryKey // private Integer id; // // @SerializedName(NAME) // @Expose // private String name; // // @SerializedName(USERNAME) // @Expose // private String username; // // @SerializedName(EMAIL) // @Expose // private String email; // // public Integer getId() { // return id; // } // // public void setId(final Integer id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(final String name) { // this.name = name; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getEmail() { // return email; // } // // public void setEmail(final String email) { // this.email = email; // } // // }
import android.content.Intent; import android.os.Bundle; import android.support.test.rule.ActivityTestRule; import io.petros.posts.model.Post; import io.petros.posts.model.User;
package io.petros.posts; public class GeneralEspressoTestHelper { protected static final String ANDROID_R_ID_HOME_CONTENT_DESCRIPTION = "Navigate up"; // Instead of: withId(android.R.id.home) // Model specific fields. protected User user = getTestUser();
// Path: app/src/main/java/io/petros/posts/model/Post.java // public class Post { // // public static final String USER_ID = "userId"; // public static final String ID = "id"; // public static final String TITLE = "title"; // public static final String BODY = "body"; // // @SerializedName(USER_ID) // @Expose // private Integer userId; // // @SerializedName(ID) // @Expose // private Integer id; // // @SerializedName(TITLE) // @Expose // private String title; // // @SerializedName(BODY) // @Expose // private String body; // // public Integer getUserId() { // return userId; // } // // public void setUserId(final Integer userId) { // this.userId = userId; // } // // public Integer getId() { // return id; // } // // public void setId(final Integer id) { // this.id = id; // } // // public String getTitle() { // return title; // } // // public void setTitle(final String title) { // this.title = title; // } // // public String getBody() { // return body; // } // // public void setBody(final String body) { // this.body = body; // } // // } // // Path: app/src/main/java/io/petros/posts/model/User.java // public class User extends RealmObject { // // public static final String ID = "id"; // public static final String NAME = "name"; // public static final String USERNAME = "username"; // public static final String EMAIL = "email"; // // @SerializedName(ID) // @Expose // @PrimaryKey // private Integer id; // // @SerializedName(NAME) // @Expose // private String name; // // @SerializedName(USERNAME) // @Expose // private String username; // // @SerializedName(EMAIL) // @Expose // private String email; // // public Integer getId() { // return id; // } // // public void setId(final Integer id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(final String name) { // this.name = name; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getEmail() { // return email; // } // // public void setEmail(final String email) { // this.email = email; // } // // } // Path: app/src/androidTest/java/io/petros/posts/GeneralEspressoTestHelper.java import android.content.Intent; import android.os.Bundle; import android.support.test.rule.ActivityTestRule; import io.petros.posts.model.Post; import io.petros.posts.model.User; package io.petros.posts; public class GeneralEspressoTestHelper { protected static final String ANDROID_R_ID_HOME_CONTENT_DESCRIPTION = "Navigate up"; // Instead of: withId(android.R.id.home) // Model specific fields. protected User user = getTestUser();
protected Post post = getTestPost();
ParaskP7/sample-code-posts
app/src/test/java/io/petros/posts/datastore/DatastoreAddActionsTest.java
// Path: app/src/test/java/io/petros/posts/PreconfiguredRobolectricTestRunner.java // public class PreconfiguredRobolectricTestRunner extends RobolectricTestRunner { // // private static final int SDK_API_LEVEL_TO_EMULATE = 25; // // /** // * Creates a runner to run {@code testClass}. Looks in your working directory for your AndroidManifest.xml file and res directory by // * default. Use the {@link Config} annotation to configure. // * // * @param testClass The test class to be run. // * @throws InitializationError If junit says so. // */ // public PreconfiguredRobolectricTestRunner(final Class<?> testClass) throws InitializationError { // super(testClass); // } // // @Override // protected Config buildGlobalConfig() { // return new Config.Builder() // .setSdk(SDK_API_LEVEL_TO_EMULATE) // .setManifest(Config.NONE) // .setApplication(TestPostsApplication.class) // .build(); // } // // } // // Path: app/src/test/java/io/petros/posts/RobolectricGeneralTestHelper.java // public class RobolectricGeneralTestHelper extends GeneralTestHelper { // // // Application specific fields. // protected final Context context = getTestContext(); // protected final PostsApplication application = getTestApplication(); // // // System specific fields. // @Mock protected ConnectivityManager connectivityManagerMock; // // // Activity specific fields. // @Mock protected PostsApplication applicationMock; // @Mock protected SnackbarActions snackbarActionsMock; // // // ROBOLECTRIC // ******************************************************************************************************* // // private Context getTestContext() { // return getShadowApplication().getApplicationContext(); // } // // private ShadowApplication getShadowApplication() { // return ShadowApplication.getInstance(); // } // // private PostsApplication getTestApplication() { // return (PostsApplication) RuntimeEnvironment.application; // } // // // MOCKS // ************************************************************************************************************* // // protected void setUpMocks() { // super.setUpMocks(); // setUpApplicationMocks(); // } // // private void setUpApplicationMocks() { // when(applicationMock.getSystemService(Context.CONNECTIVITY_SERVICE)).thenReturn(connectivityManagerMock); // when(applicationMock.snackbar()).thenReturn(snackbarActionsMock); // } // // // POST // ************************************************************************************************************** // // protected Bundle getExtras(final Post post) { // final Bundle extras = new Bundle(); // extras.putInt(Post.USER_ID, post.getUserId()); // extras.putInt(Post.ID, post.getId()); // extras.putString(Post.TITLE, post.getTitle()); // extras.putString(Post.BODY, post.getBody()); // return extras; // } // // } // // Path: app/src/main/java/io/petros/posts/model/User.java // public class User extends RealmObject { // // public static final String ID = "id"; // public static final String NAME = "name"; // public static final String USERNAME = "username"; // public static final String EMAIL = "email"; // // @SerializedName(ID) // @Expose // @PrimaryKey // private Integer id; // // @SerializedName(NAME) // @Expose // private String name; // // @SerializedName(USERNAME) // @Expose // private String username; // // @SerializedName(EMAIL) // @Expose // private String email; // // public Integer getId() { // return id; // } // // public void setId(final Integer id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(final String name) { // this.name = name; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getEmail() { // return email; // } // // public void setEmail(final String email) { // this.email = email; // } // // }
import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import io.petros.posts.PreconfiguredRobolectricTestRunner; import io.petros.posts.RobolectricGeneralTestHelper; import io.petros.posts.model.User; import io.realm.Realm; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when;
package io.petros.posts.datastore; /** * This test is ignored until PowerMock is introduced, which will mock all the Realm objects. */ @Ignore("java.lang.NullPointerException at io.realm.BaseRealm.beginTransaction") @RunWith(PreconfiguredRobolectricTestRunner.class)
// Path: app/src/test/java/io/petros/posts/PreconfiguredRobolectricTestRunner.java // public class PreconfiguredRobolectricTestRunner extends RobolectricTestRunner { // // private static final int SDK_API_LEVEL_TO_EMULATE = 25; // // /** // * Creates a runner to run {@code testClass}. Looks in your working directory for your AndroidManifest.xml file and res directory by // * default. Use the {@link Config} annotation to configure. // * // * @param testClass The test class to be run. // * @throws InitializationError If junit says so. // */ // public PreconfiguredRobolectricTestRunner(final Class<?> testClass) throws InitializationError { // super(testClass); // } // // @Override // protected Config buildGlobalConfig() { // return new Config.Builder() // .setSdk(SDK_API_LEVEL_TO_EMULATE) // .setManifest(Config.NONE) // .setApplication(TestPostsApplication.class) // .build(); // } // // } // // Path: app/src/test/java/io/petros/posts/RobolectricGeneralTestHelper.java // public class RobolectricGeneralTestHelper extends GeneralTestHelper { // // // Application specific fields. // protected final Context context = getTestContext(); // protected final PostsApplication application = getTestApplication(); // // // System specific fields. // @Mock protected ConnectivityManager connectivityManagerMock; // // // Activity specific fields. // @Mock protected PostsApplication applicationMock; // @Mock protected SnackbarActions snackbarActionsMock; // // // ROBOLECTRIC // ******************************************************************************************************* // // private Context getTestContext() { // return getShadowApplication().getApplicationContext(); // } // // private ShadowApplication getShadowApplication() { // return ShadowApplication.getInstance(); // } // // private PostsApplication getTestApplication() { // return (PostsApplication) RuntimeEnvironment.application; // } // // // MOCKS // ************************************************************************************************************* // // protected void setUpMocks() { // super.setUpMocks(); // setUpApplicationMocks(); // } // // private void setUpApplicationMocks() { // when(applicationMock.getSystemService(Context.CONNECTIVITY_SERVICE)).thenReturn(connectivityManagerMock); // when(applicationMock.snackbar()).thenReturn(snackbarActionsMock); // } // // // POST // ************************************************************************************************************** // // protected Bundle getExtras(final Post post) { // final Bundle extras = new Bundle(); // extras.putInt(Post.USER_ID, post.getUserId()); // extras.putInt(Post.ID, post.getId()); // extras.putString(Post.TITLE, post.getTitle()); // extras.putString(Post.BODY, post.getBody()); // return extras; // } // // } // // Path: app/src/main/java/io/petros/posts/model/User.java // public class User extends RealmObject { // // public static final String ID = "id"; // public static final String NAME = "name"; // public static final String USERNAME = "username"; // public static final String EMAIL = "email"; // // @SerializedName(ID) // @Expose // @PrimaryKey // private Integer id; // // @SerializedName(NAME) // @Expose // private String name; // // @SerializedName(USERNAME) // @Expose // private String username; // // @SerializedName(EMAIL) // @Expose // private String email; // // public Integer getId() { // return id; // } // // public void setId(final Integer id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(final String name) { // this.name = name; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getEmail() { // return email; // } // // public void setEmail(final String email) { // this.email = email; // } // // } // Path: app/src/test/java/io/petros/posts/datastore/DatastoreAddActionsTest.java import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import io.petros.posts.PreconfiguredRobolectricTestRunner; import io.petros.posts.RobolectricGeneralTestHelper; import io.petros.posts.model.User; import io.realm.Realm; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; package io.petros.posts.datastore; /** * This test is ignored until PowerMock is introduced, which will mock all the Realm objects. */ @Ignore("java.lang.NullPointerException at io.realm.BaseRealm.beginTransaction") @RunWith(PreconfiguredRobolectricTestRunner.class)
public class DatastoreAddActionsTest extends RobolectricGeneralTestHelper {