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
Netflix/Nicobar
nicobar-groovy2/src/main/java/com/netflix/nicobar/groovy2/plugin/Groovy2CompilerPlugin.java
// Path: nicobar-core/src/main/java/com/netflix/nicobar/core/compile/ScriptArchiveCompiler.java // public interface ScriptArchiveCompiler { // /** // * Whether or not this compiler should be used to compile the archive // */ // public boolean shouldCompile(ScriptArchive archive); // // /** // * Compile the archive into a ScriptModule // * @param archive archive to generate class files for // * @param moduleClassLoader class loader which can be used to find all classes and resources for modules. // * The resultant classes of the compile operation should be injected into the classloader // * for which the given archive has a declared dependency on // * @param targetDir a directory in which to store compiled classes, if any. // * @return The set of classes that were compiled // * @throws ScriptCompilationException if there was a compilation issue in the archive. // * @throws IOException if there was a problem reading/writing the archive // */ // public Set<Class<?>> compile(ScriptArchive archive, JBossModuleClassLoader moduleClassLoader, Path targetDir) throws ScriptCompilationException, IOException; // } // // Path: nicobar-core/src/main/java/com/netflix/nicobar/core/plugin/ScriptCompilerPlugin.java // public interface ScriptCompilerPlugin { // // public Set<? extends ScriptArchiveCompiler> getCompilers(Map<String, Object> compilerParams); // } // // Path: nicobar-groovy2/src/main/java/com/netflix/nicobar/groovy2/internal/compile/Groovy2Compiler.java // public class Groovy2Compiler implements ScriptArchiveCompiler { // // public final static String GROOVY2_COMPILER_ID = "groovy2"; // public final static String GROOVY2_COMPILER_PARAMS_CUSTOMIZERS = "customizerClassNames"; // // private List<String> customizerClassNames = new LinkedList<String>(); // // public Groovy2Compiler(Map<String, Object> compilerParams) { // this.processCompilerParams(compilerParams); // } // // private void processCompilerParams(Map<String, Object> compilerParams) { // // // filtering compilation customizers class names // if (compilerParams.containsKey(GROOVY2_COMPILER_PARAMS_CUSTOMIZERS)) { // Object customizers = compilerParams.get(GROOVY2_COMPILER_PARAMS_CUSTOMIZERS); // // if (customizers instanceof List) { // for (Object customizerClassName: (List<?>) customizers) { // if (customizerClassName instanceof String) { // this.customizerClassNames.add((String)customizerClassName); // } // } // } // } // } // // private CompilationCustomizer getCustomizerInstanceFromString(String className, JBossModuleClassLoader moduleClassLoader) { // CompilationCustomizer instance = null; // // try { // // TODO: replace JBossModuleClassLoader with generic class loader // ClassLoader classLoader = moduleClassLoader != null ? // moduleClassLoader : Thread.currentThread().getContextClassLoader(); // // Class<?> klass = classLoader.loadClass(className); // instance = (CompilationCustomizer)klass.newInstance(); // } // catch (InstantiationException | IllegalAccessException | ClassNotFoundException | ClassCastException e) { // e.printStackTrace(); // // TODO: add logger support for compiler (due to a separate class loader logger is not visible) // } // return instance; // } // // @Override // public boolean shouldCompile(ScriptArchive archive) { // return archive.getModuleSpec().getCompilerPluginIds().contains(GROOVY2_COMPILER_ID); // } // // @Override // public Set<Class<?>> compile(ScriptArchive archive, JBossModuleClassLoader moduleClassLoader, Path compilationRootDir) // throws ScriptCompilationException, IOException { // // List<CompilationCustomizer> customizers = new LinkedList<CompilationCustomizer>(); // // for (String klassName: this.customizerClassNames) { // CompilationCustomizer instance = this.getCustomizerInstanceFromString(klassName, moduleClassLoader); // if (instance != null ) { // customizers.add(instance); // } // } // // CompilerConfiguration config = new CompilerConfiguration(CompilerConfiguration.DEFAULT); // config.addCompilationCustomizers(customizers.toArray(new CompilationCustomizer[0])); // // new Groovy2CompilerHelper(compilationRootDir) // .addScriptArchive(archive) // .withParentClassloader(moduleClassLoader) // TODO: replace JBossModuleClassLoader with generic class loader // .withConfiguration(config) // .compile(); // return Collections.emptySet(); // } // }
import java.util.Collections; import java.util.Map; import java.util.Set; import com.netflix.nicobar.core.compile.ScriptArchiveCompiler; import com.netflix.nicobar.core.plugin.ScriptCompilerPlugin; import com.netflix.nicobar.groovy2.internal.compile.Groovy2Compiler;
/* * * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.nicobar.groovy2.plugin; /** * Factory class for the Groovy 2 language plug-in * * @author James Kojo * @author Vasanth Asokan */ public class Groovy2CompilerPlugin implements ScriptCompilerPlugin { public static final String PLUGIN_ID = "groovy2"; public Groovy2CompilerPlugin() { } @Override
// Path: nicobar-core/src/main/java/com/netflix/nicobar/core/compile/ScriptArchiveCompiler.java // public interface ScriptArchiveCompiler { // /** // * Whether or not this compiler should be used to compile the archive // */ // public boolean shouldCompile(ScriptArchive archive); // // /** // * Compile the archive into a ScriptModule // * @param archive archive to generate class files for // * @param moduleClassLoader class loader which can be used to find all classes and resources for modules. // * The resultant classes of the compile operation should be injected into the classloader // * for which the given archive has a declared dependency on // * @param targetDir a directory in which to store compiled classes, if any. // * @return The set of classes that were compiled // * @throws ScriptCompilationException if there was a compilation issue in the archive. // * @throws IOException if there was a problem reading/writing the archive // */ // public Set<Class<?>> compile(ScriptArchive archive, JBossModuleClassLoader moduleClassLoader, Path targetDir) throws ScriptCompilationException, IOException; // } // // Path: nicobar-core/src/main/java/com/netflix/nicobar/core/plugin/ScriptCompilerPlugin.java // public interface ScriptCompilerPlugin { // // public Set<? extends ScriptArchiveCompiler> getCompilers(Map<String, Object> compilerParams); // } // // Path: nicobar-groovy2/src/main/java/com/netflix/nicobar/groovy2/internal/compile/Groovy2Compiler.java // public class Groovy2Compiler implements ScriptArchiveCompiler { // // public final static String GROOVY2_COMPILER_ID = "groovy2"; // public final static String GROOVY2_COMPILER_PARAMS_CUSTOMIZERS = "customizerClassNames"; // // private List<String> customizerClassNames = new LinkedList<String>(); // // public Groovy2Compiler(Map<String, Object> compilerParams) { // this.processCompilerParams(compilerParams); // } // // private void processCompilerParams(Map<String, Object> compilerParams) { // // // filtering compilation customizers class names // if (compilerParams.containsKey(GROOVY2_COMPILER_PARAMS_CUSTOMIZERS)) { // Object customizers = compilerParams.get(GROOVY2_COMPILER_PARAMS_CUSTOMIZERS); // // if (customizers instanceof List) { // for (Object customizerClassName: (List<?>) customizers) { // if (customizerClassName instanceof String) { // this.customizerClassNames.add((String)customizerClassName); // } // } // } // } // } // // private CompilationCustomizer getCustomizerInstanceFromString(String className, JBossModuleClassLoader moduleClassLoader) { // CompilationCustomizer instance = null; // // try { // // TODO: replace JBossModuleClassLoader with generic class loader // ClassLoader classLoader = moduleClassLoader != null ? // moduleClassLoader : Thread.currentThread().getContextClassLoader(); // // Class<?> klass = classLoader.loadClass(className); // instance = (CompilationCustomizer)klass.newInstance(); // } // catch (InstantiationException | IllegalAccessException | ClassNotFoundException | ClassCastException e) { // e.printStackTrace(); // // TODO: add logger support for compiler (due to a separate class loader logger is not visible) // } // return instance; // } // // @Override // public boolean shouldCompile(ScriptArchive archive) { // return archive.getModuleSpec().getCompilerPluginIds().contains(GROOVY2_COMPILER_ID); // } // // @Override // public Set<Class<?>> compile(ScriptArchive archive, JBossModuleClassLoader moduleClassLoader, Path compilationRootDir) // throws ScriptCompilationException, IOException { // // List<CompilationCustomizer> customizers = new LinkedList<CompilationCustomizer>(); // // for (String klassName: this.customizerClassNames) { // CompilationCustomizer instance = this.getCustomizerInstanceFromString(klassName, moduleClassLoader); // if (instance != null ) { // customizers.add(instance); // } // } // // CompilerConfiguration config = new CompilerConfiguration(CompilerConfiguration.DEFAULT); // config.addCompilationCustomizers(customizers.toArray(new CompilationCustomizer[0])); // // new Groovy2CompilerHelper(compilationRootDir) // .addScriptArchive(archive) // .withParentClassloader(moduleClassLoader) // TODO: replace JBossModuleClassLoader with generic class loader // .withConfiguration(config) // .compile(); // return Collections.emptySet(); // } // } // Path: nicobar-groovy2/src/main/java/com/netflix/nicobar/groovy2/plugin/Groovy2CompilerPlugin.java import java.util.Collections; import java.util.Map; import java.util.Set; import com.netflix.nicobar.core.compile.ScriptArchiveCompiler; import com.netflix.nicobar.core.plugin.ScriptCompilerPlugin; import com.netflix.nicobar.groovy2.internal.compile.Groovy2Compiler; /* * * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.nicobar.groovy2.plugin; /** * Factory class for the Groovy 2 language plug-in * * @author James Kojo * @author Vasanth Asokan */ public class Groovy2CompilerPlugin implements ScriptCompilerPlugin { public static final String PLUGIN_ID = "groovy2"; public Groovy2CompilerPlugin() { } @Override
public Set<? extends ScriptArchiveCompiler> getCompilers(Map<String, Object> compilerParams) {
Netflix/Nicobar
nicobar-groovy2/src/main/java/com/netflix/nicobar/groovy2/plugin/Groovy2CompilerPlugin.java
// Path: nicobar-core/src/main/java/com/netflix/nicobar/core/compile/ScriptArchiveCompiler.java // public interface ScriptArchiveCompiler { // /** // * Whether or not this compiler should be used to compile the archive // */ // public boolean shouldCompile(ScriptArchive archive); // // /** // * Compile the archive into a ScriptModule // * @param archive archive to generate class files for // * @param moduleClassLoader class loader which can be used to find all classes and resources for modules. // * The resultant classes of the compile operation should be injected into the classloader // * for which the given archive has a declared dependency on // * @param targetDir a directory in which to store compiled classes, if any. // * @return The set of classes that were compiled // * @throws ScriptCompilationException if there was a compilation issue in the archive. // * @throws IOException if there was a problem reading/writing the archive // */ // public Set<Class<?>> compile(ScriptArchive archive, JBossModuleClassLoader moduleClassLoader, Path targetDir) throws ScriptCompilationException, IOException; // } // // Path: nicobar-core/src/main/java/com/netflix/nicobar/core/plugin/ScriptCompilerPlugin.java // public interface ScriptCompilerPlugin { // // public Set<? extends ScriptArchiveCompiler> getCompilers(Map<String, Object> compilerParams); // } // // Path: nicobar-groovy2/src/main/java/com/netflix/nicobar/groovy2/internal/compile/Groovy2Compiler.java // public class Groovy2Compiler implements ScriptArchiveCompiler { // // public final static String GROOVY2_COMPILER_ID = "groovy2"; // public final static String GROOVY2_COMPILER_PARAMS_CUSTOMIZERS = "customizerClassNames"; // // private List<String> customizerClassNames = new LinkedList<String>(); // // public Groovy2Compiler(Map<String, Object> compilerParams) { // this.processCompilerParams(compilerParams); // } // // private void processCompilerParams(Map<String, Object> compilerParams) { // // // filtering compilation customizers class names // if (compilerParams.containsKey(GROOVY2_COMPILER_PARAMS_CUSTOMIZERS)) { // Object customizers = compilerParams.get(GROOVY2_COMPILER_PARAMS_CUSTOMIZERS); // // if (customizers instanceof List) { // for (Object customizerClassName: (List<?>) customizers) { // if (customizerClassName instanceof String) { // this.customizerClassNames.add((String)customizerClassName); // } // } // } // } // } // // private CompilationCustomizer getCustomizerInstanceFromString(String className, JBossModuleClassLoader moduleClassLoader) { // CompilationCustomizer instance = null; // // try { // // TODO: replace JBossModuleClassLoader with generic class loader // ClassLoader classLoader = moduleClassLoader != null ? // moduleClassLoader : Thread.currentThread().getContextClassLoader(); // // Class<?> klass = classLoader.loadClass(className); // instance = (CompilationCustomizer)klass.newInstance(); // } // catch (InstantiationException | IllegalAccessException | ClassNotFoundException | ClassCastException e) { // e.printStackTrace(); // // TODO: add logger support for compiler (due to a separate class loader logger is not visible) // } // return instance; // } // // @Override // public boolean shouldCompile(ScriptArchive archive) { // return archive.getModuleSpec().getCompilerPluginIds().contains(GROOVY2_COMPILER_ID); // } // // @Override // public Set<Class<?>> compile(ScriptArchive archive, JBossModuleClassLoader moduleClassLoader, Path compilationRootDir) // throws ScriptCompilationException, IOException { // // List<CompilationCustomizer> customizers = new LinkedList<CompilationCustomizer>(); // // for (String klassName: this.customizerClassNames) { // CompilationCustomizer instance = this.getCustomizerInstanceFromString(klassName, moduleClassLoader); // if (instance != null ) { // customizers.add(instance); // } // } // // CompilerConfiguration config = new CompilerConfiguration(CompilerConfiguration.DEFAULT); // config.addCompilationCustomizers(customizers.toArray(new CompilationCustomizer[0])); // // new Groovy2CompilerHelper(compilationRootDir) // .addScriptArchive(archive) // .withParentClassloader(moduleClassLoader) // TODO: replace JBossModuleClassLoader with generic class loader // .withConfiguration(config) // .compile(); // return Collections.emptySet(); // } // }
import java.util.Collections; import java.util.Map; import java.util.Set; import com.netflix.nicobar.core.compile.ScriptArchiveCompiler; import com.netflix.nicobar.core.plugin.ScriptCompilerPlugin; import com.netflix.nicobar.groovy2.internal.compile.Groovy2Compiler;
/* * * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.nicobar.groovy2.plugin; /** * Factory class for the Groovy 2 language plug-in * * @author James Kojo * @author Vasanth Asokan */ public class Groovy2CompilerPlugin implements ScriptCompilerPlugin { public static final String PLUGIN_ID = "groovy2"; public Groovy2CompilerPlugin() { } @Override public Set<? extends ScriptArchiveCompiler> getCompilers(Map<String, Object> compilerParams) {
// Path: nicobar-core/src/main/java/com/netflix/nicobar/core/compile/ScriptArchiveCompiler.java // public interface ScriptArchiveCompiler { // /** // * Whether or not this compiler should be used to compile the archive // */ // public boolean shouldCompile(ScriptArchive archive); // // /** // * Compile the archive into a ScriptModule // * @param archive archive to generate class files for // * @param moduleClassLoader class loader which can be used to find all classes and resources for modules. // * The resultant classes of the compile operation should be injected into the classloader // * for which the given archive has a declared dependency on // * @param targetDir a directory in which to store compiled classes, if any. // * @return The set of classes that were compiled // * @throws ScriptCompilationException if there was a compilation issue in the archive. // * @throws IOException if there was a problem reading/writing the archive // */ // public Set<Class<?>> compile(ScriptArchive archive, JBossModuleClassLoader moduleClassLoader, Path targetDir) throws ScriptCompilationException, IOException; // } // // Path: nicobar-core/src/main/java/com/netflix/nicobar/core/plugin/ScriptCompilerPlugin.java // public interface ScriptCompilerPlugin { // // public Set<? extends ScriptArchiveCompiler> getCompilers(Map<String, Object> compilerParams); // } // // Path: nicobar-groovy2/src/main/java/com/netflix/nicobar/groovy2/internal/compile/Groovy2Compiler.java // public class Groovy2Compiler implements ScriptArchiveCompiler { // // public final static String GROOVY2_COMPILER_ID = "groovy2"; // public final static String GROOVY2_COMPILER_PARAMS_CUSTOMIZERS = "customizerClassNames"; // // private List<String> customizerClassNames = new LinkedList<String>(); // // public Groovy2Compiler(Map<String, Object> compilerParams) { // this.processCompilerParams(compilerParams); // } // // private void processCompilerParams(Map<String, Object> compilerParams) { // // // filtering compilation customizers class names // if (compilerParams.containsKey(GROOVY2_COMPILER_PARAMS_CUSTOMIZERS)) { // Object customizers = compilerParams.get(GROOVY2_COMPILER_PARAMS_CUSTOMIZERS); // // if (customizers instanceof List) { // for (Object customizerClassName: (List<?>) customizers) { // if (customizerClassName instanceof String) { // this.customizerClassNames.add((String)customizerClassName); // } // } // } // } // } // // private CompilationCustomizer getCustomizerInstanceFromString(String className, JBossModuleClassLoader moduleClassLoader) { // CompilationCustomizer instance = null; // // try { // // TODO: replace JBossModuleClassLoader with generic class loader // ClassLoader classLoader = moduleClassLoader != null ? // moduleClassLoader : Thread.currentThread().getContextClassLoader(); // // Class<?> klass = classLoader.loadClass(className); // instance = (CompilationCustomizer)klass.newInstance(); // } // catch (InstantiationException | IllegalAccessException | ClassNotFoundException | ClassCastException e) { // e.printStackTrace(); // // TODO: add logger support for compiler (due to a separate class loader logger is not visible) // } // return instance; // } // // @Override // public boolean shouldCompile(ScriptArchive archive) { // return archive.getModuleSpec().getCompilerPluginIds().contains(GROOVY2_COMPILER_ID); // } // // @Override // public Set<Class<?>> compile(ScriptArchive archive, JBossModuleClassLoader moduleClassLoader, Path compilationRootDir) // throws ScriptCompilationException, IOException { // // List<CompilationCustomizer> customizers = new LinkedList<CompilationCustomizer>(); // // for (String klassName: this.customizerClassNames) { // CompilationCustomizer instance = this.getCustomizerInstanceFromString(klassName, moduleClassLoader); // if (instance != null ) { // customizers.add(instance); // } // } // // CompilerConfiguration config = new CompilerConfiguration(CompilerConfiguration.DEFAULT); // config.addCompilationCustomizers(customizers.toArray(new CompilationCustomizer[0])); // // new Groovy2CompilerHelper(compilationRootDir) // .addScriptArchive(archive) // .withParentClassloader(moduleClassLoader) // TODO: replace JBossModuleClassLoader with generic class loader // .withConfiguration(config) // .compile(); // return Collections.emptySet(); // } // } // Path: nicobar-groovy2/src/main/java/com/netflix/nicobar/groovy2/plugin/Groovy2CompilerPlugin.java import java.util.Collections; import java.util.Map; import java.util.Set; import com.netflix.nicobar.core.compile.ScriptArchiveCompiler; import com.netflix.nicobar.core.plugin.ScriptCompilerPlugin; import com.netflix.nicobar.groovy2.internal.compile.Groovy2Compiler; /* * * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.nicobar.groovy2.plugin; /** * Factory class for the Groovy 2 language plug-in * * @author James Kojo * @author Vasanth Asokan */ public class Groovy2CompilerPlugin implements ScriptCompilerPlugin { public static final String PLUGIN_ID = "groovy2"; public Groovy2CompilerPlugin() { } @Override public Set<? extends ScriptArchiveCompiler> getCompilers(Map<String, Object> compilerParams) {
return Collections.singleton(new Groovy2Compiler(compilerParams));
Netflix/Nicobar
nicobar-core/src/main/java/com/netflix/nicobar/core/plugin/BytecodeLoadingPlugin.java
// Path: nicobar-core/src/main/java/com/netflix/nicobar/core/compile/ScriptArchiveCompiler.java // public interface ScriptArchiveCompiler { // /** // * Whether or not this compiler should be used to compile the archive // */ // public boolean shouldCompile(ScriptArchive archive); // // /** // * Compile the archive into a ScriptModule // * @param archive archive to generate class files for // * @param moduleClassLoader class loader which can be used to find all classes and resources for modules. // * The resultant classes of the compile operation should be injected into the classloader // * for which the given archive has a declared dependency on // * @param targetDir a directory in which to store compiled classes, if any. // * @return The set of classes that were compiled // * @throws ScriptCompilationException if there was a compilation issue in the archive. // * @throws IOException if there was a problem reading/writing the archive // */ // public Set<Class<?>> compile(ScriptArchive archive, JBossModuleClassLoader moduleClassLoader, Path targetDir) throws ScriptCompilationException, IOException; // } // // Path: nicobar-core/src/main/java/com/netflix/nicobar/core/internal/compile/BytecodeLoader.java // public class BytecodeLoader implements ScriptArchiveCompiler { // // /** // * Compile (load from) an archive, if it contains any .class files. // */ // @Override // public boolean shouldCompile(ScriptArchive archive) { // // Set<String> entries = archive.getArchiveEntryNames(); // boolean shouldCompile = false; // for (String entry: entries) { // if (entry.endsWith(".class")) { // shouldCompile = true; // } // } // // return shouldCompile; // } // // @Override // public Set<Class<?>> compile(ScriptArchive archive, JBossModuleClassLoader moduleClassLoader, Path targetDir) // throws ScriptCompilationException, IOException { // HashSet<Class<?>> addedClasses = new HashSet<Class<?>>(archive.getArchiveEntryNames().size()); // for (String entry : archive.getArchiveEntryNames()) { // if (!entry.endsWith(".class")) { // continue; // } // // Load from the underlying archive class resource // String entryName = entry.replace(".class", "").replace("/", "."); // try { // Class<?> addedClass = moduleClassLoader.loadClassLocal(entryName, true); // addedClasses.add(addedClass); // } catch (Exception e) { // throw new ScriptCompilationException("Unable to load class: " + entryName, e); // } // } // moduleClassLoader.addClasses(addedClasses); // // return Collections.unmodifiableSet(addedClasses); // } // }
import java.util.Collections; import java.util.Map; import java.util.Set; import com.netflix.nicobar.core.compile.ScriptArchiveCompiler; import com.netflix.nicobar.core.internal.compile.BytecodeLoader;
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.nicobar.core.plugin; /** * A {@link ScriptCompilerPlugin} for script archives that include java bytecode. * * @author Vasanth Asokan */ public class BytecodeLoadingPlugin implements ScriptCompilerPlugin { public static final String PLUGIN_ID = "bytecode"; @Override
// Path: nicobar-core/src/main/java/com/netflix/nicobar/core/compile/ScriptArchiveCompiler.java // public interface ScriptArchiveCompiler { // /** // * Whether or not this compiler should be used to compile the archive // */ // public boolean shouldCompile(ScriptArchive archive); // // /** // * Compile the archive into a ScriptModule // * @param archive archive to generate class files for // * @param moduleClassLoader class loader which can be used to find all classes and resources for modules. // * The resultant classes of the compile operation should be injected into the classloader // * for which the given archive has a declared dependency on // * @param targetDir a directory in which to store compiled classes, if any. // * @return The set of classes that were compiled // * @throws ScriptCompilationException if there was a compilation issue in the archive. // * @throws IOException if there was a problem reading/writing the archive // */ // public Set<Class<?>> compile(ScriptArchive archive, JBossModuleClassLoader moduleClassLoader, Path targetDir) throws ScriptCompilationException, IOException; // } // // Path: nicobar-core/src/main/java/com/netflix/nicobar/core/internal/compile/BytecodeLoader.java // public class BytecodeLoader implements ScriptArchiveCompiler { // // /** // * Compile (load from) an archive, if it contains any .class files. // */ // @Override // public boolean shouldCompile(ScriptArchive archive) { // // Set<String> entries = archive.getArchiveEntryNames(); // boolean shouldCompile = false; // for (String entry: entries) { // if (entry.endsWith(".class")) { // shouldCompile = true; // } // } // // return shouldCompile; // } // // @Override // public Set<Class<?>> compile(ScriptArchive archive, JBossModuleClassLoader moduleClassLoader, Path targetDir) // throws ScriptCompilationException, IOException { // HashSet<Class<?>> addedClasses = new HashSet<Class<?>>(archive.getArchiveEntryNames().size()); // for (String entry : archive.getArchiveEntryNames()) { // if (!entry.endsWith(".class")) { // continue; // } // // Load from the underlying archive class resource // String entryName = entry.replace(".class", "").replace("/", "."); // try { // Class<?> addedClass = moduleClassLoader.loadClassLocal(entryName, true); // addedClasses.add(addedClass); // } catch (Exception e) { // throw new ScriptCompilationException("Unable to load class: " + entryName, e); // } // } // moduleClassLoader.addClasses(addedClasses); // // return Collections.unmodifiableSet(addedClasses); // } // } // Path: nicobar-core/src/main/java/com/netflix/nicobar/core/plugin/BytecodeLoadingPlugin.java import java.util.Collections; import java.util.Map; import java.util.Set; import com.netflix.nicobar.core.compile.ScriptArchiveCompiler; import com.netflix.nicobar.core.internal.compile.BytecodeLoader; /* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.nicobar.core.plugin; /** * A {@link ScriptCompilerPlugin} for script archives that include java bytecode. * * @author Vasanth Asokan */ public class BytecodeLoadingPlugin implements ScriptCompilerPlugin { public static final String PLUGIN_ID = "bytecode"; @Override
public Set<? extends ScriptArchiveCompiler> getCompilers(Map<String, Object> compilerParams) {
Netflix/Nicobar
nicobar-core/src/main/java/com/netflix/nicobar/core/plugin/BytecodeLoadingPlugin.java
// Path: nicobar-core/src/main/java/com/netflix/nicobar/core/compile/ScriptArchiveCompiler.java // public interface ScriptArchiveCompiler { // /** // * Whether or not this compiler should be used to compile the archive // */ // public boolean shouldCompile(ScriptArchive archive); // // /** // * Compile the archive into a ScriptModule // * @param archive archive to generate class files for // * @param moduleClassLoader class loader which can be used to find all classes and resources for modules. // * The resultant classes of the compile operation should be injected into the classloader // * for which the given archive has a declared dependency on // * @param targetDir a directory in which to store compiled classes, if any. // * @return The set of classes that were compiled // * @throws ScriptCompilationException if there was a compilation issue in the archive. // * @throws IOException if there was a problem reading/writing the archive // */ // public Set<Class<?>> compile(ScriptArchive archive, JBossModuleClassLoader moduleClassLoader, Path targetDir) throws ScriptCompilationException, IOException; // } // // Path: nicobar-core/src/main/java/com/netflix/nicobar/core/internal/compile/BytecodeLoader.java // public class BytecodeLoader implements ScriptArchiveCompiler { // // /** // * Compile (load from) an archive, if it contains any .class files. // */ // @Override // public boolean shouldCompile(ScriptArchive archive) { // // Set<String> entries = archive.getArchiveEntryNames(); // boolean shouldCompile = false; // for (String entry: entries) { // if (entry.endsWith(".class")) { // shouldCompile = true; // } // } // // return shouldCompile; // } // // @Override // public Set<Class<?>> compile(ScriptArchive archive, JBossModuleClassLoader moduleClassLoader, Path targetDir) // throws ScriptCompilationException, IOException { // HashSet<Class<?>> addedClasses = new HashSet<Class<?>>(archive.getArchiveEntryNames().size()); // for (String entry : archive.getArchiveEntryNames()) { // if (!entry.endsWith(".class")) { // continue; // } // // Load from the underlying archive class resource // String entryName = entry.replace(".class", "").replace("/", "."); // try { // Class<?> addedClass = moduleClassLoader.loadClassLocal(entryName, true); // addedClasses.add(addedClass); // } catch (Exception e) { // throw new ScriptCompilationException("Unable to load class: " + entryName, e); // } // } // moduleClassLoader.addClasses(addedClasses); // // return Collections.unmodifiableSet(addedClasses); // } // }
import java.util.Collections; import java.util.Map; import java.util.Set; import com.netflix.nicobar.core.compile.ScriptArchiveCompiler; import com.netflix.nicobar.core.internal.compile.BytecodeLoader;
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.nicobar.core.plugin; /** * A {@link ScriptCompilerPlugin} for script archives that include java bytecode. * * @author Vasanth Asokan */ public class BytecodeLoadingPlugin implements ScriptCompilerPlugin { public static final String PLUGIN_ID = "bytecode"; @Override public Set<? extends ScriptArchiveCompiler> getCompilers(Map<String, Object> compilerParams) {
// Path: nicobar-core/src/main/java/com/netflix/nicobar/core/compile/ScriptArchiveCompiler.java // public interface ScriptArchiveCompiler { // /** // * Whether or not this compiler should be used to compile the archive // */ // public boolean shouldCompile(ScriptArchive archive); // // /** // * Compile the archive into a ScriptModule // * @param archive archive to generate class files for // * @param moduleClassLoader class loader which can be used to find all classes and resources for modules. // * The resultant classes of the compile operation should be injected into the classloader // * for which the given archive has a declared dependency on // * @param targetDir a directory in which to store compiled classes, if any. // * @return The set of classes that were compiled // * @throws ScriptCompilationException if there was a compilation issue in the archive. // * @throws IOException if there was a problem reading/writing the archive // */ // public Set<Class<?>> compile(ScriptArchive archive, JBossModuleClassLoader moduleClassLoader, Path targetDir) throws ScriptCompilationException, IOException; // } // // Path: nicobar-core/src/main/java/com/netflix/nicobar/core/internal/compile/BytecodeLoader.java // public class BytecodeLoader implements ScriptArchiveCompiler { // // /** // * Compile (load from) an archive, if it contains any .class files. // */ // @Override // public boolean shouldCompile(ScriptArchive archive) { // // Set<String> entries = archive.getArchiveEntryNames(); // boolean shouldCompile = false; // for (String entry: entries) { // if (entry.endsWith(".class")) { // shouldCompile = true; // } // } // // return shouldCompile; // } // // @Override // public Set<Class<?>> compile(ScriptArchive archive, JBossModuleClassLoader moduleClassLoader, Path targetDir) // throws ScriptCompilationException, IOException { // HashSet<Class<?>> addedClasses = new HashSet<Class<?>>(archive.getArchiveEntryNames().size()); // for (String entry : archive.getArchiveEntryNames()) { // if (!entry.endsWith(".class")) { // continue; // } // // Load from the underlying archive class resource // String entryName = entry.replace(".class", "").replace("/", "."); // try { // Class<?> addedClass = moduleClassLoader.loadClassLocal(entryName, true); // addedClasses.add(addedClass); // } catch (Exception e) { // throw new ScriptCompilationException("Unable to load class: " + entryName, e); // } // } // moduleClassLoader.addClasses(addedClasses); // // return Collections.unmodifiableSet(addedClasses); // } // } // Path: nicobar-core/src/main/java/com/netflix/nicobar/core/plugin/BytecodeLoadingPlugin.java import java.util.Collections; import java.util.Map; import java.util.Set; import com.netflix.nicobar.core.compile.ScriptArchiveCompiler; import com.netflix.nicobar.core.internal.compile.BytecodeLoader; /* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.nicobar.core.plugin; /** * A {@link ScriptCompilerPlugin} for script archives that include java bytecode. * * @author Vasanth Asokan */ public class BytecodeLoadingPlugin implements ScriptCompilerPlugin { public static final String PLUGIN_ID = "bytecode"; @Override public Set<? extends ScriptArchiveCompiler> getCompilers(Map<String, Object> compilerParams) {
return Collections.singleton(new BytecodeLoader());
Netflix/Nicobar
nicobar-groovy2/src/main/java/com/netflix/nicobar/groovy2/internal/compile/Groovy2CompilerHelper.java
// Path: nicobar-core/src/main/java/com/netflix/nicobar/core/compile/ScriptCompilationException.java // public class ScriptCompilationException extends Exception { // private static final long serialVersionUID = 1L; // // /** // * Create a generic compilation exception. // * @param message the actual message. // */ // public ScriptCompilationException(String message) { // super(message); // } // // /** // * A compilation exception with a specific underlying exception // * that is compiler specific. // */ // public ScriptCompilationException(String message, Throwable cause) { // super(message, cause); // } // }
import org.codehaus.groovy.control.CompilationUnit; import org.codehaus.groovy.control.CompilerConfiguration; import org.codehaus.groovy.control.Phases; import org.codehaus.groovy.tools.GroovyClass; import com.netflix.nicobar.core.archive.ScriptArchive; import com.netflix.nicobar.core.compile.ScriptCompilationException; import groovy.lang.GroovyClassLoader; import java.io.IOException; import java.nio.file.Path; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Objects; import java.util.Set; import org.codehaus.groovy.control.CompilationFailedException;
return this; } public Groovy2CompilerHelper addSourceFile(Path groovyFile) { if (groovyFile != null) { sourceFiles.add(groovyFile); } return this; } public Groovy2CompilerHelper addScriptArchive(ScriptArchive archive) { if (archive != null) { scriptArchives.add(archive); } return this; } public Groovy2CompilerHelper withConfiguration(CompilerConfiguration compilerConfig) { if (compilerConfig != null) { this.compileConfig = compilerConfig; } return this; } /** * Compile the given source and load the resultant classes into a new {@link ClassNotFoundException} * @return initialized and laoded classes * @throws ScriptCompilationException */ @SuppressWarnings("unchecked")
// Path: nicobar-core/src/main/java/com/netflix/nicobar/core/compile/ScriptCompilationException.java // public class ScriptCompilationException extends Exception { // private static final long serialVersionUID = 1L; // // /** // * Create a generic compilation exception. // * @param message the actual message. // */ // public ScriptCompilationException(String message) { // super(message); // } // // /** // * A compilation exception with a specific underlying exception // * that is compiler specific. // */ // public ScriptCompilationException(String message, Throwable cause) { // super(message, cause); // } // } // Path: nicobar-groovy2/src/main/java/com/netflix/nicobar/groovy2/internal/compile/Groovy2CompilerHelper.java import org.codehaus.groovy.control.CompilationUnit; import org.codehaus.groovy.control.CompilerConfiguration; import org.codehaus.groovy.control.Phases; import org.codehaus.groovy.tools.GroovyClass; import com.netflix.nicobar.core.archive.ScriptArchive; import com.netflix.nicobar.core.compile.ScriptCompilationException; import groovy.lang.GroovyClassLoader; import java.io.IOException; import java.nio.file.Path; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Objects; import java.util.Set; import org.codehaus.groovy.control.CompilationFailedException; return this; } public Groovy2CompilerHelper addSourceFile(Path groovyFile) { if (groovyFile != null) { sourceFiles.add(groovyFile); } return this; } public Groovy2CompilerHelper addScriptArchive(ScriptArchive archive) { if (archive != null) { scriptArchives.add(archive); } return this; } public Groovy2CompilerHelper withConfiguration(CompilerConfiguration compilerConfig) { if (compilerConfig != null) { this.compileConfig = compilerConfig; } return this; } /** * Compile the given source and load the resultant classes into a new {@link ClassNotFoundException} * @return initialized and laoded classes * @throws ScriptCompilationException */ @SuppressWarnings("unchecked")
public Set<GroovyClass> compile() throws ScriptCompilationException {
Netflix/Nicobar
nicobar-manager/src/main/java/com/netflix/nicobar/manager/explorer/ScriptManagerBootstrap.java
// Path: nicobar-manager/src/main/java/com/netflix/nicobar/manager/rest/GsonMessageBodyHandler.java // @Provider // @Produces(MediaType.APPLICATION_JSON) // @Consumes(MediaType.APPLICATION_JSON) // public final class GsonMessageBodyHandler implements MessageBodyWriter<Object>, MessageBodyReader<Object> { // // private Gson gson; // // @Override // public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { // return true; // } // // @Override // public Object readFrom(Class<Object> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) { // InputStreamReader streamReader = new InputStreamReader(entityStream, Charsets.UTF_8); // try { // Type jsonType; // if (type.equals(genericType)) { // jsonType = type; // } else { // jsonType = genericType; // } // return getGson().fromJson(streamReader, jsonType); // } finally { // IOUtils.closeQuietly(streamReader); // } // } // // @Override // public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { // return true; // } // // @Override // public long getSize(Object object, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { // return -1; // } // // @Override // public void writeTo(Object object, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { // OutputStreamWriter writer = new OutputStreamWriter(entityStream, Charsets.UTF_8); // try { // Type jsonType; // if (type.equals(genericType)) { // jsonType = type; // } else { // jsonType = genericType; // } // getGson().toJson(object, jsonType, writer); // } finally { // IOUtils.closeQuietly(writer); // } // } // // protected Gson getGson() { // if (gson == null) { // final GsonBuilder gsonBuilder = new GsonBuilder(); // gson = gsonBuilder.create(); // } // return gson; // } // }
import com.sun.jersey.api.core.PackagesResourceConfig; import com.sun.jersey.guice.JerseyServletModule; import com.sun.jersey.guice.spi.container.servlet.GuiceContainer; import java.util.HashMap; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.Scopes; import com.google.inject.name.Names; import com.netflix.explorers.AppConfigGlobalModelContext; import com.netflix.explorers.ExplorerManager; import com.netflix.explorers.ExplorersManagerImpl; import com.netflix.explorers.context.GlobalModelContext; import com.netflix.governator.guice.LifecycleInjectorBuilder; import com.netflix.karyon.server.ServerBootstrap; import com.netflix.nicobar.manager.rest.GsonMessageBodyHandler;
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.nicobar.manager.explorer; public class ScriptManagerBootstrap extends ServerBootstrap { private static final Logger LOG = LoggerFactory.getLogger(ScriptManagerBootstrap.class); @Override protected void beforeInjectorCreation(@SuppressWarnings("unused") LifecycleInjectorBuilder builderToBeUsed) { JerseyServletModule jerseyServletModule = new JerseyServletModule() { @Override protected void configureServlets() { bind(String.class).annotatedWith(Names.named("explorerAppName")).toInstance("scriptmanager");
// Path: nicobar-manager/src/main/java/com/netflix/nicobar/manager/rest/GsonMessageBodyHandler.java // @Provider // @Produces(MediaType.APPLICATION_JSON) // @Consumes(MediaType.APPLICATION_JSON) // public final class GsonMessageBodyHandler implements MessageBodyWriter<Object>, MessageBodyReader<Object> { // // private Gson gson; // // @Override // public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { // return true; // } // // @Override // public Object readFrom(Class<Object> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) { // InputStreamReader streamReader = new InputStreamReader(entityStream, Charsets.UTF_8); // try { // Type jsonType; // if (type.equals(genericType)) { // jsonType = type; // } else { // jsonType = genericType; // } // return getGson().fromJson(streamReader, jsonType); // } finally { // IOUtils.closeQuietly(streamReader); // } // } // // @Override // public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { // return true; // } // // @Override // public long getSize(Object object, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { // return -1; // } // // @Override // public void writeTo(Object object, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { // OutputStreamWriter writer = new OutputStreamWriter(entityStream, Charsets.UTF_8); // try { // Type jsonType; // if (type.equals(genericType)) { // jsonType = type; // } else { // jsonType = genericType; // } // getGson().toJson(object, jsonType, writer); // } finally { // IOUtils.closeQuietly(writer); // } // } // // protected Gson getGson() { // if (gson == null) { // final GsonBuilder gsonBuilder = new GsonBuilder(); // gson = gsonBuilder.create(); // } // return gson; // } // } // Path: nicobar-manager/src/main/java/com/netflix/nicobar/manager/explorer/ScriptManagerBootstrap.java import com.sun.jersey.api.core.PackagesResourceConfig; import com.sun.jersey.guice.JerseyServletModule; import com.sun.jersey.guice.spi.container.servlet.GuiceContainer; import java.util.HashMap; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.Scopes; import com.google.inject.name.Names; import com.netflix.explorers.AppConfigGlobalModelContext; import com.netflix.explorers.ExplorerManager; import com.netflix.explorers.ExplorersManagerImpl; import com.netflix.explorers.context.GlobalModelContext; import com.netflix.governator.guice.LifecycleInjectorBuilder; import com.netflix.karyon.server.ServerBootstrap; import com.netflix.nicobar.manager.rest.GsonMessageBodyHandler; /* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.nicobar.manager.explorer; public class ScriptManagerBootstrap extends ServerBootstrap { private static final Logger LOG = LoggerFactory.getLogger(ScriptManagerBootstrap.class); @Override protected void beforeInjectorCreation(@SuppressWarnings("unused") LifecycleInjectorBuilder builderToBeUsed) { JerseyServletModule jerseyServletModule = new JerseyServletModule() { @Override protected void configureServlets() { bind(String.class).annotatedWith(Names.named("explorerAppName")).toInstance("scriptmanager");
bind(GsonMessageBodyHandler.class).in(Scopes.SINGLETON);
Mockenize/mockenize-server
src/main/java/org/mockenize/service/LoggingService.java
// Path: src/main/java/org/mockenize/model/LogBean.java // @Data // public class LogBean implements Serializable, Cacheable { // // private static final long serialVersionUID = 1L; // // private String key; // // private LogType type; // // private String url; // // private String path; // // private String method; // // private RequestLogBean request; // // private ResponseLogBean response; // // private Date date = new Date(); // // protected LogBean() { // } // // public LogBean(UUID key, LogType type) { // this.key = key.toString(); // this.type = type; // } // // } // // Path: src/main/java/org/mockenize/repository/LogRepository.java // @Repository // public class LogRepository extends AbstractRepository<LogBean> { // // private static final String CACHE_KEY = "logs"; // // @Autowired // public LogRepository(HazelcastInstance hazelcastInstance) { // super(hazelcastInstance, CACHE_KEY); // map.addIndex("key", false); // map.addIndex("date", true); // } // // }
import java.util.Collection; import java.util.Iterator; import java.util.UUID; import org.mockenize.model.LogBean; import org.mockenize.repository.LogRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.fasterxml.jackson.databind.JsonNode; import com.hazelcast.query.Predicate; import com.hazelcast.query.Predicates;
package org.mockenize.service; @Service public class LoggingService { @Autowired
// Path: src/main/java/org/mockenize/model/LogBean.java // @Data // public class LogBean implements Serializable, Cacheable { // // private static final long serialVersionUID = 1L; // // private String key; // // private LogType type; // // private String url; // // private String path; // // private String method; // // private RequestLogBean request; // // private ResponseLogBean response; // // private Date date = new Date(); // // protected LogBean() { // } // // public LogBean(UUID key, LogType type) { // this.key = key.toString(); // this.type = type; // } // // } // // Path: src/main/java/org/mockenize/repository/LogRepository.java // @Repository // public class LogRepository extends AbstractRepository<LogBean> { // // private static final String CACHE_KEY = "logs"; // // @Autowired // public LogRepository(HazelcastInstance hazelcastInstance) { // super(hazelcastInstance, CACHE_KEY); // map.addIndex("key", false); // map.addIndex("date", true); // } // // } // Path: src/main/java/org/mockenize/service/LoggingService.java import java.util.Collection; import java.util.Iterator; import java.util.UUID; import org.mockenize.model.LogBean; import org.mockenize.repository.LogRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.fasterxml.jackson.databind.JsonNode; import com.hazelcast.query.Predicate; import com.hazelcast.query.Predicates; package org.mockenize.service; @Service public class LoggingService { @Autowired
private LogRepository logRepository;
Mockenize/mockenize-server
src/main/java/org/mockenize/service/LoggingService.java
// Path: src/main/java/org/mockenize/model/LogBean.java // @Data // public class LogBean implements Serializable, Cacheable { // // private static final long serialVersionUID = 1L; // // private String key; // // private LogType type; // // private String url; // // private String path; // // private String method; // // private RequestLogBean request; // // private ResponseLogBean response; // // private Date date = new Date(); // // protected LogBean() { // } // // public LogBean(UUID key, LogType type) { // this.key = key.toString(); // this.type = type; // } // // } // // Path: src/main/java/org/mockenize/repository/LogRepository.java // @Repository // public class LogRepository extends AbstractRepository<LogBean> { // // private static final String CACHE_KEY = "logs"; // // @Autowired // public LogRepository(HazelcastInstance hazelcastInstance) { // super(hazelcastInstance, CACHE_KEY); // map.addIndex("key", false); // map.addIndex("date", true); // } // // }
import java.util.Collection; import java.util.Iterator; import java.util.UUID; import org.mockenize.model.LogBean; import org.mockenize.repository.LogRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.fasterxml.jackson.databind.JsonNode; import com.hazelcast.query.Predicate; import com.hazelcast.query.Predicates;
package org.mockenize.service; @Service public class LoggingService { @Autowired private LogRepository logRepository;
// Path: src/main/java/org/mockenize/model/LogBean.java // @Data // public class LogBean implements Serializable, Cacheable { // // private static final long serialVersionUID = 1L; // // private String key; // // private LogType type; // // private String url; // // private String path; // // private String method; // // private RequestLogBean request; // // private ResponseLogBean response; // // private Date date = new Date(); // // protected LogBean() { // } // // public LogBean(UUID key, LogType type) { // this.key = key.toString(); // this.type = type; // } // // } // // Path: src/main/java/org/mockenize/repository/LogRepository.java // @Repository // public class LogRepository extends AbstractRepository<LogBean> { // // private static final String CACHE_KEY = "logs"; // // @Autowired // public LogRepository(HazelcastInstance hazelcastInstance) { // super(hazelcastInstance, CACHE_KEY); // map.addIndex("key", false); // map.addIndex("date", true); // } // // } // Path: src/main/java/org/mockenize/service/LoggingService.java import java.util.Collection; import java.util.Iterator; import java.util.UUID; import org.mockenize.model.LogBean; import org.mockenize.repository.LogRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.fasterxml.jackson.databind.JsonNode; import com.hazelcast.query.Predicate; import com.hazelcast.query.Predicates; package org.mockenize.service; @Service public class LoggingService { @Autowired private LogRepository logRepository;
public void save(LogBean logBean) {
Mockenize/mockenize-server
src/main/java/org/mockenize/controller/ProxiesController.java
// Path: src/main/java/org/mockenize/model/ProxyBean.java // @Data // public class ProxyBean implements Serializable, Cacheable { // // private static final long serialVersionUID = 1L; // // private static final String UNDERLINE = "_"; // // private static final String SLASH = "/"; // // @NotEmpty // private String key; // // @NotEmpty // private String path; // // @NotNull // private String name; // // @NotNull // private URI url; // // @Override // public String getKey() { // return path.toLowerCase().replaceAll(SLASH, UNDERLINE); // } // } // // Path: src/main/java/org/mockenize/service/ProxyService.java // @Service // public class ProxyService implements ResponseService { // // @Autowired // private ProxyRepository proxyRepository; // // @Context // private HttpServletRequest request; // // private Client client = ClientBuilder.newClient(); // // public Collection<ProxyBean> getAll() { // return proxyRepository.findAll(); // } // // public void save(ProxyBean proxyBean) { // proxyRepository.save(proxyBean); // } // // public ProxyBean getByKey(String key) { // return proxyRepository.findByKey(key); // } // // public ProxyBean delete(ProxyBean proxyBean) { // return proxyRepository.delete(proxyBean); // } // // public Collection<ProxyBean> deleteAll(Collection<ProxyBean> proxyBeans) { // Collection<ProxyBean> deletedProxies = new ArrayList<>(); // if(proxyBeans != null && !proxyBeans.isEmpty()) { // for (ProxyBean bean : proxyBeans) { // ProxyBean deleted = proxyRepository.delete(bean); // if(deleted != null) { // deletedProxies.add(deleted); // } // } // } else { // deletedProxies = proxyRepository.deleteAll(); // } // return deletedProxies; // } // // @Override // public Response getResponse(HttpServletRequest request, JsonNode requestBody) { // String path = request.getRequestURI(); // ProxyBean proxyBean = proxyRepository.findByKey(path); // Builder requestBuilder = client.target(proxyBean.getUrl()).path(getRequestPath(proxyBean.getPath(), path)) // .request(); // addHeaders(request, requestBuilder); // Entity<JsonNode> entity = Entity.entity(requestBody, getContentType(request)); // Response response = requestBuilder.build(request.getMethod(), entity).invoke(); // response.bufferEntity(); // return response; // } // // private String getRequestPath(String path, String requestedPath) { // if (path.matches("/.+")) { // Pattern pattern = Pattern.compile("/[^/\\.]+(.*)"); // Matcher matcher = pattern.matcher(requestedPath); // if (matcher.matches()) { // return matcher.group(1); // } else { // throw new ProxyPathException(); // } // } // // return null; // } // // private void addHeaders(HttpServletRequest request, Builder requestBuilder) { // Enumeration<String> headerNames = request.getHeaderNames(); // while (headerNames.hasMoreElements()) { // String key = headerNames.nextElement(); // requestBuilder.header(key, request.getHeader(key)); // } // } // // private String getContentType(HttpServletRequest request) { // if (Strings.isNullOrEmpty(request.getContentType())) { // return MediaType.TEXT_PLAIN; // } // // return request.getContentType(); // } // // public boolean exists(String path) { // return proxyRepository.exists(path); // } // // }
import java.util.Collection; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.mockenize.model.ProxyBean; import org.mockenize.service.ProxyService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller;
package org.mockenize.controller; @Controller @Path("/_mockenize/proxies") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public class ProxiesController { @Autowired
// Path: src/main/java/org/mockenize/model/ProxyBean.java // @Data // public class ProxyBean implements Serializable, Cacheable { // // private static final long serialVersionUID = 1L; // // private static final String UNDERLINE = "_"; // // private static final String SLASH = "/"; // // @NotEmpty // private String key; // // @NotEmpty // private String path; // // @NotNull // private String name; // // @NotNull // private URI url; // // @Override // public String getKey() { // return path.toLowerCase().replaceAll(SLASH, UNDERLINE); // } // } // // Path: src/main/java/org/mockenize/service/ProxyService.java // @Service // public class ProxyService implements ResponseService { // // @Autowired // private ProxyRepository proxyRepository; // // @Context // private HttpServletRequest request; // // private Client client = ClientBuilder.newClient(); // // public Collection<ProxyBean> getAll() { // return proxyRepository.findAll(); // } // // public void save(ProxyBean proxyBean) { // proxyRepository.save(proxyBean); // } // // public ProxyBean getByKey(String key) { // return proxyRepository.findByKey(key); // } // // public ProxyBean delete(ProxyBean proxyBean) { // return proxyRepository.delete(proxyBean); // } // // public Collection<ProxyBean> deleteAll(Collection<ProxyBean> proxyBeans) { // Collection<ProxyBean> deletedProxies = new ArrayList<>(); // if(proxyBeans != null && !proxyBeans.isEmpty()) { // for (ProxyBean bean : proxyBeans) { // ProxyBean deleted = proxyRepository.delete(bean); // if(deleted != null) { // deletedProxies.add(deleted); // } // } // } else { // deletedProxies = proxyRepository.deleteAll(); // } // return deletedProxies; // } // // @Override // public Response getResponse(HttpServletRequest request, JsonNode requestBody) { // String path = request.getRequestURI(); // ProxyBean proxyBean = proxyRepository.findByKey(path); // Builder requestBuilder = client.target(proxyBean.getUrl()).path(getRequestPath(proxyBean.getPath(), path)) // .request(); // addHeaders(request, requestBuilder); // Entity<JsonNode> entity = Entity.entity(requestBody, getContentType(request)); // Response response = requestBuilder.build(request.getMethod(), entity).invoke(); // response.bufferEntity(); // return response; // } // // private String getRequestPath(String path, String requestedPath) { // if (path.matches("/.+")) { // Pattern pattern = Pattern.compile("/[^/\\.]+(.*)"); // Matcher matcher = pattern.matcher(requestedPath); // if (matcher.matches()) { // return matcher.group(1); // } else { // throw new ProxyPathException(); // } // } // // return null; // } // // private void addHeaders(HttpServletRequest request, Builder requestBuilder) { // Enumeration<String> headerNames = request.getHeaderNames(); // while (headerNames.hasMoreElements()) { // String key = headerNames.nextElement(); // requestBuilder.header(key, request.getHeader(key)); // } // } // // private String getContentType(HttpServletRequest request) { // if (Strings.isNullOrEmpty(request.getContentType())) { // return MediaType.TEXT_PLAIN; // } // // return request.getContentType(); // } // // public boolean exists(String path) { // return proxyRepository.exists(path); // } // // } // Path: src/main/java/org/mockenize/controller/ProxiesController.java import java.util.Collection; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.mockenize.model.ProxyBean; import org.mockenize.service.ProxyService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; package org.mockenize.controller; @Controller @Path("/_mockenize/proxies") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public class ProxiesController { @Autowired
private ProxyService proxyService;
Mockenize/mockenize-server
src/main/java/org/mockenize/controller/ProxiesController.java
// Path: src/main/java/org/mockenize/model/ProxyBean.java // @Data // public class ProxyBean implements Serializable, Cacheable { // // private static final long serialVersionUID = 1L; // // private static final String UNDERLINE = "_"; // // private static final String SLASH = "/"; // // @NotEmpty // private String key; // // @NotEmpty // private String path; // // @NotNull // private String name; // // @NotNull // private URI url; // // @Override // public String getKey() { // return path.toLowerCase().replaceAll(SLASH, UNDERLINE); // } // } // // Path: src/main/java/org/mockenize/service/ProxyService.java // @Service // public class ProxyService implements ResponseService { // // @Autowired // private ProxyRepository proxyRepository; // // @Context // private HttpServletRequest request; // // private Client client = ClientBuilder.newClient(); // // public Collection<ProxyBean> getAll() { // return proxyRepository.findAll(); // } // // public void save(ProxyBean proxyBean) { // proxyRepository.save(proxyBean); // } // // public ProxyBean getByKey(String key) { // return proxyRepository.findByKey(key); // } // // public ProxyBean delete(ProxyBean proxyBean) { // return proxyRepository.delete(proxyBean); // } // // public Collection<ProxyBean> deleteAll(Collection<ProxyBean> proxyBeans) { // Collection<ProxyBean> deletedProxies = new ArrayList<>(); // if(proxyBeans != null && !proxyBeans.isEmpty()) { // for (ProxyBean bean : proxyBeans) { // ProxyBean deleted = proxyRepository.delete(bean); // if(deleted != null) { // deletedProxies.add(deleted); // } // } // } else { // deletedProxies = proxyRepository.deleteAll(); // } // return deletedProxies; // } // // @Override // public Response getResponse(HttpServletRequest request, JsonNode requestBody) { // String path = request.getRequestURI(); // ProxyBean proxyBean = proxyRepository.findByKey(path); // Builder requestBuilder = client.target(proxyBean.getUrl()).path(getRequestPath(proxyBean.getPath(), path)) // .request(); // addHeaders(request, requestBuilder); // Entity<JsonNode> entity = Entity.entity(requestBody, getContentType(request)); // Response response = requestBuilder.build(request.getMethod(), entity).invoke(); // response.bufferEntity(); // return response; // } // // private String getRequestPath(String path, String requestedPath) { // if (path.matches("/.+")) { // Pattern pattern = Pattern.compile("/[^/\\.]+(.*)"); // Matcher matcher = pattern.matcher(requestedPath); // if (matcher.matches()) { // return matcher.group(1); // } else { // throw new ProxyPathException(); // } // } // // return null; // } // // private void addHeaders(HttpServletRequest request, Builder requestBuilder) { // Enumeration<String> headerNames = request.getHeaderNames(); // while (headerNames.hasMoreElements()) { // String key = headerNames.nextElement(); // requestBuilder.header(key, request.getHeader(key)); // } // } // // private String getContentType(HttpServletRequest request) { // if (Strings.isNullOrEmpty(request.getContentType())) { // return MediaType.TEXT_PLAIN; // } // // return request.getContentType(); // } // // public boolean exists(String path) { // return proxyRepository.exists(path); // } // // }
import java.util.Collection; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.mockenize.model.ProxyBean; import org.mockenize.service.ProxyService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller;
package org.mockenize.controller; @Controller @Path("/_mockenize/proxies") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public class ProxiesController { @Autowired private ProxyService proxyService; @GET public Response getAll() {
// Path: src/main/java/org/mockenize/model/ProxyBean.java // @Data // public class ProxyBean implements Serializable, Cacheable { // // private static final long serialVersionUID = 1L; // // private static final String UNDERLINE = "_"; // // private static final String SLASH = "/"; // // @NotEmpty // private String key; // // @NotEmpty // private String path; // // @NotNull // private String name; // // @NotNull // private URI url; // // @Override // public String getKey() { // return path.toLowerCase().replaceAll(SLASH, UNDERLINE); // } // } // // Path: src/main/java/org/mockenize/service/ProxyService.java // @Service // public class ProxyService implements ResponseService { // // @Autowired // private ProxyRepository proxyRepository; // // @Context // private HttpServletRequest request; // // private Client client = ClientBuilder.newClient(); // // public Collection<ProxyBean> getAll() { // return proxyRepository.findAll(); // } // // public void save(ProxyBean proxyBean) { // proxyRepository.save(proxyBean); // } // // public ProxyBean getByKey(String key) { // return proxyRepository.findByKey(key); // } // // public ProxyBean delete(ProxyBean proxyBean) { // return proxyRepository.delete(proxyBean); // } // // public Collection<ProxyBean> deleteAll(Collection<ProxyBean> proxyBeans) { // Collection<ProxyBean> deletedProxies = new ArrayList<>(); // if(proxyBeans != null && !proxyBeans.isEmpty()) { // for (ProxyBean bean : proxyBeans) { // ProxyBean deleted = proxyRepository.delete(bean); // if(deleted != null) { // deletedProxies.add(deleted); // } // } // } else { // deletedProxies = proxyRepository.deleteAll(); // } // return deletedProxies; // } // // @Override // public Response getResponse(HttpServletRequest request, JsonNode requestBody) { // String path = request.getRequestURI(); // ProxyBean proxyBean = proxyRepository.findByKey(path); // Builder requestBuilder = client.target(proxyBean.getUrl()).path(getRequestPath(proxyBean.getPath(), path)) // .request(); // addHeaders(request, requestBuilder); // Entity<JsonNode> entity = Entity.entity(requestBody, getContentType(request)); // Response response = requestBuilder.build(request.getMethod(), entity).invoke(); // response.bufferEntity(); // return response; // } // // private String getRequestPath(String path, String requestedPath) { // if (path.matches("/.+")) { // Pattern pattern = Pattern.compile("/[^/\\.]+(.*)"); // Matcher matcher = pattern.matcher(requestedPath); // if (matcher.matches()) { // return matcher.group(1); // } else { // throw new ProxyPathException(); // } // } // // return null; // } // // private void addHeaders(HttpServletRequest request, Builder requestBuilder) { // Enumeration<String> headerNames = request.getHeaderNames(); // while (headerNames.hasMoreElements()) { // String key = headerNames.nextElement(); // requestBuilder.header(key, request.getHeader(key)); // } // } // // private String getContentType(HttpServletRequest request) { // if (Strings.isNullOrEmpty(request.getContentType())) { // return MediaType.TEXT_PLAIN; // } // // return request.getContentType(); // } // // public boolean exists(String path) { // return proxyRepository.exists(path); // } // // } // Path: src/main/java/org/mockenize/controller/ProxiesController.java import java.util.Collection; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.mockenize.model.ProxyBean; import org.mockenize.service.ProxyService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; package org.mockenize.controller; @Controller @Path("/_mockenize/proxies") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public class ProxiesController { @Autowired private ProxyService proxyService; @GET public Response getAll() {
Iterable<ProxyBean> proxys = proxyService.getAll();
Mockenize/mockenize-server
src/main/java/org/mockenize/provider/mapper/ExceptionMapperImpl.java
// Path: src/main/java/org/mockenize/model/ReturnBean.java // public class ReturnBean implements Serializable { // // private static final long serialVersionUID = 1L; // // private String message; // // @JsonInclude(Include.NON_NULL) // private Class<?> exceptionClass; // // public ReturnBean(Throwable throwable) { // message = throwable.getMessage(); // exceptionClass = throwable.getClass(); // } // // public ReturnBean(String message) { // this.message = message; // } // // public String getMessage() { // return message; // } // // public void setMessage(String message) { // this.message = message; // } // // public Class<?> getExceptionClass() { // return exceptionClass; // } // // public void setExceptionClass(Class<?> exceptionClass) { // this.exceptionClass = exceptionClass; // } // // }
import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.mockenize.model.ReturnBean; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
package org.mockenize.provider.mapper; public class ExceptionMapperImpl implements javax.ws.rs.ext.ExceptionMapper<Throwable> { private static final Logger LOGGER = LoggerFactory.getLogger(ExceptionMapperImpl.class); private static final String CONTENT_TYPE = "Content-Type"; @Override public Response toResponse(Throwable throwable) { LOGGER.error(throwable.getMessage(), throwable); int status = Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(); if (throwable instanceof WebApplicationException) { status = ((WebApplicationException) throwable).getResponse().getStatus(); }
// Path: src/main/java/org/mockenize/model/ReturnBean.java // public class ReturnBean implements Serializable { // // private static final long serialVersionUID = 1L; // // private String message; // // @JsonInclude(Include.NON_NULL) // private Class<?> exceptionClass; // // public ReturnBean(Throwable throwable) { // message = throwable.getMessage(); // exceptionClass = throwable.getClass(); // } // // public ReturnBean(String message) { // this.message = message; // } // // public String getMessage() { // return message; // } // // public void setMessage(String message) { // this.message = message; // } // // public Class<?> getExceptionClass() { // return exceptionClass; // } // // public void setExceptionClass(Class<?> exceptionClass) { // this.exceptionClass = exceptionClass; // } // // } // Path: src/main/java/org/mockenize/provider/mapper/ExceptionMapperImpl.java import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.mockenize.model.ReturnBean; import org.slf4j.Logger; import org.slf4j.LoggerFactory; package org.mockenize.provider.mapper; public class ExceptionMapperImpl implements javax.ws.rs.ext.ExceptionMapper<Throwable> { private static final Logger LOGGER = LoggerFactory.getLogger(ExceptionMapperImpl.class); private static final String CONTENT_TYPE = "Content-Type"; @Override public Response toResponse(Throwable throwable) { LOGGER.error(throwable.getMessage(), throwable); int status = Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(); if (throwable instanceof WebApplicationException) { status = ((WebApplicationException) throwable).getResponse().getStatus(); }
return Response.status(status).header(CONTENT_TYPE, MediaType.APPLICATION_JSON).entity(new ReturnBean(throwable)).build();
Mockenize/mockenize-server
src/main/java/org/mockenize/service/FileService.java
// Path: src/main/java/org/mockenize/model/MultipleMockBean.java // @Data // @EqualsAndHashCode(callSuper = true) // public class MultipleMockBean extends MockBean { // // private List<MockBean> values = Collections.emptyList(); // // private boolean random; // // private int lastIndexResponse = -1; // // public int nextIndex() { // if (++lastIndexResponse >= values.size()) { // lastIndexResponse = 0; // } // return lastIndexResponse; // } // // public List<MockBean> getValues() { // if (!values.isEmpty()) { // for (MockBean mockBean : values) { // mockBean.setMethod(getMethod()); // mockBean.setPath(getPath()); // } // } // return this.values; // } // }
import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Arrays; import java.util.Collection; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.mockenize.model.MultipleMockBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.io.CharStreams;
package org.mockenize.service; @Service public class FileService { @Autowired private MockService mockService; @Autowired private ObjectMapper mapper = new ObjectMapper(); private Log log = LogFactory.getLog(getClass()); public void loadFile(File file) { if (file != null && file.exists()) { if (file.isFile() && file.canRead()) { try (FileInputStream fileInputStream = new FileInputStream(file)) { String json = CharStreams.toString(new InputStreamReader(fileInputStream)); read(json); } catch (IOException e) { log.error(e); } } else { for (File f : file.listFiles()) { loadFile(f); } } } }
// Path: src/main/java/org/mockenize/model/MultipleMockBean.java // @Data // @EqualsAndHashCode(callSuper = true) // public class MultipleMockBean extends MockBean { // // private List<MockBean> values = Collections.emptyList(); // // private boolean random; // // private int lastIndexResponse = -1; // // public int nextIndex() { // if (++lastIndexResponse >= values.size()) { // lastIndexResponse = 0; // } // return lastIndexResponse; // } // // public List<MockBean> getValues() { // if (!values.isEmpty()) { // for (MockBean mockBean : values) { // mockBean.setMethod(getMethod()); // mockBean.setPath(getPath()); // } // } // return this.values; // } // } // Path: src/main/java/org/mockenize/service/FileService.java import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Arrays; import java.util.Collection; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.mockenize.model.MultipleMockBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.io.CharStreams; package org.mockenize.service; @Service public class FileService { @Autowired private MockService mockService; @Autowired private ObjectMapper mapper = new ObjectMapper(); private Log log = LogFactory.getLog(getClass()); public void loadFile(File file) { if (file != null && file.exists()) { if (file.isFile() && file.canRead()) { try (FileInputStream fileInputStream = new FileInputStream(file)) { String json = CharStreams.toString(new InputStreamReader(fileInputStream)); read(json); } catch (IOException e) { log.error(e); } } else { for (File f : file.listFiles()) { loadFile(f); } } } }
public Collection<MultipleMockBean> loadFile(InputStream fileInputStream) throws IOException {
Mockenize/mockenize-server
src/main/java/org/mockenize/repository/MockRepository.java
// Path: src/main/java/org/mockenize/model/MockBean.java // @Data // public class MockBean implements Cacheable { // // private static final String UNDERLINE = "_"; // // private static final String SLASH = "/"; // // @NotNull // private String key; // // @NotNull // private String path; // // @NotNull // private String method; // // private Map<String, String> headers = Collections.emptyMap(); // // private JsonNode body; // // @NotNull // private Integer status = 200; // // private int timeout = 0; // // private int minTimeout = 0; // // private int maxTimeout = 0; // // private String scriptName; // // @Override // public String getKey() { // return method.concat(path.replaceAll(SLASH, UNDERLINE)); // } // // public void setPath(String path) { // if (path != null && !path.startsWith(SLASH)) { // this.path = SLASH + path; // } else { // this.path = path; // } // } // // } // // Path: src/main/java/org/mockenize/vendor/hazelcast/predicate/PathPredicate.java // public class PathPredicate implements Predicate<String, Object> { // // private static final long serialVersionUID = 4605050326503577349L; // private final String value; // // public PathPredicate(String value) { // this.value = value.replaceAll("/", "_"); // } // // public PathPredicate(String... segments) { // StringBuilder stringBuilder = new StringBuilder(); // for (String segment : segments) { // stringBuilder.append(segment); // } // this.value = stringBuilder.toString().replaceAll("/", "_"); // } // // @Override // public boolean apply(Map.Entry<String, Object> mapEntry) { // return value.matches(mapEntry.getKey().replace("*", "[^/]+")); // } // }
import java.util.Collection; import java.util.Iterator; import org.mockenize.model.MockBean; import org.mockenize.vendor.hazelcast.predicate.PathPredicate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import com.hazelcast.core.HazelcastInstance;
package org.mockenize.repository; @Repository public class MockRepository extends AbstractRepository<MockBean> { public static final String MAP_KEY = "mocks"; @Autowired public MockRepository(HazelcastInstance hazelcastInstance) { super(hazelcastInstance, MAP_KEY); } public MockBean findByMethodAndPath(String method, String path) {
// Path: src/main/java/org/mockenize/model/MockBean.java // @Data // public class MockBean implements Cacheable { // // private static final String UNDERLINE = "_"; // // private static final String SLASH = "/"; // // @NotNull // private String key; // // @NotNull // private String path; // // @NotNull // private String method; // // private Map<String, String> headers = Collections.emptyMap(); // // private JsonNode body; // // @NotNull // private Integer status = 200; // // private int timeout = 0; // // private int minTimeout = 0; // // private int maxTimeout = 0; // // private String scriptName; // // @Override // public String getKey() { // return method.concat(path.replaceAll(SLASH, UNDERLINE)); // } // // public void setPath(String path) { // if (path != null && !path.startsWith(SLASH)) { // this.path = SLASH + path; // } else { // this.path = path; // } // } // // } // // Path: src/main/java/org/mockenize/vendor/hazelcast/predicate/PathPredicate.java // public class PathPredicate implements Predicate<String, Object> { // // private static final long serialVersionUID = 4605050326503577349L; // private final String value; // // public PathPredicate(String value) { // this.value = value.replaceAll("/", "_"); // } // // public PathPredicate(String... segments) { // StringBuilder stringBuilder = new StringBuilder(); // for (String segment : segments) { // stringBuilder.append(segment); // } // this.value = stringBuilder.toString().replaceAll("/", "_"); // } // // @Override // public boolean apply(Map.Entry<String, Object> mapEntry) { // return value.matches(mapEntry.getKey().replace("*", "[^/]+")); // } // } // Path: src/main/java/org/mockenize/repository/MockRepository.java import java.util.Collection; import java.util.Iterator; import org.mockenize.model.MockBean; import org.mockenize.vendor.hazelcast.predicate.PathPredicate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import com.hazelcast.core.HazelcastInstance; package org.mockenize.repository; @Repository public class MockRepository extends AbstractRepository<MockBean> { public static final String MAP_KEY = "mocks"; @Autowired public MockRepository(HazelcastInstance hazelcastInstance) { super(hazelcastInstance, MAP_KEY); } public MockBean findByMethodAndPath(String method, String path) {
Collection<MockBean> values = map.values(new PathPredicate(method, path));
Mockenize/mockenize-server
src/main/java/org/mockenize/service/RequestLogService.java
// Path: src/main/java/org/mockenize/model/LogBean.java // @Data // public class LogBean implements Serializable, Cacheable { // // private static final long serialVersionUID = 1L; // // private String key; // // private LogType type; // // private String url; // // private String path; // // private String method; // // private RequestLogBean request; // // private ResponseLogBean response; // // private Date date = new Date(); // // protected LogBean() { // } // // public LogBean(UUID key, LogType type) { // this.key = key.toString(); // this.type = type; // } // // } // // Path: src/main/java/org/mockenize/repository/RequestLogRepository.java // @Repository // public class RequestLogRepository { // // private static final String CACHE_KEY = "request-log"; // // private final IQueue<Object> queue; // // @Autowired // public RequestLogRepository(HazelcastInstance hazelcastInstance) { // queue = hazelcastInstance.getQueue(CACHE_KEY); // } // // public void save(LogBean requestLogBean) { // queue.add(requestLogBean); // } // }
import org.mockenize.model.LogBean; import org.mockenize.repository.RequestLogRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service;
package org.mockenize.service; @Service public class RequestLogService { @Autowired
// Path: src/main/java/org/mockenize/model/LogBean.java // @Data // public class LogBean implements Serializable, Cacheable { // // private static final long serialVersionUID = 1L; // // private String key; // // private LogType type; // // private String url; // // private String path; // // private String method; // // private RequestLogBean request; // // private ResponseLogBean response; // // private Date date = new Date(); // // protected LogBean() { // } // // public LogBean(UUID key, LogType type) { // this.key = key.toString(); // this.type = type; // } // // } // // Path: src/main/java/org/mockenize/repository/RequestLogRepository.java // @Repository // public class RequestLogRepository { // // private static final String CACHE_KEY = "request-log"; // // private final IQueue<Object> queue; // // @Autowired // public RequestLogRepository(HazelcastInstance hazelcastInstance) { // queue = hazelcastInstance.getQueue(CACHE_KEY); // } // // public void save(LogBean requestLogBean) { // queue.add(requestLogBean); // } // } // Path: src/main/java/org/mockenize/service/RequestLogService.java import org.mockenize.model.LogBean; import org.mockenize.repository.RequestLogRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; package org.mockenize.service; @Service public class RequestLogService { @Autowired
private RequestLogRepository requestLogRepository;
Mockenize/mockenize-server
src/main/java/org/mockenize/service/RequestLogService.java
// Path: src/main/java/org/mockenize/model/LogBean.java // @Data // public class LogBean implements Serializable, Cacheable { // // private static final long serialVersionUID = 1L; // // private String key; // // private LogType type; // // private String url; // // private String path; // // private String method; // // private RequestLogBean request; // // private ResponseLogBean response; // // private Date date = new Date(); // // protected LogBean() { // } // // public LogBean(UUID key, LogType type) { // this.key = key.toString(); // this.type = type; // } // // } // // Path: src/main/java/org/mockenize/repository/RequestLogRepository.java // @Repository // public class RequestLogRepository { // // private static final String CACHE_KEY = "request-log"; // // private final IQueue<Object> queue; // // @Autowired // public RequestLogRepository(HazelcastInstance hazelcastInstance) { // queue = hazelcastInstance.getQueue(CACHE_KEY); // } // // public void save(LogBean requestLogBean) { // queue.add(requestLogBean); // } // }
import org.mockenize.model.LogBean; import org.mockenize.repository.RequestLogRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service;
package org.mockenize.service; @Service public class RequestLogService { @Autowired private RequestLogRepository requestLogRepository;
// Path: src/main/java/org/mockenize/model/LogBean.java // @Data // public class LogBean implements Serializable, Cacheable { // // private static final long serialVersionUID = 1L; // // private String key; // // private LogType type; // // private String url; // // private String path; // // private String method; // // private RequestLogBean request; // // private ResponseLogBean response; // // private Date date = new Date(); // // protected LogBean() { // } // // public LogBean(UUID key, LogType type) { // this.key = key.toString(); // this.type = type; // } // // } // // Path: src/main/java/org/mockenize/repository/RequestLogRepository.java // @Repository // public class RequestLogRepository { // // private static final String CACHE_KEY = "request-log"; // // private final IQueue<Object> queue; // // @Autowired // public RequestLogRepository(HazelcastInstance hazelcastInstance) { // queue = hazelcastInstance.getQueue(CACHE_KEY); // } // // public void save(LogBean requestLogBean) { // queue.add(requestLogBean); // } // } // Path: src/main/java/org/mockenize/service/RequestLogService.java import org.mockenize.model.LogBean; import org.mockenize.repository.RequestLogRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; package org.mockenize.service; @Service public class RequestLogService { @Autowired private RequestLogRepository requestLogRepository;
public void save(LogBean logBean) {
Mockenize/mockenize-server
src/main/java/org/mockenize/listener/LoadFileListener.java
// Path: src/main/java/org/mockenize/service/FileService.java // @Service // public class FileService { // // @Autowired // private MockService mockService; // // @Autowired // private ObjectMapper mapper = new ObjectMapper(); // // private Log log = LogFactory.getLog(getClass()); // // public void loadFile(File file) { // if (file != null && file.exists()) { // if (file.isFile() && file.canRead()) { // try (FileInputStream fileInputStream = new FileInputStream(file)) { // String json = CharStreams.toString(new InputStreamReader(fileInputStream)); // read(json); // } catch (IOException e) { // log.error(e); // } // } else { // for (File f : file.listFiles()) { // loadFile(f); // } // } // } // } // // public Collection<MultipleMockBean> loadFile(InputStream fileInputStream) throws IOException { // String json = CharStreams.toString(new InputStreamReader(fileInputStream)); // return read(json); // } // // private Collection<MultipleMockBean> read(String json) throws IOException { // if(json.startsWith("[")) { // Collection<MultipleMockBean> multipleMockBeans = mapper.readValue(json, new TypeReference<List<MultipleMockBean>>(){}); // for (MultipleMockBean mockBean : multipleMockBeans) { // mockService.save(mockBean); // } // return multipleMockBeans; // } else { // MultipleMockBean mockBean = mapper.readValue(json, MultipleMockBean.class); // Arrays.asList(mockService.save(mockBean)); // } // return Arrays.asList(); // } // }
import java.io.File; import org.mockenize.service.FileService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.stereotype.Component;
package org.mockenize.listener; @Component public class LoadFileListener implements ApplicationListener<ContextRefreshedEvent> { @Value("${default.file}") private File file; @Autowired
// Path: src/main/java/org/mockenize/service/FileService.java // @Service // public class FileService { // // @Autowired // private MockService mockService; // // @Autowired // private ObjectMapper mapper = new ObjectMapper(); // // private Log log = LogFactory.getLog(getClass()); // // public void loadFile(File file) { // if (file != null && file.exists()) { // if (file.isFile() && file.canRead()) { // try (FileInputStream fileInputStream = new FileInputStream(file)) { // String json = CharStreams.toString(new InputStreamReader(fileInputStream)); // read(json); // } catch (IOException e) { // log.error(e); // } // } else { // for (File f : file.listFiles()) { // loadFile(f); // } // } // } // } // // public Collection<MultipleMockBean> loadFile(InputStream fileInputStream) throws IOException { // String json = CharStreams.toString(new InputStreamReader(fileInputStream)); // return read(json); // } // // private Collection<MultipleMockBean> read(String json) throws IOException { // if(json.startsWith("[")) { // Collection<MultipleMockBean> multipleMockBeans = mapper.readValue(json, new TypeReference<List<MultipleMockBean>>(){}); // for (MultipleMockBean mockBean : multipleMockBeans) { // mockService.save(mockBean); // } // return multipleMockBeans; // } else { // MultipleMockBean mockBean = mapper.readValue(json, MultipleMockBean.class); // Arrays.asList(mockService.save(mockBean)); // } // return Arrays.asList(); // } // } // Path: src/main/java/org/mockenize/listener/LoadFileListener.java import java.io.File; import org.mockenize.service.FileService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.stereotype.Component; package org.mockenize.listener; @Component public class LoadFileListener implements ApplicationListener<ContextRefreshedEvent> { @Value("${default.file}") private File file; @Autowired
private FileService loadFileService;
Mockenize/mockenize-server
src/main/java/org/mockenize/service/MockService.java
// Path: src/main/java/org/mockenize/model/MockBean.java // @Data // public class MockBean implements Cacheable { // // private static final String UNDERLINE = "_"; // // private static final String SLASH = "/"; // // @NotNull // private String key; // // @NotNull // private String path; // // @NotNull // private String method; // // private Map<String, String> headers = Collections.emptyMap(); // // private JsonNode body; // // @NotNull // private Integer status = 200; // // private int timeout = 0; // // private int minTimeout = 0; // // private int maxTimeout = 0; // // private String scriptName; // // @Override // public String getKey() { // return method.concat(path.replaceAll(SLASH, UNDERLINE)); // } // // public void setPath(String path) { // if (path != null && !path.startsWith(SLASH)) { // this.path = SLASH + path; // } else { // this.path = path; // } // } // // } // // Path: src/main/java/org/mockenize/model/MultipleMockBean.java // @Data // @EqualsAndHashCode(callSuper = true) // public class MultipleMockBean extends MockBean { // // private List<MockBean> values = Collections.emptyList(); // // private boolean random; // // private int lastIndexResponse = -1; // // public int nextIndex() { // if (++lastIndexResponse >= values.size()) { // lastIndexResponse = 0; // } // return lastIndexResponse; // } // // public List<MockBean> getValues() { // if (!values.isEmpty()) { // for (MockBean mockBean : values) { // mockBean.setMethod(getMethod()); // mockBean.setPath(getPath()); // } // } // return this.values; // } // } // // Path: src/main/java/org/mockenize/model/ScriptBean.java // @Data // public class ScriptBean implements Serializable, Cacheable { // // private static final long serialVersionUID = 1L; // // private String name; // // private String value; // // public ScriptBean(String name, String value) { // this.name = name; // this.value = value; // } // // @Override // public String getKey() { // return this.name; // } // } // // Path: src/main/java/org/mockenize/repository/MockRepository.java // @Repository // public class MockRepository extends AbstractRepository<MockBean> { // // public static final String MAP_KEY = "mocks"; // // @Autowired // public MockRepository(HazelcastInstance hazelcastInstance) { // super(hazelcastInstance, MAP_KEY); // } // // public MockBean findByMethodAndPath(String method, String path) { // Collection<MockBean> values = map.values(new PathPredicate(method, path)); // Iterator<MockBean> iterator = values.iterator(); // return iterator.hasNext() ? iterator.next() : null; // } // // }
import java.util.ArrayList; import java.util.Collection; import java.util.Map; import java.util.Map.Entry; import java.util.Random; import java.util.concurrent.ThreadLocalRandom; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.ResponseBuilder; import org.mockenize.model.MockBean; import org.mockenize.model.MultipleMockBean; import org.mockenize.model.ScriptBean; import org.mockenize.repository.MockRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.fasterxml.jackson.databind.JsonNode; import com.google.common.base.Strings;
package org.mockenize.service; @Service public class MockService implements ResponseService { private static final Logger LOGGER = LoggerFactory.getLogger(MockService.class); private static final int FIRST = 0; @Autowired
// Path: src/main/java/org/mockenize/model/MockBean.java // @Data // public class MockBean implements Cacheable { // // private static final String UNDERLINE = "_"; // // private static final String SLASH = "/"; // // @NotNull // private String key; // // @NotNull // private String path; // // @NotNull // private String method; // // private Map<String, String> headers = Collections.emptyMap(); // // private JsonNode body; // // @NotNull // private Integer status = 200; // // private int timeout = 0; // // private int minTimeout = 0; // // private int maxTimeout = 0; // // private String scriptName; // // @Override // public String getKey() { // return method.concat(path.replaceAll(SLASH, UNDERLINE)); // } // // public void setPath(String path) { // if (path != null && !path.startsWith(SLASH)) { // this.path = SLASH + path; // } else { // this.path = path; // } // } // // } // // Path: src/main/java/org/mockenize/model/MultipleMockBean.java // @Data // @EqualsAndHashCode(callSuper = true) // public class MultipleMockBean extends MockBean { // // private List<MockBean> values = Collections.emptyList(); // // private boolean random; // // private int lastIndexResponse = -1; // // public int nextIndex() { // if (++lastIndexResponse >= values.size()) { // lastIndexResponse = 0; // } // return lastIndexResponse; // } // // public List<MockBean> getValues() { // if (!values.isEmpty()) { // for (MockBean mockBean : values) { // mockBean.setMethod(getMethod()); // mockBean.setPath(getPath()); // } // } // return this.values; // } // } // // Path: src/main/java/org/mockenize/model/ScriptBean.java // @Data // public class ScriptBean implements Serializable, Cacheable { // // private static final long serialVersionUID = 1L; // // private String name; // // private String value; // // public ScriptBean(String name, String value) { // this.name = name; // this.value = value; // } // // @Override // public String getKey() { // return this.name; // } // } // // Path: src/main/java/org/mockenize/repository/MockRepository.java // @Repository // public class MockRepository extends AbstractRepository<MockBean> { // // public static final String MAP_KEY = "mocks"; // // @Autowired // public MockRepository(HazelcastInstance hazelcastInstance) { // super(hazelcastInstance, MAP_KEY); // } // // public MockBean findByMethodAndPath(String method, String path) { // Collection<MockBean> values = map.values(new PathPredicate(method, path)); // Iterator<MockBean> iterator = values.iterator(); // return iterator.hasNext() ? iterator.next() : null; // } // // } // Path: src/main/java/org/mockenize/service/MockService.java import java.util.ArrayList; import java.util.Collection; import java.util.Map; import java.util.Map.Entry; import java.util.Random; import java.util.concurrent.ThreadLocalRandom; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.ResponseBuilder; import org.mockenize.model.MockBean; import org.mockenize.model.MultipleMockBean; import org.mockenize.model.ScriptBean; import org.mockenize.repository.MockRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.fasterxml.jackson.databind.JsonNode; import com.google.common.base.Strings; package org.mockenize.service; @Service public class MockService implements ResponseService { private static final Logger LOGGER = LoggerFactory.getLogger(MockService.class); private static final int FIRST = 0; @Autowired
private MockRepository mockRepository;
Mockenize/mockenize-server
src/main/java/org/mockenize/service/MockService.java
// Path: src/main/java/org/mockenize/model/MockBean.java // @Data // public class MockBean implements Cacheable { // // private static final String UNDERLINE = "_"; // // private static final String SLASH = "/"; // // @NotNull // private String key; // // @NotNull // private String path; // // @NotNull // private String method; // // private Map<String, String> headers = Collections.emptyMap(); // // private JsonNode body; // // @NotNull // private Integer status = 200; // // private int timeout = 0; // // private int minTimeout = 0; // // private int maxTimeout = 0; // // private String scriptName; // // @Override // public String getKey() { // return method.concat(path.replaceAll(SLASH, UNDERLINE)); // } // // public void setPath(String path) { // if (path != null && !path.startsWith(SLASH)) { // this.path = SLASH + path; // } else { // this.path = path; // } // } // // } // // Path: src/main/java/org/mockenize/model/MultipleMockBean.java // @Data // @EqualsAndHashCode(callSuper = true) // public class MultipleMockBean extends MockBean { // // private List<MockBean> values = Collections.emptyList(); // // private boolean random; // // private int lastIndexResponse = -1; // // public int nextIndex() { // if (++lastIndexResponse >= values.size()) { // lastIndexResponse = 0; // } // return lastIndexResponse; // } // // public List<MockBean> getValues() { // if (!values.isEmpty()) { // for (MockBean mockBean : values) { // mockBean.setMethod(getMethod()); // mockBean.setPath(getPath()); // } // } // return this.values; // } // } // // Path: src/main/java/org/mockenize/model/ScriptBean.java // @Data // public class ScriptBean implements Serializable, Cacheable { // // private static final long serialVersionUID = 1L; // // private String name; // // private String value; // // public ScriptBean(String name, String value) { // this.name = name; // this.value = value; // } // // @Override // public String getKey() { // return this.name; // } // } // // Path: src/main/java/org/mockenize/repository/MockRepository.java // @Repository // public class MockRepository extends AbstractRepository<MockBean> { // // public static final String MAP_KEY = "mocks"; // // @Autowired // public MockRepository(HazelcastInstance hazelcastInstance) { // super(hazelcastInstance, MAP_KEY); // } // // public MockBean findByMethodAndPath(String method, String path) { // Collection<MockBean> values = map.values(new PathPredicate(method, path)); // Iterator<MockBean> iterator = values.iterator(); // return iterator.hasNext() ? iterator.next() : null; // } // // }
import java.util.ArrayList; import java.util.Collection; import java.util.Map; import java.util.Map.Entry; import java.util.Random; import java.util.concurrent.ThreadLocalRandom; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.ResponseBuilder; import org.mockenize.model.MockBean; import org.mockenize.model.MultipleMockBean; import org.mockenize.model.ScriptBean; import org.mockenize.repository.MockRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.fasterxml.jackson.databind.JsonNode; import com.google.common.base.Strings;
package org.mockenize.service; @Service public class MockService implements ResponseService { private static final Logger LOGGER = LoggerFactory.getLogger(MockService.class); private static final int FIRST = 0; @Autowired private MockRepository mockRepository; @Autowired private ScriptService scriptService; private Random random = new Random();
// Path: src/main/java/org/mockenize/model/MockBean.java // @Data // public class MockBean implements Cacheable { // // private static final String UNDERLINE = "_"; // // private static final String SLASH = "/"; // // @NotNull // private String key; // // @NotNull // private String path; // // @NotNull // private String method; // // private Map<String, String> headers = Collections.emptyMap(); // // private JsonNode body; // // @NotNull // private Integer status = 200; // // private int timeout = 0; // // private int minTimeout = 0; // // private int maxTimeout = 0; // // private String scriptName; // // @Override // public String getKey() { // return method.concat(path.replaceAll(SLASH, UNDERLINE)); // } // // public void setPath(String path) { // if (path != null && !path.startsWith(SLASH)) { // this.path = SLASH + path; // } else { // this.path = path; // } // } // // } // // Path: src/main/java/org/mockenize/model/MultipleMockBean.java // @Data // @EqualsAndHashCode(callSuper = true) // public class MultipleMockBean extends MockBean { // // private List<MockBean> values = Collections.emptyList(); // // private boolean random; // // private int lastIndexResponse = -1; // // public int nextIndex() { // if (++lastIndexResponse >= values.size()) { // lastIndexResponse = 0; // } // return lastIndexResponse; // } // // public List<MockBean> getValues() { // if (!values.isEmpty()) { // for (MockBean mockBean : values) { // mockBean.setMethod(getMethod()); // mockBean.setPath(getPath()); // } // } // return this.values; // } // } // // Path: src/main/java/org/mockenize/model/ScriptBean.java // @Data // public class ScriptBean implements Serializable, Cacheable { // // private static final long serialVersionUID = 1L; // // private String name; // // private String value; // // public ScriptBean(String name, String value) { // this.name = name; // this.value = value; // } // // @Override // public String getKey() { // return this.name; // } // } // // Path: src/main/java/org/mockenize/repository/MockRepository.java // @Repository // public class MockRepository extends AbstractRepository<MockBean> { // // public static final String MAP_KEY = "mocks"; // // @Autowired // public MockRepository(HazelcastInstance hazelcastInstance) { // super(hazelcastInstance, MAP_KEY); // } // // public MockBean findByMethodAndPath(String method, String path) { // Collection<MockBean> values = map.values(new PathPredicate(method, path)); // Iterator<MockBean> iterator = values.iterator(); // return iterator.hasNext() ? iterator.next() : null; // } // // } // Path: src/main/java/org/mockenize/service/MockService.java import java.util.ArrayList; import java.util.Collection; import java.util.Map; import java.util.Map.Entry; import java.util.Random; import java.util.concurrent.ThreadLocalRandom; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.ResponseBuilder; import org.mockenize.model.MockBean; import org.mockenize.model.MultipleMockBean; import org.mockenize.model.ScriptBean; import org.mockenize.repository.MockRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.fasterxml.jackson.databind.JsonNode; import com.google.common.base.Strings; package org.mockenize.service; @Service public class MockService implements ResponseService { private static final Logger LOGGER = LoggerFactory.getLogger(MockService.class); private static final int FIRST = 0; @Autowired private MockRepository mockRepository; @Autowired private ScriptService scriptService; private Random random = new Random();
public MockBean getByKey(String key) {
Mockenize/mockenize-server
src/main/java/org/mockenize/service/MockService.java
// Path: src/main/java/org/mockenize/model/MockBean.java // @Data // public class MockBean implements Cacheable { // // private static final String UNDERLINE = "_"; // // private static final String SLASH = "/"; // // @NotNull // private String key; // // @NotNull // private String path; // // @NotNull // private String method; // // private Map<String, String> headers = Collections.emptyMap(); // // private JsonNode body; // // @NotNull // private Integer status = 200; // // private int timeout = 0; // // private int minTimeout = 0; // // private int maxTimeout = 0; // // private String scriptName; // // @Override // public String getKey() { // return method.concat(path.replaceAll(SLASH, UNDERLINE)); // } // // public void setPath(String path) { // if (path != null && !path.startsWith(SLASH)) { // this.path = SLASH + path; // } else { // this.path = path; // } // } // // } // // Path: src/main/java/org/mockenize/model/MultipleMockBean.java // @Data // @EqualsAndHashCode(callSuper = true) // public class MultipleMockBean extends MockBean { // // private List<MockBean> values = Collections.emptyList(); // // private boolean random; // // private int lastIndexResponse = -1; // // public int nextIndex() { // if (++lastIndexResponse >= values.size()) { // lastIndexResponse = 0; // } // return lastIndexResponse; // } // // public List<MockBean> getValues() { // if (!values.isEmpty()) { // for (MockBean mockBean : values) { // mockBean.setMethod(getMethod()); // mockBean.setPath(getPath()); // } // } // return this.values; // } // } // // Path: src/main/java/org/mockenize/model/ScriptBean.java // @Data // public class ScriptBean implements Serializable, Cacheable { // // private static final long serialVersionUID = 1L; // // private String name; // // private String value; // // public ScriptBean(String name, String value) { // this.name = name; // this.value = value; // } // // @Override // public String getKey() { // return this.name; // } // } // // Path: src/main/java/org/mockenize/repository/MockRepository.java // @Repository // public class MockRepository extends AbstractRepository<MockBean> { // // public static final String MAP_KEY = "mocks"; // // @Autowired // public MockRepository(HazelcastInstance hazelcastInstance) { // super(hazelcastInstance, MAP_KEY); // } // // public MockBean findByMethodAndPath(String method, String path) { // Collection<MockBean> values = map.values(new PathPredicate(method, path)); // Iterator<MockBean> iterator = values.iterator(); // return iterator.hasNext() ? iterator.next() : null; // } // // }
import java.util.ArrayList; import java.util.Collection; import java.util.Map; import java.util.Map.Entry; import java.util.Random; import java.util.concurrent.ThreadLocalRandom; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.ResponseBuilder; import org.mockenize.model.MockBean; import org.mockenize.model.MultipleMockBean; import org.mockenize.model.ScriptBean; import org.mockenize.repository.MockRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.fasterxml.jackson.databind.JsonNode; import com.google.common.base.Strings;
package org.mockenize.service; @Service public class MockService implements ResponseService { private static final Logger LOGGER = LoggerFactory.getLogger(MockService.class); private static final int FIRST = 0; @Autowired private MockRepository mockRepository; @Autowired private ScriptService scriptService; private Random random = new Random(); public MockBean getByKey(String key) { return mockRepository.findByKey(key); } public MockBean getByMethodAndPath(String method, String path) { MockBean mockBean = mockRepository.findByMethodAndPath(method, path);
// Path: src/main/java/org/mockenize/model/MockBean.java // @Data // public class MockBean implements Cacheable { // // private static final String UNDERLINE = "_"; // // private static final String SLASH = "/"; // // @NotNull // private String key; // // @NotNull // private String path; // // @NotNull // private String method; // // private Map<String, String> headers = Collections.emptyMap(); // // private JsonNode body; // // @NotNull // private Integer status = 200; // // private int timeout = 0; // // private int minTimeout = 0; // // private int maxTimeout = 0; // // private String scriptName; // // @Override // public String getKey() { // return method.concat(path.replaceAll(SLASH, UNDERLINE)); // } // // public void setPath(String path) { // if (path != null && !path.startsWith(SLASH)) { // this.path = SLASH + path; // } else { // this.path = path; // } // } // // } // // Path: src/main/java/org/mockenize/model/MultipleMockBean.java // @Data // @EqualsAndHashCode(callSuper = true) // public class MultipleMockBean extends MockBean { // // private List<MockBean> values = Collections.emptyList(); // // private boolean random; // // private int lastIndexResponse = -1; // // public int nextIndex() { // if (++lastIndexResponse >= values.size()) { // lastIndexResponse = 0; // } // return lastIndexResponse; // } // // public List<MockBean> getValues() { // if (!values.isEmpty()) { // for (MockBean mockBean : values) { // mockBean.setMethod(getMethod()); // mockBean.setPath(getPath()); // } // } // return this.values; // } // } // // Path: src/main/java/org/mockenize/model/ScriptBean.java // @Data // public class ScriptBean implements Serializable, Cacheable { // // private static final long serialVersionUID = 1L; // // private String name; // // private String value; // // public ScriptBean(String name, String value) { // this.name = name; // this.value = value; // } // // @Override // public String getKey() { // return this.name; // } // } // // Path: src/main/java/org/mockenize/repository/MockRepository.java // @Repository // public class MockRepository extends AbstractRepository<MockBean> { // // public static final String MAP_KEY = "mocks"; // // @Autowired // public MockRepository(HazelcastInstance hazelcastInstance) { // super(hazelcastInstance, MAP_KEY); // } // // public MockBean findByMethodAndPath(String method, String path) { // Collection<MockBean> values = map.values(new PathPredicate(method, path)); // Iterator<MockBean> iterator = values.iterator(); // return iterator.hasNext() ? iterator.next() : null; // } // // } // Path: src/main/java/org/mockenize/service/MockService.java import java.util.ArrayList; import java.util.Collection; import java.util.Map; import java.util.Map.Entry; import java.util.Random; import java.util.concurrent.ThreadLocalRandom; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.ResponseBuilder; import org.mockenize.model.MockBean; import org.mockenize.model.MultipleMockBean; import org.mockenize.model.ScriptBean; import org.mockenize.repository.MockRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.fasterxml.jackson.databind.JsonNode; import com.google.common.base.Strings; package org.mockenize.service; @Service public class MockService implements ResponseService { private static final Logger LOGGER = LoggerFactory.getLogger(MockService.class); private static final int FIRST = 0; @Autowired private MockRepository mockRepository; @Autowired private ScriptService scriptService; private Random random = new Random(); public MockBean getByKey(String key) { return mockRepository.findByKey(key); } public MockBean getByMethodAndPath(String method, String path) { MockBean mockBean = mockRepository.findByMethodAndPath(method, path);
if (mockBean instanceof MultipleMockBean) {
Mockenize/mockenize-server
src/main/java/org/mockenize/service/MockService.java
// Path: src/main/java/org/mockenize/model/MockBean.java // @Data // public class MockBean implements Cacheable { // // private static final String UNDERLINE = "_"; // // private static final String SLASH = "/"; // // @NotNull // private String key; // // @NotNull // private String path; // // @NotNull // private String method; // // private Map<String, String> headers = Collections.emptyMap(); // // private JsonNode body; // // @NotNull // private Integer status = 200; // // private int timeout = 0; // // private int minTimeout = 0; // // private int maxTimeout = 0; // // private String scriptName; // // @Override // public String getKey() { // return method.concat(path.replaceAll(SLASH, UNDERLINE)); // } // // public void setPath(String path) { // if (path != null && !path.startsWith(SLASH)) { // this.path = SLASH + path; // } else { // this.path = path; // } // } // // } // // Path: src/main/java/org/mockenize/model/MultipleMockBean.java // @Data // @EqualsAndHashCode(callSuper = true) // public class MultipleMockBean extends MockBean { // // private List<MockBean> values = Collections.emptyList(); // // private boolean random; // // private int lastIndexResponse = -1; // // public int nextIndex() { // if (++lastIndexResponse >= values.size()) { // lastIndexResponse = 0; // } // return lastIndexResponse; // } // // public List<MockBean> getValues() { // if (!values.isEmpty()) { // for (MockBean mockBean : values) { // mockBean.setMethod(getMethod()); // mockBean.setPath(getPath()); // } // } // return this.values; // } // } // // Path: src/main/java/org/mockenize/model/ScriptBean.java // @Data // public class ScriptBean implements Serializable, Cacheable { // // private static final long serialVersionUID = 1L; // // private String name; // // private String value; // // public ScriptBean(String name, String value) { // this.name = name; // this.value = value; // } // // @Override // public String getKey() { // return this.name; // } // } // // Path: src/main/java/org/mockenize/repository/MockRepository.java // @Repository // public class MockRepository extends AbstractRepository<MockBean> { // // public static final String MAP_KEY = "mocks"; // // @Autowired // public MockRepository(HazelcastInstance hazelcastInstance) { // super(hazelcastInstance, MAP_KEY); // } // // public MockBean findByMethodAndPath(String method, String path) { // Collection<MockBean> values = map.values(new PathPredicate(method, path)); // Iterator<MockBean> iterator = values.iterator(); // return iterator.hasNext() ? iterator.next() : null; // } // // }
import java.util.ArrayList; import java.util.Collection; import java.util.Map; import java.util.Map.Entry; import java.util.Random; import java.util.concurrent.ThreadLocalRandom; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.ResponseBuilder; import org.mockenize.model.MockBean; import org.mockenize.model.MultipleMockBean; import org.mockenize.model.ScriptBean; import org.mockenize.repository.MockRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.fasterxml.jackson.databind.JsonNode; import com.google.common.base.Strings;
return deletedMocks; } public MockBean delete(MockBean mockBean) { return mockRepository.delete(mockBean); } public MockBean delete(String key) { return mockRepository.delete(key); } public Boolean exists(String method, String path) { return mockRepository.exists(toKey(method, path)); } @Override public Response getResponse(HttpServletRequest request, JsonNode requestBody) { MockBean mockBean = getByMethodAndPath(request.getMethod(), request.getRequestURI()); Map<String, String> headers = mockBean.getHeaders(); final ResponseBuilder responseBuilder = Response.status(mockBean.getStatus()); for (Entry<String, String> entry : headers.entrySet()) { responseBuilder.header(entry.getKey(), entry.getValue()); } String contentType = headers.getOrDefault(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_PLAIN); JsonNode responseBody = getResponseBody(mockBean, request.getRequestURI(), requestBody); return responseBuilder.type(contentType).entity(responseBody).build(); } private JsonNode getResponseBody(MockBean mockBean, String path, JsonNode body) { if (!Strings.isNullOrEmpty(mockBean.getScriptName())) {
// Path: src/main/java/org/mockenize/model/MockBean.java // @Data // public class MockBean implements Cacheable { // // private static final String UNDERLINE = "_"; // // private static final String SLASH = "/"; // // @NotNull // private String key; // // @NotNull // private String path; // // @NotNull // private String method; // // private Map<String, String> headers = Collections.emptyMap(); // // private JsonNode body; // // @NotNull // private Integer status = 200; // // private int timeout = 0; // // private int minTimeout = 0; // // private int maxTimeout = 0; // // private String scriptName; // // @Override // public String getKey() { // return method.concat(path.replaceAll(SLASH, UNDERLINE)); // } // // public void setPath(String path) { // if (path != null && !path.startsWith(SLASH)) { // this.path = SLASH + path; // } else { // this.path = path; // } // } // // } // // Path: src/main/java/org/mockenize/model/MultipleMockBean.java // @Data // @EqualsAndHashCode(callSuper = true) // public class MultipleMockBean extends MockBean { // // private List<MockBean> values = Collections.emptyList(); // // private boolean random; // // private int lastIndexResponse = -1; // // public int nextIndex() { // if (++lastIndexResponse >= values.size()) { // lastIndexResponse = 0; // } // return lastIndexResponse; // } // // public List<MockBean> getValues() { // if (!values.isEmpty()) { // for (MockBean mockBean : values) { // mockBean.setMethod(getMethod()); // mockBean.setPath(getPath()); // } // } // return this.values; // } // } // // Path: src/main/java/org/mockenize/model/ScriptBean.java // @Data // public class ScriptBean implements Serializable, Cacheable { // // private static final long serialVersionUID = 1L; // // private String name; // // private String value; // // public ScriptBean(String name, String value) { // this.name = name; // this.value = value; // } // // @Override // public String getKey() { // return this.name; // } // } // // Path: src/main/java/org/mockenize/repository/MockRepository.java // @Repository // public class MockRepository extends AbstractRepository<MockBean> { // // public static final String MAP_KEY = "mocks"; // // @Autowired // public MockRepository(HazelcastInstance hazelcastInstance) { // super(hazelcastInstance, MAP_KEY); // } // // public MockBean findByMethodAndPath(String method, String path) { // Collection<MockBean> values = map.values(new PathPredicate(method, path)); // Iterator<MockBean> iterator = values.iterator(); // return iterator.hasNext() ? iterator.next() : null; // } // // } // Path: src/main/java/org/mockenize/service/MockService.java import java.util.ArrayList; import java.util.Collection; import java.util.Map; import java.util.Map.Entry; import java.util.Random; import java.util.concurrent.ThreadLocalRandom; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.ResponseBuilder; import org.mockenize.model.MockBean; import org.mockenize.model.MultipleMockBean; import org.mockenize.model.ScriptBean; import org.mockenize.repository.MockRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.fasterxml.jackson.databind.JsonNode; import com.google.common.base.Strings; return deletedMocks; } public MockBean delete(MockBean mockBean) { return mockRepository.delete(mockBean); } public MockBean delete(String key) { return mockRepository.delete(key); } public Boolean exists(String method, String path) { return mockRepository.exists(toKey(method, path)); } @Override public Response getResponse(HttpServletRequest request, JsonNode requestBody) { MockBean mockBean = getByMethodAndPath(request.getMethod(), request.getRequestURI()); Map<String, String> headers = mockBean.getHeaders(); final ResponseBuilder responseBuilder = Response.status(mockBean.getStatus()); for (Entry<String, String> entry : headers.entrySet()) { responseBuilder.header(entry.getKey(), entry.getValue()); } String contentType = headers.getOrDefault(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_PLAIN); JsonNode responseBody = getResponseBody(mockBean, request.getRequestURI(), requestBody); return responseBuilder.type(contentType).entity(responseBody).build(); } private JsonNode getResponseBody(MockBean mockBean, String path, JsonNode body) { if (!Strings.isNullOrEmpty(mockBean.getScriptName())) {
ScriptBean scriptBean = scriptService.getByKey(mockBean.getScriptName());
Mockenize/mockenize-server
src/main/java/org/mockenize/controller/ScriptsController.java
// Path: src/main/java/org/mockenize/model/ScriptBean.java // @Data // public class ScriptBean implements Serializable, Cacheable { // // private static final long serialVersionUID = 1L; // // private String name; // // private String value; // // public ScriptBean(String name, String value) { // this.name = name; // this.value = value; // } // // @Override // public String getKey() { // return this.name; // } // } // // Path: src/main/java/org/mockenize/service/ScriptService.java // @Service // public class ScriptService { // // private static final String ENGINE_NAME = "JavaScript"; // // private static final String DEFAUL_FUNCTION_NAME = "_func"; // // private static final String PARSE_FUNCTION = "function _func(url, body) {" // + "obj=null;try{obj=JSON.parse(body)}catch(ex){};" + "ret = func(url, body, obj);" // + "try{return (typeof ret === 'string') ? ret : JSON.stringify(ret)}catch(ex){};" + "return ret};"; // // private static final String EMPTY = ""; // // @Autowired // private ObjectMapper objectMapper; // // @Autowired // private ScriptRespository scriptRespository; // // public ScriptBean getByKey(String jsName) { // ScriptBean scriptBean = scriptRespository.findByKey(jsName); // // if (scriptBean == null) { // throw new ScriptNotFoundException(jsName); // } // // return scriptBean; // } // // public ScriptBean delete(ScriptBean scriptBean) { // return scriptRespository.delete(scriptBean.getName()); // } // // public Collection<ScriptBean> deleteAll() { // return scriptRespository.deleteAll(); // } // // public void save(ScriptBean scriptBean) { // scriptRespository.save(scriptBean); // } // // public Collection<ScriptBean> getAll() { // return scriptRespository.findAll(); // } // // public JsonNode execute(ScriptBean scriptBean, String uri, JsonNode body) { // try { // ScriptEngine scriptEngine = new ScriptEngineManager().getEngineByName(ENGINE_NAME); // scriptEngine.eval(PARSE_FUNCTION + scriptBean.getValue()); // Invocable invocable = (Invocable) scriptEngine; // String stringBody = body != null ? body.toString() : EMPTY; // String ret = String.valueOf(invocable.invokeFunction(DEFAUL_FUNCTION_NAME, uri, stringBody)); // return parse(ret); // } catch (NoSuchMethodException | ScriptException | IOException e) { // throw new ScriptExecutionException(e); // } // } // // private JsonNode parse(String ret) throws IOException { // try { // return objectMapper.readTree(ret); // } catch (JsonParseException parseException) { // return objectMapper.createObjectNode().textNode(ret); // } // } // // public Collection<String> getAllKeys() { // return scriptRespository.findAllKeys(); // } // // }
import java.util.Collection; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.mockenize.model.ScriptBean; import org.mockenize.service.ScriptService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller;
package org.mockenize.controller; @Path("/_mockenize/scripts") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Controller public class ScriptsController { @Autowired
// Path: src/main/java/org/mockenize/model/ScriptBean.java // @Data // public class ScriptBean implements Serializable, Cacheable { // // private static final long serialVersionUID = 1L; // // private String name; // // private String value; // // public ScriptBean(String name, String value) { // this.name = name; // this.value = value; // } // // @Override // public String getKey() { // return this.name; // } // } // // Path: src/main/java/org/mockenize/service/ScriptService.java // @Service // public class ScriptService { // // private static final String ENGINE_NAME = "JavaScript"; // // private static final String DEFAUL_FUNCTION_NAME = "_func"; // // private static final String PARSE_FUNCTION = "function _func(url, body) {" // + "obj=null;try{obj=JSON.parse(body)}catch(ex){};" + "ret = func(url, body, obj);" // + "try{return (typeof ret === 'string') ? ret : JSON.stringify(ret)}catch(ex){};" + "return ret};"; // // private static final String EMPTY = ""; // // @Autowired // private ObjectMapper objectMapper; // // @Autowired // private ScriptRespository scriptRespository; // // public ScriptBean getByKey(String jsName) { // ScriptBean scriptBean = scriptRespository.findByKey(jsName); // // if (scriptBean == null) { // throw new ScriptNotFoundException(jsName); // } // // return scriptBean; // } // // public ScriptBean delete(ScriptBean scriptBean) { // return scriptRespository.delete(scriptBean.getName()); // } // // public Collection<ScriptBean> deleteAll() { // return scriptRespository.deleteAll(); // } // // public void save(ScriptBean scriptBean) { // scriptRespository.save(scriptBean); // } // // public Collection<ScriptBean> getAll() { // return scriptRespository.findAll(); // } // // public JsonNode execute(ScriptBean scriptBean, String uri, JsonNode body) { // try { // ScriptEngine scriptEngine = new ScriptEngineManager().getEngineByName(ENGINE_NAME); // scriptEngine.eval(PARSE_FUNCTION + scriptBean.getValue()); // Invocable invocable = (Invocable) scriptEngine; // String stringBody = body != null ? body.toString() : EMPTY; // String ret = String.valueOf(invocable.invokeFunction(DEFAUL_FUNCTION_NAME, uri, stringBody)); // return parse(ret); // } catch (NoSuchMethodException | ScriptException | IOException e) { // throw new ScriptExecutionException(e); // } // } // // private JsonNode parse(String ret) throws IOException { // try { // return objectMapper.readTree(ret); // } catch (JsonParseException parseException) { // return objectMapper.createObjectNode().textNode(ret); // } // } // // public Collection<String> getAllKeys() { // return scriptRespository.findAllKeys(); // } // // } // Path: src/main/java/org/mockenize/controller/ScriptsController.java import java.util.Collection; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.mockenize.model.ScriptBean; import org.mockenize.service.ScriptService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; package org.mockenize.controller; @Path("/_mockenize/scripts") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Controller public class ScriptsController { @Autowired
private ScriptService scriptService;
Mockenize/mockenize-server
src/main/java/org/mockenize/controller/ScriptsController.java
// Path: src/main/java/org/mockenize/model/ScriptBean.java // @Data // public class ScriptBean implements Serializable, Cacheable { // // private static final long serialVersionUID = 1L; // // private String name; // // private String value; // // public ScriptBean(String name, String value) { // this.name = name; // this.value = value; // } // // @Override // public String getKey() { // return this.name; // } // } // // Path: src/main/java/org/mockenize/service/ScriptService.java // @Service // public class ScriptService { // // private static final String ENGINE_NAME = "JavaScript"; // // private static final String DEFAUL_FUNCTION_NAME = "_func"; // // private static final String PARSE_FUNCTION = "function _func(url, body) {" // + "obj=null;try{obj=JSON.parse(body)}catch(ex){};" + "ret = func(url, body, obj);" // + "try{return (typeof ret === 'string') ? ret : JSON.stringify(ret)}catch(ex){};" + "return ret};"; // // private static final String EMPTY = ""; // // @Autowired // private ObjectMapper objectMapper; // // @Autowired // private ScriptRespository scriptRespository; // // public ScriptBean getByKey(String jsName) { // ScriptBean scriptBean = scriptRespository.findByKey(jsName); // // if (scriptBean == null) { // throw new ScriptNotFoundException(jsName); // } // // return scriptBean; // } // // public ScriptBean delete(ScriptBean scriptBean) { // return scriptRespository.delete(scriptBean.getName()); // } // // public Collection<ScriptBean> deleteAll() { // return scriptRespository.deleteAll(); // } // // public void save(ScriptBean scriptBean) { // scriptRespository.save(scriptBean); // } // // public Collection<ScriptBean> getAll() { // return scriptRespository.findAll(); // } // // public JsonNode execute(ScriptBean scriptBean, String uri, JsonNode body) { // try { // ScriptEngine scriptEngine = new ScriptEngineManager().getEngineByName(ENGINE_NAME); // scriptEngine.eval(PARSE_FUNCTION + scriptBean.getValue()); // Invocable invocable = (Invocable) scriptEngine; // String stringBody = body != null ? body.toString() : EMPTY; // String ret = String.valueOf(invocable.invokeFunction(DEFAUL_FUNCTION_NAME, uri, stringBody)); // return parse(ret); // } catch (NoSuchMethodException | ScriptException | IOException e) { // throw new ScriptExecutionException(e); // } // } // // private JsonNode parse(String ret) throws IOException { // try { // return objectMapper.readTree(ret); // } catch (JsonParseException parseException) { // return objectMapper.createObjectNode().textNode(ret); // } // } // // public Collection<String> getAllKeys() { // return scriptRespository.findAllKeys(); // } // // }
import java.util.Collection; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.mockenize.model.ScriptBean; import org.mockenize.service.ScriptService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller;
package org.mockenize.controller; @Path("/_mockenize/scripts") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Controller public class ScriptsController { @Autowired private ScriptService scriptService; @GET @Path("/name/{scriptName}") @Produces(MediaType.TEXT_PLAIN) public String getScript(@PathParam("scriptName") String scriptName) { return scriptService.getByKey(scriptName).getValue(); } @GET
// Path: src/main/java/org/mockenize/model/ScriptBean.java // @Data // public class ScriptBean implements Serializable, Cacheable { // // private static final long serialVersionUID = 1L; // // private String name; // // private String value; // // public ScriptBean(String name, String value) { // this.name = name; // this.value = value; // } // // @Override // public String getKey() { // return this.name; // } // } // // Path: src/main/java/org/mockenize/service/ScriptService.java // @Service // public class ScriptService { // // private static final String ENGINE_NAME = "JavaScript"; // // private static final String DEFAUL_FUNCTION_NAME = "_func"; // // private static final String PARSE_FUNCTION = "function _func(url, body) {" // + "obj=null;try{obj=JSON.parse(body)}catch(ex){};" + "ret = func(url, body, obj);" // + "try{return (typeof ret === 'string') ? ret : JSON.stringify(ret)}catch(ex){};" + "return ret};"; // // private static final String EMPTY = ""; // // @Autowired // private ObjectMapper objectMapper; // // @Autowired // private ScriptRespository scriptRespository; // // public ScriptBean getByKey(String jsName) { // ScriptBean scriptBean = scriptRespository.findByKey(jsName); // // if (scriptBean == null) { // throw new ScriptNotFoundException(jsName); // } // // return scriptBean; // } // // public ScriptBean delete(ScriptBean scriptBean) { // return scriptRespository.delete(scriptBean.getName()); // } // // public Collection<ScriptBean> deleteAll() { // return scriptRespository.deleteAll(); // } // // public void save(ScriptBean scriptBean) { // scriptRespository.save(scriptBean); // } // // public Collection<ScriptBean> getAll() { // return scriptRespository.findAll(); // } // // public JsonNode execute(ScriptBean scriptBean, String uri, JsonNode body) { // try { // ScriptEngine scriptEngine = new ScriptEngineManager().getEngineByName(ENGINE_NAME); // scriptEngine.eval(PARSE_FUNCTION + scriptBean.getValue()); // Invocable invocable = (Invocable) scriptEngine; // String stringBody = body != null ? body.toString() : EMPTY; // String ret = String.valueOf(invocable.invokeFunction(DEFAUL_FUNCTION_NAME, uri, stringBody)); // return parse(ret); // } catch (NoSuchMethodException | ScriptException | IOException e) { // throw new ScriptExecutionException(e); // } // } // // private JsonNode parse(String ret) throws IOException { // try { // return objectMapper.readTree(ret); // } catch (JsonParseException parseException) { // return objectMapper.createObjectNode().textNode(ret); // } // } // // public Collection<String> getAllKeys() { // return scriptRespository.findAllKeys(); // } // // } // Path: src/main/java/org/mockenize/controller/ScriptsController.java import java.util.Collection; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.mockenize.model.ScriptBean; import org.mockenize.service.ScriptService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; package org.mockenize.controller; @Path("/_mockenize/scripts") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Controller public class ScriptsController { @Autowired private ScriptService scriptService; @GET @Path("/name/{scriptName}") @Produces(MediaType.TEXT_PLAIN) public String getScript(@PathParam("scriptName") String scriptName) { return scriptService.getByKey(scriptName).getValue(); } @GET
public Collection<ScriptBean> getAll() {
Mockenize/mockenize-server
src/main/java/org/mockenize/repository/RequestLogRepository.java
// Path: src/main/java/org/mockenize/model/LogBean.java // @Data // public class LogBean implements Serializable, Cacheable { // // private static final long serialVersionUID = 1L; // // private String key; // // private LogType type; // // private String url; // // private String path; // // private String method; // // private RequestLogBean request; // // private ResponseLogBean response; // // private Date date = new Date(); // // protected LogBean() { // } // // public LogBean(UUID key, LogType type) { // this.key = key.toString(); // this.type = type; // } // // }
import com.hazelcast.core.HazelcastInstance; import com.hazelcast.core.IQueue; import org.mockenize.model.LogBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository;
package org.mockenize.repository; @Repository public class RequestLogRepository { private static final String CACHE_KEY = "request-log"; private final IQueue<Object> queue; @Autowired public RequestLogRepository(HazelcastInstance hazelcastInstance) { queue = hazelcastInstance.getQueue(CACHE_KEY); }
// Path: src/main/java/org/mockenize/model/LogBean.java // @Data // public class LogBean implements Serializable, Cacheable { // // private static final long serialVersionUID = 1L; // // private String key; // // private LogType type; // // private String url; // // private String path; // // private String method; // // private RequestLogBean request; // // private ResponseLogBean response; // // private Date date = new Date(); // // protected LogBean() { // } // // public LogBean(UUID key, LogType type) { // this.key = key.toString(); // this.type = type; // } // // } // Path: src/main/java/org/mockenize/repository/RequestLogRepository.java import com.hazelcast.core.HazelcastInstance; import com.hazelcast.core.IQueue; import org.mockenize.model.LogBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; package org.mockenize.repository; @Repository public class RequestLogRepository { private static final String CACHE_KEY = "request-log"; private final IQueue<Object> queue; @Autowired public RequestLogRepository(HazelcastInstance hazelcastInstance) { queue = hazelcastInstance.getQueue(CACHE_KEY); }
public void save(LogBean requestLogBean) {
Mockenize/mockenize-server
src/main/java/org/mockenize/provider/filter/RequestLoggingFilter.java
// Path: src/main/java/org/mockenize/model/LogBean.java // @Data // public class LogBean implements Serializable, Cacheable { // // private static final long serialVersionUID = 1L; // // private String key; // // private LogType type; // // private String url; // // private String path; // // private String method; // // private RequestLogBean request; // // private ResponseLogBean response; // // private Date date = new Date(); // // protected LogBean() { // } // // public LogBean(UUID key, LogType type) { // this.key = key.toString(); // this.type = type; // } // // } // // Path: src/main/java/org/mockenize/model/LogType.java // public enum LogType { // MOCK, // PROXY, // NONE // } // // Path: src/main/java/org/mockenize/model/RequestLogBean.java // @Data // public class RequestLogBean implements Serializable { // // private static final long serialVersionUID = 1L; // // private Map<String, String> headers = new HashMap<>(); // // private transient JsonNode body; // } // // Path: src/main/java/org/mockenize/service/LoggingService.java // @Service // public class LoggingService { // // @Autowired // private LogRepository logRepository; // // public void save(LogBean logBean) { // logRepository.save(logBean); // } // // public Collection<LogBean> getAll() { // return logRepository.findAll(); // } // // public LogBean getByKey(UUID key) { // return logRepository.findByKey(key.toString()); // } // // // public LogBean delete(UUID key) { // return logRepository.delete(key.toString()); // } // // public Collection<LogBean> deleteAll() { // return logRepository.deleteAll(); // } // // @SuppressWarnings("unchecked") // public Collection<LogBean> findByFilters(JsonNode jsonNode) { // Iterator<String> fieldNames = jsonNode.fieldNames(); // Predicate<String, LogBean> predicate = null; // while(fieldNames.hasNext()) { // String field = fieldNames.next(); // String value = jsonNode.get(field).asText(); // // Predicate<String, LogBean> tmp = Predicates.equal(field, value); // if(predicate == null) { // predicate = tmp; // } else { // predicate = Predicates.and(predicate, tmp); // } // } // return logRepository.findByPredicate(predicate); // } // }
import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.net.URI; import java.util.List; import java.util.Map; import java.util.UUID; import javax.annotation.Priority; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerRequestFilter; import javax.ws.rs.core.UriInfo; import javax.ws.rs.ext.Provider; import org.glassfish.jersey.message.internal.ReaderWriter; import org.mockenize.model.LogBean; import org.mockenize.model.LogType; import org.mockenize.model.RequestLogBean; import org.mockenize.service.LoggingService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.Joiner; import com.google.common.collect.Maps;
package org.mockenize.provider.filter; @Provider @Component @Priority(Integer.MIN_VALUE) public class RequestLoggingFilter implements ContainerRequestFilter { public static final String KEY = "Mockenize-Id"; private static final Joiner joiner = Joiner.on(", "); @Autowired private ObjectMapper objectMapper; @Autowired
// Path: src/main/java/org/mockenize/model/LogBean.java // @Data // public class LogBean implements Serializable, Cacheable { // // private static final long serialVersionUID = 1L; // // private String key; // // private LogType type; // // private String url; // // private String path; // // private String method; // // private RequestLogBean request; // // private ResponseLogBean response; // // private Date date = new Date(); // // protected LogBean() { // } // // public LogBean(UUID key, LogType type) { // this.key = key.toString(); // this.type = type; // } // // } // // Path: src/main/java/org/mockenize/model/LogType.java // public enum LogType { // MOCK, // PROXY, // NONE // } // // Path: src/main/java/org/mockenize/model/RequestLogBean.java // @Data // public class RequestLogBean implements Serializable { // // private static final long serialVersionUID = 1L; // // private Map<String, String> headers = new HashMap<>(); // // private transient JsonNode body; // } // // Path: src/main/java/org/mockenize/service/LoggingService.java // @Service // public class LoggingService { // // @Autowired // private LogRepository logRepository; // // public void save(LogBean logBean) { // logRepository.save(logBean); // } // // public Collection<LogBean> getAll() { // return logRepository.findAll(); // } // // public LogBean getByKey(UUID key) { // return logRepository.findByKey(key.toString()); // } // // // public LogBean delete(UUID key) { // return logRepository.delete(key.toString()); // } // // public Collection<LogBean> deleteAll() { // return logRepository.deleteAll(); // } // // @SuppressWarnings("unchecked") // public Collection<LogBean> findByFilters(JsonNode jsonNode) { // Iterator<String> fieldNames = jsonNode.fieldNames(); // Predicate<String, LogBean> predicate = null; // while(fieldNames.hasNext()) { // String field = fieldNames.next(); // String value = jsonNode.get(field).asText(); // // Predicate<String, LogBean> tmp = Predicates.equal(field, value); // if(predicate == null) { // predicate = tmp; // } else { // predicate = Predicates.and(predicate, tmp); // } // } // return logRepository.findByPredicate(predicate); // } // } // Path: src/main/java/org/mockenize/provider/filter/RequestLoggingFilter.java import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.net.URI; import java.util.List; import java.util.Map; import java.util.UUID; import javax.annotation.Priority; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerRequestFilter; import javax.ws.rs.core.UriInfo; import javax.ws.rs.ext.Provider; import org.glassfish.jersey.message.internal.ReaderWriter; import org.mockenize.model.LogBean; import org.mockenize.model.LogType; import org.mockenize.model.RequestLogBean; import org.mockenize.service.LoggingService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.Joiner; import com.google.common.collect.Maps; package org.mockenize.provider.filter; @Provider @Component @Priority(Integer.MIN_VALUE) public class RequestLoggingFilter implements ContainerRequestFilter { public static final String KEY = "Mockenize-Id"; private static final Joiner joiner = Joiner.on(", "); @Autowired private ObjectMapper objectMapper; @Autowired
private LoggingService loggingService;
Mockenize/mockenize-server
src/main/java/org/mockenize/provider/filter/RequestLoggingFilter.java
// Path: src/main/java/org/mockenize/model/LogBean.java // @Data // public class LogBean implements Serializable, Cacheable { // // private static final long serialVersionUID = 1L; // // private String key; // // private LogType type; // // private String url; // // private String path; // // private String method; // // private RequestLogBean request; // // private ResponseLogBean response; // // private Date date = new Date(); // // protected LogBean() { // } // // public LogBean(UUID key, LogType type) { // this.key = key.toString(); // this.type = type; // } // // } // // Path: src/main/java/org/mockenize/model/LogType.java // public enum LogType { // MOCK, // PROXY, // NONE // } // // Path: src/main/java/org/mockenize/model/RequestLogBean.java // @Data // public class RequestLogBean implements Serializable { // // private static final long serialVersionUID = 1L; // // private Map<String, String> headers = new HashMap<>(); // // private transient JsonNode body; // } // // Path: src/main/java/org/mockenize/service/LoggingService.java // @Service // public class LoggingService { // // @Autowired // private LogRepository logRepository; // // public void save(LogBean logBean) { // logRepository.save(logBean); // } // // public Collection<LogBean> getAll() { // return logRepository.findAll(); // } // // public LogBean getByKey(UUID key) { // return logRepository.findByKey(key.toString()); // } // // // public LogBean delete(UUID key) { // return logRepository.delete(key.toString()); // } // // public Collection<LogBean> deleteAll() { // return logRepository.deleteAll(); // } // // @SuppressWarnings("unchecked") // public Collection<LogBean> findByFilters(JsonNode jsonNode) { // Iterator<String> fieldNames = jsonNode.fieldNames(); // Predicate<String, LogBean> predicate = null; // while(fieldNames.hasNext()) { // String field = fieldNames.next(); // String value = jsonNode.get(field).asText(); // // Predicate<String, LogBean> tmp = Predicates.equal(field, value); // if(predicate == null) { // predicate = tmp; // } else { // predicate = Predicates.and(predicate, tmp); // } // } // return logRepository.findByPredicate(predicate); // } // }
import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.net.URI; import java.util.List; import java.util.Map; import java.util.UUID; import javax.annotation.Priority; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerRequestFilter; import javax.ws.rs.core.UriInfo; import javax.ws.rs.ext.Provider; import org.glassfish.jersey.message.internal.ReaderWriter; import org.mockenize.model.LogBean; import org.mockenize.model.LogType; import org.mockenize.model.RequestLogBean; import org.mockenize.service.LoggingService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.Joiner; import com.google.common.collect.Maps;
package org.mockenize.provider.filter; @Provider @Component @Priority(Integer.MIN_VALUE) public class RequestLoggingFilter implements ContainerRequestFilter { public static final String KEY = "Mockenize-Id"; private static final Joiner joiner = Joiner.on(", "); @Autowired private ObjectMapper objectMapper; @Autowired private LoggingService loggingService; @Autowired private HttpServletRequest request; @Override public void filter(ContainerRequestContext requestContext) throws IOException {
// Path: src/main/java/org/mockenize/model/LogBean.java // @Data // public class LogBean implements Serializable, Cacheable { // // private static final long serialVersionUID = 1L; // // private String key; // // private LogType type; // // private String url; // // private String path; // // private String method; // // private RequestLogBean request; // // private ResponseLogBean response; // // private Date date = new Date(); // // protected LogBean() { // } // // public LogBean(UUID key, LogType type) { // this.key = key.toString(); // this.type = type; // } // // } // // Path: src/main/java/org/mockenize/model/LogType.java // public enum LogType { // MOCK, // PROXY, // NONE // } // // Path: src/main/java/org/mockenize/model/RequestLogBean.java // @Data // public class RequestLogBean implements Serializable { // // private static final long serialVersionUID = 1L; // // private Map<String, String> headers = new HashMap<>(); // // private transient JsonNode body; // } // // Path: src/main/java/org/mockenize/service/LoggingService.java // @Service // public class LoggingService { // // @Autowired // private LogRepository logRepository; // // public void save(LogBean logBean) { // logRepository.save(logBean); // } // // public Collection<LogBean> getAll() { // return logRepository.findAll(); // } // // public LogBean getByKey(UUID key) { // return logRepository.findByKey(key.toString()); // } // // // public LogBean delete(UUID key) { // return logRepository.delete(key.toString()); // } // // public Collection<LogBean> deleteAll() { // return logRepository.deleteAll(); // } // // @SuppressWarnings("unchecked") // public Collection<LogBean> findByFilters(JsonNode jsonNode) { // Iterator<String> fieldNames = jsonNode.fieldNames(); // Predicate<String, LogBean> predicate = null; // while(fieldNames.hasNext()) { // String field = fieldNames.next(); // String value = jsonNode.get(field).asText(); // // Predicate<String, LogBean> tmp = Predicates.equal(field, value); // if(predicate == null) { // predicate = tmp; // } else { // predicate = Predicates.and(predicate, tmp); // } // } // return logRepository.findByPredicate(predicate); // } // } // Path: src/main/java/org/mockenize/provider/filter/RequestLoggingFilter.java import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.net.URI; import java.util.List; import java.util.Map; import java.util.UUID; import javax.annotation.Priority; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerRequestFilter; import javax.ws.rs.core.UriInfo; import javax.ws.rs.ext.Provider; import org.glassfish.jersey.message.internal.ReaderWriter; import org.mockenize.model.LogBean; import org.mockenize.model.LogType; import org.mockenize.model.RequestLogBean; import org.mockenize.service.LoggingService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.Joiner; import com.google.common.collect.Maps; package org.mockenize.provider.filter; @Provider @Component @Priority(Integer.MIN_VALUE) public class RequestLoggingFilter implements ContainerRequestFilter { public static final String KEY = "Mockenize-Id"; private static final Joiner joiner = Joiner.on(", "); @Autowired private ObjectMapper objectMapper; @Autowired private LoggingService loggingService; @Autowired private HttpServletRequest request; @Override public void filter(ContainerRequestContext requestContext) throws IOException {
LogType logType = getRequestType(requestContext.getUriInfo());
Mockenize/mockenize-server
src/main/java/org/mockenize/provider/filter/RequestLoggingFilter.java
// Path: src/main/java/org/mockenize/model/LogBean.java // @Data // public class LogBean implements Serializable, Cacheable { // // private static final long serialVersionUID = 1L; // // private String key; // // private LogType type; // // private String url; // // private String path; // // private String method; // // private RequestLogBean request; // // private ResponseLogBean response; // // private Date date = new Date(); // // protected LogBean() { // } // // public LogBean(UUID key, LogType type) { // this.key = key.toString(); // this.type = type; // } // // } // // Path: src/main/java/org/mockenize/model/LogType.java // public enum LogType { // MOCK, // PROXY, // NONE // } // // Path: src/main/java/org/mockenize/model/RequestLogBean.java // @Data // public class RequestLogBean implements Serializable { // // private static final long serialVersionUID = 1L; // // private Map<String, String> headers = new HashMap<>(); // // private transient JsonNode body; // } // // Path: src/main/java/org/mockenize/service/LoggingService.java // @Service // public class LoggingService { // // @Autowired // private LogRepository logRepository; // // public void save(LogBean logBean) { // logRepository.save(logBean); // } // // public Collection<LogBean> getAll() { // return logRepository.findAll(); // } // // public LogBean getByKey(UUID key) { // return logRepository.findByKey(key.toString()); // } // // // public LogBean delete(UUID key) { // return logRepository.delete(key.toString()); // } // // public Collection<LogBean> deleteAll() { // return logRepository.deleteAll(); // } // // @SuppressWarnings("unchecked") // public Collection<LogBean> findByFilters(JsonNode jsonNode) { // Iterator<String> fieldNames = jsonNode.fieldNames(); // Predicate<String, LogBean> predicate = null; // while(fieldNames.hasNext()) { // String field = fieldNames.next(); // String value = jsonNode.get(field).asText(); // // Predicate<String, LogBean> tmp = Predicates.equal(field, value); // if(predicate == null) { // predicate = tmp; // } else { // predicate = Predicates.and(predicate, tmp); // } // } // return logRepository.findByPredicate(predicate); // } // }
import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.net.URI; import java.util.List; import java.util.Map; import java.util.UUID; import javax.annotation.Priority; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerRequestFilter; import javax.ws.rs.core.UriInfo; import javax.ws.rs.ext.Provider; import org.glassfish.jersey.message.internal.ReaderWriter; import org.mockenize.model.LogBean; import org.mockenize.model.LogType; import org.mockenize.model.RequestLogBean; import org.mockenize.service.LoggingService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.Joiner; import com.google.common.collect.Maps;
package org.mockenize.provider.filter; @Provider @Component @Priority(Integer.MIN_VALUE) public class RequestLoggingFilter implements ContainerRequestFilter { public static final String KEY = "Mockenize-Id"; private static final Joiner joiner = Joiner.on(", "); @Autowired private ObjectMapper objectMapper; @Autowired private LoggingService loggingService; @Autowired private HttpServletRequest request; @Override public void filter(ContainerRequestContext requestContext) throws IOException { LogType logType = getRequestType(requestContext.getUriInfo()); if (LogType.MOCK.equals(logType)) { UUID key = UUID.randomUUID(); request.setAttribute(KEY, key); URI requestUri = requestContext.getUriInfo().getRequestUri();
// Path: src/main/java/org/mockenize/model/LogBean.java // @Data // public class LogBean implements Serializable, Cacheable { // // private static final long serialVersionUID = 1L; // // private String key; // // private LogType type; // // private String url; // // private String path; // // private String method; // // private RequestLogBean request; // // private ResponseLogBean response; // // private Date date = new Date(); // // protected LogBean() { // } // // public LogBean(UUID key, LogType type) { // this.key = key.toString(); // this.type = type; // } // // } // // Path: src/main/java/org/mockenize/model/LogType.java // public enum LogType { // MOCK, // PROXY, // NONE // } // // Path: src/main/java/org/mockenize/model/RequestLogBean.java // @Data // public class RequestLogBean implements Serializable { // // private static final long serialVersionUID = 1L; // // private Map<String, String> headers = new HashMap<>(); // // private transient JsonNode body; // } // // Path: src/main/java/org/mockenize/service/LoggingService.java // @Service // public class LoggingService { // // @Autowired // private LogRepository logRepository; // // public void save(LogBean logBean) { // logRepository.save(logBean); // } // // public Collection<LogBean> getAll() { // return logRepository.findAll(); // } // // public LogBean getByKey(UUID key) { // return logRepository.findByKey(key.toString()); // } // // // public LogBean delete(UUID key) { // return logRepository.delete(key.toString()); // } // // public Collection<LogBean> deleteAll() { // return logRepository.deleteAll(); // } // // @SuppressWarnings("unchecked") // public Collection<LogBean> findByFilters(JsonNode jsonNode) { // Iterator<String> fieldNames = jsonNode.fieldNames(); // Predicate<String, LogBean> predicate = null; // while(fieldNames.hasNext()) { // String field = fieldNames.next(); // String value = jsonNode.get(field).asText(); // // Predicate<String, LogBean> tmp = Predicates.equal(field, value); // if(predicate == null) { // predicate = tmp; // } else { // predicate = Predicates.and(predicate, tmp); // } // } // return logRepository.findByPredicate(predicate); // } // } // Path: src/main/java/org/mockenize/provider/filter/RequestLoggingFilter.java import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.net.URI; import java.util.List; import java.util.Map; import java.util.UUID; import javax.annotation.Priority; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerRequestFilter; import javax.ws.rs.core.UriInfo; import javax.ws.rs.ext.Provider; import org.glassfish.jersey.message.internal.ReaderWriter; import org.mockenize.model.LogBean; import org.mockenize.model.LogType; import org.mockenize.model.RequestLogBean; import org.mockenize.service.LoggingService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.Joiner; import com.google.common.collect.Maps; package org.mockenize.provider.filter; @Provider @Component @Priority(Integer.MIN_VALUE) public class RequestLoggingFilter implements ContainerRequestFilter { public static final String KEY = "Mockenize-Id"; private static final Joiner joiner = Joiner.on(", "); @Autowired private ObjectMapper objectMapper; @Autowired private LoggingService loggingService; @Autowired private HttpServletRequest request; @Override public void filter(ContainerRequestContext requestContext) throws IOException { LogType logType = getRequestType(requestContext.getUriInfo()); if (LogType.MOCK.equals(logType)) { UUID key = UUID.randomUUID(); request.setAttribute(KEY, key); URI requestUri = requestContext.getUriInfo().getRequestUri();
LogBean logBean = new LogBean(key, getRequestType(requestContext.getUriInfo()));
Mockenize/mockenize-server
src/main/java/org/mockenize/provider/filter/RequestLoggingFilter.java
// Path: src/main/java/org/mockenize/model/LogBean.java // @Data // public class LogBean implements Serializable, Cacheable { // // private static final long serialVersionUID = 1L; // // private String key; // // private LogType type; // // private String url; // // private String path; // // private String method; // // private RequestLogBean request; // // private ResponseLogBean response; // // private Date date = new Date(); // // protected LogBean() { // } // // public LogBean(UUID key, LogType type) { // this.key = key.toString(); // this.type = type; // } // // } // // Path: src/main/java/org/mockenize/model/LogType.java // public enum LogType { // MOCK, // PROXY, // NONE // } // // Path: src/main/java/org/mockenize/model/RequestLogBean.java // @Data // public class RequestLogBean implements Serializable { // // private static final long serialVersionUID = 1L; // // private Map<String, String> headers = new HashMap<>(); // // private transient JsonNode body; // } // // Path: src/main/java/org/mockenize/service/LoggingService.java // @Service // public class LoggingService { // // @Autowired // private LogRepository logRepository; // // public void save(LogBean logBean) { // logRepository.save(logBean); // } // // public Collection<LogBean> getAll() { // return logRepository.findAll(); // } // // public LogBean getByKey(UUID key) { // return logRepository.findByKey(key.toString()); // } // // // public LogBean delete(UUID key) { // return logRepository.delete(key.toString()); // } // // public Collection<LogBean> deleteAll() { // return logRepository.deleteAll(); // } // // @SuppressWarnings("unchecked") // public Collection<LogBean> findByFilters(JsonNode jsonNode) { // Iterator<String> fieldNames = jsonNode.fieldNames(); // Predicate<String, LogBean> predicate = null; // while(fieldNames.hasNext()) { // String field = fieldNames.next(); // String value = jsonNode.get(field).asText(); // // Predicate<String, LogBean> tmp = Predicates.equal(field, value); // if(predicate == null) { // predicate = tmp; // } else { // predicate = Predicates.and(predicate, tmp); // } // } // return logRepository.findByPredicate(predicate); // } // }
import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.net.URI; import java.util.List; import java.util.Map; import java.util.UUID; import javax.annotation.Priority; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerRequestFilter; import javax.ws.rs.core.UriInfo; import javax.ws.rs.ext.Provider; import org.glassfish.jersey.message.internal.ReaderWriter; import org.mockenize.model.LogBean; import org.mockenize.model.LogType; import org.mockenize.model.RequestLogBean; import org.mockenize.service.LoggingService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.Joiner; import com.google.common.collect.Maps;
@Autowired private HttpServletRequest request; @Override public void filter(ContainerRequestContext requestContext) throws IOException { LogType logType = getRequestType(requestContext.getUriInfo()); if (LogType.MOCK.equals(logType)) { UUID key = UUID.randomUUID(); request.setAttribute(KEY, key); URI requestUri = requestContext.getUriInfo().getRequestUri(); LogBean logBean = new LogBean(key, getRequestType(requestContext.getUriInfo())); logBean.setUrl(requestUri.toString()); logBean.setPath(requestUri.getPath()); logBean.setMethod(requestContext.getMethod()); logBean.setRequest(mapRequestLogBean(requestContext)); loggingService.save(logBean); } } private LogType getRequestType(UriInfo uriInfo) { String path = uriInfo.getRequestUri().getPath(); if (path.startsWith("/_")) { return LogType.NONE; } return LogType.MOCK; }
// Path: src/main/java/org/mockenize/model/LogBean.java // @Data // public class LogBean implements Serializable, Cacheable { // // private static final long serialVersionUID = 1L; // // private String key; // // private LogType type; // // private String url; // // private String path; // // private String method; // // private RequestLogBean request; // // private ResponseLogBean response; // // private Date date = new Date(); // // protected LogBean() { // } // // public LogBean(UUID key, LogType type) { // this.key = key.toString(); // this.type = type; // } // // } // // Path: src/main/java/org/mockenize/model/LogType.java // public enum LogType { // MOCK, // PROXY, // NONE // } // // Path: src/main/java/org/mockenize/model/RequestLogBean.java // @Data // public class RequestLogBean implements Serializable { // // private static final long serialVersionUID = 1L; // // private Map<String, String> headers = new HashMap<>(); // // private transient JsonNode body; // } // // Path: src/main/java/org/mockenize/service/LoggingService.java // @Service // public class LoggingService { // // @Autowired // private LogRepository logRepository; // // public void save(LogBean logBean) { // logRepository.save(logBean); // } // // public Collection<LogBean> getAll() { // return logRepository.findAll(); // } // // public LogBean getByKey(UUID key) { // return logRepository.findByKey(key.toString()); // } // // // public LogBean delete(UUID key) { // return logRepository.delete(key.toString()); // } // // public Collection<LogBean> deleteAll() { // return logRepository.deleteAll(); // } // // @SuppressWarnings("unchecked") // public Collection<LogBean> findByFilters(JsonNode jsonNode) { // Iterator<String> fieldNames = jsonNode.fieldNames(); // Predicate<String, LogBean> predicate = null; // while(fieldNames.hasNext()) { // String field = fieldNames.next(); // String value = jsonNode.get(field).asText(); // // Predicate<String, LogBean> tmp = Predicates.equal(field, value); // if(predicate == null) { // predicate = tmp; // } else { // predicate = Predicates.and(predicate, tmp); // } // } // return logRepository.findByPredicate(predicate); // } // } // Path: src/main/java/org/mockenize/provider/filter/RequestLoggingFilter.java import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.net.URI; import java.util.List; import java.util.Map; import java.util.UUID; import javax.annotation.Priority; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerRequestFilter; import javax.ws.rs.core.UriInfo; import javax.ws.rs.ext.Provider; import org.glassfish.jersey.message.internal.ReaderWriter; import org.mockenize.model.LogBean; import org.mockenize.model.LogType; import org.mockenize.model.RequestLogBean; import org.mockenize.service.LoggingService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.Joiner; import com.google.common.collect.Maps; @Autowired private HttpServletRequest request; @Override public void filter(ContainerRequestContext requestContext) throws IOException { LogType logType = getRequestType(requestContext.getUriInfo()); if (LogType.MOCK.equals(logType)) { UUID key = UUID.randomUUID(); request.setAttribute(KEY, key); URI requestUri = requestContext.getUriInfo().getRequestUri(); LogBean logBean = new LogBean(key, getRequestType(requestContext.getUriInfo())); logBean.setUrl(requestUri.toString()); logBean.setPath(requestUri.getPath()); logBean.setMethod(requestContext.getMethod()); logBean.setRequest(mapRequestLogBean(requestContext)); loggingService.save(logBean); } } private LogType getRequestType(UriInfo uriInfo) { String path = uriInfo.getRequestUri().getPath(); if (path.startsWith("/_")) { return LogType.NONE; } return LogType.MOCK; }
private RequestLogBean mapRequestLogBean(ContainerRequestContext requestContext) throws IOException {
Mockenize/mockenize-server
src/main/java/org/mockenize/service/ProxyService.java
// Path: src/main/java/org/mockenize/exception/ProxyPathException.java // public class ProxyPathException extends WebApplicationException { // // private static final long serialVersionUID = 7714442933981404781L; // // public ProxyPathException() { // super("Can't define proxy path.", Response.Status.INTERNAL_SERVER_ERROR); // } // } // // Path: src/main/java/org/mockenize/model/ProxyBean.java // @Data // public class ProxyBean implements Serializable, Cacheable { // // private static final long serialVersionUID = 1L; // // private static final String UNDERLINE = "_"; // // private static final String SLASH = "/"; // // @NotEmpty // private String key; // // @NotEmpty // private String path; // // @NotNull // private String name; // // @NotNull // private URI url; // // @Override // public String getKey() { // return path.toLowerCase().replaceAll(SLASH, UNDERLINE); // } // } // // Path: src/main/java/org/mockenize/repository/ProxyRepository.java // @Repository // public class ProxyRepository extends AbstractRepository<ProxyBean> { // // private static final String CACHE_KEY = "proxies"; // // @Autowired // public ProxyRepository(HazelcastInstance hazelcastInstance) { // super(hazelcastInstance, CACHE_KEY); // } // // }
import java.util.ArrayList; import java.util.Collection; import java.util.Enumeration; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.Entity; import javax.ws.rs.client.Invocation.Builder; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.mockenize.exception.ProxyPathException; import org.mockenize.model.ProxyBean; import org.mockenize.repository.ProxyRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.fasterxml.jackson.databind.JsonNode; import com.google.common.base.Strings;
package org.mockenize.service; @Service public class ProxyService implements ResponseService { @Autowired
// Path: src/main/java/org/mockenize/exception/ProxyPathException.java // public class ProxyPathException extends WebApplicationException { // // private static final long serialVersionUID = 7714442933981404781L; // // public ProxyPathException() { // super("Can't define proxy path.", Response.Status.INTERNAL_SERVER_ERROR); // } // } // // Path: src/main/java/org/mockenize/model/ProxyBean.java // @Data // public class ProxyBean implements Serializable, Cacheable { // // private static final long serialVersionUID = 1L; // // private static final String UNDERLINE = "_"; // // private static final String SLASH = "/"; // // @NotEmpty // private String key; // // @NotEmpty // private String path; // // @NotNull // private String name; // // @NotNull // private URI url; // // @Override // public String getKey() { // return path.toLowerCase().replaceAll(SLASH, UNDERLINE); // } // } // // Path: src/main/java/org/mockenize/repository/ProxyRepository.java // @Repository // public class ProxyRepository extends AbstractRepository<ProxyBean> { // // private static final String CACHE_KEY = "proxies"; // // @Autowired // public ProxyRepository(HazelcastInstance hazelcastInstance) { // super(hazelcastInstance, CACHE_KEY); // } // // } // Path: src/main/java/org/mockenize/service/ProxyService.java import java.util.ArrayList; import java.util.Collection; import java.util.Enumeration; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.Entity; import javax.ws.rs.client.Invocation.Builder; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.mockenize.exception.ProxyPathException; import org.mockenize.model.ProxyBean; import org.mockenize.repository.ProxyRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.fasterxml.jackson.databind.JsonNode; import com.google.common.base.Strings; package org.mockenize.service; @Service public class ProxyService implements ResponseService { @Autowired
private ProxyRepository proxyRepository;
Mockenize/mockenize-server
src/main/java/org/mockenize/service/ProxyService.java
// Path: src/main/java/org/mockenize/exception/ProxyPathException.java // public class ProxyPathException extends WebApplicationException { // // private static final long serialVersionUID = 7714442933981404781L; // // public ProxyPathException() { // super("Can't define proxy path.", Response.Status.INTERNAL_SERVER_ERROR); // } // } // // Path: src/main/java/org/mockenize/model/ProxyBean.java // @Data // public class ProxyBean implements Serializable, Cacheable { // // private static final long serialVersionUID = 1L; // // private static final String UNDERLINE = "_"; // // private static final String SLASH = "/"; // // @NotEmpty // private String key; // // @NotEmpty // private String path; // // @NotNull // private String name; // // @NotNull // private URI url; // // @Override // public String getKey() { // return path.toLowerCase().replaceAll(SLASH, UNDERLINE); // } // } // // Path: src/main/java/org/mockenize/repository/ProxyRepository.java // @Repository // public class ProxyRepository extends AbstractRepository<ProxyBean> { // // private static final String CACHE_KEY = "proxies"; // // @Autowired // public ProxyRepository(HazelcastInstance hazelcastInstance) { // super(hazelcastInstance, CACHE_KEY); // } // // }
import java.util.ArrayList; import java.util.Collection; import java.util.Enumeration; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.Entity; import javax.ws.rs.client.Invocation.Builder; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.mockenize.exception.ProxyPathException; import org.mockenize.model.ProxyBean; import org.mockenize.repository.ProxyRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.fasterxml.jackson.databind.JsonNode; import com.google.common.base.Strings;
package org.mockenize.service; @Service public class ProxyService implements ResponseService { @Autowired private ProxyRepository proxyRepository; @Context private HttpServletRequest request; private Client client = ClientBuilder.newClient();
// Path: src/main/java/org/mockenize/exception/ProxyPathException.java // public class ProxyPathException extends WebApplicationException { // // private static final long serialVersionUID = 7714442933981404781L; // // public ProxyPathException() { // super("Can't define proxy path.", Response.Status.INTERNAL_SERVER_ERROR); // } // } // // Path: src/main/java/org/mockenize/model/ProxyBean.java // @Data // public class ProxyBean implements Serializable, Cacheable { // // private static final long serialVersionUID = 1L; // // private static final String UNDERLINE = "_"; // // private static final String SLASH = "/"; // // @NotEmpty // private String key; // // @NotEmpty // private String path; // // @NotNull // private String name; // // @NotNull // private URI url; // // @Override // public String getKey() { // return path.toLowerCase().replaceAll(SLASH, UNDERLINE); // } // } // // Path: src/main/java/org/mockenize/repository/ProxyRepository.java // @Repository // public class ProxyRepository extends AbstractRepository<ProxyBean> { // // private static final String CACHE_KEY = "proxies"; // // @Autowired // public ProxyRepository(HazelcastInstance hazelcastInstance) { // super(hazelcastInstance, CACHE_KEY); // } // // } // Path: src/main/java/org/mockenize/service/ProxyService.java import java.util.ArrayList; import java.util.Collection; import java.util.Enumeration; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.Entity; import javax.ws.rs.client.Invocation.Builder; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.mockenize.exception.ProxyPathException; import org.mockenize.model.ProxyBean; import org.mockenize.repository.ProxyRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.fasterxml.jackson.databind.JsonNode; import com.google.common.base.Strings; package org.mockenize.service; @Service public class ProxyService implements ResponseService { @Autowired private ProxyRepository proxyRepository; @Context private HttpServletRequest request; private Client client = ClientBuilder.newClient();
public Collection<ProxyBean> getAll() {
Mockenize/mockenize-server
src/main/java/org/mockenize/service/ProxyService.java
// Path: src/main/java/org/mockenize/exception/ProxyPathException.java // public class ProxyPathException extends WebApplicationException { // // private static final long serialVersionUID = 7714442933981404781L; // // public ProxyPathException() { // super("Can't define proxy path.", Response.Status.INTERNAL_SERVER_ERROR); // } // } // // Path: src/main/java/org/mockenize/model/ProxyBean.java // @Data // public class ProxyBean implements Serializable, Cacheable { // // private static final long serialVersionUID = 1L; // // private static final String UNDERLINE = "_"; // // private static final String SLASH = "/"; // // @NotEmpty // private String key; // // @NotEmpty // private String path; // // @NotNull // private String name; // // @NotNull // private URI url; // // @Override // public String getKey() { // return path.toLowerCase().replaceAll(SLASH, UNDERLINE); // } // } // // Path: src/main/java/org/mockenize/repository/ProxyRepository.java // @Repository // public class ProxyRepository extends AbstractRepository<ProxyBean> { // // private static final String CACHE_KEY = "proxies"; // // @Autowired // public ProxyRepository(HazelcastInstance hazelcastInstance) { // super(hazelcastInstance, CACHE_KEY); // } // // }
import java.util.ArrayList; import java.util.Collection; import java.util.Enumeration; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.Entity; import javax.ws.rs.client.Invocation.Builder; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.mockenize.exception.ProxyPathException; import org.mockenize.model.ProxyBean; import org.mockenize.repository.ProxyRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.fasterxml.jackson.databind.JsonNode; import com.google.common.base.Strings;
if(deleted != null) { deletedProxies.add(deleted); } } } else { deletedProxies = proxyRepository.deleteAll(); } return deletedProxies; } @Override public Response getResponse(HttpServletRequest request, JsonNode requestBody) { String path = request.getRequestURI(); ProxyBean proxyBean = proxyRepository.findByKey(path); Builder requestBuilder = client.target(proxyBean.getUrl()).path(getRequestPath(proxyBean.getPath(), path)) .request(); addHeaders(request, requestBuilder); Entity<JsonNode> entity = Entity.entity(requestBody, getContentType(request)); Response response = requestBuilder.build(request.getMethod(), entity).invoke(); response.bufferEntity(); return response; } private String getRequestPath(String path, String requestedPath) { if (path.matches("/.+")) { Pattern pattern = Pattern.compile("/[^/\\.]+(.*)"); Matcher matcher = pattern.matcher(requestedPath); if (matcher.matches()) { return matcher.group(1); } else {
// Path: src/main/java/org/mockenize/exception/ProxyPathException.java // public class ProxyPathException extends WebApplicationException { // // private static final long serialVersionUID = 7714442933981404781L; // // public ProxyPathException() { // super("Can't define proxy path.", Response.Status.INTERNAL_SERVER_ERROR); // } // } // // Path: src/main/java/org/mockenize/model/ProxyBean.java // @Data // public class ProxyBean implements Serializable, Cacheable { // // private static final long serialVersionUID = 1L; // // private static final String UNDERLINE = "_"; // // private static final String SLASH = "/"; // // @NotEmpty // private String key; // // @NotEmpty // private String path; // // @NotNull // private String name; // // @NotNull // private URI url; // // @Override // public String getKey() { // return path.toLowerCase().replaceAll(SLASH, UNDERLINE); // } // } // // Path: src/main/java/org/mockenize/repository/ProxyRepository.java // @Repository // public class ProxyRepository extends AbstractRepository<ProxyBean> { // // private static final String CACHE_KEY = "proxies"; // // @Autowired // public ProxyRepository(HazelcastInstance hazelcastInstance) { // super(hazelcastInstance, CACHE_KEY); // } // // } // Path: src/main/java/org/mockenize/service/ProxyService.java import java.util.ArrayList; import java.util.Collection; import java.util.Enumeration; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.Entity; import javax.ws.rs.client.Invocation.Builder; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.mockenize.exception.ProxyPathException; import org.mockenize.model.ProxyBean; import org.mockenize.repository.ProxyRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.fasterxml.jackson.databind.JsonNode; import com.google.common.base.Strings; if(deleted != null) { deletedProxies.add(deleted); } } } else { deletedProxies = proxyRepository.deleteAll(); } return deletedProxies; } @Override public Response getResponse(HttpServletRequest request, JsonNode requestBody) { String path = request.getRequestURI(); ProxyBean proxyBean = proxyRepository.findByKey(path); Builder requestBuilder = client.target(proxyBean.getUrl()).path(getRequestPath(proxyBean.getPath(), path)) .request(); addHeaders(request, requestBuilder); Entity<JsonNode> entity = Entity.entity(requestBody, getContentType(request)); Response response = requestBuilder.build(request.getMethod(), entity).invoke(); response.bufferEntity(); return response; } private String getRequestPath(String path, String requestedPath) { if (path.matches("/.+")) { Pattern pattern = Pattern.compile("/[^/\\.]+(.*)"); Matcher matcher = pattern.matcher(requestedPath); if (matcher.matches()) { return matcher.group(1); } else {
throw new ProxyPathException();
Mockenize/mockenize-server
src/main/java/org/mockenize/service/MockenizeService.java
// Path: src/main/java/org/mockenize/exception/ResourceNotFoundException.java // public class ResourceNotFoundException extends WebApplicationException { // // private static final long serialVersionUID = -1336666303655740602L; // // public ResourceNotFoundException(String resource) { // super("Resource not found: " + resource, Response.Status.NOT_FOUND); // } // }
import javax.servlet.http.HttpServletRequest; import javax.ws.rs.core.Response; import org.mockenize.exception.ResourceNotFoundException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.fasterxml.jackson.databind.JsonNode;
package org.mockenize.service; @Service public class MockenizeService { @Autowired private MockService mockService; @Autowired private ProxyService proxyService; public Response getResponse(HttpServletRequest request, JsonNode body) { String path = request.getRequestURI(); String method = request.getMethod(); if (mockService.exists(method, path)) { return mockService.getResponse(request, body); } else if (proxyService.exists(path)) { return proxyService.getResponse(request, body); }
// Path: src/main/java/org/mockenize/exception/ResourceNotFoundException.java // public class ResourceNotFoundException extends WebApplicationException { // // private static final long serialVersionUID = -1336666303655740602L; // // public ResourceNotFoundException(String resource) { // super("Resource not found: " + resource, Response.Status.NOT_FOUND); // } // } // Path: src/main/java/org/mockenize/service/MockenizeService.java import javax.servlet.http.HttpServletRequest; import javax.ws.rs.core.Response; import org.mockenize.exception.ResourceNotFoundException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.fasterxml.jackson.databind.JsonNode; package org.mockenize.service; @Service public class MockenizeService { @Autowired private MockService mockService; @Autowired private ProxyService proxyService; public Response getResponse(HttpServletRequest request, JsonNode body) { String path = request.getRequestURI(); String method = request.getMethod(); if (mockService.exists(method, path)) { return mockService.getResponse(request, body); } else if (proxyService.exists(path)) { return proxyService.getResponse(request, body); }
throw new ResourceNotFoundException(path);
Mockenize/mockenize-server
src/main/java/org/mockenize/controller/MockenizeController.java
// Path: src/main/java/org/mockenize/service/MockenizeService.java // @Service // public class MockenizeService { // // @Autowired // private MockService mockService; // // @Autowired // private ProxyService proxyService; // // public Response getResponse(HttpServletRequest request, JsonNode body) { // String path = request.getRequestURI(); // String method = request.getMethod(); // // if (mockService.exists(method, path)) { // return mockService.getResponse(request, body); // } else if (proxyService.exists(path)) { // return proxyService.getResponse(request, body); // } // // throw new ResourceNotFoundException(path); // } // // public Response getResponse(HttpServletRequest request) { // return getResponse(request, null); // } // }
import javax.servlet.http.HttpServletRequest; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.HEAD; import javax.ws.rs.OPTIONS; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.mockenize.service.MockenizeService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import com.fasterxml.jackson.databind.JsonNode;
package org.mockenize.controller; @Controller @Path("{path:[^_].+}") @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_PLAIN }) @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_PLAIN, MediaType.TEXT_HTML }) public class MockenizeController { @Autowired
// Path: src/main/java/org/mockenize/service/MockenizeService.java // @Service // public class MockenizeService { // // @Autowired // private MockService mockService; // // @Autowired // private ProxyService proxyService; // // public Response getResponse(HttpServletRequest request, JsonNode body) { // String path = request.getRequestURI(); // String method = request.getMethod(); // // if (mockService.exists(method, path)) { // return mockService.getResponse(request, body); // } else if (proxyService.exists(path)) { // return proxyService.getResponse(request, body); // } // // throw new ResourceNotFoundException(path); // } // // public Response getResponse(HttpServletRequest request) { // return getResponse(request, null); // } // } // Path: src/main/java/org/mockenize/controller/MockenizeController.java import javax.servlet.http.HttpServletRequest; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.HEAD; import javax.ws.rs.OPTIONS; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.mockenize.service.MockenizeService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import com.fasterxml.jackson.databind.JsonNode; package org.mockenize.controller; @Controller @Path("{path:[^_].+}") @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_PLAIN }) @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_PLAIN, MediaType.TEXT_HTML }) public class MockenizeController { @Autowired
private MockenizeService mockenizeService;
Mockenize/mockenize-server
src/main/java/org/mockenize/provider/filter/ResponseLoggingFilter.java
// Path: src/main/java/org/mockenize/model/LogBean.java // @Data // public class LogBean implements Serializable, Cacheable { // // private static final long serialVersionUID = 1L; // // private String key; // // private LogType type; // // private String url; // // private String path; // // private String method; // // private RequestLogBean request; // // private ResponseLogBean response; // // private Date date = new Date(); // // protected LogBean() { // } // // public LogBean(UUID key, LogType type) { // this.key = key.toString(); // this.type = type; // } // // } // // Path: src/main/java/org/mockenize/model/ResponseLogBean.java // @Data // public class ResponseLogBean implements Serializable { // // private static final long serialVersionUID = 1L; // // private Integer status; // // private Map<String, String> headers = new HashMap<>(); // // private transient JsonNode body; // } // // Path: src/main/java/org/mockenize/service/LoggingService.java // @Service // public class LoggingService { // // @Autowired // private LogRepository logRepository; // // public void save(LogBean logBean) { // logRepository.save(logBean); // } // // public Collection<LogBean> getAll() { // return logRepository.findAll(); // } // // public LogBean getByKey(UUID key) { // return logRepository.findByKey(key.toString()); // } // // // public LogBean delete(UUID key) { // return logRepository.delete(key.toString()); // } // // public Collection<LogBean> deleteAll() { // return logRepository.deleteAll(); // } // // @SuppressWarnings("unchecked") // public Collection<LogBean> findByFilters(JsonNode jsonNode) { // Iterator<String> fieldNames = jsonNode.fieldNames(); // Predicate<String, LogBean> predicate = null; // while(fieldNames.hasNext()) { // String field = fieldNames.next(); // String value = jsonNode.get(field).asText(); // // Predicate<String, LogBean> tmp = Predicates.equal(field, value); // if(predicate == null) { // predicate = tmp; // } else { // predicate = Predicates.and(predicate, tmp); // } // } // return logRepository.findByPredicate(predicate); // } // }
import java.io.IOException; import java.io.InputStream; import java.util.List; import java.util.Map; import java.util.UUID; import javax.annotation.Priority; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerResponseContext; import javax.ws.rs.container.ContainerResponseFilter; import javax.ws.rs.ext.Provider; import org.mockenize.model.LogBean; import org.mockenize.model.ResponseLogBean; import org.mockenize.service.LoggingService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import com.google.common.collect.Maps;
package org.mockenize.provider.filter; @Provider @Component @Priority(Integer.MAX_VALUE) public class ResponseLoggingFilter implements ContainerResponseFilter { public static final String KEY = "Mockenize-Id"; private static final Joiner joiner = Joiner.on(", "); @Autowired private ObjectMapper objectMapper; @Autowired
// Path: src/main/java/org/mockenize/model/LogBean.java // @Data // public class LogBean implements Serializable, Cacheable { // // private static final long serialVersionUID = 1L; // // private String key; // // private LogType type; // // private String url; // // private String path; // // private String method; // // private RequestLogBean request; // // private ResponseLogBean response; // // private Date date = new Date(); // // protected LogBean() { // } // // public LogBean(UUID key, LogType type) { // this.key = key.toString(); // this.type = type; // } // // } // // Path: src/main/java/org/mockenize/model/ResponseLogBean.java // @Data // public class ResponseLogBean implements Serializable { // // private static final long serialVersionUID = 1L; // // private Integer status; // // private Map<String, String> headers = new HashMap<>(); // // private transient JsonNode body; // } // // Path: src/main/java/org/mockenize/service/LoggingService.java // @Service // public class LoggingService { // // @Autowired // private LogRepository logRepository; // // public void save(LogBean logBean) { // logRepository.save(logBean); // } // // public Collection<LogBean> getAll() { // return logRepository.findAll(); // } // // public LogBean getByKey(UUID key) { // return logRepository.findByKey(key.toString()); // } // // // public LogBean delete(UUID key) { // return logRepository.delete(key.toString()); // } // // public Collection<LogBean> deleteAll() { // return logRepository.deleteAll(); // } // // @SuppressWarnings("unchecked") // public Collection<LogBean> findByFilters(JsonNode jsonNode) { // Iterator<String> fieldNames = jsonNode.fieldNames(); // Predicate<String, LogBean> predicate = null; // while(fieldNames.hasNext()) { // String field = fieldNames.next(); // String value = jsonNode.get(field).asText(); // // Predicate<String, LogBean> tmp = Predicates.equal(field, value); // if(predicate == null) { // predicate = tmp; // } else { // predicate = Predicates.and(predicate, tmp); // } // } // return logRepository.findByPredicate(predicate); // } // } // Path: src/main/java/org/mockenize/provider/filter/ResponseLoggingFilter.java import java.io.IOException; import java.io.InputStream; import java.util.List; import java.util.Map; import java.util.UUID; import javax.annotation.Priority; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerResponseContext; import javax.ws.rs.container.ContainerResponseFilter; import javax.ws.rs.ext.Provider; import org.mockenize.model.LogBean; import org.mockenize.model.ResponseLogBean; import org.mockenize.service.LoggingService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import com.google.common.collect.Maps; package org.mockenize.provider.filter; @Provider @Component @Priority(Integer.MAX_VALUE) public class ResponseLoggingFilter implements ContainerResponseFilter { public static final String KEY = "Mockenize-Id"; private static final Joiner joiner = Joiner.on(", "); @Autowired private ObjectMapper objectMapper; @Autowired
private LoggingService loggingService;
Mockenize/mockenize-server
src/main/java/org/mockenize/provider/filter/ResponseLoggingFilter.java
// Path: src/main/java/org/mockenize/model/LogBean.java // @Data // public class LogBean implements Serializable, Cacheable { // // private static final long serialVersionUID = 1L; // // private String key; // // private LogType type; // // private String url; // // private String path; // // private String method; // // private RequestLogBean request; // // private ResponseLogBean response; // // private Date date = new Date(); // // protected LogBean() { // } // // public LogBean(UUID key, LogType type) { // this.key = key.toString(); // this.type = type; // } // // } // // Path: src/main/java/org/mockenize/model/ResponseLogBean.java // @Data // public class ResponseLogBean implements Serializable { // // private static final long serialVersionUID = 1L; // // private Integer status; // // private Map<String, String> headers = new HashMap<>(); // // private transient JsonNode body; // } // // Path: src/main/java/org/mockenize/service/LoggingService.java // @Service // public class LoggingService { // // @Autowired // private LogRepository logRepository; // // public void save(LogBean logBean) { // logRepository.save(logBean); // } // // public Collection<LogBean> getAll() { // return logRepository.findAll(); // } // // public LogBean getByKey(UUID key) { // return logRepository.findByKey(key.toString()); // } // // // public LogBean delete(UUID key) { // return logRepository.delete(key.toString()); // } // // public Collection<LogBean> deleteAll() { // return logRepository.deleteAll(); // } // // @SuppressWarnings("unchecked") // public Collection<LogBean> findByFilters(JsonNode jsonNode) { // Iterator<String> fieldNames = jsonNode.fieldNames(); // Predicate<String, LogBean> predicate = null; // while(fieldNames.hasNext()) { // String field = fieldNames.next(); // String value = jsonNode.get(field).asText(); // // Predicate<String, LogBean> tmp = Predicates.equal(field, value); // if(predicate == null) { // predicate = tmp; // } else { // predicate = Predicates.and(predicate, tmp); // } // } // return logRepository.findByPredicate(predicate); // } // }
import java.io.IOException; import java.io.InputStream; import java.util.List; import java.util.Map; import java.util.UUID; import javax.annotation.Priority; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerResponseContext; import javax.ws.rs.container.ContainerResponseFilter; import javax.ws.rs.ext.Provider; import org.mockenize.model.LogBean; import org.mockenize.model.ResponseLogBean; import org.mockenize.service.LoggingService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import com.google.common.collect.Maps;
package org.mockenize.provider.filter; @Provider @Component @Priority(Integer.MAX_VALUE) public class ResponseLoggingFilter implements ContainerResponseFilter { public static final String KEY = "Mockenize-Id"; private static final Joiner joiner = Joiner.on(", "); @Autowired private ObjectMapper objectMapper; @Autowired private LoggingService loggingService; @Autowired private HttpServletRequest request; @Override public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException { Object key = request.getAttribute(KEY); if (key != null) {
// Path: src/main/java/org/mockenize/model/LogBean.java // @Data // public class LogBean implements Serializable, Cacheable { // // private static final long serialVersionUID = 1L; // // private String key; // // private LogType type; // // private String url; // // private String path; // // private String method; // // private RequestLogBean request; // // private ResponseLogBean response; // // private Date date = new Date(); // // protected LogBean() { // } // // public LogBean(UUID key, LogType type) { // this.key = key.toString(); // this.type = type; // } // // } // // Path: src/main/java/org/mockenize/model/ResponseLogBean.java // @Data // public class ResponseLogBean implements Serializable { // // private static final long serialVersionUID = 1L; // // private Integer status; // // private Map<String, String> headers = new HashMap<>(); // // private transient JsonNode body; // } // // Path: src/main/java/org/mockenize/service/LoggingService.java // @Service // public class LoggingService { // // @Autowired // private LogRepository logRepository; // // public void save(LogBean logBean) { // logRepository.save(logBean); // } // // public Collection<LogBean> getAll() { // return logRepository.findAll(); // } // // public LogBean getByKey(UUID key) { // return logRepository.findByKey(key.toString()); // } // // // public LogBean delete(UUID key) { // return logRepository.delete(key.toString()); // } // // public Collection<LogBean> deleteAll() { // return logRepository.deleteAll(); // } // // @SuppressWarnings("unchecked") // public Collection<LogBean> findByFilters(JsonNode jsonNode) { // Iterator<String> fieldNames = jsonNode.fieldNames(); // Predicate<String, LogBean> predicate = null; // while(fieldNames.hasNext()) { // String field = fieldNames.next(); // String value = jsonNode.get(field).asText(); // // Predicate<String, LogBean> tmp = Predicates.equal(field, value); // if(predicate == null) { // predicate = tmp; // } else { // predicate = Predicates.and(predicate, tmp); // } // } // return logRepository.findByPredicate(predicate); // } // } // Path: src/main/java/org/mockenize/provider/filter/ResponseLoggingFilter.java import java.io.IOException; import java.io.InputStream; import java.util.List; import java.util.Map; import java.util.UUID; import javax.annotation.Priority; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerResponseContext; import javax.ws.rs.container.ContainerResponseFilter; import javax.ws.rs.ext.Provider; import org.mockenize.model.LogBean; import org.mockenize.model.ResponseLogBean; import org.mockenize.service.LoggingService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import com.google.common.collect.Maps; package org.mockenize.provider.filter; @Provider @Component @Priority(Integer.MAX_VALUE) public class ResponseLoggingFilter implements ContainerResponseFilter { public static final String KEY = "Mockenize-Id"; private static final Joiner joiner = Joiner.on(", "); @Autowired private ObjectMapper objectMapper; @Autowired private LoggingService loggingService; @Autowired private HttpServletRequest request; @Override public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException { Object key = request.getAttribute(KEY); if (key != null) {
LogBean logBean = loggingService.getByKey((UUID) key);
Mockenize/mockenize-server
src/main/java/org/mockenize/provider/filter/ResponseLoggingFilter.java
// Path: src/main/java/org/mockenize/model/LogBean.java // @Data // public class LogBean implements Serializable, Cacheable { // // private static final long serialVersionUID = 1L; // // private String key; // // private LogType type; // // private String url; // // private String path; // // private String method; // // private RequestLogBean request; // // private ResponseLogBean response; // // private Date date = new Date(); // // protected LogBean() { // } // // public LogBean(UUID key, LogType type) { // this.key = key.toString(); // this.type = type; // } // // } // // Path: src/main/java/org/mockenize/model/ResponseLogBean.java // @Data // public class ResponseLogBean implements Serializable { // // private static final long serialVersionUID = 1L; // // private Integer status; // // private Map<String, String> headers = new HashMap<>(); // // private transient JsonNode body; // } // // Path: src/main/java/org/mockenize/service/LoggingService.java // @Service // public class LoggingService { // // @Autowired // private LogRepository logRepository; // // public void save(LogBean logBean) { // logRepository.save(logBean); // } // // public Collection<LogBean> getAll() { // return logRepository.findAll(); // } // // public LogBean getByKey(UUID key) { // return logRepository.findByKey(key.toString()); // } // // // public LogBean delete(UUID key) { // return logRepository.delete(key.toString()); // } // // public Collection<LogBean> deleteAll() { // return logRepository.deleteAll(); // } // // @SuppressWarnings("unchecked") // public Collection<LogBean> findByFilters(JsonNode jsonNode) { // Iterator<String> fieldNames = jsonNode.fieldNames(); // Predicate<String, LogBean> predicate = null; // while(fieldNames.hasNext()) { // String field = fieldNames.next(); // String value = jsonNode.get(field).asText(); // // Predicate<String, LogBean> tmp = Predicates.equal(field, value); // if(predicate == null) { // predicate = tmp; // } else { // predicate = Predicates.and(predicate, tmp); // } // } // return logRepository.findByPredicate(predicate); // } // }
import java.io.IOException; import java.io.InputStream; import java.util.List; import java.util.Map; import java.util.UUID; import javax.annotation.Priority; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerResponseContext; import javax.ws.rs.container.ContainerResponseFilter; import javax.ws.rs.ext.Provider; import org.mockenize.model.LogBean; import org.mockenize.model.ResponseLogBean; import org.mockenize.service.LoggingService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import com.google.common.collect.Maps;
package org.mockenize.provider.filter; @Provider @Component @Priority(Integer.MAX_VALUE) public class ResponseLoggingFilter implements ContainerResponseFilter { public static final String KEY = "Mockenize-Id"; private static final Joiner joiner = Joiner.on(", "); @Autowired private ObjectMapper objectMapper; @Autowired private LoggingService loggingService; @Autowired private HttpServletRequest request; @Override public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException { Object key = request.getAttribute(KEY); if (key != null) { LogBean logBean = loggingService.getByKey((UUID) key); if (logBean != null) { responseContext.getHeaders().put(KEY, Lists.<Object> newArrayList(key)); logBean.setResponse(mapResponseLogBean(responseContext)); loggingService.save(logBean); } } }
// Path: src/main/java/org/mockenize/model/LogBean.java // @Data // public class LogBean implements Serializable, Cacheable { // // private static final long serialVersionUID = 1L; // // private String key; // // private LogType type; // // private String url; // // private String path; // // private String method; // // private RequestLogBean request; // // private ResponseLogBean response; // // private Date date = new Date(); // // protected LogBean() { // } // // public LogBean(UUID key, LogType type) { // this.key = key.toString(); // this.type = type; // } // // } // // Path: src/main/java/org/mockenize/model/ResponseLogBean.java // @Data // public class ResponseLogBean implements Serializable { // // private static final long serialVersionUID = 1L; // // private Integer status; // // private Map<String, String> headers = new HashMap<>(); // // private transient JsonNode body; // } // // Path: src/main/java/org/mockenize/service/LoggingService.java // @Service // public class LoggingService { // // @Autowired // private LogRepository logRepository; // // public void save(LogBean logBean) { // logRepository.save(logBean); // } // // public Collection<LogBean> getAll() { // return logRepository.findAll(); // } // // public LogBean getByKey(UUID key) { // return logRepository.findByKey(key.toString()); // } // // // public LogBean delete(UUID key) { // return logRepository.delete(key.toString()); // } // // public Collection<LogBean> deleteAll() { // return logRepository.deleteAll(); // } // // @SuppressWarnings("unchecked") // public Collection<LogBean> findByFilters(JsonNode jsonNode) { // Iterator<String> fieldNames = jsonNode.fieldNames(); // Predicate<String, LogBean> predicate = null; // while(fieldNames.hasNext()) { // String field = fieldNames.next(); // String value = jsonNode.get(field).asText(); // // Predicate<String, LogBean> tmp = Predicates.equal(field, value); // if(predicate == null) { // predicate = tmp; // } else { // predicate = Predicates.and(predicate, tmp); // } // } // return logRepository.findByPredicate(predicate); // } // } // Path: src/main/java/org/mockenize/provider/filter/ResponseLoggingFilter.java import java.io.IOException; import java.io.InputStream; import java.util.List; import java.util.Map; import java.util.UUID; import javax.annotation.Priority; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerResponseContext; import javax.ws.rs.container.ContainerResponseFilter; import javax.ws.rs.ext.Provider; import org.mockenize.model.LogBean; import org.mockenize.model.ResponseLogBean; import org.mockenize.service.LoggingService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import com.google.common.collect.Maps; package org.mockenize.provider.filter; @Provider @Component @Priority(Integer.MAX_VALUE) public class ResponseLoggingFilter implements ContainerResponseFilter { public static final String KEY = "Mockenize-Id"; private static final Joiner joiner = Joiner.on(", "); @Autowired private ObjectMapper objectMapper; @Autowired private LoggingService loggingService; @Autowired private HttpServletRequest request; @Override public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException { Object key = request.getAttribute(KEY); if (key != null) { LogBean logBean = loggingService.getByKey((UUID) key); if (logBean != null) { responseContext.getHeaders().put(KEY, Lists.<Object> newArrayList(key)); logBean.setResponse(mapResponseLogBean(responseContext)); loggingService.save(logBean); } } }
private ResponseLogBean mapResponseLogBean(ContainerResponseContext responseContext) throws IOException {
Mockenize/mockenize-server
src/main/java/org/mockenize/repository/AbstractRepository.java
// Path: src/main/java/org/mockenize/vendor/hazelcast/predicate/PathPredicate.java // public class PathPredicate implements Predicate<String, Object> { // // private static final long serialVersionUID = 4605050326503577349L; // private final String value; // // public PathPredicate(String value) { // this.value = value.replaceAll("/", "_"); // } // // public PathPredicate(String... segments) { // StringBuilder stringBuilder = new StringBuilder(); // for (String segment : segments) { // stringBuilder.append(segment); // } // this.value = stringBuilder.toString().replaceAll("/", "_"); // } // // @Override // public boolean apply(Map.Entry<String, Object> mapEntry) { // return value.matches(mapEntry.getKey().replace("*", "[^/]+")); // } // }
import java.util.Collection; import java.util.Iterator; import java.util.Set; import org.mockenize.vendor.hazelcast.predicate.PathPredicate; import com.google.common.base.Function; import com.google.common.collect.Collections2; import com.hazelcast.core.HazelcastInstance; import com.hazelcast.core.IMap; import com.hazelcast.query.Predicate;
package org.mockenize.repository; public abstract class AbstractRepository<T extends Cacheable> { protected final IMap<String, T> map; public AbstractRepository(HazelcastInstance hazelcastInstance, String mapKey) { this.map = hazelcastInstance.getMap(mapKey); map.addIndex("key", Boolean.TRUE); } public T findByKey(String key) {
// Path: src/main/java/org/mockenize/vendor/hazelcast/predicate/PathPredicate.java // public class PathPredicate implements Predicate<String, Object> { // // private static final long serialVersionUID = 4605050326503577349L; // private final String value; // // public PathPredicate(String value) { // this.value = value.replaceAll("/", "_"); // } // // public PathPredicate(String... segments) { // StringBuilder stringBuilder = new StringBuilder(); // for (String segment : segments) { // stringBuilder.append(segment); // } // this.value = stringBuilder.toString().replaceAll("/", "_"); // } // // @Override // public boolean apply(Map.Entry<String, Object> mapEntry) { // return value.matches(mapEntry.getKey().replace("*", "[^/]+")); // } // } // Path: src/main/java/org/mockenize/repository/AbstractRepository.java import java.util.Collection; import java.util.Iterator; import java.util.Set; import org.mockenize.vendor.hazelcast.predicate.PathPredicate; import com.google.common.base.Function; import com.google.common.collect.Collections2; import com.hazelcast.core.HazelcastInstance; import com.hazelcast.core.IMap; import com.hazelcast.query.Predicate; package org.mockenize.repository; public abstract class AbstractRepository<T extends Cacheable> { protected final IMap<String, T> map; public AbstractRepository(HazelcastInstance hazelcastInstance, String mapKey) { this.map = hazelcastInstance.getMap(mapKey); map.addIndex("key", Boolean.TRUE); } public T findByKey(String key) {
Set<String> keys = map.keySet(new PathPredicate(key));
Mockenize/mockenize-server
src/main/java/org/mockenize/service/ScriptService.java
// Path: src/main/java/org/mockenize/exception/ScriptExecutionException.java // public class ScriptExecutionException extends WebApplicationException { // // private static final long serialVersionUID = -4348584639704062868L; // // public ScriptExecutionException(Throwable cause) { // super(cause, Response.Status.NOT_FOUND); // } // } // // Path: src/main/java/org/mockenize/exception/ScriptNotFoundException.java // public class ScriptNotFoundException extends WebApplicationException { // // private static final long serialVersionUID = 3414602294218839377L; // // public ScriptNotFoundException(String scriptName) { // super("JS not found: " + scriptName, Response.Status.NOT_FOUND); // } // } // // Path: src/main/java/org/mockenize/model/ScriptBean.java // @Data // public class ScriptBean implements Serializable, Cacheable { // // private static final long serialVersionUID = 1L; // // private String name; // // private String value; // // public ScriptBean(String name, String value) { // this.name = name; // this.value = value; // } // // @Override // public String getKey() { // return this.name; // } // } // // Path: src/main/java/org/mockenize/repository/ScriptRespository.java // @Repository // public class ScriptRespository extends AbstractRepository<ScriptBean> { // // private static final String CACHE_KEY = "scripts"; // // @Autowired // public ScriptRespository(HazelcastInstance hazelcastInstance) { // super(hazelcastInstance, CACHE_KEY); // } // // }
import java.io.IOException; import java.util.Collection; import javax.script.Invocable; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; import org.mockenize.exception.ScriptExecutionException; import org.mockenize.exception.ScriptNotFoundException; import org.mockenize.model.ScriptBean; import org.mockenize.repository.ScriptRespository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper;
package org.mockenize.service; @Service public class ScriptService { private static final String ENGINE_NAME = "JavaScript"; private static final String DEFAUL_FUNCTION_NAME = "_func"; private static final String PARSE_FUNCTION = "function _func(url, body) {" + "obj=null;try{obj=JSON.parse(body)}catch(ex){};" + "ret = func(url, body, obj);" + "try{return (typeof ret === 'string') ? ret : JSON.stringify(ret)}catch(ex){};" + "return ret};"; private static final String EMPTY = ""; @Autowired private ObjectMapper objectMapper; @Autowired
// Path: src/main/java/org/mockenize/exception/ScriptExecutionException.java // public class ScriptExecutionException extends WebApplicationException { // // private static final long serialVersionUID = -4348584639704062868L; // // public ScriptExecutionException(Throwable cause) { // super(cause, Response.Status.NOT_FOUND); // } // } // // Path: src/main/java/org/mockenize/exception/ScriptNotFoundException.java // public class ScriptNotFoundException extends WebApplicationException { // // private static final long serialVersionUID = 3414602294218839377L; // // public ScriptNotFoundException(String scriptName) { // super("JS not found: " + scriptName, Response.Status.NOT_FOUND); // } // } // // Path: src/main/java/org/mockenize/model/ScriptBean.java // @Data // public class ScriptBean implements Serializable, Cacheable { // // private static final long serialVersionUID = 1L; // // private String name; // // private String value; // // public ScriptBean(String name, String value) { // this.name = name; // this.value = value; // } // // @Override // public String getKey() { // return this.name; // } // } // // Path: src/main/java/org/mockenize/repository/ScriptRespository.java // @Repository // public class ScriptRespository extends AbstractRepository<ScriptBean> { // // private static final String CACHE_KEY = "scripts"; // // @Autowired // public ScriptRespository(HazelcastInstance hazelcastInstance) { // super(hazelcastInstance, CACHE_KEY); // } // // } // Path: src/main/java/org/mockenize/service/ScriptService.java import java.io.IOException; import java.util.Collection; import javax.script.Invocable; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; import org.mockenize.exception.ScriptExecutionException; import org.mockenize.exception.ScriptNotFoundException; import org.mockenize.model.ScriptBean; import org.mockenize.repository.ScriptRespository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; package org.mockenize.service; @Service public class ScriptService { private static final String ENGINE_NAME = "JavaScript"; private static final String DEFAUL_FUNCTION_NAME = "_func"; private static final String PARSE_FUNCTION = "function _func(url, body) {" + "obj=null;try{obj=JSON.parse(body)}catch(ex){};" + "ret = func(url, body, obj);" + "try{return (typeof ret === 'string') ? ret : JSON.stringify(ret)}catch(ex){};" + "return ret};"; private static final String EMPTY = ""; @Autowired private ObjectMapper objectMapper; @Autowired
private ScriptRespository scriptRespository;
Mockenize/mockenize-server
src/main/java/org/mockenize/service/ScriptService.java
// Path: src/main/java/org/mockenize/exception/ScriptExecutionException.java // public class ScriptExecutionException extends WebApplicationException { // // private static final long serialVersionUID = -4348584639704062868L; // // public ScriptExecutionException(Throwable cause) { // super(cause, Response.Status.NOT_FOUND); // } // } // // Path: src/main/java/org/mockenize/exception/ScriptNotFoundException.java // public class ScriptNotFoundException extends WebApplicationException { // // private static final long serialVersionUID = 3414602294218839377L; // // public ScriptNotFoundException(String scriptName) { // super("JS not found: " + scriptName, Response.Status.NOT_FOUND); // } // } // // Path: src/main/java/org/mockenize/model/ScriptBean.java // @Data // public class ScriptBean implements Serializable, Cacheable { // // private static final long serialVersionUID = 1L; // // private String name; // // private String value; // // public ScriptBean(String name, String value) { // this.name = name; // this.value = value; // } // // @Override // public String getKey() { // return this.name; // } // } // // Path: src/main/java/org/mockenize/repository/ScriptRespository.java // @Repository // public class ScriptRespository extends AbstractRepository<ScriptBean> { // // private static final String CACHE_KEY = "scripts"; // // @Autowired // public ScriptRespository(HazelcastInstance hazelcastInstance) { // super(hazelcastInstance, CACHE_KEY); // } // // }
import java.io.IOException; import java.util.Collection; import javax.script.Invocable; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; import org.mockenize.exception.ScriptExecutionException; import org.mockenize.exception.ScriptNotFoundException; import org.mockenize.model.ScriptBean; import org.mockenize.repository.ScriptRespository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper;
package org.mockenize.service; @Service public class ScriptService { private static final String ENGINE_NAME = "JavaScript"; private static final String DEFAUL_FUNCTION_NAME = "_func"; private static final String PARSE_FUNCTION = "function _func(url, body) {" + "obj=null;try{obj=JSON.parse(body)}catch(ex){};" + "ret = func(url, body, obj);" + "try{return (typeof ret === 'string') ? ret : JSON.stringify(ret)}catch(ex){};" + "return ret};"; private static final String EMPTY = ""; @Autowired private ObjectMapper objectMapper; @Autowired private ScriptRespository scriptRespository;
// Path: src/main/java/org/mockenize/exception/ScriptExecutionException.java // public class ScriptExecutionException extends WebApplicationException { // // private static final long serialVersionUID = -4348584639704062868L; // // public ScriptExecutionException(Throwable cause) { // super(cause, Response.Status.NOT_FOUND); // } // } // // Path: src/main/java/org/mockenize/exception/ScriptNotFoundException.java // public class ScriptNotFoundException extends WebApplicationException { // // private static final long serialVersionUID = 3414602294218839377L; // // public ScriptNotFoundException(String scriptName) { // super("JS not found: " + scriptName, Response.Status.NOT_FOUND); // } // } // // Path: src/main/java/org/mockenize/model/ScriptBean.java // @Data // public class ScriptBean implements Serializable, Cacheable { // // private static final long serialVersionUID = 1L; // // private String name; // // private String value; // // public ScriptBean(String name, String value) { // this.name = name; // this.value = value; // } // // @Override // public String getKey() { // return this.name; // } // } // // Path: src/main/java/org/mockenize/repository/ScriptRespository.java // @Repository // public class ScriptRespository extends AbstractRepository<ScriptBean> { // // private static final String CACHE_KEY = "scripts"; // // @Autowired // public ScriptRespository(HazelcastInstance hazelcastInstance) { // super(hazelcastInstance, CACHE_KEY); // } // // } // Path: src/main/java/org/mockenize/service/ScriptService.java import java.io.IOException; import java.util.Collection; import javax.script.Invocable; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; import org.mockenize.exception.ScriptExecutionException; import org.mockenize.exception.ScriptNotFoundException; import org.mockenize.model.ScriptBean; import org.mockenize.repository.ScriptRespository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; package org.mockenize.service; @Service public class ScriptService { private static final String ENGINE_NAME = "JavaScript"; private static final String DEFAUL_FUNCTION_NAME = "_func"; private static final String PARSE_FUNCTION = "function _func(url, body) {" + "obj=null;try{obj=JSON.parse(body)}catch(ex){};" + "ret = func(url, body, obj);" + "try{return (typeof ret === 'string') ? ret : JSON.stringify(ret)}catch(ex){};" + "return ret};"; private static final String EMPTY = ""; @Autowired private ObjectMapper objectMapper; @Autowired private ScriptRespository scriptRespository;
public ScriptBean getByKey(String jsName) {
Mockenize/mockenize-server
src/main/java/org/mockenize/service/ScriptService.java
// Path: src/main/java/org/mockenize/exception/ScriptExecutionException.java // public class ScriptExecutionException extends WebApplicationException { // // private static final long serialVersionUID = -4348584639704062868L; // // public ScriptExecutionException(Throwable cause) { // super(cause, Response.Status.NOT_FOUND); // } // } // // Path: src/main/java/org/mockenize/exception/ScriptNotFoundException.java // public class ScriptNotFoundException extends WebApplicationException { // // private static final long serialVersionUID = 3414602294218839377L; // // public ScriptNotFoundException(String scriptName) { // super("JS not found: " + scriptName, Response.Status.NOT_FOUND); // } // } // // Path: src/main/java/org/mockenize/model/ScriptBean.java // @Data // public class ScriptBean implements Serializable, Cacheable { // // private static final long serialVersionUID = 1L; // // private String name; // // private String value; // // public ScriptBean(String name, String value) { // this.name = name; // this.value = value; // } // // @Override // public String getKey() { // return this.name; // } // } // // Path: src/main/java/org/mockenize/repository/ScriptRespository.java // @Repository // public class ScriptRespository extends AbstractRepository<ScriptBean> { // // private static final String CACHE_KEY = "scripts"; // // @Autowired // public ScriptRespository(HazelcastInstance hazelcastInstance) { // super(hazelcastInstance, CACHE_KEY); // } // // }
import java.io.IOException; import java.util.Collection; import javax.script.Invocable; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; import org.mockenize.exception.ScriptExecutionException; import org.mockenize.exception.ScriptNotFoundException; import org.mockenize.model.ScriptBean; import org.mockenize.repository.ScriptRespository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper;
package org.mockenize.service; @Service public class ScriptService { private static final String ENGINE_NAME = "JavaScript"; private static final String DEFAUL_FUNCTION_NAME = "_func"; private static final String PARSE_FUNCTION = "function _func(url, body) {" + "obj=null;try{obj=JSON.parse(body)}catch(ex){};" + "ret = func(url, body, obj);" + "try{return (typeof ret === 'string') ? ret : JSON.stringify(ret)}catch(ex){};" + "return ret};"; private static final String EMPTY = ""; @Autowired private ObjectMapper objectMapper; @Autowired private ScriptRespository scriptRespository; public ScriptBean getByKey(String jsName) { ScriptBean scriptBean = scriptRespository.findByKey(jsName); if (scriptBean == null) {
// Path: src/main/java/org/mockenize/exception/ScriptExecutionException.java // public class ScriptExecutionException extends WebApplicationException { // // private static final long serialVersionUID = -4348584639704062868L; // // public ScriptExecutionException(Throwable cause) { // super(cause, Response.Status.NOT_FOUND); // } // } // // Path: src/main/java/org/mockenize/exception/ScriptNotFoundException.java // public class ScriptNotFoundException extends WebApplicationException { // // private static final long serialVersionUID = 3414602294218839377L; // // public ScriptNotFoundException(String scriptName) { // super("JS not found: " + scriptName, Response.Status.NOT_FOUND); // } // } // // Path: src/main/java/org/mockenize/model/ScriptBean.java // @Data // public class ScriptBean implements Serializable, Cacheable { // // private static final long serialVersionUID = 1L; // // private String name; // // private String value; // // public ScriptBean(String name, String value) { // this.name = name; // this.value = value; // } // // @Override // public String getKey() { // return this.name; // } // } // // Path: src/main/java/org/mockenize/repository/ScriptRespository.java // @Repository // public class ScriptRespository extends AbstractRepository<ScriptBean> { // // private static final String CACHE_KEY = "scripts"; // // @Autowired // public ScriptRespository(HazelcastInstance hazelcastInstance) { // super(hazelcastInstance, CACHE_KEY); // } // // } // Path: src/main/java/org/mockenize/service/ScriptService.java import java.io.IOException; import java.util.Collection; import javax.script.Invocable; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; import org.mockenize.exception.ScriptExecutionException; import org.mockenize.exception.ScriptNotFoundException; import org.mockenize.model.ScriptBean; import org.mockenize.repository.ScriptRespository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; package org.mockenize.service; @Service public class ScriptService { private static final String ENGINE_NAME = "JavaScript"; private static final String DEFAUL_FUNCTION_NAME = "_func"; private static final String PARSE_FUNCTION = "function _func(url, body) {" + "obj=null;try{obj=JSON.parse(body)}catch(ex){};" + "ret = func(url, body, obj);" + "try{return (typeof ret === 'string') ? ret : JSON.stringify(ret)}catch(ex){};" + "return ret};"; private static final String EMPTY = ""; @Autowired private ObjectMapper objectMapper; @Autowired private ScriptRespository scriptRespository; public ScriptBean getByKey(String jsName) { ScriptBean scriptBean = scriptRespository.findByKey(jsName); if (scriptBean == null) {
throw new ScriptNotFoundException(jsName);
Mockenize/mockenize-server
src/main/java/org/mockenize/service/ScriptService.java
// Path: src/main/java/org/mockenize/exception/ScriptExecutionException.java // public class ScriptExecutionException extends WebApplicationException { // // private static final long serialVersionUID = -4348584639704062868L; // // public ScriptExecutionException(Throwable cause) { // super(cause, Response.Status.NOT_FOUND); // } // } // // Path: src/main/java/org/mockenize/exception/ScriptNotFoundException.java // public class ScriptNotFoundException extends WebApplicationException { // // private static final long serialVersionUID = 3414602294218839377L; // // public ScriptNotFoundException(String scriptName) { // super("JS not found: " + scriptName, Response.Status.NOT_FOUND); // } // } // // Path: src/main/java/org/mockenize/model/ScriptBean.java // @Data // public class ScriptBean implements Serializable, Cacheable { // // private static final long serialVersionUID = 1L; // // private String name; // // private String value; // // public ScriptBean(String name, String value) { // this.name = name; // this.value = value; // } // // @Override // public String getKey() { // return this.name; // } // } // // Path: src/main/java/org/mockenize/repository/ScriptRespository.java // @Repository // public class ScriptRespository extends AbstractRepository<ScriptBean> { // // private static final String CACHE_KEY = "scripts"; // // @Autowired // public ScriptRespository(HazelcastInstance hazelcastInstance) { // super(hazelcastInstance, CACHE_KEY); // } // // }
import java.io.IOException; import java.util.Collection; import javax.script.Invocable; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; import org.mockenize.exception.ScriptExecutionException; import org.mockenize.exception.ScriptNotFoundException; import org.mockenize.model.ScriptBean; import org.mockenize.repository.ScriptRespository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper;
} return scriptBean; } public ScriptBean delete(ScriptBean scriptBean) { return scriptRespository.delete(scriptBean.getName()); } public Collection<ScriptBean> deleteAll() { return scriptRespository.deleteAll(); } public void save(ScriptBean scriptBean) { scriptRespository.save(scriptBean); } public Collection<ScriptBean> getAll() { return scriptRespository.findAll(); } public JsonNode execute(ScriptBean scriptBean, String uri, JsonNode body) { try { ScriptEngine scriptEngine = new ScriptEngineManager().getEngineByName(ENGINE_NAME); scriptEngine.eval(PARSE_FUNCTION + scriptBean.getValue()); Invocable invocable = (Invocable) scriptEngine; String stringBody = body != null ? body.toString() : EMPTY; String ret = String.valueOf(invocable.invokeFunction(DEFAUL_FUNCTION_NAME, uri, stringBody)); return parse(ret); } catch (NoSuchMethodException | ScriptException | IOException e) {
// Path: src/main/java/org/mockenize/exception/ScriptExecutionException.java // public class ScriptExecutionException extends WebApplicationException { // // private static final long serialVersionUID = -4348584639704062868L; // // public ScriptExecutionException(Throwable cause) { // super(cause, Response.Status.NOT_FOUND); // } // } // // Path: src/main/java/org/mockenize/exception/ScriptNotFoundException.java // public class ScriptNotFoundException extends WebApplicationException { // // private static final long serialVersionUID = 3414602294218839377L; // // public ScriptNotFoundException(String scriptName) { // super("JS not found: " + scriptName, Response.Status.NOT_FOUND); // } // } // // Path: src/main/java/org/mockenize/model/ScriptBean.java // @Data // public class ScriptBean implements Serializable, Cacheable { // // private static final long serialVersionUID = 1L; // // private String name; // // private String value; // // public ScriptBean(String name, String value) { // this.name = name; // this.value = value; // } // // @Override // public String getKey() { // return this.name; // } // } // // Path: src/main/java/org/mockenize/repository/ScriptRespository.java // @Repository // public class ScriptRespository extends AbstractRepository<ScriptBean> { // // private static final String CACHE_KEY = "scripts"; // // @Autowired // public ScriptRespository(HazelcastInstance hazelcastInstance) { // super(hazelcastInstance, CACHE_KEY); // } // // } // Path: src/main/java/org/mockenize/service/ScriptService.java import java.io.IOException; import java.util.Collection; import javax.script.Invocable; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; import org.mockenize.exception.ScriptExecutionException; import org.mockenize.exception.ScriptNotFoundException; import org.mockenize.model.ScriptBean; import org.mockenize.repository.ScriptRespository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; } return scriptBean; } public ScriptBean delete(ScriptBean scriptBean) { return scriptRespository.delete(scriptBean.getName()); } public Collection<ScriptBean> deleteAll() { return scriptRespository.deleteAll(); } public void save(ScriptBean scriptBean) { scriptRespository.save(scriptBean); } public Collection<ScriptBean> getAll() { return scriptRespository.findAll(); } public JsonNode execute(ScriptBean scriptBean, String uri, JsonNode body) { try { ScriptEngine scriptEngine = new ScriptEngineManager().getEngineByName(ENGINE_NAME); scriptEngine.eval(PARSE_FUNCTION + scriptBean.getValue()); Invocable invocable = (Invocable) scriptEngine; String stringBody = body != null ? body.toString() : EMPTY; String ret = String.valueOf(invocable.invokeFunction(DEFAUL_FUNCTION_NAME, uri, stringBody)); return parse(ret); } catch (NoSuchMethodException | ScriptException | IOException e) {
throw new ScriptExecutionException(e);
Mockenize/mockenize-server
src/main/java/org/mockenize/controller/LogController.java
// Path: src/main/java/org/mockenize/model/LogBean.java // @Data // public class LogBean implements Serializable, Cacheable { // // private static final long serialVersionUID = 1L; // // private String key; // // private LogType type; // // private String url; // // private String path; // // private String method; // // private RequestLogBean request; // // private ResponseLogBean response; // // private Date date = new Date(); // // protected LogBean() { // } // // public LogBean(UUID key, LogType type) { // this.key = key.toString(); // this.type = type; // } // // } // // Path: src/main/java/org/mockenize/service/LoggingService.java // @Service // public class LoggingService { // // @Autowired // private LogRepository logRepository; // // public void save(LogBean logBean) { // logRepository.save(logBean); // } // // public Collection<LogBean> getAll() { // return logRepository.findAll(); // } // // public LogBean getByKey(UUID key) { // return logRepository.findByKey(key.toString()); // } // // // public LogBean delete(UUID key) { // return logRepository.delete(key.toString()); // } // // public Collection<LogBean> deleteAll() { // return logRepository.deleteAll(); // } // // @SuppressWarnings("unchecked") // public Collection<LogBean> findByFilters(JsonNode jsonNode) { // Iterator<String> fieldNames = jsonNode.fieldNames(); // Predicate<String, LogBean> predicate = null; // while(fieldNames.hasNext()) { // String field = fieldNames.next(); // String value = jsonNode.get(field).asText(); // // Predicate<String, LogBean> tmp = Predicates.equal(field, value); // if(predicate == null) { // predicate = tmp; // } else { // predicate = Predicates.and(predicate, tmp); // } // } // return logRepository.findByPredicate(predicate); // } // }
import java.util.Collection; import java.util.UUID; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.mockenize.model.LogBean; import org.mockenize.service.LoggingService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import com.fasterxml.jackson.databind.JsonNode;
package org.mockenize.controller; @Controller @Path("/_mockenize/logs") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public class LogController { @Autowired
// Path: src/main/java/org/mockenize/model/LogBean.java // @Data // public class LogBean implements Serializable, Cacheable { // // private static final long serialVersionUID = 1L; // // private String key; // // private LogType type; // // private String url; // // private String path; // // private String method; // // private RequestLogBean request; // // private ResponseLogBean response; // // private Date date = new Date(); // // protected LogBean() { // } // // public LogBean(UUID key, LogType type) { // this.key = key.toString(); // this.type = type; // } // // } // // Path: src/main/java/org/mockenize/service/LoggingService.java // @Service // public class LoggingService { // // @Autowired // private LogRepository logRepository; // // public void save(LogBean logBean) { // logRepository.save(logBean); // } // // public Collection<LogBean> getAll() { // return logRepository.findAll(); // } // // public LogBean getByKey(UUID key) { // return logRepository.findByKey(key.toString()); // } // // // public LogBean delete(UUID key) { // return logRepository.delete(key.toString()); // } // // public Collection<LogBean> deleteAll() { // return logRepository.deleteAll(); // } // // @SuppressWarnings("unchecked") // public Collection<LogBean> findByFilters(JsonNode jsonNode) { // Iterator<String> fieldNames = jsonNode.fieldNames(); // Predicate<String, LogBean> predicate = null; // while(fieldNames.hasNext()) { // String field = fieldNames.next(); // String value = jsonNode.get(field).asText(); // // Predicate<String, LogBean> tmp = Predicates.equal(field, value); // if(predicate == null) { // predicate = tmp; // } else { // predicate = Predicates.and(predicate, tmp); // } // } // return logRepository.findByPredicate(predicate); // } // } // Path: src/main/java/org/mockenize/controller/LogController.java import java.util.Collection; import java.util.UUID; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.mockenize.model.LogBean; import org.mockenize.service.LoggingService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import com.fasterxml.jackson.databind.JsonNode; package org.mockenize.controller; @Controller @Path("/_mockenize/logs") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public class LogController { @Autowired
private LoggingService loggingService;
Mockenize/mockenize-server
src/main/java/org/mockenize/controller/LogController.java
// Path: src/main/java/org/mockenize/model/LogBean.java // @Data // public class LogBean implements Serializable, Cacheable { // // private static final long serialVersionUID = 1L; // // private String key; // // private LogType type; // // private String url; // // private String path; // // private String method; // // private RequestLogBean request; // // private ResponseLogBean response; // // private Date date = new Date(); // // protected LogBean() { // } // // public LogBean(UUID key, LogType type) { // this.key = key.toString(); // this.type = type; // } // // } // // Path: src/main/java/org/mockenize/service/LoggingService.java // @Service // public class LoggingService { // // @Autowired // private LogRepository logRepository; // // public void save(LogBean logBean) { // logRepository.save(logBean); // } // // public Collection<LogBean> getAll() { // return logRepository.findAll(); // } // // public LogBean getByKey(UUID key) { // return logRepository.findByKey(key.toString()); // } // // // public LogBean delete(UUID key) { // return logRepository.delete(key.toString()); // } // // public Collection<LogBean> deleteAll() { // return logRepository.deleteAll(); // } // // @SuppressWarnings("unchecked") // public Collection<LogBean> findByFilters(JsonNode jsonNode) { // Iterator<String> fieldNames = jsonNode.fieldNames(); // Predicate<String, LogBean> predicate = null; // while(fieldNames.hasNext()) { // String field = fieldNames.next(); // String value = jsonNode.get(field).asText(); // // Predicate<String, LogBean> tmp = Predicates.equal(field, value); // if(predicate == null) { // predicate = tmp; // } else { // predicate = Predicates.and(predicate, tmp); // } // } // return logRepository.findByPredicate(predicate); // } // }
import java.util.Collection; import java.util.UUID; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.mockenize.model.LogBean; import org.mockenize.service.LoggingService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import com.fasterxml.jackson.databind.JsonNode;
package org.mockenize.controller; @Controller @Path("/_mockenize/logs") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public class LogController { @Autowired private LoggingService loggingService; @GET public Response getAll() {
// Path: src/main/java/org/mockenize/model/LogBean.java // @Data // public class LogBean implements Serializable, Cacheable { // // private static final long serialVersionUID = 1L; // // private String key; // // private LogType type; // // private String url; // // private String path; // // private String method; // // private RequestLogBean request; // // private ResponseLogBean response; // // private Date date = new Date(); // // protected LogBean() { // } // // public LogBean(UUID key, LogType type) { // this.key = key.toString(); // this.type = type; // } // // } // // Path: src/main/java/org/mockenize/service/LoggingService.java // @Service // public class LoggingService { // // @Autowired // private LogRepository logRepository; // // public void save(LogBean logBean) { // logRepository.save(logBean); // } // // public Collection<LogBean> getAll() { // return logRepository.findAll(); // } // // public LogBean getByKey(UUID key) { // return logRepository.findByKey(key.toString()); // } // // // public LogBean delete(UUID key) { // return logRepository.delete(key.toString()); // } // // public Collection<LogBean> deleteAll() { // return logRepository.deleteAll(); // } // // @SuppressWarnings("unchecked") // public Collection<LogBean> findByFilters(JsonNode jsonNode) { // Iterator<String> fieldNames = jsonNode.fieldNames(); // Predicate<String, LogBean> predicate = null; // while(fieldNames.hasNext()) { // String field = fieldNames.next(); // String value = jsonNode.get(field).asText(); // // Predicate<String, LogBean> tmp = Predicates.equal(field, value); // if(predicate == null) { // predicate = tmp; // } else { // predicate = Predicates.and(predicate, tmp); // } // } // return logRepository.findByPredicate(predicate); // } // } // Path: src/main/java/org/mockenize/controller/LogController.java import java.util.Collection; import java.util.UUID; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.mockenize.model.LogBean; import org.mockenize.service.LoggingService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import com.fasterxml.jackson.databind.JsonNode; package org.mockenize.controller; @Controller @Path("/_mockenize/logs") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public class LogController { @Autowired private LoggingService loggingService; @GET public Response getAll() {
Collection<LogBean> logs = loggingService.getAll();
susom/database
src/main/java/com/github/susom/database/SqlInsertImpl.java
// Path: src/main/java/com/github/susom/database/MixedParameterSql.java // public static class RewriteArg { // private final String sql; // // public RewriteArg(String sql) { // this.sql = sql; // } // }
import java.io.InputStream; import java.io.Reader; import java.io.StringReader; import java.math.BigDecimal; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement; import java.time.LocalDate; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Nonnull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.github.susom.database.MixedParameterSql.RewriteArg;
@Override @Nonnull public SqlInsert argLocalDate(@Nonnull String argName, LocalDate arg) { return namedArg(argName, adaptor.nullLocalDate(arg)); } @Override @Nonnull public SqlInsert argLocalDate(LocalDate arg) { return positionalArg(adaptor.nullLocalDate(arg)); } @Nonnull @Override public SqlInsert argDateNowPerApp() { return positionalArg(adaptor.nullDate(options.currentDate())); } @Override @Nonnull public SqlInsert argDateNowPerApp(@Nonnull String argName) { return namedArg(argName, adaptor.nullDate(options.currentDate())); } @Nonnull @Override public SqlInsert argDateNowPerDb() { if (options.useDatePerAppOnly()) { return positionalArg(adaptor.nullDate(options.currentDate())); }
// Path: src/main/java/com/github/susom/database/MixedParameterSql.java // public static class RewriteArg { // private final String sql; // // public RewriteArg(String sql) { // this.sql = sql; // } // } // Path: src/main/java/com/github/susom/database/SqlInsertImpl.java import java.io.InputStream; import java.io.Reader; import java.io.StringReader; import java.math.BigDecimal; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement; import java.time.LocalDate; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Nonnull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.github.susom.database.MixedParameterSql.RewriteArg; @Override @Nonnull public SqlInsert argLocalDate(@Nonnull String argName, LocalDate arg) { return namedArg(argName, adaptor.nullLocalDate(arg)); } @Override @Nonnull public SqlInsert argLocalDate(LocalDate arg) { return positionalArg(adaptor.nullLocalDate(arg)); } @Nonnull @Override public SqlInsert argDateNowPerApp() { return positionalArg(adaptor.nullDate(options.currentDate())); } @Override @Nonnull public SqlInsert argDateNowPerApp(@Nonnull String argName) { return namedArg(argName, adaptor.nullDate(options.currentDate())); } @Nonnull @Override public SqlInsert argDateNowPerDb() { if (options.useDatePerAppOnly()) { return positionalArg(adaptor.nullDate(options.currentDate())); }
return positionalArg(new RewriteArg(options.flavor().dbTimeMillis()));
susom/database
src/main/java/com/github/susom/database/DebugSql.java
// Path: src/main/java/com/github/susom/database/MixedParameterSql.java // static class SecretArg { // private final Object arg; // // SecretArg(Object arg) { // this.arg = arg; // } // // Object getArg() { // return arg; // } // // @Override // public String toString() { // return "<secret>"; // } // }
import java.io.InputStream; import java.io.Reader; import java.util.Arrays; import java.util.Date; import org.slf4j.Logger; import com.github.susom.database.MixedParameterSql.SecretArg;
if (includeExecSql) { buf.append(removeTabs(sql)); } if (includeParameters && argsToPrint.length > 0) { if (includeExecSql) { buf.append(PARAM_SQL_SEPARATOR); } for (int i = 0; i < argsToPrint.length; i++) { buf.append(removeTabs(sqlParts[i])); Object argToPrint = argsToPrint[i]; if (argToPrint instanceof String) { String argToPrintString = (String) argToPrint; int maxLength = options.maxStringLengthParam(); if (argToPrintString.length() > maxLength && maxLength > 0) { buf.append("'").append(argToPrintString.substring(0, maxLength)).append("...'"); } else { buf.append("'"); buf.append(removeTabs(escapeSingleQuoted(argToPrintString))); buf.append("'"); } } else if (argToPrint instanceof StatementAdaptor.SqlNull || argToPrint == null) { buf.append("null"); } else if (argToPrint instanceof java.sql.Timestamp) { buf.append(options.flavor().dateAsSqlFunction((Date) argToPrint, options.calendarForTimestamps())); } else if (argToPrint instanceof java.sql.Date) { buf.append(options.flavor().localDateAsSqlFunction((Date) argToPrint)); } else if (argToPrint instanceof Number) { buf.append(argToPrint); } else if (argToPrint instanceof Boolean) { buf.append(((Boolean) argToPrint) ? "'Y'" : "'N'");
// Path: src/main/java/com/github/susom/database/MixedParameterSql.java // static class SecretArg { // private final Object arg; // // SecretArg(Object arg) { // this.arg = arg; // } // // Object getArg() { // return arg; // } // // @Override // public String toString() { // return "<secret>"; // } // } // Path: src/main/java/com/github/susom/database/DebugSql.java import java.io.InputStream; import java.io.Reader; import java.util.Arrays; import java.util.Date; import org.slf4j.Logger; import com.github.susom.database.MixedParameterSql.SecretArg; if (includeExecSql) { buf.append(removeTabs(sql)); } if (includeParameters && argsToPrint.length > 0) { if (includeExecSql) { buf.append(PARAM_SQL_SEPARATOR); } for (int i = 0; i < argsToPrint.length; i++) { buf.append(removeTabs(sqlParts[i])); Object argToPrint = argsToPrint[i]; if (argToPrint instanceof String) { String argToPrintString = (String) argToPrint; int maxLength = options.maxStringLengthParam(); if (argToPrintString.length() > maxLength && maxLength > 0) { buf.append("'").append(argToPrintString.substring(0, maxLength)).append("...'"); } else { buf.append("'"); buf.append(removeTabs(escapeSingleQuoted(argToPrintString))); buf.append("'"); } } else if (argToPrint instanceof StatementAdaptor.SqlNull || argToPrint == null) { buf.append("null"); } else if (argToPrint instanceof java.sql.Timestamp) { buf.append(options.flavor().dateAsSqlFunction((Date) argToPrint, options.calendarForTimestamps())); } else if (argToPrint instanceof java.sql.Date) { buf.append(options.flavor().localDateAsSqlFunction((Date) argToPrint)); } else if (argToPrint instanceof Number) { buf.append(argToPrint); } else if (argToPrint instanceof Boolean) { buf.append(((Boolean) argToPrint) ? "'Y'" : "'N'");
} else if (argToPrint instanceof SecretArg) {
susom/database
src/main/java/com/github/susom/database/DatabaseProviderVertx.java
// Path: src/main/java/com/github/susom/database/DatabaseProvider.java // public static class Pool { // public DataSource dataSource; // public int size; // public Flavor flavor; // public Closeable poolShutdown; // // public Pool(DataSource dataSource, int size, Flavor flavor, Closeable poolShutdown) { // this.dataSource = dataSource; // this.size = size; // this.flavor = flavor; // this.poolShutdown = poolShutdown; // } // }
import io.vertx.core.AsyncResult; import io.vertx.core.Handler; import io.vertx.core.Vertx; import io.vertx.core.WorkerExecutor; import java.io.Closeable; import java.io.IOException; import java.sql.Connection; import java.sql.SQLException; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Supplier; import javax.annotation.CheckReturnValue; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.github.susom.database.DatabaseProvider.Pool;
* url; prompted on standard input if user is provided and * password is not) * database.pool.size=... How many connections in the connection pool (default 10). * database.driver.class The driver to initialize with Class.forName(). This will * be guessed from the database.url if not provided. * database.flavor One of the enumerated values in {@link Flavor}. If this * is not provided the flavor will be guessed based on the * value for database.url, if possible. * </pre> * * <p>The database flavor will be guessed based on the URL.</p> * * <p>A database pool will be created using HikariCP.</p> * * <p>Be sure to retain a copy of the builder so you can call close() later to * destroy the pool. You will most likely want to register a JVM shutdown hook * to make sure this happens. See VertxServer.java in the demo directory for * an example of how to do this.</p> */ @CheckReturnValue public static Builder pooledBuilder(Vertx vertx, Config config) { return fromPool(vertx, DatabaseProvider.createPool(config)); } /** * Use an externally configured DataSource, Flavor, and optionally a shutdown hook. * The shutdown hook may be null if you don't want calls to Builder.close() to attempt * any shutdown. The DataSource and Flavor are mandatory. */ @CheckReturnValue
// Path: src/main/java/com/github/susom/database/DatabaseProvider.java // public static class Pool { // public DataSource dataSource; // public int size; // public Flavor flavor; // public Closeable poolShutdown; // // public Pool(DataSource dataSource, int size, Flavor flavor, Closeable poolShutdown) { // this.dataSource = dataSource; // this.size = size; // this.flavor = flavor; // this.poolShutdown = poolShutdown; // } // } // Path: src/main/java/com/github/susom/database/DatabaseProviderVertx.java import io.vertx.core.AsyncResult; import io.vertx.core.Handler; import io.vertx.core.Vertx; import io.vertx.core.WorkerExecutor; import java.io.Closeable; import java.io.IOException; import java.sql.Connection; import java.sql.SQLException; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Supplier; import javax.annotation.CheckReturnValue; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.github.susom.database.DatabaseProvider.Pool; * url; prompted on standard input if user is provided and * password is not) * database.pool.size=... How many connections in the connection pool (default 10). * database.driver.class The driver to initialize with Class.forName(). This will * be guessed from the database.url if not provided. * database.flavor One of the enumerated values in {@link Flavor}. If this * is not provided the flavor will be guessed based on the * value for database.url, if possible. * </pre> * * <p>The database flavor will be guessed based on the URL.</p> * * <p>A database pool will be created using HikariCP.</p> * * <p>Be sure to retain a copy of the builder so you can call close() later to * destroy the pool. You will most likely want to register a JVM shutdown hook * to make sure this happens. See VertxServer.java in the demo directory for * an example of how to do this.</p> */ @CheckReturnValue public static Builder pooledBuilder(Vertx vertx, Config config) { return fromPool(vertx, DatabaseProvider.createPool(config)); } /** * Use an externally configured DataSource, Flavor, and optionally a shutdown hook. * The shutdown hook may be null if you don't want calls to Builder.close() to attempt * any shutdown. The DataSource and Flavor are mandatory. */ @CheckReturnValue
public static Builder fromPool(Vertx vertx, Pool pool) {
susom/database
src/main/java/com/github/susom/database/SqlSelectImpl.java
// Path: src/main/java/com/github/susom/database/MixedParameterSql.java // public static class RewriteArg { // private final String sql; // // public RewriteArg(String sql) { // this.sql = sql; // } // }
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.github.susom.database.MixedParameterSql.RewriteArg; import java.math.BigDecimal; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.time.LocalDate; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Nonnull; import javax.annotation.Nullable;
public SqlSelect argLocalDate(LocalDate arg) { // Date with no time return positionalArg(adaptor.nullLocalDate(arg)); } @Nonnull @Override public SqlSelect argLocalDate(@Nonnull String argName, LocalDate arg) { // Date with no time return namedArg(argName, adaptor.nullLocalDate(arg)); } @Nonnull @Override public SqlSelect argDateNowPerApp() { return positionalArg(adaptor.nullDate(options.currentDate())); } @Nonnull @Override public SqlSelect argDateNowPerApp(@Nonnull String argName) { return namedArg(argName, adaptor.nullDate(options.currentDate())); } @Nonnull @Override public SqlSelect argDateNowPerDb() { if (options.useDatePerAppOnly()) { return positionalArg(adaptor.nullDate(options.currentDate())); }
// Path: src/main/java/com/github/susom/database/MixedParameterSql.java // public static class RewriteArg { // private final String sql; // // public RewriteArg(String sql) { // this.sql = sql; // } // } // Path: src/main/java/com/github/susom/database/SqlSelectImpl.java import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.github.susom.database.MixedParameterSql.RewriteArg; import java.math.BigDecimal; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.time.LocalDate; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Nonnull; import javax.annotation.Nullable; public SqlSelect argLocalDate(LocalDate arg) { // Date with no time return positionalArg(adaptor.nullLocalDate(arg)); } @Nonnull @Override public SqlSelect argLocalDate(@Nonnull String argName, LocalDate arg) { // Date with no time return namedArg(argName, adaptor.nullLocalDate(arg)); } @Nonnull @Override public SqlSelect argDateNowPerApp() { return positionalArg(adaptor.nullDate(options.currentDate())); } @Nonnull @Override public SqlSelect argDateNowPerApp(@Nonnull String argName) { return namedArg(argName, adaptor.nullDate(options.currentDate())); } @Nonnull @Override public SqlSelect argDateNowPerDb() { if (options.useDatePerAppOnly()) { return positionalArg(adaptor.nullDate(options.currentDate())); }
return positionalArg(new RewriteArg(options.flavor().dbTimeMillis()));
susom/database
src/main/java/com/github/susom/database/StatementAdaptor.java
// Path: src/main/java/com/github/susom/database/MixedParameterSql.java // static class SecretArg { // private final Object arg; // // SecretArg(Object arg) { // this.arg = arg; // } // // Object getArg() { // return arg; // } // // @Override // public String toString() { // return "<secret>"; // } // }
import javax.annotation.Nullable; import org.slf4j.Logger; import com.github.susom.database.MixedParameterSql.SecretArg; import oracle.jdbc.OraclePreparedStatement; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.sql.ParameterMetaData; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.sql.Timestamp; import java.sql.Types; import java.time.LocalDate; import java.util.Date; import java.util.Scanner;
/* * Copyright 2014 The Board of Trustees of The Leland Stanford Junior University. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.susom.database; /** * Deal with mapping parameters into prepared statements. * * @author garricko */ public class StatementAdaptor { private final Options options; public StatementAdaptor(Options options) { this.options = options; } public void addParameters(PreparedStatement ps, Object[] parameters) throws SQLException { for (int i = 0; i < parameters.length; i++) { Object parameter = parameters[i]; // Unwrap secret args here so we can use them
// Path: src/main/java/com/github/susom/database/MixedParameterSql.java // static class SecretArg { // private final Object arg; // // SecretArg(Object arg) { // this.arg = arg; // } // // Object getArg() { // return arg; // } // // @Override // public String toString() { // return "<secret>"; // } // } // Path: src/main/java/com/github/susom/database/StatementAdaptor.java import javax.annotation.Nullable; import org.slf4j.Logger; import com.github.susom.database.MixedParameterSql.SecretArg; import oracle.jdbc.OraclePreparedStatement; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.sql.ParameterMetaData; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.sql.Timestamp; import java.sql.Types; import java.time.LocalDate; import java.util.Date; import java.util.Scanner; /* * Copyright 2014 The Board of Trustees of The Leland Stanford Junior University. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.susom.database; /** * Deal with mapping parameters into prepared statements. * * @author garricko */ public class StatementAdaptor { private final Options options; public StatementAdaptor(Options options) { this.options = options; } public void addParameters(PreparedStatement ps, Object[] parameters) throws SQLException { for (int i = 0; i < parameters.length; i++) { Object parameter = parameters[i]; // Unwrap secret args here so we can use them
if (parameter instanceof SecretArg) {
susom/database
src/main/java/com/github/susom/database/SqlUpdateImpl.java
// Path: src/main/java/com/github/susom/database/MixedParameterSql.java // public static class RewriteArg { // private final String sql; // // public RewriteArg(String sql) { // this.sql = sql; // } // }
import javax.annotation.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.github.susom.database.MixedParameterSql.RewriteArg; import java.io.InputStream; import java.io.Reader; import java.io.StringReader; import java.math.BigDecimal; import java.sql.Connection; import java.sql.PreparedStatement; import java.time.LocalDate; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Nonnull;
public SqlUpdate argLocalDate(@Nullable LocalDate arg) { // Date with no time return positionalArg(adaptor.nullLocalDate(arg)); } @Override @Nonnull public SqlUpdate argLocalDate(@Nonnull String argName, @Nullable LocalDate arg) { // Date with no time return namedArg(argName, adaptor.nullLocalDate(arg)); } @Nonnull @Override public SqlUpdate argDateNowPerApp() { return positionalArg(adaptor.nullDate(options.currentDate())); } @Override @Nonnull public SqlUpdate argDateNowPerApp(@Nonnull String argName) { return namedArg(argName, adaptor.nullDate(options.currentDate())); } @Nonnull @Override public SqlUpdate argDateNowPerDb() { if (options.useDatePerAppOnly()) { return positionalArg(adaptor.nullDate(options.currentDate())); }
// Path: src/main/java/com/github/susom/database/MixedParameterSql.java // public static class RewriteArg { // private final String sql; // // public RewriteArg(String sql) { // this.sql = sql; // } // } // Path: src/main/java/com/github/susom/database/SqlUpdateImpl.java import javax.annotation.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.github.susom.database.MixedParameterSql.RewriteArg; import java.io.InputStream; import java.io.Reader; import java.io.StringReader; import java.math.BigDecimal; import java.sql.Connection; import java.sql.PreparedStatement; import java.time.LocalDate; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Nonnull; public SqlUpdate argLocalDate(@Nullable LocalDate arg) { // Date with no time return positionalArg(adaptor.nullLocalDate(arg)); } @Override @Nonnull public SqlUpdate argLocalDate(@Nonnull String argName, @Nullable LocalDate arg) { // Date with no time return namedArg(argName, adaptor.nullLocalDate(arg)); } @Nonnull @Override public SqlUpdate argDateNowPerApp() { return positionalArg(adaptor.nullDate(options.currentDate())); } @Override @Nonnull public SqlUpdate argDateNowPerApp(@Nonnull String argName) { return namedArg(argName, adaptor.nullDate(options.currentDate())); } @Nonnull @Override public SqlUpdate argDateNowPerDb() { if (options.useDatePerAppOnly()) { return positionalArg(adaptor.nullDate(options.currentDate())); }
return positionalArg(new RewriteArg(options.flavor().dbTimeMillis()));
googleapis/java-storage-nio
google-cloud-nio/src/test/java/com/google/cloud/storage/contrib/nio/NIOTest.java
// Path: google-cloud-nio/src/main/java/com/google/cloud/storage/contrib/nio/testing/LocalStorageHelper.java // public final class LocalStorageHelper { // // // used for testing. Will throw if you pass it an option. // private static final FakeStorageRpc instance = new FakeStorageRpc(true); // // private LocalStorageHelper() {} // // /** // * Returns a {@link StorageOptions} that use the static FakeStorageRpc instance, and resets it // * first so you start from a clean slate. That instance will throw if you pass it any option. // */ // public static StorageOptions getOptions() { // instance.reset(); // return StorageOptions.newBuilder() // .setProjectId("fake-project-for-testing") // .setServiceRpcFactory(new FakeStorageRpcFactory()) // .build(); // } // // /** // * Returns a {@link StorageOptions} that creates a new FakeStorageRpc instance with the given // * option. // */ // public static StorageOptions customOptions(final boolean throwIfOptions) { // return StorageOptions.newBuilder() // .setProjectId("fake-project-for-testing") // .setServiceRpcFactory(new FakeStorageRpcFactory(new FakeStorageRpc(throwIfOptions))) // .build(); // } // // public static class FakeStorageRpcFactory implements ServiceRpcFactory<StorageOptions> { // // private final FakeStorageRpc instance; // // public FakeStorageRpcFactory() { // this(LocalStorageHelper.instance); // } // // public FakeStorageRpcFactory(FakeStorageRpc instance) { // this.instance = instance; // } // // @Override // public ServiceRpc create(StorageOptions storageOptions) { // return instance; // } // } // }
import static com.google.common.truth.Truth.assertThat; import com.google.cloud.storage.contrib.nio.testing.LocalStorageHelper; import com.google.cloud.testing.junit4.MultipleAttemptsRule; import java.net.URI; import java.nio.file.Path; import java.nio.file.Paths; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4;
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.storage.contrib.nio; /** * Unit tests for {@link CloudStorageFileSystemProvider}. Makes sure the NIO system picks it up * properly. */ @RunWith(JUnit4.class) public class NIOTest { @Rule public final MultipleAttemptsRule multipleAttemptsRule = new MultipleAttemptsRule(3); private URI uriToCloudStorage; @Before public void setUp() {
// Path: google-cloud-nio/src/main/java/com/google/cloud/storage/contrib/nio/testing/LocalStorageHelper.java // public final class LocalStorageHelper { // // // used for testing. Will throw if you pass it an option. // private static final FakeStorageRpc instance = new FakeStorageRpc(true); // // private LocalStorageHelper() {} // // /** // * Returns a {@link StorageOptions} that use the static FakeStorageRpc instance, and resets it // * first so you start from a clean slate. That instance will throw if you pass it any option. // */ // public static StorageOptions getOptions() { // instance.reset(); // return StorageOptions.newBuilder() // .setProjectId("fake-project-for-testing") // .setServiceRpcFactory(new FakeStorageRpcFactory()) // .build(); // } // // /** // * Returns a {@link StorageOptions} that creates a new FakeStorageRpc instance with the given // * option. // */ // public static StorageOptions customOptions(final boolean throwIfOptions) { // return StorageOptions.newBuilder() // .setProjectId("fake-project-for-testing") // .setServiceRpcFactory(new FakeStorageRpcFactory(new FakeStorageRpc(throwIfOptions))) // .build(); // } // // public static class FakeStorageRpcFactory implements ServiceRpcFactory<StorageOptions> { // // private final FakeStorageRpc instance; // // public FakeStorageRpcFactory() { // this(LocalStorageHelper.instance); // } // // public FakeStorageRpcFactory(FakeStorageRpc instance) { // this.instance = instance; // } // // @Override // public ServiceRpc create(StorageOptions storageOptions) { // return instance; // } // } // } // Path: google-cloud-nio/src/test/java/com/google/cloud/storage/contrib/nio/NIOTest.java import static com.google.common.truth.Truth.assertThat; import com.google.cloud.storage.contrib.nio.testing.LocalStorageHelper; import com.google.cloud.testing.junit4.MultipleAttemptsRule; import java.net.URI; import java.nio.file.Path; import java.nio.file.Paths; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.storage.contrib.nio; /** * Unit tests for {@link CloudStorageFileSystemProvider}. Makes sure the NIO system picks it up * properly. */ @RunWith(JUnit4.class) public class NIOTest { @Rule public final MultipleAttemptsRule multipleAttemptsRule = new MultipleAttemptsRule(3); private URI uriToCloudStorage; @Before public void setUp() {
CloudStorageFileSystemProvider.setStorageOptions(LocalStorageHelper.getOptions());
openknowledge/jaxrs-versioning
jaxrs-versioning/src/test/java/de/openknowledge/jaxrs/versioning/resources/VersionMediaTypeParameterAddressResource.java
// Path: jaxrs-versioning/src/test/java/de/openknowledge/jaxrs/versioning/model/AddressV3.java // @SupportedVersion(version = "v3", previous = AddressV2.class) // public class AddressV3 { // // protected SortedSet<String> addressLines = new TreeSet<String>(reverseOrder()); // // @MovedFrom("addressLines[0]") // protected String addressLine1; // // @MovedFrom("addressLines[1]") // protected String addressLine2; // // protected CityV3 city; // // private AddressTypeV3 type; // // protected AddressV3() { // } // // public AddressV3(String adressLine1, String adressLine2, CityV3 location) { // this.addressLine1 = adressLine1; // this.addressLine2 = adressLine2; // this.city = location; // } // // public AddressV3(CityV3 location, String... addressLines) { // this.addressLines.addAll(asList(addressLines)); // this.city = location; // } // // public String getAddressLine1() { // return addressLine1; // } // // public void setAddressLine1(String addressLine1) { // this.addressLine1 = addressLine1; // } // // public String getAddressLine2() { // return addressLine2; // } // // public void setAddressLine2(String addressLine2) { // this.addressLine2 = addressLine2; // } // // public Set<String> getAddressLines() { // return addressLines; // } // // public void setAddressLines(SortedSet<String> addressLines) { // this.addressLines = addressLines; // } // // public CityV3 getCity() { // return city; // } // // public void setCity(CityV3 city) { // this.city = city; // } // // public AddressTypeV3 getType() { // return type; // } // // public void setType(AddressTypeV3 type) { // this.type = type; // } // } // // Path: jaxrs-versioning/src/test/java/de/openknowledge/jaxrs/versioning/model/CityV3.java // public class CityV3 { // // protected String zipCode; // // protected String cityName; // // protected CityV3() { // } // // public CityV3(String zipCode, String cityName) { // this.zipCode = zipCode; // this.cityName = cityName; // } // // public String getZipCode() { // return zipCode; // } // // public void setZipCode(String zipCode) { // this.zipCode = zipCode; // } // // public String getCityName() { // return cityName; // } // // public void setCityName(String cityName) { // this.cityName = cityName; // } // }
import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import de.openknowledge.jaxrs.versioning.VersionMediaTypeParameter; import de.openknowledge.jaxrs.versioning.model.AddressV3; import de.openknowledge.jaxrs.versioning.model.CityV3;
/* * Copyright (C) open knowledge GmbH * * 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 de.openknowledge.jaxrs.versioning.resources; /** * @author Arne Limburg - open knowledge GmbH */ @Path("/addresses") public class VersionMediaTypeParameterAddressResource { @GET @Produces(MediaType.APPLICATION_JSON) @Path("/{id}") @VersionMediaTypeParameter("version")
// Path: jaxrs-versioning/src/test/java/de/openknowledge/jaxrs/versioning/model/AddressV3.java // @SupportedVersion(version = "v3", previous = AddressV2.class) // public class AddressV3 { // // protected SortedSet<String> addressLines = new TreeSet<String>(reverseOrder()); // // @MovedFrom("addressLines[0]") // protected String addressLine1; // // @MovedFrom("addressLines[1]") // protected String addressLine2; // // protected CityV3 city; // // private AddressTypeV3 type; // // protected AddressV3() { // } // // public AddressV3(String adressLine1, String adressLine2, CityV3 location) { // this.addressLine1 = adressLine1; // this.addressLine2 = adressLine2; // this.city = location; // } // // public AddressV3(CityV3 location, String... addressLines) { // this.addressLines.addAll(asList(addressLines)); // this.city = location; // } // // public String getAddressLine1() { // return addressLine1; // } // // public void setAddressLine1(String addressLine1) { // this.addressLine1 = addressLine1; // } // // public String getAddressLine2() { // return addressLine2; // } // // public void setAddressLine2(String addressLine2) { // this.addressLine2 = addressLine2; // } // // public Set<String> getAddressLines() { // return addressLines; // } // // public void setAddressLines(SortedSet<String> addressLines) { // this.addressLines = addressLines; // } // // public CityV3 getCity() { // return city; // } // // public void setCity(CityV3 city) { // this.city = city; // } // // public AddressTypeV3 getType() { // return type; // } // // public void setType(AddressTypeV3 type) { // this.type = type; // } // } // // Path: jaxrs-versioning/src/test/java/de/openknowledge/jaxrs/versioning/model/CityV3.java // public class CityV3 { // // protected String zipCode; // // protected String cityName; // // protected CityV3() { // } // // public CityV3(String zipCode, String cityName) { // this.zipCode = zipCode; // this.cityName = cityName; // } // // public String getZipCode() { // return zipCode; // } // // public void setZipCode(String zipCode) { // this.zipCode = zipCode; // } // // public String getCityName() { // return cityName; // } // // public void setCityName(String cityName) { // this.cityName = cityName; // } // } // Path: jaxrs-versioning/src/test/java/de/openknowledge/jaxrs/versioning/resources/VersionMediaTypeParameterAddressResource.java import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import de.openknowledge.jaxrs.versioning.VersionMediaTypeParameter; import de.openknowledge.jaxrs.versioning.model.AddressV3; import de.openknowledge.jaxrs.versioning.model.CityV3; /* * Copyright (C) open knowledge GmbH * * 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 de.openknowledge.jaxrs.versioning.resources; /** * @author Arne Limburg - open knowledge GmbH */ @Path("/addresses") public class VersionMediaTypeParameterAddressResource { @GET @Produces(MediaType.APPLICATION_JSON) @Path("/{id}") @VersionMediaTypeParameter("version")
public AddressV3 getAddress(@PathParam("id") String id) {
openknowledge/jaxrs-versioning
jaxrs-versioning/src/test/java/de/openknowledge/jaxrs/versioning/resources/VersionMediaTypeParameterAddressResource.java
// Path: jaxrs-versioning/src/test/java/de/openknowledge/jaxrs/versioning/model/AddressV3.java // @SupportedVersion(version = "v3", previous = AddressV2.class) // public class AddressV3 { // // protected SortedSet<String> addressLines = new TreeSet<String>(reverseOrder()); // // @MovedFrom("addressLines[0]") // protected String addressLine1; // // @MovedFrom("addressLines[1]") // protected String addressLine2; // // protected CityV3 city; // // private AddressTypeV3 type; // // protected AddressV3() { // } // // public AddressV3(String adressLine1, String adressLine2, CityV3 location) { // this.addressLine1 = adressLine1; // this.addressLine2 = adressLine2; // this.city = location; // } // // public AddressV3(CityV3 location, String... addressLines) { // this.addressLines.addAll(asList(addressLines)); // this.city = location; // } // // public String getAddressLine1() { // return addressLine1; // } // // public void setAddressLine1(String addressLine1) { // this.addressLine1 = addressLine1; // } // // public String getAddressLine2() { // return addressLine2; // } // // public void setAddressLine2(String addressLine2) { // this.addressLine2 = addressLine2; // } // // public Set<String> getAddressLines() { // return addressLines; // } // // public void setAddressLines(SortedSet<String> addressLines) { // this.addressLines = addressLines; // } // // public CityV3 getCity() { // return city; // } // // public void setCity(CityV3 city) { // this.city = city; // } // // public AddressTypeV3 getType() { // return type; // } // // public void setType(AddressTypeV3 type) { // this.type = type; // } // } // // Path: jaxrs-versioning/src/test/java/de/openknowledge/jaxrs/versioning/model/CityV3.java // public class CityV3 { // // protected String zipCode; // // protected String cityName; // // protected CityV3() { // } // // public CityV3(String zipCode, String cityName) { // this.zipCode = zipCode; // this.cityName = cityName; // } // // public String getZipCode() { // return zipCode; // } // // public void setZipCode(String zipCode) { // this.zipCode = zipCode; // } // // public String getCityName() { // return cityName; // } // // public void setCityName(String cityName) { // this.cityName = cityName; // } // }
import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import de.openknowledge.jaxrs.versioning.VersionMediaTypeParameter; import de.openknowledge.jaxrs.versioning.model.AddressV3; import de.openknowledge.jaxrs.versioning.model.CityV3;
/* * Copyright (C) open knowledge GmbH * * 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 de.openknowledge.jaxrs.versioning.resources; /** * @author Arne Limburg - open knowledge GmbH */ @Path("/addresses") public class VersionMediaTypeParameterAddressResource { @GET @Produces(MediaType.APPLICATION_JSON) @Path("/{id}") @VersionMediaTypeParameter("version") public AddressV3 getAddress(@PathParam("id") String id) {
// Path: jaxrs-versioning/src/test/java/de/openknowledge/jaxrs/versioning/model/AddressV3.java // @SupportedVersion(version = "v3", previous = AddressV2.class) // public class AddressV3 { // // protected SortedSet<String> addressLines = new TreeSet<String>(reverseOrder()); // // @MovedFrom("addressLines[0]") // protected String addressLine1; // // @MovedFrom("addressLines[1]") // protected String addressLine2; // // protected CityV3 city; // // private AddressTypeV3 type; // // protected AddressV3() { // } // // public AddressV3(String adressLine1, String adressLine2, CityV3 location) { // this.addressLine1 = adressLine1; // this.addressLine2 = adressLine2; // this.city = location; // } // // public AddressV3(CityV3 location, String... addressLines) { // this.addressLines.addAll(asList(addressLines)); // this.city = location; // } // // public String getAddressLine1() { // return addressLine1; // } // // public void setAddressLine1(String addressLine1) { // this.addressLine1 = addressLine1; // } // // public String getAddressLine2() { // return addressLine2; // } // // public void setAddressLine2(String addressLine2) { // this.addressLine2 = addressLine2; // } // // public Set<String> getAddressLines() { // return addressLines; // } // // public void setAddressLines(SortedSet<String> addressLines) { // this.addressLines = addressLines; // } // // public CityV3 getCity() { // return city; // } // // public void setCity(CityV3 city) { // this.city = city; // } // // public AddressTypeV3 getType() { // return type; // } // // public void setType(AddressTypeV3 type) { // this.type = type; // } // } // // Path: jaxrs-versioning/src/test/java/de/openknowledge/jaxrs/versioning/model/CityV3.java // public class CityV3 { // // protected String zipCode; // // protected String cityName; // // protected CityV3() { // } // // public CityV3(String zipCode, String cityName) { // this.zipCode = zipCode; // this.cityName = cityName; // } // // public String getZipCode() { // return zipCode; // } // // public void setZipCode(String zipCode) { // this.zipCode = zipCode; // } // // public String getCityName() { // return cityName; // } // // public void setCityName(String cityName) { // this.cityName = cityName; // } // } // Path: jaxrs-versioning/src/test/java/de/openknowledge/jaxrs/versioning/resources/VersionMediaTypeParameterAddressResource.java import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import de.openknowledge.jaxrs.versioning.VersionMediaTypeParameter; import de.openknowledge.jaxrs.versioning.model.AddressV3; import de.openknowledge.jaxrs.versioning.model.CityV3; /* * Copyright (C) open knowledge GmbH * * 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 de.openknowledge.jaxrs.versioning.resources; /** * @author Arne Limburg - open knowledge GmbH */ @Path("/addresses") public class VersionMediaTypeParameterAddressResource { @GET @Produces(MediaType.APPLICATION_JSON) @Path("/{id}") @VersionMediaTypeParameter("version") public AddressV3 getAddress(@PathParam("id") String id) {
return new AddressV3("Samplestreet 1", " ", new CityV3("12345", "Samplecity"));
openknowledge/jaxrs-versioning
jaxrs-versioning/src/test/java/de/openknowledge/jaxrs/versioning/model/CitySplitProvider.java
// Path: jaxrs-versioning/src/main/java/de/openknowledge/jaxrs/versioning/Provider.java // public interface Provider<T> { // public T get(VersionContext versionContext); // } // // Path: jaxrs-versioning/src/main/java/de/openknowledge/jaxrs/versioning/VersionContext.java // public interface VersionContext { // // Object getParent(); // // <T> T getParent(Class<T> type); // // String getPropertyName(); // }
import de.openknowledge.jaxrs.versioning.Provider; import de.openknowledge.jaxrs.versioning.VersionContext;
/* * Copyright (C) open knowledge GmbH * * 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 de.openknowledge.jaxrs.versioning.model; /** * @author Philipp Geers - open knowledge GmbH */ public class CitySplitProvider implements Provider<String> { @Override
// Path: jaxrs-versioning/src/main/java/de/openknowledge/jaxrs/versioning/Provider.java // public interface Provider<T> { // public T get(VersionContext versionContext); // } // // Path: jaxrs-versioning/src/main/java/de/openknowledge/jaxrs/versioning/VersionContext.java // public interface VersionContext { // // Object getParent(); // // <T> T getParent(Class<T> type); // // String getPropertyName(); // } // Path: jaxrs-versioning/src/test/java/de/openknowledge/jaxrs/versioning/model/CitySplitProvider.java import de.openknowledge.jaxrs.versioning.Provider; import de.openknowledge.jaxrs.versioning.VersionContext; /* * Copyright (C) open knowledge GmbH * * 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 de.openknowledge.jaxrs.versioning.model; /** * @author Philipp Geers - open knowledge GmbH */ public class CitySplitProvider implements Provider<String> { @Override
public String get(VersionContext versionContext) {
openknowledge/jaxrs-versioning
jaxrs-versioning/src/test/java/de/openknowledge/jaxrs/versioning/model/StreetNameProvider.java
// Path: jaxrs-versioning/src/main/java/de/openknowledge/jaxrs/versioning/Provider.java // public interface Provider<T> { // public T get(VersionContext versionContext); // } // // Path: jaxrs-versioning/src/main/java/de/openknowledge/jaxrs/versioning/VersionContext.java // public interface VersionContext { // // Object getParent(); // // <T> T getParent(Class<T> type); // // String getPropertyName(); // }
import de.openknowledge.jaxrs.versioning.Provider; import de.openknowledge.jaxrs.versioning.VersionContext;
/* * Copyright (C) open knowledge GmbH * * 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 de.openknowledge.jaxrs.versioning.model; /** * @author Arne Limburg - open knowledge GmbH */ public class StreetNameProvider implements Provider<String> { @Override
// Path: jaxrs-versioning/src/main/java/de/openknowledge/jaxrs/versioning/Provider.java // public interface Provider<T> { // public T get(VersionContext versionContext); // } // // Path: jaxrs-versioning/src/main/java/de/openknowledge/jaxrs/versioning/VersionContext.java // public interface VersionContext { // // Object getParent(); // // <T> T getParent(Class<T> type); // // String getPropertyName(); // } // Path: jaxrs-versioning/src/test/java/de/openknowledge/jaxrs/versioning/model/StreetNameProvider.java import de.openknowledge.jaxrs.versioning.Provider; import de.openknowledge.jaxrs.versioning.VersionContext; /* * Copyright (C) open knowledge GmbH * * 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 de.openknowledge.jaxrs.versioning.model; /** * @author Arne Limburg - open knowledge GmbH */ public class StreetNameProvider implements Provider<String> { @Override
public String get(VersionContext versionContext) {
openknowledge/jaxrs-versioning
jaxrs-versioning/src/main/java/de/openknowledge/jaxrs/versioning/conversion/CompatibilityMapper.java
// Path: jaxrs-versioning/src/main/java/de/openknowledge/jaxrs/versioning/Provider.java // public interface Provider<T> { // public T get(VersionContext versionContext); // }
import java.util.Collection; import org.apache.commons.lang3.StringUtils; import de.openknowledge.jaxrs.versioning.Added; import de.openknowledge.jaxrs.versioning.MovedFrom; import de.openknowledge.jaxrs.versioning.Provider; import de.openknowledge.jaxrs.versioning.Removed;
versionProperty.set(object, value); } map(value, context.getChildContext(value)); } continue; } if (versionProperty.isDefault(object)) { updateDependentValues(new VersionPropertyValue(versionProperty, context)); } else { Object value = versionProperty.get(object); setDependentValues(versionType, movedFrom, added, versionProperty, value, context); if (!versionProperty.isSimple()) { map(value, context.getChildContext(value)); } } } } private void updateDependentValues(VersionPropertyValue propertyValue) { DefaultVersionContext dependentContext = propertyValue.getContext(); VersionType<?> dependentType = versionTypeFactory.get(dependentContext.getParent().getClass()); MovedFrom movedFrom = propertyValue.getAnnotation(MovedFrom.class); if (movedFrom != null) { updateDependentValues(dependentType, propertyValue, movedFrom, dependentContext); if (!propertyValue.isDefault()) { return; } } String defaultValue = StringUtils.EMPTY;
// Path: jaxrs-versioning/src/main/java/de/openknowledge/jaxrs/versioning/Provider.java // public interface Provider<T> { // public T get(VersionContext versionContext); // } // Path: jaxrs-versioning/src/main/java/de/openknowledge/jaxrs/versioning/conversion/CompatibilityMapper.java import java.util.Collection; import org.apache.commons.lang3.StringUtils; import de.openknowledge.jaxrs.versioning.Added; import de.openknowledge.jaxrs.versioning.MovedFrom; import de.openknowledge.jaxrs.versioning.Provider; import de.openknowledge.jaxrs.versioning.Removed; versionProperty.set(object, value); } map(value, context.getChildContext(value)); } continue; } if (versionProperty.isDefault(object)) { updateDependentValues(new VersionPropertyValue(versionProperty, context)); } else { Object value = versionProperty.get(object); setDependentValues(versionType, movedFrom, added, versionProperty, value, context); if (!versionProperty.isSimple()) { map(value, context.getChildContext(value)); } } } } private void updateDependentValues(VersionPropertyValue propertyValue) { DefaultVersionContext dependentContext = propertyValue.getContext(); VersionType<?> dependentType = versionTypeFactory.get(dependentContext.getParent().getClass()); MovedFrom movedFrom = propertyValue.getAnnotation(MovedFrom.class); if (movedFrom != null) { updateDependentValues(dependentType, propertyValue, movedFrom, dependentContext); if (!propertyValue.isDefault()) { return; } } String defaultValue = StringUtils.EMPTY;
Class<? extends Provider> provider = Provider.class;
openknowledge/jaxrs-versioning
jaxrs-versioning/src/test/java/de/openknowledge/jaxrs/versioning/resources/VersionedMediaTypeAddressResource.java
// Path: jaxrs-versioning/src/test/java/de/openknowledge/jaxrs/versioning/model/AddressV3.java // @SupportedVersion(version = "v3", previous = AddressV2.class) // public class AddressV3 { // // protected SortedSet<String> addressLines = new TreeSet<String>(reverseOrder()); // // @MovedFrom("addressLines[0]") // protected String addressLine1; // // @MovedFrom("addressLines[1]") // protected String addressLine2; // // protected CityV3 city; // // private AddressTypeV3 type; // // protected AddressV3() { // } // // public AddressV3(String adressLine1, String adressLine2, CityV3 location) { // this.addressLine1 = adressLine1; // this.addressLine2 = adressLine2; // this.city = location; // } // // public AddressV3(CityV3 location, String... addressLines) { // this.addressLines.addAll(asList(addressLines)); // this.city = location; // } // // public String getAddressLine1() { // return addressLine1; // } // // public void setAddressLine1(String addressLine1) { // this.addressLine1 = addressLine1; // } // // public String getAddressLine2() { // return addressLine2; // } // // public void setAddressLine2(String addressLine2) { // this.addressLine2 = addressLine2; // } // // public Set<String> getAddressLines() { // return addressLines; // } // // public void setAddressLines(SortedSet<String> addressLines) { // this.addressLines = addressLines; // } // // public CityV3 getCity() { // return city; // } // // public void setCity(CityV3 city) { // this.city = city; // } // // public AddressTypeV3 getType() { // return type; // } // // public void setType(AddressTypeV3 type) { // this.type = type; // } // } // // Path: jaxrs-versioning/src/test/java/de/openknowledge/jaxrs/versioning/model/CityV3.java // public class CityV3 { // // protected String zipCode; // // protected String cityName; // // protected CityV3() { // } // // public CityV3(String zipCode, String cityName) { // this.zipCode = zipCode; // this.cityName = cityName; // } // // public String getZipCode() { // return zipCode; // } // // public void setZipCode(String zipCode) { // this.zipCode = zipCode; // } // // public String getCityName() { // return cityName; // } // // public void setCityName(String cityName) { // this.cityName = cityName; // } // }
import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import de.openknowledge.jaxrs.versioning.VersionedMediaType; import de.openknowledge.jaxrs.versioning.model.AddressV3; import de.openknowledge.jaxrs.versioning.model.CityV3;
/* * Copyright (C) open knowledge GmbH * * 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 de.openknowledge.jaxrs.versioning.resources; /** * @author Arne Limburg - open knowledge GmbH */ @Path("/addresses") public class VersionedMediaTypeAddressResource { @GET @Produces(MediaType.APPLICATION_JSON) @Path("/{id}") @VersionedMediaType(value = "application/vnd+de.openknowledge.jaxrs.versioning+json+{version}", mapsTo = "application/json")
// Path: jaxrs-versioning/src/test/java/de/openknowledge/jaxrs/versioning/model/AddressV3.java // @SupportedVersion(version = "v3", previous = AddressV2.class) // public class AddressV3 { // // protected SortedSet<String> addressLines = new TreeSet<String>(reverseOrder()); // // @MovedFrom("addressLines[0]") // protected String addressLine1; // // @MovedFrom("addressLines[1]") // protected String addressLine2; // // protected CityV3 city; // // private AddressTypeV3 type; // // protected AddressV3() { // } // // public AddressV3(String adressLine1, String adressLine2, CityV3 location) { // this.addressLine1 = adressLine1; // this.addressLine2 = adressLine2; // this.city = location; // } // // public AddressV3(CityV3 location, String... addressLines) { // this.addressLines.addAll(asList(addressLines)); // this.city = location; // } // // public String getAddressLine1() { // return addressLine1; // } // // public void setAddressLine1(String addressLine1) { // this.addressLine1 = addressLine1; // } // // public String getAddressLine2() { // return addressLine2; // } // // public void setAddressLine2(String addressLine2) { // this.addressLine2 = addressLine2; // } // // public Set<String> getAddressLines() { // return addressLines; // } // // public void setAddressLines(SortedSet<String> addressLines) { // this.addressLines = addressLines; // } // // public CityV3 getCity() { // return city; // } // // public void setCity(CityV3 city) { // this.city = city; // } // // public AddressTypeV3 getType() { // return type; // } // // public void setType(AddressTypeV3 type) { // this.type = type; // } // } // // Path: jaxrs-versioning/src/test/java/de/openknowledge/jaxrs/versioning/model/CityV3.java // public class CityV3 { // // protected String zipCode; // // protected String cityName; // // protected CityV3() { // } // // public CityV3(String zipCode, String cityName) { // this.zipCode = zipCode; // this.cityName = cityName; // } // // public String getZipCode() { // return zipCode; // } // // public void setZipCode(String zipCode) { // this.zipCode = zipCode; // } // // public String getCityName() { // return cityName; // } // // public void setCityName(String cityName) { // this.cityName = cityName; // } // } // Path: jaxrs-versioning/src/test/java/de/openknowledge/jaxrs/versioning/resources/VersionedMediaTypeAddressResource.java import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import de.openknowledge.jaxrs.versioning.VersionedMediaType; import de.openknowledge.jaxrs.versioning.model.AddressV3; import de.openknowledge.jaxrs.versioning.model.CityV3; /* * Copyright (C) open knowledge GmbH * * 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 de.openknowledge.jaxrs.versioning.resources; /** * @author Arne Limburg - open knowledge GmbH */ @Path("/addresses") public class VersionedMediaTypeAddressResource { @GET @Produces(MediaType.APPLICATION_JSON) @Path("/{id}") @VersionedMediaType(value = "application/vnd+de.openknowledge.jaxrs.versioning+json+{version}", mapsTo = "application/json")
public AddressV3 getAddress(@PathParam("id") String id) {
openknowledge/jaxrs-versioning
jaxrs-versioning/src/test/java/de/openknowledge/jaxrs/versioning/resources/VersionedMediaTypeAddressResource.java
// Path: jaxrs-versioning/src/test/java/de/openknowledge/jaxrs/versioning/model/AddressV3.java // @SupportedVersion(version = "v3", previous = AddressV2.class) // public class AddressV3 { // // protected SortedSet<String> addressLines = new TreeSet<String>(reverseOrder()); // // @MovedFrom("addressLines[0]") // protected String addressLine1; // // @MovedFrom("addressLines[1]") // protected String addressLine2; // // protected CityV3 city; // // private AddressTypeV3 type; // // protected AddressV3() { // } // // public AddressV3(String adressLine1, String adressLine2, CityV3 location) { // this.addressLine1 = adressLine1; // this.addressLine2 = adressLine2; // this.city = location; // } // // public AddressV3(CityV3 location, String... addressLines) { // this.addressLines.addAll(asList(addressLines)); // this.city = location; // } // // public String getAddressLine1() { // return addressLine1; // } // // public void setAddressLine1(String addressLine1) { // this.addressLine1 = addressLine1; // } // // public String getAddressLine2() { // return addressLine2; // } // // public void setAddressLine2(String addressLine2) { // this.addressLine2 = addressLine2; // } // // public Set<String> getAddressLines() { // return addressLines; // } // // public void setAddressLines(SortedSet<String> addressLines) { // this.addressLines = addressLines; // } // // public CityV3 getCity() { // return city; // } // // public void setCity(CityV3 city) { // this.city = city; // } // // public AddressTypeV3 getType() { // return type; // } // // public void setType(AddressTypeV3 type) { // this.type = type; // } // } // // Path: jaxrs-versioning/src/test/java/de/openknowledge/jaxrs/versioning/model/CityV3.java // public class CityV3 { // // protected String zipCode; // // protected String cityName; // // protected CityV3() { // } // // public CityV3(String zipCode, String cityName) { // this.zipCode = zipCode; // this.cityName = cityName; // } // // public String getZipCode() { // return zipCode; // } // // public void setZipCode(String zipCode) { // this.zipCode = zipCode; // } // // public String getCityName() { // return cityName; // } // // public void setCityName(String cityName) { // this.cityName = cityName; // } // }
import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import de.openknowledge.jaxrs.versioning.VersionedMediaType; import de.openknowledge.jaxrs.versioning.model.AddressV3; import de.openknowledge.jaxrs.versioning.model.CityV3;
/* * Copyright (C) open knowledge GmbH * * 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 de.openknowledge.jaxrs.versioning.resources; /** * @author Arne Limburg - open knowledge GmbH */ @Path("/addresses") public class VersionedMediaTypeAddressResource { @GET @Produces(MediaType.APPLICATION_JSON) @Path("/{id}") @VersionedMediaType(value = "application/vnd+de.openknowledge.jaxrs.versioning+json+{version}", mapsTo = "application/json") public AddressV3 getAddress(@PathParam("id") String id) {
// Path: jaxrs-versioning/src/test/java/de/openknowledge/jaxrs/versioning/model/AddressV3.java // @SupportedVersion(version = "v3", previous = AddressV2.class) // public class AddressV3 { // // protected SortedSet<String> addressLines = new TreeSet<String>(reverseOrder()); // // @MovedFrom("addressLines[0]") // protected String addressLine1; // // @MovedFrom("addressLines[1]") // protected String addressLine2; // // protected CityV3 city; // // private AddressTypeV3 type; // // protected AddressV3() { // } // // public AddressV3(String adressLine1, String adressLine2, CityV3 location) { // this.addressLine1 = adressLine1; // this.addressLine2 = adressLine2; // this.city = location; // } // // public AddressV3(CityV3 location, String... addressLines) { // this.addressLines.addAll(asList(addressLines)); // this.city = location; // } // // public String getAddressLine1() { // return addressLine1; // } // // public void setAddressLine1(String addressLine1) { // this.addressLine1 = addressLine1; // } // // public String getAddressLine2() { // return addressLine2; // } // // public void setAddressLine2(String addressLine2) { // this.addressLine2 = addressLine2; // } // // public Set<String> getAddressLines() { // return addressLines; // } // // public void setAddressLines(SortedSet<String> addressLines) { // this.addressLines = addressLines; // } // // public CityV3 getCity() { // return city; // } // // public void setCity(CityV3 city) { // this.city = city; // } // // public AddressTypeV3 getType() { // return type; // } // // public void setType(AddressTypeV3 type) { // this.type = type; // } // } // // Path: jaxrs-versioning/src/test/java/de/openknowledge/jaxrs/versioning/model/CityV3.java // public class CityV3 { // // protected String zipCode; // // protected String cityName; // // protected CityV3() { // } // // public CityV3(String zipCode, String cityName) { // this.zipCode = zipCode; // this.cityName = cityName; // } // // public String getZipCode() { // return zipCode; // } // // public void setZipCode(String zipCode) { // this.zipCode = zipCode; // } // // public String getCityName() { // return cityName; // } // // public void setCityName(String cityName) { // this.cityName = cityName; // } // } // Path: jaxrs-versioning/src/test/java/de/openknowledge/jaxrs/versioning/resources/VersionedMediaTypeAddressResource.java import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import de.openknowledge.jaxrs.versioning.VersionedMediaType; import de.openknowledge.jaxrs.versioning.model.AddressV3; import de.openknowledge.jaxrs.versioning.model.CityV3; /* * Copyright (C) open knowledge GmbH * * 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 de.openknowledge.jaxrs.versioning.resources; /** * @author Arne Limburg - open knowledge GmbH */ @Path("/addresses") public class VersionedMediaTypeAddressResource { @GET @Produces(MediaType.APPLICATION_JSON) @Path("/{id}") @VersionedMediaType(value = "application/vnd+de.openknowledge.jaxrs.versioning+json+{version}", mapsTo = "application/json") public AddressV3 getAddress(@PathParam("id") String id) {
return new AddressV3("Samplestreet 1", " ", new CityV3("12345", "Samplecity"));
openknowledge/jaxrs-versioning
jaxrs-versioning/src/test/java/de/openknowledge/jaxrs/versioning/resources/VersionHeaderAddressResource.java
// Path: jaxrs-versioning/src/test/java/de/openknowledge/jaxrs/versioning/model/AddressV3.java // @SupportedVersion(version = "v3", previous = AddressV2.class) // public class AddressV3 { // // protected SortedSet<String> addressLines = new TreeSet<String>(reverseOrder()); // // @MovedFrom("addressLines[0]") // protected String addressLine1; // // @MovedFrom("addressLines[1]") // protected String addressLine2; // // protected CityV3 city; // // private AddressTypeV3 type; // // protected AddressV3() { // } // // public AddressV3(String adressLine1, String adressLine2, CityV3 location) { // this.addressLine1 = adressLine1; // this.addressLine2 = adressLine2; // this.city = location; // } // // public AddressV3(CityV3 location, String... addressLines) { // this.addressLines.addAll(asList(addressLines)); // this.city = location; // } // // public String getAddressLine1() { // return addressLine1; // } // // public void setAddressLine1(String addressLine1) { // this.addressLine1 = addressLine1; // } // // public String getAddressLine2() { // return addressLine2; // } // // public void setAddressLine2(String addressLine2) { // this.addressLine2 = addressLine2; // } // // public Set<String> getAddressLines() { // return addressLines; // } // // public void setAddressLines(SortedSet<String> addressLines) { // this.addressLines = addressLines; // } // // public CityV3 getCity() { // return city; // } // // public void setCity(CityV3 city) { // this.city = city; // } // // public AddressTypeV3 getType() { // return type; // } // // public void setType(AddressTypeV3 type) { // this.type = type; // } // }
import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import de.openknowledge.jaxrs.versioning.VersionHeader; import de.openknowledge.jaxrs.versioning.model.AddressV3;
/* * Copyright (C) open knowledge GmbH * * 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 de.openknowledge.jaxrs.versioning.resources; /** * @author Arne Limburg - open knowledge GmbH * @author Philipp Geers - open knowledge GmbH */ @Path("/addresses") public class VersionHeaderAddressResource { @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Path("/{id}") @VersionHeader("Api-Version")
// Path: jaxrs-versioning/src/test/java/de/openknowledge/jaxrs/versioning/model/AddressV3.java // @SupportedVersion(version = "v3", previous = AddressV2.class) // public class AddressV3 { // // protected SortedSet<String> addressLines = new TreeSet<String>(reverseOrder()); // // @MovedFrom("addressLines[0]") // protected String addressLine1; // // @MovedFrom("addressLines[1]") // protected String addressLine2; // // protected CityV3 city; // // private AddressTypeV3 type; // // protected AddressV3() { // } // // public AddressV3(String adressLine1, String adressLine2, CityV3 location) { // this.addressLine1 = adressLine1; // this.addressLine2 = adressLine2; // this.city = location; // } // // public AddressV3(CityV3 location, String... addressLines) { // this.addressLines.addAll(asList(addressLines)); // this.city = location; // } // // public String getAddressLine1() { // return addressLine1; // } // // public void setAddressLine1(String addressLine1) { // this.addressLine1 = addressLine1; // } // // public String getAddressLine2() { // return addressLine2; // } // // public void setAddressLine2(String addressLine2) { // this.addressLine2 = addressLine2; // } // // public Set<String> getAddressLines() { // return addressLines; // } // // public void setAddressLines(SortedSet<String> addressLines) { // this.addressLines = addressLines; // } // // public CityV3 getCity() { // return city; // } // // public void setCity(CityV3 city) { // this.city = city; // } // // public AddressTypeV3 getType() { // return type; // } // // public void setType(AddressTypeV3 type) { // this.type = type; // } // } // Path: jaxrs-versioning/src/test/java/de/openknowledge/jaxrs/versioning/resources/VersionHeaderAddressResource.java import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import de.openknowledge.jaxrs.versioning.VersionHeader; import de.openknowledge.jaxrs.versioning.model.AddressV3; /* * Copyright (C) open knowledge GmbH * * 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 de.openknowledge.jaxrs.versioning.resources; /** * @author Arne Limburg - open knowledge GmbH * @author Philipp Geers - open knowledge GmbH */ @Path("/addresses") public class VersionHeaderAddressResource { @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Path("/{id}") @VersionHeader("Api-Version")
public AddressV3 createAddress(AddressV3 address) {
openknowledge/jaxrs-versioning
jaxrs-versioning/src/test/java/de/openknowledge/jaxrs/versioning/model/CityAggregationProvider.java
// Path: jaxrs-versioning/src/main/java/de/openknowledge/jaxrs/versioning/Provider.java // public interface Provider<T> { // public T get(VersionContext versionContext); // } // // Path: jaxrs-versioning/src/main/java/de/openknowledge/jaxrs/versioning/VersionContext.java // public interface VersionContext { // // Object getParent(); // // <T> T getParent(Class<T> type); // // String getPropertyName(); // }
import de.openknowledge.jaxrs.versioning.Provider; import de.openknowledge.jaxrs.versioning.VersionContext;
/* * Copyright (C) open knowledge GmbH * * 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 de.openknowledge.jaxrs.versioning.model; /** * @author Arne Limburg - open knowledge GmbH */ public class CityAggregationProvider implements Provider<String> { @Override
// Path: jaxrs-versioning/src/main/java/de/openknowledge/jaxrs/versioning/Provider.java // public interface Provider<T> { // public T get(VersionContext versionContext); // } // // Path: jaxrs-versioning/src/main/java/de/openknowledge/jaxrs/versioning/VersionContext.java // public interface VersionContext { // // Object getParent(); // // <T> T getParent(Class<T> type); // // String getPropertyName(); // } // Path: jaxrs-versioning/src/test/java/de/openknowledge/jaxrs/versioning/model/CityAggregationProvider.java import de.openknowledge.jaxrs.versioning.Provider; import de.openknowledge.jaxrs.versioning.VersionContext; /* * Copyright (C) open knowledge GmbH * * 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 de.openknowledge.jaxrs.versioning.model; /** * @author Arne Limburg - open knowledge GmbH */ public class CityAggregationProvider implements Provider<String> { @Override
public String get(VersionContext versionContext) {
openknowledge/jaxrs-versioning
jaxrs-versioning/src/test/java/de/openknowledge/jaxrs/versioning/model/HouseNumberProvider.java
// Path: jaxrs-versioning/src/main/java/de/openknowledge/jaxrs/versioning/Provider.java // public interface Provider<T> { // public T get(VersionContext versionContext); // } // // Path: jaxrs-versioning/src/main/java/de/openknowledge/jaxrs/versioning/VersionContext.java // public interface VersionContext { // // Object getParent(); // // <T> T getParent(Class<T> type); // // String getPropertyName(); // }
import de.openknowledge.jaxrs.versioning.Provider; import de.openknowledge.jaxrs.versioning.VersionContext;
/* * Copyright (C) open knowledge GmbH * * 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 de.openknowledge.jaxrs.versioning.model; /** * @author Arne Limburg - open knowledge GmbH */ public class HouseNumberProvider implements Provider<String> { @Override
// Path: jaxrs-versioning/src/main/java/de/openknowledge/jaxrs/versioning/Provider.java // public interface Provider<T> { // public T get(VersionContext versionContext); // } // // Path: jaxrs-versioning/src/main/java/de/openknowledge/jaxrs/versioning/VersionContext.java // public interface VersionContext { // // Object getParent(); // // <T> T getParent(Class<T> type); // // String getPropertyName(); // } // Path: jaxrs-versioning/src/test/java/de/openknowledge/jaxrs/versioning/model/HouseNumberProvider.java import de.openknowledge.jaxrs.versioning.Provider; import de.openknowledge.jaxrs.versioning.VersionContext; /* * Copyright (C) open knowledge GmbH * * 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 de.openknowledge.jaxrs.versioning.model; /** * @author Arne Limburg - open knowledge GmbH */ public class HouseNumberProvider implements Provider<String> { @Override
public String get(VersionContext versionContext) {
openknowledge/jaxrs-versioning
jaxrs-versioning/src/test/java/de/openknowledge/jaxrs/versioning/model/StreetAggregationProvider.java
// Path: jaxrs-versioning/src/main/java/de/openknowledge/jaxrs/versioning/Provider.java // public interface Provider<T> { // public T get(VersionContext versionContext); // } // // Path: jaxrs-versioning/src/main/java/de/openknowledge/jaxrs/versioning/VersionContext.java // public interface VersionContext { // // Object getParent(); // // <T> T getParent(Class<T> type); // // String getPropertyName(); // }
import de.openknowledge.jaxrs.versioning.Provider; import de.openknowledge.jaxrs.versioning.VersionContext;
/* * Copyright (C) open knowledge GmbH * * 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 de.openknowledge.jaxrs.versioning.model; /** * @author Philipp Geers - open knowledge GmbH */ public class StreetAggregationProvider implements Provider<String> { @Override
// Path: jaxrs-versioning/src/main/java/de/openknowledge/jaxrs/versioning/Provider.java // public interface Provider<T> { // public T get(VersionContext versionContext); // } // // Path: jaxrs-versioning/src/main/java/de/openknowledge/jaxrs/versioning/VersionContext.java // public interface VersionContext { // // Object getParent(); // // <T> T getParent(Class<T> type); // // String getPropertyName(); // } // Path: jaxrs-versioning/src/test/java/de/openknowledge/jaxrs/versioning/model/StreetAggregationProvider.java import de.openknowledge.jaxrs.versioning.Provider; import de.openknowledge.jaxrs.versioning.VersionContext; /* * Copyright (C) open knowledge GmbH * * 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 de.openknowledge.jaxrs.versioning.model; /** * @author Philipp Geers - open knowledge GmbH */ public class StreetAggregationProvider implements Provider<String> { @Override
public String get(VersionContext versionContext) {
openknowledge/jaxrs-versioning
jaxrs-versioning/src/test/java/de/openknowledge/jaxrs/versioning/resources/AddressResource.java
// Path: jaxrs-versioning/src/test/java/de/openknowledge/jaxrs/versioning/model/AddressV3.java // @SupportedVersion(version = "v3", previous = AddressV2.class) // public class AddressV3 { // // protected SortedSet<String> addressLines = new TreeSet<String>(reverseOrder()); // // @MovedFrom("addressLines[0]") // protected String addressLine1; // // @MovedFrom("addressLines[1]") // protected String addressLine2; // // protected CityV3 city; // // private AddressTypeV3 type; // // protected AddressV3() { // } // // public AddressV3(String adressLine1, String adressLine2, CityV3 location) { // this.addressLine1 = adressLine1; // this.addressLine2 = adressLine2; // this.city = location; // } // // public AddressV3(CityV3 location, String... addressLines) { // this.addressLines.addAll(asList(addressLines)); // this.city = location; // } // // public String getAddressLine1() { // return addressLine1; // } // // public void setAddressLine1(String addressLine1) { // this.addressLine1 = addressLine1; // } // // public String getAddressLine2() { // return addressLine2; // } // // public void setAddressLine2(String addressLine2) { // this.addressLine2 = addressLine2; // } // // public Set<String> getAddressLines() { // return addressLines; // } // // public void setAddressLines(SortedSet<String> addressLines) { // this.addressLines = addressLines; // } // // public CityV3 getCity() { // return city; // } // // public void setCity(CityV3 city) { // this.city = city; // } // // public AddressTypeV3 getType() { // return type; // } // // public void setType(AddressTypeV3 type) { // this.type = type; // } // } // // Path: jaxrs-versioning/src/test/java/de/openknowledge/jaxrs/versioning/model/CityV3.java // public class CityV3 { // // protected String zipCode; // // protected String cityName; // // protected CityV3() { // } // // public CityV3(String zipCode, String cityName) { // this.zipCode = zipCode; // this.cityName = cityName; // } // // public String getZipCode() { // return zipCode; // } // // public void setZipCode(String zipCode) { // this.zipCode = zipCode; // } // // public String getCityName() { // return cityName; // } // // public void setCityName(String cityName) { // this.cityName = cityName; // } // }
import java.util.Arrays; import java.util.List; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import de.openknowledge.jaxrs.versioning.model.AddressV3; import de.openknowledge.jaxrs.versioning.model.CityV3;
/* * Copyright (C) open knowledge GmbH * * 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 de.openknowledge.jaxrs.versioning.resources; /** * @author Arne Limburg - open knowledge GmbH * @author Philipp Geers - open knowledge GmbH */ @Path("/{version}/addresses") public class AddressResource { @GET @Produces(MediaType.APPLICATION_JSON)
// Path: jaxrs-versioning/src/test/java/de/openknowledge/jaxrs/versioning/model/AddressV3.java // @SupportedVersion(version = "v3", previous = AddressV2.class) // public class AddressV3 { // // protected SortedSet<String> addressLines = new TreeSet<String>(reverseOrder()); // // @MovedFrom("addressLines[0]") // protected String addressLine1; // // @MovedFrom("addressLines[1]") // protected String addressLine2; // // protected CityV3 city; // // private AddressTypeV3 type; // // protected AddressV3() { // } // // public AddressV3(String adressLine1, String adressLine2, CityV3 location) { // this.addressLine1 = adressLine1; // this.addressLine2 = adressLine2; // this.city = location; // } // // public AddressV3(CityV3 location, String... addressLines) { // this.addressLines.addAll(asList(addressLines)); // this.city = location; // } // // public String getAddressLine1() { // return addressLine1; // } // // public void setAddressLine1(String addressLine1) { // this.addressLine1 = addressLine1; // } // // public String getAddressLine2() { // return addressLine2; // } // // public void setAddressLine2(String addressLine2) { // this.addressLine2 = addressLine2; // } // // public Set<String> getAddressLines() { // return addressLines; // } // // public void setAddressLines(SortedSet<String> addressLines) { // this.addressLines = addressLines; // } // // public CityV3 getCity() { // return city; // } // // public void setCity(CityV3 city) { // this.city = city; // } // // public AddressTypeV3 getType() { // return type; // } // // public void setType(AddressTypeV3 type) { // this.type = type; // } // } // // Path: jaxrs-versioning/src/test/java/de/openknowledge/jaxrs/versioning/model/CityV3.java // public class CityV3 { // // protected String zipCode; // // protected String cityName; // // protected CityV3() { // } // // public CityV3(String zipCode, String cityName) { // this.zipCode = zipCode; // this.cityName = cityName; // } // // public String getZipCode() { // return zipCode; // } // // public void setZipCode(String zipCode) { // this.zipCode = zipCode; // } // // public String getCityName() { // return cityName; // } // // public void setCityName(String cityName) { // this.cityName = cityName; // } // } // Path: jaxrs-versioning/src/test/java/de/openknowledge/jaxrs/versioning/resources/AddressResource.java import java.util.Arrays; import java.util.List; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import de.openknowledge.jaxrs.versioning.model.AddressV3; import de.openknowledge.jaxrs.versioning.model.CityV3; /* * Copyright (C) open knowledge GmbH * * 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 de.openknowledge.jaxrs.versioning.resources; /** * @author Arne Limburg - open knowledge GmbH * @author Philipp Geers - open knowledge GmbH */ @Path("/{version}/addresses") public class AddressResource { @GET @Produces(MediaType.APPLICATION_JSON)
public List<AddressV3> getAddresses() {
openknowledge/jaxrs-versioning
jaxrs-versioning/src/test/java/de/openknowledge/jaxrs/versioning/resources/AddressResource.java
// Path: jaxrs-versioning/src/test/java/de/openknowledge/jaxrs/versioning/model/AddressV3.java // @SupportedVersion(version = "v3", previous = AddressV2.class) // public class AddressV3 { // // protected SortedSet<String> addressLines = new TreeSet<String>(reverseOrder()); // // @MovedFrom("addressLines[0]") // protected String addressLine1; // // @MovedFrom("addressLines[1]") // protected String addressLine2; // // protected CityV3 city; // // private AddressTypeV3 type; // // protected AddressV3() { // } // // public AddressV3(String adressLine1, String adressLine2, CityV3 location) { // this.addressLine1 = adressLine1; // this.addressLine2 = adressLine2; // this.city = location; // } // // public AddressV3(CityV3 location, String... addressLines) { // this.addressLines.addAll(asList(addressLines)); // this.city = location; // } // // public String getAddressLine1() { // return addressLine1; // } // // public void setAddressLine1(String addressLine1) { // this.addressLine1 = addressLine1; // } // // public String getAddressLine2() { // return addressLine2; // } // // public void setAddressLine2(String addressLine2) { // this.addressLine2 = addressLine2; // } // // public Set<String> getAddressLines() { // return addressLines; // } // // public void setAddressLines(SortedSet<String> addressLines) { // this.addressLines = addressLines; // } // // public CityV3 getCity() { // return city; // } // // public void setCity(CityV3 city) { // this.city = city; // } // // public AddressTypeV3 getType() { // return type; // } // // public void setType(AddressTypeV3 type) { // this.type = type; // } // } // // Path: jaxrs-versioning/src/test/java/de/openknowledge/jaxrs/versioning/model/CityV3.java // public class CityV3 { // // protected String zipCode; // // protected String cityName; // // protected CityV3() { // } // // public CityV3(String zipCode, String cityName) { // this.zipCode = zipCode; // this.cityName = cityName; // } // // public String getZipCode() { // return zipCode; // } // // public void setZipCode(String zipCode) { // this.zipCode = zipCode; // } // // public String getCityName() { // return cityName; // } // // public void setCityName(String cityName) { // this.cityName = cityName; // } // }
import java.util.Arrays; import java.util.List; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import de.openknowledge.jaxrs.versioning.model.AddressV3; import de.openknowledge.jaxrs.versioning.model.CityV3;
/* * Copyright (C) open knowledge GmbH * * 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 de.openknowledge.jaxrs.versioning.resources; /** * @author Arne Limburg - open knowledge GmbH * @author Philipp Geers - open knowledge GmbH */ @Path("/{version}/addresses") public class AddressResource { @GET @Produces(MediaType.APPLICATION_JSON) public List<AddressV3> getAddresses() { return Arrays.asList( new AddressV3( "Samplestreet 1", " ",
// Path: jaxrs-versioning/src/test/java/de/openknowledge/jaxrs/versioning/model/AddressV3.java // @SupportedVersion(version = "v3", previous = AddressV2.class) // public class AddressV3 { // // protected SortedSet<String> addressLines = new TreeSet<String>(reverseOrder()); // // @MovedFrom("addressLines[0]") // protected String addressLine1; // // @MovedFrom("addressLines[1]") // protected String addressLine2; // // protected CityV3 city; // // private AddressTypeV3 type; // // protected AddressV3() { // } // // public AddressV3(String adressLine1, String adressLine2, CityV3 location) { // this.addressLine1 = adressLine1; // this.addressLine2 = adressLine2; // this.city = location; // } // // public AddressV3(CityV3 location, String... addressLines) { // this.addressLines.addAll(asList(addressLines)); // this.city = location; // } // // public String getAddressLine1() { // return addressLine1; // } // // public void setAddressLine1(String addressLine1) { // this.addressLine1 = addressLine1; // } // // public String getAddressLine2() { // return addressLine2; // } // // public void setAddressLine2(String addressLine2) { // this.addressLine2 = addressLine2; // } // // public Set<String> getAddressLines() { // return addressLines; // } // // public void setAddressLines(SortedSet<String> addressLines) { // this.addressLines = addressLines; // } // // public CityV3 getCity() { // return city; // } // // public void setCity(CityV3 city) { // this.city = city; // } // // public AddressTypeV3 getType() { // return type; // } // // public void setType(AddressTypeV3 type) { // this.type = type; // } // } // // Path: jaxrs-versioning/src/test/java/de/openknowledge/jaxrs/versioning/model/CityV3.java // public class CityV3 { // // protected String zipCode; // // protected String cityName; // // protected CityV3() { // } // // public CityV3(String zipCode, String cityName) { // this.zipCode = zipCode; // this.cityName = cityName; // } // // public String getZipCode() { // return zipCode; // } // // public void setZipCode(String zipCode) { // this.zipCode = zipCode; // } // // public String getCityName() { // return cityName; // } // // public void setCityName(String cityName) { // this.cityName = cityName; // } // } // Path: jaxrs-versioning/src/test/java/de/openknowledge/jaxrs/versioning/resources/AddressResource.java import java.util.Arrays; import java.util.List; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import de.openknowledge.jaxrs.versioning.model.AddressV3; import de.openknowledge.jaxrs.versioning.model.CityV3; /* * Copyright (C) open knowledge GmbH * * 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 de.openknowledge.jaxrs.versioning.resources; /** * @author Arne Limburg - open knowledge GmbH * @author Philipp Geers - open knowledge GmbH */ @Path("/{version}/addresses") public class AddressResource { @GET @Produces(MediaType.APPLICATION_JSON) public List<AddressV3> getAddresses() { return Arrays.asList( new AddressV3( "Samplestreet 1", " ",
new CityV3(
openknowledge/jaxrs-versioning
jaxrs-versioning/src/test/java/de/openknowledge/jaxrs/versioning/resources/VersionQueryParameterAddressResource.java
// Path: jaxrs-versioning/src/test/java/de/openknowledge/jaxrs/versioning/model/AddressV3.java // @SupportedVersion(version = "v3", previous = AddressV2.class) // public class AddressV3 { // // protected SortedSet<String> addressLines = new TreeSet<String>(reverseOrder()); // // @MovedFrom("addressLines[0]") // protected String addressLine1; // // @MovedFrom("addressLines[1]") // protected String addressLine2; // // protected CityV3 city; // // private AddressTypeV3 type; // // protected AddressV3() { // } // // public AddressV3(String adressLine1, String adressLine2, CityV3 location) { // this.addressLine1 = adressLine1; // this.addressLine2 = adressLine2; // this.city = location; // } // // public AddressV3(CityV3 location, String... addressLines) { // this.addressLines.addAll(asList(addressLines)); // this.city = location; // } // // public String getAddressLine1() { // return addressLine1; // } // // public void setAddressLine1(String addressLine1) { // this.addressLine1 = addressLine1; // } // // public String getAddressLine2() { // return addressLine2; // } // // public void setAddressLine2(String addressLine2) { // this.addressLine2 = addressLine2; // } // // public Set<String> getAddressLines() { // return addressLines; // } // // public void setAddressLines(SortedSet<String> addressLines) { // this.addressLines = addressLines; // } // // public CityV3 getCity() { // return city; // } // // public void setCity(CityV3 city) { // this.city = city; // } // // public AddressTypeV3 getType() { // return type; // } // // public void setType(AddressTypeV3 type) { // this.type = type; // } // }
import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import de.openknowledge.jaxrs.versioning.VersionQueryParameter; import de.openknowledge.jaxrs.versioning.model.AddressV3;
/* * Copyright (C) open knowledge GmbH * * 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 de.openknowledge.jaxrs.versioning.resources; /** * @author Arne Limburg - open knowledge GmbH */ @Path("/addresses") public class VersionQueryParameterAddressResource { @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Path("/{id}") @VersionQueryParameter("version")
// Path: jaxrs-versioning/src/test/java/de/openknowledge/jaxrs/versioning/model/AddressV3.java // @SupportedVersion(version = "v3", previous = AddressV2.class) // public class AddressV3 { // // protected SortedSet<String> addressLines = new TreeSet<String>(reverseOrder()); // // @MovedFrom("addressLines[0]") // protected String addressLine1; // // @MovedFrom("addressLines[1]") // protected String addressLine2; // // protected CityV3 city; // // private AddressTypeV3 type; // // protected AddressV3() { // } // // public AddressV3(String adressLine1, String adressLine2, CityV3 location) { // this.addressLine1 = adressLine1; // this.addressLine2 = adressLine2; // this.city = location; // } // // public AddressV3(CityV3 location, String... addressLines) { // this.addressLines.addAll(asList(addressLines)); // this.city = location; // } // // public String getAddressLine1() { // return addressLine1; // } // // public void setAddressLine1(String addressLine1) { // this.addressLine1 = addressLine1; // } // // public String getAddressLine2() { // return addressLine2; // } // // public void setAddressLine2(String addressLine2) { // this.addressLine2 = addressLine2; // } // // public Set<String> getAddressLines() { // return addressLines; // } // // public void setAddressLines(SortedSet<String> addressLines) { // this.addressLines = addressLines; // } // // public CityV3 getCity() { // return city; // } // // public void setCity(CityV3 city) { // this.city = city; // } // // public AddressTypeV3 getType() { // return type; // } // // public void setType(AddressTypeV3 type) { // this.type = type; // } // } // Path: jaxrs-versioning/src/test/java/de/openknowledge/jaxrs/versioning/resources/VersionQueryParameterAddressResource.java import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import de.openknowledge.jaxrs.versioning.VersionQueryParameter; import de.openknowledge.jaxrs.versioning.model.AddressV3; /* * Copyright (C) open knowledge GmbH * * 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 de.openknowledge.jaxrs.versioning.resources; /** * @author Arne Limburg - open knowledge GmbH */ @Path("/addresses") public class VersionQueryParameterAddressResource { @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Path("/{id}") @VersionQueryParameter("version")
public AddressV3 createAddress(AddressV3 address) {
zak0/AppTycoon
app/src/main/java/jaakko/jaaska/apptycoon/engine/product/Product.java
// Path: app/src/main/java/jaakko/jaaska/apptycoon/engine/project/FeatureTask.java // public class FeatureTask implements ProjectTask { // // private ProductFeature mFeature; // private int mStartLevel; // private int mEndLevel; // // public FeatureTask(ProductFeature feature, int fromLevel, int toLevel) { // mFeature = feature; // mStartLevel = fromLevel; // mEndLevel = toLevel; // } // // @Override // public String getTaskTitle() { // return mFeature.getName() + " to level " + mEndLevel; // } // // @Override // public long getQuantity() { // return mEndLevel - mStartLevel; // } // // @Override // public String getTextualQuantity() { // return "+" + getQuantity(); // } // // @Override // public long getWorkAmount() { // return mFeature.getComplexityForUpgrade(mStartLevel, mEndLevel); // } // } // // Path: app/src/main/java/jaakko/jaaska/apptycoon/engine/project/NewProductTask.java // public class NewProductTask implements ProjectTask { // // /** The new product being developed. */ // private Product mProduct; // // public NewProductTask(Product product) { // mProduct = product; // } // // @Override // public String getTaskTitle() { // return "Product Development"; // } // // @Override // public long getQuantity() { // return 1; // } // // @Override // public String getTextualQuantity() { // return null; // } // // @Override // public long getWorkAmount() { // // Work amount for the "initial development" of the product. // // // // [base complexity of the product type] * 2 ^ [number of features] = [work amount] // long workAmount = mProduct.getType().getBaseComplexity(); // workAmount = (long) (workAmount * Math.pow(2, mProduct.getFeatures().size())); // // return workAmount; // } // } // // Path: app/src/main/java/jaakko/jaaska/apptycoon/engine/project/ProductDevelopmentProject.java // public class ProductDevelopmentProject extends Project { // // private Product mProduct; // private double mFractionalQuality; // private long mQualityGain; // // public ProductDevelopmentProject(String description, Product product) { // // Name of the new product dev. project is "New [product type]" // super("R&D - " + product.getType().getName(), description); // mProduct = product; // } // // @Override // protected long calculateWorkAmount() { // // long workAmount = 0; // // // Work amount is the sum of work amounts of all the tasks. // for (ProjectTask task : mTasks) { // workAmount += task.getWorkAmount(); // } // // return workAmount; // } // // @Override // public boolean isReady() { // return true; // } // // /** Delivering the project releases the new version of the product. */ // @Override // public void deliver() { // mProduct.releaseNextVersion(); // GameEngine.getInstance().getGameState().getCompany().onIncomeChanged(); // // Toast.makeText(AppTycoonApp.getContext(), // mProduct.getName() + " released", // Toast.LENGTH_LONG).show(); // } // // public void removeAllTasks() { // mTasks = new ArrayList<>(); // } // // @Override // public void progress(double workAmount, double qualityAmount, long time) { // super.progress(workAmount, qualityAmount, time); // // // Add quality gain. // mFractionalQuality += qualityAmount; // long qualityIntPart = (long) mFractionalQuality; // mFractionalQuality -= qualityIntPart; // mQualityGain += qualityIntPart; // // } // // public long getQualityGain() { // return mQualityGain; // } // }
import android.support.v4.util.Pair; import android.util.Log; import android.util.SparseArray; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Random; import jaakko.jaaska.apptycoon.engine.project.FeatureTask; import jaakko.jaaska.apptycoon.engine.project.NewProductTask; import jaakko.jaaska.apptycoon.engine.project.ProductDevelopmentProject;
package jaakko.jaaska.apptycoon.engine.product; /** * TODO: Refactor the ProductFeatures to be similar to EmployeeType: instance specific data (like level) into ProductFeature class, Product to have its features as List<ProductFeature>. */ public class Product { private static final String TAG = "Product"; private String mName; /** Number of releases of this product */ private int mReleaseCount; /** The main type */ private ProductType mType; /** Features and their current levels */ private List<Pair<ProductFeature, Integer>> mFeatures; /** Sub-products */ private List<Product> mSubProducts; /** The version of this product currently in distribution */ private Product mReleasedVersion; /** Calculated complexity of the product */ private long mComplexity; /** Current quality of the product */ private long mQuality; /** Number of active users the product has */ private long mUsers; /** Number of all-time downloads (or purchases for a paid product) */ private long mDownloads; /** Money made from one sold unit */ private int mUnitPrice; /** Amount of money the product has earned all-time */ private long mTotalEarnings; /** * Array of all the features that directly generate income. * Key of the array is the ID of the feature. * * All income values are money per second per active user. */ private SparseArray<Double> mFeatureIncomes; /** The development project for the next release. This will be null until the next version * is defined. Be sure to nullify this after the project is done! */
// Path: app/src/main/java/jaakko/jaaska/apptycoon/engine/project/FeatureTask.java // public class FeatureTask implements ProjectTask { // // private ProductFeature mFeature; // private int mStartLevel; // private int mEndLevel; // // public FeatureTask(ProductFeature feature, int fromLevel, int toLevel) { // mFeature = feature; // mStartLevel = fromLevel; // mEndLevel = toLevel; // } // // @Override // public String getTaskTitle() { // return mFeature.getName() + " to level " + mEndLevel; // } // // @Override // public long getQuantity() { // return mEndLevel - mStartLevel; // } // // @Override // public String getTextualQuantity() { // return "+" + getQuantity(); // } // // @Override // public long getWorkAmount() { // return mFeature.getComplexityForUpgrade(mStartLevel, mEndLevel); // } // } // // Path: app/src/main/java/jaakko/jaaska/apptycoon/engine/project/NewProductTask.java // public class NewProductTask implements ProjectTask { // // /** The new product being developed. */ // private Product mProduct; // // public NewProductTask(Product product) { // mProduct = product; // } // // @Override // public String getTaskTitle() { // return "Product Development"; // } // // @Override // public long getQuantity() { // return 1; // } // // @Override // public String getTextualQuantity() { // return null; // } // // @Override // public long getWorkAmount() { // // Work amount for the "initial development" of the product. // // // // [base complexity of the product type] * 2 ^ [number of features] = [work amount] // long workAmount = mProduct.getType().getBaseComplexity(); // workAmount = (long) (workAmount * Math.pow(2, mProduct.getFeatures().size())); // // return workAmount; // } // } // // Path: app/src/main/java/jaakko/jaaska/apptycoon/engine/project/ProductDevelopmentProject.java // public class ProductDevelopmentProject extends Project { // // private Product mProduct; // private double mFractionalQuality; // private long mQualityGain; // // public ProductDevelopmentProject(String description, Product product) { // // Name of the new product dev. project is "New [product type]" // super("R&D - " + product.getType().getName(), description); // mProduct = product; // } // // @Override // protected long calculateWorkAmount() { // // long workAmount = 0; // // // Work amount is the sum of work amounts of all the tasks. // for (ProjectTask task : mTasks) { // workAmount += task.getWorkAmount(); // } // // return workAmount; // } // // @Override // public boolean isReady() { // return true; // } // // /** Delivering the project releases the new version of the product. */ // @Override // public void deliver() { // mProduct.releaseNextVersion(); // GameEngine.getInstance().getGameState().getCompany().onIncomeChanged(); // // Toast.makeText(AppTycoonApp.getContext(), // mProduct.getName() + " released", // Toast.LENGTH_LONG).show(); // } // // public void removeAllTasks() { // mTasks = new ArrayList<>(); // } // // @Override // public void progress(double workAmount, double qualityAmount, long time) { // super.progress(workAmount, qualityAmount, time); // // // Add quality gain. // mFractionalQuality += qualityAmount; // long qualityIntPart = (long) mFractionalQuality; // mFractionalQuality -= qualityIntPart; // mQualityGain += qualityIntPart; // // } // // public long getQualityGain() { // return mQualityGain; // } // } // Path: app/src/main/java/jaakko/jaaska/apptycoon/engine/product/Product.java import android.support.v4.util.Pair; import android.util.Log; import android.util.SparseArray; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Random; import jaakko.jaaska.apptycoon.engine.project.FeatureTask; import jaakko.jaaska.apptycoon.engine.project.NewProductTask; import jaakko.jaaska.apptycoon.engine.project.ProductDevelopmentProject; package jaakko.jaaska.apptycoon.engine.product; /** * TODO: Refactor the ProductFeatures to be similar to EmployeeType: instance specific data (like level) into ProductFeature class, Product to have its features as List<ProductFeature>. */ public class Product { private static final String TAG = "Product"; private String mName; /** Number of releases of this product */ private int mReleaseCount; /** The main type */ private ProductType mType; /** Features and their current levels */ private List<Pair<ProductFeature, Integer>> mFeatures; /** Sub-products */ private List<Product> mSubProducts; /** The version of this product currently in distribution */ private Product mReleasedVersion; /** Calculated complexity of the product */ private long mComplexity; /** Current quality of the product */ private long mQuality; /** Number of active users the product has */ private long mUsers; /** Number of all-time downloads (or purchases for a paid product) */ private long mDownloads; /** Money made from one sold unit */ private int mUnitPrice; /** Amount of money the product has earned all-time */ private long mTotalEarnings; /** * Array of all the features that directly generate income. * Key of the array is the ID of the feature. * * All income values are money per second per active user. */ private SparseArray<Double> mFeatureIncomes; /** The development project for the next release. This will be null until the next version * is defined. Be sure to nullify this after the project is done! */
private ProductDevelopmentProject mDevProject;
zak0/AppTycoon
app/src/main/java/jaakko/jaaska/apptycoon/engine/product/Product.java
// Path: app/src/main/java/jaakko/jaaska/apptycoon/engine/project/FeatureTask.java // public class FeatureTask implements ProjectTask { // // private ProductFeature mFeature; // private int mStartLevel; // private int mEndLevel; // // public FeatureTask(ProductFeature feature, int fromLevel, int toLevel) { // mFeature = feature; // mStartLevel = fromLevel; // mEndLevel = toLevel; // } // // @Override // public String getTaskTitle() { // return mFeature.getName() + " to level " + mEndLevel; // } // // @Override // public long getQuantity() { // return mEndLevel - mStartLevel; // } // // @Override // public String getTextualQuantity() { // return "+" + getQuantity(); // } // // @Override // public long getWorkAmount() { // return mFeature.getComplexityForUpgrade(mStartLevel, mEndLevel); // } // } // // Path: app/src/main/java/jaakko/jaaska/apptycoon/engine/project/NewProductTask.java // public class NewProductTask implements ProjectTask { // // /** The new product being developed. */ // private Product mProduct; // // public NewProductTask(Product product) { // mProduct = product; // } // // @Override // public String getTaskTitle() { // return "Product Development"; // } // // @Override // public long getQuantity() { // return 1; // } // // @Override // public String getTextualQuantity() { // return null; // } // // @Override // public long getWorkAmount() { // // Work amount for the "initial development" of the product. // // // // [base complexity of the product type] * 2 ^ [number of features] = [work amount] // long workAmount = mProduct.getType().getBaseComplexity(); // workAmount = (long) (workAmount * Math.pow(2, mProduct.getFeatures().size())); // // return workAmount; // } // } // // Path: app/src/main/java/jaakko/jaaska/apptycoon/engine/project/ProductDevelopmentProject.java // public class ProductDevelopmentProject extends Project { // // private Product mProduct; // private double mFractionalQuality; // private long mQualityGain; // // public ProductDevelopmentProject(String description, Product product) { // // Name of the new product dev. project is "New [product type]" // super("R&D - " + product.getType().getName(), description); // mProduct = product; // } // // @Override // protected long calculateWorkAmount() { // // long workAmount = 0; // // // Work amount is the sum of work amounts of all the tasks. // for (ProjectTask task : mTasks) { // workAmount += task.getWorkAmount(); // } // // return workAmount; // } // // @Override // public boolean isReady() { // return true; // } // // /** Delivering the project releases the new version of the product. */ // @Override // public void deliver() { // mProduct.releaseNextVersion(); // GameEngine.getInstance().getGameState().getCompany().onIncomeChanged(); // // Toast.makeText(AppTycoonApp.getContext(), // mProduct.getName() + " released", // Toast.LENGTH_LONG).show(); // } // // public void removeAllTasks() { // mTasks = new ArrayList<>(); // } // // @Override // public void progress(double workAmount, double qualityAmount, long time) { // super.progress(workAmount, qualityAmount, time); // // // Add quality gain. // mFractionalQuality += qualityAmount; // long qualityIntPart = (long) mFractionalQuality; // mFractionalQuality -= qualityIntPart; // mQualityGain += qualityIntPart; // // } // // public long getQualityGain() { // return mQualityGain; // } // }
import android.support.v4.util.Pair; import android.util.Log; import android.util.SparseArray; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Random; import jaakko.jaaska.apptycoon.engine.project.FeatureTask; import jaakko.jaaska.apptycoon.engine.project.NewProductTask; import jaakko.jaaska.apptycoon.engine.project.ProductDevelopmentProject;
// Variable 'income' is now null if this product did not have the feature. sum += (income == null ? 0.0f : income) * (double) mUsers; } return sum; } /** * Rebuilds the development project for a new product based on the type and * features of this product. * * Call this when the product or its features change during configuration of * a new product. * * If the project is not already created, this creates it. */ public void rebuildNewProductDevelopmentProject() { if (mDevProject == null) { Log.d(TAG, "rebuildNewProductDevelopmentProject() - new project created"); mDevProject = new ProductDevelopmentProject("no description", this); } Log.d(TAG, "rebuildNewProductDevelopmentProject() - start"); // Set the project description to include the product name. mDevProject.setDescription(getName()); mDevProject.removeAllTasks(); // Add the task for the initial product development.
// Path: app/src/main/java/jaakko/jaaska/apptycoon/engine/project/FeatureTask.java // public class FeatureTask implements ProjectTask { // // private ProductFeature mFeature; // private int mStartLevel; // private int mEndLevel; // // public FeatureTask(ProductFeature feature, int fromLevel, int toLevel) { // mFeature = feature; // mStartLevel = fromLevel; // mEndLevel = toLevel; // } // // @Override // public String getTaskTitle() { // return mFeature.getName() + " to level " + mEndLevel; // } // // @Override // public long getQuantity() { // return mEndLevel - mStartLevel; // } // // @Override // public String getTextualQuantity() { // return "+" + getQuantity(); // } // // @Override // public long getWorkAmount() { // return mFeature.getComplexityForUpgrade(mStartLevel, mEndLevel); // } // } // // Path: app/src/main/java/jaakko/jaaska/apptycoon/engine/project/NewProductTask.java // public class NewProductTask implements ProjectTask { // // /** The new product being developed. */ // private Product mProduct; // // public NewProductTask(Product product) { // mProduct = product; // } // // @Override // public String getTaskTitle() { // return "Product Development"; // } // // @Override // public long getQuantity() { // return 1; // } // // @Override // public String getTextualQuantity() { // return null; // } // // @Override // public long getWorkAmount() { // // Work amount for the "initial development" of the product. // // // // [base complexity of the product type] * 2 ^ [number of features] = [work amount] // long workAmount = mProduct.getType().getBaseComplexity(); // workAmount = (long) (workAmount * Math.pow(2, mProduct.getFeatures().size())); // // return workAmount; // } // } // // Path: app/src/main/java/jaakko/jaaska/apptycoon/engine/project/ProductDevelopmentProject.java // public class ProductDevelopmentProject extends Project { // // private Product mProduct; // private double mFractionalQuality; // private long mQualityGain; // // public ProductDevelopmentProject(String description, Product product) { // // Name of the new product dev. project is "New [product type]" // super("R&D - " + product.getType().getName(), description); // mProduct = product; // } // // @Override // protected long calculateWorkAmount() { // // long workAmount = 0; // // // Work amount is the sum of work amounts of all the tasks. // for (ProjectTask task : mTasks) { // workAmount += task.getWorkAmount(); // } // // return workAmount; // } // // @Override // public boolean isReady() { // return true; // } // // /** Delivering the project releases the new version of the product. */ // @Override // public void deliver() { // mProduct.releaseNextVersion(); // GameEngine.getInstance().getGameState().getCompany().onIncomeChanged(); // // Toast.makeText(AppTycoonApp.getContext(), // mProduct.getName() + " released", // Toast.LENGTH_LONG).show(); // } // // public void removeAllTasks() { // mTasks = new ArrayList<>(); // } // // @Override // public void progress(double workAmount, double qualityAmount, long time) { // super.progress(workAmount, qualityAmount, time); // // // Add quality gain. // mFractionalQuality += qualityAmount; // long qualityIntPart = (long) mFractionalQuality; // mFractionalQuality -= qualityIntPart; // mQualityGain += qualityIntPart; // // } // // public long getQualityGain() { // return mQualityGain; // } // } // Path: app/src/main/java/jaakko/jaaska/apptycoon/engine/product/Product.java import android.support.v4.util.Pair; import android.util.Log; import android.util.SparseArray; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Random; import jaakko.jaaska.apptycoon.engine.project.FeatureTask; import jaakko.jaaska.apptycoon.engine.project.NewProductTask; import jaakko.jaaska.apptycoon.engine.project.ProductDevelopmentProject; // Variable 'income' is now null if this product did not have the feature. sum += (income == null ? 0.0f : income) * (double) mUsers; } return sum; } /** * Rebuilds the development project for a new product based on the type and * features of this product. * * Call this when the product or its features change during configuration of * a new product. * * If the project is not already created, this creates it. */ public void rebuildNewProductDevelopmentProject() { if (mDevProject == null) { Log.d(TAG, "rebuildNewProductDevelopmentProject() - new project created"); mDevProject = new ProductDevelopmentProject("no description", this); } Log.d(TAG, "rebuildNewProductDevelopmentProject() - start"); // Set the project description to include the product name. mDevProject.setDescription(getName()); mDevProject.removeAllTasks(); // Add the task for the initial product development.
mDevProject.addTask(new NewProductTask(this));
zak0/AppTycoon
app/src/main/java/jaakko/jaaska/apptycoon/engine/product/Product.java
// Path: app/src/main/java/jaakko/jaaska/apptycoon/engine/project/FeatureTask.java // public class FeatureTask implements ProjectTask { // // private ProductFeature mFeature; // private int mStartLevel; // private int mEndLevel; // // public FeatureTask(ProductFeature feature, int fromLevel, int toLevel) { // mFeature = feature; // mStartLevel = fromLevel; // mEndLevel = toLevel; // } // // @Override // public String getTaskTitle() { // return mFeature.getName() + " to level " + mEndLevel; // } // // @Override // public long getQuantity() { // return mEndLevel - mStartLevel; // } // // @Override // public String getTextualQuantity() { // return "+" + getQuantity(); // } // // @Override // public long getWorkAmount() { // return mFeature.getComplexityForUpgrade(mStartLevel, mEndLevel); // } // } // // Path: app/src/main/java/jaakko/jaaska/apptycoon/engine/project/NewProductTask.java // public class NewProductTask implements ProjectTask { // // /** The new product being developed. */ // private Product mProduct; // // public NewProductTask(Product product) { // mProduct = product; // } // // @Override // public String getTaskTitle() { // return "Product Development"; // } // // @Override // public long getQuantity() { // return 1; // } // // @Override // public String getTextualQuantity() { // return null; // } // // @Override // public long getWorkAmount() { // // Work amount for the "initial development" of the product. // // // // [base complexity of the product type] * 2 ^ [number of features] = [work amount] // long workAmount = mProduct.getType().getBaseComplexity(); // workAmount = (long) (workAmount * Math.pow(2, mProduct.getFeatures().size())); // // return workAmount; // } // } // // Path: app/src/main/java/jaakko/jaaska/apptycoon/engine/project/ProductDevelopmentProject.java // public class ProductDevelopmentProject extends Project { // // private Product mProduct; // private double mFractionalQuality; // private long mQualityGain; // // public ProductDevelopmentProject(String description, Product product) { // // Name of the new product dev. project is "New [product type]" // super("R&D - " + product.getType().getName(), description); // mProduct = product; // } // // @Override // protected long calculateWorkAmount() { // // long workAmount = 0; // // // Work amount is the sum of work amounts of all the tasks. // for (ProjectTask task : mTasks) { // workAmount += task.getWorkAmount(); // } // // return workAmount; // } // // @Override // public boolean isReady() { // return true; // } // // /** Delivering the project releases the new version of the product. */ // @Override // public void deliver() { // mProduct.releaseNextVersion(); // GameEngine.getInstance().getGameState().getCompany().onIncomeChanged(); // // Toast.makeText(AppTycoonApp.getContext(), // mProduct.getName() + " released", // Toast.LENGTH_LONG).show(); // } // // public void removeAllTasks() { // mTasks = new ArrayList<>(); // } // // @Override // public void progress(double workAmount, double qualityAmount, long time) { // super.progress(workAmount, qualityAmount, time); // // // Add quality gain. // mFractionalQuality += qualityAmount; // long qualityIntPart = (long) mFractionalQuality; // mFractionalQuality -= qualityIntPart; // mQualityGain += qualityIntPart; // // } // // public long getQualityGain() { // return mQualityGain; // } // }
import android.support.v4.util.Pair; import android.util.Log; import android.util.SparseArray; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Random; import jaakko.jaaska.apptycoon.engine.project.FeatureTask; import jaakko.jaaska.apptycoon.engine.project.NewProductTask; import jaakko.jaaska.apptycoon.engine.project.ProductDevelopmentProject;
/** * Rebuilds the development project for a new product based on the type and * features of this product. * * Call this when the product or its features change during configuration of * a new product. * * If the project is not already created, this creates it. */ public void rebuildNewProductDevelopmentProject() { if (mDevProject == null) { Log.d(TAG, "rebuildNewProductDevelopmentProject() - new project created"); mDevProject = new ProductDevelopmentProject("no description", this); } Log.d(TAG, "rebuildNewProductDevelopmentProject() - start"); // Set the project description to include the product name. mDevProject.setDescription(getName()); mDevProject.removeAllTasks(); // Add the task for the initial product development. mDevProject.addTask(new NewProductTask(this)); // Add tasks for features. for (Pair<ProductFeature, Integer> pair : mFeatures) { ProductFeature feature = pair.first; int level = pair.second;
// Path: app/src/main/java/jaakko/jaaska/apptycoon/engine/project/FeatureTask.java // public class FeatureTask implements ProjectTask { // // private ProductFeature mFeature; // private int mStartLevel; // private int mEndLevel; // // public FeatureTask(ProductFeature feature, int fromLevel, int toLevel) { // mFeature = feature; // mStartLevel = fromLevel; // mEndLevel = toLevel; // } // // @Override // public String getTaskTitle() { // return mFeature.getName() + " to level " + mEndLevel; // } // // @Override // public long getQuantity() { // return mEndLevel - mStartLevel; // } // // @Override // public String getTextualQuantity() { // return "+" + getQuantity(); // } // // @Override // public long getWorkAmount() { // return mFeature.getComplexityForUpgrade(mStartLevel, mEndLevel); // } // } // // Path: app/src/main/java/jaakko/jaaska/apptycoon/engine/project/NewProductTask.java // public class NewProductTask implements ProjectTask { // // /** The new product being developed. */ // private Product mProduct; // // public NewProductTask(Product product) { // mProduct = product; // } // // @Override // public String getTaskTitle() { // return "Product Development"; // } // // @Override // public long getQuantity() { // return 1; // } // // @Override // public String getTextualQuantity() { // return null; // } // // @Override // public long getWorkAmount() { // // Work amount for the "initial development" of the product. // // // // [base complexity of the product type] * 2 ^ [number of features] = [work amount] // long workAmount = mProduct.getType().getBaseComplexity(); // workAmount = (long) (workAmount * Math.pow(2, mProduct.getFeatures().size())); // // return workAmount; // } // } // // Path: app/src/main/java/jaakko/jaaska/apptycoon/engine/project/ProductDevelopmentProject.java // public class ProductDevelopmentProject extends Project { // // private Product mProduct; // private double mFractionalQuality; // private long mQualityGain; // // public ProductDevelopmentProject(String description, Product product) { // // Name of the new product dev. project is "New [product type]" // super("R&D - " + product.getType().getName(), description); // mProduct = product; // } // // @Override // protected long calculateWorkAmount() { // // long workAmount = 0; // // // Work amount is the sum of work amounts of all the tasks. // for (ProjectTask task : mTasks) { // workAmount += task.getWorkAmount(); // } // // return workAmount; // } // // @Override // public boolean isReady() { // return true; // } // // /** Delivering the project releases the new version of the product. */ // @Override // public void deliver() { // mProduct.releaseNextVersion(); // GameEngine.getInstance().getGameState().getCompany().onIncomeChanged(); // // Toast.makeText(AppTycoonApp.getContext(), // mProduct.getName() + " released", // Toast.LENGTH_LONG).show(); // } // // public void removeAllTasks() { // mTasks = new ArrayList<>(); // } // // @Override // public void progress(double workAmount, double qualityAmount, long time) { // super.progress(workAmount, qualityAmount, time); // // // Add quality gain. // mFractionalQuality += qualityAmount; // long qualityIntPart = (long) mFractionalQuality; // mFractionalQuality -= qualityIntPart; // mQualityGain += qualityIntPart; // // } // // public long getQualityGain() { // return mQualityGain; // } // } // Path: app/src/main/java/jaakko/jaaska/apptycoon/engine/product/Product.java import android.support.v4.util.Pair; import android.util.Log; import android.util.SparseArray; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Random; import jaakko.jaaska.apptycoon.engine.project.FeatureTask; import jaakko.jaaska.apptycoon.engine.project.NewProductTask; import jaakko.jaaska.apptycoon.engine.project.ProductDevelopmentProject; /** * Rebuilds the development project for a new product based on the type and * features of this product. * * Call this when the product or its features change during configuration of * a new product. * * If the project is not already created, this creates it. */ public void rebuildNewProductDevelopmentProject() { if (mDevProject == null) { Log.d(TAG, "rebuildNewProductDevelopmentProject() - new project created"); mDevProject = new ProductDevelopmentProject("no description", this); } Log.d(TAG, "rebuildNewProductDevelopmentProject() - start"); // Set the project description to include the product name. mDevProject.setDescription(getName()); mDevProject.removeAllTasks(); // Add the task for the initial product development. mDevProject.addTask(new NewProductTask(this)); // Add tasks for features. for (Pair<ProductFeature, Integer> pair : mFeatures) { ProductFeature feature = pair.first; int level = pair.second;
FeatureTask featureTask = new FeatureTask(feature, 0, level);
zak0/AppTycoon
app/src/test/java/jaakko/jaaska/apptycoon/UtilityTests.java
// Path: app/src/main/java/jaakko/jaaska/apptycoon/utils/Utils.java // public class Utils { // // private static final String TAG = "Utils"; // // /** // * Selects and returns a random entry from a list. // * @param list List to select an entry from. // * @return // */ // public static Object getRandomFromList(List list) { // Random r = new Random(); // return list.get(r.nextInt(list.size())); // } // // // public static String millisecondsToTimeString(long milliseconds) { // // TODO: Custom formatting // double minutes = Math.floor(milliseconds / 60000); // // double seconds = (double) (milliseconds - minutes * 60000) / 1000; // seconds = Math.floor(seconds); // // String ret = String.format("%.0fm %.0fs", minutes, seconds); // // return ret; // } // // /** // * Takes a large number and prints with a 'power of 1000' suffix added. For example, // * 12489 becomes 12.49k (with 2 decimals). Numbers less smaller than 1000 will be shown with // * the specified number of decimals, without a character suffix. // * // * @param numberToConvert The large number to convert. // * @param decimals Number of decimals to show. // * @return A nicely formatted string presentation of the large number. // */ // public static String largeNumberToNiceString(double numberToConvert, int decimals) { // // If the number is large enough for the smallest 'power of 1000', then just // // use the implementation for numbers of type long. // if (numberToConvert >= 1000.00d) { // return largeNumberToNiceString((long) numberToConvert, decimals); // } // // // Otherwise return the number with desired number of decimals as a string. // return String.format("%." + decimals + "f", numberToConvert); // } // // /** // * Takes a large number and prints with a 'power of 1000' suffix added. For example, // * 12489 becomes 12.49k (with 2 decimals). // * // * @param numberToConvert The large number to print. // * @param decimals Number of decimals to show. // * @return A nicely formatted string presentation of the large number. // */ // public static String largeNumberToNiceString(long numberToConvert, int decimals) { // String[] suffixes = {"k", "M", "G", "T", "P"}; // String suffix = ""; // double number = 0.0; // // // get a possible "power of 1000" prefix for the number // for (int i = suffixes.length - 1; i >= 0; i--) { // if (numberToConvert / Math.pow(1000, i + 1) > 1) { // number = numberToConvert / Math.pow(1000, i + 1); // suffix = suffixes[i]; // break; // } // } // // //Log.d(TAG, "largeNumberToNiceString() - numberToConvert = " + numberToConvert); // //Log.d(TAG, "largeNumberToNiceString() - number = " + number); // // // If no "power of 1000" was not found, just use the numberToConvert directly. // // This happens if the number is less than 1000. // if (number <= 0.0f) { // return Long.toString(numberToConvert); // } // // double residue = number - Math.floor(number); // residue = residue * Math.pow(10, decimals); // residue = Math.round(residue) / Math.pow(10, decimals); // number = Math.floor(number) + residue; // // return String.format("%." + decimals + "f", number) + suffix; // } // // // private static List<String> sFirstNames; // private static List<String> sLastNames; // // /** // * Generates a random name from seeds in /res/raw/firstnames.txt and lastnames.txt // * @return A random name. // */ // public static String getRandomName() { // Context context = AppTycoonApp.getContext(); // // // Load the seeds if not already loaded. // if (sFirstNames == null || sLastNames == null) { // sFirstNames = new ArrayList<>(); // sLastNames = new ArrayList<>(); // // // First names // InputStream in = context.getResources().openRawResource(R.raw.firstnames); // BufferedReader br = new BufferedReader(new InputStreamReader(in)); // String line = null; // try { // line = br.readLine(); // while (line != null) { // if (line.length() > 1) { // sFirstNames.add(line); // } // line = br.readLine(); // } // } catch (IOException e) { // e.printStackTrace(); // } // // // Last names // in = context.getResources().openRawResource(R.raw.lastnames); // br = new BufferedReader(new InputStreamReader(in)); // line = null; // try { // line = br.readLine(); // while (line != null) { // if (line.length() > 1) { // sLastNames.add(line); // } // line = br.readLine(); // } // } catch (IOException e) { // e.printStackTrace(); // } // // } // // String ret = getRandomFromList(sFirstNames) + " " + getRandomFromList(sLastNames); // Log.d(TAG, "new random name: " + ret); // return ret; // } // // public static String getRandomCustomer() { // // // return "Random Customer Inc."; // } // // // }
import static org.junit.Assert.*; import org.junit.Test; import jaakko.jaaska.apptycoon.utils.Utils;
package jaakko.jaaska.apptycoon; /** * Test cases for simple utilities implemented in {@see jaakko.jaaska.apptycoon.utils.Utils}. */ public class UtilityTests { @Test public void numberToNiceStringConverterWorks() { // Tests with longs
// Path: app/src/main/java/jaakko/jaaska/apptycoon/utils/Utils.java // public class Utils { // // private static final String TAG = "Utils"; // // /** // * Selects and returns a random entry from a list. // * @param list List to select an entry from. // * @return // */ // public static Object getRandomFromList(List list) { // Random r = new Random(); // return list.get(r.nextInt(list.size())); // } // // // public static String millisecondsToTimeString(long milliseconds) { // // TODO: Custom formatting // double minutes = Math.floor(milliseconds / 60000); // // double seconds = (double) (milliseconds - minutes * 60000) / 1000; // seconds = Math.floor(seconds); // // String ret = String.format("%.0fm %.0fs", minutes, seconds); // // return ret; // } // // /** // * Takes a large number and prints with a 'power of 1000' suffix added. For example, // * 12489 becomes 12.49k (with 2 decimals). Numbers less smaller than 1000 will be shown with // * the specified number of decimals, without a character suffix. // * // * @param numberToConvert The large number to convert. // * @param decimals Number of decimals to show. // * @return A nicely formatted string presentation of the large number. // */ // public static String largeNumberToNiceString(double numberToConvert, int decimals) { // // If the number is large enough for the smallest 'power of 1000', then just // // use the implementation for numbers of type long. // if (numberToConvert >= 1000.00d) { // return largeNumberToNiceString((long) numberToConvert, decimals); // } // // // Otherwise return the number with desired number of decimals as a string. // return String.format("%." + decimals + "f", numberToConvert); // } // // /** // * Takes a large number and prints with a 'power of 1000' suffix added. For example, // * 12489 becomes 12.49k (with 2 decimals). // * // * @param numberToConvert The large number to print. // * @param decimals Number of decimals to show. // * @return A nicely formatted string presentation of the large number. // */ // public static String largeNumberToNiceString(long numberToConvert, int decimals) { // String[] suffixes = {"k", "M", "G", "T", "P"}; // String suffix = ""; // double number = 0.0; // // // get a possible "power of 1000" prefix for the number // for (int i = suffixes.length - 1; i >= 0; i--) { // if (numberToConvert / Math.pow(1000, i + 1) > 1) { // number = numberToConvert / Math.pow(1000, i + 1); // suffix = suffixes[i]; // break; // } // } // // //Log.d(TAG, "largeNumberToNiceString() - numberToConvert = " + numberToConvert); // //Log.d(TAG, "largeNumberToNiceString() - number = " + number); // // // If no "power of 1000" was not found, just use the numberToConvert directly. // // This happens if the number is less than 1000. // if (number <= 0.0f) { // return Long.toString(numberToConvert); // } // // double residue = number - Math.floor(number); // residue = residue * Math.pow(10, decimals); // residue = Math.round(residue) / Math.pow(10, decimals); // number = Math.floor(number) + residue; // // return String.format("%." + decimals + "f", number) + suffix; // } // // // private static List<String> sFirstNames; // private static List<String> sLastNames; // // /** // * Generates a random name from seeds in /res/raw/firstnames.txt and lastnames.txt // * @return A random name. // */ // public static String getRandomName() { // Context context = AppTycoonApp.getContext(); // // // Load the seeds if not already loaded. // if (sFirstNames == null || sLastNames == null) { // sFirstNames = new ArrayList<>(); // sLastNames = new ArrayList<>(); // // // First names // InputStream in = context.getResources().openRawResource(R.raw.firstnames); // BufferedReader br = new BufferedReader(new InputStreamReader(in)); // String line = null; // try { // line = br.readLine(); // while (line != null) { // if (line.length() > 1) { // sFirstNames.add(line); // } // line = br.readLine(); // } // } catch (IOException e) { // e.printStackTrace(); // } // // // Last names // in = context.getResources().openRawResource(R.raw.lastnames); // br = new BufferedReader(new InputStreamReader(in)); // line = null; // try { // line = br.readLine(); // while (line != null) { // if (line.length() > 1) { // sLastNames.add(line); // } // line = br.readLine(); // } // } catch (IOException e) { // e.printStackTrace(); // } // // } // // String ret = getRandomFromList(sFirstNames) + " " + getRandomFromList(sLastNames); // Log.d(TAG, "new random name: " + ret); // return ret; // } // // public static String getRandomCustomer() { // // // return "Random Customer Inc."; // } // // // } // Path: app/src/test/java/jaakko/jaaska/apptycoon/UtilityTests.java import static org.junit.Assert.*; import org.junit.Test; import jaakko.jaaska.apptycoon.utils.Utils; package jaakko.jaaska.apptycoon; /** * Test cases for simple utilities implemented in {@see jaakko.jaaska.apptycoon.utils.Utils}. */ public class UtilityTests { @Test public void numberToNiceStringConverterWorks() { // Tests with longs
assertEquals("123.457M", Utils.largeNumberToNiceString(123456789, 3));
zak0/AppTycoon
app/src/main/java/jaakko/jaaska/apptycoon/engine/people/JobApplication.java
// Path: app/src/main/java/jaakko/jaaska/apptycoon/utils/Utils.java // public class Utils { // // private static final String TAG = "Utils"; // // /** // * Selects and returns a random entry from a list. // * @param list List to select an entry from. // * @return // */ // public static Object getRandomFromList(List list) { // Random r = new Random(); // return list.get(r.nextInt(list.size())); // } // // // public static String millisecondsToTimeString(long milliseconds) { // // TODO: Custom formatting // double minutes = Math.floor(milliseconds / 60000); // // double seconds = (double) (milliseconds - minutes * 60000) / 1000; // seconds = Math.floor(seconds); // // String ret = String.format("%.0fm %.0fs", minutes, seconds); // // return ret; // } // // /** // * Takes a large number and prints with a 'power of 1000' suffix added. For example, // * 12489 becomes 12.49k (with 2 decimals). Numbers less smaller than 1000 will be shown with // * the specified number of decimals, without a character suffix. // * // * @param numberToConvert The large number to convert. // * @param decimals Number of decimals to show. // * @return A nicely formatted string presentation of the large number. // */ // public static String largeNumberToNiceString(double numberToConvert, int decimals) { // // If the number is large enough for the smallest 'power of 1000', then just // // use the implementation for numbers of type long. // if (numberToConvert >= 1000.00d) { // return largeNumberToNiceString((long) numberToConvert, decimals); // } // // // Otherwise return the number with desired number of decimals as a string. // return String.format("%." + decimals + "f", numberToConvert); // } // // /** // * Takes a large number and prints with a 'power of 1000' suffix added. For example, // * 12489 becomes 12.49k (with 2 decimals). // * // * @param numberToConvert The large number to print. // * @param decimals Number of decimals to show. // * @return A nicely formatted string presentation of the large number. // */ // public static String largeNumberToNiceString(long numberToConvert, int decimals) { // String[] suffixes = {"k", "M", "G", "T", "P"}; // String suffix = ""; // double number = 0.0; // // // get a possible "power of 1000" prefix for the number // for (int i = suffixes.length - 1; i >= 0; i--) { // if (numberToConvert / Math.pow(1000, i + 1) > 1) { // number = numberToConvert / Math.pow(1000, i + 1); // suffix = suffixes[i]; // break; // } // } // // //Log.d(TAG, "largeNumberToNiceString() - numberToConvert = " + numberToConvert); // //Log.d(TAG, "largeNumberToNiceString() - number = " + number); // // // If no "power of 1000" was not found, just use the numberToConvert directly. // // This happens if the number is less than 1000. // if (number <= 0.0f) { // return Long.toString(numberToConvert); // } // // double residue = number - Math.floor(number); // residue = residue * Math.pow(10, decimals); // residue = Math.round(residue) / Math.pow(10, decimals); // number = Math.floor(number) + residue; // // return String.format("%." + decimals + "f", number) + suffix; // } // // // private static List<String> sFirstNames; // private static List<String> sLastNames; // // /** // * Generates a random name from seeds in /res/raw/firstnames.txt and lastnames.txt // * @return A random name. // */ // public static String getRandomName() { // Context context = AppTycoonApp.getContext(); // // // Load the seeds if not already loaded. // if (sFirstNames == null || sLastNames == null) { // sFirstNames = new ArrayList<>(); // sLastNames = new ArrayList<>(); // // // First names // InputStream in = context.getResources().openRawResource(R.raw.firstnames); // BufferedReader br = new BufferedReader(new InputStreamReader(in)); // String line = null; // try { // line = br.readLine(); // while (line != null) { // if (line.length() > 1) { // sFirstNames.add(line); // } // line = br.readLine(); // } // } catch (IOException e) { // e.printStackTrace(); // } // // // Last names // in = context.getResources().openRawResource(R.raw.lastnames); // br = new BufferedReader(new InputStreamReader(in)); // line = null; // try { // line = br.readLine(); // while (line != null) { // if (line.length() > 1) { // sLastNames.add(line); // } // line = br.readLine(); // } // } catch (IOException e) { // e.printStackTrace(); // } // // } // // String ret = getRandomFromList(sFirstNames) + " " + getRandomFromList(sLastNames); // Log.d(TAG, "new random name: " + ret); // return ret; // } // // public static String getRandomCustomer() { // // // return "Random Customer Inc."; // } // // // }
import jaakko.jaaska.apptycoon.utils.Utils;
package jaakko.jaaska.apptycoon.engine.people; /** * Created by jaakko on 17.4.2017. */ public class JobApplication { private String mName; // The person who is applying. private EmployeeType mJob; // The type of the job that is being applied. private long mExpiresIn; // How long until the application expires (and disappears from the system). /** * Instances are accessed through static getters. */ private JobApplication() { } /** * Generates a random open application. * @return */ public static JobApplication getRandomOpenApplication() { JobApplication ret = new JobApplication();
// Path: app/src/main/java/jaakko/jaaska/apptycoon/utils/Utils.java // public class Utils { // // private static final String TAG = "Utils"; // // /** // * Selects and returns a random entry from a list. // * @param list List to select an entry from. // * @return // */ // public static Object getRandomFromList(List list) { // Random r = new Random(); // return list.get(r.nextInt(list.size())); // } // // // public static String millisecondsToTimeString(long milliseconds) { // // TODO: Custom formatting // double minutes = Math.floor(milliseconds / 60000); // // double seconds = (double) (milliseconds - minutes * 60000) / 1000; // seconds = Math.floor(seconds); // // String ret = String.format("%.0fm %.0fs", minutes, seconds); // // return ret; // } // // /** // * Takes a large number and prints with a 'power of 1000' suffix added. For example, // * 12489 becomes 12.49k (with 2 decimals). Numbers less smaller than 1000 will be shown with // * the specified number of decimals, without a character suffix. // * // * @param numberToConvert The large number to convert. // * @param decimals Number of decimals to show. // * @return A nicely formatted string presentation of the large number. // */ // public static String largeNumberToNiceString(double numberToConvert, int decimals) { // // If the number is large enough for the smallest 'power of 1000', then just // // use the implementation for numbers of type long. // if (numberToConvert >= 1000.00d) { // return largeNumberToNiceString((long) numberToConvert, decimals); // } // // // Otherwise return the number with desired number of decimals as a string. // return String.format("%." + decimals + "f", numberToConvert); // } // // /** // * Takes a large number and prints with a 'power of 1000' suffix added. For example, // * 12489 becomes 12.49k (with 2 decimals). // * // * @param numberToConvert The large number to print. // * @param decimals Number of decimals to show. // * @return A nicely formatted string presentation of the large number. // */ // public static String largeNumberToNiceString(long numberToConvert, int decimals) { // String[] suffixes = {"k", "M", "G", "T", "P"}; // String suffix = ""; // double number = 0.0; // // // get a possible "power of 1000" prefix for the number // for (int i = suffixes.length - 1; i >= 0; i--) { // if (numberToConvert / Math.pow(1000, i + 1) > 1) { // number = numberToConvert / Math.pow(1000, i + 1); // suffix = suffixes[i]; // break; // } // } // // //Log.d(TAG, "largeNumberToNiceString() - numberToConvert = " + numberToConvert); // //Log.d(TAG, "largeNumberToNiceString() - number = " + number); // // // If no "power of 1000" was not found, just use the numberToConvert directly. // // This happens if the number is less than 1000. // if (number <= 0.0f) { // return Long.toString(numberToConvert); // } // // double residue = number - Math.floor(number); // residue = residue * Math.pow(10, decimals); // residue = Math.round(residue) / Math.pow(10, decimals); // number = Math.floor(number) + residue; // // return String.format("%." + decimals + "f", number) + suffix; // } // // // private static List<String> sFirstNames; // private static List<String> sLastNames; // // /** // * Generates a random name from seeds in /res/raw/firstnames.txt and lastnames.txt // * @return A random name. // */ // public static String getRandomName() { // Context context = AppTycoonApp.getContext(); // // // Load the seeds if not already loaded. // if (sFirstNames == null || sLastNames == null) { // sFirstNames = new ArrayList<>(); // sLastNames = new ArrayList<>(); // // // First names // InputStream in = context.getResources().openRawResource(R.raw.firstnames); // BufferedReader br = new BufferedReader(new InputStreamReader(in)); // String line = null; // try { // line = br.readLine(); // while (line != null) { // if (line.length() > 1) { // sFirstNames.add(line); // } // line = br.readLine(); // } // } catch (IOException e) { // e.printStackTrace(); // } // // // Last names // in = context.getResources().openRawResource(R.raw.lastnames); // br = new BufferedReader(new InputStreamReader(in)); // line = null; // try { // line = br.readLine(); // while (line != null) { // if (line.length() > 1) { // sLastNames.add(line); // } // line = br.readLine(); // } // } catch (IOException e) { // e.printStackTrace(); // } // // } // // String ret = getRandomFromList(sFirstNames) + " " + getRandomFromList(sLastNames); // Log.d(TAG, "new random name: " + ret); // return ret; // } // // public static String getRandomCustomer() { // // // return "Random Customer Inc."; // } // // // } // Path: app/src/main/java/jaakko/jaaska/apptycoon/engine/people/JobApplication.java import jaakko.jaaska.apptycoon.utils.Utils; package jaakko.jaaska.apptycoon.engine.people; /** * Created by jaakko on 17.4.2017. */ public class JobApplication { private String mName; // The person who is applying. private EmployeeType mJob; // The type of the job that is being applied. private long mExpiresIn; // How long until the application expires (and disappears from the system). /** * Instances are accessed through static getters. */ private JobApplication() { } /** * Generates a random open application. * @return */ public static JobApplication getRandomOpenApplication() { JobApplication ret = new JobApplication();
ret.mName = Utils.getRandomName();
zak0/AppTycoon
app/src/main/java/jaakko/jaaska/apptycoon/storage/StorageManager.java
// Path: app/src/main/java/jaakko/jaaska/apptycoon/AppTycoonApp.java // public class AppTycoonApp extends Application { // // private static AppTycoonApp sInstance; // // public static Context getContext() { // return sInstance; // } // // @Override // public void onCreate() { // sInstance = this; // super.onCreate(); // } // } // // Path: app/src/main/java/jaakko/jaaska/apptycoon/engine/core/GameState.java // public class GameState { // // private int mTimeFactor; // private Company mCompany; // // public GameState() { // mTimeFactor = 1; // } // // public void setTimeFactor(int timeFactor) { // this.mTimeFactor = timeFactor; // } // // public int getTimeFactor() { // return mTimeFactor; // } // // public Company getCompany() { // return mCompany; // } // // public void setCompany(Company company) { // mCompany = company; // } // }
import android.util.Log; import jaakko.jaaska.apptycoon.AppTycoonApp; import jaakko.jaaska.apptycoon.engine.core.GameState;
package jaakko.jaaska.apptycoon.storage; /** * Class for accessing local (and cloud) storage of game data. * * All storage actions outside from .storage package should go through this class. */ public class StorageManager { private static final String TAG = "StorageManager"; private static StorageManager mInstance; private LocalDatabaseHelper mDbHelper; private StorageManager() {
// Path: app/src/main/java/jaakko/jaaska/apptycoon/AppTycoonApp.java // public class AppTycoonApp extends Application { // // private static AppTycoonApp sInstance; // // public static Context getContext() { // return sInstance; // } // // @Override // public void onCreate() { // sInstance = this; // super.onCreate(); // } // } // // Path: app/src/main/java/jaakko/jaaska/apptycoon/engine/core/GameState.java // public class GameState { // // private int mTimeFactor; // private Company mCompany; // // public GameState() { // mTimeFactor = 1; // } // // public void setTimeFactor(int timeFactor) { // this.mTimeFactor = timeFactor; // } // // public int getTimeFactor() { // return mTimeFactor; // } // // public Company getCompany() { // return mCompany; // } // // public void setCompany(Company company) { // mCompany = company; // } // } // Path: app/src/main/java/jaakko/jaaska/apptycoon/storage/StorageManager.java import android.util.Log; import jaakko.jaaska.apptycoon.AppTycoonApp; import jaakko.jaaska.apptycoon.engine.core.GameState; package jaakko.jaaska.apptycoon.storage; /** * Class for accessing local (and cloud) storage of game data. * * All storage actions outside from .storage package should go through this class. */ public class StorageManager { private static final String TAG = "StorageManager"; private static StorageManager mInstance; private LocalDatabaseHelper mDbHelper; private StorageManager() {
mDbHelper = new LocalDatabaseHelper(AppTycoonApp.getContext());
zak0/AppTycoon
app/src/main/java/jaakko/jaaska/apptycoon/storage/StorageManager.java
// Path: app/src/main/java/jaakko/jaaska/apptycoon/AppTycoonApp.java // public class AppTycoonApp extends Application { // // private static AppTycoonApp sInstance; // // public static Context getContext() { // return sInstance; // } // // @Override // public void onCreate() { // sInstance = this; // super.onCreate(); // } // } // // Path: app/src/main/java/jaakko/jaaska/apptycoon/engine/core/GameState.java // public class GameState { // // private int mTimeFactor; // private Company mCompany; // // public GameState() { // mTimeFactor = 1; // } // // public void setTimeFactor(int timeFactor) { // this.mTimeFactor = timeFactor; // } // // public int getTimeFactor() { // return mTimeFactor; // } // // public Company getCompany() { // return mCompany; // } // // public void setCompany(Company company) { // mCompany = company; // } // }
import android.util.Log; import jaakko.jaaska.apptycoon.AppTycoonApp; import jaakko.jaaska.apptycoon.engine.core.GameState;
package jaakko.jaaska.apptycoon.storage; /** * Class for accessing local (and cloud) storage of game data. * * All storage actions outside from .storage package should go through this class. */ public class StorageManager { private static final String TAG = "StorageManager"; private static StorageManager mInstance; private LocalDatabaseHelper mDbHelper; private StorageManager() { mDbHelper = new LocalDatabaseHelper(AppTycoonApp.getContext()); } public static StorageManager getInstance() { if (mInstance == null) { Log.d(TAG, "getInstance() - new instance created"); mInstance = new StorageManager(); } return mInstance; } /** * Checks if a saved game exists in local storage. * * @return True if there is an existing game progress in local storage. */ public boolean localSaveGameExists() { mDbHelper.openReadable(); boolean ret = mDbHelper.storedGameStateExists(); mDbHelper.close(); Log.d(TAG, "localSaveGameExists() - " + ret); return ret; } /** * Load the GameState from local database. * * @return GameState object with loaded data. */
// Path: app/src/main/java/jaakko/jaaska/apptycoon/AppTycoonApp.java // public class AppTycoonApp extends Application { // // private static AppTycoonApp sInstance; // // public static Context getContext() { // return sInstance; // } // // @Override // public void onCreate() { // sInstance = this; // super.onCreate(); // } // } // // Path: app/src/main/java/jaakko/jaaska/apptycoon/engine/core/GameState.java // public class GameState { // // private int mTimeFactor; // private Company mCompany; // // public GameState() { // mTimeFactor = 1; // } // // public void setTimeFactor(int timeFactor) { // this.mTimeFactor = timeFactor; // } // // public int getTimeFactor() { // return mTimeFactor; // } // // public Company getCompany() { // return mCompany; // } // // public void setCompany(Company company) { // mCompany = company; // } // } // Path: app/src/main/java/jaakko/jaaska/apptycoon/storage/StorageManager.java import android.util.Log; import jaakko.jaaska.apptycoon.AppTycoonApp; import jaakko.jaaska.apptycoon.engine.core.GameState; package jaakko.jaaska.apptycoon.storage; /** * Class for accessing local (and cloud) storage of game data. * * All storage actions outside from .storage package should go through this class. */ public class StorageManager { private static final String TAG = "StorageManager"; private static StorageManager mInstance; private LocalDatabaseHelper mDbHelper; private StorageManager() { mDbHelper = new LocalDatabaseHelper(AppTycoonApp.getContext()); } public static StorageManager getInstance() { if (mInstance == null) { Log.d(TAG, "getInstance() - new instance created"); mInstance = new StorageManager(); } return mInstance; } /** * Checks if a saved game exists in local storage. * * @return True if there is an existing game progress in local storage. */ public boolean localSaveGameExists() { mDbHelper.openReadable(); boolean ret = mDbHelper.storedGameStateExists(); mDbHelper.close(); Log.d(TAG, "localSaveGameExists() - " + ret); return ret; } /** * Load the GameState from local database. * * @return GameState object with loaded data. */
public GameState loadFromDb() {
zak0/AppTycoon
app/src/main/java/jaakko/jaaska/apptycoon/ui/fragment/AppTycoonFragment.java
// Path: app/src/main/java/jaakko/jaaska/apptycoon/ui/listener/FragmentBackButtonOnClickListener.java // public class FragmentBackButtonOnClickListener implements View.OnClickListener { // private static final String TAG = "FBBOCL"; // // private Bundle mArgs; // private int mPreviousFragment; // // /** // * Use this to simply navigate one step back on the navigation stack. // */ // public FragmentBackButtonOnClickListener() { // // } // // /** // * Use this to navigate back AND pass a custom set of arguments with the transition to // * the target fragment. // * // * @param previousFragment ID of the fragment to navigate to // * @param args Custom set of arguments to pass with the transition // */ // public FragmentBackButtonOnClickListener(int previousFragment, Bundle args) { // mPreviousFragment = previousFragment; // mArgs = args; // } // // @Override // public void onClick(View v) { // boolean customArgs = mArgs != null; // // Log.d(TAG, "onClick() - custom args set: " + customArgs); // // // If custom args are set, treat the transition as a 'regular' fragment transition. // Message msg = customArgs ? UiUpdateHandler.obtainReplaceFragmentMessage(mPreviousFragment) : // UiUpdateHandler.obtainGoBackMessage(); // // if (customArgs) { // // Raise the flag telling that this 'regular' transition is actually a back transition. // mArgs.putBoolean(UiUpdateHandler.ARG_IS_BACK_TRANSITION, true); // mArgs.putAll(msg.getData()); // Add all the original args as well, as e.g. the target // // fragment ID is set there. // msg.setData(mArgs); // } // // msg.sendToTarget(); // } // } // // Path: app/src/main/java/jaakko/jaaska/apptycoon/ui/listener/TextViewChangeColourOnTouchListener.java // public class TextViewChangeColourOnTouchListener implements View.OnTouchListener { // // private int mOnTouchColor; // private int mOriginalColor; // // /** // * Constructor. // * // * Parameter colors are {@link android.graphics.Color Color} colors. // * // * @param onTouchColor Color of the text when touched. // * @param originalColor Original color of the text. // */ // public TextViewChangeColourOnTouchListener(int onTouchColor, int originalColor) { // mOnTouchColor = onTouchColor; // mOriginalColor = originalColor; // } // // @Override // public boolean onTouch(View v, MotionEvent event) { // // The view is ALWAYS a TextViews. // TextView tv = (TextView) v; // // switch (event.getAction()) { // case MotionEvent.ACTION_DOWN: // tv.setTextColor(mOnTouchColor); // break; // default: // tv.setTextColor(mOriginalColor); // } // return false; // } // }
import android.graphics.Color; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import jaakko.jaaska.apptycoon.R; import jaakko.jaaska.apptycoon.ui.listener.FragmentBackButtonOnClickListener; import jaakko.jaaska.apptycoon.ui.listener.TextViewChangeColourOnTouchListener;
/** * Set the fragment to which the back button navigates back to. And optional arguments. Use * this when you need to pass arguments for the previous fragment, and the plain showBackButton() * otherwise. * * @param fragmentId ID of the fragment to navigate back to. * @param args Arguments to pass to the previous fragment. */ protected void showCustomBackButton(int fragmentId, @Nullable Bundle args) { Log.d(TAG, "setBackTargetFragment() - fragmentId = " + fragmentId); mBackFragment = fragmentId; mBackArgs = args; bindBackButton(); } /** * Set an action for the action button on the fragment title bar. * @param label Label to be shown on the action button. * @param action Action to perform when the button is clicked. */ protected void setAction(String label, Action action) { Log.d(TAG, "setAction() - label = '" + label + "'"); mActionLabel = label; mAction = action; bindActionButton(); } private void bindBackButton() { Log.d(TAG, "bindBackButton()"); mTextViewBack.setVisibility(View.VISIBLE);
// Path: app/src/main/java/jaakko/jaaska/apptycoon/ui/listener/FragmentBackButtonOnClickListener.java // public class FragmentBackButtonOnClickListener implements View.OnClickListener { // private static final String TAG = "FBBOCL"; // // private Bundle mArgs; // private int mPreviousFragment; // // /** // * Use this to simply navigate one step back on the navigation stack. // */ // public FragmentBackButtonOnClickListener() { // // } // // /** // * Use this to navigate back AND pass a custom set of arguments with the transition to // * the target fragment. // * // * @param previousFragment ID of the fragment to navigate to // * @param args Custom set of arguments to pass with the transition // */ // public FragmentBackButtonOnClickListener(int previousFragment, Bundle args) { // mPreviousFragment = previousFragment; // mArgs = args; // } // // @Override // public void onClick(View v) { // boolean customArgs = mArgs != null; // // Log.d(TAG, "onClick() - custom args set: " + customArgs); // // // If custom args are set, treat the transition as a 'regular' fragment transition. // Message msg = customArgs ? UiUpdateHandler.obtainReplaceFragmentMessage(mPreviousFragment) : // UiUpdateHandler.obtainGoBackMessage(); // // if (customArgs) { // // Raise the flag telling that this 'regular' transition is actually a back transition. // mArgs.putBoolean(UiUpdateHandler.ARG_IS_BACK_TRANSITION, true); // mArgs.putAll(msg.getData()); // Add all the original args as well, as e.g. the target // // fragment ID is set there. // msg.setData(mArgs); // } // // msg.sendToTarget(); // } // } // // Path: app/src/main/java/jaakko/jaaska/apptycoon/ui/listener/TextViewChangeColourOnTouchListener.java // public class TextViewChangeColourOnTouchListener implements View.OnTouchListener { // // private int mOnTouchColor; // private int mOriginalColor; // // /** // * Constructor. // * // * Parameter colors are {@link android.graphics.Color Color} colors. // * // * @param onTouchColor Color of the text when touched. // * @param originalColor Original color of the text. // */ // public TextViewChangeColourOnTouchListener(int onTouchColor, int originalColor) { // mOnTouchColor = onTouchColor; // mOriginalColor = originalColor; // } // // @Override // public boolean onTouch(View v, MotionEvent event) { // // The view is ALWAYS a TextViews. // TextView tv = (TextView) v; // // switch (event.getAction()) { // case MotionEvent.ACTION_DOWN: // tv.setTextColor(mOnTouchColor); // break; // default: // tv.setTextColor(mOriginalColor); // } // return false; // } // } // Path: app/src/main/java/jaakko/jaaska/apptycoon/ui/fragment/AppTycoonFragment.java import android.graphics.Color; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import jaakko.jaaska.apptycoon.R; import jaakko.jaaska.apptycoon.ui.listener.FragmentBackButtonOnClickListener; import jaakko.jaaska.apptycoon.ui.listener.TextViewChangeColourOnTouchListener; /** * Set the fragment to which the back button navigates back to. And optional arguments. Use * this when you need to pass arguments for the previous fragment, and the plain showBackButton() * otherwise. * * @param fragmentId ID of the fragment to navigate back to. * @param args Arguments to pass to the previous fragment. */ protected void showCustomBackButton(int fragmentId, @Nullable Bundle args) { Log.d(TAG, "setBackTargetFragment() - fragmentId = " + fragmentId); mBackFragment = fragmentId; mBackArgs = args; bindBackButton(); } /** * Set an action for the action button on the fragment title bar. * @param label Label to be shown on the action button. * @param action Action to perform when the button is clicked. */ protected void setAction(String label, Action action) { Log.d(TAG, "setAction() - label = '" + label + "'"); mActionLabel = label; mAction = action; bindActionButton(); } private void bindBackButton() { Log.d(TAG, "bindBackButton()"); mTextViewBack.setVisibility(View.VISIBLE);
mTextViewBack.setOnTouchListener(new TextViewChangeColourOnTouchListener(Color.BLACK,
zak0/AppTycoon
app/src/main/java/jaakko/jaaska/apptycoon/ui/fragment/AppTycoonFragment.java
// Path: app/src/main/java/jaakko/jaaska/apptycoon/ui/listener/FragmentBackButtonOnClickListener.java // public class FragmentBackButtonOnClickListener implements View.OnClickListener { // private static final String TAG = "FBBOCL"; // // private Bundle mArgs; // private int mPreviousFragment; // // /** // * Use this to simply navigate one step back on the navigation stack. // */ // public FragmentBackButtonOnClickListener() { // // } // // /** // * Use this to navigate back AND pass a custom set of arguments with the transition to // * the target fragment. // * // * @param previousFragment ID of the fragment to navigate to // * @param args Custom set of arguments to pass with the transition // */ // public FragmentBackButtonOnClickListener(int previousFragment, Bundle args) { // mPreviousFragment = previousFragment; // mArgs = args; // } // // @Override // public void onClick(View v) { // boolean customArgs = mArgs != null; // // Log.d(TAG, "onClick() - custom args set: " + customArgs); // // // If custom args are set, treat the transition as a 'regular' fragment transition. // Message msg = customArgs ? UiUpdateHandler.obtainReplaceFragmentMessage(mPreviousFragment) : // UiUpdateHandler.obtainGoBackMessage(); // // if (customArgs) { // // Raise the flag telling that this 'regular' transition is actually a back transition. // mArgs.putBoolean(UiUpdateHandler.ARG_IS_BACK_TRANSITION, true); // mArgs.putAll(msg.getData()); // Add all the original args as well, as e.g. the target // // fragment ID is set there. // msg.setData(mArgs); // } // // msg.sendToTarget(); // } // } // // Path: app/src/main/java/jaakko/jaaska/apptycoon/ui/listener/TextViewChangeColourOnTouchListener.java // public class TextViewChangeColourOnTouchListener implements View.OnTouchListener { // // private int mOnTouchColor; // private int mOriginalColor; // // /** // * Constructor. // * // * Parameter colors are {@link android.graphics.Color Color} colors. // * // * @param onTouchColor Color of the text when touched. // * @param originalColor Original color of the text. // */ // public TextViewChangeColourOnTouchListener(int onTouchColor, int originalColor) { // mOnTouchColor = onTouchColor; // mOriginalColor = originalColor; // } // // @Override // public boolean onTouch(View v, MotionEvent event) { // // The view is ALWAYS a TextViews. // TextView tv = (TextView) v; // // switch (event.getAction()) { // case MotionEvent.ACTION_DOWN: // tv.setTextColor(mOnTouchColor); // break; // default: // tv.setTextColor(mOriginalColor); // } // return false; // } // }
import android.graphics.Color; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import jaakko.jaaska.apptycoon.R; import jaakko.jaaska.apptycoon.ui.listener.FragmentBackButtonOnClickListener; import jaakko.jaaska.apptycoon.ui.listener.TextViewChangeColourOnTouchListener;
* * @param fragmentId ID of the fragment to navigate back to. * @param args Arguments to pass to the previous fragment. */ protected void showCustomBackButton(int fragmentId, @Nullable Bundle args) { Log.d(TAG, "setBackTargetFragment() - fragmentId = " + fragmentId); mBackFragment = fragmentId; mBackArgs = args; bindBackButton(); } /** * Set an action for the action button on the fragment title bar. * @param label Label to be shown on the action button. * @param action Action to perform when the button is clicked. */ protected void setAction(String label, Action action) { Log.d(TAG, "setAction() - label = '" + label + "'"); mActionLabel = label; mAction = action; bindActionButton(); } private void bindBackButton() { Log.d(TAG, "bindBackButton()"); mTextViewBack.setVisibility(View.VISIBLE); mTextViewBack.setOnTouchListener(new TextViewChangeColourOnTouchListener(Color.BLACK, mTextViewBack.getCurrentTextColor())); // Use the listener with custom target and arguments if they're defined.
// Path: app/src/main/java/jaakko/jaaska/apptycoon/ui/listener/FragmentBackButtonOnClickListener.java // public class FragmentBackButtonOnClickListener implements View.OnClickListener { // private static final String TAG = "FBBOCL"; // // private Bundle mArgs; // private int mPreviousFragment; // // /** // * Use this to simply navigate one step back on the navigation stack. // */ // public FragmentBackButtonOnClickListener() { // // } // // /** // * Use this to navigate back AND pass a custom set of arguments with the transition to // * the target fragment. // * // * @param previousFragment ID of the fragment to navigate to // * @param args Custom set of arguments to pass with the transition // */ // public FragmentBackButtonOnClickListener(int previousFragment, Bundle args) { // mPreviousFragment = previousFragment; // mArgs = args; // } // // @Override // public void onClick(View v) { // boolean customArgs = mArgs != null; // // Log.d(TAG, "onClick() - custom args set: " + customArgs); // // // If custom args are set, treat the transition as a 'regular' fragment transition. // Message msg = customArgs ? UiUpdateHandler.obtainReplaceFragmentMessage(mPreviousFragment) : // UiUpdateHandler.obtainGoBackMessage(); // // if (customArgs) { // // Raise the flag telling that this 'regular' transition is actually a back transition. // mArgs.putBoolean(UiUpdateHandler.ARG_IS_BACK_TRANSITION, true); // mArgs.putAll(msg.getData()); // Add all the original args as well, as e.g. the target // // fragment ID is set there. // msg.setData(mArgs); // } // // msg.sendToTarget(); // } // } // // Path: app/src/main/java/jaakko/jaaska/apptycoon/ui/listener/TextViewChangeColourOnTouchListener.java // public class TextViewChangeColourOnTouchListener implements View.OnTouchListener { // // private int mOnTouchColor; // private int mOriginalColor; // // /** // * Constructor. // * // * Parameter colors are {@link android.graphics.Color Color} colors. // * // * @param onTouchColor Color of the text when touched. // * @param originalColor Original color of the text. // */ // public TextViewChangeColourOnTouchListener(int onTouchColor, int originalColor) { // mOnTouchColor = onTouchColor; // mOriginalColor = originalColor; // } // // @Override // public boolean onTouch(View v, MotionEvent event) { // // The view is ALWAYS a TextViews. // TextView tv = (TextView) v; // // switch (event.getAction()) { // case MotionEvent.ACTION_DOWN: // tv.setTextColor(mOnTouchColor); // break; // default: // tv.setTextColor(mOriginalColor); // } // return false; // } // } // Path: app/src/main/java/jaakko/jaaska/apptycoon/ui/fragment/AppTycoonFragment.java import android.graphics.Color; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import jaakko.jaaska.apptycoon.R; import jaakko.jaaska.apptycoon.ui.listener.FragmentBackButtonOnClickListener; import jaakko.jaaska.apptycoon.ui.listener.TextViewChangeColourOnTouchListener; * * @param fragmentId ID of the fragment to navigate back to. * @param args Arguments to pass to the previous fragment. */ protected void showCustomBackButton(int fragmentId, @Nullable Bundle args) { Log.d(TAG, "setBackTargetFragment() - fragmentId = " + fragmentId); mBackFragment = fragmentId; mBackArgs = args; bindBackButton(); } /** * Set an action for the action button on the fragment title bar. * @param label Label to be shown on the action button. * @param action Action to perform when the button is clicked. */ protected void setAction(String label, Action action) { Log.d(TAG, "setAction() - label = '" + label + "'"); mActionLabel = label; mAction = action; bindActionButton(); } private void bindBackButton() { Log.d(TAG, "bindBackButton()"); mTextViewBack.setVisibility(View.VISIBLE); mTextViewBack.setOnTouchListener(new TextViewChangeColourOnTouchListener(Color.BLACK, mTextViewBack.getCurrentTextColor())); // Use the listener with custom target and arguments if they're defined.
FragmentBackButtonOnClickListener listener = mBackFragment < 0 ?
zak0/AppTycoon
app/src/main/java/jaakko/jaaska/apptycoon/utils/Utils.java
// Path: app/src/main/java/jaakko/jaaska/apptycoon/AppTycoonApp.java // public class AppTycoonApp extends Application { // // private static AppTycoonApp sInstance; // // public static Context getContext() { // return sInstance; // } // // @Override // public void onCreate() { // sInstance = this; // super.onCreate(); // } // }
import android.content.Context; import android.util.Log; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import java.util.Random; import jaakko.jaaska.apptycoon.AppTycoonApp; import jaakko.jaaska.apptycoon.R;
break; } } //Log.d(TAG, "largeNumberToNiceString() - numberToConvert = " + numberToConvert); //Log.d(TAG, "largeNumberToNiceString() - number = " + number); // If no "power of 1000" was not found, just use the numberToConvert directly. // This happens if the number is less than 1000. if (number <= 0.0f) { return Long.toString(numberToConvert); } double residue = number - Math.floor(number); residue = residue * Math.pow(10, decimals); residue = Math.round(residue) / Math.pow(10, decimals); number = Math.floor(number) + residue; return String.format("%." + decimals + "f", number) + suffix; } private static List<String> sFirstNames; private static List<String> sLastNames; /** * Generates a random name from seeds in /res/raw/firstnames.txt and lastnames.txt * @return A random name. */ public static String getRandomName() {
// Path: app/src/main/java/jaakko/jaaska/apptycoon/AppTycoonApp.java // public class AppTycoonApp extends Application { // // private static AppTycoonApp sInstance; // // public static Context getContext() { // return sInstance; // } // // @Override // public void onCreate() { // sInstance = this; // super.onCreate(); // } // } // Path: app/src/main/java/jaakko/jaaska/apptycoon/utils/Utils.java import android.content.Context; import android.util.Log; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import java.util.Random; import jaakko.jaaska.apptycoon.AppTycoonApp; import jaakko.jaaska.apptycoon.R; break; } } //Log.d(TAG, "largeNumberToNiceString() - numberToConvert = " + numberToConvert); //Log.d(TAG, "largeNumberToNiceString() - number = " + number); // If no "power of 1000" was not found, just use the numberToConvert directly. // This happens if the number is less than 1000. if (number <= 0.0f) { return Long.toString(numberToConvert); } double residue = number - Math.floor(number); residue = residue * Math.pow(10, decimals); residue = Math.round(residue) / Math.pow(10, decimals); number = Math.floor(number) + residue; return String.format("%." + decimals + "f", number) + suffix; } private static List<String> sFirstNames; private static List<String> sLastNames; /** * Generates a random name from seeds in /res/raw/firstnames.txt and lastnames.txt * @return A random name. */ public static String getRandomName() {
Context context = AppTycoonApp.getContext();
zak0/AppTycoon
app/src/main/java/jaakko/jaaska/apptycoon/ui/dialog/AppTycoonDialog.java
// Path: app/src/main/java/jaakko/jaaska/apptycoon/ui/listener/TextViewChangeColourOnTouchListener.java // public class TextViewChangeColourOnTouchListener implements View.OnTouchListener { // // private int mOnTouchColor; // private int mOriginalColor; // // /** // * Constructor. // * // * Parameter colors are {@link android.graphics.Color Color} colors. // * // * @param onTouchColor Color of the text when touched. // * @param originalColor Original color of the text. // */ // public TextViewChangeColourOnTouchListener(int onTouchColor, int originalColor) { // mOnTouchColor = onTouchColor; // mOriginalColor = originalColor; // } // // @Override // public boolean onTouch(View v, MotionEvent event) { // // The view is ALWAYS a TextViews. // TextView tv = (TextView) v; // // switch (event.getAction()) { // case MotionEvent.ACTION_DOWN: // tv.setTextColor(mOnTouchColor); // break; // default: // tv.setTextColor(mOriginalColor); // } // return false; // } // }
import android.app.Dialog; import android.content.Context; import android.graphics.Color; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.widget.RelativeLayout; import android.widget.TextView; import jaakko.jaaska.apptycoon.R; import jaakko.jaaska.apptycoon.ui.listener.TextViewChangeColourOnTouchListener;
package jaakko.jaaska.apptycoon.ui.dialog; /** * An extension of Dialog class for easier building of dialogs with consistent look * to the rest of the game. * * The top bar and the two action buttons on it are handled within this class. Rest of the * stuff - namely the stuff specific to the dialog in question - are implemented elsewhere. * The Views are accessed similarly as with a plain Dialog. */ public class AppTycoonDialog extends Dialog { private TextView mTextViewOk; private TextView mTextViewCancel; /** * Constructor. * * @param context Current activity context. * @param layout ID of the content layout resource for the dialog. * @param dialogTitle Title of the dialog. */ public AppTycoonDialog(Context context, int layout, String dialogTitle) { this(context, LayoutInflater.from(context).inflate(layout, null), dialogTitle); } /** * Constructor. * * @param context Current activity context. * @param contentView View to be placed as the content of the dialog. * @param dialogTitle Title of the dialog. */ public AppTycoonDialog(Context context, View contentView, String dialogTitle) { super(context); setContentView(R.layout.dialog_apptycoon_dialog); RelativeLayout layoutContentContainer = (RelativeLayout) findViewById(R.id.layoutDialogContent); layoutContentContainer.addView(contentView); setTitle(dialogTitle); // Action buttons are hidden until an action for them is set. mTextViewOk = (TextView) findViewById(R.id.textViewDialogActionOk); mTextViewCancel = (TextView) findViewById(R.id.textViewDialogActionCancel); mTextViewOk.setVisibility(View.INVISIBLE); mTextViewCancel.setVisibility(View.INVISIBLE); } /** * Sets the title for the dialog. * * @param title New title for the dialog. */ @Override public void setTitle(@Nullable CharSequence title) { ((TextView) findViewById(R.id.textViewDialogTitle)).setText(title); } private void setActionTextViewListener(TextView view, View.OnClickListener listener) {
// Path: app/src/main/java/jaakko/jaaska/apptycoon/ui/listener/TextViewChangeColourOnTouchListener.java // public class TextViewChangeColourOnTouchListener implements View.OnTouchListener { // // private int mOnTouchColor; // private int mOriginalColor; // // /** // * Constructor. // * // * Parameter colors are {@link android.graphics.Color Color} colors. // * // * @param onTouchColor Color of the text when touched. // * @param originalColor Original color of the text. // */ // public TextViewChangeColourOnTouchListener(int onTouchColor, int originalColor) { // mOnTouchColor = onTouchColor; // mOriginalColor = originalColor; // } // // @Override // public boolean onTouch(View v, MotionEvent event) { // // The view is ALWAYS a TextViews. // TextView tv = (TextView) v; // // switch (event.getAction()) { // case MotionEvent.ACTION_DOWN: // tv.setTextColor(mOnTouchColor); // break; // default: // tv.setTextColor(mOriginalColor); // } // return false; // } // } // Path: app/src/main/java/jaakko/jaaska/apptycoon/ui/dialog/AppTycoonDialog.java import android.app.Dialog; import android.content.Context; import android.graphics.Color; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.widget.RelativeLayout; import android.widget.TextView; import jaakko.jaaska.apptycoon.R; import jaakko.jaaska.apptycoon.ui.listener.TextViewChangeColourOnTouchListener; package jaakko.jaaska.apptycoon.ui.dialog; /** * An extension of Dialog class for easier building of dialogs with consistent look * to the rest of the game. * * The top bar and the two action buttons on it are handled within this class. Rest of the * stuff - namely the stuff specific to the dialog in question - are implemented elsewhere. * The Views are accessed similarly as with a plain Dialog. */ public class AppTycoonDialog extends Dialog { private TextView mTextViewOk; private TextView mTextViewCancel; /** * Constructor. * * @param context Current activity context. * @param layout ID of the content layout resource for the dialog. * @param dialogTitle Title of the dialog. */ public AppTycoonDialog(Context context, int layout, String dialogTitle) { this(context, LayoutInflater.from(context).inflate(layout, null), dialogTitle); } /** * Constructor. * * @param context Current activity context. * @param contentView View to be placed as the content of the dialog. * @param dialogTitle Title of the dialog. */ public AppTycoonDialog(Context context, View contentView, String dialogTitle) { super(context); setContentView(R.layout.dialog_apptycoon_dialog); RelativeLayout layoutContentContainer = (RelativeLayout) findViewById(R.id.layoutDialogContent); layoutContentContainer.addView(contentView); setTitle(dialogTitle); // Action buttons are hidden until an action for them is set. mTextViewOk = (TextView) findViewById(R.id.textViewDialogActionOk); mTextViewCancel = (TextView) findViewById(R.id.textViewDialogActionCancel); mTextViewOk.setVisibility(View.INVISIBLE); mTextViewCancel.setVisibility(View.INVISIBLE); } /** * Sets the title for the dialog. * * @param title New title for the dialog. */ @Override public void setTitle(@Nullable CharSequence title) { ((TextView) findViewById(R.id.textViewDialogTitle)).setText(title); } private void setActionTextViewListener(TextView view, View.OnClickListener listener) {
view.setOnTouchListener(new TextViewChangeColourOnTouchListener(Color.BLACK,
lukaspili/flow-navigation
sample/src/main/java/com/example/flow/ui/view/PostsView.java
// Path: sample/src/main/java/com/example/flow/mortar/DaggerService.java // public class DaggerService { // // public static final String SERVICE_NAME = DaggerService.class.getName(); // // /** // * Caller is required to know the type of the component for this context. // */ // @SuppressWarnings("unchecked") // // public static <T> T getDaggerComponent(Context context) { // return (T) context.getSystemService(SERVICE_NAME); // } // } // // Path: sample/src/main/java/com/example/flow/ui/screen/PostsScreen.java // @Layout(R.layout.screen_posts) // public class PostsScreen extends Path implements ComponentFactory<RootActivity.Component> { // // @Override // public Object createComponent(RootActivity.Component component) { // return DaggerPostsScreen_Component.builder() // .component(component) // .build(); // } // // @dagger.Component(dependencies = RootActivity.Component.class) // @ScreenScope(Component.class) // public interface Component extends RootActivity.Component { // // void inject(PostsView view); // } // // @ScreenScope(Component.class) // public static class Presenter extends ViewPresenter<PostsView> implements PostAdapter.Listener { // // private final RestClient restClient; // // private PostAdapter adapter; // private List<Post> posts = new ArrayList<>(); // // @Inject // public Presenter(RestClient restClient) { // this.restClient = restClient; // } // // @Override // protected void onLoad(Bundle savedInstanceState) { // LinearLayoutManager layoutManager = new LinearLayoutManager(getView().getContext()); // layoutManager.setOrientation(LinearLayoutManager.VERTICAL); // getView().recyclerView.setLayoutManager(layoutManager); // // adapter = new PostAdapter(getView().getContext(), posts, this); // getView().recyclerView.setAdapter(adapter); // // if (posts.isEmpty()) { // load(); // } // } // // private void load() { // // restClient.getService().getPosts(new Callback<List<Post>>() { // @Override // public void success(List<Post> loadedPosts, Response response) { // if (!hasView()) return; // Timber.d("Success loaded %s", loadedPosts.size()); // // posts.clear(); // posts.addAll(loadedPosts); // adapter.notifyDataSetChanged(); // } // // @Override // public void failure(RetrofitError error) { // if (!hasView()) return; // Timber.d("Failure %s", error.getMessage()); // } // }); // } // // @Override // protected void onSave(Bundle outState) { // super.onSave(outState); // // // } // // @Override // public void onItemClick(int position) { // if (!hasView()) return; // // Post post = posts.get(position); // Flow.get(getView()).set(new ViewPostScreen(post)); // } // } // }
import android.content.Context; import android.support.v7.widget.RecyclerView; import android.util.AttributeSet; import android.widget.FrameLayout; import com.example.flow.R; import com.example.flow.mortar.DaggerService; import com.example.flow.ui.screen.PostsScreen; import javax.inject.Inject; import butterknife.ButterKnife; import butterknife.InjectView;
package com.example.flow.ui.view; /** * @author Lukasz Piliszczuk <lukasz.pili@gmail.com> */ public class PostsView extends FrameLayout { @InjectView(R.id.recycler_view) public RecyclerView recyclerView; @Inject
// Path: sample/src/main/java/com/example/flow/mortar/DaggerService.java // public class DaggerService { // // public static final String SERVICE_NAME = DaggerService.class.getName(); // // /** // * Caller is required to know the type of the component for this context. // */ // @SuppressWarnings("unchecked") // // public static <T> T getDaggerComponent(Context context) { // return (T) context.getSystemService(SERVICE_NAME); // } // } // // Path: sample/src/main/java/com/example/flow/ui/screen/PostsScreen.java // @Layout(R.layout.screen_posts) // public class PostsScreen extends Path implements ComponentFactory<RootActivity.Component> { // // @Override // public Object createComponent(RootActivity.Component component) { // return DaggerPostsScreen_Component.builder() // .component(component) // .build(); // } // // @dagger.Component(dependencies = RootActivity.Component.class) // @ScreenScope(Component.class) // public interface Component extends RootActivity.Component { // // void inject(PostsView view); // } // // @ScreenScope(Component.class) // public static class Presenter extends ViewPresenter<PostsView> implements PostAdapter.Listener { // // private final RestClient restClient; // // private PostAdapter adapter; // private List<Post> posts = new ArrayList<>(); // // @Inject // public Presenter(RestClient restClient) { // this.restClient = restClient; // } // // @Override // protected void onLoad(Bundle savedInstanceState) { // LinearLayoutManager layoutManager = new LinearLayoutManager(getView().getContext()); // layoutManager.setOrientation(LinearLayoutManager.VERTICAL); // getView().recyclerView.setLayoutManager(layoutManager); // // adapter = new PostAdapter(getView().getContext(), posts, this); // getView().recyclerView.setAdapter(adapter); // // if (posts.isEmpty()) { // load(); // } // } // // private void load() { // // restClient.getService().getPosts(new Callback<List<Post>>() { // @Override // public void success(List<Post> loadedPosts, Response response) { // if (!hasView()) return; // Timber.d("Success loaded %s", loadedPosts.size()); // // posts.clear(); // posts.addAll(loadedPosts); // adapter.notifyDataSetChanged(); // } // // @Override // public void failure(RetrofitError error) { // if (!hasView()) return; // Timber.d("Failure %s", error.getMessage()); // } // }); // } // // @Override // protected void onSave(Bundle outState) { // super.onSave(outState); // // // } // // @Override // public void onItemClick(int position) { // if (!hasView()) return; // // Post post = posts.get(position); // Flow.get(getView()).set(new ViewPostScreen(post)); // } // } // } // Path: sample/src/main/java/com/example/flow/ui/view/PostsView.java import android.content.Context; import android.support.v7.widget.RecyclerView; import android.util.AttributeSet; import android.widget.FrameLayout; import com.example.flow.R; import com.example.flow.mortar.DaggerService; import com.example.flow.ui.screen.PostsScreen; import javax.inject.Inject; import butterknife.ButterKnife; import butterknife.InjectView; package com.example.flow.ui.view; /** * @author Lukasz Piliszczuk <lukasz.pili@gmail.com> */ public class PostsView extends FrameLayout { @InjectView(R.id.recycler_view) public RecyclerView recyclerView; @Inject
protected PostsScreen.Presenter presenter;
lukaspili/flow-navigation
sample/src/main/java/com/example/flow/ui/view/PostsView.java
// Path: sample/src/main/java/com/example/flow/mortar/DaggerService.java // public class DaggerService { // // public static final String SERVICE_NAME = DaggerService.class.getName(); // // /** // * Caller is required to know the type of the component for this context. // */ // @SuppressWarnings("unchecked") // // public static <T> T getDaggerComponent(Context context) { // return (T) context.getSystemService(SERVICE_NAME); // } // } // // Path: sample/src/main/java/com/example/flow/ui/screen/PostsScreen.java // @Layout(R.layout.screen_posts) // public class PostsScreen extends Path implements ComponentFactory<RootActivity.Component> { // // @Override // public Object createComponent(RootActivity.Component component) { // return DaggerPostsScreen_Component.builder() // .component(component) // .build(); // } // // @dagger.Component(dependencies = RootActivity.Component.class) // @ScreenScope(Component.class) // public interface Component extends RootActivity.Component { // // void inject(PostsView view); // } // // @ScreenScope(Component.class) // public static class Presenter extends ViewPresenter<PostsView> implements PostAdapter.Listener { // // private final RestClient restClient; // // private PostAdapter adapter; // private List<Post> posts = new ArrayList<>(); // // @Inject // public Presenter(RestClient restClient) { // this.restClient = restClient; // } // // @Override // protected void onLoad(Bundle savedInstanceState) { // LinearLayoutManager layoutManager = new LinearLayoutManager(getView().getContext()); // layoutManager.setOrientation(LinearLayoutManager.VERTICAL); // getView().recyclerView.setLayoutManager(layoutManager); // // adapter = new PostAdapter(getView().getContext(), posts, this); // getView().recyclerView.setAdapter(adapter); // // if (posts.isEmpty()) { // load(); // } // } // // private void load() { // // restClient.getService().getPosts(new Callback<List<Post>>() { // @Override // public void success(List<Post> loadedPosts, Response response) { // if (!hasView()) return; // Timber.d("Success loaded %s", loadedPosts.size()); // // posts.clear(); // posts.addAll(loadedPosts); // adapter.notifyDataSetChanged(); // } // // @Override // public void failure(RetrofitError error) { // if (!hasView()) return; // Timber.d("Failure %s", error.getMessage()); // } // }); // } // // @Override // protected void onSave(Bundle outState) { // super.onSave(outState); // // // } // // @Override // public void onItemClick(int position) { // if (!hasView()) return; // // Post post = posts.get(position); // Flow.get(getView()).set(new ViewPostScreen(post)); // } // } // }
import android.content.Context; import android.support.v7.widget.RecyclerView; import android.util.AttributeSet; import android.widget.FrameLayout; import com.example.flow.R; import com.example.flow.mortar.DaggerService; import com.example.flow.ui.screen.PostsScreen; import javax.inject.Inject; import butterknife.ButterKnife; import butterknife.InjectView;
package com.example.flow.ui.view; /** * @author Lukasz Piliszczuk <lukasz.pili@gmail.com> */ public class PostsView extends FrameLayout { @InjectView(R.id.recycler_view) public RecyclerView recyclerView; @Inject protected PostsScreen.Presenter presenter; public PostsView(Context context) { super(context); init(context); } public PostsView(Context context, AttributeSet attrs) { super(context, attrs); init(context); } public PostsView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context); } protected void init(Context context) {
// Path: sample/src/main/java/com/example/flow/mortar/DaggerService.java // public class DaggerService { // // public static final String SERVICE_NAME = DaggerService.class.getName(); // // /** // * Caller is required to know the type of the component for this context. // */ // @SuppressWarnings("unchecked") // // public static <T> T getDaggerComponent(Context context) { // return (T) context.getSystemService(SERVICE_NAME); // } // } // // Path: sample/src/main/java/com/example/flow/ui/screen/PostsScreen.java // @Layout(R.layout.screen_posts) // public class PostsScreen extends Path implements ComponentFactory<RootActivity.Component> { // // @Override // public Object createComponent(RootActivity.Component component) { // return DaggerPostsScreen_Component.builder() // .component(component) // .build(); // } // // @dagger.Component(dependencies = RootActivity.Component.class) // @ScreenScope(Component.class) // public interface Component extends RootActivity.Component { // // void inject(PostsView view); // } // // @ScreenScope(Component.class) // public static class Presenter extends ViewPresenter<PostsView> implements PostAdapter.Listener { // // private final RestClient restClient; // // private PostAdapter adapter; // private List<Post> posts = new ArrayList<>(); // // @Inject // public Presenter(RestClient restClient) { // this.restClient = restClient; // } // // @Override // protected void onLoad(Bundle savedInstanceState) { // LinearLayoutManager layoutManager = new LinearLayoutManager(getView().getContext()); // layoutManager.setOrientation(LinearLayoutManager.VERTICAL); // getView().recyclerView.setLayoutManager(layoutManager); // // adapter = new PostAdapter(getView().getContext(), posts, this); // getView().recyclerView.setAdapter(adapter); // // if (posts.isEmpty()) { // load(); // } // } // // private void load() { // // restClient.getService().getPosts(new Callback<List<Post>>() { // @Override // public void success(List<Post> loadedPosts, Response response) { // if (!hasView()) return; // Timber.d("Success loaded %s", loadedPosts.size()); // // posts.clear(); // posts.addAll(loadedPosts); // adapter.notifyDataSetChanged(); // } // // @Override // public void failure(RetrofitError error) { // if (!hasView()) return; // Timber.d("Failure %s", error.getMessage()); // } // }); // } // // @Override // protected void onSave(Bundle outState) { // super.onSave(outState); // // // } // // @Override // public void onItemClick(int position) { // if (!hasView()) return; // // Post post = posts.get(position); // Flow.get(getView()).set(new ViewPostScreen(post)); // } // } // } // Path: sample/src/main/java/com/example/flow/ui/view/PostsView.java import android.content.Context; import android.support.v7.widget.RecyclerView; import android.util.AttributeSet; import android.widget.FrameLayout; import com.example.flow.R; import com.example.flow.mortar.DaggerService; import com.example.flow.ui.screen.PostsScreen; import javax.inject.Inject; import butterknife.ButterKnife; import butterknife.InjectView; package com.example.flow.ui.view; /** * @author Lukasz Piliszczuk <lukasz.pili@gmail.com> */ public class PostsView extends FrameLayout { @InjectView(R.id.recycler_view) public RecyclerView recyclerView; @Inject protected PostsScreen.Presenter presenter; public PostsView(Context context) { super(context); init(context); } public PostsView(Context context, AttributeSet attrs) { super(context, attrs); init(context); } public PostsView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context); } protected void init(Context context) {
((PostsScreen.Component) context.getSystemService(DaggerService.SERVICE_NAME)).inject(this);
lukaspili/flow-navigation
flow-common/src/main/java/flownavigation/common/flow/FramePathContainerView.java
// Path: library/src/main/java/flownavigation/path/Path.java // public abstract class Path { // // static final Path ROOT = new Path() { // }; // // public static PathContextFactory contextFactory() { // return new ContextFactory(); // } // // public static PathContextFactory contextFactory(PathContextFactory delegate) { // return new ContextFactory(delegate); // } // // private static final class LocalPathWrapper extends ContextWrapper { // static final String LOCAL_WRAPPER_SERVICE = "flow_local_screen_context_wrapper"; // private LayoutInflater inflater; // // final Object localScreen; // // LocalPathWrapper(Context base, Object localScreen) { // super(base); // this.localScreen = localScreen; // } // // @Override // public Object getSystemService(String name) { // if (LOCAL_WRAPPER_SERVICE.equals(name)) { // return this; // } // if (LAYOUT_INFLATER_SERVICE.equals(name)) { // if (inflater == null) { // inflater = LayoutInflater.from(getBaseContext()).cloneInContext(this); // } // return inflater; // } // return super.getSystemService(name); // } // } // // private static final class ContextFactory implements PathContextFactory { // // May be null. // private final PathContextFactory delegate; // // public ContextFactory() { // delegate = null; // } // // public ContextFactory(PathContextFactory delegate) { // this.delegate = delegate; // } // // @Override // public Context setUpContext(Path path, Context parentContext) { // if (delegate != null) { // parentContext = delegate.setUpContext(path, parentContext); // } // return new LocalPathWrapper(parentContext, path); // } // // @Override // public void tearDownContext(Context context) { // if (delegate != null) { // delegate.tearDownContext(context); // } // } // } // } // // Path: library/src/main/java/flownavigation/path/PathContainer.java // public abstract class PathContainer { // // /** // * Provides information about the current or most recent Traversal handled by the container. // */ // protected static final class TraversalState { // private Path fromPath; // private ViewState fromViewState; // private Path toPath; // private ViewState toViewState; // // public void setNextEntry(Path path, ViewState viewState) { // this.fromPath = this.toPath; // this.fromViewState = this.toViewState; // this.toPath = path; // this.toViewState = viewState; // } // // public Path fromPath() { // return fromPath; // } // // public Path toPath() { // return toPath; // } // // public void saveViewState(View view) { // fromViewState.save(view); // } // // public void restoreViewState(View view) { // toViewState.restore(view); // } // } // // private static final Map<Class, Integer> PATH_LAYOUT_CACHE = new LinkedHashMap<>(); // // private final int tagKey; // // protected PathContainer(int tagKey) { // this.tagKey = tagKey; // } // // public final void executeTraversal(PathContainerView view, Flow.Traversal traversal, // final Flow.TraversalCallback callback) { // // final View oldChild = view.getCurrentChild(); // // Path path = traversal.destination.top(); // ViewState viewState = traversal.destination.currentViewState(); // // Path oldPath; // ViewGroup containerView = view.getContainerView(); // TraversalState traversalState = ensureTag(containerView); // // // See if we already have the direct child we want, and if so short circuit the traversal. // if (oldChild != null) { // oldPath = Preconditions.checkNotNull(traversalState.toPath, "Container view has child %s with no path", oldChild.toString()); // if (oldPath.equals(path)) { // callback.onTraversalCompleted(); // return; // } // } // // traversalState.setNextEntry(path, viewState); // performTraversal(containerView, traversalState, traversal.direction, callback); // } // // protected abstract void performTraversal(ViewGroup container, TraversalState traversalState, // Flow.Direction direction, Flow.TraversalCallback callback); // // private TraversalState ensureTag(ViewGroup container) { // TraversalState traversalState = (TraversalState) container.getTag(tagKey); // if (traversalState == null) { // traversalState = new TraversalState(); // container.setTag(tagKey, traversalState); // } // return traversalState; // } // } // // Path: library/src/main/java/flownavigation/path/PathContainerView.java // public interface PathContainerView extends Flow.Dispatcher { // ViewGroup getCurrentChild(); // // ViewGroup getContainerView(); // // Context getContext(); // // void dispatch(Flow.Traversal traversal, Flow.TraversalCallback callback); // }
import android.content.Context; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.ViewGroup; import android.widget.FrameLayout; import flow.Flow; import flownavigation.path.Path; import flownavigation.path.PathContainer; import flownavigation.path.PathContainerView;
/* * Copyright 2014 Square Inc. * * 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 flownavigation.common.flow; /** * A FrameLayout that can show screens for a {@link Flow}. * <p/> * Copy past from flow-sample * * @author Lukasz Piliszczuk - lukasz.pili@gmail.com */ public class FramePathContainerView extends FrameLayout implements HandlesBack, PathContainerView {
// Path: library/src/main/java/flownavigation/path/Path.java // public abstract class Path { // // static final Path ROOT = new Path() { // }; // // public static PathContextFactory contextFactory() { // return new ContextFactory(); // } // // public static PathContextFactory contextFactory(PathContextFactory delegate) { // return new ContextFactory(delegate); // } // // private static final class LocalPathWrapper extends ContextWrapper { // static final String LOCAL_WRAPPER_SERVICE = "flow_local_screen_context_wrapper"; // private LayoutInflater inflater; // // final Object localScreen; // // LocalPathWrapper(Context base, Object localScreen) { // super(base); // this.localScreen = localScreen; // } // // @Override // public Object getSystemService(String name) { // if (LOCAL_WRAPPER_SERVICE.equals(name)) { // return this; // } // if (LAYOUT_INFLATER_SERVICE.equals(name)) { // if (inflater == null) { // inflater = LayoutInflater.from(getBaseContext()).cloneInContext(this); // } // return inflater; // } // return super.getSystemService(name); // } // } // // private static final class ContextFactory implements PathContextFactory { // // May be null. // private final PathContextFactory delegate; // // public ContextFactory() { // delegate = null; // } // // public ContextFactory(PathContextFactory delegate) { // this.delegate = delegate; // } // // @Override // public Context setUpContext(Path path, Context parentContext) { // if (delegate != null) { // parentContext = delegate.setUpContext(path, parentContext); // } // return new LocalPathWrapper(parentContext, path); // } // // @Override // public void tearDownContext(Context context) { // if (delegate != null) { // delegate.tearDownContext(context); // } // } // } // } // // Path: library/src/main/java/flownavigation/path/PathContainer.java // public abstract class PathContainer { // // /** // * Provides information about the current or most recent Traversal handled by the container. // */ // protected static final class TraversalState { // private Path fromPath; // private ViewState fromViewState; // private Path toPath; // private ViewState toViewState; // // public void setNextEntry(Path path, ViewState viewState) { // this.fromPath = this.toPath; // this.fromViewState = this.toViewState; // this.toPath = path; // this.toViewState = viewState; // } // // public Path fromPath() { // return fromPath; // } // // public Path toPath() { // return toPath; // } // // public void saveViewState(View view) { // fromViewState.save(view); // } // // public void restoreViewState(View view) { // toViewState.restore(view); // } // } // // private static final Map<Class, Integer> PATH_LAYOUT_CACHE = new LinkedHashMap<>(); // // private final int tagKey; // // protected PathContainer(int tagKey) { // this.tagKey = tagKey; // } // // public final void executeTraversal(PathContainerView view, Flow.Traversal traversal, // final Flow.TraversalCallback callback) { // // final View oldChild = view.getCurrentChild(); // // Path path = traversal.destination.top(); // ViewState viewState = traversal.destination.currentViewState(); // // Path oldPath; // ViewGroup containerView = view.getContainerView(); // TraversalState traversalState = ensureTag(containerView); // // // See if we already have the direct child we want, and if so short circuit the traversal. // if (oldChild != null) { // oldPath = Preconditions.checkNotNull(traversalState.toPath, "Container view has child %s with no path", oldChild.toString()); // if (oldPath.equals(path)) { // callback.onTraversalCompleted(); // return; // } // } // // traversalState.setNextEntry(path, viewState); // performTraversal(containerView, traversalState, traversal.direction, callback); // } // // protected abstract void performTraversal(ViewGroup container, TraversalState traversalState, // Flow.Direction direction, Flow.TraversalCallback callback); // // private TraversalState ensureTag(ViewGroup container) { // TraversalState traversalState = (TraversalState) container.getTag(tagKey); // if (traversalState == null) { // traversalState = new TraversalState(); // container.setTag(tagKey, traversalState); // } // return traversalState; // } // } // // Path: library/src/main/java/flownavigation/path/PathContainerView.java // public interface PathContainerView extends Flow.Dispatcher { // ViewGroup getCurrentChild(); // // ViewGroup getContainerView(); // // Context getContext(); // // void dispatch(Flow.Traversal traversal, Flow.TraversalCallback callback); // } // Path: flow-common/src/main/java/flownavigation/common/flow/FramePathContainerView.java import android.content.Context; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.ViewGroup; import android.widget.FrameLayout; import flow.Flow; import flownavigation.path.Path; import flownavigation.path.PathContainer; import flownavigation.path.PathContainerView; /* * Copyright 2014 Square Inc. * * 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 flownavigation.common.flow; /** * A FrameLayout that can show screens for a {@link Flow}. * <p/> * Copy past from flow-sample * * @author Lukasz Piliszczuk - lukasz.pili@gmail.com */ public class FramePathContainerView extends FrameLayout implements HandlesBack, PathContainerView {
private final PathContainer container;
lukaspili/flow-navigation
sample/src/main/java/com/example/flow/app/adapter/PostAdapter.java
// Path: sample/src/main/java/com/example/flow/model/Post.java // public class Post { // private long id; // private long userId; // private String title; // private String body; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public long getUserId() { // return userId; // } // // public void setUserId(long userId) { // this.userId = userId; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getBody() { // return body; // } // // public void setBody(String body) { // this.body = body; // } // }
import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.example.flow.R; import com.example.flow.model.Post; import java.util.List; import butterknife.ButterKnife; import butterknife.InjectView;
package com.example.flow.app.adapter; public class PostAdapter extends RecyclerView.Adapter<PostAdapter.ViewHolder> { private final Context context;
// Path: sample/src/main/java/com/example/flow/model/Post.java // public class Post { // private long id; // private long userId; // private String title; // private String body; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public long getUserId() { // return userId; // } // // public void setUserId(long userId) { // this.userId = userId; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getBody() { // return body; // } // // public void setBody(String body) { // this.body = body; // } // } // Path: sample/src/main/java/com/example/flow/app/adapter/PostAdapter.java import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.example.flow.R; import com.example.flow.model.Post; import java.util.List; import butterknife.ButterKnife; import butterknife.InjectView; package com.example.flow.app.adapter; public class PostAdapter extends RecyclerView.Adapter<PostAdapter.ViewHolder> { private final Context context;
private final List<Post> posts;
lukaspili/flow-navigation
mortar-common/src/main/java/flownavigation/common/mortar/BasicMortarContextFactory.java
// Path: library/src/main/java/flownavigation/path/Path.java // public abstract class Path { // // static final Path ROOT = new Path() { // }; // // public static PathContextFactory contextFactory() { // return new ContextFactory(); // } // // public static PathContextFactory contextFactory(PathContextFactory delegate) { // return new ContextFactory(delegate); // } // // private static final class LocalPathWrapper extends ContextWrapper { // static final String LOCAL_WRAPPER_SERVICE = "flow_local_screen_context_wrapper"; // private LayoutInflater inflater; // // final Object localScreen; // // LocalPathWrapper(Context base, Object localScreen) { // super(base); // this.localScreen = localScreen; // } // // @Override // public Object getSystemService(String name) { // if (LOCAL_WRAPPER_SERVICE.equals(name)) { // return this; // } // if (LAYOUT_INFLATER_SERVICE.equals(name)) { // if (inflater == null) { // inflater = LayoutInflater.from(getBaseContext()).cloneInContext(this); // } // return inflater; // } // return super.getSystemService(name); // } // } // // private static final class ContextFactory implements PathContextFactory { // // May be null. // private final PathContextFactory delegate; // // public ContextFactory() { // delegate = null; // } // // public ContextFactory(PathContextFactory delegate) { // this.delegate = delegate; // } // // @Override // public Context setUpContext(Path path, Context parentContext) { // if (delegate != null) { // parentContext = delegate.setUpContext(path, parentContext); // } // return new LocalPathWrapper(parentContext, path); // } // // @Override // public void tearDownContext(Context context) { // if (delegate != null) { // delegate.tearDownContext(context); // } // } // } // } // // Path: library/src/main/java/flownavigation/path/PathContextFactory.java // public interface PathContextFactory { // /** // * Set up any services defined by this screen, and make them accessible via the context. // * Typically this means returning a new context that wraps the given one. // */ // Context setUpContext(Path path, Context parentContext); // // /** // * Tear down any services previously started by {@link #setUpContext(Path, Context)}. Note that // * the Context instance given here may be a wrapper around an instance that this factory // * created. // */ // void tearDownContext(Context context); // }
import android.content.Context; import android.content.ContextWrapper; import android.util.Log; import android.view.LayoutInflater; import flownavigation.path.Path; import flownavigation.path.PathContextFactory; import mortar.MortarScope;
package flownavigation.common.mortar; /** * @author Lukasz Piliszczuk - lukasz.pili@gmail.com */ public class BasicMortarContextFactory implements PathContextFactory { private final ScreenScoper screenScoper; public BasicMortarContextFactory(ScreenScoper screenScoper) { this.screenScoper = screenScoper; } @Override
// Path: library/src/main/java/flownavigation/path/Path.java // public abstract class Path { // // static final Path ROOT = new Path() { // }; // // public static PathContextFactory contextFactory() { // return new ContextFactory(); // } // // public static PathContextFactory contextFactory(PathContextFactory delegate) { // return new ContextFactory(delegate); // } // // private static final class LocalPathWrapper extends ContextWrapper { // static final String LOCAL_WRAPPER_SERVICE = "flow_local_screen_context_wrapper"; // private LayoutInflater inflater; // // final Object localScreen; // // LocalPathWrapper(Context base, Object localScreen) { // super(base); // this.localScreen = localScreen; // } // // @Override // public Object getSystemService(String name) { // if (LOCAL_WRAPPER_SERVICE.equals(name)) { // return this; // } // if (LAYOUT_INFLATER_SERVICE.equals(name)) { // if (inflater == null) { // inflater = LayoutInflater.from(getBaseContext()).cloneInContext(this); // } // return inflater; // } // return super.getSystemService(name); // } // } // // private static final class ContextFactory implements PathContextFactory { // // May be null. // private final PathContextFactory delegate; // // public ContextFactory() { // delegate = null; // } // // public ContextFactory(PathContextFactory delegate) { // this.delegate = delegate; // } // // @Override // public Context setUpContext(Path path, Context parentContext) { // if (delegate != null) { // parentContext = delegate.setUpContext(path, parentContext); // } // return new LocalPathWrapper(parentContext, path); // } // // @Override // public void tearDownContext(Context context) { // if (delegate != null) { // delegate.tearDownContext(context); // } // } // } // } // // Path: library/src/main/java/flownavigation/path/PathContextFactory.java // public interface PathContextFactory { // /** // * Set up any services defined by this screen, and make them accessible via the context. // * Typically this means returning a new context that wraps the given one. // */ // Context setUpContext(Path path, Context parentContext); // // /** // * Tear down any services previously started by {@link #setUpContext(Path, Context)}. Note that // * the Context instance given here may be a wrapper around an instance that this factory // * created. // */ // void tearDownContext(Context context); // } // Path: mortar-common/src/main/java/flownavigation/common/mortar/BasicMortarContextFactory.java import android.content.Context; import android.content.ContextWrapper; import android.util.Log; import android.view.LayoutInflater; import flownavigation.path.Path; import flownavigation.path.PathContextFactory; import mortar.MortarScope; package flownavigation.common.mortar; /** * @author Lukasz Piliszczuk - lukasz.pili@gmail.com */ public class BasicMortarContextFactory implements PathContextFactory { private final ScreenScoper screenScoper; public BasicMortarContextFactory(ScreenScoper screenScoper) { this.screenScoper = screenScoper; } @Override
public Context setUpContext(Path path, Context parentContext) {
lukaspili/flow-navigation
sample/src/main/java/com/example/flow/app/App.java
// Path: sample/src/main/java/com/example/flow/mortar/DaggerService.java // public class DaggerService { // // public static final String SERVICE_NAME = DaggerService.class.getName(); // // /** // * Caller is required to know the type of the component for this context. // */ // @SuppressWarnings("unchecked") // // public static <T> T getDaggerComponent(Context context) { // return (T) context.getSystemService(SERVICE_NAME); // } // } // // Path: sample/src/main/java/com/example/flow/rest/RestClient.java // @Singleton // public class RestClient { // // private Service service; // // @Inject // public RestClient() { // // Gson gson = new GsonBuilder().create(); // // RestAdapter restAdapter = new RestAdapter.Builder() // .setLogLevel(RestAdapter.LogLevel.BASIC) // .setEndpoint("http://jsonplaceholder.typicode.com/") // .setConverter(new GsonConverter(gson)) // .build(); // // service = restAdapter.create(Service.class); // } // // public Service getService() { // return service; // } // }
import android.app.Application; import android.content.Context; import com.example.flow.BuildConfig; import com.example.flow.mortar.DaggerService; import com.example.flow.rest.RestClient; import javax.inject.Singleton; import dagger.Provides; import mortar.MortarScope; import timber.log.Timber;
package com.example.flow.app; public class App extends Application { private MortarScope mortarScope; @Override public Object getSystemService(String name) { return mortarScope.hasService(name) ? mortarScope.getService(name) : super.getSystemService(name); } @Override public void onCreate() { super.onCreate(); if (BuildConfig.DEBUG) { Timber.plant(new Timber.DebugTree()); } Component component = DaggerApp_Component.builder() .module(new Module()) .build(); component.inject(this); mortarScope = MortarScope.buildRootScope()
// Path: sample/src/main/java/com/example/flow/mortar/DaggerService.java // public class DaggerService { // // public static final String SERVICE_NAME = DaggerService.class.getName(); // // /** // * Caller is required to know the type of the component for this context. // */ // @SuppressWarnings("unchecked") // // public static <T> T getDaggerComponent(Context context) { // return (T) context.getSystemService(SERVICE_NAME); // } // } // // Path: sample/src/main/java/com/example/flow/rest/RestClient.java // @Singleton // public class RestClient { // // private Service service; // // @Inject // public RestClient() { // // Gson gson = new GsonBuilder().create(); // // RestAdapter restAdapter = new RestAdapter.Builder() // .setLogLevel(RestAdapter.LogLevel.BASIC) // .setEndpoint("http://jsonplaceholder.typicode.com/") // .setConverter(new GsonConverter(gson)) // .build(); // // service = restAdapter.create(Service.class); // } // // public Service getService() { // return service; // } // } // Path: sample/src/main/java/com/example/flow/app/App.java import android.app.Application; import android.content.Context; import com.example.flow.BuildConfig; import com.example.flow.mortar.DaggerService; import com.example.flow.rest.RestClient; import javax.inject.Singleton; import dagger.Provides; import mortar.MortarScope; import timber.log.Timber; package com.example.flow.app; public class App extends Application { private MortarScope mortarScope; @Override public Object getSystemService(String name) { return mortarScope.hasService(name) ? mortarScope.getService(name) : super.getSystemService(name); } @Override public void onCreate() { super.onCreate(); if (BuildConfig.DEBUG) { Timber.plant(new Timber.DebugTree()); } Component component = DaggerApp_Component.builder() .module(new Module()) .build(); component.inject(this); mortarScope = MortarScope.buildRootScope()
.withService(DaggerService.SERVICE_NAME, component)
lukaspili/flow-navigation
sample/src/main/java/com/example/flow/app/App.java
// Path: sample/src/main/java/com/example/flow/mortar/DaggerService.java // public class DaggerService { // // public static final String SERVICE_NAME = DaggerService.class.getName(); // // /** // * Caller is required to know the type of the component for this context. // */ // @SuppressWarnings("unchecked") // // public static <T> T getDaggerComponent(Context context) { // return (T) context.getSystemService(SERVICE_NAME); // } // } // // Path: sample/src/main/java/com/example/flow/rest/RestClient.java // @Singleton // public class RestClient { // // private Service service; // // @Inject // public RestClient() { // // Gson gson = new GsonBuilder().create(); // // RestAdapter restAdapter = new RestAdapter.Builder() // .setLogLevel(RestAdapter.LogLevel.BASIC) // .setEndpoint("http://jsonplaceholder.typicode.com/") // .setConverter(new GsonConverter(gson)) // .build(); // // service = restAdapter.create(Service.class); // } // // public Service getService() { // return service; // } // }
import android.app.Application; import android.content.Context; import com.example.flow.BuildConfig; import com.example.flow.mortar.DaggerService; import com.example.flow.rest.RestClient; import javax.inject.Singleton; import dagger.Provides; import mortar.MortarScope; import timber.log.Timber;
package com.example.flow.app; public class App extends Application { private MortarScope mortarScope; @Override public Object getSystemService(String name) { return mortarScope.hasService(name) ? mortarScope.getService(name) : super.getSystemService(name); } @Override public void onCreate() { super.onCreate(); if (BuildConfig.DEBUG) { Timber.plant(new Timber.DebugTree()); } Component component = DaggerApp_Component.builder() .module(new Module()) .build(); component.inject(this); mortarScope = MortarScope.buildRootScope() .withService(DaggerService.SERVICE_NAME, component) .build("Root"); } @dagger.Component(modules = Module.class) @Singleton public interface Component {
// Path: sample/src/main/java/com/example/flow/mortar/DaggerService.java // public class DaggerService { // // public static final String SERVICE_NAME = DaggerService.class.getName(); // // /** // * Caller is required to know the type of the component for this context. // */ // @SuppressWarnings("unchecked") // // public static <T> T getDaggerComponent(Context context) { // return (T) context.getSystemService(SERVICE_NAME); // } // } // // Path: sample/src/main/java/com/example/flow/rest/RestClient.java // @Singleton // public class RestClient { // // private Service service; // // @Inject // public RestClient() { // // Gson gson = new GsonBuilder().create(); // // RestAdapter restAdapter = new RestAdapter.Builder() // .setLogLevel(RestAdapter.LogLevel.BASIC) // .setEndpoint("http://jsonplaceholder.typicode.com/") // .setConverter(new GsonConverter(gson)) // .build(); // // service = restAdapter.create(Service.class); // } // // public Service getService() { // return service; // } // } // Path: sample/src/main/java/com/example/flow/app/App.java import android.app.Application; import android.content.Context; import com.example.flow.BuildConfig; import com.example.flow.mortar.DaggerService; import com.example.flow.rest.RestClient; import javax.inject.Singleton; import dagger.Provides; import mortar.MortarScope; import timber.log.Timber; package com.example.flow.app; public class App extends Application { private MortarScope mortarScope; @Override public Object getSystemService(String name) { return mortarScope.hasService(name) ? mortarScope.getService(name) : super.getSystemService(name); } @Override public void onCreate() { super.onCreate(); if (BuildConfig.DEBUG) { Timber.plant(new Timber.DebugTree()); } Component component = DaggerApp_Component.builder() .module(new Module()) .build(); component.inject(this); mortarScope = MortarScope.buildRootScope() .withService(DaggerService.SERVICE_NAME, component) .build("Root"); } @dagger.Component(modules = Module.class) @Singleton public interface Component {
RestClient restClient();
lukaspili/flow-navigation
sample/src/main/java/com/example/flow/ui/view/ViewPostView.java
// Path: sample/src/main/java/com/example/flow/mortar/DaggerService.java // public class DaggerService { // // public static final String SERVICE_NAME = DaggerService.class.getName(); // // /** // * Caller is required to know the type of the component for this context. // */ // @SuppressWarnings("unchecked") // // public static <T> T getDaggerComponent(Context context) { // return (T) context.getSystemService(SERVICE_NAME); // } // } // // Path: sample/src/main/java/com/example/flow/ui/screen/ViewPostScreen.java // @Layout(R.layout.screen_view_post) // public class ViewPostScreen extends Path implements ComponentFactory<RootActivity.Component> { // // private Post post; // // public ViewPostScreen(Post post) { // this.post = post; // } // // @Override // public Object createComponent(RootActivity.Component component) { // return DaggerViewPostScreen_Component.builder() // .component(component) // .module(new Module()) // .build(); // } // // @dagger.Component(dependencies = RootActivity.Component.class, modules = Module.class) // @ScreenScope(Component.class) // public interface Component extends RootActivity.Component { // // void inject(ViewPostView view); // } // // public static class Presenter extends ViewPresenter<ViewPostView> { // // private final Post post; // // @Inject // public Presenter(Post post) { // this.post = post; // } // // @Override // protected void onLoad(Bundle savedInstanceState) { // getView().titleTextView.setText(post.getTitle()); // getView().contentTextView.setText(post.getBody()); // } // // } // // @dagger.Module // public class Module { // // @Provides // @ScreenScope(Component.class) // public Presenter providePresenter() { // return new Presenter(post); // } // } // }
import android.content.Context; import android.util.AttributeSet; import android.widget.LinearLayout; import android.widget.TextView; import com.example.flow.R; import com.example.flow.mortar.DaggerService; import com.example.flow.ui.screen.ViewPostScreen; import javax.inject.Inject; import butterknife.ButterKnife; import butterknife.InjectView;
package com.example.flow.ui.view; /** * @author Lukasz Piliszczuk <lukasz.pili@gmail.com> */ public class ViewPostView extends LinearLayout { @InjectView(R.id.title) public TextView titleTextView; @InjectView(R.id.content) public TextView contentTextView; @Inject
// Path: sample/src/main/java/com/example/flow/mortar/DaggerService.java // public class DaggerService { // // public static final String SERVICE_NAME = DaggerService.class.getName(); // // /** // * Caller is required to know the type of the component for this context. // */ // @SuppressWarnings("unchecked") // // public static <T> T getDaggerComponent(Context context) { // return (T) context.getSystemService(SERVICE_NAME); // } // } // // Path: sample/src/main/java/com/example/flow/ui/screen/ViewPostScreen.java // @Layout(R.layout.screen_view_post) // public class ViewPostScreen extends Path implements ComponentFactory<RootActivity.Component> { // // private Post post; // // public ViewPostScreen(Post post) { // this.post = post; // } // // @Override // public Object createComponent(RootActivity.Component component) { // return DaggerViewPostScreen_Component.builder() // .component(component) // .module(new Module()) // .build(); // } // // @dagger.Component(dependencies = RootActivity.Component.class, modules = Module.class) // @ScreenScope(Component.class) // public interface Component extends RootActivity.Component { // // void inject(ViewPostView view); // } // // public static class Presenter extends ViewPresenter<ViewPostView> { // // private final Post post; // // @Inject // public Presenter(Post post) { // this.post = post; // } // // @Override // protected void onLoad(Bundle savedInstanceState) { // getView().titleTextView.setText(post.getTitle()); // getView().contentTextView.setText(post.getBody()); // } // // } // // @dagger.Module // public class Module { // // @Provides // @ScreenScope(Component.class) // public Presenter providePresenter() { // return new Presenter(post); // } // } // } // Path: sample/src/main/java/com/example/flow/ui/view/ViewPostView.java import android.content.Context; import android.util.AttributeSet; import android.widget.LinearLayout; import android.widget.TextView; import com.example.flow.R; import com.example.flow.mortar.DaggerService; import com.example.flow.ui.screen.ViewPostScreen; import javax.inject.Inject; import butterknife.ButterKnife; import butterknife.InjectView; package com.example.flow.ui.view; /** * @author Lukasz Piliszczuk <lukasz.pili@gmail.com> */ public class ViewPostView extends LinearLayout { @InjectView(R.id.title) public TextView titleTextView; @InjectView(R.id.content) public TextView contentTextView; @Inject
protected ViewPostScreen.Presenter presenter;
lukaspili/flow-navigation
sample/src/main/java/com/example/flow/ui/view/ViewPostView.java
// Path: sample/src/main/java/com/example/flow/mortar/DaggerService.java // public class DaggerService { // // public static final String SERVICE_NAME = DaggerService.class.getName(); // // /** // * Caller is required to know the type of the component for this context. // */ // @SuppressWarnings("unchecked") // // public static <T> T getDaggerComponent(Context context) { // return (T) context.getSystemService(SERVICE_NAME); // } // } // // Path: sample/src/main/java/com/example/flow/ui/screen/ViewPostScreen.java // @Layout(R.layout.screen_view_post) // public class ViewPostScreen extends Path implements ComponentFactory<RootActivity.Component> { // // private Post post; // // public ViewPostScreen(Post post) { // this.post = post; // } // // @Override // public Object createComponent(RootActivity.Component component) { // return DaggerViewPostScreen_Component.builder() // .component(component) // .module(new Module()) // .build(); // } // // @dagger.Component(dependencies = RootActivity.Component.class, modules = Module.class) // @ScreenScope(Component.class) // public interface Component extends RootActivity.Component { // // void inject(ViewPostView view); // } // // public static class Presenter extends ViewPresenter<ViewPostView> { // // private final Post post; // // @Inject // public Presenter(Post post) { // this.post = post; // } // // @Override // protected void onLoad(Bundle savedInstanceState) { // getView().titleTextView.setText(post.getTitle()); // getView().contentTextView.setText(post.getBody()); // } // // } // // @dagger.Module // public class Module { // // @Provides // @ScreenScope(Component.class) // public Presenter providePresenter() { // return new Presenter(post); // } // } // }
import android.content.Context; import android.util.AttributeSet; import android.widget.LinearLayout; import android.widget.TextView; import com.example.flow.R; import com.example.flow.mortar.DaggerService; import com.example.flow.ui.screen.ViewPostScreen; import javax.inject.Inject; import butterknife.ButterKnife; import butterknife.InjectView;
package com.example.flow.ui.view; /** * @author Lukasz Piliszczuk <lukasz.pili@gmail.com> */ public class ViewPostView extends LinearLayout { @InjectView(R.id.title) public TextView titleTextView; @InjectView(R.id.content) public TextView contentTextView; @Inject protected ViewPostScreen.Presenter presenter; public ViewPostView(Context context) { super(context); init(context); } public ViewPostView(Context context, AttributeSet attrs) { super(context, attrs); init(context); } public ViewPostView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context); } protected void init(Context context) {
// Path: sample/src/main/java/com/example/flow/mortar/DaggerService.java // public class DaggerService { // // public static final String SERVICE_NAME = DaggerService.class.getName(); // // /** // * Caller is required to know the type of the component for this context. // */ // @SuppressWarnings("unchecked") // // public static <T> T getDaggerComponent(Context context) { // return (T) context.getSystemService(SERVICE_NAME); // } // } // // Path: sample/src/main/java/com/example/flow/ui/screen/ViewPostScreen.java // @Layout(R.layout.screen_view_post) // public class ViewPostScreen extends Path implements ComponentFactory<RootActivity.Component> { // // private Post post; // // public ViewPostScreen(Post post) { // this.post = post; // } // // @Override // public Object createComponent(RootActivity.Component component) { // return DaggerViewPostScreen_Component.builder() // .component(component) // .module(new Module()) // .build(); // } // // @dagger.Component(dependencies = RootActivity.Component.class, modules = Module.class) // @ScreenScope(Component.class) // public interface Component extends RootActivity.Component { // // void inject(ViewPostView view); // } // // public static class Presenter extends ViewPresenter<ViewPostView> { // // private final Post post; // // @Inject // public Presenter(Post post) { // this.post = post; // } // // @Override // protected void onLoad(Bundle savedInstanceState) { // getView().titleTextView.setText(post.getTitle()); // getView().contentTextView.setText(post.getBody()); // } // // } // // @dagger.Module // public class Module { // // @Provides // @ScreenScope(Component.class) // public Presenter providePresenter() { // return new Presenter(post); // } // } // } // Path: sample/src/main/java/com/example/flow/ui/view/ViewPostView.java import android.content.Context; import android.util.AttributeSet; import android.widget.LinearLayout; import android.widget.TextView; import com.example.flow.R; import com.example.flow.mortar.DaggerService; import com.example.flow.ui.screen.ViewPostScreen; import javax.inject.Inject; import butterknife.ButterKnife; import butterknife.InjectView; package com.example.flow.ui.view; /** * @author Lukasz Piliszczuk <lukasz.pili@gmail.com> */ public class ViewPostView extends LinearLayout { @InjectView(R.id.title) public TextView titleTextView; @InjectView(R.id.content) public TextView contentTextView; @Inject protected ViewPostScreen.Presenter presenter; public ViewPostView(Context context) { super(context); init(context); } public ViewPostView(Context context, AttributeSet attrs) { super(context, attrs); init(context); } public ViewPostView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context); } protected void init(Context context) {
((ViewPostScreen.Component) context.getSystemService(DaggerService.SERVICE_NAME)).inject(this);
lukaspili/flow-navigation
sample/src/main/java/com/example/flow/rest/Service.java
// Path: sample/src/main/java/com/example/flow/model/Post.java // public class Post { // private long id; // private long userId; // private String title; // private String body; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public long getUserId() { // return userId; // } // // public void setUserId(long userId) { // this.userId = userId; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getBody() { // return body; // } // // public void setBody(String body) { // this.body = body; // } // }
import com.example.flow.model.Post; import java.util.List; import retrofit.Callback; import retrofit.http.GET;
package com.example.flow.rest; /** * @author Lukasz Piliszczuk <lukasz.pili@gmail.com> */ public interface Service { @GET("/posts")
// Path: sample/src/main/java/com/example/flow/model/Post.java // public class Post { // private long id; // private long userId; // private String title; // private String body; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public long getUserId() { // return userId; // } // // public void setUserId(long userId) { // this.userId = userId; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getBody() { // return body; // } // // public void setBody(String body) { // this.body = body; // } // } // Path: sample/src/main/java/com/example/flow/rest/Service.java import com.example.flow.model.Post; import java.util.List; import retrofit.Callback; import retrofit.http.GET; package com.example.flow.rest; /** * @author Lukasz Piliszczuk <lukasz.pili@gmail.com> */ public interface Service { @GET("/posts")
void getPosts(Callback<List<Post>> callback);
lukaspili/flow-navigation
sample/src/main/java/com/example/flow/mortar/ScreenScoper.java
// Path: mortar-common/src/main/java/flownavigation/common/mortar/BasicScreenScoper.java // public abstract class BasicScreenScoper implements ScreenScoper { // // public MortarScope getScreenScope(Context context, String name, Path path) { // MortarScope parentScope = MortarScope.getScope(context); // Log.d(getClass().getCanonicalName(), "ScreenScoper - Screen scoper with parent " + parentScope.getName()); // // MortarScope childScope = parentScope.findChild(name); // if (childScope != null) { // Log.d(getClass().getCanonicalName(), "ScreenScoper - Screen scoper returns existing scope " + name); // return childScope; // } // // MortarScope.Builder builder = parentScope.buildChild(); // configureMortarScope(context, name, path, parentScope, builder); // // Log.d(getClass().getCanonicalName(), "ScreenScoper - Screen scoper builds and returns new scope " + name); // return builder.build(name); // } // // protected abstract void configureMortarScope(Context context, String name, Path path, MortarScope parentScope, MortarScope.Builder mortarScopeBuilder); // } // // Path: library/src/main/java/flownavigation/path/Path.java // public abstract class Path { // // static final Path ROOT = new Path() { // }; // // public static PathContextFactory contextFactory() { // return new ContextFactory(); // } // // public static PathContextFactory contextFactory(PathContextFactory delegate) { // return new ContextFactory(delegate); // } // // private static final class LocalPathWrapper extends ContextWrapper { // static final String LOCAL_WRAPPER_SERVICE = "flow_local_screen_context_wrapper"; // private LayoutInflater inflater; // // final Object localScreen; // // LocalPathWrapper(Context base, Object localScreen) { // super(base); // this.localScreen = localScreen; // } // // @Override // public Object getSystemService(String name) { // if (LOCAL_WRAPPER_SERVICE.equals(name)) { // return this; // } // if (LAYOUT_INFLATER_SERVICE.equals(name)) { // if (inflater == null) { // inflater = LayoutInflater.from(getBaseContext()).cloneInContext(this); // } // return inflater; // } // return super.getSystemService(name); // } // } // // private static final class ContextFactory implements PathContextFactory { // // May be null. // private final PathContextFactory delegate; // // public ContextFactory() { // delegate = null; // } // // public ContextFactory(PathContextFactory delegate) { // this.delegate = delegate; // } // // @Override // public Context setUpContext(Path path, Context parentContext) { // if (delegate != null) { // parentContext = delegate.setUpContext(path, parentContext); // } // return new LocalPathWrapper(parentContext, path); // } // // @Override // public void tearDownContext(Context context) { // if (delegate != null) { // delegate.tearDownContext(context); // } // } // } // }
import android.content.Context; import android.util.Log; import flownavigation.common.mortar.BasicScreenScoper; import flownavigation.path.Path; import mortar.MortarScope;
package com.example.flow.mortar; /** * @author Lukasz Piliszczuk - lukasz.pili@gmail.com */ public class ScreenScoper extends BasicScreenScoper { @Override
// Path: mortar-common/src/main/java/flownavigation/common/mortar/BasicScreenScoper.java // public abstract class BasicScreenScoper implements ScreenScoper { // // public MortarScope getScreenScope(Context context, String name, Path path) { // MortarScope parentScope = MortarScope.getScope(context); // Log.d(getClass().getCanonicalName(), "ScreenScoper - Screen scoper with parent " + parentScope.getName()); // // MortarScope childScope = parentScope.findChild(name); // if (childScope != null) { // Log.d(getClass().getCanonicalName(), "ScreenScoper - Screen scoper returns existing scope " + name); // return childScope; // } // // MortarScope.Builder builder = parentScope.buildChild(); // configureMortarScope(context, name, path, parentScope, builder); // // Log.d(getClass().getCanonicalName(), "ScreenScoper - Screen scoper builds and returns new scope " + name); // return builder.build(name); // } // // protected abstract void configureMortarScope(Context context, String name, Path path, MortarScope parentScope, MortarScope.Builder mortarScopeBuilder); // } // // Path: library/src/main/java/flownavigation/path/Path.java // public abstract class Path { // // static final Path ROOT = new Path() { // }; // // public static PathContextFactory contextFactory() { // return new ContextFactory(); // } // // public static PathContextFactory contextFactory(PathContextFactory delegate) { // return new ContextFactory(delegate); // } // // private static final class LocalPathWrapper extends ContextWrapper { // static final String LOCAL_WRAPPER_SERVICE = "flow_local_screen_context_wrapper"; // private LayoutInflater inflater; // // final Object localScreen; // // LocalPathWrapper(Context base, Object localScreen) { // super(base); // this.localScreen = localScreen; // } // // @Override // public Object getSystemService(String name) { // if (LOCAL_WRAPPER_SERVICE.equals(name)) { // return this; // } // if (LAYOUT_INFLATER_SERVICE.equals(name)) { // if (inflater == null) { // inflater = LayoutInflater.from(getBaseContext()).cloneInContext(this); // } // return inflater; // } // return super.getSystemService(name); // } // } // // private static final class ContextFactory implements PathContextFactory { // // May be null. // private final PathContextFactory delegate; // // public ContextFactory() { // delegate = null; // } // // public ContextFactory(PathContextFactory delegate) { // this.delegate = delegate; // } // // @Override // public Context setUpContext(Path path, Context parentContext) { // if (delegate != null) { // parentContext = delegate.setUpContext(path, parentContext); // } // return new LocalPathWrapper(parentContext, path); // } // // @Override // public void tearDownContext(Context context) { // if (delegate != null) { // delegate.tearDownContext(context); // } // } // } // } // Path: sample/src/main/java/com/example/flow/mortar/ScreenScoper.java import android.content.Context; import android.util.Log; import flownavigation.common.mortar.BasicScreenScoper; import flownavigation.path.Path; import mortar.MortarScope; package com.example.flow.mortar; /** * @author Lukasz Piliszczuk - lukasz.pili@gmail.com */ public class ScreenScoper extends BasicScreenScoper { @Override
protected void configureMortarScope(Context context, String name, Path path, MortarScope parentScope, MortarScope.Builder mortarScopeBuilder) {
TPPIDev/TPPI-Tweaks
src/main/java/tppitweaks/creativeTab/CreativeTabTPPI.java
// Path: src/main/java/tppitweaks/item/ModItems.java // public class ModItems // { // public static TPPIMaterial tppiMaterial; // // public static void initItems() // { // tppiMaterial = new TPPIMaterial(); // GameRegistry.registerItem(tppiMaterial, "tppiMaterial"); // } // // public static void registerRecipes() // { // if (Loader.isModLoaded("appliedenergistics2") && Loader.isModLoaded("StevesFactoryManager") && ConfigurationHandler.tweakSFM) { // /* @formatter:off */ // GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(tppiMaterial, 1, 0), // "CdC", // "dsd", // "CdC", // // 'C', new ItemStack(GameRegistry.findItem("appliedenergistics2", "item.ItemMultiMaterial"), 1, 23), // 's', "itemSilicon", // 'd', new ItemStack(GameRegistry.findItem("appliedenergistics2", "item.ItemMultiMaterial"), 1, 8) // )); // /* @formatter:on */ // } // // /* --Commented out in case item is needed for future tweak // if (Loader.isModLoaded("ThermalExpansion") // { // ThermalExpansionHelper.addTransposerFill(12000, new ItemStack(GameRegistry.findItem("ThermalFoundation", "material"), 1, 76), new ItemStack(ModItems.tppiMaterial, 1, 4), new FluidStack(FluidRegistry.getFluid("pyrotheum"), 1000), false); // } // */ // } // } // // Path: src/main/java/tppitweaks/lib/Reference.java // public class Reference { // public static final String CHANNEL = "tppitweaks"; // public static final String TAB_NAME = "tabTPPI"; // // public static File modsFolder; // // public static final String DEPENDENCIES = // "before:ThaumicTinkerer;" // + "after:Thaumcraft;" // + "after:TwilightForest;" // + "after:AppliedEnergistics;" // + "after:StevesFactoryManager;" // + "after:DimensionalAnchors;" // + "after:ThermalExpansion;" // + "after:ExtraUtilities;" // + "after:EnderStorage;" // + "after:BigReactors;" // + "after:BuildCraft|Core;" // + "after:Mekanism;" // + "after:xreliquary;" // + "after:NotEnoughItems;" // + "after:Railcraft;" // + "after:IC2;" // + "after:MineFactoryReloaded;" // + "after:JABBA;" // + "after:EnderIO;" // + "required-after:recipetweakingcore"; // // public static String packName = "Test Pack Please Ignore"; // public static String packVersion = "0.2.2"; // public static String packAcronym = "TPPI"; // }
import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import tppitweaks.item.ModItems; import tppitweaks.lib.Reference;
package tppitweaks.creativeTab; public class CreativeTabTPPI extends CreativeTabs { public CreativeTabTPPI(int id) {
// Path: src/main/java/tppitweaks/item/ModItems.java // public class ModItems // { // public static TPPIMaterial tppiMaterial; // // public static void initItems() // { // tppiMaterial = new TPPIMaterial(); // GameRegistry.registerItem(tppiMaterial, "tppiMaterial"); // } // // public static void registerRecipes() // { // if (Loader.isModLoaded("appliedenergistics2") && Loader.isModLoaded("StevesFactoryManager") && ConfigurationHandler.tweakSFM) { // /* @formatter:off */ // GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(tppiMaterial, 1, 0), // "CdC", // "dsd", // "CdC", // // 'C', new ItemStack(GameRegistry.findItem("appliedenergistics2", "item.ItemMultiMaterial"), 1, 23), // 's', "itemSilicon", // 'd', new ItemStack(GameRegistry.findItem("appliedenergistics2", "item.ItemMultiMaterial"), 1, 8) // )); // /* @formatter:on */ // } // // /* --Commented out in case item is needed for future tweak // if (Loader.isModLoaded("ThermalExpansion") // { // ThermalExpansionHelper.addTransposerFill(12000, new ItemStack(GameRegistry.findItem("ThermalFoundation", "material"), 1, 76), new ItemStack(ModItems.tppiMaterial, 1, 4), new FluidStack(FluidRegistry.getFluid("pyrotheum"), 1000), false); // } // */ // } // } // // Path: src/main/java/tppitweaks/lib/Reference.java // public class Reference { // public static final String CHANNEL = "tppitweaks"; // public static final String TAB_NAME = "tabTPPI"; // // public static File modsFolder; // // public static final String DEPENDENCIES = // "before:ThaumicTinkerer;" // + "after:Thaumcraft;" // + "after:TwilightForest;" // + "after:AppliedEnergistics;" // + "after:StevesFactoryManager;" // + "after:DimensionalAnchors;" // + "after:ThermalExpansion;" // + "after:ExtraUtilities;" // + "after:EnderStorage;" // + "after:BigReactors;" // + "after:BuildCraft|Core;" // + "after:Mekanism;" // + "after:xreliquary;" // + "after:NotEnoughItems;" // + "after:Railcraft;" // + "after:IC2;" // + "after:MineFactoryReloaded;" // + "after:JABBA;" // + "after:EnderIO;" // + "required-after:recipetweakingcore"; // // public static String packName = "Test Pack Please Ignore"; // public static String packVersion = "0.2.2"; // public static String packAcronym = "TPPI"; // } // Path: src/main/java/tppitweaks/creativeTab/CreativeTabTPPI.java import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import tppitweaks.item.ModItems; import tppitweaks.lib.Reference; package tppitweaks.creativeTab; public class CreativeTabTPPI extends CreativeTabs { public CreativeTabTPPI(int id) {
super(id, Reference.TAB_NAME);
TPPIDev/TPPI-Tweaks
src/main/java/tppitweaks/creativeTab/CreativeTabTPPI.java
// Path: src/main/java/tppitweaks/item/ModItems.java // public class ModItems // { // public static TPPIMaterial tppiMaterial; // // public static void initItems() // { // tppiMaterial = new TPPIMaterial(); // GameRegistry.registerItem(tppiMaterial, "tppiMaterial"); // } // // public static void registerRecipes() // { // if (Loader.isModLoaded("appliedenergistics2") && Loader.isModLoaded("StevesFactoryManager") && ConfigurationHandler.tweakSFM) { // /* @formatter:off */ // GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(tppiMaterial, 1, 0), // "CdC", // "dsd", // "CdC", // // 'C', new ItemStack(GameRegistry.findItem("appliedenergistics2", "item.ItemMultiMaterial"), 1, 23), // 's', "itemSilicon", // 'd', new ItemStack(GameRegistry.findItem("appliedenergistics2", "item.ItemMultiMaterial"), 1, 8) // )); // /* @formatter:on */ // } // // /* --Commented out in case item is needed for future tweak // if (Loader.isModLoaded("ThermalExpansion") // { // ThermalExpansionHelper.addTransposerFill(12000, new ItemStack(GameRegistry.findItem("ThermalFoundation", "material"), 1, 76), new ItemStack(ModItems.tppiMaterial, 1, 4), new FluidStack(FluidRegistry.getFluid("pyrotheum"), 1000), false); // } // */ // } // } // // Path: src/main/java/tppitweaks/lib/Reference.java // public class Reference { // public static final String CHANNEL = "tppitweaks"; // public static final String TAB_NAME = "tabTPPI"; // // public static File modsFolder; // // public static final String DEPENDENCIES = // "before:ThaumicTinkerer;" // + "after:Thaumcraft;" // + "after:TwilightForest;" // + "after:AppliedEnergistics;" // + "after:StevesFactoryManager;" // + "after:DimensionalAnchors;" // + "after:ThermalExpansion;" // + "after:ExtraUtilities;" // + "after:EnderStorage;" // + "after:BigReactors;" // + "after:BuildCraft|Core;" // + "after:Mekanism;" // + "after:xreliquary;" // + "after:NotEnoughItems;" // + "after:Railcraft;" // + "after:IC2;" // + "after:MineFactoryReloaded;" // + "after:JABBA;" // + "after:EnderIO;" // + "required-after:recipetweakingcore"; // // public static String packName = "Test Pack Please Ignore"; // public static String packVersion = "0.2.2"; // public static String packAcronym = "TPPI"; // }
import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import tppitweaks.item.ModItems; import tppitweaks.lib.Reference;
package tppitweaks.creativeTab; public class CreativeTabTPPI extends CreativeTabs { public CreativeTabTPPI(int id) { super(id, Reference.TAB_NAME); } @Override public ItemStack getIconItemStack() {
// Path: src/main/java/tppitweaks/item/ModItems.java // public class ModItems // { // public static TPPIMaterial tppiMaterial; // // public static void initItems() // { // tppiMaterial = new TPPIMaterial(); // GameRegistry.registerItem(tppiMaterial, "tppiMaterial"); // } // // public static void registerRecipes() // { // if (Loader.isModLoaded("appliedenergistics2") && Loader.isModLoaded("StevesFactoryManager") && ConfigurationHandler.tweakSFM) { // /* @formatter:off */ // GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(tppiMaterial, 1, 0), // "CdC", // "dsd", // "CdC", // // 'C', new ItemStack(GameRegistry.findItem("appliedenergistics2", "item.ItemMultiMaterial"), 1, 23), // 's', "itemSilicon", // 'd', new ItemStack(GameRegistry.findItem("appliedenergistics2", "item.ItemMultiMaterial"), 1, 8) // )); // /* @formatter:on */ // } // // /* --Commented out in case item is needed for future tweak // if (Loader.isModLoaded("ThermalExpansion") // { // ThermalExpansionHelper.addTransposerFill(12000, new ItemStack(GameRegistry.findItem("ThermalFoundation", "material"), 1, 76), new ItemStack(ModItems.tppiMaterial, 1, 4), new FluidStack(FluidRegistry.getFluid("pyrotheum"), 1000), false); // } // */ // } // } // // Path: src/main/java/tppitweaks/lib/Reference.java // public class Reference { // public static final String CHANNEL = "tppitweaks"; // public static final String TAB_NAME = "tabTPPI"; // // public static File modsFolder; // // public static final String DEPENDENCIES = // "before:ThaumicTinkerer;" // + "after:Thaumcraft;" // + "after:TwilightForest;" // + "after:AppliedEnergistics;" // + "after:StevesFactoryManager;" // + "after:DimensionalAnchors;" // + "after:ThermalExpansion;" // + "after:ExtraUtilities;" // + "after:EnderStorage;" // + "after:BigReactors;" // + "after:BuildCraft|Core;" // + "after:Mekanism;" // + "after:xreliquary;" // + "after:NotEnoughItems;" // + "after:Railcraft;" // + "after:IC2;" // + "after:MineFactoryReloaded;" // + "after:JABBA;" // + "after:EnderIO;" // + "required-after:recipetweakingcore"; // // public static String packName = "Test Pack Please Ignore"; // public static String packVersion = "0.2.2"; // public static String packAcronym = "TPPI"; // } // Path: src/main/java/tppitweaks/creativeTab/CreativeTabTPPI.java import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import tppitweaks.item.ModItems; import tppitweaks.lib.Reference; package tppitweaks.creativeTab; public class CreativeTabTPPI extends CreativeTabs { public CreativeTabTPPI(int id) { super(id, Reference.TAB_NAME); } @Override public ItemStack getIconItemStack() {
return new ItemStack(ModItems.tppiMaterial, 1, 1);
TPPIDev/TPPI-Tweaks
src/main/java/tppitweaks/util/TPPITweaksUtils.java
// Path: src/main/java/tppitweaks/TPPITweaks.java // @Mod(modid = "TPPITweaks", name = "TPPI Tweaks", version = TPPITweaks.VERSION, dependencies = Reference.DEPENDENCIES) // public class TPPITweaks // { // public static final String VERSION = "@VERSION@"; // // @Instance("TPPITweaks") // public static TPPITweaks instance; // // @SidedProxy(clientSide = "tppitweaks.proxy.ClientProxy", serverSide = "tppitweaks.proxy.CommonProxy") // public static CommonProxy proxy; // // public static TPPIEventHandler eventHandler; // // public static final Logger logger = LogManager.getLogger("TPPITweaks"); // // public static CreativeTabTPPI creativeTab = new CreativeTabTPPI(CreativeTabs.getNextID()); // // @EventHandler // public void preInit(FMLPreInitializationEvent event) // { // RecipeTweakingCore.registerPackageName("tppitweaks.tweak.recipe"); // // ConfigurationHandler.init(new File(event.getModConfigurationDirectory().getAbsolutePath() + "/TPPI/TPPITweaks.cfg")); // } // // @EventHandler // public void init(FMLInitializationEvent event) // { // // AM2SpawnControls.doAM2SpawnControls(); // // ModItems.initItems(); // ModBlocks.initBlocks(); // // eventHandler = new TPPIEventHandler(); // MinecraftForge.EVENT_BUS.register(eventHandler); // ModItems.registerRecipes(); // ModBlocks.registerRecipes(); // // if (event.getSide().isClient()) // proxy.initTickHandler(); // // if (Loader.isModLoaded("Thaumcraft")) // TweakVanilla.init(); // } // // @EventHandler // public void postInit(FMLPostInitializationEvent event) // { // AdditionalTweaks.doOreDictTweaks(); // AdditionalTweaks.addMiscRecipes(); // } // // @EventHandler // public void onFMLServerStart(FMLServerStartingEvent event) // { // event.registerServerCommand(new CommandOres()); // event.registerServerCommand(new CommandGetInvolved()); // } // } // // Path: src/main/java/tppitweaks/lib/Reference.java // public class Reference { // public static final String CHANNEL = "tppitweaks"; // public static final String TAB_NAME = "tabTPPI"; // // public static File modsFolder; // // public static final String DEPENDENCIES = // "before:ThaumicTinkerer;" // + "after:Thaumcraft;" // + "after:TwilightForest;" // + "after:AppliedEnergistics;" // + "after:StevesFactoryManager;" // + "after:DimensionalAnchors;" // + "after:ThermalExpansion;" // + "after:ExtraUtilities;" // + "after:EnderStorage;" // + "after:BigReactors;" // + "after:BuildCraft|Core;" // + "after:Mekanism;" // + "after:xreliquary;" // + "after:NotEnoughItems;" // + "after:Railcraft;" // + "after:IC2;" // + "after:MineFactoryReloaded;" // + "after:JABBA;" // + "after:EnderIO;" // + "required-after:recipetweakingcore"; // // public static String packName = "Test Pack Please Ignore"; // public static String packVersion = "0.2.2"; // public static String packAcronym = "TPPI"; // }
import java.io.File; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import net.minecraft.util.ResourceLocation; import net.minecraftforge.common.util.ForgeDirection; import tppitweaks.TPPITweaks; import tppitweaks.lib.Reference;
public static enum ResourceType { GUI("gui"), GUI_ELEMENT("gui/elements"), SOUND("sound"), RENDER("render"), TEXTURE_BLOCKS("textures/blocks"), TEXTURE_ITEMS("textures/items"), MODEL("models"), INFUSE("infuse"); private String prefix; private ResourceType(String s) { prefix = s; } public String getPrefix() { return prefix + "/"; } } public static boolean disableMod(String partOfName, String extension) { boolean hasChanged = false; for (File f : getMods(partOfName)) {
// Path: src/main/java/tppitweaks/TPPITweaks.java // @Mod(modid = "TPPITweaks", name = "TPPI Tweaks", version = TPPITweaks.VERSION, dependencies = Reference.DEPENDENCIES) // public class TPPITweaks // { // public static final String VERSION = "@VERSION@"; // // @Instance("TPPITweaks") // public static TPPITweaks instance; // // @SidedProxy(clientSide = "tppitweaks.proxy.ClientProxy", serverSide = "tppitweaks.proxy.CommonProxy") // public static CommonProxy proxy; // // public static TPPIEventHandler eventHandler; // // public static final Logger logger = LogManager.getLogger("TPPITweaks"); // // public static CreativeTabTPPI creativeTab = new CreativeTabTPPI(CreativeTabs.getNextID()); // // @EventHandler // public void preInit(FMLPreInitializationEvent event) // { // RecipeTweakingCore.registerPackageName("tppitweaks.tweak.recipe"); // // ConfigurationHandler.init(new File(event.getModConfigurationDirectory().getAbsolutePath() + "/TPPI/TPPITweaks.cfg")); // } // // @EventHandler // public void init(FMLInitializationEvent event) // { // // AM2SpawnControls.doAM2SpawnControls(); // // ModItems.initItems(); // ModBlocks.initBlocks(); // // eventHandler = new TPPIEventHandler(); // MinecraftForge.EVENT_BUS.register(eventHandler); // ModItems.registerRecipes(); // ModBlocks.registerRecipes(); // // if (event.getSide().isClient()) // proxy.initTickHandler(); // // if (Loader.isModLoaded("Thaumcraft")) // TweakVanilla.init(); // } // // @EventHandler // public void postInit(FMLPostInitializationEvent event) // { // AdditionalTweaks.doOreDictTweaks(); // AdditionalTweaks.addMiscRecipes(); // } // // @EventHandler // public void onFMLServerStart(FMLServerStartingEvent event) // { // event.registerServerCommand(new CommandOres()); // event.registerServerCommand(new CommandGetInvolved()); // } // } // // Path: src/main/java/tppitweaks/lib/Reference.java // public class Reference { // public static final String CHANNEL = "tppitweaks"; // public static final String TAB_NAME = "tabTPPI"; // // public static File modsFolder; // // public static final String DEPENDENCIES = // "before:ThaumicTinkerer;" // + "after:Thaumcraft;" // + "after:TwilightForest;" // + "after:AppliedEnergistics;" // + "after:StevesFactoryManager;" // + "after:DimensionalAnchors;" // + "after:ThermalExpansion;" // + "after:ExtraUtilities;" // + "after:EnderStorage;" // + "after:BigReactors;" // + "after:BuildCraft|Core;" // + "after:Mekanism;" // + "after:xreliquary;" // + "after:NotEnoughItems;" // + "after:Railcraft;" // + "after:IC2;" // + "after:MineFactoryReloaded;" // + "after:JABBA;" // + "after:EnderIO;" // + "required-after:recipetweakingcore"; // // public static String packName = "Test Pack Please Ignore"; // public static String packVersion = "0.2.2"; // public static String packAcronym = "TPPI"; // } // Path: src/main/java/tppitweaks/util/TPPITweaksUtils.java import java.io.File; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import net.minecraft.util.ResourceLocation; import net.minecraftforge.common.util.ForgeDirection; import tppitweaks.TPPITweaks; import tppitweaks.lib.Reference; public static enum ResourceType { GUI("gui"), GUI_ELEMENT("gui/elements"), SOUND("sound"), RENDER("render"), TEXTURE_BLOCKS("textures/blocks"), TEXTURE_ITEMS("textures/items"), MODEL("models"), INFUSE("infuse"); private String prefix; private ResourceType(String s) { prefix = s; } public String getPrefix() { return prefix + "/"; } } public static boolean disableMod(String partOfName, String extension) { boolean hasChanged = false; for (File f : getMods(partOfName)) {
TPPITweaks.logger.info("Disabling: " + f.getName());
TPPIDev/TPPI-Tweaks
src/main/java/tppitweaks/util/TPPITweaksUtils.java
// Path: src/main/java/tppitweaks/TPPITweaks.java // @Mod(modid = "TPPITweaks", name = "TPPI Tweaks", version = TPPITweaks.VERSION, dependencies = Reference.DEPENDENCIES) // public class TPPITweaks // { // public static final String VERSION = "@VERSION@"; // // @Instance("TPPITweaks") // public static TPPITweaks instance; // // @SidedProxy(clientSide = "tppitweaks.proxy.ClientProxy", serverSide = "tppitweaks.proxy.CommonProxy") // public static CommonProxy proxy; // // public static TPPIEventHandler eventHandler; // // public static final Logger logger = LogManager.getLogger("TPPITweaks"); // // public static CreativeTabTPPI creativeTab = new CreativeTabTPPI(CreativeTabs.getNextID()); // // @EventHandler // public void preInit(FMLPreInitializationEvent event) // { // RecipeTweakingCore.registerPackageName("tppitweaks.tweak.recipe"); // // ConfigurationHandler.init(new File(event.getModConfigurationDirectory().getAbsolutePath() + "/TPPI/TPPITweaks.cfg")); // } // // @EventHandler // public void init(FMLInitializationEvent event) // { // // AM2SpawnControls.doAM2SpawnControls(); // // ModItems.initItems(); // ModBlocks.initBlocks(); // // eventHandler = new TPPIEventHandler(); // MinecraftForge.EVENT_BUS.register(eventHandler); // ModItems.registerRecipes(); // ModBlocks.registerRecipes(); // // if (event.getSide().isClient()) // proxy.initTickHandler(); // // if (Loader.isModLoaded("Thaumcraft")) // TweakVanilla.init(); // } // // @EventHandler // public void postInit(FMLPostInitializationEvent event) // { // AdditionalTweaks.doOreDictTweaks(); // AdditionalTweaks.addMiscRecipes(); // } // // @EventHandler // public void onFMLServerStart(FMLServerStartingEvent event) // { // event.registerServerCommand(new CommandOres()); // event.registerServerCommand(new CommandGetInvolved()); // } // } // // Path: src/main/java/tppitweaks/lib/Reference.java // public class Reference { // public static final String CHANNEL = "tppitweaks"; // public static final String TAB_NAME = "tabTPPI"; // // public static File modsFolder; // // public static final String DEPENDENCIES = // "before:ThaumicTinkerer;" // + "after:Thaumcraft;" // + "after:TwilightForest;" // + "after:AppliedEnergistics;" // + "after:StevesFactoryManager;" // + "after:DimensionalAnchors;" // + "after:ThermalExpansion;" // + "after:ExtraUtilities;" // + "after:EnderStorage;" // + "after:BigReactors;" // + "after:BuildCraft|Core;" // + "after:Mekanism;" // + "after:xreliquary;" // + "after:NotEnoughItems;" // + "after:Railcraft;" // + "after:IC2;" // + "after:MineFactoryReloaded;" // + "after:JABBA;" // + "after:EnderIO;" // + "required-after:recipetweakingcore"; // // public static String packName = "Test Pack Please Ignore"; // public static String packVersion = "0.2.2"; // public static String packAcronym = "TPPI"; // }
import java.io.File; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import net.minecraft.util.ResourceLocation; import net.minecraftforge.common.util.ForgeDirection; import tppitweaks.TPPITweaks; import tppitweaks.lib.Reference;
public static boolean enableMod(String partOfName, String extensionToRemove) { boolean hasChanged = false; for (File f : getMods(partOfName)) { TPPITweaks.logger.info("Enabling: " + f.getName()); if (f.getName().contains(extensionToRemove)) { f.renameTo(new File(f.getAbsolutePath().replace(extensionToRemove, ""))); hasChanged = true; } else { TPPITweaks.logger.info(partOfName + " was already enabled!"); } } return hasChanged; } /** * Finds all mods that contain the passed string in their filename that exist in the /mods folder * * @return A list of Files that are mod jars (or zips) */ public static ArrayList<File> getMods(String partOfName) { ArrayList<File> files = new ArrayList<File>(); File mods;
// Path: src/main/java/tppitweaks/TPPITweaks.java // @Mod(modid = "TPPITweaks", name = "TPPI Tweaks", version = TPPITweaks.VERSION, dependencies = Reference.DEPENDENCIES) // public class TPPITweaks // { // public static final String VERSION = "@VERSION@"; // // @Instance("TPPITweaks") // public static TPPITweaks instance; // // @SidedProxy(clientSide = "tppitweaks.proxy.ClientProxy", serverSide = "tppitweaks.proxy.CommonProxy") // public static CommonProxy proxy; // // public static TPPIEventHandler eventHandler; // // public static final Logger logger = LogManager.getLogger("TPPITweaks"); // // public static CreativeTabTPPI creativeTab = new CreativeTabTPPI(CreativeTabs.getNextID()); // // @EventHandler // public void preInit(FMLPreInitializationEvent event) // { // RecipeTweakingCore.registerPackageName("tppitweaks.tweak.recipe"); // // ConfigurationHandler.init(new File(event.getModConfigurationDirectory().getAbsolutePath() + "/TPPI/TPPITweaks.cfg")); // } // // @EventHandler // public void init(FMLInitializationEvent event) // { // // AM2SpawnControls.doAM2SpawnControls(); // // ModItems.initItems(); // ModBlocks.initBlocks(); // // eventHandler = new TPPIEventHandler(); // MinecraftForge.EVENT_BUS.register(eventHandler); // ModItems.registerRecipes(); // ModBlocks.registerRecipes(); // // if (event.getSide().isClient()) // proxy.initTickHandler(); // // if (Loader.isModLoaded("Thaumcraft")) // TweakVanilla.init(); // } // // @EventHandler // public void postInit(FMLPostInitializationEvent event) // { // AdditionalTweaks.doOreDictTweaks(); // AdditionalTweaks.addMiscRecipes(); // } // // @EventHandler // public void onFMLServerStart(FMLServerStartingEvent event) // { // event.registerServerCommand(new CommandOres()); // event.registerServerCommand(new CommandGetInvolved()); // } // } // // Path: src/main/java/tppitweaks/lib/Reference.java // public class Reference { // public static final String CHANNEL = "tppitweaks"; // public static final String TAB_NAME = "tabTPPI"; // // public static File modsFolder; // // public static final String DEPENDENCIES = // "before:ThaumicTinkerer;" // + "after:Thaumcraft;" // + "after:TwilightForest;" // + "after:AppliedEnergistics;" // + "after:StevesFactoryManager;" // + "after:DimensionalAnchors;" // + "after:ThermalExpansion;" // + "after:ExtraUtilities;" // + "after:EnderStorage;" // + "after:BigReactors;" // + "after:BuildCraft|Core;" // + "after:Mekanism;" // + "after:xreliquary;" // + "after:NotEnoughItems;" // + "after:Railcraft;" // + "after:IC2;" // + "after:MineFactoryReloaded;" // + "after:JABBA;" // + "after:EnderIO;" // + "required-after:recipetweakingcore"; // // public static String packName = "Test Pack Please Ignore"; // public static String packVersion = "0.2.2"; // public static String packAcronym = "TPPI"; // } // Path: src/main/java/tppitweaks/util/TPPITweaksUtils.java import java.io.File; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import net.minecraft.util.ResourceLocation; import net.minecraftforge.common.util.ForgeDirection; import tppitweaks.TPPITweaks; import tppitweaks.lib.Reference; public static boolean enableMod(String partOfName, String extensionToRemove) { boolean hasChanged = false; for (File f : getMods(partOfName)) { TPPITweaks.logger.info("Enabling: " + f.getName()); if (f.getName().contains(extensionToRemove)) { f.renameTo(new File(f.getAbsolutePath().replace(extensionToRemove, ""))); hasChanged = true; } else { TPPITweaks.logger.info(partOfName + " was already enabled!"); } } return hasChanged; } /** * Finds all mods that contain the passed string in their filename that exist in the /mods folder * * @return A list of Files that are mod jars (or zips) */ public static ArrayList<File> getMods(String partOfName) { ArrayList<File> files = new ArrayList<File>(); File mods;
mods = Reference.modsFolder;
TPPIDev/TPPI-Tweaks
src/main/java/tppitweaks/block/TPPIBlock.java
// Path: src/main/java/tppitweaks/TPPITweaks.java // @Mod(modid = "TPPITweaks", name = "TPPI Tweaks", version = TPPITweaks.VERSION, dependencies = Reference.DEPENDENCIES) // public class TPPITweaks // { // public static final String VERSION = "@VERSION@"; // // @Instance("TPPITweaks") // public static TPPITweaks instance; // // @SidedProxy(clientSide = "tppitweaks.proxy.ClientProxy", serverSide = "tppitweaks.proxy.CommonProxy") // public static CommonProxy proxy; // // public static TPPIEventHandler eventHandler; // // public static final Logger logger = LogManager.getLogger("TPPITweaks"); // // public static CreativeTabTPPI creativeTab = new CreativeTabTPPI(CreativeTabs.getNextID()); // // @EventHandler // public void preInit(FMLPreInitializationEvent event) // { // RecipeTweakingCore.registerPackageName("tppitweaks.tweak.recipe"); // // ConfigurationHandler.init(new File(event.getModConfigurationDirectory().getAbsolutePath() + "/TPPI/TPPITweaks.cfg")); // } // // @EventHandler // public void init(FMLInitializationEvent event) // { // // AM2SpawnControls.doAM2SpawnControls(); // // ModItems.initItems(); // ModBlocks.initBlocks(); // // eventHandler = new TPPIEventHandler(); // MinecraftForge.EVENT_BUS.register(eventHandler); // ModItems.registerRecipes(); // ModBlocks.registerRecipes(); // // if (event.getSide().isClient()) // proxy.initTickHandler(); // // if (Loader.isModLoaded("Thaumcraft")) // TweakVanilla.init(); // } // // @EventHandler // public void postInit(FMLPostInitializationEvent event) // { // AdditionalTweaks.doOreDictTweaks(); // AdditionalTweaks.addMiscRecipes(); // } // // @EventHandler // public void onFMLServerStart(FMLServerStartingEvent event) // { // event.registerServerCommand(new CommandOres()); // event.registerServerCommand(new CommandGetInvolved()); // } // }
import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.util.IIcon; import net.minecraft.world.IBlockAccess; import tppitweaks.TPPITweaks; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly;
package tppitweaks.block; public class TPPIBlock extends Block { @SideOnly(Side.CLIENT) private IIcon icon; public TPPIBlock() { super(Material.iron); setHardness(5.0F); setResistance(10.0F); setStepSound(soundTypeMetal); setBlockName("redstoneCompressed"); setBlockTextureName("tppitweaks:redstoneCompressed");
// Path: src/main/java/tppitweaks/TPPITweaks.java // @Mod(modid = "TPPITweaks", name = "TPPI Tweaks", version = TPPITweaks.VERSION, dependencies = Reference.DEPENDENCIES) // public class TPPITweaks // { // public static final String VERSION = "@VERSION@"; // // @Instance("TPPITweaks") // public static TPPITweaks instance; // // @SidedProxy(clientSide = "tppitweaks.proxy.ClientProxy", serverSide = "tppitweaks.proxy.CommonProxy") // public static CommonProxy proxy; // // public static TPPIEventHandler eventHandler; // // public static final Logger logger = LogManager.getLogger("TPPITweaks"); // // public static CreativeTabTPPI creativeTab = new CreativeTabTPPI(CreativeTabs.getNextID()); // // @EventHandler // public void preInit(FMLPreInitializationEvent event) // { // RecipeTweakingCore.registerPackageName("tppitweaks.tweak.recipe"); // // ConfigurationHandler.init(new File(event.getModConfigurationDirectory().getAbsolutePath() + "/TPPI/TPPITweaks.cfg")); // } // // @EventHandler // public void init(FMLInitializationEvent event) // { // // AM2SpawnControls.doAM2SpawnControls(); // // ModItems.initItems(); // ModBlocks.initBlocks(); // // eventHandler = new TPPIEventHandler(); // MinecraftForge.EVENT_BUS.register(eventHandler); // ModItems.registerRecipes(); // ModBlocks.registerRecipes(); // // if (event.getSide().isClient()) // proxy.initTickHandler(); // // if (Loader.isModLoaded("Thaumcraft")) // TweakVanilla.init(); // } // // @EventHandler // public void postInit(FMLPostInitializationEvent event) // { // AdditionalTweaks.doOreDictTweaks(); // AdditionalTweaks.addMiscRecipes(); // } // // @EventHandler // public void onFMLServerStart(FMLServerStartingEvent event) // { // event.registerServerCommand(new CommandOres()); // event.registerServerCommand(new CommandGetInvolved()); // } // } // Path: src/main/java/tppitweaks/block/TPPIBlock.java import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.util.IIcon; import net.minecraft.world.IBlockAccess; import tppitweaks.TPPITweaks; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; package tppitweaks.block; public class TPPIBlock extends Block { @SideOnly(Side.CLIENT) private IIcon icon; public TPPIBlock() { super(Material.iron); setHardness(5.0F); setResistance(10.0F); setStepSound(soundTypeMetal); setBlockName("redstoneCompressed"); setBlockTextureName("tppitweaks:redstoneCompressed");
setCreativeTab(TPPITweaks.creativeTab);
TPPIDev/TPPI-Tweaks
src/main/java/tppitweaks/util/TxtParser.java
// Path: src/main/java/tppitweaks/TPPITweaks.java // @Mod(modid = "TPPITweaks", name = "TPPI Tweaks", version = TPPITweaks.VERSION, dependencies = Reference.DEPENDENCIES) // public class TPPITweaks // { // public static final String VERSION = "@VERSION@"; // // @Instance("TPPITweaks") // public static TPPITweaks instance; // // @SidedProxy(clientSide = "tppitweaks.proxy.ClientProxy", serverSide = "tppitweaks.proxy.CommonProxy") // public static CommonProxy proxy; // // public static TPPIEventHandler eventHandler; // // public static final Logger logger = LogManager.getLogger("TPPITweaks"); // // public static CreativeTabTPPI creativeTab = new CreativeTabTPPI(CreativeTabs.getNextID()); // // @EventHandler // public void preInit(FMLPreInitializationEvent event) // { // RecipeTweakingCore.registerPackageName("tppitweaks.tweak.recipe"); // // ConfigurationHandler.init(new File(event.getModConfigurationDirectory().getAbsolutePath() + "/TPPI/TPPITweaks.cfg")); // } // // @EventHandler // public void init(FMLInitializationEvent event) // { // // AM2SpawnControls.doAM2SpawnControls(); // // ModItems.initItems(); // ModBlocks.initBlocks(); // // eventHandler = new TPPIEventHandler(); // MinecraftForge.EVENT_BUS.register(eventHandler); // ModItems.registerRecipes(); // ModBlocks.registerRecipes(); // // if (event.getSide().isClient()) // proxy.initTickHandler(); // // if (Loader.isModLoaded("Thaumcraft")) // TweakVanilla.init(); // } // // @EventHandler // public void postInit(FMLPostInitializationEvent event) // { // AdditionalTweaks.doOreDictTweaks(); // AdditionalTweaks.addMiscRecipes(); // } // // @EventHandler // public void onFMLServerStart(FMLServerStartingEvent event) // { // event.registerServerCommand(new CommandOres()); // event.registerServerCommand(new CommandGetInvolved()); // } // }
import java.io.InputStream; import java.util.ArrayList; import java.util.Scanner; import tppitweaks.TPPITweaks;
String nextPage = ""; while (scanner.hasNextLine()) { String temp = scanner.nextLine(); // If the line is a comment if (temp.length() == 0 || temp.startsWith("**")) { // If the line is possibly a line-skip comment if (temp.startsWith("***")) { boolean validSkip = true; for (int i = 3; i < temp.length(); i++) if (!isANumber(temp.charAt(i))) { validSkip = false; break; } // Skip the requested amount of lines by parsing the number // after the asterisks if (validSkip) { for (int i = 0; i <= Integer.parseInt(temp.substring(3, temp.length())); i++) { scanner.nextLine(); } } else
// Path: src/main/java/tppitweaks/TPPITweaks.java // @Mod(modid = "TPPITweaks", name = "TPPI Tweaks", version = TPPITweaks.VERSION, dependencies = Reference.DEPENDENCIES) // public class TPPITweaks // { // public static final String VERSION = "@VERSION@"; // // @Instance("TPPITweaks") // public static TPPITweaks instance; // // @SidedProxy(clientSide = "tppitweaks.proxy.ClientProxy", serverSide = "tppitweaks.proxy.CommonProxy") // public static CommonProxy proxy; // // public static TPPIEventHandler eventHandler; // // public static final Logger logger = LogManager.getLogger("TPPITweaks"); // // public static CreativeTabTPPI creativeTab = new CreativeTabTPPI(CreativeTabs.getNextID()); // // @EventHandler // public void preInit(FMLPreInitializationEvent event) // { // RecipeTweakingCore.registerPackageName("tppitweaks.tweak.recipe"); // // ConfigurationHandler.init(new File(event.getModConfigurationDirectory().getAbsolutePath() + "/TPPI/TPPITweaks.cfg")); // } // // @EventHandler // public void init(FMLInitializationEvent event) // { // // AM2SpawnControls.doAM2SpawnControls(); // // ModItems.initItems(); // ModBlocks.initBlocks(); // // eventHandler = new TPPIEventHandler(); // MinecraftForge.EVENT_BUS.register(eventHandler); // ModItems.registerRecipes(); // ModBlocks.registerRecipes(); // // if (event.getSide().isClient()) // proxy.initTickHandler(); // // if (Loader.isModLoaded("Thaumcraft")) // TweakVanilla.init(); // } // // @EventHandler // public void postInit(FMLPostInitializationEvent event) // { // AdditionalTweaks.doOreDictTweaks(); // AdditionalTweaks.addMiscRecipes(); // } // // @EventHandler // public void onFMLServerStart(FMLServerStartingEvent event) // { // event.registerServerCommand(new CommandOres()); // event.registerServerCommand(new CommandGetInvolved()); // } // } // Path: src/main/java/tppitweaks/util/TxtParser.java import java.io.InputStream; import java.util.ArrayList; import java.util.Scanner; import tppitweaks.TPPITweaks; String nextPage = ""; while (scanner.hasNextLine()) { String temp = scanner.nextLine(); // If the line is a comment if (temp.length() == 0 || temp.startsWith("**")) { // If the line is possibly a line-skip comment if (temp.startsWith("***")) { boolean validSkip = true; for (int i = 3; i < temp.length(); i++) if (!isANumber(temp.charAt(i))) { validSkip = false; break; } // Skip the requested amount of lines by parsing the number // after the asterisks if (validSkip) { for (int i = 0; i <= Integer.parseInt(temp.substring(3, temp.length())); i++) { scanner.nextLine(); } } else
TPPITweaks.logger.warn("Invalid line-skip in changelog. This may not work as intended");
TPPIDev/TPPI-Tweaks
src/main/java/tppitweaks/core/CoreTransformer.java
// Path: src/main/java/tppitweaks/TPPITweaks.java // @Mod(modid = "TPPITweaks", name = "TPPI Tweaks", version = TPPITweaks.VERSION, dependencies = Reference.DEPENDENCIES) // public class TPPITweaks // { // public static final String VERSION = "@VERSION@"; // // @Instance("TPPITweaks") // public static TPPITweaks instance; // // @SidedProxy(clientSide = "tppitweaks.proxy.ClientProxy", serverSide = "tppitweaks.proxy.CommonProxy") // public static CommonProxy proxy; // // public static TPPIEventHandler eventHandler; // // public static final Logger logger = LogManager.getLogger("TPPITweaks"); // // public static CreativeTabTPPI creativeTab = new CreativeTabTPPI(CreativeTabs.getNextID()); // // @EventHandler // public void preInit(FMLPreInitializationEvent event) // { // RecipeTweakingCore.registerPackageName("tppitweaks.tweak.recipe"); // // ConfigurationHandler.init(new File(event.getModConfigurationDirectory().getAbsolutePath() + "/TPPI/TPPITweaks.cfg")); // } // // @EventHandler // public void init(FMLInitializationEvent event) // { // // AM2SpawnControls.doAM2SpawnControls(); // // ModItems.initItems(); // ModBlocks.initBlocks(); // // eventHandler = new TPPIEventHandler(); // MinecraftForge.EVENT_BUS.register(eventHandler); // ModItems.registerRecipes(); // ModBlocks.registerRecipes(); // // if (event.getSide().isClient()) // proxy.initTickHandler(); // // if (Loader.isModLoaded("Thaumcraft")) // TweakVanilla.init(); // } // // @EventHandler // public void postInit(FMLPostInitializationEvent event) // { // AdditionalTweaks.doOreDictTweaks(); // AdditionalTweaks.addMiscRecipes(); // } // // @EventHandler // public void onFMLServerStart(FMLServerStartingEvent event) // { // event.registerServerCommand(new CommandOres()); // event.registerServerCommand(new CommandGetInvolved()); // } // }
import static org.objectweb.asm.Opcodes.*; import java.util.Iterator; import net.minecraft.launchwrapper.IClassTransformer; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.Label; import org.objectweb.asm.tree.AbstractInsnNode; import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.InsnList; import org.objectweb.asm.tree.InsnNode; import org.objectweb.asm.tree.LabelNode; import org.objectweb.asm.tree.MethodInsnNode; import org.objectweb.asm.tree.MethodNode; import org.objectweb.asm.tree.VarInsnNode; import tppitweaks.TPPITweaks;
package tppitweaks.core; public class CoreTransformer implements IClassTransformer { private final String FURNACE_GEN_CLASS = "extrautils.tileentity.generator.TileEntityGeneratorFurnace"; private final String SURVIVALIST_GEN_CLASS = "extrautils.tileentity.generator.TileEntityGeneratorFurnaceSurvival"; private final String KEYSTONE_CONTAINER_CLASS = "am2.containers.ContainerKeystoneLockable"; private final String FURNACE_GEN_METHOD = "getFuelBurn"; private final String FURNACE_GEN_METHOD_DESC = "(Lnet/minecraft/item/ItemStack;)I"; private final String NEW_FURNACE_GEN_METHOD = "getFuelBurnFurnace"; private final String NEW_SURVIVALIST_GEN_METHOD = "getFuelBurnSurvivalist"; @Override public byte[] transform(String name, String transformedName, byte[] basicClass) { if (name.compareTo(FURNACE_GEN_CLASS) == 0) return transformFurnaceClass(basicClass, NEW_FURNACE_GEN_METHOD); else if (name.compareTo(SURVIVALIST_GEN_CLASS) == 0) return transformFurnaceClass(basicClass, NEW_SURVIVALIST_GEN_METHOD); else if (name.compareTo(KEYSTONE_CONTAINER_CLASS) == 0) return transformKeystoneContainer(basicClass); return basicClass; } private byte[] transformFurnaceClass(byte[] basicClass, String newMethod) {
// Path: src/main/java/tppitweaks/TPPITweaks.java // @Mod(modid = "TPPITweaks", name = "TPPI Tweaks", version = TPPITweaks.VERSION, dependencies = Reference.DEPENDENCIES) // public class TPPITweaks // { // public static final String VERSION = "@VERSION@"; // // @Instance("TPPITweaks") // public static TPPITweaks instance; // // @SidedProxy(clientSide = "tppitweaks.proxy.ClientProxy", serverSide = "tppitweaks.proxy.CommonProxy") // public static CommonProxy proxy; // // public static TPPIEventHandler eventHandler; // // public static final Logger logger = LogManager.getLogger("TPPITweaks"); // // public static CreativeTabTPPI creativeTab = new CreativeTabTPPI(CreativeTabs.getNextID()); // // @EventHandler // public void preInit(FMLPreInitializationEvent event) // { // RecipeTweakingCore.registerPackageName("tppitweaks.tweak.recipe"); // // ConfigurationHandler.init(new File(event.getModConfigurationDirectory().getAbsolutePath() + "/TPPI/TPPITweaks.cfg")); // } // // @EventHandler // public void init(FMLInitializationEvent event) // { // // AM2SpawnControls.doAM2SpawnControls(); // // ModItems.initItems(); // ModBlocks.initBlocks(); // // eventHandler = new TPPIEventHandler(); // MinecraftForge.EVENT_BUS.register(eventHandler); // ModItems.registerRecipes(); // ModBlocks.registerRecipes(); // // if (event.getSide().isClient()) // proxy.initTickHandler(); // // if (Loader.isModLoaded("Thaumcraft")) // TweakVanilla.init(); // } // // @EventHandler // public void postInit(FMLPostInitializationEvent event) // { // AdditionalTweaks.doOreDictTweaks(); // AdditionalTweaks.addMiscRecipes(); // } // // @EventHandler // public void onFMLServerStart(FMLServerStartingEvent event) // { // event.registerServerCommand(new CommandOres()); // event.registerServerCommand(new CommandGetInvolved()); // } // } // Path: src/main/java/tppitweaks/core/CoreTransformer.java import static org.objectweb.asm.Opcodes.*; import java.util.Iterator; import net.minecraft.launchwrapper.IClassTransformer; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.Label; import org.objectweb.asm.tree.AbstractInsnNode; import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.InsnList; import org.objectweb.asm.tree.InsnNode; import org.objectweb.asm.tree.LabelNode; import org.objectweb.asm.tree.MethodInsnNode; import org.objectweb.asm.tree.MethodNode; import org.objectweb.asm.tree.VarInsnNode; import tppitweaks.TPPITweaks; package tppitweaks.core; public class CoreTransformer implements IClassTransformer { private final String FURNACE_GEN_CLASS = "extrautils.tileentity.generator.TileEntityGeneratorFurnace"; private final String SURVIVALIST_GEN_CLASS = "extrautils.tileentity.generator.TileEntityGeneratorFurnaceSurvival"; private final String KEYSTONE_CONTAINER_CLASS = "am2.containers.ContainerKeystoneLockable"; private final String FURNACE_GEN_METHOD = "getFuelBurn"; private final String FURNACE_GEN_METHOD_DESC = "(Lnet/minecraft/item/ItemStack;)I"; private final String NEW_FURNACE_GEN_METHOD = "getFuelBurnFurnace"; private final String NEW_SURVIVALIST_GEN_METHOD = "getFuelBurnSurvivalist"; @Override public byte[] transform(String name, String transformedName, byte[] basicClass) { if (name.compareTo(FURNACE_GEN_CLASS) == 0) return transformFurnaceClass(basicClass, NEW_FURNACE_GEN_METHOD); else if (name.compareTo(SURVIVALIST_GEN_CLASS) == 0) return transformFurnaceClass(basicClass, NEW_SURVIVALIST_GEN_METHOD); else if (name.compareTo(KEYSTONE_CONTAINER_CLASS) == 0) return transformKeystoneContainer(basicClass); return basicClass; } private byte[] transformFurnaceClass(byte[] basicClass, String newMethod) {
TPPITweaks.logger.info("Transforming ExU Generator to method " + newMethod);
TPPIDev/TPPI-Tweaks
src/main/java/tppitweaks/core/CoreTPPITweaks.java
// Path: src/main/java/tppitweaks/lib/Reference.java // public class Reference { // public static final String CHANNEL = "tppitweaks"; // public static final String TAB_NAME = "tabTPPI"; // // public static File modsFolder; // // public static final String DEPENDENCIES = // "before:ThaumicTinkerer;" // + "after:Thaumcraft;" // + "after:TwilightForest;" // + "after:AppliedEnergistics;" // + "after:StevesFactoryManager;" // + "after:DimensionalAnchors;" // + "after:ThermalExpansion;" // + "after:ExtraUtilities;" // + "after:EnderStorage;" // + "after:BigReactors;" // + "after:BuildCraft|Core;" // + "after:Mekanism;" // + "after:xreliquary;" // + "after:NotEnoughItems;" // + "after:Railcraft;" // + "after:IC2;" // + "after:MineFactoryReloaded;" // + "after:JABBA;" // + "after:EnderIO;" // + "required-after:recipetweakingcore"; // // public static String packName = "Test Pack Please Ignore"; // public static String packVersion = "0.2.2"; // public static String packAcronym = "TPPI"; // }
import java.io.File; import java.io.IOException; import java.util.Map; import tppitweaks.lib.Reference; import cpw.mods.fml.relauncher.IFMLLoadingPlugin;
@Override public String getModContainerClass() { return null; } @Override public String getSetupClass() { return null; } @Override public void injectData(Map<String, Object> data) { System.out.println("TPPITweaks coremod, rise from your grave, we require you once more."); File mcDir = (File) data.get("mcLocation"); File modsDir = null; try { modsDir = new File(mcDir.getCanonicalPath() + "/mods/"); } catch (IOException e) { System.err.println("Mods dir does not exist. How did you mess that up?"); }
// Path: src/main/java/tppitweaks/lib/Reference.java // public class Reference { // public static final String CHANNEL = "tppitweaks"; // public static final String TAB_NAME = "tabTPPI"; // // public static File modsFolder; // // public static final String DEPENDENCIES = // "before:ThaumicTinkerer;" // + "after:Thaumcraft;" // + "after:TwilightForest;" // + "after:AppliedEnergistics;" // + "after:StevesFactoryManager;" // + "after:DimensionalAnchors;" // + "after:ThermalExpansion;" // + "after:ExtraUtilities;" // + "after:EnderStorage;" // + "after:BigReactors;" // + "after:BuildCraft|Core;" // + "after:Mekanism;" // + "after:xreliquary;" // + "after:NotEnoughItems;" // + "after:Railcraft;" // + "after:IC2;" // + "after:MineFactoryReloaded;" // + "after:JABBA;" // + "after:EnderIO;" // + "required-after:recipetweakingcore"; // // public static String packName = "Test Pack Please Ignore"; // public static String packVersion = "0.2.2"; // public static String packAcronym = "TPPI"; // } // Path: src/main/java/tppitweaks/core/CoreTPPITweaks.java import java.io.File; import java.io.IOException; import java.util.Map; import tppitweaks.lib.Reference; import cpw.mods.fml.relauncher.IFMLLoadingPlugin; @Override public String getModContainerClass() { return null; } @Override public String getSetupClass() { return null; } @Override public void injectData(Map<String, Object> data) { System.out.println("TPPITweaks coremod, rise from your grave, we require you once more."); File mcDir = (File) data.get("mcLocation"); File modsDir = null; try { modsDir = new File(mcDir.getCanonicalPath() + "/mods/"); } catch (IOException e) { System.err.println("Mods dir does not exist. How did you mess that up?"); }
Reference.modsFolder = modsDir;
TPPIDev/TPPI-Tweaks
src/main/java/tppitweaks/config/ConfigurationHandler.java
// Path: src/main/java/tppitweaks/TPPITweaks.java // @Mod(modid = "TPPITweaks", name = "TPPI Tweaks", version = TPPITweaks.VERSION, dependencies = Reference.DEPENDENCIES) // public class TPPITweaks // { // public static final String VERSION = "@VERSION@"; // // @Instance("TPPITweaks") // public static TPPITweaks instance; // // @SidedProxy(clientSide = "tppitweaks.proxy.ClientProxy", serverSide = "tppitweaks.proxy.CommonProxy") // public static CommonProxy proxy; // // public static TPPIEventHandler eventHandler; // // public static final Logger logger = LogManager.getLogger("TPPITweaks"); // // public static CreativeTabTPPI creativeTab = new CreativeTabTPPI(CreativeTabs.getNextID()); // // @EventHandler // public void preInit(FMLPreInitializationEvent event) // { // RecipeTweakingCore.registerPackageName("tppitweaks.tweak.recipe"); // // ConfigurationHandler.init(new File(event.getModConfigurationDirectory().getAbsolutePath() + "/TPPI/TPPITweaks.cfg")); // } // // @EventHandler // public void init(FMLInitializationEvent event) // { // // AM2SpawnControls.doAM2SpawnControls(); // // ModItems.initItems(); // ModBlocks.initBlocks(); // // eventHandler = new TPPIEventHandler(); // MinecraftForge.EVENT_BUS.register(eventHandler); // ModItems.registerRecipes(); // ModBlocks.registerRecipes(); // // if (event.getSide().isClient()) // proxy.initTickHandler(); // // if (Loader.isModLoaded("Thaumcraft")) // TweakVanilla.init(); // } // // @EventHandler // public void postInit(FMLPostInitializationEvent event) // { // AdditionalTweaks.doOreDictTweaks(); // AdditionalTweaks.addMiscRecipes(); // } // // @EventHandler // public void onFMLServerStart(FMLServerStartingEvent event) // { // event.registerServerCommand(new CommandOres()); // event.registerServerCommand(new CommandGetInvolved()); // } // }
import net.minecraftforge.common.config.Configuration; import tppitweaks.TPPITweaks; import java.io.*; import java.util.ArrayList; import java.util.HashMap; import java.util.Scanner;
* @return whether anything changed */ public static boolean manuallyChangeConfigValue(String filePathFromConfigFolder, String prefix, String from, String to) { File config = filePathFromConfigFolder == null ? cfg : new File(cfg.getParentFile().getParent() + "/" + filePathFromConfigFolder); boolean found = false; try { FileReader fr1 = new FileReader(config); BufferedReader read = new BufferedReader(fr1); ArrayList<String> strings = new ArrayList<String>(); while (read.ready()) { strings.add(read.readLine()); } fr1.close(); read.close(); FileWriter fw = new FileWriter(config); BufferedWriter bw = new BufferedWriter(fw); for (String s : strings) { if (!found && s.contains(prefix + "=" + from) && !s.contains("=" + to)) { s = s.replace(prefix + "=" + from, prefix + "=" + to);
// Path: src/main/java/tppitweaks/TPPITweaks.java // @Mod(modid = "TPPITweaks", name = "TPPI Tweaks", version = TPPITweaks.VERSION, dependencies = Reference.DEPENDENCIES) // public class TPPITweaks // { // public static final String VERSION = "@VERSION@"; // // @Instance("TPPITweaks") // public static TPPITweaks instance; // // @SidedProxy(clientSide = "tppitweaks.proxy.ClientProxy", serverSide = "tppitweaks.proxy.CommonProxy") // public static CommonProxy proxy; // // public static TPPIEventHandler eventHandler; // // public static final Logger logger = LogManager.getLogger("TPPITweaks"); // // public static CreativeTabTPPI creativeTab = new CreativeTabTPPI(CreativeTabs.getNextID()); // // @EventHandler // public void preInit(FMLPreInitializationEvent event) // { // RecipeTweakingCore.registerPackageName("tppitweaks.tweak.recipe"); // // ConfigurationHandler.init(new File(event.getModConfigurationDirectory().getAbsolutePath() + "/TPPI/TPPITweaks.cfg")); // } // // @EventHandler // public void init(FMLInitializationEvent event) // { // // AM2SpawnControls.doAM2SpawnControls(); // // ModItems.initItems(); // ModBlocks.initBlocks(); // // eventHandler = new TPPIEventHandler(); // MinecraftForge.EVENT_BUS.register(eventHandler); // ModItems.registerRecipes(); // ModBlocks.registerRecipes(); // // if (event.getSide().isClient()) // proxy.initTickHandler(); // // if (Loader.isModLoaded("Thaumcraft")) // TweakVanilla.init(); // } // // @EventHandler // public void postInit(FMLPostInitializationEvent event) // { // AdditionalTweaks.doOreDictTweaks(); // AdditionalTweaks.addMiscRecipes(); // } // // @EventHandler // public void onFMLServerStart(FMLServerStartingEvent event) // { // event.registerServerCommand(new CommandOres()); // event.registerServerCommand(new CommandGetInvolved()); // } // } // Path: src/main/java/tppitweaks/config/ConfigurationHandler.java import net.minecraftforge.common.config.Configuration; import tppitweaks.TPPITweaks; import java.io.*; import java.util.ArrayList; import java.util.HashMap; import java.util.Scanner; * @return whether anything changed */ public static boolean manuallyChangeConfigValue(String filePathFromConfigFolder, String prefix, String from, String to) { File config = filePathFromConfigFolder == null ? cfg : new File(cfg.getParentFile().getParent() + "/" + filePathFromConfigFolder); boolean found = false; try { FileReader fr1 = new FileReader(config); BufferedReader read = new BufferedReader(fr1); ArrayList<String> strings = new ArrayList<String>(); while (read.ready()) { strings.add(read.readLine()); } fr1.close(); read.close(); FileWriter fw = new FileWriter(config); BufferedWriter bw = new BufferedWriter(fw); for (String s : strings) { if (!found && s.contains(prefix + "=" + from) && !s.contains("=" + to)) { s = s.replace(prefix + "=" + from, prefix + "=" + to);
TPPITweaks.logger.info("Successfully changed config value " + prefix + " from " + from + " to " + to);
apache/commons-logging
src/main/java/org/apache/commons/logging/LogSource.java
// Path: src/main/java/org/apache/commons/logging/impl/NoOpLog.java // public class NoOpLog implements Log, Serializable { // // /** Serializable version identifier. */ // private static final long serialVersionUID = 561423906191706148L; // // /** Convenience constructor */ // public NoOpLog() { } // /** Base constructor */ // public NoOpLog(final String name) { } // /** Do nothing */ // @Override // public void trace(final Object message) { } // /** Do nothing */ // @Override // public void trace(final Object message, final Throwable t) { } // /** Do nothing */ // @Override // public void debug(final Object message) { } // /** Do nothing */ // @Override // public void debug(final Object message, final Throwable t) { } // /** Do nothing */ // @Override // public void info(final Object message) { } // /** Do nothing */ // @Override // public void info(final Object message, final Throwable t) { } // /** Do nothing */ // @Override // public void warn(final Object message) { } // /** Do nothing */ // @Override // public void warn(final Object message, final Throwable t) { } // /** Do nothing */ // @Override // public void error(final Object message) { } // /** Do nothing */ // @Override // public void error(final Object message, final Throwable t) { } // /** Do nothing */ // @Override // public void fatal(final Object message) { } // /** Do nothing */ // @Override // public void fatal(final Object message, final Throwable t) { } // // /** // * Debug is never enabled. // * // * @return false // */ // @Override // public final boolean isDebugEnabled() { return false; } // // /** // * Error is never enabled. // * // * @return false // */ // @Override // public final boolean isErrorEnabled() { return false; } // // /** // * Fatal is never enabled. // * // * @return false // */ // @Override // public final boolean isFatalEnabled() { return false; } // // /** // * Info is never enabled. // * // * @return false // */ // @Override // public final boolean isInfoEnabled() { return false; } // // /** // * Trace is never enabled. // * // * @return false // */ // @Override // public final boolean isTraceEnabled() { return false; } // // /** // * Warn is never enabled. // * // * @return false // */ // @Override // public final boolean isWarnEnabled() { return false; } // }
import java.lang.reflect.Constructor; import java.util.Hashtable; import org.apache.commons.logging.impl.NoOpLog;
static public Log getInstance(final Class clazz) { return getInstance(clazz.getName()); } /** * Create a new {@link Log} implementation, based on the given <i>name</i>. * <p> * The specific {@link Log} implementation returned is determined by the * value of the {@code org.apache.commons.logging.log} property. The value * of {@code org.apache.commons.logging.log} may be set to the fully specified * name of a class that implements the {@link Log} interface. This class must * also have a public constructor that takes a single {@link String} argument * (containing the <i>name</i> of the {@link Log} to be constructed. * <p> * When {@code org.apache.commons.logging.log} is not set, or when no corresponding * class can be found, this method will return a Log4JLogger if the log4j Logger * class is available in the {@link LogSource}'s classpath, or a Jdk14Logger if we * are on a JDK 1.4 or later system, or NoOpLog if neither of the above conditions is true. * * @param name the log name (or category) */ static public Log makeNewLogInstance(final String name) { Log log; try { final Object[] args = { name }; log = (Log) logImplctor.newInstance(args); } catch (final Throwable t) { log = null; } if (null == log) {
// Path: src/main/java/org/apache/commons/logging/impl/NoOpLog.java // public class NoOpLog implements Log, Serializable { // // /** Serializable version identifier. */ // private static final long serialVersionUID = 561423906191706148L; // // /** Convenience constructor */ // public NoOpLog() { } // /** Base constructor */ // public NoOpLog(final String name) { } // /** Do nothing */ // @Override // public void trace(final Object message) { } // /** Do nothing */ // @Override // public void trace(final Object message, final Throwable t) { } // /** Do nothing */ // @Override // public void debug(final Object message) { } // /** Do nothing */ // @Override // public void debug(final Object message, final Throwable t) { } // /** Do nothing */ // @Override // public void info(final Object message) { } // /** Do nothing */ // @Override // public void info(final Object message, final Throwable t) { } // /** Do nothing */ // @Override // public void warn(final Object message) { } // /** Do nothing */ // @Override // public void warn(final Object message, final Throwable t) { } // /** Do nothing */ // @Override // public void error(final Object message) { } // /** Do nothing */ // @Override // public void error(final Object message, final Throwable t) { } // /** Do nothing */ // @Override // public void fatal(final Object message) { } // /** Do nothing */ // @Override // public void fatal(final Object message, final Throwable t) { } // // /** // * Debug is never enabled. // * // * @return false // */ // @Override // public final boolean isDebugEnabled() { return false; } // // /** // * Error is never enabled. // * // * @return false // */ // @Override // public final boolean isErrorEnabled() { return false; } // // /** // * Fatal is never enabled. // * // * @return false // */ // @Override // public final boolean isFatalEnabled() { return false; } // // /** // * Info is never enabled. // * // * @return false // */ // @Override // public final boolean isInfoEnabled() { return false; } // // /** // * Trace is never enabled. // * // * @return false // */ // @Override // public final boolean isTraceEnabled() { return false; } // // /** // * Warn is never enabled. // * // * @return false // */ // @Override // public final boolean isWarnEnabled() { return false; } // } // Path: src/main/java/org/apache/commons/logging/LogSource.java import java.lang.reflect.Constructor; import java.util.Hashtable; import org.apache.commons.logging.impl.NoOpLog; static public Log getInstance(final Class clazz) { return getInstance(clazz.getName()); } /** * Create a new {@link Log} implementation, based on the given <i>name</i>. * <p> * The specific {@link Log} implementation returned is determined by the * value of the {@code org.apache.commons.logging.log} property. The value * of {@code org.apache.commons.logging.log} may be set to the fully specified * name of a class that implements the {@link Log} interface. This class must * also have a public constructor that takes a single {@link String} argument * (containing the <i>name</i> of the {@link Log} to be constructed. * <p> * When {@code org.apache.commons.logging.log} is not set, or when no corresponding * class can be found, this method will return a Log4JLogger if the log4j Logger * class is available in the {@link LogSource}'s classpath, or a Jdk14Logger if we * are on a JDK 1.4 or later system, or NoOpLog if neither of the above conditions is true. * * @param name the log name (or category) */ static public Log makeNewLogInstance(final String name) { Log log; try { final Object[] args = { name }; log = (Log) logImplctor.newInstance(args); } catch (final Throwable t) { log = null; } if (null == log) {
log = new NoOpLog(name);
ashdavies/eternity
mobile/src/main/java/io/ashdavies/eternity/firebase/MessageService.java
// Path: mobile/src/main/java/io/ashdavies/eternity/Config.java // public interface Config extends Logger.Preparable { // // boolean favouriteEnabled(); // // boolean repostEnabled(); // // interface State { // // boolean invalidated(); // // void invalidate(); // // void reset(); // } // }
import com.google.firebase.messaging.FirebaseMessagingService; import com.google.firebase.messaging.RemoteMessage; import dagger.android.AndroidInjection; import io.ashdavies.eternity.Config; import javax.inject.Inject;
package io.ashdavies.eternity.firebase; public class MessageService extends FirebaseMessagingService { private static final String KEY_INVALIDATE_CONFIG = "io.ashdavies.eternity.message.state.invalidate";
// Path: mobile/src/main/java/io/ashdavies/eternity/Config.java // public interface Config extends Logger.Preparable { // // boolean favouriteEnabled(); // // boolean repostEnabled(); // // interface State { // // boolean invalidated(); // // void invalidate(); // // void reset(); // } // } // Path: mobile/src/main/java/io/ashdavies/eternity/firebase/MessageService.java import com.google.firebase.messaging.FirebaseMessagingService; import com.google.firebase.messaging.RemoteMessage; import dagger.android.AndroidInjection; import io.ashdavies.eternity.Config; import javax.inject.Inject; package io.ashdavies.eternity.firebase; public class MessageService extends FirebaseMessagingService { private static final String KEY_INVALIDATE_CONFIG = "io.ashdavies.eternity.message.state.invalidate";
@Inject Config.State state;
ashdavies/eternity
mobile/src/main/java/io/ashdavies/eternity/chat/MessageListener.java
// Path: mobile/src/main/java/io/ashdavies/eternity/domain/Message.java // @AutoValue // @FirebaseValue // public abstract class Message { // // public abstract String uuid(); // public abstract String text(); // public abstract Author author(); // public abstract long created(); // // @Nullable // public abstract Message original(); // // public Object toFirebaseValue() { // return new AutoValue_Message.FirebaseValue(this); // } // // private static Builder builder() { // return new AutoValue_Message.Builder() // .uuid(UUID.randomUUID().toString()) // .created(System.currentTimeMillis()); // } // // public static Builder from(String text) { // return builder().text(text); // } // // public static Builder from(Message message) { // return from(message.text()).original(message); // } // // public static Message create(DataSnapshot snapshot) { // return snapshot.getValue(AutoValue_Message.FirebaseValue.class).toAutoValue(); // } // // @AutoValue.Builder // public abstract static class Builder { // // public abstract Builder uuid(String uuid); // public abstract Builder text(String text); // public abstract Builder author(Author author); // public abstract Builder created(long created); // // public abstract Builder original(@Nullable Message message); // // public abstract Message build(); // } // }
import io.ashdavies.eternity.domain.Message;
package io.ashdavies.eternity.chat; interface MessageListener { boolean favouriteEnabled();
// Path: mobile/src/main/java/io/ashdavies/eternity/domain/Message.java // @AutoValue // @FirebaseValue // public abstract class Message { // // public abstract String uuid(); // public abstract String text(); // public abstract Author author(); // public abstract long created(); // // @Nullable // public abstract Message original(); // // public Object toFirebaseValue() { // return new AutoValue_Message.FirebaseValue(this); // } // // private static Builder builder() { // return new AutoValue_Message.Builder() // .uuid(UUID.randomUUID().toString()) // .created(System.currentTimeMillis()); // } // // public static Builder from(String text) { // return builder().text(text); // } // // public static Builder from(Message message) { // return from(message.text()).original(message); // } // // public static Message create(DataSnapshot snapshot) { // return snapshot.getValue(AutoValue_Message.FirebaseValue.class).toAutoValue(); // } // // @AutoValue.Builder // public abstract static class Builder { // // public abstract Builder uuid(String uuid); // public abstract Builder text(String text); // public abstract Builder author(Author author); // public abstract Builder created(long created); // // public abstract Builder original(@Nullable Message message); // // public abstract Message build(); // } // } // Path: mobile/src/main/java/io/ashdavies/eternity/chat/MessageListener.java import io.ashdavies.eternity.domain.Message; package io.ashdavies.eternity.chat; interface MessageListener { boolean favouriteEnabled();
void favourite(Message message, boolean favourite);
ashdavies/eternity
mobile/src/main/java/io/ashdavies/eternity/signin/GoogleSignInResultSingle.java
// Path: mobile/src/main/java/io/ashdavies/eternity/google/GoogleSignInException.java // public class GoogleSignInException extends Throwable { // // private final GoogleSignInResult result; // // public GoogleSignInException(GoogleSignInResult result) { // super(result.getStatus().getStatusMessage()); // this.result = result; // } // // public GoogleSignInResult getResult() { // return result; // } // }
import android.content.Intent; import com.google.android.gms.auth.api.Auth; import com.google.android.gms.auth.api.signin.GoogleSignInAccount; import com.google.android.gms.auth.api.signin.GoogleSignInResult; import io.ashdavies.eternity.google.GoogleSignInException; import io.reactivex.Single; import io.reactivex.SingleEmitter; import io.reactivex.SingleOnSubscribe;
package io.ashdavies.eternity.signin; class GoogleSignInResultSingle implements SingleOnSubscribe<GoogleSignInAccount> { private final GoogleSignInResult result; private GoogleSignInResultSingle(GoogleSignInResult result) { this.result = result; } static Single<GoogleSignInAccount> from(Intent data) { return Single.create(new GoogleSignInResultSingle(Auth.GoogleSignInApi.getSignInResultFromIntent(data))); } @Override public void subscribe(SingleEmitter<GoogleSignInAccount> emitter) throws Exception { if (!result.isSuccess()) {
// Path: mobile/src/main/java/io/ashdavies/eternity/google/GoogleSignInException.java // public class GoogleSignInException extends Throwable { // // private final GoogleSignInResult result; // // public GoogleSignInException(GoogleSignInResult result) { // super(result.getStatus().getStatusMessage()); // this.result = result; // } // // public GoogleSignInResult getResult() { // return result; // } // } // Path: mobile/src/main/java/io/ashdavies/eternity/signin/GoogleSignInResultSingle.java import android.content.Intent; import com.google.android.gms.auth.api.Auth; import com.google.android.gms.auth.api.signin.GoogleSignInAccount; import com.google.android.gms.auth.api.signin.GoogleSignInResult; import io.ashdavies.eternity.google.GoogleSignInException; import io.reactivex.Single; import io.reactivex.SingleEmitter; import io.reactivex.SingleOnSubscribe; package io.ashdavies.eternity.signin; class GoogleSignInResultSingle implements SingleOnSubscribe<GoogleSignInAccount> { private final GoogleSignInResult result; private GoogleSignInResultSingle(GoogleSignInResult result) { this.result = result; } static Single<GoogleSignInAccount> from(Intent data) { return Single.create(new GoogleSignInResultSingle(Auth.GoogleSignInApi.getSignInResultFromIntent(data))); } @Override public void subscribe(SingleEmitter<GoogleSignInAccount> emitter) throws Exception { if (!result.isSuccess()) {
emitter.onError(new GoogleSignInException(result));
ashdavies/eternity
mobile/src/main/java/io/ashdavies/eternity/firebase/FirebaseModule.java
// Path: mobile/src/main/java/io/ashdavies/eternity/Config.java // public interface Config extends Logger.Preparable { // // boolean favouriteEnabled(); // // boolean repostEnabled(); // // interface State { // // boolean invalidated(); // // void invalidate(); // // void reset(); // } // } // // Path: mobile/src/main/java/io/ashdavies/eternity/Logger.java // public interface Logger { // // void log(String message); // // void error(Throwable throwable, Object... args); // // interface Preparable { // // void prepare(Logger logger); // } // } // // Path: mobile/src/main/java/io/ashdavies/eternity/Reporting.java // public interface Reporting { // // void log(String message, Bundle bundle); // }
import dagger.Binds; import dagger.Module; import dagger.Provides; import io.ashdavies.eternity.Config; import io.ashdavies.eternity.Logger; import io.ashdavies.eternity.Reporting; import io.ashdavies.eternity.inject.ApplicationScope;
package io.ashdavies.eternity.firebase; @Module public abstract class FirebaseModule { @Provides @ApplicationScope
// Path: mobile/src/main/java/io/ashdavies/eternity/Config.java // public interface Config extends Logger.Preparable { // // boolean favouriteEnabled(); // // boolean repostEnabled(); // // interface State { // // boolean invalidated(); // // void invalidate(); // // void reset(); // } // } // // Path: mobile/src/main/java/io/ashdavies/eternity/Logger.java // public interface Logger { // // void log(String message); // // void error(Throwable throwable, Object... args); // // interface Preparable { // // void prepare(Logger logger); // } // } // // Path: mobile/src/main/java/io/ashdavies/eternity/Reporting.java // public interface Reporting { // // void log(String message, Bundle bundle); // } // Path: mobile/src/main/java/io/ashdavies/eternity/firebase/FirebaseModule.java import dagger.Binds; import dagger.Module; import dagger.Provides; import io.ashdavies.eternity.Config; import io.ashdavies.eternity.Logger; import io.ashdavies.eternity.Reporting; import io.ashdavies.eternity.inject.ApplicationScope; package io.ashdavies.eternity.firebase; @Module public abstract class FirebaseModule { @Provides @ApplicationScope
static Config config(Config.State state) {
ashdavies/eternity
mobile/src/main/java/io/ashdavies/eternity/firebase/FirebaseModule.java
// Path: mobile/src/main/java/io/ashdavies/eternity/Config.java // public interface Config extends Logger.Preparable { // // boolean favouriteEnabled(); // // boolean repostEnabled(); // // interface State { // // boolean invalidated(); // // void invalidate(); // // void reset(); // } // } // // Path: mobile/src/main/java/io/ashdavies/eternity/Logger.java // public interface Logger { // // void log(String message); // // void error(Throwable throwable, Object... args); // // interface Preparable { // // void prepare(Logger logger); // } // } // // Path: mobile/src/main/java/io/ashdavies/eternity/Reporting.java // public interface Reporting { // // void log(String message, Bundle bundle); // }
import dagger.Binds; import dagger.Module; import dagger.Provides; import io.ashdavies.eternity.Config; import io.ashdavies.eternity.Logger; import io.ashdavies.eternity.Reporting; import io.ashdavies.eternity.inject.ApplicationScope;
package io.ashdavies.eternity.firebase; @Module public abstract class FirebaseModule { @Provides @ApplicationScope static Config config(Config.State state) { return FirebaseConfig.newInstance(state); } @Binds abstract Config.State state(ConfigStateStorage storage); @Binds
// Path: mobile/src/main/java/io/ashdavies/eternity/Config.java // public interface Config extends Logger.Preparable { // // boolean favouriteEnabled(); // // boolean repostEnabled(); // // interface State { // // boolean invalidated(); // // void invalidate(); // // void reset(); // } // } // // Path: mobile/src/main/java/io/ashdavies/eternity/Logger.java // public interface Logger { // // void log(String message); // // void error(Throwable throwable, Object... args); // // interface Preparable { // // void prepare(Logger logger); // } // } // // Path: mobile/src/main/java/io/ashdavies/eternity/Reporting.java // public interface Reporting { // // void log(String message, Bundle bundle); // } // Path: mobile/src/main/java/io/ashdavies/eternity/firebase/FirebaseModule.java import dagger.Binds; import dagger.Module; import dagger.Provides; import io.ashdavies.eternity.Config; import io.ashdavies.eternity.Logger; import io.ashdavies.eternity.Reporting; import io.ashdavies.eternity.inject.ApplicationScope; package io.ashdavies.eternity.firebase; @Module public abstract class FirebaseModule { @Provides @ApplicationScope static Config config(Config.State state) { return FirebaseConfig.newInstance(state); } @Binds abstract Config.State state(ConfigStateStorage storage); @Binds
abstract Logger logger(FirebaseLogger logger);