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
BladeRunnerJS/brjs
brjs-core/src/main/java/org/bladerunnerjs/utility/BundleSetBuilder.java
// Path: brjs-core/src/main/java/org/bladerunnerjs/api/LinkedAsset.java // public interface LinkedAsset extends Asset { // /** // * Returns a list of files this LinkedAssetFile depends on // * @param bundlableNode TODO // * @throws ModelOperationException for any exception when calculating dependencies and resolving require paths // * @return The list of assets // */ // List<Asset> getDependentAssets(BundlableNode bundlableNode) throws ModelOperationException; // // /** // * BRJS calculates dependencies implicitly for additional {@link Asset}s found by plugins, for example, a JavaScript file // * from a blade will implicitly depend on a CSS file in the same blade once this has been located. The method will add these implicit // * dependencies to the current LinkedAsset. // * // * @param implicitDependencies the previously retrieved implicitDependencies to be added // */ // void addImplicitDependencies(List<Asset> implicitDependencies); // }
import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import org.bladerunnerjs.api.Asset; import org.bladerunnerjs.api.BRJS; import org.bladerunnerjs.api.BundlableNode; import org.bladerunnerjs.api.BundleSet; import org.bladerunnerjs.api.JsLib; import org.bladerunnerjs.api.LinkedAsset; import org.bladerunnerjs.api.SourceModule; import org.bladerunnerjs.api.Workbench; import org.bladerunnerjs.api.logging.Logger; import org.bladerunnerjs.api.memoization.MemoizedFile; import org.bladerunnerjs.api.model.exception.ModelOperationException; import org.bladerunnerjs.api.model.exception.OutOfBundleScopeRequirePathException; import org.bladerunnerjs.api.model.exception.OutOfScopeRequirePathException; import org.bladerunnerjs.api.model.exception.RequirePathException; import org.bladerunnerjs.model.AssetContainer; import org.bladerunnerjs.model.BundleSetCreator; import org.bladerunnerjs.model.BundleSetCreator.Messages; import org.bladerunnerjs.model.StandardBundleSet; import com.google.common.base.Joiner;
package org.bladerunnerjs.utility; public class BundleSetBuilder { public static final String BOOTSTRAP_LIB_NAME = "br-bootstrap"; public static final String STRICT_CHECKING_DISABLED_MSG = "Strict checking has been disabled for the directory '%s' and for the Asset '%s'."+ " This allows the Blade class to directly depend on another Blade class when the App loaded. This dependency should be broken using Services and the file '%s' should be removed to re-enable the scope enforcement."; public static final String INVALID_REQUIRE_MSG = "The class '%s' depends on the class '%s' which is outside of it's scope - this dependency should be broken using Services."; // use Maps rather than Lists and Sets so we're in control of what's used as the key rather than relying on #equals being implemented properly
// Path: brjs-core/src/main/java/org/bladerunnerjs/api/LinkedAsset.java // public interface LinkedAsset extends Asset { // /** // * Returns a list of files this LinkedAssetFile depends on // * @param bundlableNode TODO // * @throws ModelOperationException for any exception when calculating dependencies and resolving require paths // * @return The list of assets // */ // List<Asset> getDependentAssets(BundlableNode bundlableNode) throws ModelOperationException; // // /** // * BRJS calculates dependencies implicitly for additional {@link Asset}s found by plugins, for example, a JavaScript file // * from a blade will implicitly depend on a CSS file in the same blade once this has been located. The method will add these implicit // * dependencies to the current LinkedAsset. // * // * @param implicitDependencies the previously retrieved implicitDependencies to be added // */ // void addImplicitDependencies(List<Asset> implicitDependencies); // } // Path: brjs-core/src/main/java/org/bladerunnerjs/utility/BundleSetBuilder.java import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import org.bladerunnerjs.api.Asset; import org.bladerunnerjs.api.BRJS; import org.bladerunnerjs.api.BundlableNode; import org.bladerunnerjs.api.BundleSet; import org.bladerunnerjs.api.JsLib; import org.bladerunnerjs.api.LinkedAsset; import org.bladerunnerjs.api.SourceModule; import org.bladerunnerjs.api.Workbench; import org.bladerunnerjs.api.logging.Logger; import org.bladerunnerjs.api.memoization.MemoizedFile; import org.bladerunnerjs.api.model.exception.ModelOperationException; import org.bladerunnerjs.api.model.exception.OutOfBundleScopeRequirePathException; import org.bladerunnerjs.api.model.exception.OutOfScopeRequirePathException; import org.bladerunnerjs.api.model.exception.RequirePathException; import org.bladerunnerjs.model.AssetContainer; import org.bladerunnerjs.model.BundleSetCreator; import org.bladerunnerjs.model.BundleSetCreator.Messages; import org.bladerunnerjs.model.StandardBundleSet; import com.google.common.base.Joiner; package org.bladerunnerjs.utility; public class BundleSetBuilder { public static final String BOOTSTRAP_LIB_NAME = "br-bootstrap"; public static final String STRICT_CHECKING_DISABLED_MSG = "Strict checking has been disabled for the directory '%s' and for the Asset '%s'."+ " This allows the Blade class to directly depend on another Blade class when the App loaded. This dependency should be broken using Services and the file '%s' should be removed to re-enable the scope enforcement."; public static final String INVALID_REQUIRE_MSG = "The class '%s' depends on the class '%s' which is outside of it's scope - this dependency should be broken using Services."; // use Maps rather than Lists and Sets so we're in control of what's used as the key rather than relying on #equals being implemented properly
private final AssetMap<LinkedAsset> seedAssets = new AssetMap<>();
BladeRunnerJS/brjs
plugins/brjs-plugins/src/test/java/org/bladerunnerjs/spec/plugin/bundler/composite/CompositeJsContentPluginTest.java
// Path: plugins/brjs-plugins/src/main/java/org/bladerunnerjs/plugin/bundlers/aliasing/AliasingUtility.java // public static AliasesFile aliasesFile(AssetContainer assetContainer) { // return getNodeProperty(assetContainer, AliasesFile.class.getSimpleName(), AliasesFile.class, // () -> { return new AliasesFile(assetContainer); }); // }
import static org.bladerunnerjs.plugin.bundlers.aliasing.AliasingUtility.aliasesFile; import java.io.File; import org.bladerunnerjs.api.App; import org.bladerunnerjs.api.Aspect; import org.bladerunnerjs.api.JsLib; import org.bladerunnerjs.api.spec.engine.SpecTest; import org.bladerunnerjs.spec.aliasing.AliasesFileBuilder; import org.bladerunnerjs.utility.FileUtils; import org.junit.Before; import org.junit.Test;
package org.bladerunnerjs.spec.plugin.bundler.composite; public class CompositeJsContentPluginTest extends SpecTest { private App app; private Aspect aspect; private StringBuffer requestResponse = new StringBuffer(); private JsLib thirdpartyLib; private JsLib brLib; private JsLib appLib; private JsLib brbootstrap; private Aspect defaultAspect; private File targetDir; private AliasesFileBuilder aspectAliasesFileBuilder; @Before public void initTestObjects() throws Exception { given(brjs).automaticallyFindsBundlerPlugins() .and(brjs).automaticallyFindsMinifierPlugins() .and(brjs).hasBeenCreated(); app = brjs.app("app1"); aspect = app.aspect("default"); defaultAspect = app.defaultAspect(); thirdpartyLib = app.jsLib("thirdparty-lib"); brLib = app.jsLib("br"); brbootstrap = brjs.sdkLib("br-bootstrap"); appLib = app.jsLib("appLib"); targetDir = FileUtils.createTemporaryDirectory( this.getClass() );
// Path: plugins/brjs-plugins/src/main/java/org/bladerunnerjs/plugin/bundlers/aliasing/AliasingUtility.java // public static AliasesFile aliasesFile(AssetContainer assetContainer) { // return getNodeProperty(assetContainer, AliasesFile.class.getSimpleName(), AliasesFile.class, // () -> { return new AliasesFile(assetContainer); }); // } // Path: plugins/brjs-plugins/src/test/java/org/bladerunnerjs/spec/plugin/bundler/composite/CompositeJsContentPluginTest.java import static org.bladerunnerjs.plugin.bundlers.aliasing.AliasingUtility.aliasesFile; import java.io.File; import org.bladerunnerjs.api.App; import org.bladerunnerjs.api.Aspect; import org.bladerunnerjs.api.JsLib; import org.bladerunnerjs.api.spec.engine.SpecTest; import org.bladerunnerjs.spec.aliasing.AliasesFileBuilder; import org.bladerunnerjs.utility.FileUtils; import org.junit.Before; import org.junit.Test; package org.bladerunnerjs.spec.plugin.bundler.composite; public class CompositeJsContentPluginTest extends SpecTest { private App app; private Aspect aspect; private StringBuffer requestResponse = new StringBuffer(); private JsLib thirdpartyLib; private JsLib brLib; private JsLib appLib; private JsLib brbootstrap; private Aspect defaultAspect; private File targetDir; private AliasesFileBuilder aspectAliasesFileBuilder; @Before public void initTestObjects() throws Exception { given(brjs).automaticallyFindsBundlerPlugins() .and(brjs).automaticallyFindsMinifierPlugins() .and(brjs).hasBeenCreated(); app = brjs.app("app1"); aspect = app.aspect("default"); defaultAspect = app.defaultAspect(); thirdpartyLib = app.jsLib("thirdparty-lib"); brLib = app.jsLib("br"); brbootstrap = brjs.sdkLib("br-bootstrap"); appLib = app.jsLib("appLib"); targetDir = FileUtils.createTemporaryDirectory( this.getClass() );
aspectAliasesFileBuilder = new AliasesFileBuilder(this, aliasesFile(aspect));
BladeRunnerJS/brjs
plugins/brjs-plugins/src/test/java/org/bladerunnerjs/spec/command/ApplicationDepsCommandTest.java
// Path: plugins/brjs-plugins/src/main/java/org/bladerunnerjs/plugin/bundlers/aliasing/AliasingUtility.java // public static AliasDefinitionsFile aliasDefinitionsFile(AssetContainer assetContainer, String path) { // return getNodeProperty(assetContainer, AliasDefinitionsFile.class.getSimpleName()+"_"+path, AliasDefinitionsFile.class, // () -> { return new AliasDefinitionsFile(assetContainer, assetContainer.file(path)); }); // } // // Path: plugins/brjs-plugins/src/main/java/org/bladerunnerjs/plugin/bundlers/aliasing/AliasingUtility.java // public static AliasesFile aliasesFile(AssetContainer assetContainer) { // return getNodeProperty(assetContainer, AliasesFile.class.getSimpleName(), AliasesFile.class, // () -> { return new AliasesFile(assetContainer); }); // }
import static org.bladerunnerjs.plugin.bundlers.aliasing.AliasingUtility.aliasDefinitionsFile; import static org.bladerunnerjs.plugin.bundlers.aliasing.AliasingUtility.aliasesFile; import org.bladerunnerjs.api.App; import org.bladerunnerjs.api.Aspect; import org.bladerunnerjs.api.Blade; import org.bladerunnerjs.api.JsLib; import org.bladerunnerjs.api.model.exception.command.ArgumentParsingException; import org.bladerunnerjs.api.model.exception.command.CommandArgumentsException; import org.bladerunnerjs.api.model.exception.command.NodeDoesNotExistException; import org.bladerunnerjs.api.spec.engine.SpecTest; import org.bladerunnerjs.model.SdkJsLib; import org.bladerunnerjs.plugin.commands.standard.ApplicationDepsCommand; import org.bladerunnerjs.plugin.plugins.require.AliasDataSourceModule; import org.bladerunnerjs.spec.aliasing.AliasDefinitionsFileBuilder; import org.bladerunnerjs.spec.aliasing.AliasesFileBuilder; import org.junit.Before; import org.junit.Test;
package org.bladerunnerjs.spec.command; public class ApplicationDepsCommandTest extends SpecTest { App app; Aspect aspect; SdkJsLib brLib; private Blade bladeInDefaultBladeset; private Aspect defaultAspect; private AliasesFileBuilder aspectAliasesFileBuilder; private AliasDefinitionsFileBuilder bladeAliasDefinitionsFileBuilder; private Blade blade; @Before public void initTestObjects() throws Exception { given(brjs).hasCommandPlugins(new ApplicationDepsCommand()) .and(brjs).automaticallyFindsAssetPlugins() .and(brjs).automaticallyFindsRequirePlugins() .and(brjs).hasBeenCreated(); app = brjs.app("app"); aspect = app.aspect("default"); defaultAspect = app.defaultAspect(); blade = app.bladeset("bs").blade("b1"); brLib = brjs.sdkLib("br"); bladeInDefaultBladeset = app.defaultBladeset().blade("b1");
// Path: plugins/brjs-plugins/src/main/java/org/bladerunnerjs/plugin/bundlers/aliasing/AliasingUtility.java // public static AliasDefinitionsFile aliasDefinitionsFile(AssetContainer assetContainer, String path) { // return getNodeProperty(assetContainer, AliasDefinitionsFile.class.getSimpleName()+"_"+path, AliasDefinitionsFile.class, // () -> { return new AliasDefinitionsFile(assetContainer, assetContainer.file(path)); }); // } // // Path: plugins/brjs-plugins/src/main/java/org/bladerunnerjs/plugin/bundlers/aliasing/AliasingUtility.java // public static AliasesFile aliasesFile(AssetContainer assetContainer) { // return getNodeProperty(assetContainer, AliasesFile.class.getSimpleName(), AliasesFile.class, // () -> { return new AliasesFile(assetContainer); }); // } // Path: plugins/brjs-plugins/src/test/java/org/bladerunnerjs/spec/command/ApplicationDepsCommandTest.java import static org.bladerunnerjs.plugin.bundlers.aliasing.AliasingUtility.aliasDefinitionsFile; import static org.bladerunnerjs.plugin.bundlers.aliasing.AliasingUtility.aliasesFile; import org.bladerunnerjs.api.App; import org.bladerunnerjs.api.Aspect; import org.bladerunnerjs.api.Blade; import org.bladerunnerjs.api.JsLib; import org.bladerunnerjs.api.model.exception.command.ArgumentParsingException; import org.bladerunnerjs.api.model.exception.command.CommandArgumentsException; import org.bladerunnerjs.api.model.exception.command.NodeDoesNotExistException; import org.bladerunnerjs.api.spec.engine.SpecTest; import org.bladerunnerjs.model.SdkJsLib; import org.bladerunnerjs.plugin.commands.standard.ApplicationDepsCommand; import org.bladerunnerjs.plugin.plugins.require.AliasDataSourceModule; import org.bladerunnerjs.spec.aliasing.AliasDefinitionsFileBuilder; import org.bladerunnerjs.spec.aliasing.AliasesFileBuilder; import org.junit.Before; import org.junit.Test; package org.bladerunnerjs.spec.command; public class ApplicationDepsCommandTest extends SpecTest { App app; Aspect aspect; SdkJsLib brLib; private Blade bladeInDefaultBladeset; private Aspect defaultAspect; private AliasesFileBuilder aspectAliasesFileBuilder; private AliasDefinitionsFileBuilder bladeAliasDefinitionsFileBuilder; private Blade blade; @Before public void initTestObjects() throws Exception { given(brjs).hasCommandPlugins(new ApplicationDepsCommand()) .and(brjs).automaticallyFindsAssetPlugins() .and(brjs).automaticallyFindsRequirePlugins() .and(brjs).hasBeenCreated(); app = brjs.app("app"); aspect = app.aspect("default"); defaultAspect = app.defaultAspect(); blade = app.bladeset("bs").blade("b1"); brLib = brjs.sdkLib("br"); bladeInDefaultBladeset = app.defaultBladeset().blade("b1");
aspectAliasesFileBuilder = new AliasesFileBuilder(this, aliasesFile(aspect));
BladeRunnerJS/brjs
plugins/brjs-plugins/src/test/java/org/bladerunnerjs/spec/command/ApplicationDepsCommandTest.java
// Path: plugins/brjs-plugins/src/main/java/org/bladerunnerjs/plugin/bundlers/aliasing/AliasingUtility.java // public static AliasDefinitionsFile aliasDefinitionsFile(AssetContainer assetContainer, String path) { // return getNodeProperty(assetContainer, AliasDefinitionsFile.class.getSimpleName()+"_"+path, AliasDefinitionsFile.class, // () -> { return new AliasDefinitionsFile(assetContainer, assetContainer.file(path)); }); // } // // Path: plugins/brjs-plugins/src/main/java/org/bladerunnerjs/plugin/bundlers/aliasing/AliasingUtility.java // public static AliasesFile aliasesFile(AssetContainer assetContainer) { // return getNodeProperty(assetContainer, AliasesFile.class.getSimpleName(), AliasesFile.class, // () -> { return new AliasesFile(assetContainer); }); // }
import static org.bladerunnerjs.plugin.bundlers.aliasing.AliasingUtility.aliasDefinitionsFile; import static org.bladerunnerjs.plugin.bundlers.aliasing.AliasingUtility.aliasesFile; import org.bladerunnerjs.api.App; import org.bladerunnerjs.api.Aspect; import org.bladerunnerjs.api.Blade; import org.bladerunnerjs.api.JsLib; import org.bladerunnerjs.api.model.exception.command.ArgumentParsingException; import org.bladerunnerjs.api.model.exception.command.CommandArgumentsException; import org.bladerunnerjs.api.model.exception.command.NodeDoesNotExistException; import org.bladerunnerjs.api.spec.engine.SpecTest; import org.bladerunnerjs.model.SdkJsLib; import org.bladerunnerjs.plugin.commands.standard.ApplicationDepsCommand; import org.bladerunnerjs.plugin.plugins.require.AliasDataSourceModule; import org.bladerunnerjs.spec.aliasing.AliasDefinitionsFileBuilder; import org.bladerunnerjs.spec.aliasing.AliasesFileBuilder; import org.junit.Before; import org.junit.Test;
package org.bladerunnerjs.spec.command; public class ApplicationDepsCommandTest extends SpecTest { App app; Aspect aspect; SdkJsLib brLib; private Blade bladeInDefaultBladeset; private Aspect defaultAspect; private AliasesFileBuilder aspectAliasesFileBuilder; private AliasDefinitionsFileBuilder bladeAliasDefinitionsFileBuilder; private Blade blade; @Before public void initTestObjects() throws Exception { given(brjs).hasCommandPlugins(new ApplicationDepsCommand()) .and(brjs).automaticallyFindsAssetPlugins() .and(brjs).automaticallyFindsRequirePlugins() .and(brjs).hasBeenCreated(); app = brjs.app("app"); aspect = app.aspect("default"); defaultAspect = app.defaultAspect(); blade = app.bladeset("bs").blade("b1"); brLib = brjs.sdkLib("br"); bladeInDefaultBladeset = app.defaultBladeset().blade("b1"); aspectAliasesFileBuilder = new AliasesFileBuilder(this, aliasesFile(aspect));
// Path: plugins/brjs-plugins/src/main/java/org/bladerunnerjs/plugin/bundlers/aliasing/AliasingUtility.java // public static AliasDefinitionsFile aliasDefinitionsFile(AssetContainer assetContainer, String path) { // return getNodeProperty(assetContainer, AliasDefinitionsFile.class.getSimpleName()+"_"+path, AliasDefinitionsFile.class, // () -> { return new AliasDefinitionsFile(assetContainer, assetContainer.file(path)); }); // } // // Path: plugins/brjs-plugins/src/main/java/org/bladerunnerjs/plugin/bundlers/aliasing/AliasingUtility.java // public static AliasesFile aliasesFile(AssetContainer assetContainer) { // return getNodeProperty(assetContainer, AliasesFile.class.getSimpleName(), AliasesFile.class, // () -> { return new AliasesFile(assetContainer); }); // } // Path: plugins/brjs-plugins/src/test/java/org/bladerunnerjs/spec/command/ApplicationDepsCommandTest.java import static org.bladerunnerjs.plugin.bundlers.aliasing.AliasingUtility.aliasDefinitionsFile; import static org.bladerunnerjs.plugin.bundlers.aliasing.AliasingUtility.aliasesFile; import org.bladerunnerjs.api.App; import org.bladerunnerjs.api.Aspect; import org.bladerunnerjs.api.Blade; import org.bladerunnerjs.api.JsLib; import org.bladerunnerjs.api.model.exception.command.ArgumentParsingException; import org.bladerunnerjs.api.model.exception.command.CommandArgumentsException; import org.bladerunnerjs.api.model.exception.command.NodeDoesNotExistException; import org.bladerunnerjs.api.spec.engine.SpecTest; import org.bladerunnerjs.model.SdkJsLib; import org.bladerunnerjs.plugin.commands.standard.ApplicationDepsCommand; import org.bladerunnerjs.plugin.plugins.require.AliasDataSourceModule; import org.bladerunnerjs.spec.aliasing.AliasDefinitionsFileBuilder; import org.bladerunnerjs.spec.aliasing.AliasesFileBuilder; import org.junit.Before; import org.junit.Test; package org.bladerunnerjs.spec.command; public class ApplicationDepsCommandTest extends SpecTest { App app; Aspect aspect; SdkJsLib brLib; private Blade bladeInDefaultBladeset; private Aspect defaultAspect; private AliasesFileBuilder aspectAliasesFileBuilder; private AliasDefinitionsFileBuilder bladeAliasDefinitionsFileBuilder; private Blade blade; @Before public void initTestObjects() throws Exception { given(brjs).hasCommandPlugins(new ApplicationDepsCommand()) .and(brjs).automaticallyFindsAssetPlugins() .and(brjs).automaticallyFindsRequirePlugins() .and(brjs).hasBeenCreated(); app = brjs.app("app"); aspect = app.aspect("default"); defaultAspect = app.defaultAspect(); blade = app.bladeset("bs").blade("b1"); brLib = brjs.sdkLib("br"); bladeInDefaultBladeset = app.defaultBladeset().blade("b1"); aspectAliasesFileBuilder = new AliasesFileBuilder(this, aliasesFile(aspect));
bladeAliasDefinitionsFileBuilder = new AliasDefinitionsFileBuilder(this, aliasDefinitionsFile(blade, "src"));
BladeRunnerJS/brjs
brjs-core/src/main/java/org/bladerunnerjs/utility/trie/TrieFactory.java
// Path: brjs-core/src/main/java/org/bladerunnerjs/api/memoization/Getter.java // public interface Getter<E extends Exception> { // Object get() throws E; // }
import java.util.List; import java.util.regex.Pattern; import org.apache.commons.lang3.StringUtils; import org.bladerunnerjs.api.Asset; import org.bladerunnerjs.api.memoization.Getter; import org.bladerunnerjs.api.memoization.MemoizedValue; import org.bladerunnerjs.api.model.exception.ModelOperationException; import org.bladerunnerjs.model.AssetContainer; import org.bladerunnerjs.model.engine.NodeProperties; import org.bladerunnerjs.utility.trie.exception.EmptyTrieKeyException; import org.bladerunnerjs.utility.trie.exception.TrieKeyAlreadyExistsException;
package org.bladerunnerjs.utility.trie; public class TrieFactory { private final MemoizedValue<Trie<Asset>> trie; private final AssetContainer assetContainer; private static final Pattern ALIAS_MATCHER_PATTERN = Pattern.compile("[\"'][\\S ]+[\"']|<\\S+[\\s/>]"); private static final Pattern QUOTED_SOURCE_MODULE_MATCHER_PATTERN = Pattern.compile("[\"']\\S+[\"']"); private static final Pattern SOURCE_MODULE_MATCHER_PATTERN = Pattern.compile(".*", Pattern.DOTALL); public static TrieFactory getFactoryForAssetContainer(AssetContainer assetContainer) { NodeProperties nodeProperties = assetContainer.nodeProperties("TrieFactory"); if(nodeProperties.getTransientProperty("trieFactoryInstance") == null) { nodeProperties.setTransientProperty("trieFactoryInstance", new TrieFactory(assetContainer)); } return (TrieFactory) nodeProperties.getTransientProperty("trieFactoryInstance"); } private TrieFactory(AssetContainer assetContainer) { this.assetContainer = assetContainer; trie = new MemoizedValue<>(assetContainer.dir()+" - TrieFactory.trie", assetContainer); } public Trie<Asset> createTrie() throws ModelOperationException {
// Path: brjs-core/src/main/java/org/bladerunnerjs/api/memoization/Getter.java // public interface Getter<E extends Exception> { // Object get() throws E; // } // Path: brjs-core/src/main/java/org/bladerunnerjs/utility/trie/TrieFactory.java import java.util.List; import java.util.regex.Pattern; import org.apache.commons.lang3.StringUtils; import org.bladerunnerjs.api.Asset; import org.bladerunnerjs.api.memoization.Getter; import org.bladerunnerjs.api.memoization.MemoizedValue; import org.bladerunnerjs.api.model.exception.ModelOperationException; import org.bladerunnerjs.model.AssetContainer; import org.bladerunnerjs.model.engine.NodeProperties; import org.bladerunnerjs.utility.trie.exception.EmptyTrieKeyException; import org.bladerunnerjs.utility.trie.exception.TrieKeyAlreadyExistsException; package org.bladerunnerjs.utility.trie; public class TrieFactory { private final MemoizedValue<Trie<Asset>> trie; private final AssetContainer assetContainer; private static final Pattern ALIAS_MATCHER_PATTERN = Pattern.compile("[\"'][\\S ]+[\"']|<\\S+[\\s/>]"); private static final Pattern QUOTED_SOURCE_MODULE_MATCHER_PATTERN = Pattern.compile("[\"']\\S+[\"']"); private static final Pattern SOURCE_MODULE_MATCHER_PATTERN = Pattern.compile(".*", Pattern.DOTALL); public static TrieFactory getFactoryForAssetContainer(AssetContainer assetContainer) { NodeProperties nodeProperties = assetContainer.nodeProperties("TrieFactory"); if(nodeProperties.getTransientProperty("trieFactoryInstance") == null) { nodeProperties.setTransientProperty("trieFactoryInstance", new TrieFactory(assetContainer)); } return (TrieFactory) nodeProperties.getTransientProperty("trieFactoryInstance"); } private TrieFactory(AssetContainer assetContainer) { this.assetContainer = assetContainer; trie = new MemoizedValue<>(assetContainer.dir()+" - TrieFactory.trie", assetContainer); } public Trie<Asset> createTrie() throws ModelOperationException {
return trie.value(new Getter<ModelOperationException>() {
BladeRunnerJS/brjs
plugins/brjs-plugins/src/main/java/org/bladerunnerjs/plugin/bundlers/aliasing/AliasingUtility.java
// Path: brjs-core/src/main/java/org/bladerunnerjs/api/memoization/Getter.java // public interface Getter<E extends Exception> { // Object get() throws E; // }
import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.apache.commons.io.IOUtils; import org.apache.commons.io.LineIterator; import org.bladerunnerjs.api.memoization.Getter; import org.bladerunnerjs.api.memoization.MemoizedFile; import org.bladerunnerjs.api.memoization.MemoizedValue; import org.bladerunnerjs.api.model.exception.request.ContentFileProcessingException; import org.bladerunnerjs.model.AssetContainer; import org.bladerunnerjs.model.engine.Node; import org.bladerunnerjs.model.engine.NodeProperties; import org.bladerunnerjs.utility.UnicodeReader; import org.bladerunnerjs.api.App; import org.bladerunnerjs.api.BundlableNode;
package org.bladerunnerjs.plugin.bundlers.aliasing; public class AliasingUtility { public static final String BR_UNKNOWN_CLASS_NAME = "br.UnknownClass"; public static boolean usesLegacySchema(MemoizedFile aliaseFile, String defaultCharEncoding) throws IOException { LineIterator it = IOUtils.lineIterator( new UnicodeReader(aliaseFile, defaultCharEncoding) ); for (int lineNumber = 0; it.hasNext() && lineNumber < 3; lineNumber++) { if (it.nextLine().contains("schema.caplin.com")) { return true; } } return false; } /* Memoization Utilities */ public static AliasesFile aliasesFile(AssetContainer assetContainer) { return getNodeProperty(assetContainer, AliasesFile.class.getSimpleName(), AliasesFile.class, () -> { return new AliasesFile(assetContainer); }); } public static AliasesFile aliasesFile(App app) { return getNodeProperty(app, AliasesFile.class.getSimpleName(), AliasesFile.class, () -> { return new AliasesFile(app); }); } public static AliasDefinitionsFile aliasDefinitionsFile(AssetContainer assetContainer, String path) { return getNodeProperty(assetContainer, AliasDefinitionsFile.class.getSimpleName()+"_"+path, AliasDefinitionsFile.class, () -> { return new AliasDefinitionsFile(assetContainer, assetContainer.file(path)); }); } @SuppressWarnings("unchecked")
// Path: brjs-core/src/main/java/org/bladerunnerjs/api/memoization/Getter.java // public interface Getter<E extends Exception> { // Object get() throws E; // } // Path: plugins/brjs-plugins/src/main/java/org/bladerunnerjs/plugin/bundlers/aliasing/AliasingUtility.java import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.apache.commons.io.IOUtils; import org.apache.commons.io.LineIterator; import org.bladerunnerjs.api.memoization.Getter; import org.bladerunnerjs.api.memoization.MemoizedFile; import org.bladerunnerjs.api.memoization.MemoizedValue; import org.bladerunnerjs.api.model.exception.request.ContentFileProcessingException; import org.bladerunnerjs.model.AssetContainer; import org.bladerunnerjs.model.engine.Node; import org.bladerunnerjs.model.engine.NodeProperties; import org.bladerunnerjs.utility.UnicodeReader; import org.bladerunnerjs.api.App; import org.bladerunnerjs.api.BundlableNode; package org.bladerunnerjs.plugin.bundlers.aliasing; public class AliasingUtility { public static final String BR_UNKNOWN_CLASS_NAME = "br.UnknownClass"; public static boolean usesLegacySchema(MemoizedFile aliaseFile, String defaultCharEncoding) throws IOException { LineIterator it = IOUtils.lineIterator( new UnicodeReader(aliaseFile, defaultCharEncoding) ); for (int lineNumber = 0; it.hasNext() && lineNumber < 3; lineNumber++) { if (it.nextLine().contains("schema.caplin.com")) { return true; } } return false; } /* Memoization Utilities */ public static AliasesFile aliasesFile(AssetContainer assetContainer) { return getNodeProperty(assetContainer, AliasesFile.class.getSimpleName(), AliasesFile.class, () -> { return new AliasesFile(assetContainer); }); } public static AliasesFile aliasesFile(App app) { return getNodeProperty(app, AliasesFile.class.getSimpleName(), AliasesFile.class, () -> { return new AliasesFile(app); }); } public static AliasDefinitionsFile aliasDefinitionsFile(AssetContainer assetContainer, String path) { return getNodeProperty(assetContainer, AliasDefinitionsFile.class.getSimpleName()+"_"+path, AliasDefinitionsFile.class, () -> { return new AliasDefinitionsFile(assetContainer, assetContainer.file(path)); }); } @SuppressWarnings("unchecked")
static <OT extends Object> OT getNodeProperty(Node node, String propertyKey, Class<? extends OT> valueType, Getter<Exception> valueGetter) {
BladeRunnerJS/brjs
brjs-core-tests/src/test/java/org/bladerunnerjs/plugin/VirtualProxyPluginTest.java
// Path: brjs-core/src/main/java/org/bladerunnerjs/api/plugin/base/AbstractPlugin.java // public abstract class AbstractPlugin implements Plugin { // @Override // public boolean equals(Object otherPlugin) { // return (otherPlugin instanceof VirtualProxyPlugin) ? otherPlugin.equals(this) : (this == otherPlugin); // } // // @Override // public void close() { // // do nothing -- concrete implementations may choose to override this method, but very few will ever need to // } // // @Override // public <P extends Plugin> boolean instanceOf(Class<P> pluginInterface) { // return pluginInterface.isAssignableFrom(getClass()); // } // // @SuppressWarnings("unchecked") // @Override // public <P extends Plugin> P castTo(Class<P> pluginInterface) { // return (P) this; // } // // @Override // public Class<?> getPluginClass() { // return getClass(); // } // // }
import static org.junit.Assert.*; import org.bladerunnerjs.api.BRJS; import org.bladerunnerjs.api.plugin.Plugin; import org.bladerunnerjs.api.plugin.base.AbstractPlugin; import org.bladerunnerjs.plugin.proxy.VirtualProxyPlugin; import org.junit.Test;
package org.bladerunnerjs.plugin; public class VirtualProxyPluginTest { @Test public void instanceOfWorks() { Plugin plugin = new VirtualProxyPlugin(new MyTestPlugin()); assertTrue("1", plugin.instanceOf(MyTestPlugin.class)); assertTrue("2", plugin.instanceOf(TestPlugin.class)); } @Test public void equalityWorks() { Plugin plugin = new MyTestPlugin(); Plugin proxyPlugin = new VirtualProxyPlugin(plugin); assertTrue("1", plugin.equals(plugin)); assertTrue("2", proxyPlugin.equals(proxyPlugin)); assertTrue("3", proxyPlugin.equals(plugin)); assertTrue("4", plugin.equals(proxyPlugin)); } private interface TestPlugin extends Plugin { }
// Path: brjs-core/src/main/java/org/bladerunnerjs/api/plugin/base/AbstractPlugin.java // public abstract class AbstractPlugin implements Plugin { // @Override // public boolean equals(Object otherPlugin) { // return (otherPlugin instanceof VirtualProxyPlugin) ? otherPlugin.equals(this) : (this == otherPlugin); // } // // @Override // public void close() { // // do nothing -- concrete implementations may choose to override this method, but very few will ever need to // } // // @Override // public <P extends Plugin> boolean instanceOf(Class<P> pluginInterface) { // return pluginInterface.isAssignableFrom(getClass()); // } // // @SuppressWarnings("unchecked") // @Override // public <P extends Plugin> P castTo(Class<P> pluginInterface) { // return (P) this; // } // // @Override // public Class<?> getPluginClass() { // return getClass(); // } // // } // Path: brjs-core-tests/src/test/java/org/bladerunnerjs/plugin/VirtualProxyPluginTest.java import static org.junit.Assert.*; import org.bladerunnerjs.api.BRJS; import org.bladerunnerjs.api.plugin.Plugin; import org.bladerunnerjs.api.plugin.base.AbstractPlugin; import org.bladerunnerjs.plugin.proxy.VirtualProxyPlugin; import org.junit.Test; package org.bladerunnerjs.plugin; public class VirtualProxyPluginTest { @Test public void instanceOfWorks() { Plugin plugin = new VirtualProxyPlugin(new MyTestPlugin()); assertTrue("1", plugin.instanceOf(MyTestPlugin.class)); assertTrue("2", plugin.instanceOf(TestPlugin.class)); } @Test public void equalityWorks() { Plugin plugin = new MyTestPlugin(); Plugin proxyPlugin = new VirtualProxyPlugin(plugin); assertTrue("1", plugin.equals(plugin)); assertTrue("2", proxyPlugin.equals(proxyPlugin)); assertTrue("3", proxyPlugin.equals(plugin)); assertTrue("4", plugin.equals(proxyPlugin)); } private interface TestPlugin extends Plugin { }
private class MyTestPlugin extends AbstractPlugin implements TestPlugin {
mguymon/model-citizen
core/src/test/java/com/tobedevoured/modelcitizen/blueprint/SpareTireBlueprint.java
// Path: core/src/main/java/com/tobedevoured/modelcitizen/callback/ConstructorCallback.java // public abstract class ConstructorCallback implements Constructable { // // public abstract Object createInstance(); // } // // Path: core/src/test/java/com/tobedevoured/modelcitizen/model/SpareTire.java // public class SpareTire extends Wheel { // // private Integer mileLimit; // // public SpareTire(String name) { // super(name); // } // // public Integer getMileLimit() { // return mileLimit; // } // // public void setMileLimit(Integer mileLimit) { // this.mileLimit = mileLimit; // } // }
import com.tobedevoured.modelcitizen.annotation.Blueprint; import com.tobedevoured.modelcitizen.annotation.Default; import com.tobedevoured.modelcitizen.callback.ConstructorCallback; import com.tobedevoured.modelcitizen.model.SpareTire; import com.tobedevoured.modelcitizen.model.Wheel;
package com.tobedevoured.modelcitizen.blueprint; /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @Blueprint(SpareTire.class) public class SpareTireBlueprint extends WheelBlueprint { @Default public Integer mileLimit = 400; @Default public Integer size = 9;
// Path: core/src/main/java/com/tobedevoured/modelcitizen/callback/ConstructorCallback.java // public abstract class ConstructorCallback implements Constructable { // // public abstract Object createInstance(); // } // // Path: core/src/test/java/com/tobedevoured/modelcitizen/model/SpareTire.java // public class SpareTire extends Wheel { // // private Integer mileLimit; // // public SpareTire(String name) { // super(name); // } // // public Integer getMileLimit() { // return mileLimit; // } // // public void setMileLimit(Integer mileLimit) { // this.mileLimit = mileLimit; // } // } // Path: core/src/test/java/com/tobedevoured/modelcitizen/blueprint/SpareTireBlueprint.java import com.tobedevoured.modelcitizen.annotation.Blueprint; import com.tobedevoured.modelcitizen.annotation.Default; import com.tobedevoured.modelcitizen.callback.ConstructorCallback; import com.tobedevoured.modelcitizen.model.SpareTire; import com.tobedevoured.modelcitizen.model.Wheel; package com.tobedevoured.modelcitizen.blueprint; /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @Blueprint(SpareTire.class) public class SpareTireBlueprint extends WheelBlueprint { @Default public Integer mileLimit = 400; @Default public Integer size = 9;
ConstructorCallback constructor = new ConstructorCallback() {
mguymon/model-citizen
core/src/test/java/com/tobedevoured/modelcitizen/blueprint/WheelBlueprint.java
// Path: core/src/main/java/com/tobedevoured/modelcitizen/callback/ConstructorCallback.java // public abstract class ConstructorCallback implements Constructable { // // public abstract Object createInstance(); // } // // Path: core/src/test/java/com/tobedevoured/modelcitizen/model/Option.java // public class Option { // public String name; // // public void setName(String name) { // this.name = name; // } // // public String getName() { // return name; // } // }
import java.util.List; import com.tobedevoured.modelcitizen.annotation.*; import com.tobedevoured.modelcitizen.callback.ConstructorCallback; import com.tobedevoured.modelcitizen.model.Wheel; import com.tobedevoured.modelcitizen.model.Option;
package com.tobedevoured.modelcitizen.blueprint; /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @Blueprint(value=Wheel.class, template=CustomTemplate.class) public class WheelBlueprint {
// Path: core/src/main/java/com/tobedevoured/modelcitizen/callback/ConstructorCallback.java // public abstract class ConstructorCallback implements Constructable { // // public abstract Object createInstance(); // } // // Path: core/src/test/java/com/tobedevoured/modelcitizen/model/Option.java // public class Option { // public String name; // // public void setName(String name) { // this.name = name; // } // // public String getName() { // return name; // } // } // Path: core/src/test/java/com/tobedevoured/modelcitizen/blueprint/WheelBlueprint.java import java.util.List; import com.tobedevoured.modelcitizen.annotation.*; import com.tobedevoured.modelcitizen.callback.ConstructorCallback; import com.tobedevoured.modelcitizen.model.Wheel; import com.tobedevoured.modelcitizen.model.Option; package com.tobedevoured.modelcitizen.blueprint; /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @Blueprint(value=Wheel.class, template=CustomTemplate.class) public class WheelBlueprint {
ConstructorCallback constructor = new ConstructorCallback() {
mguymon/model-citizen
core/src/test/java/com/tobedevoured/modelcitizen/blueprint/WheelBlueprint.java
// Path: core/src/main/java/com/tobedevoured/modelcitizen/callback/ConstructorCallback.java // public abstract class ConstructorCallback implements Constructable { // // public abstract Object createInstance(); // } // // Path: core/src/test/java/com/tobedevoured/modelcitizen/model/Option.java // public class Option { // public String name; // // public void setName(String name) { // this.name = name; // } // // public String getName() { // return name; // } // }
import java.util.List; import com.tobedevoured.modelcitizen.annotation.*; import com.tobedevoured.modelcitizen.callback.ConstructorCallback; import com.tobedevoured.modelcitizen.model.Wheel; import com.tobedevoured.modelcitizen.model.Option;
package com.tobedevoured.modelcitizen.blueprint; /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @Blueprint(value=Wheel.class, template=CustomTemplate.class) public class WheelBlueprint { ConstructorCallback constructor = new ConstructorCallback() { @Override public Object createInstance() { Wheel wheel = new Wheel("tire name"); return wheel; } }; @Default public Integer size = 10; @Default public String color = "black";
// Path: core/src/main/java/com/tobedevoured/modelcitizen/callback/ConstructorCallback.java // public abstract class ConstructorCallback implements Constructable { // // public abstract Object createInstance(); // } // // Path: core/src/test/java/com/tobedevoured/modelcitizen/model/Option.java // public class Option { // public String name; // // public void setName(String name) { // this.name = name; // } // // public String getName() { // return name; // } // } // Path: core/src/test/java/com/tobedevoured/modelcitizen/blueprint/WheelBlueprint.java import java.util.List; import com.tobedevoured.modelcitizen.annotation.*; import com.tobedevoured.modelcitizen.callback.ConstructorCallback; import com.tobedevoured.modelcitizen.model.Wheel; import com.tobedevoured.modelcitizen.model.Option; package com.tobedevoured.modelcitizen.blueprint; /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @Blueprint(value=Wheel.class, template=CustomTemplate.class) public class WheelBlueprint { ConstructorCallback constructor = new ConstructorCallback() { @Override public Object createInstance() { Wheel wheel = new Wheel("tire name"); return wheel; } }; @Default public Integer size = 10; @Default public String color = "black";
@MappedList(target = Option.class, size = 3)
yetanotherx/WorldEditCUI
src/main/java/deobf/spc_WorldEditCUI.java
// Path: src/main/java/wecui/WorldEditCUI.java // public class WorldEditCUI { // // public static final String VERSION = "1.4.5"; // public static final String MCVERSION = "1.4.5"; // public static final int protocolVersion = 2; // protected Minecraft minecraft; // protected EventManager eventManager; // protected Obfuscation obfuscation; // protected BaseRegion selection; // protected CUIDebug debugger; // protected CUIConfiguration configuration; // //protected LocalPlugin localPlugin; // // public WorldEditCUI(Minecraft minecraft) { // this.minecraft = minecraft; // } // // public void initialize() { // this.eventManager = new EventManager(this); // this.obfuscation = new Obfuscation(this); // this.selection = new CuboidRegion(this); // this.configuration = new CUIConfiguration(this); // this.debugger = new CUIDebug(this); // //this.localPlugin = new LocalPlugin(this); // // try { // this.eventManager.initialize(); // this.obfuscation.initialize(); // this.selection.initialize(); // this.configuration.initialize(); // this.debugger.initialize(); // //this.localPlugin.initialize(); // } catch (InitializationException e) { // e.printStackTrace(); // return; // } // // this.registerListeners(); // } // // protected void registerListeners() { // CUIEvent.handlers.register(new CUIListener(this), Order.Default); // ChannelEvent.handlers.register(new ChannelListener(this), Order.Default); // WorldRenderEvent.handlers.register(new WorldRenderListener(this), Order.Default); // // WorldEditCommandListener commListener = new WorldEditCommandListener(this); // ChatCommandEvent.getHandlers("worldedit").register(commListener, Order.Default); // ChatCommandEvent.getHandlers("we").register(commListener, Order.Default); // } // // public CUIConfiguration getConfiguration() { // return configuration; // } // // public void setConfiguration(CUIConfiguration configuration) { // this.configuration = configuration; // } // // public CUIDebug getDebugger() { // return debugger; // } // // public void setDebugger(CUIDebug debugger) { // this.debugger = debugger; // } // // public EventManager getEventManager() { // return eventManager; // } // // public void setEventManager(EventManager eventManager) { // this.eventManager = eventManager; // } // // /*public LocalPlugin getLocalPlugin() { // return localPlugin; // } // // public void setLocalPlugin(LocalPlugin localPlugin) { // this.localPlugin = localPlugin; // }*/ // // public Minecraft getMinecraft() { // return minecraft; // } // // public void setMinecraft(Minecraft minecraft) { // this.minecraft = minecraft; // } // // public Obfuscation getObfuscation() { // return obfuscation; // } // // public void setObfuscation(Obfuscation obfuscation) { // this.obfuscation = obfuscation; // } // // public BaseRegion getSelection() { // return selection; // } // // public void setSelection(BaseRegion selection) { // this.selection = selection; // } // // public static String getVersion() { // return VERSION + " for Minecraft version " + MCVERSION; // } // } // // Path: src/main/java/wecui/event/CUIEvent.java // public class CUIEvent extends Event<CUIEvent> { // // protected WorldEditCUI controller; // protected String type; // protected String[] params; // protected boolean handled = false; // public static final HandlerList<CUIEvent> handlers = new HandlerList<CUIEvent>(); // // public CUIEvent(WorldEditCUI controller, String type, String[] params) { // this.controller = controller; // this.type = type; // // //"".split("[|]") returns String[] {""} for some reason, instead of String[] {}. // if (params.length == 1 && params[0].length() == 0) { // params = new String[]{}; // } // // this.params = params; // this.controller.getDebugger().debug("CUI Event (" + type + ") - Params: " + Utilities.join(params, ", ")); // // } // // @Override // protected String getEventName() { // return "CUIEvent"; // } // // @Override // protected HandlerList<CUIEvent> getHandlers() { // return handlers; // } // // public void setHandled(boolean handled) { // this.handled = handled; // } // // /** // * Called upon receiving an invalid event. // * Debugs an error message and handles the event. // * // * @param reason Error message // */ // public void markInvalid(String reason) { // this.controller.getDebugger().debug("INVALID WECUIEvent " + type + " - " + Utilities.join(params, "|") + " - Reason: " + reason); // setHandled(true); // } // // public int getInt(int index) { // return (int) Float.parseFloat(params[index]); // } // // public String getString(int index) { // return params[index]; // } // // public boolean isHandled() { // return handled; // } // // public boolean isCancelled() { // return isHandled(); // } // // public String[] getParams() { // return params; // } // // public String getType() { // return type; // } // }
import wecui.WorldEditCUI; import wecui.event.CUIEvent;
package deobf; /** * Main SinglePlayerCommands class * * @author lahwran * @author yetanotherx * */ public class spc_WorldEditCUI extends SPCPlugin { protected WorldEditCUI controller; public spc_WorldEditCUI(WorldEditCUI controller) { this.controller = controller; } @Override public String getVersion() { return WorldEditCUI.getVersion(); } @Override public String getName() { return "WorldEditCUI"; } @Override public void handleCUIEvent(String type, String params[]) { if (controller != null) {
// Path: src/main/java/wecui/WorldEditCUI.java // public class WorldEditCUI { // // public static final String VERSION = "1.4.5"; // public static final String MCVERSION = "1.4.5"; // public static final int protocolVersion = 2; // protected Minecraft minecraft; // protected EventManager eventManager; // protected Obfuscation obfuscation; // protected BaseRegion selection; // protected CUIDebug debugger; // protected CUIConfiguration configuration; // //protected LocalPlugin localPlugin; // // public WorldEditCUI(Minecraft minecraft) { // this.minecraft = minecraft; // } // // public void initialize() { // this.eventManager = new EventManager(this); // this.obfuscation = new Obfuscation(this); // this.selection = new CuboidRegion(this); // this.configuration = new CUIConfiguration(this); // this.debugger = new CUIDebug(this); // //this.localPlugin = new LocalPlugin(this); // // try { // this.eventManager.initialize(); // this.obfuscation.initialize(); // this.selection.initialize(); // this.configuration.initialize(); // this.debugger.initialize(); // //this.localPlugin.initialize(); // } catch (InitializationException e) { // e.printStackTrace(); // return; // } // // this.registerListeners(); // } // // protected void registerListeners() { // CUIEvent.handlers.register(new CUIListener(this), Order.Default); // ChannelEvent.handlers.register(new ChannelListener(this), Order.Default); // WorldRenderEvent.handlers.register(new WorldRenderListener(this), Order.Default); // // WorldEditCommandListener commListener = new WorldEditCommandListener(this); // ChatCommandEvent.getHandlers("worldedit").register(commListener, Order.Default); // ChatCommandEvent.getHandlers("we").register(commListener, Order.Default); // } // // public CUIConfiguration getConfiguration() { // return configuration; // } // // public void setConfiguration(CUIConfiguration configuration) { // this.configuration = configuration; // } // // public CUIDebug getDebugger() { // return debugger; // } // // public void setDebugger(CUIDebug debugger) { // this.debugger = debugger; // } // // public EventManager getEventManager() { // return eventManager; // } // // public void setEventManager(EventManager eventManager) { // this.eventManager = eventManager; // } // // /*public LocalPlugin getLocalPlugin() { // return localPlugin; // } // // public void setLocalPlugin(LocalPlugin localPlugin) { // this.localPlugin = localPlugin; // }*/ // // public Minecraft getMinecraft() { // return minecraft; // } // // public void setMinecraft(Minecraft minecraft) { // this.minecraft = minecraft; // } // // public Obfuscation getObfuscation() { // return obfuscation; // } // // public void setObfuscation(Obfuscation obfuscation) { // this.obfuscation = obfuscation; // } // // public BaseRegion getSelection() { // return selection; // } // // public void setSelection(BaseRegion selection) { // this.selection = selection; // } // // public static String getVersion() { // return VERSION + " for Minecraft version " + MCVERSION; // } // } // // Path: src/main/java/wecui/event/CUIEvent.java // public class CUIEvent extends Event<CUIEvent> { // // protected WorldEditCUI controller; // protected String type; // protected String[] params; // protected boolean handled = false; // public static final HandlerList<CUIEvent> handlers = new HandlerList<CUIEvent>(); // // public CUIEvent(WorldEditCUI controller, String type, String[] params) { // this.controller = controller; // this.type = type; // // //"".split("[|]") returns String[] {""} for some reason, instead of String[] {}. // if (params.length == 1 && params[0].length() == 0) { // params = new String[]{}; // } // // this.params = params; // this.controller.getDebugger().debug("CUI Event (" + type + ") - Params: " + Utilities.join(params, ", ")); // // } // // @Override // protected String getEventName() { // return "CUIEvent"; // } // // @Override // protected HandlerList<CUIEvent> getHandlers() { // return handlers; // } // // public void setHandled(boolean handled) { // this.handled = handled; // } // // /** // * Called upon receiving an invalid event. // * Debugs an error message and handles the event. // * // * @param reason Error message // */ // public void markInvalid(String reason) { // this.controller.getDebugger().debug("INVALID WECUIEvent " + type + " - " + Utilities.join(params, "|") + " - Reason: " + reason); // setHandled(true); // } // // public int getInt(int index) { // return (int) Float.parseFloat(params[index]); // } // // public String getString(int index) { // return params[index]; // } // // public boolean isHandled() { // return handled; // } // // public boolean isCancelled() { // return isHandled(); // } // // public String[] getParams() { // return params; // } // // public String getType() { // return type; // } // } // Path: src/main/java/deobf/spc_WorldEditCUI.java import wecui.WorldEditCUI; import wecui.event.CUIEvent; package deobf; /** * Main SinglePlayerCommands class * * @author lahwran * @author yetanotherx * */ public class spc_WorldEditCUI extends SPCPlugin { protected WorldEditCUI controller; public spc_WorldEditCUI(WorldEditCUI controller) { this.controller = controller; } @Override public String getVersion() { return WorldEditCUI.getVersion(); } @Override public String getName() { return "WorldEditCUI"; } @Override public void handleCUIEvent(String type, String params[]) { if (controller != null) {
controller.getEventManager().callEvent(new CUIEvent(controller, type, params));
yetanotherx/WorldEditCUI
src/main/java/deobf/EntityUpdateThread.java
// Path: src/main/java/wecui/obfuscation/Obfuscation.java // public class Obfuscation implements InitializationFactory { // // protected WorldEditCUI controller; // protected Minecraft minecraft; // // public Obfuscation(WorldEditCUI controller) { // this.controller = controller; // } // // @Override // public void initialize() { // this.minecraft = this.controller.getMinecraft(); // } // // public boolean isMultiplayerWorld() { // return true; // TODO - Temprarily until I can figure out the new server thing // //return minecraft.l(); // } // // /** // * Displays a chat message on the screen, if the player is currently playing // * @param chat // */ // public void showChatMessage(String chat) { // if (getPlayer() != null) { // getPlayer().b(chat); // } // } // // public EntityPlayerSP getPlayer() { // return getPlayer(minecraft); // } // // public WorldClient getWorld() { // return getWorld(minecraft); // } // // public Entity spawnEntity() { // Minecraft mc = this.controller.getMinecraft(); // // Entity entity = new RenderEntity(this.controller, getWorld(mc)); // setEntityPositionToPlayer(mc, entity); // getWorld(mc).d(entity); // setEntityPositionToPlayer(mc, entity); // controller.getDebugger().debug("RenderEntity spawned"); // return entity; // } // // public static double getPlayerX(EntityPlayerSP player) { // return player.t; // } // // public static double getPlayerY(EntityPlayerSP player) { // return player.u; // } // // public static double getPlayerZ(EntityPlayerSP player) { // return player.v; // } // // public double getPlayerXGuess(float renderTick) { // EntityPlayerSP plyr = getPlayer(); // return plyr.q + ((plyr.t - plyr.q) * renderTick); // } // // public double getPlayerYGuess(float renderTick) { // EntityPlayerSP plyr = getPlayer(); // return plyr.r + ((plyr.u - plyr.r) * renderTick); // } // // public double getPlayerZGuess(float renderTick) { // EntityPlayerSP plyr = getPlayer(); // return plyr.s + ((plyr.v - plyr.s) * renderTick); // } // // public static EntityPlayerSP getPlayer(Minecraft mc) { // return mc.g; // } // // public static WorldClient getWorld(Minecraft mc) { // return mc.e; // } // // public static void setEntityPositionToPlayer(Minecraft mc, Entity entity) { // entity.b(getPlayerX(mc.g), getPlayerY(mc.g), getPlayerZ(mc.g)); // } // // public NetClientHandler getNetClientHandler(EntityClientPlayerMP player) { // return player.a; // } // // public static String getChatFromPacket(Packet3Chat packet) { // return packet.b; // } // // public static byte[] getBytesFromPacket(Packet250CustomPayload packet) { // return packet.c; // } // // public static Packet250CustomPayload newPayloadPacket(String name, int len, byte[] data) { // Packet250CustomPayload packet = new Packet250CustomPayload(); // packet.a = name; // packet.b = len; // packet.c = data; // return packet; // } // // public static File getMinecraftDir() { // return Minecraft.b(); // } // // public static File getWorldEditCUIDir() { // return new File(getMinecraftDir(), "mods" + File.separator + "WorldEditCUI"); // } // }
import java.util.logging.Level; import java.util.logging.Logger; import wecui.obfuscation.Obfuscation;
package deobf; public class EntityUpdateThread extends Thread { private mod_WorldEditCUI mod; public EntityUpdateThread(mod_WorldEditCUI mod) { this.mod = mod; } @Override public void run() { while(true) { try { Thread.sleep(30000); } catch (InterruptedException ex) { Logger.getLogger(EntityUpdateThread.class.getName()).log(Level.SEVERE, null, ex); } if( mod.lastEntity != null ) {
// Path: src/main/java/wecui/obfuscation/Obfuscation.java // public class Obfuscation implements InitializationFactory { // // protected WorldEditCUI controller; // protected Minecraft minecraft; // // public Obfuscation(WorldEditCUI controller) { // this.controller = controller; // } // // @Override // public void initialize() { // this.minecraft = this.controller.getMinecraft(); // } // // public boolean isMultiplayerWorld() { // return true; // TODO - Temprarily until I can figure out the new server thing // //return minecraft.l(); // } // // /** // * Displays a chat message on the screen, if the player is currently playing // * @param chat // */ // public void showChatMessage(String chat) { // if (getPlayer() != null) { // getPlayer().b(chat); // } // } // // public EntityPlayerSP getPlayer() { // return getPlayer(minecraft); // } // // public WorldClient getWorld() { // return getWorld(minecraft); // } // // public Entity spawnEntity() { // Minecraft mc = this.controller.getMinecraft(); // // Entity entity = new RenderEntity(this.controller, getWorld(mc)); // setEntityPositionToPlayer(mc, entity); // getWorld(mc).d(entity); // setEntityPositionToPlayer(mc, entity); // controller.getDebugger().debug("RenderEntity spawned"); // return entity; // } // // public static double getPlayerX(EntityPlayerSP player) { // return player.t; // } // // public static double getPlayerY(EntityPlayerSP player) { // return player.u; // } // // public static double getPlayerZ(EntityPlayerSP player) { // return player.v; // } // // public double getPlayerXGuess(float renderTick) { // EntityPlayerSP plyr = getPlayer(); // return plyr.q + ((plyr.t - plyr.q) * renderTick); // } // // public double getPlayerYGuess(float renderTick) { // EntityPlayerSP plyr = getPlayer(); // return plyr.r + ((plyr.u - plyr.r) * renderTick); // } // // public double getPlayerZGuess(float renderTick) { // EntityPlayerSP plyr = getPlayer(); // return plyr.s + ((plyr.v - plyr.s) * renderTick); // } // // public static EntityPlayerSP getPlayer(Minecraft mc) { // return mc.g; // } // // public static WorldClient getWorld(Minecraft mc) { // return mc.e; // } // // public static void setEntityPositionToPlayer(Minecraft mc, Entity entity) { // entity.b(getPlayerX(mc.g), getPlayerY(mc.g), getPlayerZ(mc.g)); // } // // public NetClientHandler getNetClientHandler(EntityClientPlayerMP player) { // return player.a; // } // // public static String getChatFromPacket(Packet3Chat packet) { // return packet.b; // } // // public static byte[] getBytesFromPacket(Packet250CustomPayload packet) { // return packet.c; // } // // public static Packet250CustomPayload newPayloadPacket(String name, int len, byte[] data) { // Packet250CustomPayload packet = new Packet250CustomPayload(); // packet.a = name; // packet.b = len; // packet.c = data; // return packet; // } // // public static File getMinecraftDir() { // return Minecraft.b(); // } // // public static File getWorldEditCUIDir() { // return new File(getMinecraftDir(), "mods" + File.separator + "WorldEditCUI"); // } // } // Path: src/main/java/deobf/EntityUpdateThread.java import java.util.logging.Level; import java.util.logging.Logger; import wecui.obfuscation.Obfuscation; package deobf; public class EntityUpdateThread extends Thread { private mod_WorldEditCUI mod; public EntityUpdateThread(mod_WorldEditCUI mod) { this.mod = mod; } @Override public void run() { while(true) { try { Thread.sleep(30000); } catch (InterruptedException ex) { Logger.getLogger(EntityUpdateThread.class.getName()).log(Level.SEVERE, null, ex); } if( mod.lastEntity != null ) {
Obfuscation.setEntityPositionToPlayer(mod.controller.getMinecraft(), mod.lastEntity);
yetanotherx/WorldEditCUI
src/main/java/wecui/config/Configuration.java
// Path: src/main/java/wecui/exception/ConfigurationException.java // public class ConfigurationException extends Exception { // // private static final long serialVersionUID = -2442886939908724203L; // // public ConfigurationException() { // super(); // } // // public ConfigurationException(String msg) { // super(msg); // } // }
import wecui.exception.ConfigurationException; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.util.HashMap; import java.util.Map; import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.constructor.SafeConstructor; import org.yaml.snakeyaml.reader.UnicodeReader;
package wecui.config; /** * YAML configuration loader. To use this class, construct it with path to * a file and call its load() method. For specifying node paths in the * various get*() methods, they support SK's path notation, allowing you to * select child nodes by delimiting node names with periods. * * <p> * For example, given the following configuration file:</p> * * <pre>members: * - Hollie * - Jason * - Bobo * - Aya * - Tetsu * worldguard: * fire: * spread: false * blocks: [cloth, rock, glass] * sturmeh: * cool: false * eats: * babies: true</pre> * * <p>Calling code could access sturmeh's baby eating state by using * <code>getBoolean("sturmeh.eats.babies", false)</code>. For lists, there are * methods such as <code>getStringList</code> that will return a type safe list. * * <p>This class is currently incomplete. It is not yet possible to get a node. * </p> * */ public class Configuration extends ConfigurationNode { private Yaml yaml; private File file; private String header = null; public Configuration(File file) { super(new HashMap<String, Object>()); DumperOptions options = new DumperOptions(); options.setIndent(4); options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); yaml = new Yaml(new SafeConstructor(), new EmptyNullRepresenter(), options); this.file = file; } /** * Loads the configuration file. All errors are thrown away. */ public void load() { FileInputStream stream = null; try { stream = new FileInputStream(file); read(yaml.load(new UnicodeReader(stream))); } catch (IOException e) { root = new HashMap<String, Object>();
// Path: src/main/java/wecui/exception/ConfigurationException.java // public class ConfigurationException extends Exception { // // private static final long serialVersionUID = -2442886939908724203L; // // public ConfigurationException() { // super(); // } // // public ConfigurationException(String msg) { // super(msg); // } // } // Path: src/main/java/wecui/config/Configuration.java import wecui.exception.ConfigurationException; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.util.HashMap; import java.util.Map; import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.constructor.SafeConstructor; import org.yaml.snakeyaml.reader.UnicodeReader; package wecui.config; /** * YAML configuration loader. To use this class, construct it with path to * a file and call its load() method. For specifying node paths in the * various get*() methods, they support SK's path notation, allowing you to * select child nodes by delimiting node names with periods. * * <p> * For example, given the following configuration file:</p> * * <pre>members: * - Hollie * - Jason * - Bobo * - Aya * - Tetsu * worldguard: * fire: * spread: false * blocks: [cloth, rock, glass] * sturmeh: * cool: false * eats: * babies: true</pre> * * <p>Calling code could access sturmeh's baby eating state by using * <code>getBoolean("sturmeh.eats.babies", false)</code>. For lists, there are * methods such as <code>getStringList</code> that will return a type safe list. * * <p>This class is currently incomplete. It is not yet possible to get a node. * </p> * */ public class Configuration extends ConfigurationNode { private Yaml yaml; private File file; private String header = null; public Configuration(File file) { super(new HashMap<String, Object>()); DumperOptions options = new DumperOptions(); options.setIndent(4); options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); yaml = new Yaml(new SafeConstructor(), new EmptyNullRepresenter(), options); this.file = file; } /** * Loads the configuration file. All errors are thrown away. */ public void load() { FileInputStream stream = null; try { stream = new FileInputStream(file); read(yaml.load(new UnicodeReader(stream))); } catch (IOException e) { root = new HashMap<String, Object>();
} catch (ConfigurationException e) {
yetanotherx/WorldEditCUI
src/main/java/wecui/render/RenderHooks.java
// Path: src/main/java/wecui/event/WorldRenderEvent.java // public class WorldRenderEvent extends Event<WorldRenderEvent> { // // protected WorldEditCUI controller; // protected float partialTick; // protected Vector3 pos; // public static final HandlerList<WorldRenderEvent> handlers = new HandlerList<WorldRenderEvent>(); // // public WorldRenderEvent(WorldEditCUI controller) { // } // // public void setPartialTick(float partialTick) { // this.partialTick = partialTick; // } // // public void setPosition(Vector3 pos) { // this.pos = pos; // } // // public float getPartialTick() { // return partialTick; // } // // public Vector3 getPosition() { // return pos; // } // // @Override // protected String getEventName() { // return "WorldRenderEvent"; // } // // @Override // protected HandlerList<WorldRenderEvent> getHandlers() { // return handlers; // } // } // // Path: src/main/java/wecui/WorldEditCUI.java // public class WorldEditCUI { // // public static final String VERSION = "1.4.5"; // public static final String MCVERSION = "1.4.5"; // public static final int protocolVersion = 2; // protected Minecraft minecraft; // protected EventManager eventManager; // protected Obfuscation obfuscation; // protected BaseRegion selection; // protected CUIDebug debugger; // protected CUIConfiguration configuration; // //protected LocalPlugin localPlugin; // // public WorldEditCUI(Minecraft minecraft) { // this.minecraft = minecraft; // } // // public void initialize() { // this.eventManager = new EventManager(this); // this.obfuscation = new Obfuscation(this); // this.selection = new CuboidRegion(this); // this.configuration = new CUIConfiguration(this); // this.debugger = new CUIDebug(this); // //this.localPlugin = new LocalPlugin(this); // // try { // this.eventManager.initialize(); // this.obfuscation.initialize(); // this.selection.initialize(); // this.configuration.initialize(); // this.debugger.initialize(); // //this.localPlugin.initialize(); // } catch (InitializationException e) { // e.printStackTrace(); // return; // } // // this.registerListeners(); // } // // protected void registerListeners() { // CUIEvent.handlers.register(new CUIListener(this), Order.Default); // ChannelEvent.handlers.register(new ChannelListener(this), Order.Default); // WorldRenderEvent.handlers.register(new WorldRenderListener(this), Order.Default); // // WorldEditCommandListener commListener = new WorldEditCommandListener(this); // ChatCommandEvent.getHandlers("worldedit").register(commListener, Order.Default); // ChatCommandEvent.getHandlers("we").register(commListener, Order.Default); // } // // public CUIConfiguration getConfiguration() { // return configuration; // } // // public void setConfiguration(CUIConfiguration configuration) { // this.configuration = configuration; // } // // public CUIDebug getDebugger() { // return debugger; // } // // public void setDebugger(CUIDebug debugger) { // this.debugger = debugger; // } // // public EventManager getEventManager() { // return eventManager; // } // // public void setEventManager(EventManager eventManager) { // this.eventManager = eventManager; // } // // /*public LocalPlugin getLocalPlugin() { // return localPlugin; // } // // public void setLocalPlugin(LocalPlugin localPlugin) { // this.localPlugin = localPlugin; // }*/ // // public Minecraft getMinecraft() { // return minecraft; // } // // public void setMinecraft(Minecraft minecraft) { // this.minecraft = minecraft; // } // // public Obfuscation getObfuscation() { // return obfuscation; // } // // public void setObfuscation(Obfuscation obfuscation) { // this.obfuscation = obfuscation; // } // // public BaseRegion getSelection() { // return selection; // } // // public void setSelection(BaseRegion selection) { // this.selection = selection; // } // // public static String getVersion() { // return VERSION + " for Minecraft version " + MCVERSION; // } // } // // Path: src/main/java/wecui/obfuscation/RenderObfuscation.java // public class RenderObfuscation { // // protected Tessellator tess; // // protected RenderObfuscation() { // tess = Tessellator.a; // } // // public void startDrawing(int type) { // tess.b(type); // } // // public void addVertex(double x, double y, double z) { // tess.a(x, y, z); // } // // public void finishDrawing() { // tess.a(); // } // // /** // * TODO: Find if this is even necessary // */ // public static void disableLighting() { // RenderHelper.a(); // } // // public static void enableLighting() { // RenderHelper.b(); // } // // public static RenderObfuscation getInstance() { // return RenderObfuscationHolder.INSTANCE; // } // // protected static class RenderObfuscationHolder { // // protected static final RenderObfuscation INSTANCE = new RenderObfuscation(); // } // }
import deobf.Entity; import deobf.Render; import wecui.event.WorldRenderEvent; import wecui.WorldEditCUI; import wecui.obfuscation.RenderObfuscation;
package wecui.render; /** * Custom entity renderer, attached in the ModLoader class * * @author lahwran * @author yetanotherx * * @obfuscated 1.4.5 */ public class RenderHooks extends Render { protected WorldEditCUI controller;
// Path: src/main/java/wecui/event/WorldRenderEvent.java // public class WorldRenderEvent extends Event<WorldRenderEvent> { // // protected WorldEditCUI controller; // protected float partialTick; // protected Vector3 pos; // public static final HandlerList<WorldRenderEvent> handlers = new HandlerList<WorldRenderEvent>(); // // public WorldRenderEvent(WorldEditCUI controller) { // } // // public void setPartialTick(float partialTick) { // this.partialTick = partialTick; // } // // public void setPosition(Vector3 pos) { // this.pos = pos; // } // // public float getPartialTick() { // return partialTick; // } // // public Vector3 getPosition() { // return pos; // } // // @Override // protected String getEventName() { // return "WorldRenderEvent"; // } // // @Override // protected HandlerList<WorldRenderEvent> getHandlers() { // return handlers; // } // } // // Path: src/main/java/wecui/WorldEditCUI.java // public class WorldEditCUI { // // public static final String VERSION = "1.4.5"; // public static final String MCVERSION = "1.4.5"; // public static final int protocolVersion = 2; // protected Minecraft minecraft; // protected EventManager eventManager; // protected Obfuscation obfuscation; // protected BaseRegion selection; // protected CUIDebug debugger; // protected CUIConfiguration configuration; // //protected LocalPlugin localPlugin; // // public WorldEditCUI(Minecraft minecraft) { // this.minecraft = minecraft; // } // // public void initialize() { // this.eventManager = new EventManager(this); // this.obfuscation = new Obfuscation(this); // this.selection = new CuboidRegion(this); // this.configuration = new CUIConfiguration(this); // this.debugger = new CUIDebug(this); // //this.localPlugin = new LocalPlugin(this); // // try { // this.eventManager.initialize(); // this.obfuscation.initialize(); // this.selection.initialize(); // this.configuration.initialize(); // this.debugger.initialize(); // //this.localPlugin.initialize(); // } catch (InitializationException e) { // e.printStackTrace(); // return; // } // // this.registerListeners(); // } // // protected void registerListeners() { // CUIEvent.handlers.register(new CUIListener(this), Order.Default); // ChannelEvent.handlers.register(new ChannelListener(this), Order.Default); // WorldRenderEvent.handlers.register(new WorldRenderListener(this), Order.Default); // // WorldEditCommandListener commListener = new WorldEditCommandListener(this); // ChatCommandEvent.getHandlers("worldedit").register(commListener, Order.Default); // ChatCommandEvent.getHandlers("we").register(commListener, Order.Default); // } // // public CUIConfiguration getConfiguration() { // return configuration; // } // // public void setConfiguration(CUIConfiguration configuration) { // this.configuration = configuration; // } // // public CUIDebug getDebugger() { // return debugger; // } // // public void setDebugger(CUIDebug debugger) { // this.debugger = debugger; // } // // public EventManager getEventManager() { // return eventManager; // } // // public void setEventManager(EventManager eventManager) { // this.eventManager = eventManager; // } // // /*public LocalPlugin getLocalPlugin() { // return localPlugin; // } // // public void setLocalPlugin(LocalPlugin localPlugin) { // this.localPlugin = localPlugin; // }*/ // // public Minecraft getMinecraft() { // return minecraft; // } // // public void setMinecraft(Minecraft minecraft) { // this.minecraft = minecraft; // } // // public Obfuscation getObfuscation() { // return obfuscation; // } // // public void setObfuscation(Obfuscation obfuscation) { // this.obfuscation = obfuscation; // } // // public BaseRegion getSelection() { // return selection; // } // // public void setSelection(BaseRegion selection) { // this.selection = selection; // } // // public static String getVersion() { // return VERSION + " for Minecraft version " + MCVERSION; // } // } // // Path: src/main/java/wecui/obfuscation/RenderObfuscation.java // public class RenderObfuscation { // // protected Tessellator tess; // // protected RenderObfuscation() { // tess = Tessellator.a; // } // // public void startDrawing(int type) { // tess.b(type); // } // // public void addVertex(double x, double y, double z) { // tess.a(x, y, z); // } // // public void finishDrawing() { // tess.a(); // } // // /** // * TODO: Find if this is even necessary // */ // public static void disableLighting() { // RenderHelper.a(); // } // // public static void enableLighting() { // RenderHelper.b(); // } // // public static RenderObfuscation getInstance() { // return RenderObfuscationHolder.INSTANCE; // } // // protected static class RenderObfuscationHolder { // // protected static final RenderObfuscation INSTANCE = new RenderObfuscation(); // } // } // Path: src/main/java/wecui/render/RenderHooks.java import deobf.Entity; import deobf.Render; import wecui.event.WorldRenderEvent; import wecui.WorldEditCUI; import wecui.obfuscation.RenderObfuscation; package wecui.render; /** * Custom entity renderer, attached in the ModLoader class * * @author lahwran * @author yetanotherx * * @obfuscated 1.4.5 */ public class RenderHooks extends Render { protected WorldEditCUI controller;
protected WorldRenderEvent event;
yetanotherx/WorldEditCUI
src/main/java/wecui/render/RenderHooks.java
// Path: src/main/java/wecui/event/WorldRenderEvent.java // public class WorldRenderEvent extends Event<WorldRenderEvent> { // // protected WorldEditCUI controller; // protected float partialTick; // protected Vector3 pos; // public static final HandlerList<WorldRenderEvent> handlers = new HandlerList<WorldRenderEvent>(); // // public WorldRenderEvent(WorldEditCUI controller) { // } // // public void setPartialTick(float partialTick) { // this.partialTick = partialTick; // } // // public void setPosition(Vector3 pos) { // this.pos = pos; // } // // public float getPartialTick() { // return partialTick; // } // // public Vector3 getPosition() { // return pos; // } // // @Override // protected String getEventName() { // return "WorldRenderEvent"; // } // // @Override // protected HandlerList<WorldRenderEvent> getHandlers() { // return handlers; // } // } // // Path: src/main/java/wecui/WorldEditCUI.java // public class WorldEditCUI { // // public static final String VERSION = "1.4.5"; // public static final String MCVERSION = "1.4.5"; // public static final int protocolVersion = 2; // protected Minecraft minecraft; // protected EventManager eventManager; // protected Obfuscation obfuscation; // protected BaseRegion selection; // protected CUIDebug debugger; // protected CUIConfiguration configuration; // //protected LocalPlugin localPlugin; // // public WorldEditCUI(Minecraft minecraft) { // this.minecraft = minecraft; // } // // public void initialize() { // this.eventManager = new EventManager(this); // this.obfuscation = new Obfuscation(this); // this.selection = new CuboidRegion(this); // this.configuration = new CUIConfiguration(this); // this.debugger = new CUIDebug(this); // //this.localPlugin = new LocalPlugin(this); // // try { // this.eventManager.initialize(); // this.obfuscation.initialize(); // this.selection.initialize(); // this.configuration.initialize(); // this.debugger.initialize(); // //this.localPlugin.initialize(); // } catch (InitializationException e) { // e.printStackTrace(); // return; // } // // this.registerListeners(); // } // // protected void registerListeners() { // CUIEvent.handlers.register(new CUIListener(this), Order.Default); // ChannelEvent.handlers.register(new ChannelListener(this), Order.Default); // WorldRenderEvent.handlers.register(new WorldRenderListener(this), Order.Default); // // WorldEditCommandListener commListener = new WorldEditCommandListener(this); // ChatCommandEvent.getHandlers("worldedit").register(commListener, Order.Default); // ChatCommandEvent.getHandlers("we").register(commListener, Order.Default); // } // // public CUIConfiguration getConfiguration() { // return configuration; // } // // public void setConfiguration(CUIConfiguration configuration) { // this.configuration = configuration; // } // // public CUIDebug getDebugger() { // return debugger; // } // // public void setDebugger(CUIDebug debugger) { // this.debugger = debugger; // } // // public EventManager getEventManager() { // return eventManager; // } // // public void setEventManager(EventManager eventManager) { // this.eventManager = eventManager; // } // // /*public LocalPlugin getLocalPlugin() { // return localPlugin; // } // // public void setLocalPlugin(LocalPlugin localPlugin) { // this.localPlugin = localPlugin; // }*/ // // public Minecraft getMinecraft() { // return minecraft; // } // // public void setMinecraft(Minecraft minecraft) { // this.minecraft = minecraft; // } // // public Obfuscation getObfuscation() { // return obfuscation; // } // // public void setObfuscation(Obfuscation obfuscation) { // this.obfuscation = obfuscation; // } // // public BaseRegion getSelection() { // return selection; // } // // public void setSelection(BaseRegion selection) { // this.selection = selection; // } // // public static String getVersion() { // return VERSION + " for Minecraft version " + MCVERSION; // } // } // // Path: src/main/java/wecui/obfuscation/RenderObfuscation.java // public class RenderObfuscation { // // protected Tessellator tess; // // protected RenderObfuscation() { // tess = Tessellator.a; // } // // public void startDrawing(int type) { // tess.b(type); // } // // public void addVertex(double x, double y, double z) { // tess.a(x, y, z); // } // // public void finishDrawing() { // tess.a(); // } // // /** // * TODO: Find if this is even necessary // */ // public static void disableLighting() { // RenderHelper.a(); // } // // public static void enableLighting() { // RenderHelper.b(); // } // // public static RenderObfuscation getInstance() { // return RenderObfuscationHolder.INSTANCE; // } // // protected static class RenderObfuscationHolder { // // protected static final RenderObfuscation INSTANCE = new RenderObfuscation(); // } // }
import deobf.Entity; import deobf.Render; import wecui.event.WorldRenderEvent; import wecui.WorldEditCUI; import wecui.obfuscation.RenderObfuscation;
package wecui.render; /** * Custom entity renderer, attached in the ModLoader class * * @author lahwran * @author yetanotherx * * @obfuscated 1.4.5 */ public class RenderHooks extends Render { protected WorldEditCUI controller; protected WorldRenderEvent event; public RenderHooks(WorldEditCUI controller) { this.controller = controller; this.event = new WorldRenderEvent(controller); } /** * Actually renders the entity. * @param entity * @param x * @param y * @param z * @param yaw * @param renderTick */ public void renderCUI(Entity entity, double x, double y, double z, float yaw, float renderTick) {
// Path: src/main/java/wecui/event/WorldRenderEvent.java // public class WorldRenderEvent extends Event<WorldRenderEvent> { // // protected WorldEditCUI controller; // protected float partialTick; // protected Vector3 pos; // public static final HandlerList<WorldRenderEvent> handlers = new HandlerList<WorldRenderEvent>(); // // public WorldRenderEvent(WorldEditCUI controller) { // } // // public void setPartialTick(float partialTick) { // this.partialTick = partialTick; // } // // public void setPosition(Vector3 pos) { // this.pos = pos; // } // // public float getPartialTick() { // return partialTick; // } // // public Vector3 getPosition() { // return pos; // } // // @Override // protected String getEventName() { // return "WorldRenderEvent"; // } // // @Override // protected HandlerList<WorldRenderEvent> getHandlers() { // return handlers; // } // } // // Path: src/main/java/wecui/WorldEditCUI.java // public class WorldEditCUI { // // public static final String VERSION = "1.4.5"; // public static final String MCVERSION = "1.4.5"; // public static final int protocolVersion = 2; // protected Minecraft minecraft; // protected EventManager eventManager; // protected Obfuscation obfuscation; // protected BaseRegion selection; // protected CUIDebug debugger; // protected CUIConfiguration configuration; // //protected LocalPlugin localPlugin; // // public WorldEditCUI(Minecraft minecraft) { // this.minecraft = minecraft; // } // // public void initialize() { // this.eventManager = new EventManager(this); // this.obfuscation = new Obfuscation(this); // this.selection = new CuboidRegion(this); // this.configuration = new CUIConfiguration(this); // this.debugger = new CUIDebug(this); // //this.localPlugin = new LocalPlugin(this); // // try { // this.eventManager.initialize(); // this.obfuscation.initialize(); // this.selection.initialize(); // this.configuration.initialize(); // this.debugger.initialize(); // //this.localPlugin.initialize(); // } catch (InitializationException e) { // e.printStackTrace(); // return; // } // // this.registerListeners(); // } // // protected void registerListeners() { // CUIEvent.handlers.register(new CUIListener(this), Order.Default); // ChannelEvent.handlers.register(new ChannelListener(this), Order.Default); // WorldRenderEvent.handlers.register(new WorldRenderListener(this), Order.Default); // // WorldEditCommandListener commListener = new WorldEditCommandListener(this); // ChatCommandEvent.getHandlers("worldedit").register(commListener, Order.Default); // ChatCommandEvent.getHandlers("we").register(commListener, Order.Default); // } // // public CUIConfiguration getConfiguration() { // return configuration; // } // // public void setConfiguration(CUIConfiguration configuration) { // this.configuration = configuration; // } // // public CUIDebug getDebugger() { // return debugger; // } // // public void setDebugger(CUIDebug debugger) { // this.debugger = debugger; // } // // public EventManager getEventManager() { // return eventManager; // } // // public void setEventManager(EventManager eventManager) { // this.eventManager = eventManager; // } // // /*public LocalPlugin getLocalPlugin() { // return localPlugin; // } // // public void setLocalPlugin(LocalPlugin localPlugin) { // this.localPlugin = localPlugin; // }*/ // // public Minecraft getMinecraft() { // return minecraft; // } // // public void setMinecraft(Minecraft minecraft) { // this.minecraft = minecraft; // } // // public Obfuscation getObfuscation() { // return obfuscation; // } // // public void setObfuscation(Obfuscation obfuscation) { // this.obfuscation = obfuscation; // } // // public BaseRegion getSelection() { // return selection; // } // // public void setSelection(BaseRegion selection) { // this.selection = selection; // } // // public static String getVersion() { // return VERSION + " for Minecraft version " + MCVERSION; // } // } // // Path: src/main/java/wecui/obfuscation/RenderObfuscation.java // public class RenderObfuscation { // // protected Tessellator tess; // // protected RenderObfuscation() { // tess = Tessellator.a; // } // // public void startDrawing(int type) { // tess.b(type); // } // // public void addVertex(double x, double y, double z) { // tess.a(x, y, z); // } // // public void finishDrawing() { // tess.a(); // } // // /** // * TODO: Find if this is even necessary // */ // public static void disableLighting() { // RenderHelper.a(); // } // // public static void enableLighting() { // RenderHelper.b(); // } // // public static RenderObfuscation getInstance() { // return RenderObfuscationHolder.INSTANCE; // } // // protected static class RenderObfuscationHolder { // // protected static final RenderObfuscation INSTANCE = new RenderObfuscation(); // } // } // Path: src/main/java/wecui/render/RenderHooks.java import deobf.Entity; import deobf.Render; import wecui.event.WorldRenderEvent; import wecui.WorldEditCUI; import wecui.obfuscation.RenderObfuscation; package wecui.render; /** * Custom entity renderer, attached in the ModLoader class * * @author lahwran * @author yetanotherx * * @obfuscated 1.4.5 */ public class RenderHooks extends Render { protected WorldEditCUI controller; protected WorldRenderEvent event; public RenderHooks(WorldEditCUI controller) { this.controller = controller; this.event = new WorldRenderEvent(controller); } /** * Actually renders the entity. * @param entity * @param x * @param y * @param z * @param yaw * @param renderTick */ public void renderCUI(Entity entity, double x, double y, double z, float yaw, float renderTick) {
RenderObfuscation.disableLighting();
yetanotherx/WorldEditCUI
src/main/java/wecui/CUIDebug.java
// Path: src/main/java/wecui/exception/InitializationException.java // public class InitializationException extends Exception { // // private static final long serialVersionUID = 1L; // // public InitializationException(String string) { // super(string); // } // // public InitializationException() { // } // } // // Path: src/main/java/wecui/obfuscation/Obfuscation.java // public class Obfuscation implements InitializationFactory { // // protected WorldEditCUI controller; // protected Minecraft minecraft; // // public Obfuscation(WorldEditCUI controller) { // this.controller = controller; // } // // @Override // public void initialize() { // this.minecraft = this.controller.getMinecraft(); // } // // public boolean isMultiplayerWorld() { // return true; // TODO - Temprarily until I can figure out the new server thing // //return minecraft.l(); // } // // /** // * Displays a chat message on the screen, if the player is currently playing // * @param chat // */ // public void showChatMessage(String chat) { // if (getPlayer() != null) { // getPlayer().b(chat); // } // } // // public EntityPlayerSP getPlayer() { // return getPlayer(minecraft); // } // // public WorldClient getWorld() { // return getWorld(minecraft); // } // // public Entity spawnEntity() { // Minecraft mc = this.controller.getMinecraft(); // // Entity entity = new RenderEntity(this.controller, getWorld(mc)); // setEntityPositionToPlayer(mc, entity); // getWorld(mc).d(entity); // setEntityPositionToPlayer(mc, entity); // controller.getDebugger().debug("RenderEntity spawned"); // return entity; // } // // public static double getPlayerX(EntityPlayerSP player) { // return player.t; // } // // public static double getPlayerY(EntityPlayerSP player) { // return player.u; // } // // public static double getPlayerZ(EntityPlayerSP player) { // return player.v; // } // // public double getPlayerXGuess(float renderTick) { // EntityPlayerSP plyr = getPlayer(); // return plyr.q + ((plyr.t - plyr.q) * renderTick); // } // // public double getPlayerYGuess(float renderTick) { // EntityPlayerSP plyr = getPlayer(); // return plyr.r + ((plyr.u - plyr.r) * renderTick); // } // // public double getPlayerZGuess(float renderTick) { // EntityPlayerSP plyr = getPlayer(); // return plyr.s + ((plyr.v - plyr.s) * renderTick); // } // // public static EntityPlayerSP getPlayer(Minecraft mc) { // return mc.g; // } // // public static WorldClient getWorld(Minecraft mc) { // return mc.e; // } // // public static void setEntityPositionToPlayer(Minecraft mc, Entity entity) { // entity.b(getPlayerX(mc.g), getPlayerY(mc.g), getPlayerZ(mc.g)); // } // // public NetClientHandler getNetClientHandler(EntityClientPlayerMP player) { // return player.a; // } // // public static String getChatFromPacket(Packet3Chat packet) { // return packet.b; // } // // public static byte[] getBytesFromPacket(Packet250CustomPayload packet) { // return packet.c; // } // // public static Packet250CustomPayload newPayloadPacket(String name, int len, byte[] data) { // Packet250CustomPayload packet = new Packet250CustomPayload(); // packet.a = name; // packet.b = len; // packet.c = data; // return packet; // } // // public static File getMinecraftDir() { // return Minecraft.b(); // } // // public static File getWorldEditCUIDir() { // return new File(getMinecraftDir(), "mods" + File.separator + "WorldEditCUI"); // } // } // // Path: src/main/java/wecui/util/ConsoleLogFormatter.java // public class ConsoleLogFormatter extends Formatter { // // private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // // public String format(LogRecord logrecord) { // StringBuilder stringbuilder = new StringBuilder(); // // stringbuilder.append(this.format.format(Long.valueOf(logrecord.getMillis()))); // Level level = logrecord.getLevel(); // // if (level == Level.FINEST) { // stringbuilder.append(" [FINEST] "); // } else if (level == Level.FINER) { // stringbuilder.append(" [FINER] "); // } else if (level == Level.FINE) { // stringbuilder.append(" [FINE] "); // } else if (level == Level.INFO) { // stringbuilder.append(" [INFO] "); // } else if (level == Level.WARNING) { // stringbuilder.append(" [WARNING] "); // } else if (level == Level.SEVERE) { // stringbuilder.append(" [SEVERE] "); // } else { // stringbuilder.append(" [").append(level.getLocalizedName()).append("] "); // } // // stringbuilder.append(logrecord.getMessage()); // stringbuilder.append('\n'); // Throwable throwable = logrecord.getThrown(); // // if (throwable != null) { // StringWriter stringwriter = new StringWriter(); // // throwable.printStackTrace(new PrintWriter(stringwriter)); // stringbuilder.append(stringwriter.toString()); // } // // return stringbuilder.toString(); // } // }
import java.io.File; import java.io.IOException; import java.util.logging.ConsoleHandler; import java.util.logging.FileHandler; import java.util.logging.Level; import java.util.logging.Logger; import wecui.exception.InitializationException; import wecui.obfuscation.Obfuscation; import wecui.util.ConsoleLogFormatter;
package wecui; /** * Debugging helper class * * @author yetanotherx * */ public class CUIDebug implements InitializationFactory { protected WorldEditCUI controller; protected File debugFile; protected boolean debugMode = false; protected final static Logger logger = Logger.getLogger("WorldEditCUI"); public CUIDebug(WorldEditCUI controller) { this.controller = controller; } @Override
// Path: src/main/java/wecui/exception/InitializationException.java // public class InitializationException extends Exception { // // private static final long serialVersionUID = 1L; // // public InitializationException(String string) { // super(string); // } // // public InitializationException() { // } // } // // Path: src/main/java/wecui/obfuscation/Obfuscation.java // public class Obfuscation implements InitializationFactory { // // protected WorldEditCUI controller; // protected Minecraft minecraft; // // public Obfuscation(WorldEditCUI controller) { // this.controller = controller; // } // // @Override // public void initialize() { // this.minecraft = this.controller.getMinecraft(); // } // // public boolean isMultiplayerWorld() { // return true; // TODO - Temprarily until I can figure out the new server thing // //return minecraft.l(); // } // // /** // * Displays a chat message on the screen, if the player is currently playing // * @param chat // */ // public void showChatMessage(String chat) { // if (getPlayer() != null) { // getPlayer().b(chat); // } // } // // public EntityPlayerSP getPlayer() { // return getPlayer(minecraft); // } // // public WorldClient getWorld() { // return getWorld(minecraft); // } // // public Entity spawnEntity() { // Minecraft mc = this.controller.getMinecraft(); // // Entity entity = new RenderEntity(this.controller, getWorld(mc)); // setEntityPositionToPlayer(mc, entity); // getWorld(mc).d(entity); // setEntityPositionToPlayer(mc, entity); // controller.getDebugger().debug("RenderEntity spawned"); // return entity; // } // // public static double getPlayerX(EntityPlayerSP player) { // return player.t; // } // // public static double getPlayerY(EntityPlayerSP player) { // return player.u; // } // // public static double getPlayerZ(EntityPlayerSP player) { // return player.v; // } // // public double getPlayerXGuess(float renderTick) { // EntityPlayerSP plyr = getPlayer(); // return plyr.q + ((plyr.t - plyr.q) * renderTick); // } // // public double getPlayerYGuess(float renderTick) { // EntityPlayerSP plyr = getPlayer(); // return plyr.r + ((plyr.u - plyr.r) * renderTick); // } // // public double getPlayerZGuess(float renderTick) { // EntityPlayerSP plyr = getPlayer(); // return plyr.s + ((plyr.v - plyr.s) * renderTick); // } // // public static EntityPlayerSP getPlayer(Minecraft mc) { // return mc.g; // } // // public static WorldClient getWorld(Minecraft mc) { // return mc.e; // } // // public static void setEntityPositionToPlayer(Minecraft mc, Entity entity) { // entity.b(getPlayerX(mc.g), getPlayerY(mc.g), getPlayerZ(mc.g)); // } // // public NetClientHandler getNetClientHandler(EntityClientPlayerMP player) { // return player.a; // } // // public static String getChatFromPacket(Packet3Chat packet) { // return packet.b; // } // // public static byte[] getBytesFromPacket(Packet250CustomPayload packet) { // return packet.c; // } // // public static Packet250CustomPayload newPayloadPacket(String name, int len, byte[] data) { // Packet250CustomPayload packet = new Packet250CustomPayload(); // packet.a = name; // packet.b = len; // packet.c = data; // return packet; // } // // public static File getMinecraftDir() { // return Minecraft.b(); // } // // public static File getWorldEditCUIDir() { // return new File(getMinecraftDir(), "mods" + File.separator + "WorldEditCUI"); // } // } // // Path: src/main/java/wecui/util/ConsoleLogFormatter.java // public class ConsoleLogFormatter extends Formatter { // // private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // // public String format(LogRecord logrecord) { // StringBuilder stringbuilder = new StringBuilder(); // // stringbuilder.append(this.format.format(Long.valueOf(logrecord.getMillis()))); // Level level = logrecord.getLevel(); // // if (level == Level.FINEST) { // stringbuilder.append(" [FINEST] "); // } else if (level == Level.FINER) { // stringbuilder.append(" [FINER] "); // } else if (level == Level.FINE) { // stringbuilder.append(" [FINE] "); // } else if (level == Level.INFO) { // stringbuilder.append(" [INFO] "); // } else if (level == Level.WARNING) { // stringbuilder.append(" [WARNING] "); // } else if (level == Level.SEVERE) { // stringbuilder.append(" [SEVERE] "); // } else { // stringbuilder.append(" [").append(level.getLocalizedName()).append("] "); // } // // stringbuilder.append(logrecord.getMessage()); // stringbuilder.append('\n'); // Throwable throwable = logrecord.getThrown(); // // if (throwable != null) { // StringWriter stringwriter = new StringWriter(); // // throwable.printStackTrace(new PrintWriter(stringwriter)); // stringbuilder.append(stringwriter.toString()); // } // // return stringbuilder.toString(); // } // } // Path: src/main/java/wecui/CUIDebug.java import java.io.File; import java.io.IOException; import java.util.logging.ConsoleHandler; import java.util.logging.FileHandler; import java.util.logging.Level; import java.util.logging.Logger; import wecui.exception.InitializationException; import wecui.obfuscation.Obfuscation; import wecui.util.ConsoleLogFormatter; package wecui; /** * Debugging helper class * * @author yetanotherx * */ public class CUIDebug implements InitializationFactory { protected WorldEditCUI controller; protected File debugFile; protected boolean debugMode = false; protected final static Logger logger = Logger.getLogger("WorldEditCUI"); public CUIDebug(WorldEditCUI controller) { this.controller = controller; } @Override
public void initialize() throws InitializationException {
yetanotherx/WorldEditCUI
src/main/java/wecui/CUIDebug.java
// Path: src/main/java/wecui/exception/InitializationException.java // public class InitializationException extends Exception { // // private static final long serialVersionUID = 1L; // // public InitializationException(String string) { // super(string); // } // // public InitializationException() { // } // } // // Path: src/main/java/wecui/obfuscation/Obfuscation.java // public class Obfuscation implements InitializationFactory { // // protected WorldEditCUI controller; // protected Minecraft minecraft; // // public Obfuscation(WorldEditCUI controller) { // this.controller = controller; // } // // @Override // public void initialize() { // this.minecraft = this.controller.getMinecraft(); // } // // public boolean isMultiplayerWorld() { // return true; // TODO - Temprarily until I can figure out the new server thing // //return minecraft.l(); // } // // /** // * Displays a chat message on the screen, if the player is currently playing // * @param chat // */ // public void showChatMessage(String chat) { // if (getPlayer() != null) { // getPlayer().b(chat); // } // } // // public EntityPlayerSP getPlayer() { // return getPlayer(minecraft); // } // // public WorldClient getWorld() { // return getWorld(minecraft); // } // // public Entity spawnEntity() { // Minecraft mc = this.controller.getMinecraft(); // // Entity entity = new RenderEntity(this.controller, getWorld(mc)); // setEntityPositionToPlayer(mc, entity); // getWorld(mc).d(entity); // setEntityPositionToPlayer(mc, entity); // controller.getDebugger().debug("RenderEntity spawned"); // return entity; // } // // public static double getPlayerX(EntityPlayerSP player) { // return player.t; // } // // public static double getPlayerY(EntityPlayerSP player) { // return player.u; // } // // public static double getPlayerZ(EntityPlayerSP player) { // return player.v; // } // // public double getPlayerXGuess(float renderTick) { // EntityPlayerSP plyr = getPlayer(); // return plyr.q + ((plyr.t - plyr.q) * renderTick); // } // // public double getPlayerYGuess(float renderTick) { // EntityPlayerSP plyr = getPlayer(); // return plyr.r + ((plyr.u - plyr.r) * renderTick); // } // // public double getPlayerZGuess(float renderTick) { // EntityPlayerSP plyr = getPlayer(); // return plyr.s + ((plyr.v - plyr.s) * renderTick); // } // // public static EntityPlayerSP getPlayer(Minecraft mc) { // return mc.g; // } // // public static WorldClient getWorld(Minecraft mc) { // return mc.e; // } // // public static void setEntityPositionToPlayer(Minecraft mc, Entity entity) { // entity.b(getPlayerX(mc.g), getPlayerY(mc.g), getPlayerZ(mc.g)); // } // // public NetClientHandler getNetClientHandler(EntityClientPlayerMP player) { // return player.a; // } // // public static String getChatFromPacket(Packet3Chat packet) { // return packet.b; // } // // public static byte[] getBytesFromPacket(Packet250CustomPayload packet) { // return packet.c; // } // // public static Packet250CustomPayload newPayloadPacket(String name, int len, byte[] data) { // Packet250CustomPayload packet = new Packet250CustomPayload(); // packet.a = name; // packet.b = len; // packet.c = data; // return packet; // } // // public static File getMinecraftDir() { // return Minecraft.b(); // } // // public static File getWorldEditCUIDir() { // return new File(getMinecraftDir(), "mods" + File.separator + "WorldEditCUI"); // } // } // // Path: src/main/java/wecui/util/ConsoleLogFormatter.java // public class ConsoleLogFormatter extends Formatter { // // private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // // public String format(LogRecord logrecord) { // StringBuilder stringbuilder = new StringBuilder(); // // stringbuilder.append(this.format.format(Long.valueOf(logrecord.getMillis()))); // Level level = logrecord.getLevel(); // // if (level == Level.FINEST) { // stringbuilder.append(" [FINEST] "); // } else if (level == Level.FINER) { // stringbuilder.append(" [FINER] "); // } else if (level == Level.FINE) { // stringbuilder.append(" [FINE] "); // } else if (level == Level.INFO) { // stringbuilder.append(" [INFO] "); // } else if (level == Level.WARNING) { // stringbuilder.append(" [WARNING] "); // } else if (level == Level.SEVERE) { // stringbuilder.append(" [SEVERE] "); // } else { // stringbuilder.append(" [").append(level.getLocalizedName()).append("] "); // } // // stringbuilder.append(logrecord.getMessage()); // stringbuilder.append('\n'); // Throwable throwable = logrecord.getThrown(); // // if (throwable != null) { // StringWriter stringwriter = new StringWriter(); // // throwable.printStackTrace(new PrintWriter(stringwriter)); // stringbuilder.append(stringwriter.toString()); // } // // return stringbuilder.toString(); // } // }
import java.io.File; import java.io.IOException; import java.util.logging.ConsoleHandler; import java.util.logging.FileHandler; import java.util.logging.Level; import java.util.logging.Logger; import wecui.exception.InitializationException; import wecui.obfuscation.Obfuscation; import wecui.util.ConsoleLogFormatter;
package wecui; /** * Debugging helper class * * @author yetanotherx * */ public class CUIDebug implements InitializationFactory { protected WorldEditCUI controller; protected File debugFile; protected boolean debugMode = false; protected final static Logger logger = Logger.getLogger("WorldEditCUI"); public CUIDebug(WorldEditCUI controller) { this.controller = controller; } @Override public void initialize() throws InitializationException {
// Path: src/main/java/wecui/exception/InitializationException.java // public class InitializationException extends Exception { // // private static final long serialVersionUID = 1L; // // public InitializationException(String string) { // super(string); // } // // public InitializationException() { // } // } // // Path: src/main/java/wecui/obfuscation/Obfuscation.java // public class Obfuscation implements InitializationFactory { // // protected WorldEditCUI controller; // protected Minecraft minecraft; // // public Obfuscation(WorldEditCUI controller) { // this.controller = controller; // } // // @Override // public void initialize() { // this.minecraft = this.controller.getMinecraft(); // } // // public boolean isMultiplayerWorld() { // return true; // TODO - Temprarily until I can figure out the new server thing // //return minecraft.l(); // } // // /** // * Displays a chat message on the screen, if the player is currently playing // * @param chat // */ // public void showChatMessage(String chat) { // if (getPlayer() != null) { // getPlayer().b(chat); // } // } // // public EntityPlayerSP getPlayer() { // return getPlayer(minecraft); // } // // public WorldClient getWorld() { // return getWorld(minecraft); // } // // public Entity spawnEntity() { // Minecraft mc = this.controller.getMinecraft(); // // Entity entity = new RenderEntity(this.controller, getWorld(mc)); // setEntityPositionToPlayer(mc, entity); // getWorld(mc).d(entity); // setEntityPositionToPlayer(mc, entity); // controller.getDebugger().debug("RenderEntity spawned"); // return entity; // } // // public static double getPlayerX(EntityPlayerSP player) { // return player.t; // } // // public static double getPlayerY(EntityPlayerSP player) { // return player.u; // } // // public static double getPlayerZ(EntityPlayerSP player) { // return player.v; // } // // public double getPlayerXGuess(float renderTick) { // EntityPlayerSP plyr = getPlayer(); // return plyr.q + ((plyr.t - plyr.q) * renderTick); // } // // public double getPlayerYGuess(float renderTick) { // EntityPlayerSP plyr = getPlayer(); // return plyr.r + ((plyr.u - plyr.r) * renderTick); // } // // public double getPlayerZGuess(float renderTick) { // EntityPlayerSP plyr = getPlayer(); // return plyr.s + ((plyr.v - plyr.s) * renderTick); // } // // public static EntityPlayerSP getPlayer(Minecraft mc) { // return mc.g; // } // // public static WorldClient getWorld(Minecraft mc) { // return mc.e; // } // // public static void setEntityPositionToPlayer(Minecraft mc, Entity entity) { // entity.b(getPlayerX(mc.g), getPlayerY(mc.g), getPlayerZ(mc.g)); // } // // public NetClientHandler getNetClientHandler(EntityClientPlayerMP player) { // return player.a; // } // // public static String getChatFromPacket(Packet3Chat packet) { // return packet.b; // } // // public static byte[] getBytesFromPacket(Packet250CustomPayload packet) { // return packet.c; // } // // public static Packet250CustomPayload newPayloadPacket(String name, int len, byte[] data) { // Packet250CustomPayload packet = new Packet250CustomPayload(); // packet.a = name; // packet.b = len; // packet.c = data; // return packet; // } // // public static File getMinecraftDir() { // return Minecraft.b(); // } // // public static File getWorldEditCUIDir() { // return new File(getMinecraftDir(), "mods" + File.separator + "WorldEditCUI"); // } // } // // Path: src/main/java/wecui/util/ConsoleLogFormatter.java // public class ConsoleLogFormatter extends Formatter { // // private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // // public String format(LogRecord logrecord) { // StringBuilder stringbuilder = new StringBuilder(); // // stringbuilder.append(this.format.format(Long.valueOf(logrecord.getMillis()))); // Level level = logrecord.getLevel(); // // if (level == Level.FINEST) { // stringbuilder.append(" [FINEST] "); // } else if (level == Level.FINER) { // stringbuilder.append(" [FINER] "); // } else if (level == Level.FINE) { // stringbuilder.append(" [FINE] "); // } else if (level == Level.INFO) { // stringbuilder.append(" [INFO] "); // } else if (level == Level.WARNING) { // stringbuilder.append(" [WARNING] "); // } else if (level == Level.SEVERE) { // stringbuilder.append(" [SEVERE] "); // } else { // stringbuilder.append(" [").append(level.getLocalizedName()).append("] "); // } // // stringbuilder.append(logrecord.getMessage()); // stringbuilder.append('\n'); // Throwable throwable = logrecord.getThrown(); // // if (throwable != null) { // StringWriter stringwriter = new StringWriter(); // // throwable.printStackTrace(new PrintWriter(stringwriter)); // stringbuilder.append(stringwriter.toString()); // } // // return stringbuilder.toString(); // } // } // Path: src/main/java/wecui/CUIDebug.java import java.io.File; import java.io.IOException; import java.util.logging.ConsoleHandler; import java.util.logging.FileHandler; import java.util.logging.Level; import java.util.logging.Logger; import wecui.exception.InitializationException; import wecui.obfuscation.Obfuscation; import wecui.util.ConsoleLogFormatter; package wecui; /** * Debugging helper class * * @author yetanotherx * */ public class CUIDebug implements InitializationFactory { protected WorldEditCUI controller; protected File debugFile; protected boolean debugMode = false; protected final static Logger logger = Logger.getLogger("WorldEditCUI"); public CUIDebug(WorldEditCUI controller) { this.controller = controller; } @Override public void initialize() throws InitializationException {
ConsoleLogFormatter formatter = new ConsoleLogFormatter();
yetanotherx/WorldEditCUI
src/main/java/wecui/fevents/EventManager.java
// Path: src/main/java/wecui/InitializationFactory.java // public interface InitializationFactory { // // public void initialize() throws InitializationException; // } // // Path: src/main/java/wecui/WorldEditCUI.java // public class WorldEditCUI { // // public static final String VERSION = "1.4.5"; // public static final String MCVERSION = "1.4.5"; // public static final int protocolVersion = 2; // protected Minecraft minecraft; // protected EventManager eventManager; // protected Obfuscation obfuscation; // protected BaseRegion selection; // protected CUIDebug debugger; // protected CUIConfiguration configuration; // //protected LocalPlugin localPlugin; // // public WorldEditCUI(Minecraft minecraft) { // this.minecraft = minecraft; // } // // public void initialize() { // this.eventManager = new EventManager(this); // this.obfuscation = new Obfuscation(this); // this.selection = new CuboidRegion(this); // this.configuration = new CUIConfiguration(this); // this.debugger = new CUIDebug(this); // //this.localPlugin = new LocalPlugin(this); // // try { // this.eventManager.initialize(); // this.obfuscation.initialize(); // this.selection.initialize(); // this.configuration.initialize(); // this.debugger.initialize(); // //this.localPlugin.initialize(); // } catch (InitializationException e) { // e.printStackTrace(); // return; // } // // this.registerListeners(); // } // // protected void registerListeners() { // CUIEvent.handlers.register(new CUIListener(this), Order.Default); // ChannelEvent.handlers.register(new ChannelListener(this), Order.Default); // WorldRenderEvent.handlers.register(new WorldRenderListener(this), Order.Default); // // WorldEditCommandListener commListener = new WorldEditCommandListener(this); // ChatCommandEvent.getHandlers("worldedit").register(commListener, Order.Default); // ChatCommandEvent.getHandlers("we").register(commListener, Order.Default); // } // // public CUIConfiguration getConfiguration() { // return configuration; // } // // public void setConfiguration(CUIConfiguration configuration) { // this.configuration = configuration; // } // // public CUIDebug getDebugger() { // return debugger; // } // // public void setDebugger(CUIDebug debugger) { // this.debugger = debugger; // } // // public EventManager getEventManager() { // return eventManager; // } // // public void setEventManager(EventManager eventManager) { // this.eventManager = eventManager; // } // // /*public LocalPlugin getLocalPlugin() { // return localPlugin; // } // // public void setLocalPlugin(LocalPlugin localPlugin) { // this.localPlugin = localPlugin; // }*/ // // public Minecraft getMinecraft() { // return minecraft; // } // // public void setMinecraft(Minecraft minecraft) { // this.minecraft = minecraft; // } // // public Obfuscation getObfuscation() { // return obfuscation; // } // // public void setObfuscation(Obfuscation obfuscation) { // this.obfuscation = obfuscation; // } // // public BaseRegion getSelection() { // return selection; // } // // public void setSelection(BaseRegion selection) { // this.selection = selection; // } // // public static String getVersion() { // return VERSION + " for Minecraft version " + MCVERSION; // } // } // // Path: src/main/java/wecui/exception/InitializationException.java // public class InitializationException extends Exception { // // private static final long serialVersionUID = 1L; // // public InitializationException(String string) { // super(string); // } // // public InitializationException() { // } // }
import wecui.InitializationFactory; import wecui.WorldEditCUI; import wecui.exception.InitializationException;
package wecui.fevents; /** * This class doesn't actually need to exist, but it feels wrong to have this * part of the event call logic inside Event * * @author lahwran */ public class EventManager implements InitializationFactory { protected WorldEditCUI controller; public EventManager(WorldEditCUI controller) { this.controller = controller; } /** * Call an event. * * @param <TEvent> Event subclass * @param event Event to handle */ public <TEvent extends Event<TEvent>> void callEvent(TEvent event) { HandlerList<TEvent> handlerlist = event.getHandlers(); handlerlist.bake(); Listener<TEvent>[][] handlers = handlerlist.handlers; int[] handlerids = handlerlist.handlerids; for (int arrayidx = 0; arrayidx < handlers.length; arrayidx++) { // if the order slot is even and the event has stopped propogating if (event.isCancelled() && (handlerids[arrayidx] & 1) == 0) { continue; // then don't call this order slot } for (int handler = 0; handler < handlers[arrayidx].length; handler++) { try { handlers[arrayidx][handler].onEvent(event); } catch (Throwable t) { System.err.println("Error while passing event " + event); t.printStackTrace(); } } } } @Override
// Path: src/main/java/wecui/InitializationFactory.java // public interface InitializationFactory { // // public void initialize() throws InitializationException; // } // // Path: src/main/java/wecui/WorldEditCUI.java // public class WorldEditCUI { // // public static final String VERSION = "1.4.5"; // public static final String MCVERSION = "1.4.5"; // public static final int protocolVersion = 2; // protected Minecraft minecraft; // protected EventManager eventManager; // protected Obfuscation obfuscation; // protected BaseRegion selection; // protected CUIDebug debugger; // protected CUIConfiguration configuration; // //protected LocalPlugin localPlugin; // // public WorldEditCUI(Minecraft minecraft) { // this.minecraft = minecraft; // } // // public void initialize() { // this.eventManager = new EventManager(this); // this.obfuscation = new Obfuscation(this); // this.selection = new CuboidRegion(this); // this.configuration = new CUIConfiguration(this); // this.debugger = new CUIDebug(this); // //this.localPlugin = new LocalPlugin(this); // // try { // this.eventManager.initialize(); // this.obfuscation.initialize(); // this.selection.initialize(); // this.configuration.initialize(); // this.debugger.initialize(); // //this.localPlugin.initialize(); // } catch (InitializationException e) { // e.printStackTrace(); // return; // } // // this.registerListeners(); // } // // protected void registerListeners() { // CUIEvent.handlers.register(new CUIListener(this), Order.Default); // ChannelEvent.handlers.register(new ChannelListener(this), Order.Default); // WorldRenderEvent.handlers.register(new WorldRenderListener(this), Order.Default); // // WorldEditCommandListener commListener = new WorldEditCommandListener(this); // ChatCommandEvent.getHandlers("worldedit").register(commListener, Order.Default); // ChatCommandEvent.getHandlers("we").register(commListener, Order.Default); // } // // public CUIConfiguration getConfiguration() { // return configuration; // } // // public void setConfiguration(CUIConfiguration configuration) { // this.configuration = configuration; // } // // public CUIDebug getDebugger() { // return debugger; // } // // public void setDebugger(CUIDebug debugger) { // this.debugger = debugger; // } // // public EventManager getEventManager() { // return eventManager; // } // // public void setEventManager(EventManager eventManager) { // this.eventManager = eventManager; // } // // /*public LocalPlugin getLocalPlugin() { // return localPlugin; // } // // public void setLocalPlugin(LocalPlugin localPlugin) { // this.localPlugin = localPlugin; // }*/ // // public Minecraft getMinecraft() { // return minecraft; // } // // public void setMinecraft(Minecraft minecraft) { // this.minecraft = minecraft; // } // // public Obfuscation getObfuscation() { // return obfuscation; // } // // public void setObfuscation(Obfuscation obfuscation) { // this.obfuscation = obfuscation; // } // // public BaseRegion getSelection() { // return selection; // } // // public void setSelection(BaseRegion selection) { // this.selection = selection; // } // // public static String getVersion() { // return VERSION + " for Minecraft version " + MCVERSION; // } // } // // Path: src/main/java/wecui/exception/InitializationException.java // public class InitializationException extends Exception { // // private static final long serialVersionUID = 1L; // // public InitializationException(String string) { // super(string); // } // // public InitializationException() { // } // } // Path: src/main/java/wecui/fevents/EventManager.java import wecui.InitializationFactory; import wecui.WorldEditCUI; import wecui.exception.InitializationException; package wecui.fevents; /** * This class doesn't actually need to exist, but it feels wrong to have this * part of the event call logic inside Event * * @author lahwran */ public class EventManager implements InitializationFactory { protected WorldEditCUI controller; public EventManager(WorldEditCUI controller) { this.controller = controller; } /** * Call an event. * * @param <TEvent> Event subclass * @param event Event to handle */ public <TEvent extends Event<TEvent>> void callEvent(TEvent event) { HandlerList<TEvent> handlerlist = event.getHandlers(); handlerlist.bake(); Listener<TEvent>[][] handlers = handlerlist.handlers; int[] handlerids = handlerlist.handlerids; for (int arrayidx = 0; arrayidx < handlers.length; arrayidx++) { // if the order slot is even and the event has stopped propogating if (event.isCancelled() && (handlerids[arrayidx] & 1) == 0) { continue; // then don't call this order slot } for (int handler = 0; handler < handlers[arrayidx].length; handler++) { try { handlers[arrayidx][handler].onEvent(event); } catch (Throwable t) { System.err.println("Error while passing event " + event); t.printStackTrace(); } } } } @Override
public void initialize() throws InitializationException {
Skyost/SkyDocs
src/main/java/fr/skyost/skydocs/SkyDocs.java
// Path: src/main/java/fr/skyost/skydocs/command/CommandManager.java // public class CommandManager { // // /** // * Contains all app's commands. // */ // // private final HashMap<String, CommandExecutor> commands = new HashMap<>(); // // /** // * The default command executor (if no command is associated with the provided arguments, this will be executed instead). // */ // // private CommandExecutor defaultExecutor; // // /** // * Creates a new command manager instance. // */ // // public CommandManager() { // this(args -> new HelpCommand(copyOfRangeIfPossible(args)).run(false)); // } // // /** // * Creates a new command manager instance. // * // * @param defaultExecutor The default command executor. // */ // // public CommandManager(final CommandExecutor defaultExecutor) { // register(args -> new NewCommand(copyOfRangeIfPossible(args)).run(), Constants.COMMAND_NEW); // register(args -> new BuildCommand(true, copyOfRangeIfPossible(args)).run(), Constants.COMMAND_BUILD); // register(args -> new ServeCommand(copyOfRangeIfPossible(args)).run(false), Constants.COMMAND_SERVE); // register(args -> new UpdateCommand().run(false), Constants.COMMAND_UPDATE); // register(args -> new GUICommand().run(false), Constants.COMMAND_GUI); // // this.defaultExecutor = defaultExecutor; // } // // /** // * Executes the command that matches the given arguments. // * // * @param args The arguments. // */ // // public final void execute(String... args) { // if(args.length == 0) { // args = new String[]{Constants.COMMAND_GUI}; // } // if(args[0].startsWith("-")) { // args[0] = args[0].substring(1); // } // // execute(args[0], Arrays.copyOfRange(args, 1, args.length)); // } // // /** // * Finds a command by its name and executes it with the given arguments. // * // * @param command The name. // * @param args The arguments. // */ // // public final void execute(final String command, final String... args) { // getExecutor(command).execute(args); // } // // /** // * Returns the executor that matches the specified command name. // * // * @param command The command name. // * // * @return The executor that matches the specified command name. // */ // // public final CommandExecutor getExecutor(final String command) { // final CommandExecutor executor = commands.get(command.toLowerCase()); // return executor == null ? defaultExecutor : executor; // } // // /** // * Registers a command executor. // * // * @param executor The command executor. // * @param commands The associated commands. // */ // // private void register(final CommandExecutor executor, final String... commands) { // for(final String command : commands) { // this.commands.put(command.toLowerCase(), executor); // } // } // // /** // * Returns the default command executor. // * // * @return The default command executor. // */ // // public CommandExecutor getDefaultExecutor() { // return defaultExecutor; // } // // /** // * Sets the default command executor. // * // * @param defaultExecutor The default command executor. // */ // // public void setDefaultExecutor(final CommandExecutor defaultExecutor) { // this.defaultExecutor = defaultExecutor; // } // // /** // * Copies all arguments from index 1 if possible. // * // * @param args The arguments. // * // * @return The copy. // */ // // private static String[] copyOfRangeIfPossible(final String... args) { // if(args == null || args.length == 0) { // return args; // } // // return Arrays.copyOfRange(args, 1, args.length); // } // // /** // * Represents a command executor. // */ // // @FunctionalInterface // public interface CommandExecutor { // // /** // * Executes the given command with the specified arguments. // * // * @param args The arguments. // */ // // void execute(final String... args); // // } // // }
import fr.skyost.skydocs.command.CommandManager;
package fr.skyost.skydocs; /** * Executable class of SkyDocs. */ public class SkyDocs { /** * Main method of SkyDocs. * * @param args Arguments to pass. */ public static void main(String[] args) {
// Path: src/main/java/fr/skyost/skydocs/command/CommandManager.java // public class CommandManager { // // /** // * Contains all app's commands. // */ // // private final HashMap<String, CommandExecutor> commands = new HashMap<>(); // // /** // * The default command executor (if no command is associated with the provided arguments, this will be executed instead). // */ // // private CommandExecutor defaultExecutor; // // /** // * Creates a new command manager instance. // */ // // public CommandManager() { // this(args -> new HelpCommand(copyOfRangeIfPossible(args)).run(false)); // } // // /** // * Creates a new command manager instance. // * // * @param defaultExecutor The default command executor. // */ // // public CommandManager(final CommandExecutor defaultExecutor) { // register(args -> new NewCommand(copyOfRangeIfPossible(args)).run(), Constants.COMMAND_NEW); // register(args -> new BuildCommand(true, copyOfRangeIfPossible(args)).run(), Constants.COMMAND_BUILD); // register(args -> new ServeCommand(copyOfRangeIfPossible(args)).run(false), Constants.COMMAND_SERVE); // register(args -> new UpdateCommand().run(false), Constants.COMMAND_UPDATE); // register(args -> new GUICommand().run(false), Constants.COMMAND_GUI); // // this.defaultExecutor = defaultExecutor; // } // // /** // * Executes the command that matches the given arguments. // * // * @param args The arguments. // */ // // public final void execute(String... args) { // if(args.length == 0) { // args = new String[]{Constants.COMMAND_GUI}; // } // if(args[0].startsWith("-")) { // args[0] = args[0].substring(1); // } // // execute(args[0], Arrays.copyOfRange(args, 1, args.length)); // } // // /** // * Finds a command by its name and executes it with the given arguments. // * // * @param command The name. // * @param args The arguments. // */ // // public final void execute(final String command, final String... args) { // getExecutor(command).execute(args); // } // // /** // * Returns the executor that matches the specified command name. // * // * @param command The command name. // * // * @return The executor that matches the specified command name. // */ // // public final CommandExecutor getExecutor(final String command) { // final CommandExecutor executor = commands.get(command.toLowerCase()); // return executor == null ? defaultExecutor : executor; // } // // /** // * Registers a command executor. // * // * @param executor The command executor. // * @param commands The associated commands. // */ // // private void register(final CommandExecutor executor, final String... commands) { // for(final String command : commands) { // this.commands.put(command.toLowerCase(), executor); // } // } // // /** // * Returns the default command executor. // * // * @return The default command executor. // */ // // public CommandExecutor getDefaultExecutor() { // return defaultExecutor; // } // // /** // * Sets the default command executor. // * // * @param defaultExecutor The default command executor. // */ // // public void setDefaultExecutor(final CommandExecutor defaultExecutor) { // this.defaultExecutor = defaultExecutor; // } // // /** // * Copies all arguments from index 1 if possible. // * // * @param args The arguments. // * // * @return The copy. // */ // // private static String[] copyOfRangeIfPossible(final String... args) { // if(args == null || args.length == 0) { // return args; // } // // return Arrays.copyOfRange(args, 1, args.length); // } // // /** // * Represents a command executor. // */ // // @FunctionalInterface // public interface CommandExecutor { // // /** // * Executes the given command with the specified arguments. // * // * @param args The arguments. // */ // // void execute(final String... args); // // } // // } // Path: src/main/java/fr/skyost/skydocs/SkyDocs.java import fr.skyost.skydocs.command.CommandManager; package fr.skyost.skydocs; /** * Executable class of SkyDocs. */ public class SkyDocs { /** * Main method of SkyDocs. * * @param args Arguments to pass. */ public static void main(String[] args) {
new CommandManager().execute(args);
zhengjunbase/codehelper.generator
src/test/java/com/ccnode/codegenerator/utils/GenCodeUtilTest.java
// Path: src/main/java/com/ccnode/codegenerator/util/GenCodeUtil.java // public class GenCodeUtil { // // private final static Logger LOGGER = LoggerWrapper.getLogger(GenCodeUtil.class); // // public static final String ONE_RETRACT = " "; // public static final String TWO_RETRACT = " "; // public static final String THREE_RETRACT = " "; // public static final String FOUR_RETRACT = " "; // public static String MYSQL_TYPE = StringUtils.EMPTY; // public static String PACKAGE_LINE = StringUtils.EMPTY; // // // public static List<String> grapOld(@NotNull List<String> oldList, // @NotNull String startKeyWord, @NotNull String endKeyWord){ // int startIndex = -1; // int endIndex= -1; // int i = 0; // for (String line : oldList) { // if(sqlContain(line,startKeyWord)){ // startIndex = i; // } // if(sqlContain(line,endKeyWord)){ // endIndex = i; // } // i ++; // } // if(startIndex == -1 || endIndex == -1){ // return Lists.newArrayList(); // } // return oldList.subList(startIndex, endIndex + 1); // } // // public static String getPojoPackage(@NotNull String fullPojoFilePath){ // try{ // List<String> strings = IOUtils.readLines(fullPojoFilePath); // for (String string : strings) { // if(string.startsWith("package")){ // string = string.replace(";", ""); // string = string.replace(" ", ""); // string = string.replace("package", ""); // return string; // } // } // }catch(Exception e){ // return "ERROR_PACKAGE"; // } // return StringUtils.EMPTY; // // } // // public static boolean sqlContain(List<String> lines, @NotNull String word) { // lines = PojoUtil.avoidEmptyList(lines); // for (String line : lines) { // if(sqlContain(line, word)){ // return true; // } // } // return false; // } // // public static String deducePackage(String daoFilePathString, String pojoPackage,String pojoPathString, String modulePathStr){ // //get the path by // LOGGER.info("path:{}, pojoPackage:{}",daoFilePathString,pojoPackage); // Path realpojoPath = Paths.get(pojoPathString); // String[] split = pojoPackage.split("\\."); // int len = split.length; // Path sourcePath = realpojoPath; // while(len>=0){ // sourcePath = sourcePath.getParent(); // len--; // } // Path daoFilePath = Paths.get(daoFilePathString); // Path daoFolder = daoFilePath.getParent(); // //shall combine two path // Path relativeToSouce = sourcePath.relativize(daoFolder); // String relate = relativeToSouce.toString(); // if(!StringUtils.isEmpty(modulePathStr)) { // Path modulePath = Paths.get(modulePathStr); // String modulePathString = modulePath.toString(); // relate = relate.substring(relate.indexOf(modulePathString) + modulePathString.length() + 1); // } // relate = relate.replace("\\", "."); // relate = relate.replace("/","."); // return relate; // } // // public static String pathToPackage(String path){ // path = path.replace("/","."); // path = path.replace("\\","."); // if(path.startsWith("src.main.java.")){ // path = path.replace("src.main.java.",""); // } // if(path.startsWith("src.main.")){ // path = path.replace("src.main.",""); // } // if(path.startsWith("src.")){ // path = path.replace("src.",""); // } // if(path.startsWith(".")){ // path = path.substring(1,path.length()); // } // return path; // } // // // // public static boolean sqlContain(String sequence, @NotNull String word){ // if(StringUtils.isBlank(sequence)){ // return false; // } // return StringUtils.containsIgnoreCase( // StringUtils.deleteWhitespace(sequence), // StringUtils.deleteWhitespace(word)); // } // // public static String getUnderScore(String value) { // if(value == null){ // return StringUtils.EMPTY; // } // return CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, value); // } // // public static String getLowerCamel(String value){ // return CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL,value); // } // // public static void main(String[] args) { // // System.out.println(deducePackage("src/main/java/com/qunar/insurance","com.qunar.insurance.annotion")); // // System.out.println(deducePackage("src/com/java/com/qunar/insurance","com.com.com.annotion")); // // System.out.println(deducePackage("src/com/java/com/qunar/insurance","xxx.com.com.annotion")); // } // // }
import com.ccnode.codegenerator.util.GenCodeUtil; import org.junit.Assert; import org.junit.Test; import java.nio.file.Path; import java.nio.file.Paths;
package com.ccnode.codegenerator.utils; /** * Created by bruce.ge on 2016/11/27. */ public class GenCodeUtilTest { @Test public void test(){
// Path: src/main/java/com/ccnode/codegenerator/util/GenCodeUtil.java // public class GenCodeUtil { // // private final static Logger LOGGER = LoggerWrapper.getLogger(GenCodeUtil.class); // // public static final String ONE_RETRACT = " "; // public static final String TWO_RETRACT = " "; // public static final String THREE_RETRACT = " "; // public static final String FOUR_RETRACT = " "; // public static String MYSQL_TYPE = StringUtils.EMPTY; // public static String PACKAGE_LINE = StringUtils.EMPTY; // // // public static List<String> grapOld(@NotNull List<String> oldList, // @NotNull String startKeyWord, @NotNull String endKeyWord){ // int startIndex = -1; // int endIndex= -1; // int i = 0; // for (String line : oldList) { // if(sqlContain(line,startKeyWord)){ // startIndex = i; // } // if(sqlContain(line,endKeyWord)){ // endIndex = i; // } // i ++; // } // if(startIndex == -1 || endIndex == -1){ // return Lists.newArrayList(); // } // return oldList.subList(startIndex, endIndex + 1); // } // // public static String getPojoPackage(@NotNull String fullPojoFilePath){ // try{ // List<String> strings = IOUtils.readLines(fullPojoFilePath); // for (String string : strings) { // if(string.startsWith("package")){ // string = string.replace(";", ""); // string = string.replace(" ", ""); // string = string.replace("package", ""); // return string; // } // } // }catch(Exception e){ // return "ERROR_PACKAGE"; // } // return StringUtils.EMPTY; // // } // // public static boolean sqlContain(List<String> lines, @NotNull String word) { // lines = PojoUtil.avoidEmptyList(lines); // for (String line : lines) { // if(sqlContain(line, word)){ // return true; // } // } // return false; // } // // public static String deducePackage(String daoFilePathString, String pojoPackage,String pojoPathString, String modulePathStr){ // //get the path by // LOGGER.info("path:{}, pojoPackage:{}",daoFilePathString,pojoPackage); // Path realpojoPath = Paths.get(pojoPathString); // String[] split = pojoPackage.split("\\."); // int len = split.length; // Path sourcePath = realpojoPath; // while(len>=0){ // sourcePath = sourcePath.getParent(); // len--; // } // Path daoFilePath = Paths.get(daoFilePathString); // Path daoFolder = daoFilePath.getParent(); // //shall combine two path // Path relativeToSouce = sourcePath.relativize(daoFolder); // String relate = relativeToSouce.toString(); // if(!StringUtils.isEmpty(modulePathStr)) { // Path modulePath = Paths.get(modulePathStr); // String modulePathString = modulePath.toString(); // relate = relate.substring(relate.indexOf(modulePathString) + modulePathString.length() + 1); // } // relate = relate.replace("\\", "."); // relate = relate.replace("/","."); // return relate; // } // // public static String pathToPackage(String path){ // path = path.replace("/","."); // path = path.replace("\\","."); // if(path.startsWith("src.main.java.")){ // path = path.replace("src.main.java.",""); // } // if(path.startsWith("src.main.")){ // path = path.replace("src.main.",""); // } // if(path.startsWith("src.")){ // path = path.replace("src.",""); // } // if(path.startsWith(".")){ // path = path.substring(1,path.length()); // } // return path; // } // // // // public static boolean sqlContain(String sequence, @NotNull String word){ // if(StringUtils.isBlank(sequence)){ // return false; // } // return StringUtils.containsIgnoreCase( // StringUtils.deleteWhitespace(sequence), // StringUtils.deleteWhitespace(word)); // } // // public static String getUnderScore(String value) { // if(value == null){ // return StringUtils.EMPTY; // } // return CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, value); // } // // public static String getLowerCamel(String value){ // return CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL,value); // } // // public static void main(String[] args) { // // System.out.println(deducePackage("src/main/java/com/qunar/insurance","com.qunar.insurance.annotion")); // // System.out.println(deducePackage("src/com/java/com/qunar/insurance","com.com.com.annotion")); // // System.out.println(deducePackage("src/com/java/com/qunar/insurance","xxx.com.com.annotion")); // } // // } // Path: src/test/java/com/ccnode/codegenerator/utils/GenCodeUtilTest.java import com.ccnode.codegenerator.util.GenCodeUtil; import org.junit.Assert; import org.junit.Test; import java.nio.file.Path; import java.nio.file.Paths; package com.ccnode.codegenerator.utils; /** * Created by bruce.ge on 2016/11/27. */ public class GenCodeUtilTest { @Test public void test(){
String packageStr = GenCodeUtil.deducePackage("down\\src\\main\\java\\com\\rest\\mapper","com.rest.domain","upworkattachment\\src\\main\\java\\com\\rest\\domain\\PeoplePO.java","down/src/main/java");
zhengjunbase/codehelper.generator
src/main/java/com/ccnode/codegenerator/util/ReplaceUtil.java
// Path: src/main/java/com/ccnode/codegenerator/pojo/ListInfo.java // public class ListInfo<T> { // // private List<T> fullList; // private List<T> selectSegments; // int startPos; //include // int endPos; //exclude // private List<T> newSegments; // private List<T> newList; // // public List<T> getFullList() { // return fullList; // } // // public void setFullList(List<T> fullList) { // this.fullList = fullList; // } // // public List<T> getSelectSegments() { // return selectSegments; // } // // public void setSelectSegments(List<T> selectSegments) { // this.selectSegments = selectSegments; // } // // public int getStartPos() { // return startPos; // } // // public void setStartPos(int startPos) { // this.startPos = startPos; // } // // public int getEndPos() { // return endPos; // } // // public void setEndPos(int endPos) { // this.endPos = endPos; // } // // public List<T> getNewSegments() { // return newSegments; // } // // public void setNewSegments(List<T> newSegments) { // this.newSegments = newSegments; // } // // public List<T> getNewList() { // return newList; // } // // public void setNewList(List<T> newList) { // this.newList = newList; // } // // public void setPos(Pair<Integer,Integer> pos) { // this.startPos = pos.getLeft(); // this.endPos = pos.getRight(); // this.selectSegments = fullList.subList(startPos,endPos); // } // } // // Path: src/main/java/com/ccnode/codegenerator/function/EqualCondition.java // public interface EqualCondition<T> { // // public boolean isEqual( T t, T t2 ); // // } // // Path: src/main/java/com/ccnode/codegenerator/pojo/ListInfo.java // public class ListInfo<T> { // // private List<T> fullList; // private List<T> selectSegments; // int startPos; //include // int endPos; //exclude // private List<T> newSegments; // private List<T> newList; // // public List<T> getFullList() { // return fullList; // } // // public void setFullList(List<T> fullList) { // this.fullList = fullList; // } // // public List<T> getSelectSegments() { // return selectSegments; // } // // public void setSelectSegments(List<T> selectSegments) { // this.selectSegments = selectSegments; // } // // public int getStartPos() { // return startPos; // } // // public void setStartPos(int startPos) { // this.startPos = startPos; // } // // public int getEndPos() { // return endPos; // } // // public void setEndPos(int endPos) { // this.endPos = endPos; // } // // public List<T> getNewSegments() { // return newSegments; // } // // public void setNewSegments(List<T> newSegments) { // this.newSegments = newSegments; // } // // public List<T> getNewList() { // return newList; // } // // public void setNewList(List<T> newList) { // this.newList = newList; // } // // public void setPos(Pair<Integer,Integer> pos) { // this.startPos = pos.getLeft(); // this.endPos = pos.getRight(); // this.selectSegments = fullList.subList(startPos,endPos); // } // }
import com.ccnode.codegenerator.pojo.ListInfo; import com.ccnode.codegenerator.function.EqualCondition; import com.ccnode.codegenerator.pojo.ListInfo; import com.google.common.collect.Lists; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.Pair; import org.jetbrains.annotations.Nullable; import java.util.List;
package com.ccnode.codegenerator.util; /** * What always stop you is what you always believe. * <p> * Created by zhengjun.du on 2016/05/29 15:20 */ public class ReplaceUtil { public static <T> Pair<Integer,Integer> getPos(List<T> oldList, T start, T end, EqualCondition condition){ int startPos = -1; int endPos = -1; int index = 0; for (T t : oldList) { if(startPos == -1 && condition.isEqual(t, start)){ startPos = index; } if(startPos >= 0 && condition.isEqual(t, end)){ endPos = index + 1; return Pair.of(startPos,endPos); } index ++; } return Pair.of(oldList.size() - 1,oldList.size() - 1); }
// Path: src/main/java/com/ccnode/codegenerator/pojo/ListInfo.java // public class ListInfo<T> { // // private List<T> fullList; // private List<T> selectSegments; // int startPos; //include // int endPos; //exclude // private List<T> newSegments; // private List<T> newList; // // public List<T> getFullList() { // return fullList; // } // // public void setFullList(List<T> fullList) { // this.fullList = fullList; // } // // public List<T> getSelectSegments() { // return selectSegments; // } // // public void setSelectSegments(List<T> selectSegments) { // this.selectSegments = selectSegments; // } // // public int getStartPos() { // return startPos; // } // // public void setStartPos(int startPos) { // this.startPos = startPos; // } // // public int getEndPos() { // return endPos; // } // // public void setEndPos(int endPos) { // this.endPos = endPos; // } // // public List<T> getNewSegments() { // return newSegments; // } // // public void setNewSegments(List<T> newSegments) { // this.newSegments = newSegments; // } // // public List<T> getNewList() { // return newList; // } // // public void setNewList(List<T> newList) { // this.newList = newList; // } // // public void setPos(Pair<Integer,Integer> pos) { // this.startPos = pos.getLeft(); // this.endPos = pos.getRight(); // this.selectSegments = fullList.subList(startPos,endPos); // } // } // // Path: src/main/java/com/ccnode/codegenerator/function/EqualCondition.java // public interface EqualCondition<T> { // // public boolean isEqual( T t, T t2 ); // // } // // Path: src/main/java/com/ccnode/codegenerator/pojo/ListInfo.java // public class ListInfo<T> { // // private List<T> fullList; // private List<T> selectSegments; // int startPos; //include // int endPos; //exclude // private List<T> newSegments; // private List<T> newList; // // public List<T> getFullList() { // return fullList; // } // // public void setFullList(List<T> fullList) { // this.fullList = fullList; // } // // public List<T> getSelectSegments() { // return selectSegments; // } // // public void setSelectSegments(List<T> selectSegments) { // this.selectSegments = selectSegments; // } // // public int getStartPos() { // return startPos; // } // // public void setStartPos(int startPos) { // this.startPos = startPos; // } // // public int getEndPos() { // return endPos; // } // // public void setEndPos(int endPos) { // this.endPos = endPos; // } // // public List<T> getNewSegments() { // return newSegments; // } // // public void setNewSegments(List<T> newSegments) { // this.newSegments = newSegments; // } // // public List<T> getNewList() { // return newList; // } // // public void setNewList(List<T> newList) { // this.newList = newList; // } // // public void setPos(Pair<Integer,Integer> pos) { // this.startPos = pos.getLeft(); // this.endPos = pos.getRight(); // this.selectSegments = fullList.subList(startPos,endPos); // } // } // Path: src/main/java/com/ccnode/codegenerator/util/ReplaceUtil.java import com.ccnode.codegenerator.pojo.ListInfo; import com.ccnode.codegenerator.function.EqualCondition; import com.ccnode.codegenerator.pojo.ListInfo; import com.google.common.collect.Lists; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.Pair; import org.jetbrains.annotations.Nullable; import java.util.List; package com.ccnode.codegenerator.util; /** * What always stop you is what you always believe. * <p> * Created by zhengjun.du on 2016/05/29 15:20 */ public class ReplaceUtil { public static <T> Pair<Integer,Integer> getPos(List<T> oldList, T start, T end, EqualCondition condition){ int startPos = -1; int endPos = -1; int index = 0; for (T t : oldList) { if(startPos == -1 && condition.isEqual(t, start)){ startPos = index; } if(startPos >= 0 && condition.isEqual(t, end)){ endPos = index + 1; return Pair.of(startPos,endPos); } index ++; } return Pair.of(oldList.size() - 1,oldList.size() - 1); }
public static <T> void merge(ListInfo<T> listInfo, EqualCondition condition) {
zhengjunbase/codehelper.generator
src/main/java/com/ccnode/codegenerator/pojo/GenCodeResponse.java
// Path: src/main/java/com/ccnode/codegenerator/util/GenCodeConfig.java // public class GenCodeConfig { // public static final String MAPPER_SUFFIX = "Dao"; // public static final String DAO_SUFFIX = "Dao"; // public static final String SERVICE_SUFFIX = "Service"; // String projectPath = StringUtils.EMPTY; // String serviceDir = StringUtils.EMPTY; // String mapperDir = StringUtils.EMPTY; // String sqlDir = StringUtils.EMPTY; // String daoDir = StringUtils.EMPTY; // String pojoName; // String daoSuffix; // String mapperSuffix; // String serviceSuffix; // String daoModulePath; // String serviceModulePath; // String mapperModulePath; // // Map<String,String> configMap = Maps.newHashMap(); // // public Map<String, String> getConfigMap() { // return configMap; // } // // public void setConfigMap(Map<String, String> configMap) { // this.configMap = configMap; // } // // public String getPojoName() { // return pojoName; // } // // public void setPojoName(String pojoName) { // this.pojoName = pojoName; // } // // public String getProjectPath() { // return projectPath; // } // // public void setProjectPath(String projectPath) { // this.projectPath = projectPath; // } // // public String getServiceDir() { // return serviceDir; // } // // public void setServiceDir(String serviceDir) { // this.serviceDir = serviceDir; // } // // public String getMapperDir() { // return mapperDir; // } // // public void setMapperDir(String mapperDir) { // this.mapperDir = mapperDir; // } // // public String getSqlDir() { // return sqlDir; // } // // public void setSqlDir(String sqlDir) { // this.sqlDir = sqlDir; // } // // public String getDaoDir() { // return daoDir; // } // // public void setDaoDir(String daoDir) { // this.daoDir = daoDir; // } // // public String getDaoSuffix() { // return daoSuffix; // } // // public void setDaoSuffix(String daoSuffix) { // this.daoSuffix = daoSuffix; // } // // public String getMapperSuffix() { // return mapperSuffix; // } // // public void setMapperSuffix(String mapperSuffix) { // this.mapperSuffix = mapperSuffix; // } // // public String getServiceSuffix() { // return serviceSuffix; // } // // public void setServiceSuffix(String serviceSuffix) { // this.serviceSuffix = serviceSuffix; // } // // public String getDaoModulePath() { // return daoModulePath; // } // // public void setDaoModulePath(String daoModulePath) { // this.daoModulePath = daoModulePath; // } // // public String getServiceModulePath() { // return serviceModulePath; // } // // public void setServiceModulePath(String serviceModulePath) { // this.serviceModulePath = serviceModulePath; // } // // public String getMapperModulePath() { // return mapperModulePath; // } // // public void setMapperModulePath(String mapperModulePath) { // this.mapperModulePath = mapperModulePath; // } // }
import com.ccnode.codegenerator.util.GenCodeConfig; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import org.apache.commons.lang3.StringUtils; import java.util.List; import java.util.Map;
package com.ccnode.codegenerator.pojo; /** * What always stop you is what you always believe. * <p> * Created by zhengjun.du on 2016/05/17 19:54 */ public class GenCodeResponse extends BaseResponse { Map<String,String> userConfigMap = Maps.newHashMap();
// Path: src/main/java/com/ccnode/codegenerator/util/GenCodeConfig.java // public class GenCodeConfig { // public static final String MAPPER_SUFFIX = "Dao"; // public static final String DAO_SUFFIX = "Dao"; // public static final String SERVICE_SUFFIX = "Service"; // String projectPath = StringUtils.EMPTY; // String serviceDir = StringUtils.EMPTY; // String mapperDir = StringUtils.EMPTY; // String sqlDir = StringUtils.EMPTY; // String daoDir = StringUtils.EMPTY; // String pojoName; // String daoSuffix; // String mapperSuffix; // String serviceSuffix; // String daoModulePath; // String serviceModulePath; // String mapperModulePath; // // Map<String,String> configMap = Maps.newHashMap(); // // public Map<String, String> getConfigMap() { // return configMap; // } // // public void setConfigMap(Map<String, String> configMap) { // this.configMap = configMap; // } // // public String getPojoName() { // return pojoName; // } // // public void setPojoName(String pojoName) { // this.pojoName = pojoName; // } // // public String getProjectPath() { // return projectPath; // } // // public void setProjectPath(String projectPath) { // this.projectPath = projectPath; // } // // public String getServiceDir() { // return serviceDir; // } // // public void setServiceDir(String serviceDir) { // this.serviceDir = serviceDir; // } // // public String getMapperDir() { // return mapperDir; // } // // public void setMapperDir(String mapperDir) { // this.mapperDir = mapperDir; // } // // public String getSqlDir() { // return sqlDir; // } // // public void setSqlDir(String sqlDir) { // this.sqlDir = sqlDir; // } // // public String getDaoDir() { // return daoDir; // } // // public void setDaoDir(String daoDir) { // this.daoDir = daoDir; // } // // public String getDaoSuffix() { // return daoSuffix; // } // // public void setDaoSuffix(String daoSuffix) { // this.daoSuffix = daoSuffix; // } // // public String getMapperSuffix() { // return mapperSuffix; // } // // public void setMapperSuffix(String mapperSuffix) { // this.mapperSuffix = mapperSuffix; // } // // public String getServiceSuffix() { // return serviceSuffix; // } // // public void setServiceSuffix(String serviceSuffix) { // this.serviceSuffix = serviceSuffix; // } // // public String getDaoModulePath() { // return daoModulePath; // } // // public void setDaoModulePath(String daoModulePath) { // this.daoModulePath = daoModulePath; // } // // public String getServiceModulePath() { // return serviceModulePath; // } // // public void setServiceModulePath(String serviceModulePath) { // this.serviceModulePath = serviceModulePath; // } // // public String getMapperModulePath() { // return mapperModulePath; // } // // public void setMapperModulePath(String mapperModulePath) { // this.mapperModulePath = mapperModulePath; // } // } // Path: src/main/java/com/ccnode/codegenerator/pojo/GenCodeResponse.java import com.ccnode.codegenerator.util.GenCodeConfig; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import org.apache.commons.lang3.StringUtils; import java.util.List; import java.util.Map; package com.ccnode.codegenerator.pojo; /** * What always stop you is what you always believe. * <p> * Created by zhengjun.du on 2016/05/17 19:54 */ public class GenCodeResponse extends BaseResponse { Map<String,String> userConfigMap = Maps.newHashMap();
GenCodeConfig codeConfig;
zhengjunbase/codehelper.generator
src/main/java/com/ccnode/codegenerator/enums/UrlManager.java
// Path: src/main/java/com/ccnode/codegenerator/common/VersionManager.java // public class VersionManager { // // public static String CURRENT_VERSION = "2018-06-24"; // // public static String getCurrentVersion() { // return CURRENT_VERSION; // } // } // // Path: src/main/java/com/ccnode/codegenerator/storage/SettingService.java // @State(name="SettingService", storages={@Storage(id="other", file="$APP_CONFIG$/codeHelper.xml")}) // public class SettingService implements PersistentStateComponent<SettingDto> { // // SettingDto settingDto; // // public static SettingService getInstance(){ // return ServiceManager.getService(SettingService.class); // } // // public static String getUUID(){ // return getInstance().getState().getUuid(); // } // // public static SettingDto getSetting(){ // return getInstance().getState(); // } // // // @NotNull // @Override // public SettingDto getState() { // if(settingDto == null){ // settingDto = new SettingDto(); // settingDto.setUuid(UUID.randomUUID().toString()); // settingDto.setVersion(VersionManager.getCurrentVersion()); // if(settingDto.getInstalledDate() == null){ // settingDto.setInstalledDate(new Date()); // } // }else{ // if(settingDto.getUpdateDate() == null && !VersionManager.CURRENT_VERSION.equalsIgnoreCase(settingDto.getVersion())){ // settingDto.setOldVersion(settingDto.getVersion()); // settingDto.setVersion(VersionManager.CURRENT_VERSION); // settingDto.setUpdateDate(new Date()); // } // } // if(StringUtils.isBlank(settingDto.getUuid())){ // settingDto.setUuid(UUID.randomUUID().toString()); // } // return settingDto; // } // // // @Override // public void loadState(SettingDto o) { // XmlSerializerUtil.copyBean(o, getState()); // } // // public static void setDonated(){ // getInstance().getState().setDonatedDate(new Date()); // } // // public void setSettingDto(SettingDto settingDto) { // this.settingDto = settingDto; // } // // public static Boolean notExpired(String eKey) { // Date date = SecurityHelper.decryptToDate(eKey); // if (date == null || new Date().compareTo(date) > 0) { // return false; // } else { // return true; // } // } // // public static boolean showDonateBtn(){ // // Integer count = getSetting().getCount(); // // if(isDonated()){ // // return false; // // } // // if(count == null count > 5 && count % 7 == 0){ // // return true; // // } // return false; // } // // public static boolean isDonated() { // return getInstance().getState().getDonatedDate() != null && DateUtil // .getDayBetween(getInstance().getState().getDonatedDate(), new Date()) < 365; // } // // public static String getOldVersion(){ // String oldVersion = getInstance().getState().getVersion(); // if(StringUtils.isBlank(oldVersion)){ // return "no_version"; // } // return oldVersion; // } // // public static void updateLastRunTime(){ // getSetting().setLastRunTime(new Date()); // } // // public static int getSecondAfterLastRun(){ // long l = new Date().getTime() - getSetting().getLastRunTime().getTime() /1000L; // return (int) l; // } // // }
import com.ccnode.codegenerator.common.VersionManager; import com.ccnode.codegenerator.storage.SettingService;
package com.ccnode.codegenerator.enums; /** * What always stop you is what you always believe. * <p> * Created by zhengjun.du on 2016/08/31 16:39 */ public class UrlManager { private static String GENERATOR_URL = "http://www.codehelper.me/generator/"; private static String MAIN_PAGE = "https://github.com/zhengjunbase/codehelper.generator"; private static String POST_URL = "http://www.codehelper.me/generator/post"; private static String DONATE_CLICK_URL = "http://www.codehelper.me/generator" ; public static String getUrlSuffix (){
// Path: src/main/java/com/ccnode/codegenerator/common/VersionManager.java // public class VersionManager { // // public static String CURRENT_VERSION = "2018-06-24"; // // public static String getCurrentVersion() { // return CURRENT_VERSION; // } // } // // Path: src/main/java/com/ccnode/codegenerator/storage/SettingService.java // @State(name="SettingService", storages={@Storage(id="other", file="$APP_CONFIG$/codeHelper.xml")}) // public class SettingService implements PersistentStateComponent<SettingDto> { // // SettingDto settingDto; // // public static SettingService getInstance(){ // return ServiceManager.getService(SettingService.class); // } // // public static String getUUID(){ // return getInstance().getState().getUuid(); // } // // public static SettingDto getSetting(){ // return getInstance().getState(); // } // // // @NotNull // @Override // public SettingDto getState() { // if(settingDto == null){ // settingDto = new SettingDto(); // settingDto.setUuid(UUID.randomUUID().toString()); // settingDto.setVersion(VersionManager.getCurrentVersion()); // if(settingDto.getInstalledDate() == null){ // settingDto.setInstalledDate(new Date()); // } // }else{ // if(settingDto.getUpdateDate() == null && !VersionManager.CURRENT_VERSION.equalsIgnoreCase(settingDto.getVersion())){ // settingDto.setOldVersion(settingDto.getVersion()); // settingDto.setVersion(VersionManager.CURRENT_VERSION); // settingDto.setUpdateDate(new Date()); // } // } // if(StringUtils.isBlank(settingDto.getUuid())){ // settingDto.setUuid(UUID.randomUUID().toString()); // } // return settingDto; // } // // // @Override // public void loadState(SettingDto o) { // XmlSerializerUtil.copyBean(o, getState()); // } // // public static void setDonated(){ // getInstance().getState().setDonatedDate(new Date()); // } // // public void setSettingDto(SettingDto settingDto) { // this.settingDto = settingDto; // } // // public static Boolean notExpired(String eKey) { // Date date = SecurityHelper.decryptToDate(eKey); // if (date == null || new Date().compareTo(date) > 0) { // return false; // } else { // return true; // } // } // // public static boolean showDonateBtn(){ // // Integer count = getSetting().getCount(); // // if(isDonated()){ // // return false; // // } // // if(count == null count > 5 && count % 7 == 0){ // // return true; // // } // return false; // } // // public static boolean isDonated() { // return getInstance().getState().getDonatedDate() != null && DateUtil // .getDayBetween(getInstance().getState().getDonatedDate(), new Date()) < 365; // } // // public static String getOldVersion(){ // String oldVersion = getInstance().getState().getVersion(); // if(StringUtils.isBlank(oldVersion)){ // return "no_version"; // } // return oldVersion; // } // // public static void updateLastRunTime(){ // getSetting().setLastRunTime(new Date()); // } // // public static int getSecondAfterLastRun(){ // long l = new Date().getTime() - getSetting().getLastRunTime().getTime() /1000L; // return (int) l; // } // // } // Path: src/main/java/com/ccnode/codegenerator/enums/UrlManager.java import com.ccnode.codegenerator.common.VersionManager; import com.ccnode.codegenerator.storage.SettingService; package com.ccnode.codegenerator.enums; /** * What always stop you is what you always believe. * <p> * Created by zhengjun.du on 2016/08/31 16:39 */ public class UrlManager { private static String GENERATOR_URL = "http://www.codehelper.me/generator/"; private static String MAIN_PAGE = "https://github.com/zhengjunbase/codehelper.generator"; private static String POST_URL = "http://www.codehelper.me/generator/post"; private static String DONATE_CLICK_URL = "http://www.codehelper.me/generator" ; public static String getUrlSuffix (){
return "?id=" + SettingService.getUUID() + "&version=" + VersionManager.getCurrentVersion();
zhengjunbase/codehelper.generator
src/main/java/com/ccnode/codegenerator/enums/UrlManager.java
// Path: src/main/java/com/ccnode/codegenerator/common/VersionManager.java // public class VersionManager { // // public static String CURRENT_VERSION = "2018-06-24"; // // public static String getCurrentVersion() { // return CURRENT_VERSION; // } // } // // Path: src/main/java/com/ccnode/codegenerator/storage/SettingService.java // @State(name="SettingService", storages={@Storage(id="other", file="$APP_CONFIG$/codeHelper.xml")}) // public class SettingService implements PersistentStateComponent<SettingDto> { // // SettingDto settingDto; // // public static SettingService getInstance(){ // return ServiceManager.getService(SettingService.class); // } // // public static String getUUID(){ // return getInstance().getState().getUuid(); // } // // public static SettingDto getSetting(){ // return getInstance().getState(); // } // // // @NotNull // @Override // public SettingDto getState() { // if(settingDto == null){ // settingDto = new SettingDto(); // settingDto.setUuid(UUID.randomUUID().toString()); // settingDto.setVersion(VersionManager.getCurrentVersion()); // if(settingDto.getInstalledDate() == null){ // settingDto.setInstalledDate(new Date()); // } // }else{ // if(settingDto.getUpdateDate() == null && !VersionManager.CURRENT_VERSION.equalsIgnoreCase(settingDto.getVersion())){ // settingDto.setOldVersion(settingDto.getVersion()); // settingDto.setVersion(VersionManager.CURRENT_VERSION); // settingDto.setUpdateDate(new Date()); // } // } // if(StringUtils.isBlank(settingDto.getUuid())){ // settingDto.setUuid(UUID.randomUUID().toString()); // } // return settingDto; // } // // // @Override // public void loadState(SettingDto o) { // XmlSerializerUtil.copyBean(o, getState()); // } // // public static void setDonated(){ // getInstance().getState().setDonatedDate(new Date()); // } // // public void setSettingDto(SettingDto settingDto) { // this.settingDto = settingDto; // } // // public static Boolean notExpired(String eKey) { // Date date = SecurityHelper.decryptToDate(eKey); // if (date == null || new Date().compareTo(date) > 0) { // return false; // } else { // return true; // } // } // // public static boolean showDonateBtn(){ // // Integer count = getSetting().getCount(); // // if(isDonated()){ // // return false; // // } // // if(count == null count > 5 && count % 7 == 0){ // // return true; // // } // return false; // } // // public static boolean isDonated() { // return getInstance().getState().getDonatedDate() != null && DateUtil // .getDayBetween(getInstance().getState().getDonatedDate(), new Date()) < 365; // } // // public static String getOldVersion(){ // String oldVersion = getInstance().getState().getVersion(); // if(StringUtils.isBlank(oldVersion)){ // return "no_version"; // } // return oldVersion; // } // // public static void updateLastRunTime(){ // getSetting().setLastRunTime(new Date()); // } // // public static int getSecondAfterLastRun(){ // long l = new Date().getTime() - getSetting().getLastRunTime().getTime() /1000L; // return (int) l; // } // // }
import com.ccnode.codegenerator.common.VersionManager; import com.ccnode.codegenerator.storage.SettingService;
package com.ccnode.codegenerator.enums; /** * What always stop you is what you always believe. * <p> * Created by zhengjun.du on 2016/08/31 16:39 */ public class UrlManager { private static String GENERATOR_URL = "http://www.codehelper.me/generator/"; private static String MAIN_PAGE = "https://github.com/zhengjunbase/codehelper.generator"; private static String POST_URL = "http://www.codehelper.me/generator/post"; private static String DONATE_CLICK_URL = "http://www.codehelper.me/generator" ; public static String getUrlSuffix (){
// Path: src/main/java/com/ccnode/codegenerator/common/VersionManager.java // public class VersionManager { // // public static String CURRENT_VERSION = "2018-06-24"; // // public static String getCurrentVersion() { // return CURRENT_VERSION; // } // } // // Path: src/main/java/com/ccnode/codegenerator/storage/SettingService.java // @State(name="SettingService", storages={@Storage(id="other", file="$APP_CONFIG$/codeHelper.xml")}) // public class SettingService implements PersistentStateComponent<SettingDto> { // // SettingDto settingDto; // // public static SettingService getInstance(){ // return ServiceManager.getService(SettingService.class); // } // // public static String getUUID(){ // return getInstance().getState().getUuid(); // } // // public static SettingDto getSetting(){ // return getInstance().getState(); // } // // // @NotNull // @Override // public SettingDto getState() { // if(settingDto == null){ // settingDto = new SettingDto(); // settingDto.setUuid(UUID.randomUUID().toString()); // settingDto.setVersion(VersionManager.getCurrentVersion()); // if(settingDto.getInstalledDate() == null){ // settingDto.setInstalledDate(new Date()); // } // }else{ // if(settingDto.getUpdateDate() == null && !VersionManager.CURRENT_VERSION.equalsIgnoreCase(settingDto.getVersion())){ // settingDto.setOldVersion(settingDto.getVersion()); // settingDto.setVersion(VersionManager.CURRENT_VERSION); // settingDto.setUpdateDate(new Date()); // } // } // if(StringUtils.isBlank(settingDto.getUuid())){ // settingDto.setUuid(UUID.randomUUID().toString()); // } // return settingDto; // } // // // @Override // public void loadState(SettingDto o) { // XmlSerializerUtil.copyBean(o, getState()); // } // // public static void setDonated(){ // getInstance().getState().setDonatedDate(new Date()); // } // // public void setSettingDto(SettingDto settingDto) { // this.settingDto = settingDto; // } // // public static Boolean notExpired(String eKey) { // Date date = SecurityHelper.decryptToDate(eKey); // if (date == null || new Date().compareTo(date) > 0) { // return false; // } else { // return true; // } // } // // public static boolean showDonateBtn(){ // // Integer count = getSetting().getCount(); // // if(isDonated()){ // // return false; // // } // // if(count == null count > 5 && count % 7 == 0){ // // return true; // // } // return false; // } // // public static boolean isDonated() { // return getInstance().getState().getDonatedDate() != null && DateUtil // .getDayBetween(getInstance().getState().getDonatedDate(), new Date()) < 365; // } // // public static String getOldVersion(){ // String oldVersion = getInstance().getState().getVersion(); // if(StringUtils.isBlank(oldVersion)){ // return "no_version"; // } // return oldVersion; // } // // public static void updateLastRunTime(){ // getSetting().setLastRunTime(new Date()); // } // // public static int getSecondAfterLastRun(){ // long l = new Date().getTime() - getSetting().getLastRunTime().getTime() /1000L; // return (int) l; // } // // } // Path: src/main/java/com/ccnode/codegenerator/enums/UrlManager.java import com.ccnode.codegenerator.common.VersionManager; import com.ccnode.codegenerator.storage.SettingService; package com.ccnode.codegenerator.enums; /** * What always stop you is what you always believe. * <p> * Created by zhengjun.du on 2016/08/31 16:39 */ public class UrlManager { private static String GENERATOR_URL = "http://www.codehelper.me/generator/"; private static String MAIN_PAGE = "https://github.com/zhengjunbase/codehelper.generator"; private static String POST_URL = "http://www.codehelper.me/generator/post"; private static String DONATE_CLICK_URL = "http://www.codehelper.me/generator" ; public static String getUrlSuffix (){
return "?id=" + SettingService.getUUID() + "&version=" + VersionManager.getCurrentVersion();
zhengjunbase/codehelper.generator
src/main/java/com/ccnode/codegenerator/view/ShowLearnMoreAction.java
// Path: src/main/java/com/ccnode/codegenerator/enums/UrlManager.java // public class UrlManager { // // private static String GENERATOR_URL = "http://www.codehelper.me/generator/"; // private static String MAIN_PAGE = "https://github.com/zhengjunbase/codehelper.generator"; // private static String POST_URL = "http://www.codehelper.me/generator/post"; // private static String DONATE_CLICK_URL = "http://www.codehelper.me/generator" ; // // public static String getUrlSuffix (){ // return "?id=" + SettingService.getUUID() + "&version=" + VersionManager.getCurrentVersion(); // } // // public static String getMainPage() { // return MAIN_PAGE + getUrlSuffix(); // } // // // // public static String getPostUrl() { // return POST_URL + getUrlSuffix(); // } // // // public static String getDonateClickUrl() { // return DONATE_CLICK_URL + getUrlSuffix() + "#toc_4"; // } // // // }
import com.ccnode.codegenerator.enums.UrlManager; import com.intellij.ide.browsers.BrowserLauncher; import com.intellij.ide.browsers.WebBrowserManager; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent;
package com.ccnode.codegenerator.view; /** * What always stop you is what you always believe. * <p> * Created by zhengjun.du on 2016/04/16 21:30 */ public class ShowLearnMoreAction extends AnAction { public void actionPerformed(AnActionEvent event) {
// Path: src/main/java/com/ccnode/codegenerator/enums/UrlManager.java // public class UrlManager { // // private static String GENERATOR_URL = "http://www.codehelper.me/generator/"; // private static String MAIN_PAGE = "https://github.com/zhengjunbase/codehelper.generator"; // private static String POST_URL = "http://www.codehelper.me/generator/post"; // private static String DONATE_CLICK_URL = "http://www.codehelper.me/generator" ; // // public static String getUrlSuffix (){ // return "?id=" + SettingService.getUUID() + "&version=" + VersionManager.getCurrentVersion(); // } // // public static String getMainPage() { // return MAIN_PAGE + getUrlSuffix(); // } // // // // public static String getPostUrl() { // return POST_URL + getUrlSuffix(); // } // // // public static String getDonateClickUrl() { // return DONATE_CLICK_URL + getUrlSuffix() + "#toc_4"; // } // // // } // Path: src/main/java/com/ccnode/codegenerator/view/ShowLearnMoreAction.java import com.ccnode.codegenerator.enums.UrlManager; import com.intellij.ide.browsers.BrowserLauncher; import com.intellij.ide.browsers.WebBrowserManager; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; package com.ccnode.codegenerator.view; /** * What always stop you is what you always believe. * <p> * Created by zhengjun.du on 2016/04/16 21:30 */ public class ShowLearnMoreAction extends AnAction { public void actionPerformed(AnActionEvent event) {
BrowserLauncher.getInstance().browse(UrlManager.getMainPage() , WebBrowserManager.getInstance().getFirstActiveBrowser());
zhengjunbase/codehelper.generator
src/main/java/com/ccnode/codegenerator/pojo/PojoFieldInfo.java
// Path: src/main/java/com/ccnode/codegenerator/enums/SupportFieldClass.java // public enum SupportFieldClass { // STRING(0,"java.lang.String"), // DATE(1,"java.util.Date"), // BIG_DECIMAL(2,"java.math.BigDecimal"), // INTEGER(3,"java.lang.Integer"), // LONG(4,"java.lang.Long"), // SHORT(5,"java.lang.Short"), // DOUBLE(6,"java.lang.Double"), // FLOAT(7,"java.lang.Float"), // JAVA_SQL_TIMESTAMP(8,"java.sql.Timestamp"), // JAVA_SQL_Date(9,"java.sql.Date"), // BASIC_INT(10,"int"), // BASIC_LONG(11,"long"), // BASIC_SHORT(12,"short"), // BASIC_DOUBLE(13,"double"), // BASIC_FLOAT(14,"float"), // NONE(-1,"none"); // // private Integer code; // private String desc; // // private SupportFieldClass(Integer code,String desc){ // this.code = code; // this.desc = desc; // } // // public Integer getCode() { // return code; // } // // public String getDesc() { // return desc; // } // // public static SupportFieldClass fromName(String name){ // for(SupportFieldClass e : SupportFieldClass.values()){ // if (e.name().equals(name)){ // return e; // } // } // return SupportFieldClass.NONE; // } // // public static SupportFieldClass fromCode(Integer code){ // for(SupportFieldClass e : SupportFieldClass.values()){ // if (e.getCode().equals(code)){ // return e; // } // } // return SupportFieldClass.NONE; // } // // public static SupportFieldClass fromDesc(String desc){ // for(SupportFieldClass e : SupportFieldClass.values()){ // if (e.getDesc().equalsIgnoreCase(desc)){ // return e; // } // } // return SupportFieldClass.NONE; // } // // // }
import com.ccnode.codegenerator.enums.SupportFieldClass; import org.jetbrains.annotations.Nullable; import java.lang.annotation.Annotation; import java.util.List;
package com.ccnode.codegenerator.pojo; /** * What always stop you is what you always believe. * <p> * Created by zhengjun.du on 2016/05/17 19:41 */ public class PojoFieldInfo { String fieldName;
// Path: src/main/java/com/ccnode/codegenerator/enums/SupportFieldClass.java // public enum SupportFieldClass { // STRING(0,"java.lang.String"), // DATE(1,"java.util.Date"), // BIG_DECIMAL(2,"java.math.BigDecimal"), // INTEGER(3,"java.lang.Integer"), // LONG(4,"java.lang.Long"), // SHORT(5,"java.lang.Short"), // DOUBLE(6,"java.lang.Double"), // FLOAT(7,"java.lang.Float"), // JAVA_SQL_TIMESTAMP(8,"java.sql.Timestamp"), // JAVA_SQL_Date(9,"java.sql.Date"), // BASIC_INT(10,"int"), // BASIC_LONG(11,"long"), // BASIC_SHORT(12,"short"), // BASIC_DOUBLE(13,"double"), // BASIC_FLOAT(14,"float"), // NONE(-1,"none"); // // private Integer code; // private String desc; // // private SupportFieldClass(Integer code,String desc){ // this.code = code; // this.desc = desc; // } // // public Integer getCode() { // return code; // } // // public String getDesc() { // return desc; // } // // public static SupportFieldClass fromName(String name){ // for(SupportFieldClass e : SupportFieldClass.values()){ // if (e.name().equals(name)){ // return e; // } // } // return SupportFieldClass.NONE; // } // // public static SupportFieldClass fromCode(Integer code){ // for(SupportFieldClass e : SupportFieldClass.values()){ // if (e.getCode().equals(code)){ // return e; // } // } // return SupportFieldClass.NONE; // } // // public static SupportFieldClass fromDesc(String desc){ // for(SupportFieldClass e : SupportFieldClass.values()){ // if (e.getDesc().equalsIgnoreCase(desc)){ // return e; // } // } // return SupportFieldClass.NONE; // } // // // } // Path: src/main/java/com/ccnode/codegenerator/pojo/PojoFieldInfo.java import com.ccnode.codegenerator.enums.SupportFieldClass; import org.jetbrains.annotations.Nullable; import java.lang.annotation.Annotation; import java.util.List; package com.ccnode.codegenerator.pojo; /** * What always stop you is what you always believe. * <p> * Created by zhengjun.du on 2016/05/17 19:41 */ public class PojoFieldInfo { String fieldName;
SupportFieldClass fieldClass;
zhengjunbase/codehelper.generator
src/main/java/com/ccnode/codegenerator/genCode/GenCodeServiceTest.java
// Path: src/main/java/com/ccnode/codegenerator/pojo/GenCodeRequest.java // public class GenCodeRequest extends BaseRequest { // // Project project; // List<String> pojoNames; // String projectPath; // String pathSplitter; // // public GenCodeRequest() { // } // // public GenCodeRequest(List<String> pojoNames, String projectPath, String pathSplitter) { // this.pojoNames = pojoNames; // this.projectPath = projectPath; // this.pathSplitter = pathSplitter; // } // // public void setPojoNames(List<String> pojoNames) { // this.pojoNames = pojoNames; // } // // public List<String> getPojoNames() { // return pojoNames; // } // // // public String getProjectPath() { // return projectPath; // } // // public String getPathSplitter() { // return pathSplitter; // } // // public Project getProject() { // return project; // } // // public void setProject(Project project) { // this.project = project; // } // }
import com.ccnode.codegenerator.pojo.GenCodeRequest; import com.google.common.collect.Lists; import org.junit.Test; import java.util.List;
package com.ccnode.codegenerator.genCode; /** * What always stop you is what you always believe. * <p> * Created by zhengjun.du on 2016/05/25 21:24 */ public class GenCodeServiceTest { @Test public void genCode() throws Exception { List<String> list = Lists.newArrayList("TestPojo","TestPojoField");
// Path: src/main/java/com/ccnode/codegenerator/pojo/GenCodeRequest.java // public class GenCodeRequest extends BaseRequest { // // Project project; // List<String> pojoNames; // String projectPath; // String pathSplitter; // // public GenCodeRequest() { // } // // public GenCodeRequest(List<String> pojoNames, String projectPath, String pathSplitter) { // this.pojoNames = pojoNames; // this.projectPath = projectPath; // this.pathSplitter = pathSplitter; // } // // public void setPojoNames(List<String> pojoNames) { // this.pojoNames = pojoNames; // } // // public List<String> getPojoNames() { // return pojoNames; // } // // // public String getProjectPath() { // return projectPath; // } // // public String getPathSplitter() { // return pathSplitter; // } // // public Project getProject() { // return project; // } // // public void setProject(Project project) { // this.project = project; // } // } // Path: src/main/java/com/ccnode/codegenerator/genCode/GenCodeServiceTest.java import com.ccnode.codegenerator.pojo.GenCodeRequest; import com.google.common.collect.Lists; import org.junit.Test; import java.util.List; package com.ccnode.codegenerator.genCode; /** * What always stop you is what you always believe. * <p> * Created by zhengjun.du on 2016/05/25 21:24 */ public class GenCodeServiceTest { @Test public void genCode() throws Exception { List<String> list = Lists.newArrayList("TestPojo","TestPojoField");
GenCodeRequest request = new GenCodeRequest(list,"/Users/zhengjun/Workspaces/genCodeSpace/MybatisGenerator","/");
zhengjunbase/codehelper.generator
src/main/java/com/ccnode/codegenerator/pojo/GeneratedFile.java
// Path: src/main/java/com/ccnode/codegenerator/enums/FileType.java // public enum FileType { // SQL(0,".sql"), // MAPPER(1,".xml"), // SERVICE(2,".java"), // DAO(3,".java"), // NONE(-1,"none"); // // private Integer code; // private String suffix; // // private FileType(Integer code,String suffix){ // this.code = code; // this.suffix = suffix; // } // // public Integer getCode() { // return code; // } // // public String getSuffix() { // return suffix; // } // // public static FileType fromName(String name){ // for(FileType e : FileType.values()){ // if (e.name().equals(name)){ // return e; // } // } // return FileType.NONE; // } // // public static FileType fromCode(Integer code){ // for(FileType e : FileType.values()){ // if (e.getCode().equals(code)){ // return e; // } // } // return FileType.NONE; // } // // public static String codeToName(Integer code){ // FileType o = fromCode(code); // return o.name(); // } // // public static Integer nameToCode(String name){ // FileType o = fromName(name); // return o.getCode(); // } // } // // Path: src/main/java/com/ccnode/codegenerator/enums/FileType.java // public enum FileType { // SQL(0,".sql"), // MAPPER(1,".xml"), // SERVICE(2,".java"), // DAO(3,".java"), // NONE(-1,"none"); // // private Integer code; // private String suffix; // // private FileType(Integer code,String suffix){ // this.code = code; // this.suffix = suffix; // } // // public Integer getCode() { // return code; // } // // public String getSuffix() { // return suffix; // } // // public static FileType fromName(String name){ // for(FileType e : FileType.values()){ // if (e.name().equals(name)){ // return e; // } // } // return FileType.NONE; // } // // public static FileType fromCode(Integer code){ // for(FileType e : FileType.values()){ // if (e.getCode().equals(code)){ // return e; // } // } // return FileType.NONE; // } // // public static String codeToName(Integer code){ // FileType o = fromCode(code); // return o.name(); // } // // public static Integer nameToCode(String name){ // FileType o = fromName(name); // return o.getCode(); // } // }
import com.ccnode.codegenerator.enums.FileType; import com.ccnode.codegenerator.enums.FileType; import java.io.File; import java.util.List;
package com.ccnode.codegenerator.pojo; /** * What always stop you is what you always believe. * <p> * Created by zhengjun.du on 2016/05/17 19:55 */ public class GeneratedFile { File file; String filePath; List<String> newLines; List<String> oldLines; List<String> originLines;
// Path: src/main/java/com/ccnode/codegenerator/enums/FileType.java // public enum FileType { // SQL(0,".sql"), // MAPPER(1,".xml"), // SERVICE(2,".java"), // DAO(3,".java"), // NONE(-1,"none"); // // private Integer code; // private String suffix; // // private FileType(Integer code,String suffix){ // this.code = code; // this.suffix = suffix; // } // // public Integer getCode() { // return code; // } // // public String getSuffix() { // return suffix; // } // // public static FileType fromName(String name){ // for(FileType e : FileType.values()){ // if (e.name().equals(name)){ // return e; // } // } // return FileType.NONE; // } // // public static FileType fromCode(Integer code){ // for(FileType e : FileType.values()){ // if (e.getCode().equals(code)){ // return e; // } // } // return FileType.NONE; // } // // public static String codeToName(Integer code){ // FileType o = fromCode(code); // return o.name(); // } // // public static Integer nameToCode(String name){ // FileType o = fromName(name); // return o.getCode(); // } // } // // Path: src/main/java/com/ccnode/codegenerator/enums/FileType.java // public enum FileType { // SQL(0,".sql"), // MAPPER(1,".xml"), // SERVICE(2,".java"), // DAO(3,".java"), // NONE(-1,"none"); // // private Integer code; // private String suffix; // // private FileType(Integer code,String suffix){ // this.code = code; // this.suffix = suffix; // } // // public Integer getCode() { // return code; // } // // public String getSuffix() { // return suffix; // } // // public static FileType fromName(String name){ // for(FileType e : FileType.values()){ // if (e.name().equals(name)){ // return e; // } // } // return FileType.NONE; // } // // public static FileType fromCode(Integer code){ // for(FileType e : FileType.values()){ // if (e.getCode().equals(code)){ // return e; // } // } // return FileType.NONE; // } // // public static String codeToName(Integer code){ // FileType o = fromCode(code); // return o.name(); // } // // public static Integer nameToCode(String name){ // FileType o = fromName(name); // return o.getCode(); // } // } // Path: src/main/java/com/ccnode/codegenerator/pojo/GeneratedFile.java import com.ccnode.codegenerator.enums.FileType; import com.ccnode.codegenerator.enums.FileType; import java.io.File; import java.util.List; package com.ccnode.codegenerator.pojo; /** * What always stop you is what you always believe. * <p> * Created by zhengjun.du on 2016/05/17 19:55 */ public class GeneratedFile { File file; String filePath; List<String> newLines; List<String> oldLines; List<String> originLines;
FileType fileType;
zhengjunbase/codehelper.generator
src/main/java/com/ccnode/codegenerator/util/HttpUtil.java
// Path: src/main/java/com/ccnode/codegenerator/pojo/RequestData.java // public class RequestData { // // private String data ; // // public String getData() { // return data; // } // // public void setData(String data) { // this.data = data; // } // }
import com.ccnode.codegenerator.pojo.RequestData; import org.apache.commons.lang3.StringUtils; import org.apache.http.*; import org.apache.http.client.HttpRequestRetryHandler; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.protocol.HttpClientContext; import org.apache.http.config.Registry; import org.apache.http.config.RegistryBuilder; import org.apache.http.conn.socket.ConnectionSocketFactory; import org.apache.http.conn.socket.PlainConnectionSocketFactory; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.conn.ssl.SSLContextBuilder; import org.apache.http.conn.ssl.TrustStrategy; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.protocol.HttpContext; import org.apache.http.util.EntityUtils; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import javax.net.ssl.SSLException; import javax.net.ssl.X509TrustManager; import java.io.IOException; import java.io.InterruptedIOException; import java.net.UnknownHostException; import java.nio.charset.Charset; import java.security.cert.CertificateException; import java.security.cert.X509Certificate;
logger.warn(NOTICELINE + " httpUtil init done " + NOTICELINE); } catch (Exception e) { logger.error(NOTICELINE + "httpclient init fail" + NOTICELINE, e); throw new RuntimeException(e); } } private static class TrustAnyTrustManager implements X509TrustManager, TrustStrategy { public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {} public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {} public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[]{};} @Override public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {return true;} } public static CloseableHttpClient getHttpclient() { if (null == httpclient) { init(); } return httpclient; } public static String postJson(String url, String body) { return postJsonWithResult(url, body).result; } public static String postJson(String url, Object body) {
// Path: src/main/java/com/ccnode/codegenerator/pojo/RequestData.java // public class RequestData { // // private String data ; // // public String getData() { // return data; // } // // public void setData(String data) { // this.data = data; // } // } // Path: src/main/java/com/ccnode/codegenerator/util/HttpUtil.java import com.ccnode.codegenerator.pojo.RequestData; import org.apache.commons.lang3.StringUtils; import org.apache.http.*; import org.apache.http.client.HttpRequestRetryHandler; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.protocol.HttpClientContext; import org.apache.http.config.Registry; import org.apache.http.config.RegistryBuilder; import org.apache.http.conn.socket.ConnectionSocketFactory; import org.apache.http.conn.socket.PlainConnectionSocketFactory; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.conn.ssl.SSLContextBuilder; import org.apache.http.conn.ssl.TrustStrategy; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.protocol.HttpContext; import org.apache.http.util.EntityUtils; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import javax.net.ssl.SSLException; import javax.net.ssl.X509TrustManager; import java.io.IOException; import java.io.InterruptedIOException; import java.net.UnknownHostException; import java.nio.charset.Charset; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; logger.warn(NOTICELINE + " httpUtil init done " + NOTICELINE); } catch (Exception e) { logger.error(NOTICELINE + "httpclient init fail" + NOTICELINE, e); throw new RuntimeException(e); } } private static class TrustAnyTrustManager implements X509TrustManager, TrustStrategy { public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {} public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {} public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[]{};} @Override public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {return true;} } public static CloseableHttpClient getHttpclient() { if (null == httpclient) { init(); } return httpclient; } public static String postJson(String url, String body) { return postJsonWithResult(url, body).result; } public static String postJson(String url, Object body) {
RequestData data = new RequestData();
zhengjunbase/codehelper.generator
src/main/java/com/ccnode/codegenerator/util/IOUtils.java
// Path: src/main/java/com/ccnode/codegenerator/exception/BizException.java // public class BizException extends RuntimeException { // // public BizException(){ // } // // public BizException(String s){ // super(s); // } // // } // // Path: src/main/java/com/ccnode/codegenerator/exception/BizException.java // public class BizException extends RuntimeException { // // public BizException(){ // } // // public BizException(String s){ // super(s); // } // // } // // Path: src/main/java/com/ccnode/codegenerator/pojoHelper/GenCodeResponseHelper.java // public class GenCodeResponseHelper { // // private static GenCodeResponse response; // // public static void setResponse(GenCodeResponse response) { // GenCodeResponseHelper.response = response; // } // // public static GenCodeResponse getResponse() { // return response; // } // // public static GeneratedFile getByFileType(@NotNull OnePojoInfo onePojoInfo, FileType type, GenCodeResponse genCodeResponse){ // String mapperSuffix = UserConfigService.removeStartAndEndSplitter(genCodeResponse.getUserConfigMap().get("mapper.suffix")); // String daoSuffix = UserConfigService.removeStartAndEndSplitter(genCodeResponse.getUserConfigMap().get("dao.suffix")); // String serviceSuffix = UserConfigService.removeStartAndEndSplitter(genCodeResponse.getUserConfigMap().get("service.suffix")); // String suffix = StringUtils.EMPTY; // switch (type){ // case MAPPER: // suffix = mapperSuffix == null ? GenCodeConfig.MAPPER_SUFFIX:mapperSuffix; // break; // case DAO: // suffix = daoSuffix == null ? GenCodeConfig.DAO_SUFFIX:daoSuffix; // break; // case SERVICE: // suffix = serviceSuffix == null ? GenCodeConfig.SERVICE_SUFFIX:serviceSuffix; // break; // } // for (GeneratedFile generatedFile : onePojoInfo.getFiles()) { // if(type == FileType.NONE){ // continue; // } // if(generatedFile.getFileType().getCode().intValue() == type.getCode().intValue() // && (suffix+generatedFile.getFileType().getSuffix()).equals(suffix+ type.getSuffix())){ // generatedFile.setSuffix(suffix); // for (PojoFieldInfo fieldInfo:onePojoInfo.getPojoFieldInfos()) { // if("id".equalsIgnoreCase(fieldInfo.getFieldName())){ // onePojoInfo.setIdType(fieldInfo.getFieldClass().getDesc()); // break; // } // } // return generatedFile; // } // } // // todo // throw new RuntimeException("获取文件错误"); // } // public static Boolean isUseGenericDao(GenCodeResponse response){ // return getSwitch(response,"usegenericdao"); // } // // public static Boolean getSwitch(GenCodeResponse response, String key){ // return response != null && response.getUserConfigMap() != null && Objects.equal( response.getUserConfigMap().get(key),"true"); // } // // public static String getProjectPathWithSplitter(GenCodeResponse response){ // String projectPath = response.getRequest().getProjectPath(); // if(StringUtils.isBlank(projectPath)){ // throw new RuntimeException("error, projectPath is empty"); // } // if(!projectPath.endsWith(response.getPathSplitter())){ // projectPath += response.getPathSplitter(); // } // return projectPath; // } // // public static String getPathSplitter(){ // return System.getProperty("file.separator"); // } // @Nullable // public static String getSplitKey(GenCodeResponse response){ // return response.getUserConfigMap().get("splitkey"); // } // // }
import com.ccnode.codegenerator.exception.BizException; import com.ccnode.codegenerator.exception.BizException; import com.ccnode.codegenerator.pojoHelper.GenCodeResponseHelper; import com.google.common.base.Charsets; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import com.google.common.io.CharSink; import com.google.common.io.Files; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.StringUtils; import org.jetbrains.annotations.Nullable; import java.io.File; import java.io.IOException; import java.nio.charset.Charset; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern;
public static <T> List<T> readLines(String fileName, LineProcessor<T> lineProcessor) throws IOException { File file = new File(fileName); Preconditions.checkNotNull(file); Preconditions.checkState(file.isFile()); return readLines(file, lineProcessor); } public static void writeLines(String fileName,List<String> list) throws IOException { writeLines(fileName, list, DEFAULT_CHARSET); } public static void writeLines(String fileName,List<String> list,Charset charset) throws IOException { CharSink cs = Files.asCharSink(new File(fileName), charset); list = PojoUtil.avoidEmptyList(list); cs.writeLines(list); } public static void writeLines(File file,List<String> list) throws IOException { writeLines(file, list, DEFAULT_CHARSET); } public static void writeLines(File file,List<String> list,Charset charset) throws IOException { CharSink cs = Files.asCharSink(file, charset); list = PojoUtil.avoidEmptyList(list); cs.writeLines(list); } @Nullable public static File matchOnlyOneFile(String directory, String subFileName){ List<File> allSubFiles = IOUtils.getAllSubFiles(directory);
// Path: src/main/java/com/ccnode/codegenerator/exception/BizException.java // public class BizException extends RuntimeException { // // public BizException(){ // } // // public BizException(String s){ // super(s); // } // // } // // Path: src/main/java/com/ccnode/codegenerator/exception/BizException.java // public class BizException extends RuntimeException { // // public BizException(){ // } // // public BizException(String s){ // super(s); // } // // } // // Path: src/main/java/com/ccnode/codegenerator/pojoHelper/GenCodeResponseHelper.java // public class GenCodeResponseHelper { // // private static GenCodeResponse response; // // public static void setResponse(GenCodeResponse response) { // GenCodeResponseHelper.response = response; // } // // public static GenCodeResponse getResponse() { // return response; // } // // public static GeneratedFile getByFileType(@NotNull OnePojoInfo onePojoInfo, FileType type, GenCodeResponse genCodeResponse){ // String mapperSuffix = UserConfigService.removeStartAndEndSplitter(genCodeResponse.getUserConfigMap().get("mapper.suffix")); // String daoSuffix = UserConfigService.removeStartAndEndSplitter(genCodeResponse.getUserConfigMap().get("dao.suffix")); // String serviceSuffix = UserConfigService.removeStartAndEndSplitter(genCodeResponse.getUserConfigMap().get("service.suffix")); // String suffix = StringUtils.EMPTY; // switch (type){ // case MAPPER: // suffix = mapperSuffix == null ? GenCodeConfig.MAPPER_SUFFIX:mapperSuffix; // break; // case DAO: // suffix = daoSuffix == null ? GenCodeConfig.DAO_SUFFIX:daoSuffix; // break; // case SERVICE: // suffix = serviceSuffix == null ? GenCodeConfig.SERVICE_SUFFIX:serviceSuffix; // break; // } // for (GeneratedFile generatedFile : onePojoInfo.getFiles()) { // if(type == FileType.NONE){ // continue; // } // if(generatedFile.getFileType().getCode().intValue() == type.getCode().intValue() // && (suffix+generatedFile.getFileType().getSuffix()).equals(suffix+ type.getSuffix())){ // generatedFile.setSuffix(suffix); // for (PojoFieldInfo fieldInfo:onePojoInfo.getPojoFieldInfos()) { // if("id".equalsIgnoreCase(fieldInfo.getFieldName())){ // onePojoInfo.setIdType(fieldInfo.getFieldClass().getDesc()); // break; // } // } // return generatedFile; // } // } // // todo // throw new RuntimeException("获取文件错误"); // } // public static Boolean isUseGenericDao(GenCodeResponse response){ // return getSwitch(response,"usegenericdao"); // } // // public static Boolean getSwitch(GenCodeResponse response, String key){ // return response != null && response.getUserConfigMap() != null && Objects.equal( response.getUserConfigMap().get(key),"true"); // } // // public static String getProjectPathWithSplitter(GenCodeResponse response){ // String projectPath = response.getRequest().getProjectPath(); // if(StringUtils.isBlank(projectPath)){ // throw new RuntimeException("error, projectPath is empty"); // } // if(!projectPath.endsWith(response.getPathSplitter())){ // projectPath += response.getPathSplitter(); // } // return projectPath; // } // // public static String getPathSplitter(){ // return System.getProperty("file.separator"); // } // @Nullable // public static String getSplitKey(GenCodeResponse response){ // return response.getUserConfigMap().get("splitkey"); // } // // } // Path: src/main/java/com/ccnode/codegenerator/util/IOUtils.java import com.ccnode.codegenerator.exception.BizException; import com.ccnode.codegenerator.exception.BizException; import com.ccnode.codegenerator.pojoHelper.GenCodeResponseHelper; import com.google.common.base.Charsets; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import com.google.common.io.CharSink; import com.google.common.io.Files; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.StringUtils; import org.jetbrains.annotations.Nullable; import java.io.File; import java.io.IOException; import java.nio.charset.Charset; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; public static <T> List<T> readLines(String fileName, LineProcessor<T> lineProcessor) throws IOException { File file = new File(fileName); Preconditions.checkNotNull(file); Preconditions.checkState(file.isFile()); return readLines(file, lineProcessor); } public static void writeLines(String fileName,List<String> list) throws IOException { writeLines(fileName, list, DEFAULT_CHARSET); } public static void writeLines(String fileName,List<String> list,Charset charset) throws IOException { CharSink cs = Files.asCharSink(new File(fileName), charset); list = PojoUtil.avoidEmptyList(list); cs.writeLines(list); } public static void writeLines(File file,List<String> list) throws IOException { writeLines(file, list, DEFAULT_CHARSET); } public static void writeLines(File file,List<String> list,Charset charset) throws IOException { CharSink cs = Files.asCharSink(file, charset); list = PojoUtil.avoidEmptyList(list); cs.writeLines(list); } @Nullable public static File matchOnlyOneFile(String directory, String subFileName){ List<File> allSubFiles = IOUtils.getAllSubFiles(directory);
if(!subFileName.startsWith(GenCodeResponseHelper.getPathSplitter())){
zhengjunbase/codehelper.generator
src/main/java/com/ccnode/codegenerator/util/IOUtils.java
// Path: src/main/java/com/ccnode/codegenerator/exception/BizException.java // public class BizException extends RuntimeException { // // public BizException(){ // } // // public BizException(String s){ // super(s); // } // // } // // Path: src/main/java/com/ccnode/codegenerator/exception/BizException.java // public class BizException extends RuntimeException { // // public BizException(){ // } // // public BizException(String s){ // super(s); // } // // } // // Path: src/main/java/com/ccnode/codegenerator/pojoHelper/GenCodeResponseHelper.java // public class GenCodeResponseHelper { // // private static GenCodeResponse response; // // public static void setResponse(GenCodeResponse response) { // GenCodeResponseHelper.response = response; // } // // public static GenCodeResponse getResponse() { // return response; // } // // public static GeneratedFile getByFileType(@NotNull OnePojoInfo onePojoInfo, FileType type, GenCodeResponse genCodeResponse){ // String mapperSuffix = UserConfigService.removeStartAndEndSplitter(genCodeResponse.getUserConfigMap().get("mapper.suffix")); // String daoSuffix = UserConfigService.removeStartAndEndSplitter(genCodeResponse.getUserConfigMap().get("dao.suffix")); // String serviceSuffix = UserConfigService.removeStartAndEndSplitter(genCodeResponse.getUserConfigMap().get("service.suffix")); // String suffix = StringUtils.EMPTY; // switch (type){ // case MAPPER: // suffix = mapperSuffix == null ? GenCodeConfig.MAPPER_SUFFIX:mapperSuffix; // break; // case DAO: // suffix = daoSuffix == null ? GenCodeConfig.DAO_SUFFIX:daoSuffix; // break; // case SERVICE: // suffix = serviceSuffix == null ? GenCodeConfig.SERVICE_SUFFIX:serviceSuffix; // break; // } // for (GeneratedFile generatedFile : onePojoInfo.getFiles()) { // if(type == FileType.NONE){ // continue; // } // if(generatedFile.getFileType().getCode().intValue() == type.getCode().intValue() // && (suffix+generatedFile.getFileType().getSuffix()).equals(suffix+ type.getSuffix())){ // generatedFile.setSuffix(suffix); // for (PojoFieldInfo fieldInfo:onePojoInfo.getPojoFieldInfos()) { // if("id".equalsIgnoreCase(fieldInfo.getFieldName())){ // onePojoInfo.setIdType(fieldInfo.getFieldClass().getDesc()); // break; // } // } // return generatedFile; // } // } // // todo // throw new RuntimeException("获取文件错误"); // } // public static Boolean isUseGenericDao(GenCodeResponse response){ // return getSwitch(response,"usegenericdao"); // } // // public static Boolean getSwitch(GenCodeResponse response, String key){ // return response != null && response.getUserConfigMap() != null && Objects.equal( response.getUserConfigMap().get(key),"true"); // } // // public static String getProjectPathWithSplitter(GenCodeResponse response){ // String projectPath = response.getRequest().getProjectPath(); // if(StringUtils.isBlank(projectPath)){ // throw new RuntimeException("error, projectPath is empty"); // } // if(!projectPath.endsWith(response.getPathSplitter())){ // projectPath += response.getPathSplitter(); // } // return projectPath; // } // // public static String getPathSplitter(){ // return System.getProperty("file.separator"); // } // @Nullable // public static String getSplitKey(GenCodeResponse response){ // return response.getUserConfigMap().get("splitkey"); // } // // }
import com.ccnode.codegenerator.exception.BizException; import com.ccnode.codegenerator.exception.BizException; import com.ccnode.codegenerator.pojoHelper.GenCodeResponseHelper; import com.google.common.base.Charsets; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import com.google.common.io.CharSink; import com.google.common.io.Files; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.StringUtils; import org.jetbrains.annotations.Nullable; import java.io.File; import java.io.IOException; import java.nio.charset.Charset; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern;
} public static void writeLines(File file,List<String> list) throws IOException { writeLines(file, list, DEFAULT_CHARSET); } public static void writeLines(File file,List<String> list,Charset charset) throws IOException { CharSink cs = Files.asCharSink(file, charset); list = PojoUtil.avoidEmptyList(list); cs.writeLines(list); } @Nullable public static File matchOnlyOneFile(String directory, String subFileName){ List<File> allSubFiles = IOUtils.getAllSubFiles(directory); if(!subFileName.startsWith(GenCodeResponseHelper.getPathSplitter())){ subFileName = GenCodeResponseHelper.getPathSplitter() + subFileName; } allSubFiles = PojoUtil.avoidEmptyList(allSubFiles); File configFile = null; String targetDirPrefix = GenCodeResponseHelper.getPathSplitter() + "target" + GenCodeResponseHelper.getPathSplitter(); for (File subFile : allSubFiles) { if(!StringUtils.containsIgnoreCase(subFile.getAbsolutePath(), targetDirPrefix) && StringUtils.endsWithIgnoreCase(subFile.getAbsolutePath(),subFileName)){ if(configFile == null){ configFile = subFile; }else{ //todo 调试的时候加上. // return "NOT_ONLY";
// Path: src/main/java/com/ccnode/codegenerator/exception/BizException.java // public class BizException extends RuntimeException { // // public BizException(){ // } // // public BizException(String s){ // super(s); // } // // } // // Path: src/main/java/com/ccnode/codegenerator/exception/BizException.java // public class BizException extends RuntimeException { // // public BizException(){ // } // // public BizException(String s){ // super(s); // } // // } // // Path: src/main/java/com/ccnode/codegenerator/pojoHelper/GenCodeResponseHelper.java // public class GenCodeResponseHelper { // // private static GenCodeResponse response; // // public static void setResponse(GenCodeResponse response) { // GenCodeResponseHelper.response = response; // } // // public static GenCodeResponse getResponse() { // return response; // } // // public static GeneratedFile getByFileType(@NotNull OnePojoInfo onePojoInfo, FileType type, GenCodeResponse genCodeResponse){ // String mapperSuffix = UserConfigService.removeStartAndEndSplitter(genCodeResponse.getUserConfigMap().get("mapper.suffix")); // String daoSuffix = UserConfigService.removeStartAndEndSplitter(genCodeResponse.getUserConfigMap().get("dao.suffix")); // String serviceSuffix = UserConfigService.removeStartAndEndSplitter(genCodeResponse.getUserConfigMap().get("service.suffix")); // String suffix = StringUtils.EMPTY; // switch (type){ // case MAPPER: // suffix = mapperSuffix == null ? GenCodeConfig.MAPPER_SUFFIX:mapperSuffix; // break; // case DAO: // suffix = daoSuffix == null ? GenCodeConfig.DAO_SUFFIX:daoSuffix; // break; // case SERVICE: // suffix = serviceSuffix == null ? GenCodeConfig.SERVICE_SUFFIX:serviceSuffix; // break; // } // for (GeneratedFile generatedFile : onePojoInfo.getFiles()) { // if(type == FileType.NONE){ // continue; // } // if(generatedFile.getFileType().getCode().intValue() == type.getCode().intValue() // && (suffix+generatedFile.getFileType().getSuffix()).equals(suffix+ type.getSuffix())){ // generatedFile.setSuffix(suffix); // for (PojoFieldInfo fieldInfo:onePojoInfo.getPojoFieldInfos()) { // if("id".equalsIgnoreCase(fieldInfo.getFieldName())){ // onePojoInfo.setIdType(fieldInfo.getFieldClass().getDesc()); // break; // } // } // return generatedFile; // } // } // // todo // throw new RuntimeException("获取文件错误"); // } // public static Boolean isUseGenericDao(GenCodeResponse response){ // return getSwitch(response,"usegenericdao"); // } // // public static Boolean getSwitch(GenCodeResponse response, String key){ // return response != null && response.getUserConfigMap() != null && Objects.equal( response.getUserConfigMap().get(key),"true"); // } // // public static String getProjectPathWithSplitter(GenCodeResponse response){ // String projectPath = response.getRequest().getProjectPath(); // if(StringUtils.isBlank(projectPath)){ // throw new RuntimeException("error, projectPath is empty"); // } // if(!projectPath.endsWith(response.getPathSplitter())){ // projectPath += response.getPathSplitter(); // } // return projectPath; // } // // public static String getPathSplitter(){ // return System.getProperty("file.separator"); // } // @Nullable // public static String getSplitKey(GenCodeResponse response){ // return response.getUserConfigMap().get("splitkey"); // } // // } // Path: src/main/java/com/ccnode/codegenerator/util/IOUtils.java import com.ccnode.codegenerator.exception.BizException; import com.ccnode.codegenerator.exception.BizException; import com.ccnode.codegenerator.pojoHelper.GenCodeResponseHelper; import com.google.common.base.Charsets; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import com.google.common.io.CharSink; import com.google.common.io.Files; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.StringUtils; import org.jetbrains.annotations.Nullable; import java.io.File; import java.io.IOException; import java.nio.charset.Charset; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; } public static void writeLines(File file,List<String> list) throws IOException { writeLines(file, list, DEFAULT_CHARSET); } public static void writeLines(File file,List<String> list,Charset charset) throws IOException { CharSink cs = Files.asCharSink(file, charset); list = PojoUtil.avoidEmptyList(list); cs.writeLines(list); } @Nullable public static File matchOnlyOneFile(String directory, String subFileName){ List<File> allSubFiles = IOUtils.getAllSubFiles(directory); if(!subFileName.startsWith(GenCodeResponseHelper.getPathSplitter())){ subFileName = GenCodeResponseHelper.getPathSplitter() + subFileName; } allSubFiles = PojoUtil.avoidEmptyList(allSubFiles); File configFile = null; String targetDirPrefix = GenCodeResponseHelper.getPathSplitter() + "target" + GenCodeResponseHelper.getPathSplitter(); for (File subFile : allSubFiles) { if(!StringUtils.containsIgnoreCase(subFile.getAbsolutePath(), targetDirPrefix) && StringUtils.endsWithIgnoreCase(subFile.getAbsolutePath(),subFileName)){ if(configFile == null){ configFile = subFile; }else{ //todo 调试的时候加上. // return "NOT_ONLY";
throw new BizException("not only one file:" + subFileName);
cestella/streaming_outliers
core/src/main/java/com/caseystella/analytics/timeseries/inmemory/InMemoryTimeSeriesDB.java
// Path: core/src/main/java/com/caseystella/analytics/DataPoint.java // public class DataPoint { // private long timestamp; // private double value; // private Map<String, String> metadata; // private String source; // // public DataPoint() { // // } // // public DataPoint(long timestamp, double value, Map<String, String> metadata, String source) { // this.timestamp = timestamp; // this.value = value; // this.metadata = metadata; // this.source = source; // } // // public String getSource() { // return source; // } // // public void setSource(String source) { // this.source = source; // } // // // // public long getTimestamp() { // return timestamp; // } // // public void setTimestamp(long timestamp) { // this.timestamp = timestamp; // } // // public double getValue() { // return value; // } // // public void setValue(double value) { // this.value = value; // } // // public Map<String, String> getMetadata() { // return metadata; // } // // public void setMetadata(Map<String, String> metadata) { // this.metadata = metadata; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // DataPoint dataPoint = (DataPoint) o; // // if (getTimestamp() != dataPoint.getTimestamp()) return false; // if (Double.compare(dataPoint.getValue(), getValue()) != 0) return false; // if (getMetadata() != null ? !getMetadata().equals(dataPoint.getMetadata()) : dataPoint.getMetadata() != null) // return false; // return source != null ? source.equals(dataPoint.source) : dataPoint.source == null; // // } // // @Override // public int hashCode() { // int result; // long temp; // result = (int) (getTimestamp() ^ (getTimestamp() >>> 32)); // temp = Double.doubleToLongBits(getValue()); // result = 31 * result + (int) (temp ^ (temp >>> 32)); // result = 31 * result + (getMetadata() != null ? getMetadata().hashCode() : 0); // result = 31 * result + (source != null ? source.hashCode() : 0); // return result; // } // @Override // public String toString() { // return "(" + // "timestamp=" + timestamp + // ", value=" + value + // ", metadata=" + metadata + // ", source=" + source+ // ')'; // } // // } // // Path: core/src/main/java/com/caseystella/analytics/distribution/TimeRange.java // public interface TimeRange extends Range<Long>{ // // } // // Path: core/src/main/java/com/caseystella/analytics/timeseries/TimeseriesDatabaseHandler.java // public interface TimeseriesDatabaseHandler extends Serializable { // void persist(String metric, DataPoint pt, Map<String, String> tags, Function<Object, Void> callback); // List<DataPoint> retrieve(String metric, DataPoint pt, TimeRange range, Map<String, String> filter, int maxPts); // void configure(Map<String, Object> config); // }
import com.caseystella.analytics.DataPoint; import com.caseystella.analytics.distribution.TimeRange; import com.caseystella.analytics.timeseries.TimeseriesDatabaseHandler; import com.google.common.base.Function; import com.google.common.collect.ComparisonChain; import com.google.common.collect.Sets; import java.util.*;
} pt.setMetadata(metadata); tsMap.add(pt); } } public static DataPoint getRightEndpoint(long ts) { DataPoint dp = new DataPoint(); dp.setTimestamp(ts); dp.setValue(Long.MAX_VALUE); return dp; } public static DataPoint getLeftEndpoint(long ts) { DataPoint dp = new DataPoint(); dp.setTimestamp(ts); dp.setValue(Long.MIN_VALUE); return dp; } private static boolean mapContains(Map<String, String> tags, Map<String, String> filter) { if(filter != null) { for (Map.Entry<String, String> kv : filter.entrySet()) { Object o = tags.get(kv.getKey()); if (o == null || !o.equals(kv.getValue())) { return false; } } } return true; } @Override
// Path: core/src/main/java/com/caseystella/analytics/DataPoint.java // public class DataPoint { // private long timestamp; // private double value; // private Map<String, String> metadata; // private String source; // // public DataPoint() { // // } // // public DataPoint(long timestamp, double value, Map<String, String> metadata, String source) { // this.timestamp = timestamp; // this.value = value; // this.metadata = metadata; // this.source = source; // } // // public String getSource() { // return source; // } // // public void setSource(String source) { // this.source = source; // } // // // // public long getTimestamp() { // return timestamp; // } // // public void setTimestamp(long timestamp) { // this.timestamp = timestamp; // } // // public double getValue() { // return value; // } // // public void setValue(double value) { // this.value = value; // } // // public Map<String, String> getMetadata() { // return metadata; // } // // public void setMetadata(Map<String, String> metadata) { // this.metadata = metadata; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // DataPoint dataPoint = (DataPoint) o; // // if (getTimestamp() != dataPoint.getTimestamp()) return false; // if (Double.compare(dataPoint.getValue(), getValue()) != 0) return false; // if (getMetadata() != null ? !getMetadata().equals(dataPoint.getMetadata()) : dataPoint.getMetadata() != null) // return false; // return source != null ? source.equals(dataPoint.source) : dataPoint.source == null; // // } // // @Override // public int hashCode() { // int result; // long temp; // result = (int) (getTimestamp() ^ (getTimestamp() >>> 32)); // temp = Double.doubleToLongBits(getValue()); // result = 31 * result + (int) (temp ^ (temp >>> 32)); // result = 31 * result + (getMetadata() != null ? getMetadata().hashCode() : 0); // result = 31 * result + (source != null ? source.hashCode() : 0); // return result; // } // @Override // public String toString() { // return "(" + // "timestamp=" + timestamp + // ", value=" + value + // ", metadata=" + metadata + // ", source=" + source+ // ')'; // } // // } // // Path: core/src/main/java/com/caseystella/analytics/distribution/TimeRange.java // public interface TimeRange extends Range<Long>{ // // } // // Path: core/src/main/java/com/caseystella/analytics/timeseries/TimeseriesDatabaseHandler.java // public interface TimeseriesDatabaseHandler extends Serializable { // void persist(String metric, DataPoint pt, Map<String, String> tags, Function<Object, Void> callback); // List<DataPoint> retrieve(String metric, DataPoint pt, TimeRange range, Map<String, String> filter, int maxPts); // void configure(Map<String, Object> config); // } // Path: core/src/main/java/com/caseystella/analytics/timeseries/inmemory/InMemoryTimeSeriesDB.java import com.caseystella.analytics.DataPoint; import com.caseystella.analytics.distribution.TimeRange; import com.caseystella.analytics.timeseries.TimeseriesDatabaseHandler; import com.google.common.base.Function; import com.google.common.collect.ComparisonChain; import com.google.common.collect.Sets; import java.util.*; } pt.setMetadata(metadata); tsMap.add(pt); } } public static DataPoint getRightEndpoint(long ts) { DataPoint dp = new DataPoint(); dp.setTimestamp(ts); dp.setValue(Long.MAX_VALUE); return dp; } public static DataPoint getLeftEndpoint(long ts) { DataPoint dp = new DataPoint(); dp.setTimestamp(ts); dp.setValue(Long.MIN_VALUE); return dp; } private static boolean mapContains(Map<String, String> tags, Map<String, String> filter) { if(filter != null) { for (Map.Entry<String, String> kv : filter.entrySet()) { Object o = tags.get(kv.getKey()); if (o == null || !o.equals(kv.getValue())) { return false; } } } return true; } @Override
public List<DataPoint> retrieve(String metric, DataPoint pt, TimeRange range, Map<String, String> filter, int maxPts) {
cestella/streaming_outliers
core/src/main/java/com/caseystella/analytics/distribution/Distribution.java
// Path: core/src/main/java/com/caseystella/analytics/DataPoint.java // public class DataPoint { // private long timestamp; // private double value; // private Map<String, String> metadata; // private String source; // // public DataPoint() { // // } // // public DataPoint(long timestamp, double value, Map<String, String> metadata, String source) { // this.timestamp = timestamp; // this.value = value; // this.metadata = metadata; // this.source = source; // } // // public String getSource() { // return source; // } // // public void setSource(String source) { // this.source = source; // } // // // // public long getTimestamp() { // return timestamp; // } // // public void setTimestamp(long timestamp) { // this.timestamp = timestamp; // } // // public double getValue() { // return value; // } // // public void setValue(double value) { // this.value = value; // } // // public Map<String, String> getMetadata() { // return metadata; // } // // public void setMetadata(Map<String, String> metadata) { // this.metadata = metadata; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // DataPoint dataPoint = (DataPoint) o; // // if (getTimestamp() != dataPoint.getTimestamp()) return false; // if (Double.compare(dataPoint.getValue(), getValue()) != 0) return false; // if (getMetadata() != null ? !getMetadata().equals(dataPoint.getMetadata()) : dataPoint.getMetadata() != null) // return false; // return source != null ? source.equals(dataPoint.source) : dataPoint.source == null; // // } // // @Override // public int hashCode() { // int result; // long temp; // result = (int) (getTimestamp() ^ (getTimestamp() >>> 32)); // temp = Double.doubleToLongBits(getValue()); // result = 31 * result + (int) (temp ^ (temp >>> 32)); // result = 31 * result + (getMetadata() != null ? getMetadata().hashCode() : 0); // result = 31 * result + (source != null ? source.hashCode() : 0); // return result; // } // @Override // public String toString() { // return "(" + // "timestamp=" + timestamp + // ", value=" + value + // ", metadata=" + metadata + // ", source=" + source+ // ')'; // } // // } // // Path: core/src/main/java/com/caseystella/analytics/distribution/config/RotationConfig.java // public class RotationConfig implements Serializable { // Type type; // Long amount; // Unit unit; // // public Type getType() { // return type; // } // // public void setType(Type type) { // this.type = type; // } // // public Long getAmount() { // return amount; // } // // public void setAmount(Long amount) { // this.amount = amount; // } // // public Unit getUnit() { // return unit; // } // // public void setUnit(Unit unit) { // this.unit = unit; // } // } // // Path: core/src/main/java/com/caseystella/analytics/distribution/config/Type.java // public enum Type { // BY_TIME, // BY_AMOUNT, // NEVER // } // // Path: core/src/main/java/com/caseystella/analytics/distribution/sampling/ExponentiallyBiasedAChao.java // public class ExponentiallyBiasedAChao<T> extends AChao<T> { // private final double bias; // // public ExponentiallyBiasedAChao(int capacity, double bias, Random random) { // super(capacity, random); // assert (bias >= 0 && bias < 1); // this.bias = bias; // } // // public ExponentiallyBiasedAChao(int capacity, double bias) { // super(capacity); // assert (bias >= 0 && bias < 1); // this.bias = bias; // } // // public void advancePeriod() { // advancePeriod(1); // } // // public void advancePeriod(int numPeriods) { // runningCount *= Math.pow(1 - bias, numPeriods); // } // // public void insert(T ele) { // insert(ele, 1); // } // } // // Path: core/src/main/java/com/caseystella/analytics/distribution/scaling/ScalingFunction.java // public interface ScalingFunction { // double scale(double val, GlobalStatistics stats); // }
import com.caseystella.analytics.DataPoint; import com.caseystella.analytics.distribution.config.RotationConfig; import com.caseystella.analytics.distribution.config.Type; import com.caseystella.analytics.distribution.sampling.ExponentiallyBiasedAChao; import com.caseystella.analytics.distribution.scaling.ScalingFunction; import com.google.common.base.Function; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.twitter.algebird.QTree; import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; import scala.Tuple2; import java.util.LinkedList; import java.util.List; import java.util.Random;
package com.caseystella.analytics.distribution; public class Distribution implements Measurable { public static class Context { private Distribution currentDistribution; private Distribution previousDistribution; private LinkedList<Distribution> chunks = new LinkedList<>();
// Path: core/src/main/java/com/caseystella/analytics/DataPoint.java // public class DataPoint { // private long timestamp; // private double value; // private Map<String, String> metadata; // private String source; // // public DataPoint() { // // } // // public DataPoint(long timestamp, double value, Map<String, String> metadata, String source) { // this.timestamp = timestamp; // this.value = value; // this.metadata = metadata; // this.source = source; // } // // public String getSource() { // return source; // } // // public void setSource(String source) { // this.source = source; // } // // // // public long getTimestamp() { // return timestamp; // } // // public void setTimestamp(long timestamp) { // this.timestamp = timestamp; // } // // public double getValue() { // return value; // } // // public void setValue(double value) { // this.value = value; // } // // public Map<String, String> getMetadata() { // return metadata; // } // // public void setMetadata(Map<String, String> metadata) { // this.metadata = metadata; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // DataPoint dataPoint = (DataPoint) o; // // if (getTimestamp() != dataPoint.getTimestamp()) return false; // if (Double.compare(dataPoint.getValue(), getValue()) != 0) return false; // if (getMetadata() != null ? !getMetadata().equals(dataPoint.getMetadata()) : dataPoint.getMetadata() != null) // return false; // return source != null ? source.equals(dataPoint.source) : dataPoint.source == null; // // } // // @Override // public int hashCode() { // int result; // long temp; // result = (int) (getTimestamp() ^ (getTimestamp() >>> 32)); // temp = Double.doubleToLongBits(getValue()); // result = 31 * result + (int) (temp ^ (temp >>> 32)); // result = 31 * result + (getMetadata() != null ? getMetadata().hashCode() : 0); // result = 31 * result + (source != null ? source.hashCode() : 0); // return result; // } // @Override // public String toString() { // return "(" + // "timestamp=" + timestamp + // ", value=" + value + // ", metadata=" + metadata + // ", source=" + source+ // ')'; // } // // } // // Path: core/src/main/java/com/caseystella/analytics/distribution/config/RotationConfig.java // public class RotationConfig implements Serializable { // Type type; // Long amount; // Unit unit; // // public Type getType() { // return type; // } // // public void setType(Type type) { // this.type = type; // } // // public Long getAmount() { // return amount; // } // // public void setAmount(Long amount) { // this.amount = amount; // } // // public Unit getUnit() { // return unit; // } // // public void setUnit(Unit unit) { // this.unit = unit; // } // } // // Path: core/src/main/java/com/caseystella/analytics/distribution/config/Type.java // public enum Type { // BY_TIME, // BY_AMOUNT, // NEVER // } // // Path: core/src/main/java/com/caseystella/analytics/distribution/sampling/ExponentiallyBiasedAChao.java // public class ExponentiallyBiasedAChao<T> extends AChao<T> { // private final double bias; // // public ExponentiallyBiasedAChao(int capacity, double bias, Random random) { // super(capacity, random); // assert (bias >= 0 && bias < 1); // this.bias = bias; // } // // public ExponentiallyBiasedAChao(int capacity, double bias) { // super(capacity); // assert (bias >= 0 && bias < 1); // this.bias = bias; // } // // public void advancePeriod() { // advancePeriod(1); // } // // public void advancePeriod(int numPeriods) { // runningCount *= Math.pow(1 - bias, numPeriods); // } // // public void insert(T ele) { // insert(ele, 1); // } // } // // Path: core/src/main/java/com/caseystella/analytics/distribution/scaling/ScalingFunction.java // public interface ScalingFunction { // double scale(double val, GlobalStatistics stats); // } // Path: core/src/main/java/com/caseystella/analytics/distribution/Distribution.java import com.caseystella.analytics.DataPoint; import com.caseystella.analytics.distribution.config.RotationConfig; import com.caseystella.analytics.distribution.config.Type; import com.caseystella.analytics.distribution.sampling.ExponentiallyBiasedAChao; import com.caseystella.analytics.distribution.scaling.ScalingFunction; import com.google.common.base.Function; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.twitter.algebird.QTree; import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; import scala.Tuple2; import java.util.LinkedList; import java.util.List; import java.util.Random; package com.caseystella.analytics.distribution; public class Distribution implements Measurable { public static class Context { private Distribution currentDistribution; private Distribution previousDistribution; private LinkedList<Distribution> chunks = new LinkedList<>();
private ExponentiallyBiasedAChao<Double> reservoir;
cestella/streaming_outliers
core/src/main/java/com/caseystella/analytics/distribution/Distribution.java
// Path: core/src/main/java/com/caseystella/analytics/DataPoint.java // public class DataPoint { // private long timestamp; // private double value; // private Map<String, String> metadata; // private String source; // // public DataPoint() { // // } // // public DataPoint(long timestamp, double value, Map<String, String> metadata, String source) { // this.timestamp = timestamp; // this.value = value; // this.metadata = metadata; // this.source = source; // } // // public String getSource() { // return source; // } // // public void setSource(String source) { // this.source = source; // } // // // // public long getTimestamp() { // return timestamp; // } // // public void setTimestamp(long timestamp) { // this.timestamp = timestamp; // } // // public double getValue() { // return value; // } // // public void setValue(double value) { // this.value = value; // } // // public Map<String, String> getMetadata() { // return metadata; // } // // public void setMetadata(Map<String, String> metadata) { // this.metadata = metadata; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // DataPoint dataPoint = (DataPoint) o; // // if (getTimestamp() != dataPoint.getTimestamp()) return false; // if (Double.compare(dataPoint.getValue(), getValue()) != 0) return false; // if (getMetadata() != null ? !getMetadata().equals(dataPoint.getMetadata()) : dataPoint.getMetadata() != null) // return false; // return source != null ? source.equals(dataPoint.source) : dataPoint.source == null; // // } // // @Override // public int hashCode() { // int result; // long temp; // result = (int) (getTimestamp() ^ (getTimestamp() >>> 32)); // temp = Double.doubleToLongBits(getValue()); // result = 31 * result + (int) (temp ^ (temp >>> 32)); // result = 31 * result + (getMetadata() != null ? getMetadata().hashCode() : 0); // result = 31 * result + (source != null ? source.hashCode() : 0); // return result; // } // @Override // public String toString() { // return "(" + // "timestamp=" + timestamp + // ", value=" + value + // ", metadata=" + metadata + // ", source=" + source+ // ')'; // } // // } // // Path: core/src/main/java/com/caseystella/analytics/distribution/config/RotationConfig.java // public class RotationConfig implements Serializable { // Type type; // Long amount; // Unit unit; // // public Type getType() { // return type; // } // // public void setType(Type type) { // this.type = type; // } // // public Long getAmount() { // return amount; // } // // public void setAmount(Long amount) { // this.amount = amount; // } // // public Unit getUnit() { // return unit; // } // // public void setUnit(Unit unit) { // this.unit = unit; // } // } // // Path: core/src/main/java/com/caseystella/analytics/distribution/config/Type.java // public enum Type { // BY_TIME, // BY_AMOUNT, // NEVER // } // // Path: core/src/main/java/com/caseystella/analytics/distribution/sampling/ExponentiallyBiasedAChao.java // public class ExponentiallyBiasedAChao<T> extends AChao<T> { // private final double bias; // // public ExponentiallyBiasedAChao(int capacity, double bias, Random random) { // super(capacity, random); // assert (bias >= 0 && bias < 1); // this.bias = bias; // } // // public ExponentiallyBiasedAChao(int capacity, double bias) { // super(capacity); // assert (bias >= 0 && bias < 1); // this.bias = bias; // } // // public void advancePeriod() { // advancePeriod(1); // } // // public void advancePeriod(int numPeriods) { // runningCount *= Math.pow(1 - bias, numPeriods); // } // // public void insert(T ele) { // insert(ele, 1); // } // } // // Path: core/src/main/java/com/caseystella/analytics/distribution/scaling/ScalingFunction.java // public interface ScalingFunction { // double scale(double val, GlobalStatistics stats); // }
import com.caseystella.analytics.DataPoint; import com.caseystella.analytics.distribution.config.RotationConfig; import com.caseystella.analytics.distribution.config.Type; import com.caseystella.analytics.distribution.sampling.ExponentiallyBiasedAChao; import com.caseystella.analytics.distribution.scaling.ScalingFunction; import com.google.common.base.Function; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.twitter.algebird.QTree; import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; import scala.Tuple2; import java.util.LinkedList; import java.util.List; import java.util.Random;
private Distribution currentDistribution; private Distribution previousDistribution; private LinkedList<Distribution> chunks = new LinkedList<>(); private ExponentiallyBiasedAChao<Double> reservoir; public Context(int reservoirSize, double decayRate) { if(reservoirSize > 0) { reservoir = new ExponentiallyBiasedAChao<>(reservoirSize, decayRate, new Random(0)); } else { reservoir = null; } } public Distribution getPreviousDistribution() { return previousDistribution; } public Distribution getCurrentDistribution() { return currentDistribution; } public LinkedList<Distribution> getChunks() { return chunks; } public ExponentiallyBiasedAChao<Double> getSample() { return reservoir; } public long getAmount() { return currentDistribution == null?0L:currentDistribution.getAmount(); } public void addDataPoint( DataPoint dp
// Path: core/src/main/java/com/caseystella/analytics/DataPoint.java // public class DataPoint { // private long timestamp; // private double value; // private Map<String, String> metadata; // private String source; // // public DataPoint() { // // } // // public DataPoint(long timestamp, double value, Map<String, String> metadata, String source) { // this.timestamp = timestamp; // this.value = value; // this.metadata = metadata; // this.source = source; // } // // public String getSource() { // return source; // } // // public void setSource(String source) { // this.source = source; // } // // // // public long getTimestamp() { // return timestamp; // } // // public void setTimestamp(long timestamp) { // this.timestamp = timestamp; // } // // public double getValue() { // return value; // } // // public void setValue(double value) { // this.value = value; // } // // public Map<String, String> getMetadata() { // return metadata; // } // // public void setMetadata(Map<String, String> metadata) { // this.metadata = metadata; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // DataPoint dataPoint = (DataPoint) o; // // if (getTimestamp() != dataPoint.getTimestamp()) return false; // if (Double.compare(dataPoint.getValue(), getValue()) != 0) return false; // if (getMetadata() != null ? !getMetadata().equals(dataPoint.getMetadata()) : dataPoint.getMetadata() != null) // return false; // return source != null ? source.equals(dataPoint.source) : dataPoint.source == null; // // } // // @Override // public int hashCode() { // int result; // long temp; // result = (int) (getTimestamp() ^ (getTimestamp() >>> 32)); // temp = Double.doubleToLongBits(getValue()); // result = 31 * result + (int) (temp ^ (temp >>> 32)); // result = 31 * result + (getMetadata() != null ? getMetadata().hashCode() : 0); // result = 31 * result + (source != null ? source.hashCode() : 0); // return result; // } // @Override // public String toString() { // return "(" + // "timestamp=" + timestamp + // ", value=" + value + // ", metadata=" + metadata + // ", source=" + source+ // ')'; // } // // } // // Path: core/src/main/java/com/caseystella/analytics/distribution/config/RotationConfig.java // public class RotationConfig implements Serializable { // Type type; // Long amount; // Unit unit; // // public Type getType() { // return type; // } // // public void setType(Type type) { // this.type = type; // } // // public Long getAmount() { // return amount; // } // // public void setAmount(Long amount) { // this.amount = amount; // } // // public Unit getUnit() { // return unit; // } // // public void setUnit(Unit unit) { // this.unit = unit; // } // } // // Path: core/src/main/java/com/caseystella/analytics/distribution/config/Type.java // public enum Type { // BY_TIME, // BY_AMOUNT, // NEVER // } // // Path: core/src/main/java/com/caseystella/analytics/distribution/sampling/ExponentiallyBiasedAChao.java // public class ExponentiallyBiasedAChao<T> extends AChao<T> { // private final double bias; // // public ExponentiallyBiasedAChao(int capacity, double bias, Random random) { // super(capacity, random); // assert (bias >= 0 && bias < 1); // this.bias = bias; // } // // public ExponentiallyBiasedAChao(int capacity, double bias) { // super(capacity); // assert (bias >= 0 && bias < 1); // this.bias = bias; // } // // public void advancePeriod() { // advancePeriod(1); // } // // public void advancePeriod(int numPeriods) { // runningCount *= Math.pow(1 - bias, numPeriods); // } // // public void insert(T ele) { // insert(ele, 1); // } // } // // Path: core/src/main/java/com/caseystella/analytics/distribution/scaling/ScalingFunction.java // public interface ScalingFunction { // double scale(double val, GlobalStatistics stats); // } // Path: core/src/main/java/com/caseystella/analytics/distribution/Distribution.java import com.caseystella.analytics.DataPoint; import com.caseystella.analytics.distribution.config.RotationConfig; import com.caseystella.analytics.distribution.config.Type; import com.caseystella.analytics.distribution.sampling.ExponentiallyBiasedAChao; import com.caseystella.analytics.distribution.scaling.ScalingFunction; import com.google.common.base.Function; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.twitter.algebird.QTree; import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; import scala.Tuple2; import java.util.LinkedList; import java.util.List; import java.util.Random; private Distribution currentDistribution; private Distribution previousDistribution; private LinkedList<Distribution> chunks = new LinkedList<>(); private ExponentiallyBiasedAChao<Double> reservoir; public Context(int reservoirSize, double decayRate) { if(reservoirSize > 0) { reservoir = new ExponentiallyBiasedAChao<>(reservoirSize, decayRate, new Random(0)); } else { reservoir = null; } } public Distribution getPreviousDistribution() { return previousDistribution; } public Distribution getCurrentDistribution() { return currentDistribution; } public LinkedList<Distribution> getChunks() { return chunks; } public ExponentiallyBiasedAChao<Double> getSample() { return reservoir; } public long getAmount() { return currentDistribution == null?0L:currentDistribution.getAmount(); } public void addDataPoint( DataPoint dp
, RotationConfig rotationPolicy
cestella/streaming_outliers
core/src/main/java/com/caseystella/analytics/distribution/Distribution.java
// Path: core/src/main/java/com/caseystella/analytics/DataPoint.java // public class DataPoint { // private long timestamp; // private double value; // private Map<String, String> metadata; // private String source; // // public DataPoint() { // // } // // public DataPoint(long timestamp, double value, Map<String, String> metadata, String source) { // this.timestamp = timestamp; // this.value = value; // this.metadata = metadata; // this.source = source; // } // // public String getSource() { // return source; // } // // public void setSource(String source) { // this.source = source; // } // // // // public long getTimestamp() { // return timestamp; // } // // public void setTimestamp(long timestamp) { // this.timestamp = timestamp; // } // // public double getValue() { // return value; // } // // public void setValue(double value) { // this.value = value; // } // // public Map<String, String> getMetadata() { // return metadata; // } // // public void setMetadata(Map<String, String> metadata) { // this.metadata = metadata; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // DataPoint dataPoint = (DataPoint) o; // // if (getTimestamp() != dataPoint.getTimestamp()) return false; // if (Double.compare(dataPoint.getValue(), getValue()) != 0) return false; // if (getMetadata() != null ? !getMetadata().equals(dataPoint.getMetadata()) : dataPoint.getMetadata() != null) // return false; // return source != null ? source.equals(dataPoint.source) : dataPoint.source == null; // // } // // @Override // public int hashCode() { // int result; // long temp; // result = (int) (getTimestamp() ^ (getTimestamp() >>> 32)); // temp = Double.doubleToLongBits(getValue()); // result = 31 * result + (int) (temp ^ (temp >>> 32)); // result = 31 * result + (getMetadata() != null ? getMetadata().hashCode() : 0); // result = 31 * result + (source != null ? source.hashCode() : 0); // return result; // } // @Override // public String toString() { // return "(" + // "timestamp=" + timestamp + // ", value=" + value + // ", metadata=" + metadata + // ", source=" + source+ // ')'; // } // // } // // Path: core/src/main/java/com/caseystella/analytics/distribution/config/RotationConfig.java // public class RotationConfig implements Serializable { // Type type; // Long amount; // Unit unit; // // public Type getType() { // return type; // } // // public void setType(Type type) { // this.type = type; // } // // public Long getAmount() { // return amount; // } // // public void setAmount(Long amount) { // this.amount = amount; // } // // public Unit getUnit() { // return unit; // } // // public void setUnit(Unit unit) { // this.unit = unit; // } // } // // Path: core/src/main/java/com/caseystella/analytics/distribution/config/Type.java // public enum Type { // BY_TIME, // BY_AMOUNT, // NEVER // } // // Path: core/src/main/java/com/caseystella/analytics/distribution/sampling/ExponentiallyBiasedAChao.java // public class ExponentiallyBiasedAChao<T> extends AChao<T> { // private final double bias; // // public ExponentiallyBiasedAChao(int capacity, double bias, Random random) { // super(capacity, random); // assert (bias >= 0 && bias < 1); // this.bias = bias; // } // // public ExponentiallyBiasedAChao(int capacity, double bias) { // super(capacity); // assert (bias >= 0 && bias < 1); // this.bias = bias; // } // // public void advancePeriod() { // advancePeriod(1); // } // // public void advancePeriod(int numPeriods) { // runningCount *= Math.pow(1 - bias, numPeriods); // } // // public void insert(T ele) { // insert(ele, 1); // } // } // // Path: core/src/main/java/com/caseystella/analytics/distribution/scaling/ScalingFunction.java // public interface ScalingFunction { // double scale(double val, GlobalStatistics stats); // }
import com.caseystella.analytics.DataPoint; import com.caseystella.analytics.distribution.config.RotationConfig; import com.caseystella.analytics.distribution.config.Type; import com.caseystella.analytics.distribution.sampling.ExponentiallyBiasedAChao; import com.caseystella.analytics.distribution.scaling.ScalingFunction; import com.google.common.base.Function; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.twitter.algebird.QTree; import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; import scala.Tuple2; import java.util.LinkedList; import java.util.List; import java.util.Random;
long begin = Long.MAX_VALUE; long end = -1; long amount = 0; for(Distribution d : chunks) { begin = Math.min(begin, d.getBegin()); end = Math.max(end, d.getEnd()); amount += d.getAmount(); } final long measurableBegin = begin; final long measurableEnd= end; final long measurableAmount = amount; return new Measurable() { @Override public long getAmount() { return measurableAmount; } @Override public Long getBegin() { return measurableBegin; } @Override public Long getEnd() { return measurableEnd; } }; } private boolean outOfPolicy(Measurable dist, RotationConfig policy) {
// Path: core/src/main/java/com/caseystella/analytics/DataPoint.java // public class DataPoint { // private long timestamp; // private double value; // private Map<String, String> metadata; // private String source; // // public DataPoint() { // // } // // public DataPoint(long timestamp, double value, Map<String, String> metadata, String source) { // this.timestamp = timestamp; // this.value = value; // this.metadata = metadata; // this.source = source; // } // // public String getSource() { // return source; // } // // public void setSource(String source) { // this.source = source; // } // // // // public long getTimestamp() { // return timestamp; // } // // public void setTimestamp(long timestamp) { // this.timestamp = timestamp; // } // // public double getValue() { // return value; // } // // public void setValue(double value) { // this.value = value; // } // // public Map<String, String> getMetadata() { // return metadata; // } // // public void setMetadata(Map<String, String> metadata) { // this.metadata = metadata; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // DataPoint dataPoint = (DataPoint) o; // // if (getTimestamp() != dataPoint.getTimestamp()) return false; // if (Double.compare(dataPoint.getValue(), getValue()) != 0) return false; // if (getMetadata() != null ? !getMetadata().equals(dataPoint.getMetadata()) : dataPoint.getMetadata() != null) // return false; // return source != null ? source.equals(dataPoint.source) : dataPoint.source == null; // // } // // @Override // public int hashCode() { // int result; // long temp; // result = (int) (getTimestamp() ^ (getTimestamp() >>> 32)); // temp = Double.doubleToLongBits(getValue()); // result = 31 * result + (int) (temp ^ (temp >>> 32)); // result = 31 * result + (getMetadata() != null ? getMetadata().hashCode() : 0); // result = 31 * result + (source != null ? source.hashCode() : 0); // return result; // } // @Override // public String toString() { // return "(" + // "timestamp=" + timestamp + // ", value=" + value + // ", metadata=" + metadata + // ", source=" + source+ // ')'; // } // // } // // Path: core/src/main/java/com/caseystella/analytics/distribution/config/RotationConfig.java // public class RotationConfig implements Serializable { // Type type; // Long amount; // Unit unit; // // public Type getType() { // return type; // } // // public void setType(Type type) { // this.type = type; // } // // public Long getAmount() { // return amount; // } // // public void setAmount(Long amount) { // this.amount = amount; // } // // public Unit getUnit() { // return unit; // } // // public void setUnit(Unit unit) { // this.unit = unit; // } // } // // Path: core/src/main/java/com/caseystella/analytics/distribution/config/Type.java // public enum Type { // BY_TIME, // BY_AMOUNT, // NEVER // } // // Path: core/src/main/java/com/caseystella/analytics/distribution/sampling/ExponentiallyBiasedAChao.java // public class ExponentiallyBiasedAChao<T> extends AChao<T> { // private final double bias; // // public ExponentiallyBiasedAChao(int capacity, double bias, Random random) { // super(capacity, random); // assert (bias >= 0 && bias < 1); // this.bias = bias; // } // // public ExponentiallyBiasedAChao(int capacity, double bias) { // super(capacity); // assert (bias >= 0 && bias < 1); // this.bias = bias; // } // // public void advancePeriod() { // advancePeriod(1); // } // // public void advancePeriod(int numPeriods) { // runningCount *= Math.pow(1 - bias, numPeriods); // } // // public void insert(T ele) { // insert(ele, 1); // } // } // // Path: core/src/main/java/com/caseystella/analytics/distribution/scaling/ScalingFunction.java // public interface ScalingFunction { // double scale(double val, GlobalStatistics stats); // } // Path: core/src/main/java/com/caseystella/analytics/distribution/Distribution.java import com.caseystella.analytics.DataPoint; import com.caseystella.analytics.distribution.config.RotationConfig; import com.caseystella.analytics.distribution.config.Type; import com.caseystella.analytics.distribution.sampling.ExponentiallyBiasedAChao; import com.caseystella.analytics.distribution.scaling.ScalingFunction; import com.google.common.base.Function; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.twitter.algebird.QTree; import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; import scala.Tuple2; import java.util.LinkedList; import java.util.List; import java.util.Random; long begin = Long.MAX_VALUE; long end = -1; long amount = 0; for(Distribution d : chunks) { begin = Math.min(begin, d.getBegin()); end = Math.max(end, d.getEnd()); amount += d.getAmount(); } final long measurableBegin = begin; final long measurableEnd= end; final long measurableAmount = amount; return new Measurable() { @Override public long getAmount() { return measurableAmount; } @Override public Long getBegin() { return measurableBegin; } @Override public Long getEnd() { return measurableEnd; } }; } private boolean outOfPolicy(Measurable dist, RotationConfig policy) {
if(policy.getType() == Type.BY_AMOUNT) {
cestella/streaming_outliers
core/src/main/java/com/caseystella/analytics/distribution/config/RotationConfig.java
// Path: core/src/main/java/com/caseystella/analytics/distribution/config/Type.java // public enum Type { // BY_TIME, // BY_AMOUNT, // NEVER // } // // Path: core/src/main/java/com/caseystella/analytics/distribution/config/Unit.java // public enum Unit implements Function<TimeRange, Long> { // // MILLISECONDS(new SimpleConversion(1L)), // SECONDS(new SimpleConversion(SimpleConversion.MS_IN_SECOND)), // HOURS(new SimpleConversion(SimpleConversion.MS_IN_HOUR)), // DAYS(new SimpleConversion(SimpleConversion.MS_IN_DAY)), // MONTHS(new Function<TimeRange, Long>() { // @Nullable // @Override // public Long apply(@Nullable TimeRange timeRange) { // DateTime end = new DateTime(timeRange.getEnd()); // DateTime begin = new DateTime(timeRange.getBegin()); // Months months = Months.monthsBetween(begin, end); // return (long)months.getMonths(); // } // }), // YEARS(new Function<TimeRange, Long>() { // // @Nullable // @Override // public Long apply(@Nullable TimeRange timeRange) { // DateTime end = new DateTime(timeRange.getEnd()); // DateTime begin = new DateTime(timeRange.getBegin()); // Years years = Years.yearsBetween(begin, end); // return (long)years.getYears(); // } // }), // POINTS(new Function<TimeRange, Long>() { // @Nullable // @Override // public Long apply(@Nullable TimeRange timeRange) { // return null; // } // }); // // // public static class SimpleConversion implements Function<TimeRange, Long> // { // public static final long MS_IN_SECOND = 1000; // public static final long MS_IN_MINUTE = 60*MS_IN_SECOND; // public static final long MS_IN_HOUR = 60*MS_IN_MINUTE; // public static final long MS_IN_DAY = 24*MS_IN_HOUR; // long conversion; // public SimpleConversion(long conversion) { // this.conversion = conversion; // } // // @Nullable // @Override // public Long apply(@Nullable TimeRange timeRange) { // return (timeRange.getEnd()- timeRange.getBegin())/conversion; // } // } // // private Function<TimeRange, Long> _func; // // Unit(Function<TimeRange, Long> _func) // { // this._func = _func; // } // // public Long apply(TimeRange in) { // return _func.apply(in); // } // }
import com.caseystella.analytics.distribution.config.Type; import com.caseystella.analytics.distribution.config.Unit; import java.io.Serializable;
package com.caseystella.analytics.distribution.config; public class RotationConfig implements Serializable { Type type; Long amount;
// Path: core/src/main/java/com/caseystella/analytics/distribution/config/Type.java // public enum Type { // BY_TIME, // BY_AMOUNT, // NEVER // } // // Path: core/src/main/java/com/caseystella/analytics/distribution/config/Unit.java // public enum Unit implements Function<TimeRange, Long> { // // MILLISECONDS(new SimpleConversion(1L)), // SECONDS(new SimpleConversion(SimpleConversion.MS_IN_SECOND)), // HOURS(new SimpleConversion(SimpleConversion.MS_IN_HOUR)), // DAYS(new SimpleConversion(SimpleConversion.MS_IN_DAY)), // MONTHS(new Function<TimeRange, Long>() { // @Nullable // @Override // public Long apply(@Nullable TimeRange timeRange) { // DateTime end = new DateTime(timeRange.getEnd()); // DateTime begin = new DateTime(timeRange.getBegin()); // Months months = Months.monthsBetween(begin, end); // return (long)months.getMonths(); // } // }), // YEARS(new Function<TimeRange, Long>() { // // @Nullable // @Override // public Long apply(@Nullable TimeRange timeRange) { // DateTime end = new DateTime(timeRange.getEnd()); // DateTime begin = new DateTime(timeRange.getBegin()); // Years years = Years.yearsBetween(begin, end); // return (long)years.getYears(); // } // }), // POINTS(new Function<TimeRange, Long>() { // @Nullable // @Override // public Long apply(@Nullable TimeRange timeRange) { // return null; // } // }); // // // public static class SimpleConversion implements Function<TimeRange, Long> // { // public static final long MS_IN_SECOND = 1000; // public static final long MS_IN_MINUTE = 60*MS_IN_SECOND; // public static final long MS_IN_HOUR = 60*MS_IN_MINUTE; // public static final long MS_IN_DAY = 24*MS_IN_HOUR; // long conversion; // public SimpleConversion(long conversion) { // this.conversion = conversion; // } // // @Nullable // @Override // public Long apply(@Nullable TimeRange timeRange) { // return (timeRange.getEnd()- timeRange.getBegin())/conversion; // } // } // // private Function<TimeRange, Long> _func; // // Unit(Function<TimeRange, Long> _func) // { // this._func = _func; // } // // public Long apply(TimeRange in) { // return _func.apply(in); // } // } // Path: core/src/main/java/com/caseystella/analytics/distribution/config/RotationConfig.java import com.caseystella.analytics.distribution.config.Type; import com.caseystella.analytics.distribution.config.Unit; import java.io.Serializable; package com.caseystella.analytics.distribution.config; public class RotationConfig implements Serializable { Type type; Long amount;
Unit unit;
cestella/streaming_outliers
integration_test/src/main/java/com/caseystella/analytics/integration/components/TSDBComponent.java
// Path: integration_test/src/main/java/com/caseystella/analytics/integration/UnableToStartException.java // public class UnableToStartException extends Exception { // public UnableToStartException(String message) { // super(message); // } // public UnableToStartException(String message, Throwable t) { // super(message, t); // } // }
import com.caseystella.analytics.integration.UnableToStartException; import net.opentsdb.core.TSDB; import net.opentsdb.uid.UniqueId; import net.opentsdb.utils.Config; import org.apache.hadoop.hbase.HConstants; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.util.Bytes; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map;
package com.caseystella.analytics.integration.components; public class TSDBComponent extends HBaseComponent { private TSDB tsdb; private List<String> metrics = new ArrayList<>(); public TSDB getTSDB() { return tsdb; } public TSDBComponent withMetrics(String... metrics) { for(String metric : metrics) { this.metrics.add(metric); } return this; } static class TSDBConfig extends Config { public TSDBConfig(Map<String, String> props) throws IOException { this(props.entrySet()); } public TSDBConfig(Iterable<Map.Entry<String, String>> props) throws IOException { super(false); for(Map.Entry<String, String> prop : props) { properties.put(prop.getKey(), prop.getValue()); } } } @Override
// Path: integration_test/src/main/java/com/caseystella/analytics/integration/UnableToStartException.java // public class UnableToStartException extends Exception { // public UnableToStartException(String message) { // super(message); // } // public UnableToStartException(String message, Throwable t) { // super(message, t); // } // } // Path: integration_test/src/main/java/com/caseystella/analytics/integration/components/TSDBComponent.java import com.caseystella.analytics.integration.UnableToStartException; import net.opentsdb.core.TSDB; import net.opentsdb.uid.UniqueId; import net.opentsdb.utils.Config; import org.apache.hadoop.hbase.HConstants; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.util.Bytes; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; package com.caseystella.analytics.integration.components; public class TSDBComponent extends HBaseComponent { private TSDB tsdb; private List<String> metrics = new ArrayList<>(); public TSDB getTSDB() { return tsdb; } public TSDBComponent withMetrics(String... metrics) { for(String metric : metrics) { this.metrics.add(metric); } return this; } static class TSDBConfig extends Config { public TSDBConfig(Map<String, String> props) throws IOException { this(props.entrySet()); } public TSDBConfig(Iterable<Map.Entry<String, String>> props) throws IOException { super(false); for(Map.Entry<String, String> prop : props) { properties.put(prop.getKey(), prop.getValue()); } } } @Override
public void start() throws UnableToStartException {
cestella/streaming_outliers
core/src/main/java/com/caseystella/analytics/outlier/streaming/OutlierConfig.java
// Path: core/src/main/java/com/caseystella/analytics/distribution/GlobalStatistics.java // public class GlobalStatistics implements Serializable { // Double mean; // Double min; // Double max; // Double stddev; // // public Double getMean() { // return mean; // } // // public void setMean(double mean) { // this.mean = mean; // } // // public Double getMin() { // return min; // } // // public void setMin(double min) { // this.min = min; // } // // public Double getMax() { // return max; // } // // public void setMax(double max) { // this.max = max; // } // // public Double getStddev() { // return stddev; // } // // public void setStddev(double stddev) { // this.stddev = stddev; // } // } // // Path: core/src/main/java/com/caseystella/analytics/distribution/config/RotationConfig.java // public class RotationConfig implements Serializable { // Type type; // Long amount; // Unit unit; // // public Type getType() { // return type; // } // // public void setType(Type type) { // this.type = type; // } // // public Long getAmount() { // return amount; // } // // public void setAmount(Long amount) { // this.amount = amount; // } // // public Unit getUnit() { // return unit; // } // // public void setUnit(Unit unit) { // this.unit = unit; // } // } // // Path: core/src/main/java/com/caseystella/analytics/distribution/scaling/ScalingFunctions.java // public enum ScalingFunctions implements ScalingFunction { // NONE(new ScalingFunction() { // // @Override // public double scale(double val, GlobalStatistics stats) { // return val; // } // }) // ,SHIFT_TO_POSITIVE(new DefaultScalingFunctions.ShiftToPositive()) // // ,SQUEEZE_TO_UNIT( new DefaultScalingFunctions.SqueezeToUnit()) // // ,FIXED_MEAN_UNIT_VARIANCE(new DefaultScalingFunctions.FixedMeanUnitVariance()) // ,ZERO_MEAN_UNIT_VARIANCE(new DefaultScalingFunctions.ZeroMeanUnitVariance()) // ; // private ScalingFunction _func; // ScalingFunctions(ScalingFunction func) { // _func = func; // } // // @Override // public double scale(double val, GlobalStatistics globalStatistics) { // return _func.scale(val, globalStatistics); // } // }
import com.caseystella.analytics.distribution.GlobalStatistics; import com.caseystella.analytics.distribution.config.RotationConfig; import com.caseystella.analytics.distribution.scaling.ScalingFunctions; import com.google.common.collect.ImmutableList; import java.io.Serializable; import java.util.HashMap; import java.util.List; import java.util.Map;
package com.caseystella.analytics.outlier.streaming; public class OutlierConfig implements Serializable { private RotationConfig rotationPolicy; private RotationConfig chunkingPolicy;
// Path: core/src/main/java/com/caseystella/analytics/distribution/GlobalStatistics.java // public class GlobalStatistics implements Serializable { // Double mean; // Double min; // Double max; // Double stddev; // // public Double getMean() { // return mean; // } // // public void setMean(double mean) { // this.mean = mean; // } // // public Double getMin() { // return min; // } // // public void setMin(double min) { // this.min = min; // } // // public Double getMax() { // return max; // } // // public void setMax(double max) { // this.max = max; // } // // public Double getStddev() { // return stddev; // } // // public void setStddev(double stddev) { // this.stddev = stddev; // } // } // // Path: core/src/main/java/com/caseystella/analytics/distribution/config/RotationConfig.java // public class RotationConfig implements Serializable { // Type type; // Long amount; // Unit unit; // // public Type getType() { // return type; // } // // public void setType(Type type) { // this.type = type; // } // // public Long getAmount() { // return amount; // } // // public void setAmount(Long amount) { // this.amount = amount; // } // // public Unit getUnit() { // return unit; // } // // public void setUnit(Unit unit) { // this.unit = unit; // } // } // // Path: core/src/main/java/com/caseystella/analytics/distribution/scaling/ScalingFunctions.java // public enum ScalingFunctions implements ScalingFunction { // NONE(new ScalingFunction() { // // @Override // public double scale(double val, GlobalStatistics stats) { // return val; // } // }) // ,SHIFT_TO_POSITIVE(new DefaultScalingFunctions.ShiftToPositive()) // // ,SQUEEZE_TO_UNIT( new DefaultScalingFunctions.SqueezeToUnit()) // // ,FIXED_MEAN_UNIT_VARIANCE(new DefaultScalingFunctions.FixedMeanUnitVariance()) // ,ZERO_MEAN_UNIT_VARIANCE(new DefaultScalingFunctions.ZeroMeanUnitVariance()) // ; // private ScalingFunction _func; // ScalingFunctions(ScalingFunction func) { // _func = func; // } // // @Override // public double scale(double val, GlobalStatistics globalStatistics) { // return _func.scale(val, globalStatistics); // } // } // Path: core/src/main/java/com/caseystella/analytics/outlier/streaming/OutlierConfig.java import com.caseystella.analytics.distribution.GlobalStatistics; import com.caseystella.analytics.distribution.config.RotationConfig; import com.caseystella.analytics.distribution.scaling.ScalingFunctions; import com.google.common.collect.ImmutableList; import java.io.Serializable; import java.util.HashMap; import java.util.List; import java.util.Map; package com.caseystella.analytics.outlier.streaming; public class OutlierConfig implements Serializable { private RotationConfig rotationPolicy; private RotationConfig chunkingPolicy;
private GlobalStatistics globalStatistics;
cestella/streaming_outliers
core/src/main/java/com/caseystella/analytics/outlier/streaming/OutlierConfig.java
// Path: core/src/main/java/com/caseystella/analytics/distribution/GlobalStatistics.java // public class GlobalStatistics implements Serializable { // Double mean; // Double min; // Double max; // Double stddev; // // public Double getMean() { // return mean; // } // // public void setMean(double mean) { // this.mean = mean; // } // // public Double getMin() { // return min; // } // // public void setMin(double min) { // this.min = min; // } // // public Double getMax() { // return max; // } // // public void setMax(double max) { // this.max = max; // } // // public Double getStddev() { // return stddev; // } // // public void setStddev(double stddev) { // this.stddev = stddev; // } // } // // Path: core/src/main/java/com/caseystella/analytics/distribution/config/RotationConfig.java // public class RotationConfig implements Serializable { // Type type; // Long amount; // Unit unit; // // public Type getType() { // return type; // } // // public void setType(Type type) { // this.type = type; // } // // public Long getAmount() { // return amount; // } // // public void setAmount(Long amount) { // this.amount = amount; // } // // public Unit getUnit() { // return unit; // } // // public void setUnit(Unit unit) { // this.unit = unit; // } // } // // Path: core/src/main/java/com/caseystella/analytics/distribution/scaling/ScalingFunctions.java // public enum ScalingFunctions implements ScalingFunction { // NONE(new ScalingFunction() { // // @Override // public double scale(double val, GlobalStatistics stats) { // return val; // } // }) // ,SHIFT_TO_POSITIVE(new DefaultScalingFunctions.ShiftToPositive()) // // ,SQUEEZE_TO_UNIT( new DefaultScalingFunctions.SqueezeToUnit()) // // ,FIXED_MEAN_UNIT_VARIANCE(new DefaultScalingFunctions.FixedMeanUnitVariance()) // ,ZERO_MEAN_UNIT_VARIANCE(new DefaultScalingFunctions.ZeroMeanUnitVariance()) // ; // private ScalingFunction _func; // ScalingFunctions(ScalingFunction func) { // _func = func; // } // // @Override // public double scale(double val, GlobalStatistics globalStatistics) { // return _func.scale(val, globalStatistics); // } // }
import com.caseystella.analytics.distribution.GlobalStatistics; import com.caseystella.analytics.distribution.config.RotationConfig; import com.caseystella.analytics.distribution.scaling.ScalingFunctions; import com.google.common.collect.ImmutableList; import java.io.Serializable; import java.util.HashMap; import java.util.List; import java.util.Map;
package com.caseystella.analytics.outlier.streaming; public class OutlierConfig implements Serializable { private RotationConfig rotationPolicy; private RotationConfig chunkingPolicy; private GlobalStatistics globalStatistics; private OutlierAlgorithm sketchyOutlierAlgorithm; private com.caseystella.analytics.outlier.batch.OutlierAlgorithm batchOutlierAlgorithm;
// Path: core/src/main/java/com/caseystella/analytics/distribution/GlobalStatistics.java // public class GlobalStatistics implements Serializable { // Double mean; // Double min; // Double max; // Double stddev; // // public Double getMean() { // return mean; // } // // public void setMean(double mean) { // this.mean = mean; // } // // public Double getMin() { // return min; // } // // public void setMin(double min) { // this.min = min; // } // // public Double getMax() { // return max; // } // // public void setMax(double max) { // this.max = max; // } // // public Double getStddev() { // return stddev; // } // // public void setStddev(double stddev) { // this.stddev = stddev; // } // } // // Path: core/src/main/java/com/caseystella/analytics/distribution/config/RotationConfig.java // public class RotationConfig implements Serializable { // Type type; // Long amount; // Unit unit; // // public Type getType() { // return type; // } // // public void setType(Type type) { // this.type = type; // } // // public Long getAmount() { // return amount; // } // // public void setAmount(Long amount) { // this.amount = amount; // } // // public Unit getUnit() { // return unit; // } // // public void setUnit(Unit unit) { // this.unit = unit; // } // } // // Path: core/src/main/java/com/caseystella/analytics/distribution/scaling/ScalingFunctions.java // public enum ScalingFunctions implements ScalingFunction { // NONE(new ScalingFunction() { // // @Override // public double scale(double val, GlobalStatistics stats) { // return val; // } // }) // ,SHIFT_TO_POSITIVE(new DefaultScalingFunctions.ShiftToPositive()) // // ,SQUEEZE_TO_UNIT( new DefaultScalingFunctions.SqueezeToUnit()) // // ,FIXED_MEAN_UNIT_VARIANCE(new DefaultScalingFunctions.FixedMeanUnitVariance()) // ,ZERO_MEAN_UNIT_VARIANCE(new DefaultScalingFunctions.ZeroMeanUnitVariance()) // ; // private ScalingFunction _func; // ScalingFunctions(ScalingFunction func) { // _func = func; // } // // @Override // public double scale(double val, GlobalStatistics globalStatistics) { // return _func.scale(val, globalStatistics); // } // } // Path: core/src/main/java/com/caseystella/analytics/outlier/streaming/OutlierConfig.java import com.caseystella.analytics.distribution.GlobalStatistics; import com.caseystella.analytics.distribution.config.RotationConfig; import com.caseystella.analytics.distribution.scaling.ScalingFunctions; import com.google.common.collect.ImmutableList; import java.io.Serializable; import java.util.HashMap; import java.util.List; import java.util.Map; package com.caseystella.analytics.outlier.streaming; public class OutlierConfig implements Serializable { private RotationConfig rotationPolicy; private RotationConfig chunkingPolicy; private GlobalStatistics globalStatistics; private OutlierAlgorithm sketchyOutlierAlgorithm; private com.caseystella.analytics.outlier.batch.OutlierAlgorithm batchOutlierAlgorithm;
private ScalingFunctions scalingFunction = null;
cestella/streaming_outliers
integration_test/src/main/java/com/caseystella/analytics/integration/components/StormTopologyComponent.java
// Path: integration_test/src/main/java/com/caseystella/analytics/integration/InMemoryComponent.java // public interface InMemoryComponent { // public void start() throws UnableToStartException; // public void stop(); // } // // Path: integration_test/src/main/java/com/caseystella/analytics/integration/UnableToStartException.java // public class UnableToStartException extends Exception { // public UnableToStartException(String message) { // super(message); // } // public UnableToStartException(String message, Throwable t) { // super(message, t); // } // }
import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.util.Properties; import backtype.storm.Config; import backtype.storm.LocalCluster; import backtype.storm.generated.StormTopology; import backtype.storm.topology.TopologyBuilder; import backtype.storm.utils.Utils; import com.caseystella.analytics.integration.InMemoryComponent; import com.caseystella.analytics.integration.UnableToStartException; import org.apache.storm.flux.FluxBuilder; import org.apache.storm.flux.model.ExecutionContext; import org.apache.storm.flux.model.TopologyDef; import org.apache.storm.flux.parser.FluxParser; import org.apache.thrift7.TException; import org.junit.Assert;
this.topologyBuilder = builder; this.topologyName = topologyName; this.stormConfig = config; } StormTopologyComponent(String topologyName, File topologyLocation, Properties topologyProperties) { this.topologyName = topologyName; this.topologyLocation = topologyLocation; this.topologyProperties = topologyProperties; } public LocalCluster getStormCluster() { return stormCluster; } public String getTopologyName() { return topologyName; } public File getTopologyLocation() { return topologyLocation; } public Properties getTopologyProperties() { return topologyProperties; } public Config getStormConfig() { return stormConfig; }
// Path: integration_test/src/main/java/com/caseystella/analytics/integration/InMemoryComponent.java // public interface InMemoryComponent { // public void start() throws UnableToStartException; // public void stop(); // } // // Path: integration_test/src/main/java/com/caseystella/analytics/integration/UnableToStartException.java // public class UnableToStartException extends Exception { // public UnableToStartException(String message) { // super(message); // } // public UnableToStartException(String message, Throwable t) { // super(message, t); // } // } // Path: integration_test/src/main/java/com/caseystella/analytics/integration/components/StormTopologyComponent.java import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.util.Properties; import backtype.storm.Config; import backtype.storm.LocalCluster; import backtype.storm.generated.StormTopology; import backtype.storm.topology.TopologyBuilder; import backtype.storm.utils.Utils; import com.caseystella.analytics.integration.InMemoryComponent; import com.caseystella.analytics.integration.UnableToStartException; import org.apache.storm.flux.FluxBuilder; import org.apache.storm.flux.model.ExecutionContext; import org.apache.storm.flux.model.TopologyDef; import org.apache.storm.flux.parser.FluxParser; import org.apache.thrift7.TException; import org.junit.Assert; this.topologyBuilder = builder; this.topologyName = topologyName; this.stormConfig = config; } StormTopologyComponent(String topologyName, File topologyLocation, Properties topologyProperties) { this.topologyName = topologyName; this.topologyLocation = topologyLocation; this.topologyProperties = topologyProperties; } public LocalCluster getStormCluster() { return stormCluster; } public String getTopologyName() { return topologyName; } public File getTopologyLocation() { return topologyLocation; } public Properties getTopologyProperties() { return topologyProperties; } public Config getStormConfig() { return stormConfig; }
public void start() throws UnableToStartException {
cestella/streaming_outliers
core/src/main/java/com/caseystella/analytics/timeseries/TimeseriesDatabaseHandler.java
// Path: core/src/main/java/com/caseystella/analytics/DataPoint.java // public class DataPoint { // private long timestamp; // private double value; // private Map<String, String> metadata; // private String source; // // public DataPoint() { // // } // // public DataPoint(long timestamp, double value, Map<String, String> metadata, String source) { // this.timestamp = timestamp; // this.value = value; // this.metadata = metadata; // this.source = source; // } // // public String getSource() { // return source; // } // // public void setSource(String source) { // this.source = source; // } // // // // public long getTimestamp() { // return timestamp; // } // // public void setTimestamp(long timestamp) { // this.timestamp = timestamp; // } // // public double getValue() { // return value; // } // // public void setValue(double value) { // this.value = value; // } // // public Map<String, String> getMetadata() { // return metadata; // } // // public void setMetadata(Map<String, String> metadata) { // this.metadata = metadata; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // DataPoint dataPoint = (DataPoint) o; // // if (getTimestamp() != dataPoint.getTimestamp()) return false; // if (Double.compare(dataPoint.getValue(), getValue()) != 0) return false; // if (getMetadata() != null ? !getMetadata().equals(dataPoint.getMetadata()) : dataPoint.getMetadata() != null) // return false; // return source != null ? source.equals(dataPoint.source) : dataPoint.source == null; // // } // // @Override // public int hashCode() { // int result; // long temp; // result = (int) (getTimestamp() ^ (getTimestamp() >>> 32)); // temp = Double.doubleToLongBits(getValue()); // result = 31 * result + (int) (temp ^ (temp >>> 32)); // result = 31 * result + (getMetadata() != null ? getMetadata().hashCode() : 0); // result = 31 * result + (source != null ? source.hashCode() : 0); // return result; // } // @Override // public String toString() { // return "(" + // "timestamp=" + timestamp + // ", value=" + value + // ", metadata=" + metadata + // ", source=" + source+ // ')'; // } // // } // // Path: core/src/main/java/com/caseystella/analytics/distribution/TimeRange.java // public interface TimeRange extends Range<Long>{ // // }
import com.caseystella.analytics.DataPoint; import com.caseystella.analytics.distribution.TimeRange; import com.google.common.base.Function; import java.io.Serializable; import java.util.List; import java.util.Map;
package com.caseystella.analytics.timeseries; public interface TimeseriesDatabaseHandler extends Serializable { void persist(String metric, DataPoint pt, Map<String, String> tags, Function<Object, Void> callback);
// Path: core/src/main/java/com/caseystella/analytics/DataPoint.java // public class DataPoint { // private long timestamp; // private double value; // private Map<String, String> metadata; // private String source; // // public DataPoint() { // // } // // public DataPoint(long timestamp, double value, Map<String, String> metadata, String source) { // this.timestamp = timestamp; // this.value = value; // this.metadata = metadata; // this.source = source; // } // // public String getSource() { // return source; // } // // public void setSource(String source) { // this.source = source; // } // // // // public long getTimestamp() { // return timestamp; // } // // public void setTimestamp(long timestamp) { // this.timestamp = timestamp; // } // // public double getValue() { // return value; // } // // public void setValue(double value) { // this.value = value; // } // // public Map<String, String> getMetadata() { // return metadata; // } // // public void setMetadata(Map<String, String> metadata) { // this.metadata = metadata; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // DataPoint dataPoint = (DataPoint) o; // // if (getTimestamp() != dataPoint.getTimestamp()) return false; // if (Double.compare(dataPoint.getValue(), getValue()) != 0) return false; // if (getMetadata() != null ? !getMetadata().equals(dataPoint.getMetadata()) : dataPoint.getMetadata() != null) // return false; // return source != null ? source.equals(dataPoint.source) : dataPoint.source == null; // // } // // @Override // public int hashCode() { // int result; // long temp; // result = (int) (getTimestamp() ^ (getTimestamp() >>> 32)); // temp = Double.doubleToLongBits(getValue()); // result = 31 * result + (int) (temp ^ (temp >>> 32)); // result = 31 * result + (getMetadata() != null ? getMetadata().hashCode() : 0); // result = 31 * result + (source != null ? source.hashCode() : 0); // return result; // } // @Override // public String toString() { // return "(" + // "timestamp=" + timestamp + // ", value=" + value + // ", metadata=" + metadata + // ", source=" + source+ // ')'; // } // // } // // Path: core/src/main/java/com/caseystella/analytics/distribution/TimeRange.java // public interface TimeRange extends Range<Long>{ // // } // Path: core/src/main/java/com/caseystella/analytics/timeseries/TimeseriesDatabaseHandler.java import com.caseystella.analytics.DataPoint; import com.caseystella.analytics.distribution.TimeRange; import com.google.common.base.Function; import java.io.Serializable; import java.util.List; import java.util.Map; package com.caseystella.analytics.timeseries; public interface TimeseriesDatabaseHandler extends Serializable { void persist(String metric, DataPoint pt, Map<String, String> tags, Function<Object, Void> callback);
List<DataPoint> retrieve(String metric, DataPoint pt, TimeRange range, Map<String, String> filter, int maxPts);
cestella/streaming_outliers
core/src/main/java/com/caseystella/analytics/outlier/Outlier.java
// Path: core/src/main/java/com/caseystella/analytics/DataPoint.java // public class DataPoint { // private long timestamp; // private double value; // private Map<String, String> metadata; // private String source; // // public DataPoint() { // // } // // public DataPoint(long timestamp, double value, Map<String, String> metadata, String source) { // this.timestamp = timestamp; // this.value = value; // this.metadata = metadata; // this.source = source; // } // // public String getSource() { // return source; // } // // public void setSource(String source) { // this.source = source; // } // // // // public long getTimestamp() { // return timestamp; // } // // public void setTimestamp(long timestamp) { // this.timestamp = timestamp; // } // // public double getValue() { // return value; // } // // public void setValue(double value) { // this.value = value; // } // // public Map<String, String> getMetadata() { // return metadata; // } // // public void setMetadata(Map<String, String> metadata) { // this.metadata = metadata; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // DataPoint dataPoint = (DataPoint) o; // // if (getTimestamp() != dataPoint.getTimestamp()) return false; // if (Double.compare(dataPoint.getValue(), getValue()) != 0) return false; // if (getMetadata() != null ? !getMetadata().equals(dataPoint.getMetadata()) : dataPoint.getMetadata() != null) // return false; // return source != null ? source.equals(dataPoint.source) : dataPoint.source == null; // // } // // @Override // public int hashCode() { // int result; // long temp; // result = (int) (getTimestamp() ^ (getTimestamp() >>> 32)); // temp = Double.doubleToLongBits(getValue()); // result = 31 * result + (int) (temp ^ (temp >>> 32)); // result = 31 * result + (getMetadata() != null ? getMetadata().hashCode() : 0); // result = 31 * result + (source != null ? source.hashCode() : 0); // return result; // } // @Override // public String toString() { // return "(" + // "timestamp=" + timestamp + // ", value=" + value + // ", metadata=" + metadata + // ", source=" + source+ // ')'; // } // // } // // Path: core/src/main/java/com/caseystella/analytics/distribution/TimeRange.java // public interface TimeRange extends Range<Long>{ // // }
import com.caseystella.analytics.DataPoint; import com.caseystella.analytics.distribution.TimeRange; import com.google.common.base.Joiner; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map;
package com.caseystella.analytics.outlier; public class Outlier { DataPoint dataPoint; Severity severity;
// Path: core/src/main/java/com/caseystella/analytics/DataPoint.java // public class DataPoint { // private long timestamp; // private double value; // private Map<String, String> metadata; // private String source; // // public DataPoint() { // // } // // public DataPoint(long timestamp, double value, Map<String, String> metadata, String source) { // this.timestamp = timestamp; // this.value = value; // this.metadata = metadata; // this.source = source; // } // // public String getSource() { // return source; // } // // public void setSource(String source) { // this.source = source; // } // // // // public long getTimestamp() { // return timestamp; // } // // public void setTimestamp(long timestamp) { // this.timestamp = timestamp; // } // // public double getValue() { // return value; // } // // public void setValue(double value) { // this.value = value; // } // // public Map<String, String> getMetadata() { // return metadata; // } // // public void setMetadata(Map<String, String> metadata) { // this.metadata = metadata; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // DataPoint dataPoint = (DataPoint) o; // // if (getTimestamp() != dataPoint.getTimestamp()) return false; // if (Double.compare(dataPoint.getValue(), getValue()) != 0) return false; // if (getMetadata() != null ? !getMetadata().equals(dataPoint.getMetadata()) : dataPoint.getMetadata() != null) // return false; // return source != null ? source.equals(dataPoint.source) : dataPoint.source == null; // // } // // @Override // public int hashCode() { // int result; // long temp; // result = (int) (getTimestamp() ^ (getTimestamp() >>> 32)); // temp = Double.doubleToLongBits(getValue()); // result = 31 * result + (int) (temp ^ (temp >>> 32)); // result = 31 * result + (getMetadata() != null ? getMetadata().hashCode() : 0); // result = 31 * result + (source != null ? source.hashCode() : 0); // return result; // } // @Override // public String toString() { // return "(" + // "timestamp=" + timestamp + // ", value=" + value + // ", metadata=" + metadata + // ", source=" + source+ // ')'; // } // // } // // Path: core/src/main/java/com/caseystella/analytics/distribution/TimeRange.java // public interface TimeRange extends Range<Long>{ // // } // Path: core/src/main/java/com/caseystella/analytics/outlier/Outlier.java import com.caseystella.analytics.DataPoint; import com.caseystella.analytics.distribution.TimeRange; import com.google.common.base.Joiner; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; package com.caseystella.analytics.outlier; public class Outlier { DataPoint dataPoint; Severity severity;
TimeRange range;
cestella/streaming_outliers
core/src/main/java/com/caseystella/analytics/outlier/OutlierHelper.java
// Path: core/src/main/java/com/caseystella/analytics/DataPoint.java // public class DataPoint { // private long timestamp; // private double value; // private Map<String, String> metadata; // private String source; // // public DataPoint() { // // } // // public DataPoint(long timestamp, double value, Map<String, String> metadata, String source) { // this.timestamp = timestamp; // this.value = value; // this.metadata = metadata; // this.source = source; // } // // public String getSource() { // return source; // } // // public void setSource(String source) { // this.source = source; // } // // // // public long getTimestamp() { // return timestamp; // } // // public void setTimestamp(long timestamp) { // this.timestamp = timestamp; // } // // public double getValue() { // return value; // } // // public void setValue(double value) { // this.value = value; // } // // public Map<String, String> getMetadata() { // return metadata; // } // // public void setMetadata(Map<String, String> metadata) { // this.metadata = metadata; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // DataPoint dataPoint = (DataPoint) o; // // if (getTimestamp() != dataPoint.getTimestamp()) return false; // if (Double.compare(dataPoint.getValue(), getValue()) != 0) return false; // if (getMetadata() != null ? !getMetadata().equals(dataPoint.getMetadata()) : dataPoint.getMetadata() != null) // return false; // return source != null ? source.equals(dataPoint.source) : dataPoint.source == null; // // } // // @Override // public int hashCode() { // int result; // long temp; // result = (int) (getTimestamp() ^ (getTimestamp() >>> 32)); // temp = Double.doubleToLongBits(getValue()); // result = 31 * result + (int) (temp ^ (temp >>> 32)); // result = 31 * result + (getMetadata() != null ? getMetadata().hashCode() : 0); // result = 31 * result + (source != null ? source.hashCode() : 0); // return result; // } // @Override // public String toString() { // return "(" + // "timestamp=" + timestamp + // ", value=" + value + // ", metadata=" + metadata + // ", source=" + source+ // ')'; // } // // } // // Path: core/src/main/java/com/caseystella/analytics/util/JSONUtil.java // public enum JSONUtil { // INSTANCE; // static ThreadLocal<ObjectMapper> MAPPER = new ThreadLocal<ObjectMapper>() { // /** // * Returns the current thread's "initial value" for this // * thread-local variable. This method will be invoked the first // * time a thread accesses the variable with the {@link #get} // * method, unless the thread previously invoked the {@link #set} // * method, in which case the <tt>initialValue</tt> method will not // * be invoked for the thread. Normally, this method is invoked at // * most once per thread, but it may be invoked again in case of // * subsequent invocations of {@link #remove} followed by {@link #get}. // * <p/> // * <p>This implementation simply returns <tt>null</tt>; if the // * programmer desires thread-local variables to have an initial // * value other than <tt>null</tt>, <tt>ThreadLocal</tt> must be // * subclassed, and this method overridden. Typically, an // * anonymous inner class will be used. // * // * @return the initial value for this thread-local // */ // @Override // protected ObjectMapper initialValue() { // return new ObjectMapper(); // } // }; // // public <T> T load(File f, Class<T> clazz) throws IOException { // return load(new FileInputStream(f), clazz); // } // // public <T> T load(InputStream is, Class<T> clazz) throws IOException { // T ret = MAPPER.get().readValue(is, clazz); // return ret; // } // public <T> T load(String s, Charset c, Class<T> clazz) throws IOException { // return load( new ByteArrayInputStream(s.getBytes(c)), clazz); // } // public <T> T load(String s, Class<T> clazz) throws IOException { // return load( s, Charset.defaultCharset(), clazz); // } // public <T> T load(InputStream is, TypeReference<T> reference) throws IOException { // T ret = MAPPER.get().readValue(is, reference); // return ret; // } // public <T> T load(String s, Charset c, TypeReference<T> reference) throws IOException { // return load( new ByteArrayInputStream(s.getBytes(c)), reference); // } // public <T> T load(String s, TypeReference<T> reference) throws IOException { // return load( s, Charset.defaultCharset(), reference); // } // // public String toJSON(Object bean ) throws JsonProcessingException { // return MAPPER.get().writerWithDefaultPrettyPrinter().writeValueAsString(bean); // } // // }
import com.caseystella.analytics.DataPoint; import com.caseystella.analytics.util.JSONUtil; import com.fasterxml.jackson.core.JsonProcessingException; import com.google.common.base.Joiner; import com.google.common.collect.Iterables; import java.util.*;
package com.caseystella.analytics.outlier; public enum OutlierHelper { INSTANCE;
// Path: core/src/main/java/com/caseystella/analytics/DataPoint.java // public class DataPoint { // private long timestamp; // private double value; // private Map<String, String> metadata; // private String source; // // public DataPoint() { // // } // // public DataPoint(long timestamp, double value, Map<String, String> metadata, String source) { // this.timestamp = timestamp; // this.value = value; // this.metadata = metadata; // this.source = source; // } // // public String getSource() { // return source; // } // // public void setSource(String source) { // this.source = source; // } // // // // public long getTimestamp() { // return timestamp; // } // // public void setTimestamp(long timestamp) { // this.timestamp = timestamp; // } // // public double getValue() { // return value; // } // // public void setValue(double value) { // this.value = value; // } // // public Map<String, String> getMetadata() { // return metadata; // } // // public void setMetadata(Map<String, String> metadata) { // this.metadata = metadata; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // DataPoint dataPoint = (DataPoint) o; // // if (getTimestamp() != dataPoint.getTimestamp()) return false; // if (Double.compare(dataPoint.getValue(), getValue()) != 0) return false; // if (getMetadata() != null ? !getMetadata().equals(dataPoint.getMetadata()) : dataPoint.getMetadata() != null) // return false; // return source != null ? source.equals(dataPoint.source) : dataPoint.source == null; // // } // // @Override // public int hashCode() { // int result; // long temp; // result = (int) (getTimestamp() ^ (getTimestamp() >>> 32)); // temp = Double.doubleToLongBits(getValue()); // result = 31 * result + (int) (temp ^ (temp >>> 32)); // result = 31 * result + (getMetadata() != null ? getMetadata().hashCode() : 0); // result = 31 * result + (source != null ? source.hashCode() : 0); // return result; // } // @Override // public String toString() { // return "(" + // "timestamp=" + timestamp + // ", value=" + value + // ", metadata=" + metadata + // ", source=" + source+ // ')'; // } // // } // // Path: core/src/main/java/com/caseystella/analytics/util/JSONUtil.java // public enum JSONUtil { // INSTANCE; // static ThreadLocal<ObjectMapper> MAPPER = new ThreadLocal<ObjectMapper>() { // /** // * Returns the current thread's "initial value" for this // * thread-local variable. This method will be invoked the first // * time a thread accesses the variable with the {@link #get} // * method, unless the thread previously invoked the {@link #set} // * method, in which case the <tt>initialValue</tt> method will not // * be invoked for the thread. Normally, this method is invoked at // * most once per thread, but it may be invoked again in case of // * subsequent invocations of {@link #remove} followed by {@link #get}. // * <p/> // * <p>This implementation simply returns <tt>null</tt>; if the // * programmer desires thread-local variables to have an initial // * value other than <tt>null</tt>, <tt>ThreadLocal</tt> must be // * subclassed, and this method overridden. Typically, an // * anonymous inner class will be used. // * // * @return the initial value for this thread-local // */ // @Override // protected ObjectMapper initialValue() { // return new ObjectMapper(); // } // }; // // public <T> T load(File f, Class<T> clazz) throws IOException { // return load(new FileInputStream(f), clazz); // } // // public <T> T load(InputStream is, Class<T> clazz) throws IOException { // T ret = MAPPER.get().readValue(is, clazz); // return ret; // } // public <T> T load(String s, Charset c, Class<T> clazz) throws IOException { // return load( new ByteArrayInputStream(s.getBytes(c)), clazz); // } // public <T> T load(String s, Class<T> clazz) throws IOException { // return load( s, Charset.defaultCharset(), clazz); // } // public <T> T load(InputStream is, TypeReference<T> reference) throws IOException { // T ret = MAPPER.get().readValue(is, reference); // return ret; // } // public <T> T load(String s, Charset c, TypeReference<T> reference) throws IOException { // return load( new ByteArrayInputStream(s.getBytes(c)), reference); // } // public <T> T load(String s, TypeReference<T> reference) throws IOException { // return load( s, Charset.defaultCharset(), reference); // } // // public String toJSON(Object bean ) throws JsonProcessingException { // return MAPPER.get().writerWithDefaultPrettyPrinter().writeValueAsString(bean); // } // // } // Path: core/src/main/java/com/caseystella/analytics/outlier/OutlierHelper.java import com.caseystella.analytics.DataPoint; import com.caseystella.analytics.util.JSONUtil; import com.fasterxml.jackson.core.JsonProcessingException; import com.google.common.base.Joiner; import com.google.common.collect.Iterables; import java.util.*; package com.caseystella.analytics.outlier; public enum OutlierHelper { INSTANCE;
public Map<String, Object> toJson(DataPoint dp) {
cestella/streaming_outliers
core/src/main/java/com/caseystella/analytics/extractor/DataPointExtractorConfig.java
// Path: core/src/main/java/com/caseystella/analytics/converters/primitive/PrimitiveConverter.java // public class PrimitiveConverter { // public static final String TYPE_CONF = "type"; // public static final String NAME_CONF = "name"; // public enum Type implements Function<byte[], Object> { // DOUBLE(new Function<byte[], Object>() { // @Override // public Object apply(byte[] bytes) { // return Bytes.toDouble(bytes); // } // }) // ,LONG(new Function<byte[], Object>() { // @Override // public Object apply(byte[] bytes) { // return Bytes.toLong(bytes); // } // }) // ,INTEGER(new Function<byte[], Object>() { // @Override // public Object apply(byte[] bytes) { // return Bytes.toInt(bytes); // } // }) // ,STRING(new Function<byte[], Object>() { // @Override // public Object apply(byte[] bytes) { // return Bytes.toString(bytes); // } // }) // ; // private Function<byte[], Object> _func; // Type(Function<byte[], Object> func) { // _func = func; // } // @Override // public Object apply(byte[] bytes) { // return _func.apply(bytes); // } // } // // public static class PrimitiveMeasurementConverter implements MeasurementConverter { // // @Override // public Double convert(Object in, Map<String, Object> config) { // if(in instanceof Double) { // return (Double)in; // } // else if(in instanceof Number) { // return ((Number)in).doubleValue(); // } // else if(in instanceof String) { // return Double.parseDouble(in.toString()); // } // else // { // throw new RuntimeException("Unable to convert " + in + " to a double"); // } // } // } // // public static class PrimitiveTimestampConverter implements TimestampConverter{ // @Override // public Long convert(Object in, Map<String, Object> config) { // if(in instanceof Long) { // return (Long)in; // } // else if(in instanceof Number) { // return ((Number)in).longValue(); // } // else if(in instanceof String) { // return Long.parseLong(in.toString()); // } // else // { // throw new RuntimeException("Unable to convert " + in + " to a long"); // } // } // } // // public static class PrimitiveMappingConverter implements MappingConverter { // // @Override // public Map<String, Object> convert(final byte[] in, final Map<String, Object> config) { // final Type t = Type.valueOf((String) config.get(TYPE_CONF)); // return new HashMap<String, Object>() {{ // put((String) config.get(NAME_CONF), t.apply(in)); // }}; // } // } // } // // Path: core/src/main/java/com/caseystella/analytics/util/JSONUtil.java // public enum JSONUtil { // INSTANCE; // static ThreadLocal<ObjectMapper> MAPPER = new ThreadLocal<ObjectMapper>() { // /** // * Returns the current thread's "initial value" for this // * thread-local variable. This method will be invoked the first // * time a thread accesses the variable with the {@link #get} // * method, unless the thread previously invoked the {@link #set} // * method, in which case the <tt>initialValue</tt> method will not // * be invoked for the thread. Normally, this method is invoked at // * most once per thread, but it may be invoked again in case of // * subsequent invocations of {@link #remove} followed by {@link #get}. // * <p/> // * <p>This implementation simply returns <tt>null</tt>; if the // * programmer desires thread-local variables to have an initial // * value other than <tt>null</tt>, <tt>ThreadLocal</tt> must be // * subclassed, and this method overridden. Typically, an // * anonymous inner class will be used. // * // * @return the initial value for this thread-local // */ // @Override // protected ObjectMapper initialValue() { // return new ObjectMapper(); // } // }; // // public <T> T load(File f, Class<T> clazz) throws IOException { // return load(new FileInputStream(f), clazz); // } // // public <T> T load(InputStream is, Class<T> clazz) throws IOException { // T ret = MAPPER.get().readValue(is, clazz); // return ret; // } // public <T> T load(String s, Charset c, Class<T> clazz) throws IOException { // return load( new ByteArrayInputStream(s.getBytes(c)), clazz); // } // public <T> T load(String s, Class<T> clazz) throws IOException { // return load( s, Charset.defaultCharset(), clazz); // } // public <T> T load(InputStream is, TypeReference<T> reference) throws IOException { // T ret = MAPPER.get().readValue(is, reference); // return ret; // } // public <T> T load(String s, Charset c, TypeReference<T> reference) throws IOException { // return load( new ByteArrayInputStream(s.getBytes(c)), reference); // } // public <T> T load(String s, TypeReference<T> reference) throws IOException { // return load( s, Charset.defaultCharset(), reference); // } // // public String toJSON(Object bean ) throws JsonProcessingException { // return MAPPER.get().writerWithDefaultPrettyPrinter().writeValueAsString(bean); // } // // }
import com.caseystella.analytics.converters.*; import com.caseystella.analytics.converters.primitive.PrimitiveConverter; import com.caseystella.analytics.util.JSONUtil; import java.io.IOException; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.Map;
package com.caseystella.analytics.extractor; public class DataPointExtractorConfig implements Serializable { public static class Measurement implements Serializable { private String source; private List<String> sourceFields; private String timestampField;
// Path: core/src/main/java/com/caseystella/analytics/converters/primitive/PrimitiveConverter.java // public class PrimitiveConverter { // public static final String TYPE_CONF = "type"; // public static final String NAME_CONF = "name"; // public enum Type implements Function<byte[], Object> { // DOUBLE(new Function<byte[], Object>() { // @Override // public Object apply(byte[] bytes) { // return Bytes.toDouble(bytes); // } // }) // ,LONG(new Function<byte[], Object>() { // @Override // public Object apply(byte[] bytes) { // return Bytes.toLong(bytes); // } // }) // ,INTEGER(new Function<byte[], Object>() { // @Override // public Object apply(byte[] bytes) { // return Bytes.toInt(bytes); // } // }) // ,STRING(new Function<byte[], Object>() { // @Override // public Object apply(byte[] bytes) { // return Bytes.toString(bytes); // } // }) // ; // private Function<byte[], Object> _func; // Type(Function<byte[], Object> func) { // _func = func; // } // @Override // public Object apply(byte[] bytes) { // return _func.apply(bytes); // } // } // // public static class PrimitiveMeasurementConverter implements MeasurementConverter { // // @Override // public Double convert(Object in, Map<String, Object> config) { // if(in instanceof Double) { // return (Double)in; // } // else if(in instanceof Number) { // return ((Number)in).doubleValue(); // } // else if(in instanceof String) { // return Double.parseDouble(in.toString()); // } // else // { // throw new RuntimeException("Unable to convert " + in + " to a double"); // } // } // } // // public static class PrimitiveTimestampConverter implements TimestampConverter{ // @Override // public Long convert(Object in, Map<String, Object> config) { // if(in instanceof Long) { // return (Long)in; // } // else if(in instanceof Number) { // return ((Number)in).longValue(); // } // else if(in instanceof String) { // return Long.parseLong(in.toString()); // } // else // { // throw new RuntimeException("Unable to convert " + in + " to a long"); // } // } // } // // public static class PrimitiveMappingConverter implements MappingConverter { // // @Override // public Map<String, Object> convert(final byte[] in, final Map<String, Object> config) { // final Type t = Type.valueOf((String) config.get(TYPE_CONF)); // return new HashMap<String, Object>() {{ // put((String) config.get(NAME_CONF), t.apply(in)); // }}; // } // } // } // // Path: core/src/main/java/com/caseystella/analytics/util/JSONUtil.java // public enum JSONUtil { // INSTANCE; // static ThreadLocal<ObjectMapper> MAPPER = new ThreadLocal<ObjectMapper>() { // /** // * Returns the current thread's "initial value" for this // * thread-local variable. This method will be invoked the first // * time a thread accesses the variable with the {@link #get} // * method, unless the thread previously invoked the {@link #set} // * method, in which case the <tt>initialValue</tt> method will not // * be invoked for the thread. Normally, this method is invoked at // * most once per thread, but it may be invoked again in case of // * subsequent invocations of {@link #remove} followed by {@link #get}. // * <p/> // * <p>This implementation simply returns <tt>null</tt>; if the // * programmer desires thread-local variables to have an initial // * value other than <tt>null</tt>, <tt>ThreadLocal</tt> must be // * subclassed, and this method overridden. Typically, an // * anonymous inner class will be used. // * // * @return the initial value for this thread-local // */ // @Override // protected ObjectMapper initialValue() { // return new ObjectMapper(); // } // }; // // public <T> T load(File f, Class<T> clazz) throws IOException { // return load(new FileInputStream(f), clazz); // } // // public <T> T load(InputStream is, Class<T> clazz) throws IOException { // T ret = MAPPER.get().readValue(is, clazz); // return ret; // } // public <T> T load(String s, Charset c, Class<T> clazz) throws IOException { // return load( new ByteArrayInputStream(s.getBytes(c)), clazz); // } // public <T> T load(String s, Class<T> clazz) throws IOException { // return load( s, Charset.defaultCharset(), clazz); // } // public <T> T load(InputStream is, TypeReference<T> reference) throws IOException { // T ret = MAPPER.get().readValue(is, reference); // return ret; // } // public <T> T load(String s, Charset c, TypeReference<T> reference) throws IOException { // return load( new ByteArrayInputStream(s.getBytes(c)), reference); // } // public <T> T load(String s, TypeReference<T> reference) throws IOException { // return load( s, Charset.defaultCharset(), reference); // } // // public String toJSON(Object bean ) throws JsonProcessingException { // return MAPPER.get().writerWithDefaultPrettyPrinter().writeValueAsString(bean); // } // // } // Path: core/src/main/java/com/caseystella/analytics/extractor/DataPointExtractorConfig.java import com.caseystella.analytics.converters.*; import com.caseystella.analytics.converters.primitive.PrimitiveConverter; import com.caseystella.analytics.util.JSONUtil; import java.io.IOException; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.Map; package com.caseystella.analytics.extractor; public class DataPointExtractorConfig implements Serializable { public static class Measurement implements Serializable { private String source; private List<String> sourceFields; private String timestampField;
private TimestampConverter timestampConverter = new PrimitiveConverter.PrimitiveTimestampConverter();
cestella/streaming_outliers
core/src/main/java/com/caseystella/analytics/distribution/scaling/ScalingFunctions.java
// Path: core/src/main/java/com/caseystella/analytics/distribution/GlobalStatistics.java // public class GlobalStatistics implements Serializable { // Double mean; // Double min; // Double max; // Double stddev; // // public Double getMean() { // return mean; // } // // public void setMean(double mean) { // this.mean = mean; // } // // public Double getMin() { // return min; // } // // public void setMin(double min) { // this.min = min; // } // // public Double getMax() { // return max; // } // // public void setMax(double max) { // this.max = max; // } // // public Double getStddev() { // return stddev; // } // // public void setStddev(double stddev) { // this.stddev = stddev; // } // }
import com.caseystella.analytics.distribution.GlobalStatistics;
package com.caseystella.analytics.distribution.scaling; public enum ScalingFunctions implements ScalingFunction { NONE(new ScalingFunction() { @Override
// Path: core/src/main/java/com/caseystella/analytics/distribution/GlobalStatistics.java // public class GlobalStatistics implements Serializable { // Double mean; // Double min; // Double max; // Double stddev; // // public Double getMean() { // return mean; // } // // public void setMean(double mean) { // this.mean = mean; // } // // public Double getMin() { // return min; // } // // public void setMin(double min) { // this.min = min; // } // // public Double getMax() { // return max; // } // // public void setMax(double max) { // this.max = max; // } // // public Double getStddev() { // return stddev; // } // // public void setStddev(double stddev) { // this.stddev = stddev; // } // } // Path: core/src/main/java/com/caseystella/analytics/distribution/scaling/ScalingFunctions.java import com.caseystella.analytics.distribution.GlobalStatistics; package com.caseystella.analytics.distribution.scaling; public enum ScalingFunctions implements ScalingFunction { NONE(new ScalingFunction() { @Override
public double scale(double val, GlobalStatistics stats) {
cestella/streaming_outliers
core/src/main/java/com/caseystella/analytics/converters/primitive/PrimitiveConverter.java
// Path: core/src/main/java/com/caseystella/analytics/converters/MappingConverter.java // public interface MappingConverter extends Converter<Map<String, Object>, byte[]> { // } // // Path: core/src/main/java/com/caseystella/analytics/converters/TimestampConverter.java // public interface TimestampConverter extends Converter<Long, Object>{ // } // // Path: core/src/main/java/com/caseystella/analytics/converters/MeasurementConverter.java // public interface MeasurementConverter extends Converter<Double, Object> { // }
import com.caseystella.analytics.converters.MappingConverter; import com.caseystella.analytics.converters.TimestampConverter; import com.caseystella.analytics.converters.MeasurementConverter; import com.google.common.base.Function; import org.apache.hadoop.hbase.util.Bytes; import java.util.HashMap; import java.util.Map;
}) ,LONG(new Function<byte[], Object>() { @Override public Object apply(byte[] bytes) { return Bytes.toLong(bytes); } }) ,INTEGER(new Function<byte[], Object>() { @Override public Object apply(byte[] bytes) { return Bytes.toInt(bytes); } }) ,STRING(new Function<byte[], Object>() { @Override public Object apply(byte[] bytes) { return Bytes.toString(bytes); } }) ; private Function<byte[], Object> _func; Type(Function<byte[], Object> func) { _func = func; } @Override public Object apply(byte[] bytes) { return _func.apply(bytes); } }
// Path: core/src/main/java/com/caseystella/analytics/converters/MappingConverter.java // public interface MappingConverter extends Converter<Map<String, Object>, byte[]> { // } // // Path: core/src/main/java/com/caseystella/analytics/converters/TimestampConverter.java // public interface TimestampConverter extends Converter<Long, Object>{ // } // // Path: core/src/main/java/com/caseystella/analytics/converters/MeasurementConverter.java // public interface MeasurementConverter extends Converter<Double, Object> { // } // Path: core/src/main/java/com/caseystella/analytics/converters/primitive/PrimitiveConverter.java import com.caseystella.analytics.converters.MappingConverter; import com.caseystella.analytics.converters.TimestampConverter; import com.caseystella.analytics.converters.MeasurementConverter; import com.google.common.base.Function; import org.apache.hadoop.hbase.util.Bytes; import java.util.HashMap; import java.util.Map; }) ,LONG(new Function<byte[], Object>() { @Override public Object apply(byte[] bytes) { return Bytes.toLong(bytes); } }) ,INTEGER(new Function<byte[], Object>() { @Override public Object apply(byte[] bytes) { return Bytes.toInt(bytes); } }) ,STRING(new Function<byte[], Object>() { @Override public Object apply(byte[] bytes) { return Bytes.toString(bytes); } }) ; private Function<byte[], Object> _func; Type(Function<byte[], Object> func) { _func = func; } @Override public Object apply(byte[] bytes) { return _func.apply(bytes); } }
public static class PrimitiveMeasurementConverter implements MeasurementConverter {
cestella/streaming_outliers
core/src/main/java/com/caseystella/analytics/converters/primitive/PrimitiveConverter.java
// Path: core/src/main/java/com/caseystella/analytics/converters/MappingConverter.java // public interface MappingConverter extends Converter<Map<String, Object>, byte[]> { // } // // Path: core/src/main/java/com/caseystella/analytics/converters/TimestampConverter.java // public interface TimestampConverter extends Converter<Long, Object>{ // } // // Path: core/src/main/java/com/caseystella/analytics/converters/MeasurementConverter.java // public interface MeasurementConverter extends Converter<Double, Object> { // }
import com.caseystella.analytics.converters.MappingConverter; import com.caseystella.analytics.converters.TimestampConverter; import com.caseystella.analytics.converters.MeasurementConverter; import com.google.common.base.Function; import org.apache.hadoop.hbase.util.Bytes; import java.util.HashMap; import java.util.Map;
private Function<byte[], Object> _func; Type(Function<byte[], Object> func) { _func = func; } @Override public Object apply(byte[] bytes) { return _func.apply(bytes); } } public static class PrimitiveMeasurementConverter implements MeasurementConverter { @Override public Double convert(Object in, Map<String, Object> config) { if(in instanceof Double) { return (Double)in; } else if(in instanceof Number) { return ((Number)in).doubleValue(); } else if(in instanceof String) { return Double.parseDouble(in.toString()); } else { throw new RuntimeException("Unable to convert " + in + " to a double"); } } }
// Path: core/src/main/java/com/caseystella/analytics/converters/MappingConverter.java // public interface MappingConverter extends Converter<Map<String, Object>, byte[]> { // } // // Path: core/src/main/java/com/caseystella/analytics/converters/TimestampConverter.java // public interface TimestampConverter extends Converter<Long, Object>{ // } // // Path: core/src/main/java/com/caseystella/analytics/converters/MeasurementConverter.java // public interface MeasurementConverter extends Converter<Double, Object> { // } // Path: core/src/main/java/com/caseystella/analytics/converters/primitive/PrimitiveConverter.java import com.caseystella.analytics.converters.MappingConverter; import com.caseystella.analytics.converters.TimestampConverter; import com.caseystella.analytics.converters.MeasurementConverter; import com.google.common.base.Function; import org.apache.hadoop.hbase.util.Bytes; import java.util.HashMap; import java.util.Map; private Function<byte[], Object> _func; Type(Function<byte[], Object> func) { _func = func; } @Override public Object apply(byte[] bytes) { return _func.apply(bytes); } } public static class PrimitiveMeasurementConverter implements MeasurementConverter { @Override public Double convert(Object in, Map<String, Object> config) { if(in instanceof Double) { return (Double)in; } else if(in instanceof Number) { return ((Number)in).doubleValue(); } else if(in instanceof String) { return Double.parseDouble(in.toString()); } else { throw new RuntimeException("Unable to convert " + in + " to a double"); } } }
public static class PrimitiveTimestampConverter implements TimestampConverter{
cestella/streaming_outliers
core/src/main/java/com/caseystella/analytics/converters/primitive/PrimitiveConverter.java
// Path: core/src/main/java/com/caseystella/analytics/converters/MappingConverter.java // public interface MappingConverter extends Converter<Map<String, Object>, byte[]> { // } // // Path: core/src/main/java/com/caseystella/analytics/converters/TimestampConverter.java // public interface TimestampConverter extends Converter<Long, Object>{ // } // // Path: core/src/main/java/com/caseystella/analytics/converters/MeasurementConverter.java // public interface MeasurementConverter extends Converter<Double, Object> { // }
import com.caseystella.analytics.converters.MappingConverter; import com.caseystella.analytics.converters.TimestampConverter; import com.caseystella.analytics.converters.MeasurementConverter; import com.google.common.base.Function; import org.apache.hadoop.hbase.util.Bytes; import java.util.HashMap; import java.util.Map;
} else if(in instanceof String) { return Double.parseDouble(in.toString()); } else { throw new RuntimeException("Unable to convert " + in + " to a double"); } } } public static class PrimitiveTimestampConverter implements TimestampConverter{ @Override public Long convert(Object in, Map<String, Object> config) { if(in instanceof Long) { return (Long)in; } else if(in instanceof Number) { return ((Number)in).longValue(); } else if(in instanceof String) { return Long.parseLong(in.toString()); } else { throw new RuntimeException("Unable to convert " + in + " to a long"); } } }
// Path: core/src/main/java/com/caseystella/analytics/converters/MappingConverter.java // public interface MappingConverter extends Converter<Map<String, Object>, byte[]> { // } // // Path: core/src/main/java/com/caseystella/analytics/converters/TimestampConverter.java // public interface TimestampConverter extends Converter<Long, Object>{ // } // // Path: core/src/main/java/com/caseystella/analytics/converters/MeasurementConverter.java // public interface MeasurementConverter extends Converter<Double, Object> { // } // Path: core/src/main/java/com/caseystella/analytics/converters/primitive/PrimitiveConverter.java import com.caseystella.analytics.converters.MappingConverter; import com.caseystella.analytics.converters.TimestampConverter; import com.caseystella.analytics.converters.MeasurementConverter; import com.google.common.base.Function; import org.apache.hadoop.hbase.util.Bytes; import java.util.HashMap; import java.util.Map; } else if(in instanceof String) { return Double.parseDouble(in.toString()); } else { throw new RuntimeException("Unable to convert " + in + " to a double"); } } } public static class PrimitiveTimestampConverter implements TimestampConverter{ @Override public Long convert(Object in, Map<String, Object> config) { if(in instanceof Long) { return (Long)in; } else if(in instanceof Number) { return ((Number)in).longValue(); } else if(in instanceof String) { return Long.parseLong(in.toString()); } else { throw new RuntimeException("Unable to convert " + in + " to a long"); } } }
public static class PrimitiveMappingConverter implements MappingConverter {
cestella/streaming_outliers
integration_test/src/main/java/com/caseystella/analytics/integration/components/ElasticSearchComponent.java
// Path: integration_test/src/main/java/com/caseystella/analytics/integration/InMemoryComponent.java // public interface InMemoryComponent { // public void start() throws UnableToStartException; // public void stop(); // } // // Path: integration_test/src/main/java/com/caseystella/analytics/integration/UnableToStartException.java // public class UnableToStartException extends Exception { // public UnableToStartException(String message) { // super(message); // } // public UnableToStartException(String message, Throwable t) { // super(message, t); // } // }
import com.caseystella.analytics.integration.InMemoryComponent; import com.caseystella.analytics.integration.UnableToStartException; import org.apache.commons.io.FileUtils; import org.elasticsearch.ElasticsearchTimeoutException; import org.elasticsearch.action.admin.cluster.health.ClusterHealthAction; import org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest; import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse; import org.elasticsearch.action.admin.indices.refresh.RefreshRequest; import org.elasticsearch.action.admin.indices.stats.IndicesStatsRequest; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.client.Client; import org.elasticsearch.client.ElasticsearchClient; import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.cluster.health.ClusterHealthStatus; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.transport.InetSocketTransportAddress; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.node.Node; import org.elasticsearch.node.NodeBuilder; import org.elasticsearch.search.SearchHit; import java.io.File; import java.io.IOException; import java.net.InetAddress; import java.net.UnknownHostException; import java.nio.file.Files; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set;
} public ElasticSearchComponent build() { return new ElasticSearchComponent(httpPort, indexDir, extraElasticSearchSettings); } } private Client client; private Node node; private int httpPort; private File indexDir; private Map<String, String> extraElasticSearchSettings; public ElasticSearchComponent(int httpPort, File indexDir) { this(httpPort, indexDir, null); } public ElasticSearchComponent(int httpPort, File indexDir, Map<String, String> extraElasticSearchSettings) { this.httpPort = httpPort; this.indexDir = indexDir; this.extraElasticSearchSettings = extraElasticSearchSettings; } public Client getClient() { return client; } private void cleanDir(File dir) throws IOException { if(dir.exists()) { FileUtils.deleteDirectory(dir); } dir.mkdirs(); }
// Path: integration_test/src/main/java/com/caseystella/analytics/integration/InMemoryComponent.java // public interface InMemoryComponent { // public void start() throws UnableToStartException; // public void stop(); // } // // Path: integration_test/src/main/java/com/caseystella/analytics/integration/UnableToStartException.java // public class UnableToStartException extends Exception { // public UnableToStartException(String message) { // super(message); // } // public UnableToStartException(String message, Throwable t) { // super(message, t); // } // } // Path: integration_test/src/main/java/com/caseystella/analytics/integration/components/ElasticSearchComponent.java import com.caseystella.analytics.integration.InMemoryComponent; import com.caseystella.analytics.integration.UnableToStartException; import org.apache.commons.io.FileUtils; import org.elasticsearch.ElasticsearchTimeoutException; import org.elasticsearch.action.admin.cluster.health.ClusterHealthAction; import org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest; import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse; import org.elasticsearch.action.admin.indices.refresh.RefreshRequest; import org.elasticsearch.action.admin.indices.stats.IndicesStatsRequest; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.client.Client; import org.elasticsearch.client.ElasticsearchClient; import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.cluster.health.ClusterHealthStatus; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.transport.InetSocketTransportAddress; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.node.Node; import org.elasticsearch.node.NodeBuilder; import org.elasticsearch.search.SearchHit; import java.io.File; import java.io.IOException; import java.net.InetAddress; import java.net.UnknownHostException; import java.nio.file.Files; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; } public ElasticSearchComponent build() { return new ElasticSearchComponent(httpPort, indexDir, extraElasticSearchSettings); } } private Client client; private Node node; private int httpPort; private File indexDir; private Map<String, String> extraElasticSearchSettings; public ElasticSearchComponent(int httpPort, File indexDir) { this(httpPort, indexDir, null); } public ElasticSearchComponent(int httpPort, File indexDir, Map<String, String> extraElasticSearchSettings) { this.httpPort = httpPort; this.indexDir = indexDir; this.extraElasticSearchSettings = extraElasticSearchSettings; } public Client getClient() { return client; } private void cleanDir(File dir) throws IOException { if(dir.exists()) { FileUtils.deleteDirectory(dir); } dir.mkdirs(); }
public void start() throws UnableToStartException {
cestella/streaming_outliers
core/src/main/java/com/caseystella/analytics/converters/primitive/DateConverter.java
// Path: core/src/main/java/com/caseystella/analytics/converters/Converter.java // public interface Converter<T, S> extends Serializable { // T convert(S in, Map<String, Object> config ); // } // // Path: core/src/main/java/com/caseystella/analytics/converters/MappingConverter.java // public interface MappingConverter extends Converter<Map<String, Object>, byte[]> { // } // // Path: core/src/main/java/com/caseystella/analytics/converters/TimestampConverter.java // public interface TimestampConverter extends Converter<Long, Object>{ // }
import com.caseystella.analytics.converters.Converter; import com.caseystella.analytics.converters.MappingConverter; import com.caseystella.analytics.converters.TimestampConverter; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map;
package com.caseystella.analytics.converters.primitive; public class DateConverter { public static final String FORMAT_CONF = "format"; public static final String NAME_CONF = "name"; public static final String TO_TS_CONF = "to_ts";
// Path: core/src/main/java/com/caseystella/analytics/converters/Converter.java // public interface Converter<T, S> extends Serializable { // T convert(S in, Map<String, Object> config ); // } // // Path: core/src/main/java/com/caseystella/analytics/converters/MappingConverter.java // public interface MappingConverter extends Converter<Map<String, Object>, byte[]> { // } // // Path: core/src/main/java/com/caseystella/analytics/converters/TimestampConverter.java // public interface TimestampConverter extends Converter<Long, Object>{ // } // Path: core/src/main/java/com/caseystella/analytics/converters/primitive/DateConverter.java import com.caseystella.analytics.converters.Converter; import com.caseystella.analytics.converters.MappingConverter; import com.caseystella.analytics.converters.TimestampConverter; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map; package com.caseystella.analytics.converters.primitive; public class DateConverter { public static final String FORMAT_CONF = "format"; public static final String NAME_CONF = "name"; public static final String TO_TS_CONF = "to_ts";
public static class DateTimestampConverter implements TimestampConverter {
cestella/streaming_outliers
core/src/main/java/com/caseystella/analytics/converters/primitive/DateConverter.java
// Path: core/src/main/java/com/caseystella/analytics/converters/Converter.java // public interface Converter<T, S> extends Serializable { // T convert(S in, Map<String, Object> config ); // } // // Path: core/src/main/java/com/caseystella/analytics/converters/MappingConverter.java // public interface MappingConverter extends Converter<Map<String, Object>, byte[]> { // } // // Path: core/src/main/java/com/caseystella/analytics/converters/TimestampConverter.java // public interface TimestampConverter extends Converter<Long, Object>{ // }
import com.caseystella.analytics.converters.Converter; import com.caseystella.analytics.converters.MappingConverter; import com.caseystella.analytics.converters.TimestampConverter; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map;
package com.caseystella.analytics.converters.primitive; public class DateConverter { public static final String FORMAT_CONF = "format"; public static final String NAME_CONF = "name"; public static final String TO_TS_CONF = "to_ts"; public static class DateTimestampConverter implements TimestampConverter { @Override public Long convert(Object in, Map<String, Object> config) { if(in instanceof Date) { return ((Date)in).getTime(); } else if(in instanceof String) { String format = (String) config.get(FORMAT_CONF); SimpleDateFormat sdf = new SimpleDateFormat(format); String s = in.toString(); try { Date d = sdf.parse(s); return d.getTime(); } catch (ParseException e) { throw new RuntimeException("Malformed Date: " + s); } } else { throw new RuntimeException("Unable to convert " + in + " to date"); } } }
// Path: core/src/main/java/com/caseystella/analytics/converters/Converter.java // public interface Converter<T, S> extends Serializable { // T convert(S in, Map<String, Object> config ); // } // // Path: core/src/main/java/com/caseystella/analytics/converters/MappingConverter.java // public interface MappingConverter extends Converter<Map<String, Object>, byte[]> { // } // // Path: core/src/main/java/com/caseystella/analytics/converters/TimestampConverter.java // public interface TimestampConverter extends Converter<Long, Object>{ // } // Path: core/src/main/java/com/caseystella/analytics/converters/primitive/DateConverter.java import com.caseystella.analytics.converters.Converter; import com.caseystella.analytics.converters.MappingConverter; import com.caseystella.analytics.converters.TimestampConverter; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map; package com.caseystella.analytics.converters.primitive; public class DateConverter { public static final String FORMAT_CONF = "format"; public static final String NAME_CONF = "name"; public static final String TO_TS_CONF = "to_ts"; public static class DateTimestampConverter implements TimestampConverter { @Override public Long convert(Object in, Map<String, Object> config) { if(in instanceof Date) { return ((Date)in).getTime(); } else if(in instanceof String) { String format = (String) config.get(FORMAT_CONF); SimpleDateFormat sdf = new SimpleDateFormat(format); String s = in.toString(); try { Date d = sdf.parse(s); return d.getTime(); } catch (ParseException e) { throw new RuntimeException("Malformed Date: " + s); } } else { throw new RuntimeException("Unable to convert " + in + " to date"); } } }
public static class DateMappingConverter implements MappingConverter{
cestella/streaming_outliers
integration_test/src/main/java/com/caseystella/analytics/integration/components/HBaseComponent.java
// Path: integration_test/src/main/java/com/caseystella/analytics/integration/InMemoryComponent.java // public interface InMemoryComponent { // public void start() throws UnableToStartException; // public void stop(); // } // // Path: integration_test/src/main/java/com/caseystella/analytics/integration/UnableToStartException.java // public class UnableToStartException extends Exception { // public UnableToStartException(String message) { // super(message); // } // public UnableToStartException(String message, Throwable t) { // super(message, t); // } // }
import com.caseystella.analytics.integration.InMemoryComponent; import com.caseystella.analytics.integration.UnableToStartException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.HBaseTestingUtility; import java.io.IOException;
package com.caseystella.analytics.integration.components; public class HBaseComponent implements InMemoryComponent{ private boolean startMR = false; private Configuration config; private HBaseTestingUtility testingUtility; public HBaseComponent withMR() { startMR = true; return this; } public Configuration getConfig() { return config; } public HBaseTestingUtility getTestingUtility() { return testingUtility; } @Override
// Path: integration_test/src/main/java/com/caseystella/analytics/integration/InMemoryComponent.java // public interface InMemoryComponent { // public void start() throws UnableToStartException; // public void stop(); // } // // Path: integration_test/src/main/java/com/caseystella/analytics/integration/UnableToStartException.java // public class UnableToStartException extends Exception { // public UnableToStartException(String message) { // super(message); // } // public UnableToStartException(String message, Throwable t) { // super(message, t); // } // } // Path: integration_test/src/main/java/com/caseystella/analytics/integration/components/HBaseComponent.java import com.caseystella.analytics.integration.InMemoryComponent; import com.caseystella.analytics.integration.UnableToStartException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.HBaseTestingUtility; import java.io.IOException; package com.caseystella.analytics.integration.components; public class HBaseComponent implements InMemoryComponent{ private boolean startMR = false; private Configuration config; private HBaseTestingUtility testingUtility; public HBaseComponent withMR() { startMR = true; return this; } public Configuration getConfig() { return config; } public HBaseTestingUtility getTestingUtility() { return testingUtility; } @Override
public void start() throws UnableToStartException {
cestella/streaming_outliers
core/src/main/java/com/caseystella/analytics/extractor/DataPointExtractor.java
// Path: core/src/main/java/com/caseystella/analytics/DataPoint.java // public class DataPoint { // private long timestamp; // private double value; // private Map<String, String> metadata; // private String source; // // public DataPoint() { // // } // // public DataPoint(long timestamp, double value, Map<String, String> metadata, String source) { // this.timestamp = timestamp; // this.value = value; // this.metadata = metadata; // this.source = source; // } // // public String getSource() { // return source; // } // // public void setSource(String source) { // this.source = source; // } // // // // public long getTimestamp() { // return timestamp; // } // // public void setTimestamp(long timestamp) { // this.timestamp = timestamp; // } // // public double getValue() { // return value; // } // // public void setValue(double value) { // this.value = value; // } // // public Map<String, String> getMetadata() { // return metadata; // } // // public void setMetadata(Map<String, String> metadata) { // this.metadata = metadata; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // DataPoint dataPoint = (DataPoint) o; // // if (getTimestamp() != dataPoint.getTimestamp()) return false; // if (Double.compare(dataPoint.getValue(), getValue()) != 0) return false; // if (getMetadata() != null ? !getMetadata().equals(dataPoint.getMetadata()) : dataPoint.getMetadata() != null) // return false; // return source != null ? source.equals(dataPoint.source) : dataPoint.source == null; // // } // // @Override // public int hashCode() { // int result; // long temp; // result = (int) (getTimestamp() ^ (getTimestamp() >>> 32)); // temp = Double.doubleToLongBits(getValue()); // result = 31 * result + (int) (temp ^ (temp >>> 32)); // result = 31 * result + (getMetadata() != null ? getMetadata().hashCode() : 0); // result = 31 * result + (source != null ? source.hashCode() : 0); // return result; // } // @Override // public String toString() { // return "(" + // "timestamp=" + timestamp + // ", value=" + value + // ", metadata=" + metadata + // ", source=" + source+ // ')'; // } // // }
import com.caseystella.analytics.DataPoint; import com.google.common.base.Joiner; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map;
package com.caseystella.analytics.extractor; public class DataPointExtractor implements Extractor { DataPointExtractorConfig config = null; public DataPointExtractor() { } public DataPointExtractor(DataPointExtractorConfig config) { this.config = config; } public DataPointExtractor withConfig(DataPointExtractorConfig config) { this.config = config; return this; } @Override
// Path: core/src/main/java/com/caseystella/analytics/DataPoint.java // public class DataPoint { // private long timestamp; // private double value; // private Map<String, String> metadata; // private String source; // // public DataPoint() { // // } // // public DataPoint(long timestamp, double value, Map<String, String> metadata, String source) { // this.timestamp = timestamp; // this.value = value; // this.metadata = metadata; // this.source = source; // } // // public String getSource() { // return source; // } // // public void setSource(String source) { // this.source = source; // } // // // // public long getTimestamp() { // return timestamp; // } // // public void setTimestamp(long timestamp) { // this.timestamp = timestamp; // } // // public double getValue() { // return value; // } // // public void setValue(double value) { // this.value = value; // } // // public Map<String, String> getMetadata() { // return metadata; // } // // public void setMetadata(Map<String, String> metadata) { // this.metadata = metadata; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // DataPoint dataPoint = (DataPoint) o; // // if (getTimestamp() != dataPoint.getTimestamp()) return false; // if (Double.compare(dataPoint.getValue(), getValue()) != 0) return false; // if (getMetadata() != null ? !getMetadata().equals(dataPoint.getMetadata()) : dataPoint.getMetadata() != null) // return false; // return source != null ? source.equals(dataPoint.source) : dataPoint.source == null; // // } // // @Override // public int hashCode() { // int result; // long temp; // result = (int) (getTimestamp() ^ (getTimestamp() >>> 32)); // temp = Double.doubleToLongBits(getValue()); // result = 31 * result + (int) (temp ^ (temp >>> 32)); // result = 31 * result + (getMetadata() != null ? getMetadata().hashCode() : 0); // result = 31 * result + (source != null ? source.hashCode() : 0); // return result; // } // @Override // public String toString() { // return "(" + // "timestamp=" + timestamp + // ", value=" + value + // ", metadata=" + metadata + // ", source=" + source+ // ')'; // } // // } // Path: core/src/main/java/com/caseystella/analytics/extractor/DataPointExtractor.java import com.caseystella.analytics.DataPoint; import com.google.common.base.Joiner; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; package com.caseystella.analytics.extractor; public class DataPointExtractor implements Extractor { DataPointExtractorConfig config = null; public DataPointExtractor() { } public DataPointExtractor(DataPointExtractorConfig config) { this.config = config; } public DataPointExtractor withConfig(DataPointExtractorConfig config) { this.config = config; return this; } @Override
public Iterable<DataPoint> extract(byte[] key, byte[] value, boolean failOnMalformed) {
cestella/streaming_outliers
core/src/test/java/com/caseystella/analytics/extractor/ExtractorsTest.java
// Path: core/src/main/java/com/caseystella/analytics/DataPoint.java // public class DataPoint { // private long timestamp; // private double value; // private Map<String, String> metadata; // private String source; // // public DataPoint() { // // } // // public DataPoint(long timestamp, double value, Map<String, String> metadata, String source) { // this.timestamp = timestamp; // this.value = value; // this.metadata = metadata; // this.source = source; // } // // public String getSource() { // return source; // } // // public void setSource(String source) { // this.source = source; // } // // // // public long getTimestamp() { // return timestamp; // } // // public void setTimestamp(long timestamp) { // this.timestamp = timestamp; // } // // public double getValue() { // return value; // } // // public void setValue(double value) { // this.value = value; // } // // public Map<String, String> getMetadata() { // return metadata; // } // // public void setMetadata(Map<String, String> metadata) { // this.metadata = metadata; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // DataPoint dataPoint = (DataPoint) o; // // if (getTimestamp() != dataPoint.getTimestamp()) return false; // if (Double.compare(dataPoint.getValue(), getValue()) != 0) return false; // if (getMetadata() != null ? !getMetadata().equals(dataPoint.getMetadata()) : dataPoint.getMetadata() != null) // return false; // return source != null ? source.equals(dataPoint.source) : dataPoint.source == null; // // } // // @Override // public int hashCode() { // int result; // long temp; // result = (int) (getTimestamp() ^ (getTimestamp() >>> 32)); // temp = Double.doubleToLongBits(getValue()); // result = 31 * result + (int) (temp ^ (temp >>> 32)); // result = 31 * result + (getMetadata() != null ? getMetadata().hashCode() : 0); // result = 31 * result + (source != null ? source.hashCode() : 0); // return result; // } // @Override // public String toString() { // return "(" + // "timestamp=" + timestamp + // ", value=" + value + // ", metadata=" + metadata + // ", source=" + source+ // ')'; // } // // }
import com.caseystella.analytics.DataPoint; import com.google.common.collect.Iterables; import junit.framework.Assert; import org.adrianwalker.multilinestring.Multiline; import org.apache.hadoop.hbase.util.Bytes; import org.junit.Test; import java.text.SimpleDateFormat;
package com.caseystella.analytics.extractor; public class ExtractorsTest { /** { "keyConverter" : "NOOP" , "valueConverter" : "CSVConverter" , "valueConverterConfig" : { "columnMap" : { "sensor1_ts" : 0 ,"sensor1_value" : 1 ,"sensor2_ts" : 4 ,"sensor2_value" : 5 ,"plant_id" : 7 } } , "measurements" : [ { "source" : "sensor_1" ,"timestampField" : "sensor1_ts" ,"measurementField" : "sensor1_value" ,"metadataFields" : [ "plant_id"] } ,{ "source" : "sensor_2" ,"timestampField" : "sensor2_ts" ,"measurementField" : "sensor2_value" ,"metadataFields" : [ "plant_id"] } ] } */ @Multiline public static String extractorConfig; @Test public void testExtractor() throws Exception { Assert.assertNotNull(extractorConfig); DataPointExtractorConfig config = DataPointExtractorConfig.load(extractorConfig); DataPointExtractor extractor = new DataPointExtractor().withConfig(config); {
// Path: core/src/main/java/com/caseystella/analytics/DataPoint.java // public class DataPoint { // private long timestamp; // private double value; // private Map<String, String> metadata; // private String source; // // public DataPoint() { // // } // // public DataPoint(long timestamp, double value, Map<String, String> metadata, String source) { // this.timestamp = timestamp; // this.value = value; // this.metadata = metadata; // this.source = source; // } // // public String getSource() { // return source; // } // // public void setSource(String source) { // this.source = source; // } // // // // public long getTimestamp() { // return timestamp; // } // // public void setTimestamp(long timestamp) { // this.timestamp = timestamp; // } // // public double getValue() { // return value; // } // // public void setValue(double value) { // this.value = value; // } // // public Map<String, String> getMetadata() { // return metadata; // } // // public void setMetadata(Map<String, String> metadata) { // this.metadata = metadata; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // DataPoint dataPoint = (DataPoint) o; // // if (getTimestamp() != dataPoint.getTimestamp()) return false; // if (Double.compare(dataPoint.getValue(), getValue()) != 0) return false; // if (getMetadata() != null ? !getMetadata().equals(dataPoint.getMetadata()) : dataPoint.getMetadata() != null) // return false; // return source != null ? source.equals(dataPoint.source) : dataPoint.source == null; // // } // // @Override // public int hashCode() { // int result; // long temp; // result = (int) (getTimestamp() ^ (getTimestamp() >>> 32)); // temp = Double.doubleToLongBits(getValue()); // result = 31 * result + (int) (temp ^ (temp >>> 32)); // result = 31 * result + (getMetadata() != null ? getMetadata().hashCode() : 0); // result = 31 * result + (source != null ? source.hashCode() : 0); // return result; // } // @Override // public String toString() { // return "(" + // "timestamp=" + timestamp + // ", value=" + value + // ", metadata=" + metadata + // ", source=" + source+ // ')'; // } // // } // Path: core/src/test/java/com/caseystella/analytics/extractor/ExtractorsTest.java import com.caseystella.analytics.DataPoint; import com.google.common.collect.Iterables; import junit.framework.Assert; import org.adrianwalker.multilinestring.Multiline; import org.apache.hadoop.hbase.util.Bytes; import org.junit.Test; import java.text.SimpleDateFormat; package com.caseystella.analytics.extractor; public class ExtractorsTest { /** { "keyConverter" : "NOOP" , "valueConverter" : "CSVConverter" , "valueConverterConfig" : { "columnMap" : { "sensor1_ts" : 0 ,"sensor1_value" : 1 ,"sensor2_ts" : 4 ,"sensor2_value" : 5 ,"plant_id" : 7 } } , "measurements" : [ { "source" : "sensor_1" ,"timestampField" : "sensor1_ts" ,"measurementField" : "sensor1_value" ,"metadataFields" : [ "plant_id"] } ,{ "source" : "sensor_2" ,"timestampField" : "sensor2_ts" ,"measurementField" : "sensor2_value" ,"metadataFields" : [ "plant_id"] } ] } */ @Multiline public static String extractorConfig; @Test public void testExtractor() throws Exception { Assert.assertNotNull(extractorConfig); DataPointExtractorConfig config = DataPointExtractorConfig.load(extractorConfig); DataPointExtractor extractor = new DataPointExtractor().withConfig(config); {
Iterable<DataPoint> dataPoints = extractor.extract(Bytes.toBytes(0L), Bytes.toBytes(" #0,100,foo,bar,50,7,grok,plant_1,baz"), true);
cestella/streaming_outliers
core/src/main/java/com/caseystella/analytics/distribution/scaling/DefaultScalingFunctions.java
// Path: core/src/main/java/com/caseystella/analytics/distribution/GlobalStatistics.java // public class GlobalStatistics implements Serializable { // Double mean; // Double min; // Double max; // Double stddev; // // public Double getMean() { // return mean; // } // // public void setMean(double mean) { // this.mean = mean; // } // // public Double getMin() { // return min; // } // // public void setMin(double min) { // this.min = min; // } // // public Double getMax() { // return max; // } // // public void setMax(double max) { // this.max = max; // } // // public Double getStddev() { // return stddev; // } // // public void setStddev(double stddev) { // this.stddev = stddev; // } // }
import com.caseystella.analytics.distribution.GlobalStatistics;
package com.caseystella.analytics.distribution.scaling; public class DefaultScalingFunctions { public static class ShiftToPositive implements ScalingFunction { @Override
// Path: core/src/main/java/com/caseystella/analytics/distribution/GlobalStatistics.java // public class GlobalStatistics implements Serializable { // Double mean; // Double min; // Double max; // Double stddev; // // public Double getMean() { // return mean; // } // // public void setMean(double mean) { // this.mean = mean; // } // // public Double getMin() { // return min; // } // // public void setMin(double min) { // this.min = min; // } // // public Double getMax() { // return max; // } // // public void setMax(double max) { // this.max = max; // } // // public Double getStddev() { // return stddev; // } // // public void setStddev(double stddev) { // this.stddev = stddev; // } // } // Path: core/src/main/java/com/caseystella/analytics/distribution/scaling/DefaultScalingFunctions.java import com.caseystella.analytics.distribution.GlobalStatistics; package com.caseystella.analytics.distribution.scaling; public class DefaultScalingFunctions { public static class ShiftToPositive implements ScalingFunction { @Override
public double scale(double val, GlobalStatistics globalStatistics) {
cestella/streaming_outliers
core/src/test/java/com/caseystella/analytics/distribution/DistributionTest.java
// Path: core/src/main/java/com/caseystella/analytics/DataPoint.java // public class DataPoint { // private long timestamp; // private double value; // private Map<String, String> metadata; // private String source; // // public DataPoint() { // // } // // public DataPoint(long timestamp, double value, Map<String, String> metadata, String source) { // this.timestamp = timestamp; // this.value = value; // this.metadata = metadata; // this.source = source; // } // // public String getSource() { // return source; // } // // public void setSource(String source) { // this.source = source; // } // // // // public long getTimestamp() { // return timestamp; // } // // public void setTimestamp(long timestamp) { // this.timestamp = timestamp; // } // // public double getValue() { // return value; // } // // public void setValue(double value) { // this.value = value; // } // // public Map<String, String> getMetadata() { // return metadata; // } // // public void setMetadata(Map<String, String> metadata) { // this.metadata = metadata; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // DataPoint dataPoint = (DataPoint) o; // // if (getTimestamp() != dataPoint.getTimestamp()) return false; // if (Double.compare(dataPoint.getValue(), getValue()) != 0) return false; // if (getMetadata() != null ? !getMetadata().equals(dataPoint.getMetadata()) : dataPoint.getMetadata() != null) // return false; // return source != null ? source.equals(dataPoint.source) : dataPoint.source == null; // // } // // @Override // public int hashCode() { // int result; // long temp; // result = (int) (getTimestamp() ^ (getTimestamp() >>> 32)); // temp = Double.doubleToLongBits(getValue()); // result = 31 * result + (int) (temp ^ (temp >>> 32)); // result = 31 * result + (getMetadata() != null ? getMetadata().hashCode() : 0); // result = 31 * result + (source != null ? source.hashCode() : 0); // return result; // } // @Override // public String toString() { // return "(" + // "timestamp=" + timestamp + // ", value=" + value + // ", metadata=" + metadata + // ", source=" + source+ // ')'; // } // // } // // Path: core/src/main/java/com/caseystella/analytics/distribution/scaling/ScalingFunctions.java // public enum ScalingFunctions implements ScalingFunction { // NONE(new ScalingFunction() { // // @Override // public double scale(double val, GlobalStatistics stats) { // return val; // } // }) // ,SHIFT_TO_POSITIVE(new DefaultScalingFunctions.ShiftToPositive()) // // ,SQUEEZE_TO_UNIT( new DefaultScalingFunctions.SqueezeToUnit()) // // ,FIXED_MEAN_UNIT_VARIANCE(new DefaultScalingFunctions.FixedMeanUnitVariance()) // ,ZERO_MEAN_UNIT_VARIANCE(new DefaultScalingFunctions.ZeroMeanUnitVariance()) // ; // private ScalingFunction _func; // ScalingFunctions(ScalingFunction func) { // _func = func; // } // // @Override // public double scale(double val, GlobalStatistics globalStatistics) { // return _func.scale(val, globalStatistics); // } // }
import com.caseystella.analytics.DataPoint; import com.caseystella.analytics.distribution.scaling.ScalingFunctions; import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; import org.junit.Assert; import org.junit.Test; import java.util.ArrayList; import java.util.List; import java.util.Random;
package com.caseystella.analytics.distribution; public class DistributionTest { @Test public void testQuantiles() { Random r = new Random(0);
// Path: core/src/main/java/com/caseystella/analytics/DataPoint.java // public class DataPoint { // private long timestamp; // private double value; // private Map<String, String> metadata; // private String source; // // public DataPoint() { // // } // // public DataPoint(long timestamp, double value, Map<String, String> metadata, String source) { // this.timestamp = timestamp; // this.value = value; // this.metadata = metadata; // this.source = source; // } // // public String getSource() { // return source; // } // // public void setSource(String source) { // this.source = source; // } // // // // public long getTimestamp() { // return timestamp; // } // // public void setTimestamp(long timestamp) { // this.timestamp = timestamp; // } // // public double getValue() { // return value; // } // // public void setValue(double value) { // this.value = value; // } // // public Map<String, String> getMetadata() { // return metadata; // } // // public void setMetadata(Map<String, String> metadata) { // this.metadata = metadata; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // DataPoint dataPoint = (DataPoint) o; // // if (getTimestamp() != dataPoint.getTimestamp()) return false; // if (Double.compare(dataPoint.getValue(), getValue()) != 0) return false; // if (getMetadata() != null ? !getMetadata().equals(dataPoint.getMetadata()) : dataPoint.getMetadata() != null) // return false; // return source != null ? source.equals(dataPoint.source) : dataPoint.source == null; // // } // // @Override // public int hashCode() { // int result; // long temp; // result = (int) (getTimestamp() ^ (getTimestamp() >>> 32)); // temp = Double.doubleToLongBits(getValue()); // result = 31 * result + (int) (temp ^ (temp >>> 32)); // result = 31 * result + (getMetadata() != null ? getMetadata().hashCode() : 0); // result = 31 * result + (source != null ? source.hashCode() : 0); // return result; // } // @Override // public String toString() { // return "(" + // "timestamp=" + timestamp + // ", value=" + value + // ", metadata=" + metadata + // ", source=" + source+ // ')'; // } // // } // // Path: core/src/main/java/com/caseystella/analytics/distribution/scaling/ScalingFunctions.java // public enum ScalingFunctions implements ScalingFunction { // NONE(new ScalingFunction() { // // @Override // public double scale(double val, GlobalStatistics stats) { // return val; // } // }) // ,SHIFT_TO_POSITIVE(new DefaultScalingFunctions.ShiftToPositive()) // // ,SQUEEZE_TO_UNIT( new DefaultScalingFunctions.SqueezeToUnit()) // // ,FIXED_MEAN_UNIT_VARIANCE(new DefaultScalingFunctions.FixedMeanUnitVariance()) // ,ZERO_MEAN_UNIT_VARIANCE(new DefaultScalingFunctions.ZeroMeanUnitVariance()) // ; // private ScalingFunction _func; // ScalingFunctions(ScalingFunction func) { // _func = func; // } // // @Override // public double scale(double val, GlobalStatistics globalStatistics) { // return _func.scale(val, globalStatistics); // } // } // Path: core/src/test/java/com/caseystella/analytics/distribution/DistributionTest.java import com.caseystella.analytics.DataPoint; import com.caseystella.analytics.distribution.scaling.ScalingFunctions; import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; import org.junit.Assert; import org.junit.Test; import java.util.ArrayList; import java.util.List; import java.util.Random; package com.caseystella.analytics.distribution; public class DistributionTest { @Test public void testQuantiles() { Random r = new Random(0);
List<DataPoint> points = new ArrayList<>();
cestella/streaming_outliers
core/src/test/java/com/caseystella/analytics/distribution/DistributionTest.java
// Path: core/src/main/java/com/caseystella/analytics/DataPoint.java // public class DataPoint { // private long timestamp; // private double value; // private Map<String, String> metadata; // private String source; // // public DataPoint() { // // } // // public DataPoint(long timestamp, double value, Map<String, String> metadata, String source) { // this.timestamp = timestamp; // this.value = value; // this.metadata = metadata; // this.source = source; // } // // public String getSource() { // return source; // } // // public void setSource(String source) { // this.source = source; // } // // // // public long getTimestamp() { // return timestamp; // } // // public void setTimestamp(long timestamp) { // this.timestamp = timestamp; // } // // public double getValue() { // return value; // } // // public void setValue(double value) { // this.value = value; // } // // public Map<String, String> getMetadata() { // return metadata; // } // // public void setMetadata(Map<String, String> metadata) { // this.metadata = metadata; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // DataPoint dataPoint = (DataPoint) o; // // if (getTimestamp() != dataPoint.getTimestamp()) return false; // if (Double.compare(dataPoint.getValue(), getValue()) != 0) return false; // if (getMetadata() != null ? !getMetadata().equals(dataPoint.getMetadata()) : dataPoint.getMetadata() != null) // return false; // return source != null ? source.equals(dataPoint.source) : dataPoint.source == null; // // } // // @Override // public int hashCode() { // int result; // long temp; // result = (int) (getTimestamp() ^ (getTimestamp() >>> 32)); // temp = Double.doubleToLongBits(getValue()); // result = 31 * result + (int) (temp ^ (temp >>> 32)); // result = 31 * result + (getMetadata() != null ? getMetadata().hashCode() : 0); // result = 31 * result + (source != null ? source.hashCode() : 0); // return result; // } // @Override // public String toString() { // return "(" + // "timestamp=" + timestamp + // ", value=" + value + // ", metadata=" + metadata + // ", source=" + source+ // ')'; // } // // } // // Path: core/src/main/java/com/caseystella/analytics/distribution/scaling/ScalingFunctions.java // public enum ScalingFunctions implements ScalingFunction { // NONE(new ScalingFunction() { // // @Override // public double scale(double val, GlobalStatistics stats) { // return val; // } // }) // ,SHIFT_TO_POSITIVE(new DefaultScalingFunctions.ShiftToPositive()) // // ,SQUEEZE_TO_UNIT( new DefaultScalingFunctions.SqueezeToUnit()) // // ,FIXED_MEAN_UNIT_VARIANCE(new DefaultScalingFunctions.FixedMeanUnitVariance()) // ,ZERO_MEAN_UNIT_VARIANCE(new DefaultScalingFunctions.ZeroMeanUnitVariance()) // ; // private ScalingFunction _func; // ScalingFunctions(ScalingFunction func) { // _func = func; // } // // @Override // public double scale(double val, GlobalStatistics globalStatistics) { // return _func.scale(val, globalStatistics); // } // }
import com.caseystella.analytics.DataPoint; import com.caseystella.analytics.distribution.scaling.ScalingFunctions; import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; import org.junit.Assert; import org.junit.Test; import java.util.ArrayList; import java.util.List; import java.util.Random;
package com.caseystella.analytics.distribution; public class DistributionTest { @Test public void testQuantiles() { Random r = new Random(0); List<DataPoint> points = new ArrayList<>(); DescriptiveStatistics stats = new DescriptiveStatistics(); Distribution distribution = null; for(int i = 0; i < 100;++i) { double val = r.nextDouble()*1000; DataPoint dp = (new DataPoint(i, val, null, "foo")); points.add(dp); stats.addValue(val); if(distribution == null) {
// Path: core/src/main/java/com/caseystella/analytics/DataPoint.java // public class DataPoint { // private long timestamp; // private double value; // private Map<String, String> metadata; // private String source; // // public DataPoint() { // // } // // public DataPoint(long timestamp, double value, Map<String, String> metadata, String source) { // this.timestamp = timestamp; // this.value = value; // this.metadata = metadata; // this.source = source; // } // // public String getSource() { // return source; // } // // public void setSource(String source) { // this.source = source; // } // // // // public long getTimestamp() { // return timestamp; // } // // public void setTimestamp(long timestamp) { // this.timestamp = timestamp; // } // // public double getValue() { // return value; // } // // public void setValue(double value) { // this.value = value; // } // // public Map<String, String> getMetadata() { // return metadata; // } // // public void setMetadata(Map<String, String> metadata) { // this.metadata = metadata; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // DataPoint dataPoint = (DataPoint) o; // // if (getTimestamp() != dataPoint.getTimestamp()) return false; // if (Double.compare(dataPoint.getValue(), getValue()) != 0) return false; // if (getMetadata() != null ? !getMetadata().equals(dataPoint.getMetadata()) : dataPoint.getMetadata() != null) // return false; // return source != null ? source.equals(dataPoint.source) : dataPoint.source == null; // // } // // @Override // public int hashCode() { // int result; // long temp; // result = (int) (getTimestamp() ^ (getTimestamp() >>> 32)); // temp = Double.doubleToLongBits(getValue()); // result = 31 * result + (int) (temp ^ (temp >>> 32)); // result = 31 * result + (getMetadata() != null ? getMetadata().hashCode() : 0); // result = 31 * result + (source != null ? source.hashCode() : 0); // return result; // } // @Override // public String toString() { // return "(" + // "timestamp=" + timestamp + // ", value=" + value + // ", metadata=" + metadata + // ", source=" + source+ // ')'; // } // // } // // Path: core/src/main/java/com/caseystella/analytics/distribution/scaling/ScalingFunctions.java // public enum ScalingFunctions implements ScalingFunction { // NONE(new ScalingFunction() { // // @Override // public double scale(double val, GlobalStatistics stats) { // return val; // } // }) // ,SHIFT_TO_POSITIVE(new DefaultScalingFunctions.ShiftToPositive()) // // ,SQUEEZE_TO_UNIT( new DefaultScalingFunctions.SqueezeToUnit()) // // ,FIXED_MEAN_UNIT_VARIANCE(new DefaultScalingFunctions.FixedMeanUnitVariance()) // ,ZERO_MEAN_UNIT_VARIANCE(new DefaultScalingFunctions.ZeroMeanUnitVariance()) // ; // private ScalingFunction _func; // ScalingFunctions(ScalingFunction func) { // _func = func; // } // // @Override // public double scale(double val, GlobalStatistics globalStatistics) { // return _func.scale(val, globalStatistics); // } // } // Path: core/src/test/java/com/caseystella/analytics/distribution/DistributionTest.java import com.caseystella.analytics.DataPoint; import com.caseystella.analytics.distribution.scaling.ScalingFunctions; import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; import org.junit.Assert; import org.junit.Test; import java.util.ArrayList; import java.util.List; import java.util.Random; package com.caseystella.analytics.distribution; public class DistributionTest { @Test public void testQuantiles() { Random r = new Random(0); List<DataPoint> points = new ArrayList<>(); DescriptiveStatistics stats = new DescriptiveStatistics(); Distribution distribution = null; for(int i = 0; i < 100;++i) { double val = r.nextDouble()*1000; DataPoint dp = (new DataPoint(i, val, null, "foo")); points.add(dp); stats.addValue(val); if(distribution == null) {
distribution = new Distribution(dp, ScalingFunctions.NONE, new GlobalStatistics());
sarnowski/eve-api
cdi/src/main/java/org/onsteroids/eve/api/provider/AbstractApiService.java
// Path: cdi/src/main/java/org/onsteroids/eve/api/InternalApiException.java // public final class InternalApiException extends ApiException { // private static final Logger LOG = LoggerFactory.getLogger(InternalApiException.class); // // public InternalApiException(String message) { // super(message); // } // // public InternalApiException(String message, Throwable cause) { // super(message, cause); // } // // public InternalApiException(Throwable cause) { // super(cause); // } // } // // Path: cdi/src/main/java/org/onsteroids/eve/api/cache/ApiCache.java // public interface ApiCache { // // /** // * @param apiResult the api result to cache // */ // void putApiResult(ApiResult apiResult); // // /** // * @param serverUri the api server uri // * @param xmlPath the xml path // * @param <T> an api result type // * @return the cached api result or null if apiresult not cached // */ // <T extends ApiResult> T getApiResult(Class<T> resultType, URI serverUri, String xmlPath); // // /** // * @param serverUri the api server uri // * @param xmlPath the xml path // * @param parameters the used parameters (can be null) // * @param <T> an api result type // * @return the cached api result or null if apiresult not cached // */ // <T extends ApiResult> T getApiResult(Class<T> resultType, URI serverUri, String xmlPath, Map<String,String> parameters); // // /** // * @param serverUri the api server uri // * @param xmlPath the xml path // * @param key the used api key (can be null) // * @param <T> an api result type // * @return the cached api result or null if apiresult not cached // */ // <T extends ApiResult> T getApiResult(Class<T> resultType, URI serverUri, String xmlPath, ApiKey key); // // /** // * @param serverUri the api server uri // * @param xmlPath the xml path // * @param key the used api key (can be null) // * @param parameters the used parameters (can be null) // * @param <T> an api result type // * @return the cached api result or null if apiresult not cached // */ // <T extends ApiResult> T getApiResult(Class<T> resultType, URI serverUri, String xmlPath, ApiKey key, Map<String,String> parameters); // // } // // Path: cdi/src/main/java/org/onsteroids/eve/api/connector/ApiConnection.java // public interface ApiConnection { // // /** // * @return the used server URI // */ // URI getServerUri(); // // // /** // * @param xmlPath e.g. /server/ServerStatus.xml.aspx // * @return the returned response from the server // * @throws ApiException // */ // XmlApiResult call(String xmlPath) throws ApiException; // // /** // * @param xmlPath e.g. /server/ServerStatus.xml.aspx // * @param parameters additional parameters to provide, e.g. characterID // * @return the returned response from the server // * @throws ApiException // */ // XmlApiResult call(String xmlPath, Map<String,String> parameters) throws ApiException; // // /** // * @param xmlPath e.g. /server/ServerStatus.xml.aspx // * @param key the API key to authenticate against // * @return the returned response from the server // * @throws ApiException // */ // XmlApiResult call(String xmlPath, ApiKey key) throws ApiException; // // /** // * @param xmlPath e.g. /server/ServerStatus.xml.aspx // * @param key the API key to authenticate against // * @param parameters additional parameters to provide, e.g. characterID // * @return the returned response from the server // * @throws ApiException // */ // XmlApiResult call(String xmlPath, ApiKey key, Map<String,String> parameters) throws ApiException; // // } // // Path: cdi/src/main/java/org/onsteroids/eve/api/connector/XmlApiResult.java // public interface XmlApiResult extends ApiResult { // // /** // * @return returns the &lt;result&gt; node of the api response // */ // Node getResult(); // // /** // * getTimeDifference = serverTime - localTime // * // * @return the time difference from server to local in milliseconds // */ // long getTimeDifference(); // // }
import java.util.Map; import com.eveonline.api.ApiKey; import com.eveonline.api.exceptions.ApiException; import com.eveonline.api.server.ServerStatusApi; import com.google.common.collect.Maps; import org.onsteroids.eve.api.InternalApiException; import org.onsteroids.eve.api.cache.ApiCache; import org.onsteroids.eve.api.connector.ApiConnection; import org.onsteroids.eve.api.connector.XmlApiResult; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
/** * Copyright 2010 Tobias Sarnowski * * 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. */ /** * (c) 2010 Tobias Sarnowski * All rights reserved. */ package org.onsteroids.eve.api.provider; /** * @author Tobias Sarnowski */ public abstract class AbstractApiService { private static final Logger LOG = LoggerFactory.getLogger(AbstractApiService.class);
// Path: cdi/src/main/java/org/onsteroids/eve/api/InternalApiException.java // public final class InternalApiException extends ApiException { // private static final Logger LOG = LoggerFactory.getLogger(InternalApiException.class); // // public InternalApiException(String message) { // super(message); // } // // public InternalApiException(String message, Throwable cause) { // super(message, cause); // } // // public InternalApiException(Throwable cause) { // super(cause); // } // } // // Path: cdi/src/main/java/org/onsteroids/eve/api/cache/ApiCache.java // public interface ApiCache { // // /** // * @param apiResult the api result to cache // */ // void putApiResult(ApiResult apiResult); // // /** // * @param serverUri the api server uri // * @param xmlPath the xml path // * @param <T> an api result type // * @return the cached api result or null if apiresult not cached // */ // <T extends ApiResult> T getApiResult(Class<T> resultType, URI serverUri, String xmlPath); // // /** // * @param serverUri the api server uri // * @param xmlPath the xml path // * @param parameters the used parameters (can be null) // * @param <T> an api result type // * @return the cached api result or null if apiresult not cached // */ // <T extends ApiResult> T getApiResult(Class<T> resultType, URI serverUri, String xmlPath, Map<String,String> parameters); // // /** // * @param serverUri the api server uri // * @param xmlPath the xml path // * @param key the used api key (can be null) // * @param <T> an api result type // * @return the cached api result or null if apiresult not cached // */ // <T extends ApiResult> T getApiResult(Class<T> resultType, URI serverUri, String xmlPath, ApiKey key); // // /** // * @param serverUri the api server uri // * @param xmlPath the xml path // * @param key the used api key (can be null) // * @param parameters the used parameters (can be null) // * @param <T> an api result type // * @return the cached api result or null if apiresult not cached // */ // <T extends ApiResult> T getApiResult(Class<T> resultType, URI serverUri, String xmlPath, ApiKey key, Map<String,String> parameters); // // } // // Path: cdi/src/main/java/org/onsteroids/eve/api/connector/ApiConnection.java // public interface ApiConnection { // // /** // * @return the used server URI // */ // URI getServerUri(); // // // /** // * @param xmlPath e.g. /server/ServerStatus.xml.aspx // * @return the returned response from the server // * @throws ApiException // */ // XmlApiResult call(String xmlPath) throws ApiException; // // /** // * @param xmlPath e.g. /server/ServerStatus.xml.aspx // * @param parameters additional parameters to provide, e.g. characterID // * @return the returned response from the server // * @throws ApiException // */ // XmlApiResult call(String xmlPath, Map<String,String> parameters) throws ApiException; // // /** // * @param xmlPath e.g. /server/ServerStatus.xml.aspx // * @param key the API key to authenticate against // * @return the returned response from the server // * @throws ApiException // */ // XmlApiResult call(String xmlPath, ApiKey key) throws ApiException; // // /** // * @param xmlPath e.g. /server/ServerStatus.xml.aspx // * @param key the API key to authenticate against // * @param parameters additional parameters to provide, e.g. characterID // * @return the returned response from the server // * @throws ApiException // */ // XmlApiResult call(String xmlPath, ApiKey key, Map<String,String> parameters) throws ApiException; // // } // // Path: cdi/src/main/java/org/onsteroids/eve/api/connector/XmlApiResult.java // public interface XmlApiResult extends ApiResult { // // /** // * @return returns the &lt;result&gt; node of the api response // */ // Node getResult(); // // /** // * getTimeDifference = serverTime - localTime // * // * @return the time difference from server to local in milliseconds // */ // long getTimeDifference(); // // } // Path: cdi/src/main/java/org/onsteroids/eve/api/provider/AbstractApiService.java import java.util.Map; import com.eveonline.api.ApiKey; import com.eveonline.api.exceptions.ApiException; import com.eveonline.api.server.ServerStatusApi; import com.google.common.collect.Maps; import org.onsteroids.eve.api.InternalApiException; import org.onsteroids.eve.api.cache.ApiCache; import org.onsteroids.eve.api.connector.ApiConnection; import org.onsteroids.eve.api.connector.XmlApiResult; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Copyright 2010 Tobias Sarnowski * * 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. */ /** * (c) 2010 Tobias Sarnowski * All rights reserved. */ package org.onsteroids.eve.api.provider; /** * @author Tobias Sarnowski */ public abstract class AbstractApiService { private static final Logger LOG = LoggerFactory.getLogger(AbstractApiService.class);
private ApiConnection apiConnection;
sarnowski/eve-api
cdi/src/main/java/org/onsteroids/eve/api/provider/AbstractApiService.java
// Path: cdi/src/main/java/org/onsteroids/eve/api/InternalApiException.java // public final class InternalApiException extends ApiException { // private static final Logger LOG = LoggerFactory.getLogger(InternalApiException.class); // // public InternalApiException(String message) { // super(message); // } // // public InternalApiException(String message, Throwable cause) { // super(message, cause); // } // // public InternalApiException(Throwable cause) { // super(cause); // } // } // // Path: cdi/src/main/java/org/onsteroids/eve/api/cache/ApiCache.java // public interface ApiCache { // // /** // * @param apiResult the api result to cache // */ // void putApiResult(ApiResult apiResult); // // /** // * @param serverUri the api server uri // * @param xmlPath the xml path // * @param <T> an api result type // * @return the cached api result or null if apiresult not cached // */ // <T extends ApiResult> T getApiResult(Class<T> resultType, URI serverUri, String xmlPath); // // /** // * @param serverUri the api server uri // * @param xmlPath the xml path // * @param parameters the used parameters (can be null) // * @param <T> an api result type // * @return the cached api result or null if apiresult not cached // */ // <T extends ApiResult> T getApiResult(Class<T> resultType, URI serverUri, String xmlPath, Map<String,String> parameters); // // /** // * @param serverUri the api server uri // * @param xmlPath the xml path // * @param key the used api key (can be null) // * @param <T> an api result type // * @return the cached api result or null if apiresult not cached // */ // <T extends ApiResult> T getApiResult(Class<T> resultType, URI serverUri, String xmlPath, ApiKey key); // // /** // * @param serverUri the api server uri // * @param xmlPath the xml path // * @param key the used api key (can be null) // * @param parameters the used parameters (can be null) // * @param <T> an api result type // * @return the cached api result or null if apiresult not cached // */ // <T extends ApiResult> T getApiResult(Class<T> resultType, URI serverUri, String xmlPath, ApiKey key, Map<String,String> parameters); // // } // // Path: cdi/src/main/java/org/onsteroids/eve/api/connector/ApiConnection.java // public interface ApiConnection { // // /** // * @return the used server URI // */ // URI getServerUri(); // // // /** // * @param xmlPath e.g. /server/ServerStatus.xml.aspx // * @return the returned response from the server // * @throws ApiException // */ // XmlApiResult call(String xmlPath) throws ApiException; // // /** // * @param xmlPath e.g. /server/ServerStatus.xml.aspx // * @param parameters additional parameters to provide, e.g. characterID // * @return the returned response from the server // * @throws ApiException // */ // XmlApiResult call(String xmlPath, Map<String,String> parameters) throws ApiException; // // /** // * @param xmlPath e.g. /server/ServerStatus.xml.aspx // * @param key the API key to authenticate against // * @return the returned response from the server // * @throws ApiException // */ // XmlApiResult call(String xmlPath, ApiKey key) throws ApiException; // // /** // * @param xmlPath e.g. /server/ServerStatus.xml.aspx // * @param key the API key to authenticate against // * @param parameters additional parameters to provide, e.g. characterID // * @return the returned response from the server // * @throws ApiException // */ // XmlApiResult call(String xmlPath, ApiKey key, Map<String,String> parameters) throws ApiException; // // } // // Path: cdi/src/main/java/org/onsteroids/eve/api/connector/XmlApiResult.java // public interface XmlApiResult extends ApiResult { // // /** // * @return returns the &lt;result&gt; node of the api response // */ // Node getResult(); // // /** // * getTimeDifference = serverTime - localTime // * // * @return the time difference from server to local in milliseconds // */ // long getTimeDifference(); // // }
import java.util.Map; import com.eveonline.api.ApiKey; import com.eveonline.api.exceptions.ApiException; import com.eveonline.api.server.ServerStatusApi; import com.google.common.collect.Maps; import org.onsteroids.eve.api.InternalApiException; import org.onsteroids.eve.api.cache.ApiCache; import org.onsteroids.eve.api.connector.ApiConnection; import org.onsteroids.eve.api.connector.XmlApiResult; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
/** * Copyright 2010 Tobias Sarnowski * * 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. */ /** * (c) 2010 Tobias Sarnowski * All rights reserved. */ package org.onsteroids.eve.api.provider; /** * @author Tobias Sarnowski */ public abstract class AbstractApiService { private static final Logger LOG = LoggerFactory.getLogger(AbstractApiService.class); private ApiConnection apiConnection;
// Path: cdi/src/main/java/org/onsteroids/eve/api/InternalApiException.java // public final class InternalApiException extends ApiException { // private static final Logger LOG = LoggerFactory.getLogger(InternalApiException.class); // // public InternalApiException(String message) { // super(message); // } // // public InternalApiException(String message, Throwable cause) { // super(message, cause); // } // // public InternalApiException(Throwable cause) { // super(cause); // } // } // // Path: cdi/src/main/java/org/onsteroids/eve/api/cache/ApiCache.java // public interface ApiCache { // // /** // * @param apiResult the api result to cache // */ // void putApiResult(ApiResult apiResult); // // /** // * @param serverUri the api server uri // * @param xmlPath the xml path // * @param <T> an api result type // * @return the cached api result or null if apiresult not cached // */ // <T extends ApiResult> T getApiResult(Class<T> resultType, URI serverUri, String xmlPath); // // /** // * @param serverUri the api server uri // * @param xmlPath the xml path // * @param parameters the used parameters (can be null) // * @param <T> an api result type // * @return the cached api result or null if apiresult not cached // */ // <T extends ApiResult> T getApiResult(Class<T> resultType, URI serverUri, String xmlPath, Map<String,String> parameters); // // /** // * @param serverUri the api server uri // * @param xmlPath the xml path // * @param key the used api key (can be null) // * @param <T> an api result type // * @return the cached api result or null if apiresult not cached // */ // <T extends ApiResult> T getApiResult(Class<T> resultType, URI serverUri, String xmlPath, ApiKey key); // // /** // * @param serverUri the api server uri // * @param xmlPath the xml path // * @param key the used api key (can be null) // * @param parameters the used parameters (can be null) // * @param <T> an api result type // * @return the cached api result or null if apiresult not cached // */ // <T extends ApiResult> T getApiResult(Class<T> resultType, URI serverUri, String xmlPath, ApiKey key, Map<String,String> parameters); // // } // // Path: cdi/src/main/java/org/onsteroids/eve/api/connector/ApiConnection.java // public interface ApiConnection { // // /** // * @return the used server URI // */ // URI getServerUri(); // // // /** // * @param xmlPath e.g. /server/ServerStatus.xml.aspx // * @return the returned response from the server // * @throws ApiException // */ // XmlApiResult call(String xmlPath) throws ApiException; // // /** // * @param xmlPath e.g. /server/ServerStatus.xml.aspx // * @param parameters additional parameters to provide, e.g. characterID // * @return the returned response from the server // * @throws ApiException // */ // XmlApiResult call(String xmlPath, Map<String,String> parameters) throws ApiException; // // /** // * @param xmlPath e.g. /server/ServerStatus.xml.aspx // * @param key the API key to authenticate against // * @return the returned response from the server // * @throws ApiException // */ // XmlApiResult call(String xmlPath, ApiKey key) throws ApiException; // // /** // * @param xmlPath e.g. /server/ServerStatus.xml.aspx // * @param key the API key to authenticate against // * @param parameters additional parameters to provide, e.g. characterID // * @return the returned response from the server // * @throws ApiException // */ // XmlApiResult call(String xmlPath, ApiKey key, Map<String,String> parameters) throws ApiException; // // } // // Path: cdi/src/main/java/org/onsteroids/eve/api/connector/XmlApiResult.java // public interface XmlApiResult extends ApiResult { // // /** // * @return returns the &lt;result&gt; node of the api response // */ // Node getResult(); // // /** // * getTimeDifference = serverTime - localTime // * // * @return the time difference from server to local in milliseconds // */ // long getTimeDifference(); // // } // Path: cdi/src/main/java/org/onsteroids/eve/api/provider/AbstractApiService.java import java.util.Map; import com.eveonline.api.ApiKey; import com.eveonline.api.exceptions.ApiException; import com.eveonline.api.server.ServerStatusApi; import com.google.common.collect.Maps; import org.onsteroids.eve.api.InternalApiException; import org.onsteroids.eve.api.cache.ApiCache; import org.onsteroids.eve.api.connector.ApiConnection; import org.onsteroids.eve.api.connector.XmlApiResult; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Copyright 2010 Tobias Sarnowski * * 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. */ /** * (c) 2010 Tobias Sarnowski * All rights reserved. */ package org.onsteroids.eve.api.provider; /** * @author Tobias Sarnowski */ public abstract class AbstractApiService { private static final Logger LOG = LoggerFactory.getLogger(AbstractApiService.class); private ApiConnection apiConnection;
private ApiCache apiCache;
sarnowski/eve-api
examples/javase/src/main/java/org/onsteroids/eve/api/examples/javase/ServerStatusApp.java
// Path: cdi/src/main/java/org/onsteroids/eve/api/Api.java // public interface Api { // // /** // * @param apiService the API service type to retrieve // * @param <T> the service definition // * @return the ready-to-use API service instance // */ // <T extends ApiService> T get(Class<T> apiService); // // } // // Path: weld/src/main/java/org/onsteroids/eve/api/WeldApi.java // public final class WeldApi implements Api { // private static final Logger LOG = LoggerFactory.getLogger(WeldApi.class); // // private static Weld weld; // private static WeldContainer weldContainer; // // WeldApi() { // // } // // public static Api createApi() { // if (weld == null) { // weld = new Weld(); // weldContainer = weld.initialize(); // } // return new WeldApi(); // } // // public synchronized static void shutdownApi() { // Preconditions.checkNotNull(weld, "Weld not running"); // weld.shutdown(); // weld = null; // weldContainer = null; // } // // @Override // public <T extends ApiService> T get(Class<T> apiService) { // Preconditions.checkNotNull(weld, "Weld not running"); // return weldContainer.instance().select(apiService).get(); // } // }
import com.eveonline.api.exceptions.ApiException; import com.eveonline.api.server.ServerStatus; import com.eveonline.api.server.ServerStatusApi; import org.onsteroids.eve.api.Api; import org.onsteroids.eve.api.WeldApi;
package org.onsteroids.eve.api.examples.javase; /** * @author Tobias Sarnowski */ public class ServerStatusApp { public static void main(String[] args) {
// Path: cdi/src/main/java/org/onsteroids/eve/api/Api.java // public interface Api { // // /** // * @param apiService the API service type to retrieve // * @param <T> the service definition // * @return the ready-to-use API service instance // */ // <T extends ApiService> T get(Class<T> apiService); // // } // // Path: weld/src/main/java/org/onsteroids/eve/api/WeldApi.java // public final class WeldApi implements Api { // private static final Logger LOG = LoggerFactory.getLogger(WeldApi.class); // // private static Weld weld; // private static WeldContainer weldContainer; // // WeldApi() { // // } // // public static Api createApi() { // if (weld == null) { // weld = new Weld(); // weldContainer = weld.initialize(); // } // return new WeldApi(); // } // // public synchronized static void shutdownApi() { // Preconditions.checkNotNull(weld, "Weld not running"); // weld.shutdown(); // weld = null; // weldContainer = null; // } // // @Override // public <T extends ApiService> T get(Class<T> apiService) { // Preconditions.checkNotNull(weld, "Weld not running"); // return weldContainer.instance().select(apiService).get(); // } // } // Path: examples/javase/src/main/java/org/onsteroids/eve/api/examples/javase/ServerStatusApp.java import com.eveonline.api.exceptions.ApiException; import com.eveonline.api.server.ServerStatus; import com.eveonline.api.server.ServerStatusApi; import org.onsteroids.eve.api.Api; import org.onsteroids.eve.api.WeldApi; package org.onsteroids.eve.api.examples.javase; /** * @author Tobias Sarnowski */ public class ServerStatusApp { public static void main(String[] args) {
Api api = WeldApi.createApi();
sarnowski/eve-api
examples/javase/src/main/java/org/onsteroids/eve/api/examples/javase/ServerStatusApp.java
// Path: cdi/src/main/java/org/onsteroids/eve/api/Api.java // public interface Api { // // /** // * @param apiService the API service type to retrieve // * @param <T> the service definition // * @return the ready-to-use API service instance // */ // <T extends ApiService> T get(Class<T> apiService); // // } // // Path: weld/src/main/java/org/onsteroids/eve/api/WeldApi.java // public final class WeldApi implements Api { // private static final Logger LOG = LoggerFactory.getLogger(WeldApi.class); // // private static Weld weld; // private static WeldContainer weldContainer; // // WeldApi() { // // } // // public static Api createApi() { // if (weld == null) { // weld = new Weld(); // weldContainer = weld.initialize(); // } // return new WeldApi(); // } // // public synchronized static void shutdownApi() { // Preconditions.checkNotNull(weld, "Weld not running"); // weld.shutdown(); // weld = null; // weldContainer = null; // } // // @Override // public <T extends ApiService> T get(Class<T> apiService) { // Preconditions.checkNotNull(weld, "Weld not running"); // return weldContainer.instance().select(apiService).get(); // } // }
import com.eveonline.api.exceptions.ApiException; import com.eveonline.api.server.ServerStatus; import com.eveonline.api.server.ServerStatusApi; import org.onsteroids.eve.api.Api; import org.onsteroids.eve.api.WeldApi;
package org.onsteroids.eve.api.examples.javase; /** * @author Tobias Sarnowski */ public class ServerStatusApp { public static void main(String[] args) {
// Path: cdi/src/main/java/org/onsteroids/eve/api/Api.java // public interface Api { // // /** // * @param apiService the API service type to retrieve // * @param <T> the service definition // * @return the ready-to-use API service instance // */ // <T extends ApiService> T get(Class<T> apiService); // // } // // Path: weld/src/main/java/org/onsteroids/eve/api/WeldApi.java // public final class WeldApi implements Api { // private static final Logger LOG = LoggerFactory.getLogger(WeldApi.class); // // private static Weld weld; // private static WeldContainer weldContainer; // // WeldApi() { // // } // // public static Api createApi() { // if (weld == null) { // weld = new Weld(); // weldContainer = weld.initialize(); // } // return new WeldApi(); // } // // public synchronized static void shutdownApi() { // Preconditions.checkNotNull(weld, "Weld not running"); // weld.shutdown(); // weld = null; // weldContainer = null; // } // // @Override // public <T extends ApiService> T get(Class<T> apiService) { // Preconditions.checkNotNull(weld, "Weld not running"); // return weldContainer.instance().select(apiService).get(); // } // } // Path: examples/javase/src/main/java/org/onsteroids/eve/api/examples/javase/ServerStatusApp.java import com.eveonline.api.exceptions.ApiException; import com.eveonline.api.server.ServerStatus; import com.eveonline.api.server.ServerStatusApi; import org.onsteroids.eve.api.Api; import org.onsteroids.eve.api.WeldApi; package org.onsteroids.eve.api.examples.javase; /** * @author Tobias Sarnowski */ public class ServerStatusApp { public static void main(String[] args) {
Api api = WeldApi.createApi();
sarnowski/eve-api
cdi/src/main/java/org/onsteroids/eve/api/provider/SerializableApiResult.java
// Path: cdi/src/main/java/org/onsteroids/eve/api/connector/XmlApiResult.java // public interface XmlApiResult extends ApiResult { // // /** // * @return returns the &lt;result&gt; node of the api response // */ // Node getResult(); // // /** // * getTimeDifference = serverTime - localTime // * // * @return the time difference from server to local in milliseconds // */ // long getTimeDifference(); // // }
import java.util.Map; import com.eveonline.api.ApiKey; import com.eveonline.api.ApiResult; import com.eveonline.api.exceptions.ApiException; import com.google.common.base.Preconditions; import org.onsteroids.eve.api.connector.XmlApiResult; import org.w3c.dom.Node; import java.io.Serializable; import java.net.URI; import java.util.Date;
/** * Copyright 2010 Tobias Sarnowski * * 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. */ /** * (c) 2010 Tobias Sarnowski * All rights reserved. */ package org.onsteroids.eve.api.provider; /** * @author Tobias Sarnowski */ public abstract class SerializableApiResult implements ApiResult, Serializable { private Date created; private Date cachedUntil; private long timeDifference; private String requestedXmlPath; private ApiKey usedApiKey; private Map<String,String> usedParameters; private URI usedServerUri; public SerializableApiResult() { }
// Path: cdi/src/main/java/org/onsteroids/eve/api/connector/XmlApiResult.java // public interface XmlApiResult extends ApiResult { // // /** // * @return returns the &lt;result&gt; node of the api response // */ // Node getResult(); // // /** // * getTimeDifference = serverTime - localTime // * // * @return the time difference from server to local in milliseconds // */ // long getTimeDifference(); // // } // Path: cdi/src/main/java/org/onsteroids/eve/api/provider/SerializableApiResult.java import java.util.Map; import com.eveonline.api.ApiKey; import com.eveonline.api.ApiResult; import com.eveonline.api.exceptions.ApiException; import com.google.common.base.Preconditions; import org.onsteroids.eve.api.connector.XmlApiResult; import org.w3c.dom.Node; import java.io.Serializable; import java.net.URI; import java.util.Date; /** * Copyright 2010 Tobias Sarnowski * * 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. */ /** * (c) 2010 Tobias Sarnowski * All rights reserved. */ package org.onsteroids.eve.api.provider; /** * @author Tobias Sarnowski */ public abstract class SerializableApiResult implements ApiResult, Serializable { private Date created; private Date cachedUntil; private long timeDifference; private String requestedXmlPath; private ApiKey usedApiKey; private Map<String,String> usedParameters; private URI usedServerUri; public SerializableApiResult() { }
public SerializableApiResult(XmlApiResult xmlApiResult, Node node) throws ApiException {
sarnowski/eve-api
cdi/src/main/java/org/onsteroids/eve/api/provider/img/DefaultCharacterPortraitApi.java
// Path: cdi/src/main/java/org/onsteroids/eve/api/InternalApiException.java // public final class InternalApiException extends ApiException { // private static final Logger LOG = LoggerFactory.getLogger(InternalApiException.class); // // public InternalApiException(String message) { // super(message); // } // // public InternalApiException(String message, Throwable cause) { // super(message, cause); // } // // public InternalApiException(Throwable cause) { // super(cause); // } // }
import com.eveonline.api.exceptions.ApiException; import com.eveonline.api.img.CharacterPortrait; import com.eveonline.api.img.CharacterPortraitApi; import com.google.common.collect.Lists; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.utils.URIUtils; import org.apache.http.client.utils.URLEncodedUtils; import org.apache.http.message.BasicNameValuePair; import org.onsteroids.eve.api.InternalApiException; import org.onsteroids.eve.api.connector.http.ApiClient; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.inject.Inject; import javax.inject.Provider; import javax.inject.Singleton; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.List;
/** * Copyright 2010 Tobias Sarnowski * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onsteroids.eve.api.provider.img; /** * @author Tobias Sarnowski */ @Singleton final class DefaultCharacterPortraitApi implements CharacterPortraitApi { private static final Logger LOG = LoggerFactory.getLogger(DefaultCharacterPortraitApi.class); private static final String FORMAT = "image/jpeg"; private final Provider<HttpClient> httpClientProvider; private final URI serverUri; @Inject public DefaultCharacterPortraitApi(@ApiClient Provider<HttpClient> httpClientProvider) throws URISyntaxException { this.httpClientProvider = httpClientProvider; serverUri = new URI(CharacterPortraitApi.URL); } @Override public CharacterPortrait getCharacterPortrait(long characterId, PortraitSize size) throws ApiException { HttpClient httpClient = httpClientProvider.get(); List<NameValuePair> qparams = Lists.newArrayList(); qparams.add(new BasicNameValuePair("c", Long.toString(characterId))); qparams.add(new BasicNameValuePair("s", Integer.toString(size.getSize()))); final URI requestURI; try { requestURI = URIUtils.createURI( serverUri.getScheme(), serverUri.getHost(), serverUri.getPort(), serverUri.getPath(), URLEncodedUtils.format(qparams, "UTF-8"), null ); } catch (URISyntaxException e) {
// Path: cdi/src/main/java/org/onsteroids/eve/api/InternalApiException.java // public final class InternalApiException extends ApiException { // private static final Logger LOG = LoggerFactory.getLogger(InternalApiException.class); // // public InternalApiException(String message) { // super(message); // } // // public InternalApiException(String message, Throwable cause) { // super(message, cause); // } // // public InternalApiException(Throwable cause) { // super(cause); // } // } // Path: cdi/src/main/java/org/onsteroids/eve/api/provider/img/DefaultCharacterPortraitApi.java import com.eveonline.api.exceptions.ApiException; import com.eveonline.api.img.CharacterPortrait; import com.eveonline.api.img.CharacterPortraitApi; import com.google.common.collect.Lists; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.utils.URIUtils; import org.apache.http.client.utils.URLEncodedUtils; import org.apache.http.message.BasicNameValuePair; import org.onsteroids.eve.api.InternalApiException; import org.onsteroids.eve.api.connector.http.ApiClient; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.inject.Inject; import javax.inject.Provider; import javax.inject.Singleton; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.List; /** * Copyright 2010 Tobias Sarnowski * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onsteroids.eve.api.provider.img; /** * @author Tobias Sarnowski */ @Singleton final class DefaultCharacterPortraitApi implements CharacterPortraitApi { private static final Logger LOG = LoggerFactory.getLogger(DefaultCharacterPortraitApi.class); private static final String FORMAT = "image/jpeg"; private final Provider<HttpClient> httpClientProvider; private final URI serverUri; @Inject public DefaultCharacterPortraitApi(@ApiClient Provider<HttpClient> httpClientProvider) throws URISyntaxException { this.httpClientProvider = httpClientProvider; serverUri = new URI(CharacterPortraitApi.URL); } @Override public CharacterPortrait getCharacterPortrait(long characterId, PortraitSize size) throws ApiException { HttpClient httpClient = httpClientProvider.get(); List<NameValuePair> qparams = Lists.newArrayList(); qparams.add(new BasicNameValuePair("c", Long.toString(characterId))); qparams.add(new BasicNameValuePair("s", Integer.toString(size.getSize()))); final URI requestURI; try { requestURI = URIUtils.createURI( serverUri.getScheme(), serverUri.getHost(), serverUri.getPort(), serverUri.getPath(), URLEncodedUtils.format(qparams, "UTF-8"), null ); } catch (URISyntaxException e) {
throw new InternalApiException(e);
sarnowski/eve-api
cdi/src/main/java/org/onsteroids/eve/api/provider/SerializableApiListResult.java
// Path: cdi/src/main/java/org/onsteroids/eve/api/InternalApiException.java // public final class InternalApiException extends ApiException { // private static final Logger LOG = LoggerFactory.getLogger(InternalApiException.class); // // public InternalApiException(String message) { // super(message); // } // // public InternalApiException(String message, Throwable cause) { // super(message, cause); // } // // public InternalApiException(Throwable cause) { // super(cause); // } // } // // Path: cdi/src/main/java/org/onsteroids/eve/api/XmlUtility.java // public final class XmlUtility { // private static final Logger LOG = LoggerFactory.getLogger(XmlUtility.class); // // private Node node; // // public XmlUtility(Node node) { // this.node = Preconditions.checkNotNull(node, "Node"); // } // // // public Node getNodeByName(String name) { // return getNodeByName(name, node); // } // // public static Node getNodeByName(String name, Node parent) { // Preconditions.checkNotNull(name, "Name"); // Preconditions.checkNotNull(parent, "Parent"); // NodeList list = parent.getChildNodes(); // for (int n = 0; n < list.getLength(); n++) { // Node node = list.item(n); // if (name.equals(node.getNodeName())) { // return node; // } // } // throw new IllegalArgumentException("Node " + name + " not found"); // } // // // public boolean hasNodeWithName(String name) { // return hasNodeWithName(name, node); // } // // public static boolean hasNodeWithName(String name, Node parent) { // Preconditions.checkNotNull(name, "Name"); // Preconditions.checkNotNull(parent, "Parent"); // NodeList list = parent.getChildNodes(); // for (int n = 0; n < list.getLength(); n++) { // Node node = list.item(n); // if (name.equals(node.getNodeName())) { // return true; // } // } // return false; // } // // // public List<Node> getNodesByName(String name) { // return getNodesByName(name, node); // } // // public static List<Node> getNodesByName(String name, Node parent) { // Preconditions.checkNotNull(name, "Name"); // Preconditions.checkNotNull(parent, "Parent"); // List<Node> nodes = Lists.newArrayList(); // NodeList list = parent.getChildNodes(); // for (int n = 0; n < list.getLength(); n++) { // Node node = list.item(n); // if (name.equals(node.getNodeName())) { // nodes.add(node); // } // } // return nodes; // } // // // public String getContentOf(String nodeName) { // return getContentOf(nodeName, node); // } // // public static String getContentOf(String nodeName, Node node) { // Preconditions.checkNotNull(nodeName, "nodeName"); // Preconditions.checkNotNull(node, "node"); // return getNodeByName(nodeName, node).getTextContent(); // } // // // public String getAttribute(String name) { // return getAttribute(name, node); // } // // public static String getAttribute(String name, Node node) { // Preconditions.checkNotNull(name, "Name"); // Preconditions.checkNotNull(node, "Node"); // Preconditions.checkNotNull(node.getAttributes().getNamedItem(name), "Attribute not found: " + name); // return node.getAttributes().getNamedItem(name).getTextContent(); // } // } // // Path: cdi/src/main/java/org/onsteroids/eve/api/connector/XmlApiResult.java // public interface XmlApiResult extends ApiResult { // // /** // * @return returns the &lt;result&gt; node of the api response // */ // Node getResult(); // // /** // * getTimeDifference = serverTime - localTime // * // * @return the time difference from server to local in milliseconds // */ // long getTimeDifference(); // // }
import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import com.eveonline.api.ApiListResult; import com.eveonline.api.exceptions.ApiException; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import org.onsteroids.eve.api.InternalApiException; import org.onsteroids.eve.api.XmlUtility; import org.onsteroids.eve.api.connector.XmlApiResult; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Node;
/** * Copyright 2010 Tobias Sarnowski * * 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. */ /** * (c) 2010 Tobias Sarnowski * All rights reserved. */ package org.onsteroids.eve.api.provider; /** * @author Tobias Sarnowski */ public abstract class SerializableApiListResult<S extends SerializableApiResult> extends SerializableApiResult implements ApiListResult<S> { // because java doesn't support multi inheritance we have to choose between SerializableApiResult and ForwardingList // from google collections. We want to be immutable and using all features of ApiResult which can change quite often // so we implement the forwarding, immutable list ourself. private static final Logger LOG = LoggerFactory.getLogger(SerializableApiListResult.class); private List<S> results; public SerializableApiListResult() { }
// Path: cdi/src/main/java/org/onsteroids/eve/api/InternalApiException.java // public final class InternalApiException extends ApiException { // private static final Logger LOG = LoggerFactory.getLogger(InternalApiException.class); // // public InternalApiException(String message) { // super(message); // } // // public InternalApiException(String message, Throwable cause) { // super(message, cause); // } // // public InternalApiException(Throwable cause) { // super(cause); // } // } // // Path: cdi/src/main/java/org/onsteroids/eve/api/XmlUtility.java // public final class XmlUtility { // private static final Logger LOG = LoggerFactory.getLogger(XmlUtility.class); // // private Node node; // // public XmlUtility(Node node) { // this.node = Preconditions.checkNotNull(node, "Node"); // } // // // public Node getNodeByName(String name) { // return getNodeByName(name, node); // } // // public static Node getNodeByName(String name, Node parent) { // Preconditions.checkNotNull(name, "Name"); // Preconditions.checkNotNull(parent, "Parent"); // NodeList list = parent.getChildNodes(); // for (int n = 0; n < list.getLength(); n++) { // Node node = list.item(n); // if (name.equals(node.getNodeName())) { // return node; // } // } // throw new IllegalArgumentException("Node " + name + " not found"); // } // // // public boolean hasNodeWithName(String name) { // return hasNodeWithName(name, node); // } // // public static boolean hasNodeWithName(String name, Node parent) { // Preconditions.checkNotNull(name, "Name"); // Preconditions.checkNotNull(parent, "Parent"); // NodeList list = parent.getChildNodes(); // for (int n = 0; n < list.getLength(); n++) { // Node node = list.item(n); // if (name.equals(node.getNodeName())) { // return true; // } // } // return false; // } // // // public List<Node> getNodesByName(String name) { // return getNodesByName(name, node); // } // // public static List<Node> getNodesByName(String name, Node parent) { // Preconditions.checkNotNull(name, "Name"); // Preconditions.checkNotNull(parent, "Parent"); // List<Node> nodes = Lists.newArrayList(); // NodeList list = parent.getChildNodes(); // for (int n = 0; n < list.getLength(); n++) { // Node node = list.item(n); // if (name.equals(node.getNodeName())) { // nodes.add(node); // } // } // return nodes; // } // // // public String getContentOf(String nodeName) { // return getContentOf(nodeName, node); // } // // public static String getContentOf(String nodeName, Node node) { // Preconditions.checkNotNull(nodeName, "nodeName"); // Preconditions.checkNotNull(node, "node"); // return getNodeByName(nodeName, node).getTextContent(); // } // // // public String getAttribute(String name) { // return getAttribute(name, node); // } // // public static String getAttribute(String name, Node node) { // Preconditions.checkNotNull(name, "Name"); // Preconditions.checkNotNull(node, "Node"); // Preconditions.checkNotNull(node.getAttributes().getNamedItem(name), "Attribute not found: " + name); // return node.getAttributes().getNamedItem(name).getTextContent(); // } // } // // Path: cdi/src/main/java/org/onsteroids/eve/api/connector/XmlApiResult.java // public interface XmlApiResult extends ApiResult { // // /** // * @return returns the &lt;result&gt; node of the api response // */ // Node getResult(); // // /** // * getTimeDifference = serverTime - localTime // * // * @return the time difference from server to local in milliseconds // */ // long getTimeDifference(); // // } // Path: cdi/src/main/java/org/onsteroids/eve/api/provider/SerializableApiListResult.java import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import com.eveonline.api.ApiListResult; import com.eveonline.api.exceptions.ApiException; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import org.onsteroids.eve.api.InternalApiException; import org.onsteroids.eve.api.XmlUtility; import org.onsteroids.eve.api.connector.XmlApiResult; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Node; /** * Copyright 2010 Tobias Sarnowski * * 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. */ /** * (c) 2010 Tobias Sarnowski * All rights reserved. */ package org.onsteroids.eve.api.provider; /** * @author Tobias Sarnowski */ public abstract class SerializableApiListResult<S extends SerializableApiResult> extends SerializableApiResult implements ApiListResult<S> { // because java doesn't support multi inheritance we have to choose between SerializableApiResult and ForwardingList // from google collections. We want to be immutable and using all features of ApiResult which can change quite often // so we implement the forwarding, immutable list ourself. private static final Logger LOG = LoggerFactory.getLogger(SerializableApiListResult.class); private List<S> results; public SerializableApiListResult() { }
public SerializableApiListResult(XmlApiResult xmlApiResult, Node xmlResult) throws ApiException {
ceaseless-prayer/CeaselessAndroid
app/src/main/java/org/theotech/ceaselessandroid/notification/DailyNotificationReceiver.java
// Path: app/src/main/java/org/theotech/ceaselessandroid/prefs/TimePickerDialogPreference.java // public class TimePickerDialogPreference extends DialogPreference { // private static final String TAG = TimePickerDialogPreference.class.getSimpleName(); // // private int lastHour = 0; // private int lastMinute = 0; // private TimePicker picker = null; // private TextView timeView = null; // // public TimePickerDialogPreference(Context ctxt, AttributeSet attrs) { // super(ctxt, attrs); // } // // public static int getHour(String time) { // String[] pieces = time.split(":"); // return Integer.parseInt(pieces[0]); // } // // public static int getMinute(String time) { // String[] pieces = time.split(":"); // return Integer.parseInt(pieces[1]); // } // // @Override // protected View onCreateDialogView() { // picker = new TimePicker(getContext()); // return picker; // } // // @Override // protected void onBindDialogView(View v) { // super.onBindDialogView(v); // picker.setCurrentHour(lastHour); // picker.setCurrentMinute(lastMinute); // } // // @Override // protected void onBindView(View v) { // super.onBindView(v); // timeView = (TextView) v.findViewById(R.id.timeTextView); // timeView.setText(getPersistedString(getContext().getString(R.string.default_notification_time))); // } // // @Override // protected void onDialogClosed(boolean positiveResult) { // super.onDialogClosed(positiveResult); // // if (positiveResult) { // lastHour = picker.getCurrentHour(); // lastMinute = picker.getCurrentMinute(); // // String time = String.format("%02d", lastHour) + ":" + String.format("%02d", lastMinute); // // if (callChangeListener(time)) { // persistString(time); // } // // timeView.setText(getPersistedString(getContext().getString(R.string.default_notification_time))); // } // } // // @Override // protected Object onGetDefaultValue(TypedArray a, int index) { // return (a.getString(index)); // } // // @Override // protected void onSetInitialValue(boolean restoreValue, Object defaultValue) { // String time = null; // // if (restoreValue) { // if (defaultValue == null) { // time = getPersistedString("00:00"); // } // } else { // time = defaultValue.toString(); // } // // lastHour = getHour(time); // lastMinute = getMinute(time); // } // }
import android.app.AlarmManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Build; import android.preference.PreferenceManager; import androidx.annotation.NonNull; import android.util.Log; import org.theotech.ceaselessandroid.prefs.TimePickerDialogPreference; import java.util.Calendar;
// you can add buffer time too here to ignore some small differences in milliseconds Log.d(TAG, "setting alarm for same day."); setNotificationAlarm(pendingIntent, alarmManager, intendedTime); } else { // set from next day // you might consider using calendar.add() for adding one day to the current day Log.d(TAG, "Setting alarm for next day"); firingCal.add(Calendar.DAY_OF_MONTH, 1); intendedTime = firingCal.getTimeInMillis(); setNotificationAlarm(pendingIntent, alarmManager, intendedTime); } } else { Log.d(TAG, "No repeating alarm set since notifications are off."); } } private void setNotificationAlarm(PendingIntent pendingIntent, AlarmManager alarmManager, long intendedTime) { Log.d(TAG, "Setting intended time to " + intendedTime); alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, intendedTime, AlarmManager.INTERVAL_DAY, pendingIntent); } @NonNull private Calendar getNotificationFiringCalendar(String time) { Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.MILLISECOND, 0); calendar.set(Calendar.SECOND, 0);
// Path: app/src/main/java/org/theotech/ceaselessandroid/prefs/TimePickerDialogPreference.java // public class TimePickerDialogPreference extends DialogPreference { // private static final String TAG = TimePickerDialogPreference.class.getSimpleName(); // // private int lastHour = 0; // private int lastMinute = 0; // private TimePicker picker = null; // private TextView timeView = null; // // public TimePickerDialogPreference(Context ctxt, AttributeSet attrs) { // super(ctxt, attrs); // } // // public static int getHour(String time) { // String[] pieces = time.split(":"); // return Integer.parseInt(pieces[0]); // } // // public static int getMinute(String time) { // String[] pieces = time.split(":"); // return Integer.parseInt(pieces[1]); // } // // @Override // protected View onCreateDialogView() { // picker = new TimePicker(getContext()); // return picker; // } // // @Override // protected void onBindDialogView(View v) { // super.onBindDialogView(v); // picker.setCurrentHour(lastHour); // picker.setCurrentMinute(lastMinute); // } // // @Override // protected void onBindView(View v) { // super.onBindView(v); // timeView = (TextView) v.findViewById(R.id.timeTextView); // timeView.setText(getPersistedString(getContext().getString(R.string.default_notification_time))); // } // // @Override // protected void onDialogClosed(boolean positiveResult) { // super.onDialogClosed(positiveResult); // // if (positiveResult) { // lastHour = picker.getCurrentHour(); // lastMinute = picker.getCurrentMinute(); // // String time = String.format("%02d", lastHour) + ":" + String.format("%02d", lastMinute); // // if (callChangeListener(time)) { // persistString(time); // } // // timeView.setText(getPersistedString(getContext().getString(R.string.default_notification_time))); // } // } // // @Override // protected Object onGetDefaultValue(TypedArray a, int index) { // return (a.getString(index)); // } // // @Override // protected void onSetInitialValue(boolean restoreValue, Object defaultValue) { // String time = null; // // if (restoreValue) { // if (defaultValue == null) { // time = getPersistedString("00:00"); // } // } else { // time = defaultValue.toString(); // } // // lastHour = getHour(time); // lastMinute = getMinute(time); // } // } // Path: app/src/main/java/org/theotech/ceaselessandroid/notification/DailyNotificationReceiver.java import android.app.AlarmManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Build; import android.preference.PreferenceManager; import androidx.annotation.NonNull; import android.util.Log; import org.theotech.ceaselessandroid.prefs.TimePickerDialogPreference; import java.util.Calendar; // you can add buffer time too here to ignore some small differences in milliseconds Log.d(TAG, "setting alarm for same day."); setNotificationAlarm(pendingIntent, alarmManager, intendedTime); } else { // set from next day // you might consider using calendar.add() for adding one day to the current day Log.d(TAG, "Setting alarm for next day"); firingCal.add(Calendar.DAY_OF_MONTH, 1); intendedTime = firingCal.getTimeInMillis(); setNotificationAlarm(pendingIntent, alarmManager, intendedTime); } } else { Log.d(TAG, "No repeating alarm set since notifications are off."); } } private void setNotificationAlarm(PendingIntent pendingIntent, AlarmManager alarmManager, long intendedTime) { Log.d(TAG, "Setting intended time to " + intendedTime); alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, intendedTime, AlarmManager.INTERVAL_DAY, pendingIntent); } @NonNull private Calendar getNotificationFiringCalendar(String time) { Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.MILLISECOND, 0); calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MINUTE, TimePickerDialogPreference.getMinute(time));
ceaseless-prayer/CeaselessAndroid
app/src/main/java/org/theotech/ceaselessandroid/tutorial/HTFDemoPersonFragment.java
// Path: app/src/main/java/org/theotech/ceaselessandroid/util/Constants.java // public class Constants { // public static final int NUM_AUXILIARY_CARDS = 2; // public static final int SCHEMA_VERSION = 0; // public static final String REALM_FILE_NAME = "org.theotech.ceaselessandroid"; // // public static final String HOME_SECTION_NUMBER_BUNDLE_ARG = "homeSectionNumber"; // public static final String USE_CACHE_BUNDLE_ARG = "useCache"; // public static final String PERSON_ID_BUNDLE_ARG = "personId"; // public static final String NOTE_ID_BUNDLE_ARG = "noteId"; // public static final String NEXT_BACKGROUND_IMAGE = "nextBackgroundImage"; // public static final String CURRENT_BACKGROUND_IMAGE = "currentBackgroundImage"; // public static final String PRESELECTED_PERSON_NAME = "preselectedPersonName"; // public static final String PRESELECTED_PERSON_ID = "preselectedPersonId"; // // public static final String SHOW_PERSON_INTENT = "org.theotech.ceaselessandroid.SHOW_PERSON"; // public static final String SHOW_NOTE_INTENT = "org.theotech.ceaselessandroid.SHOW_NOTE"; // public static final String DEFAULT_PREFERENCES_FILE = "org.theotech.ceaselessandroid_preferences"; // // public static final String NUMBER_OF_PEOPLE_TO_PRAY_FOR = "numberOfPeopleToPrayForDaily"; // // public static final String DEMO_NAME_BUNDLE_ARG = "demoName"; // public static final String DEMO_TOOLTIP_BUNDLE_ARG = "demoShowToolTip"; // // public static final String DEFAULT_CEASELESS_CHANNEL_ID = "ceaselessPrayerReminders"; // }
import android.app.Activity; import android.os.Bundle; import androidx.fragment.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.view.animation.LinearInterpolator; import android.view.animation.TranslateAnimation; import android.widget.ArrayAdapter; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.PopupMenu; import android.widget.RelativeLayout; import android.widget.TextView; import com.joanzapata.iconify.widget.IconTextView; import com.makeramen.roundedimageview.RoundedImageView; import com.squareup.picasso.Picasso; import org.theotech.ceaselessandroid.R; import org.theotech.ceaselessandroid.util.Constants; import butterknife.BindView; import butterknife.ButterKnife;
@BindView(R.id.message_tooltip) RelativeLayout messageTooltip; @BindView(R.id.add_note_tooltip) RelativeLayout addNoteTooltip; @BindView(R.id.tool_tip_one) RelativeLayout toolTipOne; @BindView(R.id.tool_tip_two) TextView toolTipTwo; @BindView(R.id.tool_tip_four) LinearLayout toolTipFour; @BindView(R.id.up_arrow) IconTextView upArrow; @BindView(R.id.right_arrow) IconTextView rightArrow; private boolean showToolTip; private int sceneNum = 0; private PopupMenu popup; private View view; private boolean menuItemClicked = false; public HTFDemoPersonFragment() { // Required empty public constructor } public static HTFDemoPersonFragment newInstance(String personName, boolean showToolTip) { HTFDemoPersonFragment fragment = new HTFDemoPersonFragment(); Bundle args = new Bundle();
// Path: app/src/main/java/org/theotech/ceaselessandroid/util/Constants.java // public class Constants { // public static final int NUM_AUXILIARY_CARDS = 2; // public static final int SCHEMA_VERSION = 0; // public static final String REALM_FILE_NAME = "org.theotech.ceaselessandroid"; // // public static final String HOME_SECTION_NUMBER_BUNDLE_ARG = "homeSectionNumber"; // public static final String USE_CACHE_BUNDLE_ARG = "useCache"; // public static final String PERSON_ID_BUNDLE_ARG = "personId"; // public static final String NOTE_ID_BUNDLE_ARG = "noteId"; // public static final String NEXT_BACKGROUND_IMAGE = "nextBackgroundImage"; // public static final String CURRENT_BACKGROUND_IMAGE = "currentBackgroundImage"; // public static final String PRESELECTED_PERSON_NAME = "preselectedPersonName"; // public static final String PRESELECTED_PERSON_ID = "preselectedPersonId"; // // public static final String SHOW_PERSON_INTENT = "org.theotech.ceaselessandroid.SHOW_PERSON"; // public static final String SHOW_NOTE_INTENT = "org.theotech.ceaselessandroid.SHOW_NOTE"; // public static final String DEFAULT_PREFERENCES_FILE = "org.theotech.ceaselessandroid_preferences"; // // public static final String NUMBER_OF_PEOPLE_TO_PRAY_FOR = "numberOfPeopleToPrayForDaily"; // // public static final String DEMO_NAME_BUNDLE_ARG = "demoName"; // public static final String DEMO_TOOLTIP_BUNDLE_ARG = "demoShowToolTip"; // // public static final String DEFAULT_CEASELESS_CHANNEL_ID = "ceaselessPrayerReminders"; // } // Path: app/src/main/java/org/theotech/ceaselessandroid/tutorial/HTFDemoPersonFragment.java import android.app.Activity; import android.os.Bundle; import androidx.fragment.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.view.animation.LinearInterpolator; import android.view.animation.TranslateAnimation; import android.widget.ArrayAdapter; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.PopupMenu; import android.widget.RelativeLayout; import android.widget.TextView; import com.joanzapata.iconify.widget.IconTextView; import com.makeramen.roundedimageview.RoundedImageView; import com.squareup.picasso.Picasso; import org.theotech.ceaselessandroid.R; import org.theotech.ceaselessandroid.util.Constants; import butterknife.BindView; import butterknife.ButterKnife; @BindView(R.id.message_tooltip) RelativeLayout messageTooltip; @BindView(R.id.add_note_tooltip) RelativeLayout addNoteTooltip; @BindView(R.id.tool_tip_one) RelativeLayout toolTipOne; @BindView(R.id.tool_tip_two) TextView toolTipTwo; @BindView(R.id.tool_tip_four) LinearLayout toolTipFour; @BindView(R.id.up_arrow) IconTextView upArrow; @BindView(R.id.right_arrow) IconTextView rightArrow; private boolean showToolTip; private int sceneNum = 0; private PopupMenu popup; private View view; private boolean menuItemClicked = false; public HTFDemoPersonFragment() { // Required empty public constructor } public static HTFDemoPersonFragment newInstance(String personName, boolean showToolTip) { HTFDemoPersonFragment fragment = new HTFDemoPersonFragment(); Bundle args = new Bundle();
args.putString(Constants.DEMO_NAME_BUNDLE_ARG, personName);
ceaseless-prayer/CeaselessAndroid
app/src/main/java/org/theotech/ceaselessandroid/CeaselessApplication.java
// Path: app/src/main/java/org/theotech/ceaselessandroid/util/Constants.java // public class Constants { // public static final int NUM_AUXILIARY_CARDS = 2; // public static final int SCHEMA_VERSION = 0; // public static final String REALM_FILE_NAME = "org.theotech.ceaselessandroid"; // // public static final String HOME_SECTION_NUMBER_BUNDLE_ARG = "homeSectionNumber"; // public static final String USE_CACHE_BUNDLE_ARG = "useCache"; // public static final String PERSON_ID_BUNDLE_ARG = "personId"; // public static final String NOTE_ID_BUNDLE_ARG = "noteId"; // public static final String NEXT_BACKGROUND_IMAGE = "nextBackgroundImage"; // public static final String CURRENT_BACKGROUND_IMAGE = "currentBackgroundImage"; // public static final String PRESELECTED_PERSON_NAME = "preselectedPersonName"; // public static final String PRESELECTED_PERSON_ID = "preselectedPersonId"; // // public static final String SHOW_PERSON_INTENT = "org.theotech.ceaselessandroid.SHOW_PERSON"; // public static final String SHOW_NOTE_INTENT = "org.theotech.ceaselessandroid.SHOW_NOTE"; // public static final String DEFAULT_PREFERENCES_FILE = "org.theotech.ceaselessandroid_preferences"; // // public static final String NUMBER_OF_PEOPLE_TO_PRAY_FOR = "numberOfPeopleToPrayForDaily"; // // public static final String DEMO_NAME_BUNDLE_ARG = "demoName"; // public static final String DEMO_TOOLTIP_BUNDLE_ARG = "demoShowToolTip"; // // public static final String DEFAULT_CEASELESS_CHANNEL_ID = "ceaselessPrayerReminders"; // }
import android.app.Application; import android.app.NotificationChannel; import android.app.NotificationManager; import android.os.Build; import com.crashlytics.android.Crashlytics; import com.joanzapata.iconify.Iconify; import com.joanzapata.iconify.fonts.FontAwesomeModule; import com.onesignal.OneSignal; import com.squareup.picasso.OkHttpDownloader; import com.squareup.picasso.Picasso; import org.theotech.ceaselessandroid.util.Constants; import io.fabric.sdk.android.Fabric; import io.realm.Realm; import io.realm.RealmConfiguration;
package org.theotech.ceaselessandroid; /** * Created by Andrew Ma on 10/5/15. */ public class CeaselessApplication extends Application { private void createNotificationChannel() { // Create the NotificationChannel, but only on API 26+ because // the NotificationChannel class is new and not in the support library if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { CharSequence name = getString(R.string.reminder_notification_title); int importance = NotificationManager.IMPORTANCE_DEFAULT;
// Path: app/src/main/java/org/theotech/ceaselessandroid/util/Constants.java // public class Constants { // public static final int NUM_AUXILIARY_CARDS = 2; // public static final int SCHEMA_VERSION = 0; // public static final String REALM_FILE_NAME = "org.theotech.ceaselessandroid"; // // public static final String HOME_SECTION_NUMBER_BUNDLE_ARG = "homeSectionNumber"; // public static final String USE_CACHE_BUNDLE_ARG = "useCache"; // public static final String PERSON_ID_BUNDLE_ARG = "personId"; // public static final String NOTE_ID_BUNDLE_ARG = "noteId"; // public static final String NEXT_BACKGROUND_IMAGE = "nextBackgroundImage"; // public static final String CURRENT_BACKGROUND_IMAGE = "currentBackgroundImage"; // public static final String PRESELECTED_PERSON_NAME = "preselectedPersonName"; // public static final String PRESELECTED_PERSON_ID = "preselectedPersonId"; // // public static final String SHOW_PERSON_INTENT = "org.theotech.ceaselessandroid.SHOW_PERSON"; // public static final String SHOW_NOTE_INTENT = "org.theotech.ceaselessandroid.SHOW_NOTE"; // public static final String DEFAULT_PREFERENCES_FILE = "org.theotech.ceaselessandroid_preferences"; // // public static final String NUMBER_OF_PEOPLE_TO_PRAY_FOR = "numberOfPeopleToPrayForDaily"; // // public static final String DEMO_NAME_BUNDLE_ARG = "demoName"; // public static final String DEMO_TOOLTIP_BUNDLE_ARG = "demoShowToolTip"; // // public static final String DEFAULT_CEASELESS_CHANNEL_ID = "ceaselessPrayerReminders"; // } // Path: app/src/main/java/org/theotech/ceaselessandroid/CeaselessApplication.java import android.app.Application; import android.app.NotificationChannel; import android.app.NotificationManager; import android.os.Build; import com.crashlytics.android.Crashlytics; import com.joanzapata.iconify.Iconify; import com.joanzapata.iconify.fonts.FontAwesomeModule; import com.onesignal.OneSignal; import com.squareup.picasso.OkHttpDownloader; import com.squareup.picasso.Picasso; import org.theotech.ceaselessandroid.util.Constants; import io.fabric.sdk.android.Fabric; import io.realm.Realm; import io.realm.RealmConfiguration; package org.theotech.ceaselessandroid; /** * Created by Andrew Ma on 10/5/15. */ public class CeaselessApplication extends Application { private void createNotificationChannel() { // Create the NotificationChannel, but only on API 26+ because // the NotificationChannel class is new and not in the support library if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { CharSequence name = getString(R.string.reminder_notification_title); int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(Constants.DEFAULT_CEASELESS_CHANNEL_ID, name, importance);
ceaseless-prayer/CeaselessAndroid
app/src/main/java/org/theotech/ceaselessandroid/view/PersonsCompletionView.java
// Path: app/src/main/java/org/theotech/ceaselessandroid/realm/pojo/PersonPOJO.java // public class PersonPOJO implements Serializable { // private String id; // private String name; // private String source; // private List<NotePOJO> notes; // private Date lastPrayed; // private boolean favorite; // private boolean ignored; // private boolean prayed; // // public PersonPOJO(String id, String name, String source, List<NotePOJO> notes, Date lastPrayed, boolean favorite, boolean ignored, boolean prayed) { // this.id = id; // this.name = name; // this.source = source; // this.notes = notes; // this.lastPrayed = lastPrayed; // this.favorite = favorite; // this.ignored = ignored; // this.prayed = prayed; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getSource() { // return source; // } // // public void setSource(String source) { // this.source = source; // } // // public List<NotePOJO> getNotes() { // return notes; // } // // public void setNotes(List<NotePOJO> notes) { // this.notes = notes; // } // // public Date getLastPrayed() { // return lastPrayed; // } // // public void setLastPrayed(Date lastPrayed) { // this.lastPrayed = lastPrayed; // } // // public boolean isFavorite() { // return favorite; // } // // public void setFavorite(boolean favorite) { // this.favorite = favorite; // } // // public boolean isIgnored() { // return ignored; // } // // public void setIgnored(boolean ignored) { // this.ignored = ignored; // } // // public boolean isPrayed() { // return prayed; // } // // public void setPrayed(boolean prayed) { // this.prayed = prayed; // } // // @Override // public String toString() { // return name; // } // } // // Path: app/src/main/java/org/theotech/ceaselessandroid/util/Constants.java // public class Constants { // public static final int NUM_AUXILIARY_CARDS = 2; // public static final int SCHEMA_VERSION = 0; // public static final String REALM_FILE_NAME = "org.theotech.ceaselessandroid"; // // public static final String HOME_SECTION_NUMBER_BUNDLE_ARG = "homeSectionNumber"; // public static final String USE_CACHE_BUNDLE_ARG = "useCache"; // public static final String PERSON_ID_BUNDLE_ARG = "personId"; // public static final String NOTE_ID_BUNDLE_ARG = "noteId"; // public static final String NEXT_BACKGROUND_IMAGE = "nextBackgroundImage"; // public static final String CURRENT_BACKGROUND_IMAGE = "currentBackgroundImage"; // public static final String PRESELECTED_PERSON_NAME = "preselectedPersonName"; // public static final String PRESELECTED_PERSON_ID = "preselectedPersonId"; // // public static final String SHOW_PERSON_INTENT = "org.theotech.ceaselessandroid.SHOW_PERSON"; // public static final String SHOW_NOTE_INTENT = "org.theotech.ceaselessandroid.SHOW_NOTE"; // public static final String DEFAULT_PREFERENCES_FILE = "org.theotech.ceaselessandroid_preferences"; // // public static final String NUMBER_OF_PEOPLE_TO_PRAY_FOR = "numberOfPeopleToPrayForDaily"; // // public static final String DEMO_NAME_BUNDLE_ARG = "demoName"; // public static final String DEMO_TOOLTIP_BUNDLE_ARG = "demoShowToolTip"; // // public static final String DEFAULT_CEASELESS_CHANNEL_ID = "ceaselessPrayerReminders"; // }
import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import com.tokenautocomplete.TokenCompleteTextView; import org.theotech.ceaselessandroid.R; import org.theotech.ceaselessandroid.realm.pojo.PersonPOJO; import org.theotech.ceaselessandroid.util.Constants;
package org.theotech.ceaselessandroid.view; /** * Created by uberx on 10/16/15. */ public class PersonsCompletionView extends TokenCompleteTextView<PersonPOJO> { public PersonsCompletionView(Context context, AttributeSet attrs) { super(context, attrs); setTokenClickStyle(TokenClickStyle.SelectDeselect); } @Override protected View getViewForObject(final PersonPOJO personPOJO) { LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Activity.LAYOUT_INFLATER_SERVICE); LinearLayout view = (LinearLayout) inflater.inflate(R.layout.person_token, (ViewGroup) PersonsCompletionView.this.getParent(), false); TextView personTag = (TextView) view.findViewById(R.id.person_tag); personTag.setText(personPOJO.getName()); personTag.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Bundle bundle = new Bundle();
// Path: app/src/main/java/org/theotech/ceaselessandroid/realm/pojo/PersonPOJO.java // public class PersonPOJO implements Serializable { // private String id; // private String name; // private String source; // private List<NotePOJO> notes; // private Date lastPrayed; // private boolean favorite; // private boolean ignored; // private boolean prayed; // // public PersonPOJO(String id, String name, String source, List<NotePOJO> notes, Date lastPrayed, boolean favorite, boolean ignored, boolean prayed) { // this.id = id; // this.name = name; // this.source = source; // this.notes = notes; // this.lastPrayed = lastPrayed; // this.favorite = favorite; // this.ignored = ignored; // this.prayed = prayed; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getSource() { // return source; // } // // public void setSource(String source) { // this.source = source; // } // // public List<NotePOJO> getNotes() { // return notes; // } // // public void setNotes(List<NotePOJO> notes) { // this.notes = notes; // } // // public Date getLastPrayed() { // return lastPrayed; // } // // public void setLastPrayed(Date lastPrayed) { // this.lastPrayed = lastPrayed; // } // // public boolean isFavorite() { // return favorite; // } // // public void setFavorite(boolean favorite) { // this.favorite = favorite; // } // // public boolean isIgnored() { // return ignored; // } // // public void setIgnored(boolean ignored) { // this.ignored = ignored; // } // // public boolean isPrayed() { // return prayed; // } // // public void setPrayed(boolean prayed) { // this.prayed = prayed; // } // // @Override // public String toString() { // return name; // } // } // // Path: app/src/main/java/org/theotech/ceaselessandroid/util/Constants.java // public class Constants { // public static final int NUM_AUXILIARY_CARDS = 2; // public static final int SCHEMA_VERSION = 0; // public static final String REALM_FILE_NAME = "org.theotech.ceaselessandroid"; // // public static final String HOME_SECTION_NUMBER_BUNDLE_ARG = "homeSectionNumber"; // public static final String USE_CACHE_BUNDLE_ARG = "useCache"; // public static final String PERSON_ID_BUNDLE_ARG = "personId"; // public static final String NOTE_ID_BUNDLE_ARG = "noteId"; // public static final String NEXT_BACKGROUND_IMAGE = "nextBackgroundImage"; // public static final String CURRENT_BACKGROUND_IMAGE = "currentBackgroundImage"; // public static final String PRESELECTED_PERSON_NAME = "preselectedPersonName"; // public static final String PRESELECTED_PERSON_ID = "preselectedPersonId"; // // public static final String SHOW_PERSON_INTENT = "org.theotech.ceaselessandroid.SHOW_PERSON"; // public static final String SHOW_NOTE_INTENT = "org.theotech.ceaselessandroid.SHOW_NOTE"; // public static final String DEFAULT_PREFERENCES_FILE = "org.theotech.ceaselessandroid_preferences"; // // public static final String NUMBER_OF_PEOPLE_TO_PRAY_FOR = "numberOfPeopleToPrayForDaily"; // // public static final String DEMO_NAME_BUNDLE_ARG = "demoName"; // public static final String DEMO_TOOLTIP_BUNDLE_ARG = "demoShowToolTip"; // // public static final String DEFAULT_CEASELESS_CHANNEL_ID = "ceaselessPrayerReminders"; // } // Path: app/src/main/java/org/theotech/ceaselessandroid/view/PersonsCompletionView.java import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import com.tokenautocomplete.TokenCompleteTextView; import org.theotech.ceaselessandroid.R; import org.theotech.ceaselessandroid.realm.pojo.PersonPOJO; import org.theotech.ceaselessandroid.util.Constants; package org.theotech.ceaselessandroid.view; /** * Created by uberx on 10/16/15. */ public class PersonsCompletionView extends TokenCompleteTextView<PersonPOJO> { public PersonsCompletionView(Context context, AttributeSet attrs) { super(context, attrs); setTokenClickStyle(TokenClickStyle.SelectDeselect); } @Override protected View getViewForObject(final PersonPOJO personPOJO) { LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Activity.LAYOUT_INFLATER_SERVICE); LinearLayout view = (LinearLayout) inflater.inflate(R.layout.person_token, (ViewGroup) PersonsCompletionView.this.getParent(), false); TextView personTag = (TextView) view.findViewById(R.id.person_tag); personTag.setText(personPOJO.getName()); personTag.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Bundle bundle = new Bundle();
bundle.putString(Constants.PERSON_ID_BUNDLE_ARG, personPOJO.getId());
ceaseless-prayer/CeaselessAndroid
app/src/main/java/org/theotech/ceaselessandroid/fragment/ContactUsFragment.java
// Path: app/src/main/java/org/theotech/ceaselessandroid/util/AnalyticsUtils.java // public class AnalyticsUtils { // // private static final String TAG = AnalyticsUtils.class.getSimpleName(); // // public static void sendScreenViewHit(Activity activity, String name) { // Log.v(TAG, "Setting screen name: " + name); // FirebaseAnalytics.getInstance(activity).setCurrentScreen(activity, name, null /* class override */); // } // // public static void sendEventWithCategoryAndValue(Activity activity, String category, String action, String label, Long value) { // final Bundle params = new Bundle(); // params.putString("category", category); // params.putString("action", action); // params.putString("label", label); // params.putLong("value", value); // FirebaseAnalytics.getInstance(activity).logEvent("ga_event", params); // } // // public static void sendEventWithCategory(Activity activity, String category, String action, String label) { // final Bundle params = new Bundle(); // params.putString("category", category); // params.putString("action", action); // params.putString("label", label); // FirebaseAnalytics.getInstance(activity).logEvent("ga_event", params); // } // }
import android.app.Fragment; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.squareup.picasso.Picasso; import org.theotech.ceaselessandroid.R; import org.theotech.ceaselessandroid.util.AnalyticsUtils; import butterknife.BindView; import butterknife.ButterKnife;
} public void startEmailIntent() { Intent i = new Intent(Intent.ACTION_SEND); i.setType("message/rfc822"); i.putExtra(Intent.EXTRA_EMAIL, new String[]{"ceaseless@theotech.org"}); // TODO localize i.putExtra(Intent.EXTRA_SUBJECT, "Ceaseless for Android Feedback"); i.putExtra(Intent.EXTRA_TEXT, "Feedback for Ceaseless Android app: \n"); try { startActivity(Intent.createChooser(i, "Send mail...")); } catch (android.content.ActivityNotFoundException ex) { Toast.makeText(getActivity(), "There are no email clients installed.", Toast.LENGTH_SHORT).show(); } } public void startWebIntent(String url) { Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); try { startActivity(browserIntent); } catch (android.content.ActivityNotFoundException ex) { Toast.makeText(getActivity(), "Unable to open web browser.", Toast.LENGTH_SHORT).show(); } } @Override public void onResume() { super.onResume();
// Path: app/src/main/java/org/theotech/ceaselessandroid/util/AnalyticsUtils.java // public class AnalyticsUtils { // // private static final String TAG = AnalyticsUtils.class.getSimpleName(); // // public static void sendScreenViewHit(Activity activity, String name) { // Log.v(TAG, "Setting screen name: " + name); // FirebaseAnalytics.getInstance(activity).setCurrentScreen(activity, name, null /* class override */); // } // // public static void sendEventWithCategoryAndValue(Activity activity, String category, String action, String label, Long value) { // final Bundle params = new Bundle(); // params.putString("category", category); // params.putString("action", action); // params.putString("label", label); // params.putLong("value", value); // FirebaseAnalytics.getInstance(activity).logEvent("ga_event", params); // } // // public static void sendEventWithCategory(Activity activity, String category, String action, String label) { // final Bundle params = new Bundle(); // params.putString("category", category); // params.putString("action", action); // params.putString("label", label); // FirebaseAnalytics.getInstance(activity).logEvent("ga_event", params); // } // } // Path: app/src/main/java/org/theotech/ceaselessandroid/fragment/ContactUsFragment.java import android.app.Fragment; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.squareup.picasso.Picasso; import org.theotech.ceaselessandroid.R; import org.theotech.ceaselessandroid.util.AnalyticsUtils; import butterknife.BindView; import butterknife.ButterKnife; } public void startEmailIntent() { Intent i = new Intent(Intent.ACTION_SEND); i.setType("message/rfc822"); i.putExtra(Intent.EXTRA_EMAIL, new String[]{"ceaseless@theotech.org"}); // TODO localize i.putExtra(Intent.EXTRA_SUBJECT, "Ceaseless for Android Feedback"); i.putExtra(Intent.EXTRA_TEXT, "Feedback for Ceaseless Android app: \n"); try { startActivity(Intent.createChooser(i, "Send mail...")); } catch (android.content.ActivityNotFoundException ex) { Toast.makeText(getActivity(), "There are no email clients installed.", Toast.LENGTH_SHORT).show(); } } public void startWebIntent(String url) { Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); try { startActivity(browserIntent); } catch (android.content.ActivityNotFoundException ex) { Toast.makeText(getActivity(), "Unable to open web browser.", Toast.LENGTH_SHORT).show(); } } @Override public void onResume() { super.onResume();
AnalyticsUtils.sendScreenViewHit(this.getActivity(), "ContactUsScreen");
ceaseless-prayer/CeaselessAndroid
app/src/main/java/org/theotech/ceaselessandroid/note/NoteManager.java
// Path: app/src/main/java/org/theotech/ceaselessandroid/realm/pojo/NotePOJO.java // public class NotePOJO implements Serializable { // private String id; // private Date creationDate; // private Date lastUpdatedDate; // private String title; // private String text; // private List<String> peopleTagged; // private List<String> peopleTaggedNames; // // public NotePOJO(String id, Date creationDate, Date lastUpdatedDate, String title, String text, List<String> peopleTagged, List<String> peopleTaggedNames) { // this.id = id; // this.creationDate = creationDate; // this.lastUpdatedDate = lastUpdatedDate; // this.title = title; // this.text = text; // this.peopleTagged = peopleTagged; // this.peopleTaggedNames = peopleTaggedNames; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public Date getCreationDate() { // return creationDate; // } // // public void setCreationDate(Date creationDate) { // this.creationDate = creationDate; // } // // public Date getLastUpdatedDate() { // return lastUpdatedDate; // } // // public void setLastUpdatedDate(Date lastUpdatedDate) { // this.lastUpdatedDate = lastUpdatedDate; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getText() { // return text; // } // // public void setText(String text) { // this.text = text; // } // // public List<String> getPeopleTagged() { // return peopleTagged; // } // // public List<String> getPeopleTaggedNames() { // return peopleTaggedNames; // } // // public void setPeopleTagged(List<String> peopleTagged) { // this.peopleTagged = peopleTagged; // } // // @Override // public String toString() { // return id; // } // } // // Path: app/src/main/java/org/theotech/ceaselessandroid/realm/pojo/PersonPOJO.java // public class PersonPOJO implements Serializable { // private String id; // private String name; // private String source; // private List<NotePOJO> notes; // private Date lastPrayed; // private boolean favorite; // private boolean ignored; // private boolean prayed; // // public PersonPOJO(String id, String name, String source, List<NotePOJO> notes, Date lastPrayed, boolean favorite, boolean ignored, boolean prayed) { // this.id = id; // this.name = name; // this.source = source; // this.notes = notes; // this.lastPrayed = lastPrayed; // this.favorite = favorite; // this.ignored = ignored; // this.prayed = prayed; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getSource() { // return source; // } // // public void setSource(String source) { // this.source = source; // } // // public List<NotePOJO> getNotes() { // return notes; // } // // public void setNotes(List<NotePOJO> notes) { // this.notes = notes; // } // // public Date getLastPrayed() { // return lastPrayed; // } // // public void setLastPrayed(Date lastPrayed) { // this.lastPrayed = lastPrayed; // } // // public boolean isFavorite() { // return favorite; // } // // public void setFavorite(boolean favorite) { // this.favorite = favorite; // } // // public boolean isIgnored() { // return ignored; // } // // public void setIgnored(boolean ignored) { // this.ignored = ignored; // } // // public boolean isPrayed() { // return prayed; // } // // public void setPrayed(boolean prayed) { // this.prayed = prayed; // } // // @Override // public String toString() { // return name; // } // }
import org.theotech.ceaselessandroid.realm.pojo.NotePOJO; import org.theotech.ceaselessandroid.realm.pojo.PersonPOJO; import java.util.List;
package org.theotech.ceaselessandroid.note; /** * Created by chrislim on 11/3/15. */ public interface NoteManager { List<NotePOJO> getNotes();
// Path: app/src/main/java/org/theotech/ceaselessandroid/realm/pojo/NotePOJO.java // public class NotePOJO implements Serializable { // private String id; // private Date creationDate; // private Date lastUpdatedDate; // private String title; // private String text; // private List<String> peopleTagged; // private List<String> peopleTaggedNames; // // public NotePOJO(String id, Date creationDate, Date lastUpdatedDate, String title, String text, List<String> peopleTagged, List<String> peopleTaggedNames) { // this.id = id; // this.creationDate = creationDate; // this.lastUpdatedDate = lastUpdatedDate; // this.title = title; // this.text = text; // this.peopleTagged = peopleTagged; // this.peopleTaggedNames = peopleTaggedNames; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public Date getCreationDate() { // return creationDate; // } // // public void setCreationDate(Date creationDate) { // this.creationDate = creationDate; // } // // public Date getLastUpdatedDate() { // return lastUpdatedDate; // } // // public void setLastUpdatedDate(Date lastUpdatedDate) { // this.lastUpdatedDate = lastUpdatedDate; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getText() { // return text; // } // // public void setText(String text) { // this.text = text; // } // // public List<String> getPeopleTagged() { // return peopleTagged; // } // // public List<String> getPeopleTaggedNames() { // return peopleTaggedNames; // } // // public void setPeopleTagged(List<String> peopleTagged) { // this.peopleTagged = peopleTagged; // } // // @Override // public String toString() { // return id; // } // } // // Path: app/src/main/java/org/theotech/ceaselessandroid/realm/pojo/PersonPOJO.java // public class PersonPOJO implements Serializable { // private String id; // private String name; // private String source; // private List<NotePOJO> notes; // private Date lastPrayed; // private boolean favorite; // private boolean ignored; // private boolean prayed; // // public PersonPOJO(String id, String name, String source, List<NotePOJO> notes, Date lastPrayed, boolean favorite, boolean ignored, boolean prayed) { // this.id = id; // this.name = name; // this.source = source; // this.notes = notes; // this.lastPrayed = lastPrayed; // this.favorite = favorite; // this.ignored = ignored; // this.prayed = prayed; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getSource() { // return source; // } // // public void setSource(String source) { // this.source = source; // } // // public List<NotePOJO> getNotes() { // return notes; // } // // public void setNotes(List<NotePOJO> notes) { // this.notes = notes; // } // // public Date getLastPrayed() { // return lastPrayed; // } // // public void setLastPrayed(Date lastPrayed) { // this.lastPrayed = lastPrayed; // } // // public boolean isFavorite() { // return favorite; // } // // public void setFavorite(boolean favorite) { // this.favorite = favorite; // } // // public boolean isIgnored() { // return ignored; // } // // public void setIgnored(boolean ignored) { // this.ignored = ignored; // } // // public boolean isPrayed() { // return prayed; // } // // public void setPrayed(boolean prayed) { // this.prayed = prayed; // } // // @Override // public String toString() { // return name; // } // } // Path: app/src/main/java/org/theotech/ceaselessandroid/note/NoteManager.java import org.theotech.ceaselessandroid.realm.pojo.NotePOJO; import org.theotech.ceaselessandroid.realm.pojo.PersonPOJO; import java.util.List; package org.theotech.ceaselessandroid.note; /** * Created by chrislim on 11/3/15. */ public interface NoteManager { List<NotePOJO> getNotes();
void addNote(String title, String text, List<PersonPOJO> personPOJOs);
ceaseless-prayer/CeaselessAndroid
app/src/main/java/org/theotech/ceaselessandroid/fragment/AboutFragment.java
// Path: app/src/main/java/org/theotech/ceaselessandroid/util/AnalyticsUtils.java // public class AnalyticsUtils { // // private static final String TAG = AnalyticsUtils.class.getSimpleName(); // // public static void sendScreenViewHit(Activity activity, String name) { // Log.v(TAG, "Setting screen name: " + name); // FirebaseAnalytics.getInstance(activity).setCurrentScreen(activity, name, null /* class override */); // } // // public static void sendEventWithCategoryAndValue(Activity activity, String category, String action, String label, Long value) { // final Bundle params = new Bundle(); // params.putString("category", category); // params.putString("action", action); // params.putString("label", label); // params.putLong("value", value); // FirebaseAnalytics.getInstance(activity).logEvent("ga_event", params); // } // // public static void sendEventWithCategory(Activity activity, String category, String action, String label) { // final Bundle params = new Bundle(); // params.putString("category", category); // params.putString("action", action); // params.putString("label", label); // FirebaseAnalytics.getInstance(activity).logEvent("ga_event", params); // } // }
import android.app.Fragment; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.webkit.WebView; import android.webkit.WebViewClient; import org.theotech.ceaselessandroid.R; import org.theotech.ceaselessandroid.util.AnalyticsUtils; import butterknife.BindView; import butterknife.ButterKnife;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // set title getActivity().setTitle(getString(R.string.nav_about)); // create view and bind View view = inflater.inflate(R.layout.fragment_help, container, false); ButterKnife.bind(this, view); aboutWV.getSettings().setJavaScriptEnabled(true); aboutWV.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView wv, String url) { if (url.startsWith("mailto:")) { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); startActivity(intent); return true; } else { return false; } } }); aboutWV.loadUrl(getString(R.string.about_url)); return view; } @Override public void onResume() { super.onResume();
// Path: app/src/main/java/org/theotech/ceaselessandroid/util/AnalyticsUtils.java // public class AnalyticsUtils { // // private static final String TAG = AnalyticsUtils.class.getSimpleName(); // // public static void sendScreenViewHit(Activity activity, String name) { // Log.v(TAG, "Setting screen name: " + name); // FirebaseAnalytics.getInstance(activity).setCurrentScreen(activity, name, null /* class override */); // } // // public static void sendEventWithCategoryAndValue(Activity activity, String category, String action, String label, Long value) { // final Bundle params = new Bundle(); // params.putString("category", category); // params.putString("action", action); // params.putString("label", label); // params.putLong("value", value); // FirebaseAnalytics.getInstance(activity).logEvent("ga_event", params); // } // // public static void sendEventWithCategory(Activity activity, String category, String action, String label) { // final Bundle params = new Bundle(); // params.putString("category", category); // params.putString("action", action); // params.putString("label", label); // FirebaseAnalytics.getInstance(activity).logEvent("ga_event", params); // } // } // Path: app/src/main/java/org/theotech/ceaselessandroid/fragment/AboutFragment.java import android.app.Fragment; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.webkit.WebView; import android.webkit.WebViewClient; import org.theotech.ceaselessandroid.R; import org.theotech.ceaselessandroid.util.AnalyticsUtils; import butterknife.BindView; import butterknife.ButterKnife; public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // set title getActivity().setTitle(getString(R.string.nav_about)); // create view and bind View view = inflater.inflate(R.layout.fragment_help, container, false); ButterKnife.bind(this, view); aboutWV.getSettings().setJavaScriptEnabled(true); aboutWV.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView wv, String url) { if (url.startsWith("mailto:")) { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); startActivity(intent); return true; } else { return false; } } }); aboutWV.loadUrl(getString(R.string.about_url)); return view; } @Override public void onResume() { super.onResume();
AnalyticsUtils.sendScreenViewHit(this.getActivity(), "AboutScreen");
codebulb/LambdaOmega
src/main/java/ch/codebulb/lambdaomega/abstractions/BiFunctionalI.java
// Path: src/main/java/ch/codebulb/lambdaomega/abstractions/functions/DoubleBiFunction.java // @FunctionalInterface // public interface DoubleBiFunction<R> { // // /** // * Applies this function to the given arguments. // * // * @param t the first function argument // * @param u the second function argument // * @return the function result // */ // R apply(double t, double u); // // } // // Path: src/main/java/ch/codebulb/lambdaomega/abstractions/functions/IntBiFunction.java // @FunctionalInterface // public interface IntBiFunction<R> { // // /** // * Applies this function to the given arguments. // * // * @param t the first function argument // * @param u the second function argument // * @return the function result // */ // R apply(int t, int u); // // } // // Path: src/main/java/ch/codebulb/lambdaomega/abstractions/functions/LongBiFunction.java // @FunctionalInterface // public interface LongBiFunction<R> { // // /** // * Applies this function to the given arguments. // * // * @param t the first function argument // * @param u the second function argument // * @return the function result // */ // R apply(long t, long u); // // }
import ch.codebulb.lambdaomega.abstractions.functions.DoubleBiFunction; import ch.codebulb.lambdaomega.abstractions.functions.IntBiFunction; import ch.codebulb.lambdaomega.abstractions.functions.LongBiFunction; import java.util.function.BiConsumer; import java.util.function.BiFunction; import java.util.function.BiPredicate; import java.util.function.BinaryOperator; import java.util.function.DoubleBinaryOperator; import java.util.function.IntBinaryOperator; import java.util.function.LongBinaryOperator; import java.util.function.ObjDoubleConsumer; import java.util.function.ObjIntConsumer; import java.util.function.ObjLongConsumer; import java.util.function.ToDoubleBiFunction; import java.util.function.ToIntBiFunction; import java.util.function.ToLongBiFunction;
package ch.codebulb.lambdaomega.abstractions; /** * A multi-interface providing a single unified API for all 2-ary {@link FunctionalInterface}s of Java 8 and LambdaOmega. * Implement / use {@link #call(Object, Object)} / {@link #call()} to call this function.<p/> * * Note: {@link BinaryOperator} is not covered by this interface as it is mutually incompatible with {@link BiFunction}. * * @param <T> the type of the first argument to the function * @param <U> the type of the second argument to the function * @param <R> the type of the result of the function */ @FunctionalInterface public interface BiFunctionalI<T, U, R> extends BiFunction<T, U, R>, BiConsumer<T, U>, BiPredicate<T, U>, IntBinaryOperator, LongBinaryOperator, DoubleBinaryOperator,
// Path: src/main/java/ch/codebulb/lambdaomega/abstractions/functions/DoubleBiFunction.java // @FunctionalInterface // public interface DoubleBiFunction<R> { // // /** // * Applies this function to the given arguments. // * // * @param t the first function argument // * @param u the second function argument // * @return the function result // */ // R apply(double t, double u); // // } // // Path: src/main/java/ch/codebulb/lambdaomega/abstractions/functions/IntBiFunction.java // @FunctionalInterface // public interface IntBiFunction<R> { // // /** // * Applies this function to the given arguments. // * // * @param t the first function argument // * @param u the second function argument // * @return the function result // */ // R apply(int t, int u); // // } // // Path: src/main/java/ch/codebulb/lambdaomega/abstractions/functions/LongBiFunction.java // @FunctionalInterface // public interface LongBiFunction<R> { // // /** // * Applies this function to the given arguments. // * // * @param t the first function argument // * @param u the second function argument // * @return the function result // */ // R apply(long t, long u); // // } // Path: src/main/java/ch/codebulb/lambdaomega/abstractions/BiFunctionalI.java import ch.codebulb.lambdaomega.abstractions.functions.DoubleBiFunction; import ch.codebulb.lambdaomega.abstractions.functions.IntBiFunction; import ch.codebulb.lambdaomega.abstractions.functions.LongBiFunction; import java.util.function.BiConsumer; import java.util.function.BiFunction; import java.util.function.BiPredicate; import java.util.function.BinaryOperator; import java.util.function.DoubleBinaryOperator; import java.util.function.IntBinaryOperator; import java.util.function.LongBinaryOperator; import java.util.function.ObjDoubleConsumer; import java.util.function.ObjIntConsumer; import java.util.function.ObjLongConsumer; import java.util.function.ToDoubleBiFunction; import java.util.function.ToIntBiFunction; import java.util.function.ToLongBiFunction; package ch.codebulb.lambdaomega.abstractions; /** * A multi-interface providing a single unified API for all 2-ary {@link FunctionalInterface}s of Java 8 and LambdaOmega. * Implement / use {@link #call(Object, Object)} / {@link #call()} to call this function.<p/> * * Note: {@link BinaryOperator} is not covered by this interface as it is mutually incompatible with {@link BiFunction}. * * @param <T> the type of the first argument to the function * @param <U> the type of the second argument to the function * @param <R> the type of the result of the function */ @FunctionalInterface public interface BiFunctionalI<T, U, R> extends BiFunction<T, U, R>, BiConsumer<T, U>, BiPredicate<T, U>, IntBinaryOperator, LongBinaryOperator, DoubleBinaryOperator,
IntBiFunction<R>, LongBiFunction<R>, DoubleBiFunction<R>,
codebulb/LambdaOmega
src/main/java/ch/codebulb/lambdaomega/abstractions/BiFunctionalI.java
// Path: src/main/java/ch/codebulb/lambdaomega/abstractions/functions/DoubleBiFunction.java // @FunctionalInterface // public interface DoubleBiFunction<R> { // // /** // * Applies this function to the given arguments. // * // * @param t the first function argument // * @param u the second function argument // * @return the function result // */ // R apply(double t, double u); // // } // // Path: src/main/java/ch/codebulb/lambdaomega/abstractions/functions/IntBiFunction.java // @FunctionalInterface // public interface IntBiFunction<R> { // // /** // * Applies this function to the given arguments. // * // * @param t the first function argument // * @param u the second function argument // * @return the function result // */ // R apply(int t, int u); // // } // // Path: src/main/java/ch/codebulb/lambdaomega/abstractions/functions/LongBiFunction.java // @FunctionalInterface // public interface LongBiFunction<R> { // // /** // * Applies this function to the given arguments. // * // * @param t the first function argument // * @param u the second function argument // * @return the function result // */ // R apply(long t, long u); // // }
import ch.codebulb.lambdaomega.abstractions.functions.DoubleBiFunction; import ch.codebulb.lambdaomega.abstractions.functions.IntBiFunction; import ch.codebulb.lambdaomega.abstractions.functions.LongBiFunction; import java.util.function.BiConsumer; import java.util.function.BiFunction; import java.util.function.BiPredicate; import java.util.function.BinaryOperator; import java.util.function.DoubleBinaryOperator; import java.util.function.IntBinaryOperator; import java.util.function.LongBinaryOperator; import java.util.function.ObjDoubleConsumer; import java.util.function.ObjIntConsumer; import java.util.function.ObjLongConsumer; import java.util.function.ToDoubleBiFunction; import java.util.function.ToIntBiFunction; import java.util.function.ToLongBiFunction;
package ch.codebulb.lambdaomega.abstractions; /** * A multi-interface providing a single unified API for all 2-ary {@link FunctionalInterface}s of Java 8 and LambdaOmega. * Implement / use {@link #call(Object, Object)} / {@link #call()} to call this function.<p/> * * Note: {@link BinaryOperator} is not covered by this interface as it is mutually incompatible with {@link BiFunction}. * * @param <T> the type of the first argument to the function * @param <U> the type of the second argument to the function * @param <R> the type of the result of the function */ @FunctionalInterface public interface BiFunctionalI<T, U, R> extends BiFunction<T, U, R>, BiConsumer<T, U>, BiPredicate<T, U>, IntBinaryOperator, LongBinaryOperator, DoubleBinaryOperator,
// Path: src/main/java/ch/codebulb/lambdaomega/abstractions/functions/DoubleBiFunction.java // @FunctionalInterface // public interface DoubleBiFunction<R> { // // /** // * Applies this function to the given arguments. // * // * @param t the first function argument // * @param u the second function argument // * @return the function result // */ // R apply(double t, double u); // // } // // Path: src/main/java/ch/codebulb/lambdaomega/abstractions/functions/IntBiFunction.java // @FunctionalInterface // public interface IntBiFunction<R> { // // /** // * Applies this function to the given arguments. // * // * @param t the first function argument // * @param u the second function argument // * @return the function result // */ // R apply(int t, int u); // // } // // Path: src/main/java/ch/codebulb/lambdaomega/abstractions/functions/LongBiFunction.java // @FunctionalInterface // public interface LongBiFunction<R> { // // /** // * Applies this function to the given arguments. // * // * @param t the first function argument // * @param u the second function argument // * @return the function result // */ // R apply(long t, long u); // // } // Path: src/main/java/ch/codebulb/lambdaomega/abstractions/BiFunctionalI.java import ch.codebulb.lambdaomega.abstractions.functions.DoubleBiFunction; import ch.codebulb.lambdaomega.abstractions.functions.IntBiFunction; import ch.codebulb.lambdaomega.abstractions.functions.LongBiFunction; import java.util.function.BiConsumer; import java.util.function.BiFunction; import java.util.function.BiPredicate; import java.util.function.BinaryOperator; import java.util.function.DoubleBinaryOperator; import java.util.function.IntBinaryOperator; import java.util.function.LongBinaryOperator; import java.util.function.ObjDoubleConsumer; import java.util.function.ObjIntConsumer; import java.util.function.ObjLongConsumer; import java.util.function.ToDoubleBiFunction; import java.util.function.ToIntBiFunction; import java.util.function.ToLongBiFunction; package ch.codebulb.lambdaomega.abstractions; /** * A multi-interface providing a single unified API for all 2-ary {@link FunctionalInterface}s of Java 8 and LambdaOmega. * Implement / use {@link #call(Object, Object)} / {@link #call()} to call this function.<p/> * * Note: {@link BinaryOperator} is not covered by this interface as it is mutually incompatible with {@link BiFunction}. * * @param <T> the type of the first argument to the function * @param <U> the type of the second argument to the function * @param <R> the type of the result of the function */ @FunctionalInterface public interface BiFunctionalI<T, U, R> extends BiFunction<T, U, R>, BiConsumer<T, U>, BiPredicate<T, U>, IntBinaryOperator, LongBinaryOperator, DoubleBinaryOperator,
IntBiFunction<R>, LongBiFunction<R>, DoubleBiFunction<R>,
codebulb/LambdaOmega
src/main/java/ch/codebulb/lambdaomega/abstractions/BiFunctionalI.java
// Path: src/main/java/ch/codebulb/lambdaomega/abstractions/functions/DoubleBiFunction.java // @FunctionalInterface // public interface DoubleBiFunction<R> { // // /** // * Applies this function to the given arguments. // * // * @param t the first function argument // * @param u the second function argument // * @return the function result // */ // R apply(double t, double u); // // } // // Path: src/main/java/ch/codebulb/lambdaomega/abstractions/functions/IntBiFunction.java // @FunctionalInterface // public interface IntBiFunction<R> { // // /** // * Applies this function to the given arguments. // * // * @param t the first function argument // * @param u the second function argument // * @return the function result // */ // R apply(int t, int u); // // } // // Path: src/main/java/ch/codebulb/lambdaomega/abstractions/functions/LongBiFunction.java // @FunctionalInterface // public interface LongBiFunction<R> { // // /** // * Applies this function to the given arguments. // * // * @param t the first function argument // * @param u the second function argument // * @return the function result // */ // R apply(long t, long u); // // }
import ch.codebulb.lambdaomega.abstractions.functions.DoubleBiFunction; import ch.codebulb.lambdaomega.abstractions.functions.IntBiFunction; import ch.codebulb.lambdaomega.abstractions.functions.LongBiFunction; import java.util.function.BiConsumer; import java.util.function.BiFunction; import java.util.function.BiPredicate; import java.util.function.BinaryOperator; import java.util.function.DoubleBinaryOperator; import java.util.function.IntBinaryOperator; import java.util.function.LongBinaryOperator; import java.util.function.ObjDoubleConsumer; import java.util.function.ObjIntConsumer; import java.util.function.ObjLongConsumer; import java.util.function.ToDoubleBiFunction; import java.util.function.ToIntBiFunction; import java.util.function.ToLongBiFunction;
package ch.codebulb.lambdaomega.abstractions; /** * A multi-interface providing a single unified API for all 2-ary {@link FunctionalInterface}s of Java 8 and LambdaOmega. * Implement / use {@link #call(Object, Object)} / {@link #call()} to call this function.<p/> * * Note: {@link BinaryOperator} is not covered by this interface as it is mutually incompatible with {@link BiFunction}. * * @param <T> the type of the first argument to the function * @param <U> the type of the second argument to the function * @param <R> the type of the result of the function */ @FunctionalInterface public interface BiFunctionalI<T, U, R> extends BiFunction<T, U, R>, BiConsumer<T, U>, BiPredicate<T, U>, IntBinaryOperator, LongBinaryOperator, DoubleBinaryOperator,
// Path: src/main/java/ch/codebulb/lambdaomega/abstractions/functions/DoubleBiFunction.java // @FunctionalInterface // public interface DoubleBiFunction<R> { // // /** // * Applies this function to the given arguments. // * // * @param t the first function argument // * @param u the second function argument // * @return the function result // */ // R apply(double t, double u); // // } // // Path: src/main/java/ch/codebulb/lambdaomega/abstractions/functions/IntBiFunction.java // @FunctionalInterface // public interface IntBiFunction<R> { // // /** // * Applies this function to the given arguments. // * // * @param t the first function argument // * @param u the second function argument // * @return the function result // */ // R apply(int t, int u); // // } // // Path: src/main/java/ch/codebulb/lambdaomega/abstractions/functions/LongBiFunction.java // @FunctionalInterface // public interface LongBiFunction<R> { // // /** // * Applies this function to the given arguments. // * // * @param t the first function argument // * @param u the second function argument // * @return the function result // */ // R apply(long t, long u); // // } // Path: src/main/java/ch/codebulb/lambdaomega/abstractions/BiFunctionalI.java import ch.codebulb.lambdaomega.abstractions.functions.DoubleBiFunction; import ch.codebulb.lambdaomega.abstractions.functions.IntBiFunction; import ch.codebulb.lambdaomega.abstractions.functions.LongBiFunction; import java.util.function.BiConsumer; import java.util.function.BiFunction; import java.util.function.BiPredicate; import java.util.function.BinaryOperator; import java.util.function.DoubleBinaryOperator; import java.util.function.IntBinaryOperator; import java.util.function.LongBinaryOperator; import java.util.function.ObjDoubleConsumer; import java.util.function.ObjIntConsumer; import java.util.function.ObjLongConsumer; import java.util.function.ToDoubleBiFunction; import java.util.function.ToIntBiFunction; import java.util.function.ToLongBiFunction; package ch.codebulb.lambdaomega.abstractions; /** * A multi-interface providing a single unified API for all 2-ary {@link FunctionalInterface}s of Java 8 and LambdaOmega. * Implement / use {@link #call(Object, Object)} / {@link #call()} to call this function.<p/> * * Note: {@link BinaryOperator} is not covered by this interface as it is mutually incompatible with {@link BiFunction}. * * @param <T> the type of the first argument to the function * @param <U> the type of the second argument to the function * @param <R> the type of the result of the function */ @FunctionalInterface public interface BiFunctionalI<T, U, R> extends BiFunction<T, U, R>, BiConsumer<T, U>, BiPredicate<T, U>, IntBinaryOperator, LongBinaryOperator, DoubleBinaryOperator,
IntBiFunction<R>, LongBiFunction<R>, DoubleBiFunction<R>,
codebulb/LambdaOmega
src/test/java/ch/codebulb/lambdaomega/MBaseIndexedTest.java
// Path: src/main/java/ch/codebulb/lambdaomega/L.java // public static <T> L<T> l() { // return new L<>(new ArrayList<>()); // } // // Path: src/main/java/ch/codebulb/lambdaomega/L.java // public static <T> List<T> list(T... ts) { // return l(ts).l; // } // // Path: src/main/java/ch/codebulb/lambdaomega/M.java // public static <K, V> E<K, V> e(K k, V v) { // return new E(k, v); // } // // Path: src/main/java/ch/codebulb/lambdaomega/M.java // public static M m() { // return m(new LinkedHashMap<>()); // } // // Path: src/main/java/ch/codebulb/lambdaomega/S.java // public static <T> Set<T> set(T... ts) { // return C.toSet(ts); // } // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static final List<Integer> EXPECTED_LIST = new ArrayList<>(); // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static final Map<String, Integer> EXPECTED_MAP = new LinkedHashMap<>(); // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static final Map<String, Integer> EXPECTED_MAP_2_ELEMENTS = new LinkedHashMap<>(); // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static <T> void assertEquals(T expected, T... actual) { // Arrays.stream(actual).forEach(it -> Assert.assertEquals(expected, it)); // } // // Path: src/main/java/ch/codebulb/lambdaomega/abstractions/IndexedListI.java // public static class IndexAlreadyPresentException extends RuntimeException { // // cannot use generics in Throwable // public final Object key; // public final Object previousValue; // // public IndexAlreadyPresentException(Object key, Object previousValue) { // super("Duplicate key found in map. Use #set(...) to override a value. Key: " + key + ", previous value: " + previousValue); // this.key = key; // this.previousValue = previousValue; // } // }
import static ch.codebulb.lambdaomega.L.l; import static ch.codebulb.lambdaomega.L.list; import static ch.codebulb.lambdaomega.M.e; import static ch.codebulb.lambdaomega.M.m; import static ch.codebulb.lambdaomega.S.set; import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_LIST; import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_MAP; import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_MAP_2_ELEMENTS; import static ch.codebulb.lambdaomega.TestUtil.assertEquals; import ch.codebulb.lambdaomega.abstractions.IndexedListI.IndexAlreadyPresentException; import java.util.Map; import static org.junit.Assert.fail; import org.junit.Test;
package ch.codebulb.lambdaomega; /** * Test cases for the {@link M} implementation for {@link IndexedI}. */ public class MBaseIndexedTest { @Test public void testAdd() { // Add individual elements
// Path: src/main/java/ch/codebulb/lambdaomega/L.java // public static <T> L<T> l() { // return new L<>(new ArrayList<>()); // } // // Path: src/main/java/ch/codebulb/lambdaomega/L.java // public static <T> List<T> list(T... ts) { // return l(ts).l; // } // // Path: src/main/java/ch/codebulb/lambdaomega/M.java // public static <K, V> E<K, V> e(K k, V v) { // return new E(k, v); // } // // Path: src/main/java/ch/codebulb/lambdaomega/M.java // public static M m() { // return m(new LinkedHashMap<>()); // } // // Path: src/main/java/ch/codebulb/lambdaomega/S.java // public static <T> Set<T> set(T... ts) { // return C.toSet(ts); // } // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static final List<Integer> EXPECTED_LIST = new ArrayList<>(); // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static final Map<String, Integer> EXPECTED_MAP = new LinkedHashMap<>(); // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static final Map<String, Integer> EXPECTED_MAP_2_ELEMENTS = new LinkedHashMap<>(); // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static <T> void assertEquals(T expected, T... actual) { // Arrays.stream(actual).forEach(it -> Assert.assertEquals(expected, it)); // } // // Path: src/main/java/ch/codebulb/lambdaomega/abstractions/IndexedListI.java // public static class IndexAlreadyPresentException extends RuntimeException { // // cannot use generics in Throwable // public final Object key; // public final Object previousValue; // // public IndexAlreadyPresentException(Object key, Object previousValue) { // super("Duplicate key found in map. Use #set(...) to override a value. Key: " + key + ", previous value: " + previousValue); // this.key = key; // this.previousValue = previousValue; // } // } // Path: src/test/java/ch/codebulb/lambdaomega/MBaseIndexedTest.java import static ch.codebulb.lambdaomega.L.l; import static ch.codebulb.lambdaomega.L.list; import static ch.codebulb.lambdaomega.M.e; import static ch.codebulb.lambdaomega.M.m; import static ch.codebulb.lambdaomega.S.set; import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_LIST; import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_MAP; import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_MAP_2_ELEMENTS; import static ch.codebulb.lambdaomega.TestUtil.assertEquals; import ch.codebulb.lambdaomega.abstractions.IndexedListI.IndexAlreadyPresentException; import java.util.Map; import static org.junit.Assert.fail; import org.junit.Test; package ch.codebulb.lambdaomega; /** * Test cases for the {@link M} implementation for {@link IndexedI}. */ public class MBaseIndexedTest { @Test public void testAdd() { // Add individual elements
assertEquals(EXPECTED_MAP_2_ELEMENTS, m("a", 0).Insert("b", 1).m);
codebulb/LambdaOmega
src/test/java/ch/codebulb/lambdaomega/MBaseIndexedTest.java
// Path: src/main/java/ch/codebulb/lambdaomega/L.java // public static <T> L<T> l() { // return new L<>(new ArrayList<>()); // } // // Path: src/main/java/ch/codebulb/lambdaomega/L.java // public static <T> List<T> list(T... ts) { // return l(ts).l; // } // // Path: src/main/java/ch/codebulb/lambdaomega/M.java // public static <K, V> E<K, V> e(K k, V v) { // return new E(k, v); // } // // Path: src/main/java/ch/codebulb/lambdaomega/M.java // public static M m() { // return m(new LinkedHashMap<>()); // } // // Path: src/main/java/ch/codebulb/lambdaomega/S.java // public static <T> Set<T> set(T... ts) { // return C.toSet(ts); // } // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static final List<Integer> EXPECTED_LIST = new ArrayList<>(); // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static final Map<String, Integer> EXPECTED_MAP = new LinkedHashMap<>(); // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static final Map<String, Integer> EXPECTED_MAP_2_ELEMENTS = new LinkedHashMap<>(); // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static <T> void assertEquals(T expected, T... actual) { // Arrays.stream(actual).forEach(it -> Assert.assertEquals(expected, it)); // } // // Path: src/main/java/ch/codebulb/lambdaomega/abstractions/IndexedListI.java // public static class IndexAlreadyPresentException extends RuntimeException { // // cannot use generics in Throwable // public final Object key; // public final Object previousValue; // // public IndexAlreadyPresentException(Object key, Object previousValue) { // super("Duplicate key found in map. Use #set(...) to override a value. Key: " + key + ", previous value: " + previousValue); // this.key = key; // this.previousValue = previousValue; // } // }
import static ch.codebulb.lambdaomega.L.l; import static ch.codebulb.lambdaomega.L.list; import static ch.codebulb.lambdaomega.M.e; import static ch.codebulb.lambdaomega.M.m; import static ch.codebulb.lambdaomega.S.set; import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_LIST; import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_MAP; import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_MAP_2_ELEMENTS; import static ch.codebulb.lambdaomega.TestUtil.assertEquals; import ch.codebulb.lambdaomega.abstractions.IndexedListI.IndexAlreadyPresentException; import java.util.Map; import static org.junit.Assert.fail; import org.junit.Test;
package ch.codebulb.lambdaomega; /** * Test cases for the {@link M} implementation for {@link IndexedI}. */ public class MBaseIndexedTest { @Test public void testAdd() { // Add individual elements
// Path: src/main/java/ch/codebulb/lambdaomega/L.java // public static <T> L<T> l() { // return new L<>(new ArrayList<>()); // } // // Path: src/main/java/ch/codebulb/lambdaomega/L.java // public static <T> List<T> list(T... ts) { // return l(ts).l; // } // // Path: src/main/java/ch/codebulb/lambdaomega/M.java // public static <K, V> E<K, V> e(K k, V v) { // return new E(k, v); // } // // Path: src/main/java/ch/codebulb/lambdaomega/M.java // public static M m() { // return m(new LinkedHashMap<>()); // } // // Path: src/main/java/ch/codebulb/lambdaomega/S.java // public static <T> Set<T> set(T... ts) { // return C.toSet(ts); // } // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static final List<Integer> EXPECTED_LIST = new ArrayList<>(); // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static final Map<String, Integer> EXPECTED_MAP = new LinkedHashMap<>(); // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static final Map<String, Integer> EXPECTED_MAP_2_ELEMENTS = new LinkedHashMap<>(); // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static <T> void assertEquals(T expected, T... actual) { // Arrays.stream(actual).forEach(it -> Assert.assertEquals(expected, it)); // } // // Path: src/main/java/ch/codebulb/lambdaomega/abstractions/IndexedListI.java // public static class IndexAlreadyPresentException extends RuntimeException { // // cannot use generics in Throwable // public final Object key; // public final Object previousValue; // // public IndexAlreadyPresentException(Object key, Object previousValue) { // super("Duplicate key found in map. Use #set(...) to override a value. Key: " + key + ", previous value: " + previousValue); // this.key = key; // this.previousValue = previousValue; // } // } // Path: src/test/java/ch/codebulb/lambdaomega/MBaseIndexedTest.java import static ch.codebulb.lambdaomega.L.l; import static ch.codebulb.lambdaomega.L.list; import static ch.codebulb.lambdaomega.M.e; import static ch.codebulb.lambdaomega.M.m; import static ch.codebulb.lambdaomega.S.set; import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_LIST; import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_MAP; import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_MAP_2_ELEMENTS; import static ch.codebulb.lambdaomega.TestUtil.assertEquals; import ch.codebulb.lambdaomega.abstractions.IndexedListI.IndexAlreadyPresentException; import java.util.Map; import static org.junit.Assert.fail; import org.junit.Test; package ch.codebulb.lambdaomega; /** * Test cases for the {@link M} implementation for {@link IndexedI}. */ public class MBaseIndexedTest { @Test public void testAdd() { // Add individual elements
assertEquals(EXPECTED_MAP_2_ELEMENTS, m("a", 0).Insert("b", 1).m);
codebulb/LambdaOmega
src/test/java/ch/codebulb/lambdaomega/MBaseIndexedTest.java
// Path: src/main/java/ch/codebulb/lambdaomega/L.java // public static <T> L<T> l() { // return new L<>(new ArrayList<>()); // } // // Path: src/main/java/ch/codebulb/lambdaomega/L.java // public static <T> List<T> list(T... ts) { // return l(ts).l; // } // // Path: src/main/java/ch/codebulb/lambdaomega/M.java // public static <K, V> E<K, V> e(K k, V v) { // return new E(k, v); // } // // Path: src/main/java/ch/codebulb/lambdaomega/M.java // public static M m() { // return m(new LinkedHashMap<>()); // } // // Path: src/main/java/ch/codebulb/lambdaomega/S.java // public static <T> Set<T> set(T... ts) { // return C.toSet(ts); // } // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static final List<Integer> EXPECTED_LIST = new ArrayList<>(); // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static final Map<String, Integer> EXPECTED_MAP = new LinkedHashMap<>(); // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static final Map<String, Integer> EXPECTED_MAP_2_ELEMENTS = new LinkedHashMap<>(); // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static <T> void assertEquals(T expected, T... actual) { // Arrays.stream(actual).forEach(it -> Assert.assertEquals(expected, it)); // } // // Path: src/main/java/ch/codebulb/lambdaomega/abstractions/IndexedListI.java // public static class IndexAlreadyPresentException extends RuntimeException { // // cannot use generics in Throwable // public final Object key; // public final Object previousValue; // // public IndexAlreadyPresentException(Object key, Object previousValue) { // super("Duplicate key found in map. Use #set(...) to override a value. Key: " + key + ", previous value: " + previousValue); // this.key = key; // this.previousValue = previousValue; // } // }
import static ch.codebulb.lambdaomega.L.l; import static ch.codebulb.lambdaomega.L.list; import static ch.codebulb.lambdaomega.M.e; import static ch.codebulb.lambdaomega.M.m; import static ch.codebulb.lambdaomega.S.set; import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_LIST; import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_MAP; import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_MAP_2_ELEMENTS; import static ch.codebulb.lambdaomega.TestUtil.assertEquals; import ch.codebulb.lambdaomega.abstractions.IndexedListI.IndexAlreadyPresentException; import java.util.Map; import static org.junit.Assert.fail; import org.junit.Test;
package ch.codebulb.lambdaomega; /** * Test cases for the {@link M} implementation for {@link IndexedI}. */ public class MBaseIndexedTest { @Test public void testAdd() { // Add individual elements
// Path: src/main/java/ch/codebulb/lambdaomega/L.java // public static <T> L<T> l() { // return new L<>(new ArrayList<>()); // } // // Path: src/main/java/ch/codebulb/lambdaomega/L.java // public static <T> List<T> list(T... ts) { // return l(ts).l; // } // // Path: src/main/java/ch/codebulb/lambdaomega/M.java // public static <K, V> E<K, V> e(K k, V v) { // return new E(k, v); // } // // Path: src/main/java/ch/codebulb/lambdaomega/M.java // public static M m() { // return m(new LinkedHashMap<>()); // } // // Path: src/main/java/ch/codebulb/lambdaomega/S.java // public static <T> Set<T> set(T... ts) { // return C.toSet(ts); // } // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static final List<Integer> EXPECTED_LIST = new ArrayList<>(); // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static final Map<String, Integer> EXPECTED_MAP = new LinkedHashMap<>(); // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static final Map<String, Integer> EXPECTED_MAP_2_ELEMENTS = new LinkedHashMap<>(); // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static <T> void assertEquals(T expected, T... actual) { // Arrays.stream(actual).forEach(it -> Assert.assertEquals(expected, it)); // } // // Path: src/main/java/ch/codebulb/lambdaomega/abstractions/IndexedListI.java // public static class IndexAlreadyPresentException extends RuntimeException { // // cannot use generics in Throwable // public final Object key; // public final Object previousValue; // // public IndexAlreadyPresentException(Object key, Object previousValue) { // super("Duplicate key found in map. Use #set(...) to override a value. Key: " + key + ", previous value: " + previousValue); // this.key = key; // this.previousValue = previousValue; // } // } // Path: src/test/java/ch/codebulb/lambdaomega/MBaseIndexedTest.java import static ch.codebulb.lambdaomega.L.l; import static ch.codebulb.lambdaomega.L.list; import static ch.codebulb.lambdaomega.M.e; import static ch.codebulb.lambdaomega.M.m; import static ch.codebulb.lambdaomega.S.set; import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_LIST; import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_MAP; import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_MAP_2_ELEMENTS; import static ch.codebulb.lambdaomega.TestUtil.assertEquals; import ch.codebulb.lambdaomega.abstractions.IndexedListI.IndexAlreadyPresentException; import java.util.Map; import static org.junit.Assert.fail; import org.junit.Test; package ch.codebulb.lambdaomega; /** * Test cases for the {@link M} implementation for {@link IndexedI}. */ public class MBaseIndexedTest { @Test public void testAdd() { // Add individual elements
assertEquals(EXPECTED_MAP_2_ELEMENTS, m("a", 0).Insert("b", 1).m);
codebulb/LambdaOmega
src/test/java/ch/codebulb/lambdaomega/MBaseIndexedTest.java
// Path: src/main/java/ch/codebulb/lambdaomega/L.java // public static <T> L<T> l() { // return new L<>(new ArrayList<>()); // } // // Path: src/main/java/ch/codebulb/lambdaomega/L.java // public static <T> List<T> list(T... ts) { // return l(ts).l; // } // // Path: src/main/java/ch/codebulb/lambdaomega/M.java // public static <K, V> E<K, V> e(K k, V v) { // return new E(k, v); // } // // Path: src/main/java/ch/codebulb/lambdaomega/M.java // public static M m() { // return m(new LinkedHashMap<>()); // } // // Path: src/main/java/ch/codebulb/lambdaomega/S.java // public static <T> Set<T> set(T... ts) { // return C.toSet(ts); // } // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static final List<Integer> EXPECTED_LIST = new ArrayList<>(); // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static final Map<String, Integer> EXPECTED_MAP = new LinkedHashMap<>(); // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static final Map<String, Integer> EXPECTED_MAP_2_ELEMENTS = new LinkedHashMap<>(); // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static <T> void assertEquals(T expected, T... actual) { // Arrays.stream(actual).forEach(it -> Assert.assertEquals(expected, it)); // } // // Path: src/main/java/ch/codebulb/lambdaomega/abstractions/IndexedListI.java // public static class IndexAlreadyPresentException extends RuntimeException { // // cannot use generics in Throwable // public final Object key; // public final Object previousValue; // // public IndexAlreadyPresentException(Object key, Object previousValue) { // super("Duplicate key found in map. Use #set(...) to override a value. Key: " + key + ", previous value: " + previousValue); // this.key = key; // this.previousValue = previousValue; // } // }
import static ch.codebulb.lambdaomega.L.l; import static ch.codebulb.lambdaomega.L.list; import static ch.codebulb.lambdaomega.M.e; import static ch.codebulb.lambdaomega.M.m; import static ch.codebulb.lambdaomega.S.set; import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_LIST; import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_MAP; import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_MAP_2_ELEMENTS; import static ch.codebulb.lambdaomega.TestUtil.assertEquals; import ch.codebulb.lambdaomega.abstractions.IndexedListI.IndexAlreadyPresentException; import java.util.Map; import static org.junit.Assert.fail; import org.junit.Test;
package ch.codebulb.lambdaomega; /** * Test cases for the {@link M} implementation for {@link IndexedI}. */ public class MBaseIndexedTest { @Test public void testAdd() { // Add individual elements assertEquals(EXPECTED_MAP_2_ELEMENTS, m("a", 0).Insert("b", 1).m); assertEquals(EXPECTED_MAP_2_ELEMENTS, m("a", 0).i("b", 1).m); assertEquals(EXPECTED_MAP_2_ELEMENTS, m("a", 0).insert("b", 1)); M<String, Integer> addMap = m("a", 0).i("b", 1); try { addMap.Insert("b", 2); fail(); }
// Path: src/main/java/ch/codebulb/lambdaomega/L.java // public static <T> L<T> l() { // return new L<>(new ArrayList<>()); // } // // Path: src/main/java/ch/codebulb/lambdaomega/L.java // public static <T> List<T> list(T... ts) { // return l(ts).l; // } // // Path: src/main/java/ch/codebulb/lambdaomega/M.java // public static <K, V> E<K, V> e(K k, V v) { // return new E(k, v); // } // // Path: src/main/java/ch/codebulb/lambdaomega/M.java // public static M m() { // return m(new LinkedHashMap<>()); // } // // Path: src/main/java/ch/codebulb/lambdaomega/S.java // public static <T> Set<T> set(T... ts) { // return C.toSet(ts); // } // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static final List<Integer> EXPECTED_LIST = new ArrayList<>(); // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static final Map<String, Integer> EXPECTED_MAP = new LinkedHashMap<>(); // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static final Map<String, Integer> EXPECTED_MAP_2_ELEMENTS = new LinkedHashMap<>(); // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static <T> void assertEquals(T expected, T... actual) { // Arrays.stream(actual).forEach(it -> Assert.assertEquals(expected, it)); // } // // Path: src/main/java/ch/codebulb/lambdaomega/abstractions/IndexedListI.java // public static class IndexAlreadyPresentException extends RuntimeException { // // cannot use generics in Throwable // public final Object key; // public final Object previousValue; // // public IndexAlreadyPresentException(Object key, Object previousValue) { // super("Duplicate key found in map. Use #set(...) to override a value. Key: " + key + ", previous value: " + previousValue); // this.key = key; // this.previousValue = previousValue; // } // } // Path: src/test/java/ch/codebulb/lambdaomega/MBaseIndexedTest.java import static ch.codebulb.lambdaomega.L.l; import static ch.codebulb.lambdaomega.L.list; import static ch.codebulb.lambdaomega.M.e; import static ch.codebulb.lambdaomega.M.m; import static ch.codebulb.lambdaomega.S.set; import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_LIST; import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_MAP; import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_MAP_2_ELEMENTS; import static ch.codebulb.lambdaomega.TestUtil.assertEquals; import ch.codebulb.lambdaomega.abstractions.IndexedListI.IndexAlreadyPresentException; import java.util.Map; import static org.junit.Assert.fail; import org.junit.Test; package ch.codebulb.lambdaomega; /** * Test cases for the {@link M} implementation for {@link IndexedI}. */ public class MBaseIndexedTest { @Test public void testAdd() { // Add individual elements assertEquals(EXPECTED_MAP_2_ELEMENTS, m("a", 0).Insert("b", 1).m); assertEquals(EXPECTED_MAP_2_ELEMENTS, m("a", 0).i("b", 1).m); assertEquals(EXPECTED_MAP_2_ELEMENTS, m("a", 0).insert("b", 1)); M<String, Integer> addMap = m("a", 0).i("b", 1); try { addMap.Insert("b", 2); fail(); }
catch (IndexAlreadyPresentException ex) {
codebulb/LambdaOmega
src/test/java/ch/codebulb/lambdaomega/MBaseIndexedTest.java
// Path: src/main/java/ch/codebulb/lambdaomega/L.java // public static <T> L<T> l() { // return new L<>(new ArrayList<>()); // } // // Path: src/main/java/ch/codebulb/lambdaomega/L.java // public static <T> List<T> list(T... ts) { // return l(ts).l; // } // // Path: src/main/java/ch/codebulb/lambdaomega/M.java // public static <K, V> E<K, V> e(K k, V v) { // return new E(k, v); // } // // Path: src/main/java/ch/codebulb/lambdaomega/M.java // public static M m() { // return m(new LinkedHashMap<>()); // } // // Path: src/main/java/ch/codebulb/lambdaomega/S.java // public static <T> Set<T> set(T... ts) { // return C.toSet(ts); // } // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static final List<Integer> EXPECTED_LIST = new ArrayList<>(); // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static final Map<String, Integer> EXPECTED_MAP = new LinkedHashMap<>(); // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static final Map<String, Integer> EXPECTED_MAP_2_ELEMENTS = new LinkedHashMap<>(); // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static <T> void assertEquals(T expected, T... actual) { // Arrays.stream(actual).forEach(it -> Assert.assertEquals(expected, it)); // } // // Path: src/main/java/ch/codebulb/lambdaomega/abstractions/IndexedListI.java // public static class IndexAlreadyPresentException extends RuntimeException { // // cannot use generics in Throwable // public final Object key; // public final Object previousValue; // // public IndexAlreadyPresentException(Object key, Object previousValue) { // super("Duplicate key found in map. Use #set(...) to override a value. Key: " + key + ", previous value: " + previousValue); // this.key = key; // this.previousValue = previousValue; // } // }
import static ch.codebulb.lambdaomega.L.l; import static ch.codebulb.lambdaomega.L.list; import static ch.codebulb.lambdaomega.M.e; import static ch.codebulb.lambdaomega.M.m; import static ch.codebulb.lambdaomega.S.set; import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_LIST; import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_MAP; import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_MAP_2_ELEMENTS; import static ch.codebulb.lambdaomega.TestUtil.assertEquals; import ch.codebulb.lambdaomega.abstractions.IndexedListI.IndexAlreadyPresentException; import java.util.Map; import static org.junit.Assert.fail; import org.junit.Test;
addMap.Insert("b", 2); fail(); } catch (IndexAlreadyPresentException ex) { assertEquals("b", ex.key); assertEquals(1, ex.previousValue); } assertEquals(EXPECTED_MAP_2_ELEMENTS, addMap.m); addMap = m("a", 0).i("b", 1); try { addMap.insert("b", 2); fail(); } catch (IndexAlreadyPresentException ex) { assertEquals("b", ex.key); assertEquals(1, ex.previousValue); } assertEquals(EXPECTED_MAP_2_ELEMENTS, addMap.m); addMap = m("a", 0).i("b", 1); try { addMap.i("b", 2); fail(); } catch (IndexAlreadyPresentException ex) { assertEquals("b", ex.key); assertEquals(1, ex.previousValue); } assertEquals(EXPECTED_MAP_2_ELEMENTS, addMap.m); // Add all entries
// Path: src/main/java/ch/codebulb/lambdaomega/L.java // public static <T> L<T> l() { // return new L<>(new ArrayList<>()); // } // // Path: src/main/java/ch/codebulb/lambdaomega/L.java // public static <T> List<T> list(T... ts) { // return l(ts).l; // } // // Path: src/main/java/ch/codebulb/lambdaomega/M.java // public static <K, V> E<K, V> e(K k, V v) { // return new E(k, v); // } // // Path: src/main/java/ch/codebulb/lambdaomega/M.java // public static M m() { // return m(new LinkedHashMap<>()); // } // // Path: src/main/java/ch/codebulb/lambdaomega/S.java // public static <T> Set<T> set(T... ts) { // return C.toSet(ts); // } // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static final List<Integer> EXPECTED_LIST = new ArrayList<>(); // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static final Map<String, Integer> EXPECTED_MAP = new LinkedHashMap<>(); // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static final Map<String, Integer> EXPECTED_MAP_2_ELEMENTS = new LinkedHashMap<>(); // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static <T> void assertEquals(T expected, T... actual) { // Arrays.stream(actual).forEach(it -> Assert.assertEquals(expected, it)); // } // // Path: src/main/java/ch/codebulb/lambdaomega/abstractions/IndexedListI.java // public static class IndexAlreadyPresentException extends RuntimeException { // // cannot use generics in Throwable // public final Object key; // public final Object previousValue; // // public IndexAlreadyPresentException(Object key, Object previousValue) { // super("Duplicate key found in map. Use #set(...) to override a value. Key: " + key + ", previous value: " + previousValue); // this.key = key; // this.previousValue = previousValue; // } // } // Path: src/test/java/ch/codebulb/lambdaomega/MBaseIndexedTest.java import static ch.codebulb.lambdaomega.L.l; import static ch.codebulb.lambdaomega.L.list; import static ch.codebulb.lambdaomega.M.e; import static ch.codebulb.lambdaomega.M.m; import static ch.codebulb.lambdaomega.S.set; import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_LIST; import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_MAP; import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_MAP_2_ELEMENTS; import static ch.codebulb.lambdaomega.TestUtil.assertEquals; import ch.codebulb.lambdaomega.abstractions.IndexedListI.IndexAlreadyPresentException; import java.util.Map; import static org.junit.Assert.fail; import org.junit.Test; addMap.Insert("b", 2); fail(); } catch (IndexAlreadyPresentException ex) { assertEquals("b", ex.key); assertEquals(1, ex.previousValue); } assertEquals(EXPECTED_MAP_2_ELEMENTS, addMap.m); addMap = m("a", 0).i("b", 1); try { addMap.insert("b", 2); fail(); } catch (IndexAlreadyPresentException ex) { assertEquals("b", ex.key); assertEquals(1, ex.previousValue); } assertEquals(EXPECTED_MAP_2_ELEMENTS, addMap.m); addMap = m("a", 0).i("b", 1); try { addMap.i("b", 2); fail(); } catch (IndexAlreadyPresentException ex) { assertEquals("b", ex.key); assertEquals(1, ex.previousValue); } assertEquals(EXPECTED_MAP_2_ELEMENTS, addMap.m); // Add all entries
assertEquals(EXPECTED_MAP, m("a", 0).InsertAll(m("b", 1).i("c", 2).m).m);
codebulb/LambdaOmega
src/test/java/ch/codebulb/lambdaomega/MBaseIndexedTest.java
// Path: src/main/java/ch/codebulb/lambdaomega/L.java // public static <T> L<T> l() { // return new L<>(new ArrayList<>()); // } // // Path: src/main/java/ch/codebulb/lambdaomega/L.java // public static <T> List<T> list(T... ts) { // return l(ts).l; // } // // Path: src/main/java/ch/codebulb/lambdaomega/M.java // public static <K, V> E<K, V> e(K k, V v) { // return new E(k, v); // } // // Path: src/main/java/ch/codebulb/lambdaomega/M.java // public static M m() { // return m(new LinkedHashMap<>()); // } // // Path: src/main/java/ch/codebulb/lambdaomega/S.java // public static <T> Set<T> set(T... ts) { // return C.toSet(ts); // } // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static final List<Integer> EXPECTED_LIST = new ArrayList<>(); // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static final Map<String, Integer> EXPECTED_MAP = new LinkedHashMap<>(); // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static final Map<String, Integer> EXPECTED_MAP_2_ELEMENTS = new LinkedHashMap<>(); // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static <T> void assertEquals(T expected, T... actual) { // Arrays.stream(actual).forEach(it -> Assert.assertEquals(expected, it)); // } // // Path: src/main/java/ch/codebulb/lambdaomega/abstractions/IndexedListI.java // public static class IndexAlreadyPresentException extends RuntimeException { // // cannot use generics in Throwable // public final Object key; // public final Object previousValue; // // public IndexAlreadyPresentException(Object key, Object previousValue) { // super("Duplicate key found in map. Use #set(...) to override a value. Key: " + key + ", previous value: " + previousValue); // this.key = key; // this.previousValue = previousValue; // } // }
import static ch.codebulb.lambdaomega.L.l; import static ch.codebulb.lambdaomega.L.list; import static ch.codebulb.lambdaomega.M.e; import static ch.codebulb.lambdaomega.M.m; import static ch.codebulb.lambdaomega.S.set; import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_LIST; import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_MAP; import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_MAP_2_ELEMENTS; import static ch.codebulb.lambdaomega.TestUtil.assertEquals; import ch.codebulb.lambdaomega.abstractions.IndexedListI.IndexAlreadyPresentException; import java.util.Map; import static org.junit.Assert.fail; import org.junit.Test;
addMap.I(m("b", 1).i("c", 2), m("a", 3)); fail(); } catch (IndexAlreadyPresentException ex) {} assertEquals(EXPECTED_MAP_2_ELEMENTS, addMap.m); // Put at index M<String, Number> putMap = m(String.class, Number.class).i("a", 3).i("b", 1).i("c", 2); assertEquals(EXPECTED_MAP, putMap.put("a", 0), putMap.m); assertEquals(EXPECTED_MAP, m("a", 3).i("b", 1).i("c", 2).Put("a", 0).m); assertEquals(EXPECTED_MAP, m("a", 3).i("b", 1).i("c", 2).p("a", 0).m); putMap = m(String.class, Number.class).i("a", null).i("b", 1).i("c", 2); assertEquals(null, putMap.putIfAbsent("a", 0)); assertEquals(EXPECTED_MAP, putMap.m); assertEquals(1, putMap.putIfAbsent("b", 3)); assertEquals(EXPECTED_MAP, putMap.m); assertEquals(EXPECTED_MAP, m("a", 0).PutAll(m("b", 1).m, m("c", 2).m).m); assertEquals(EXPECTED_MAP, m("a", 0).P(m("b", 1).m, m("c", 2).m).m); assertEquals(EXPECTED_MAP, m("a", 0).putAll(m("b", 1).m, m("c", 2).m)); assertEquals(EXPECTED_MAP, m("a", 0).PutAll(m("b", 1), m("c", 2)).m); assertEquals(EXPECTED_MAP, m("a", 0).P(m("b", 1), m("c", 2)).m); assertEquals(EXPECTED_MAP, m("a", 0).putAll(m("b", 1), m("c", 2))); // Set / replace assertEquals(EXPECTED_MAP, m("a", 3).i("b", 1).i("c", 2).Set("a", 0).m); assertEquals(EXPECTED_MAP, m("a", 3).i("b", 1).i("c", 2).s("a", 0).m); M<String, Number> replaceMap = m(String.class, Number.class).i("a", 3).i("b", 1).i("c", 2);
// Path: src/main/java/ch/codebulb/lambdaomega/L.java // public static <T> L<T> l() { // return new L<>(new ArrayList<>()); // } // // Path: src/main/java/ch/codebulb/lambdaomega/L.java // public static <T> List<T> list(T... ts) { // return l(ts).l; // } // // Path: src/main/java/ch/codebulb/lambdaomega/M.java // public static <K, V> E<K, V> e(K k, V v) { // return new E(k, v); // } // // Path: src/main/java/ch/codebulb/lambdaomega/M.java // public static M m() { // return m(new LinkedHashMap<>()); // } // // Path: src/main/java/ch/codebulb/lambdaomega/S.java // public static <T> Set<T> set(T... ts) { // return C.toSet(ts); // } // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static final List<Integer> EXPECTED_LIST = new ArrayList<>(); // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static final Map<String, Integer> EXPECTED_MAP = new LinkedHashMap<>(); // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static final Map<String, Integer> EXPECTED_MAP_2_ELEMENTS = new LinkedHashMap<>(); // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static <T> void assertEquals(T expected, T... actual) { // Arrays.stream(actual).forEach(it -> Assert.assertEquals(expected, it)); // } // // Path: src/main/java/ch/codebulb/lambdaomega/abstractions/IndexedListI.java // public static class IndexAlreadyPresentException extends RuntimeException { // // cannot use generics in Throwable // public final Object key; // public final Object previousValue; // // public IndexAlreadyPresentException(Object key, Object previousValue) { // super("Duplicate key found in map. Use #set(...) to override a value. Key: " + key + ", previous value: " + previousValue); // this.key = key; // this.previousValue = previousValue; // } // } // Path: src/test/java/ch/codebulb/lambdaomega/MBaseIndexedTest.java import static ch.codebulb.lambdaomega.L.l; import static ch.codebulb.lambdaomega.L.list; import static ch.codebulb.lambdaomega.M.e; import static ch.codebulb.lambdaomega.M.m; import static ch.codebulb.lambdaomega.S.set; import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_LIST; import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_MAP; import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_MAP_2_ELEMENTS; import static ch.codebulb.lambdaomega.TestUtil.assertEquals; import ch.codebulb.lambdaomega.abstractions.IndexedListI.IndexAlreadyPresentException; import java.util.Map; import static org.junit.Assert.fail; import org.junit.Test; addMap.I(m("b", 1).i("c", 2), m("a", 3)); fail(); } catch (IndexAlreadyPresentException ex) {} assertEquals(EXPECTED_MAP_2_ELEMENTS, addMap.m); // Put at index M<String, Number> putMap = m(String.class, Number.class).i("a", 3).i("b", 1).i("c", 2); assertEquals(EXPECTED_MAP, putMap.put("a", 0), putMap.m); assertEquals(EXPECTED_MAP, m("a", 3).i("b", 1).i("c", 2).Put("a", 0).m); assertEquals(EXPECTED_MAP, m("a", 3).i("b", 1).i("c", 2).p("a", 0).m); putMap = m(String.class, Number.class).i("a", null).i("b", 1).i("c", 2); assertEquals(null, putMap.putIfAbsent("a", 0)); assertEquals(EXPECTED_MAP, putMap.m); assertEquals(1, putMap.putIfAbsent("b", 3)); assertEquals(EXPECTED_MAP, putMap.m); assertEquals(EXPECTED_MAP, m("a", 0).PutAll(m("b", 1).m, m("c", 2).m).m); assertEquals(EXPECTED_MAP, m("a", 0).P(m("b", 1).m, m("c", 2).m).m); assertEquals(EXPECTED_MAP, m("a", 0).putAll(m("b", 1).m, m("c", 2).m)); assertEquals(EXPECTED_MAP, m("a", 0).PutAll(m("b", 1), m("c", 2)).m); assertEquals(EXPECTED_MAP, m("a", 0).P(m("b", 1), m("c", 2)).m); assertEquals(EXPECTED_MAP, m("a", 0).putAll(m("b", 1), m("c", 2))); // Set / replace assertEquals(EXPECTED_MAP, m("a", 3).i("b", 1).i("c", 2).Set("a", 0).m); assertEquals(EXPECTED_MAP, m("a", 3).i("b", 1).i("c", 2).s("a", 0).m); M<String, Number> replaceMap = m(String.class, Number.class).i("a", 3).i("b", 1).i("c", 2);
assertEquals(EXPECTED_MAP, replaceMap.set("a", 0), replaceMap.m);
codebulb/LambdaOmega
src/test/java/ch/codebulb/lambdaomega/MBaseIndexedTest.java
// Path: src/main/java/ch/codebulb/lambdaomega/L.java // public static <T> L<T> l() { // return new L<>(new ArrayList<>()); // } // // Path: src/main/java/ch/codebulb/lambdaomega/L.java // public static <T> List<T> list(T... ts) { // return l(ts).l; // } // // Path: src/main/java/ch/codebulb/lambdaomega/M.java // public static <K, V> E<K, V> e(K k, V v) { // return new E(k, v); // } // // Path: src/main/java/ch/codebulb/lambdaomega/M.java // public static M m() { // return m(new LinkedHashMap<>()); // } // // Path: src/main/java/ch/codebulb/lambdaomega/S.java // public static <T> Set<T> set(T... ts) { // return C.toSet(ts); // } // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static final List<Integer> EXPECTED_LIST = new ArrayList<>(); // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static final Map<String, Integer> EXPECTED_MAP = new LinkedHashMap<>(); // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static final Map<String, Integer> EXPECTED_MAP_2_ELEMENTS = new LinkedHashMap<>(); // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static <T> void assertEquals(T expected, T... actual) { // Arrays.stream(actual).forEach(it -> Assert.assertEquals(expected, it)); // } // // Path: src/main/java/ch/codebulb/lambdaomega/abstractions/IndexedListI.java // public static class IndexAlreadyPresentException extends RuntimeException { // // cannot use generics in Throwable // public final Object key; // public final Object previousValue; // // public IndexAlreadyPresentException(Object key, Object previousValue) { // super("Duplicate key found in map. Use #set(...) to override a value. Key: " + key + ", previous value: " + previousValue); // this.key = key; // this.previousValue = previousValue; // } // }
import static ch.codebulb.lambdaomega.L.l; import static ch.codebulb.lambdaomega.L.list; import static ch.codebulb.lambdaomega.M.e; import static ch.codebulb.lambdaomega.M.m; import static ch.codebulb.lambdaomega.S.set; import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_LIST; import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_MAP; import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_MAP_2_ELEMENTS; import static ch.codebulb.lambdaomega.TestUtil.assertEquals; import ch.codebulb.lambdaomega.abstractions.IndexedListI.IndexAlreadyPresentException; import java.util.Map; import static org.junit.Assert.fail; import org.junit.Test;
assertEquals(EXPECTED_MAP, m("a", 3).i("b", 1).i("c", 2).Set("a", 0).m); assertEquals(EXPECTED_MAP, m("a", 3).i("b", 1).i("c", 2).s("a", 0).m); M<String, Number> replaceMap = m(String.class, Number.class).i("a", 3).i("b", 1).i("c", 2); assertEquals(EXPECTED_MAP, replaceMap.set("a", 0), replaceMap.m); assertEquals(EXPECTED_MAP, m("a", 0).SetAll(m("b", 1).m, m("c", 2).m).m); assertEquals(EXPECTED_MAP, m("a", 0).SetAll(m("b", 1), m("c", 2)).m); assertEquals(EXPECTED_MAP, m("a", 0).S(m("b", 1).m, m("c", 2).m).m); assertEquals(EXPECTED_MAP, m("a", 0).S(m("b", 1), m("c", 2)).m); assertEquals(EXPECTED_MAP, m("a", 0).setAll(m("b", 1).m, m("c", 2).m)); assertEquals(EXPECTED_MAP, m("a", 0).setAll(m("b", 1), m("c", 2))); replaceMap = m(String.class, Number.class).i("a", 3).i("b", 1).i("c", 2); Map<String, Number> replaceMapExpected = m(String.class, Number.class).i("a", 3).i("b", 1).i("c", 2).m; assertEquals(3, replaceMapExpected.replace("a", 0), replaceMap.replace("a", 0)); assertEquals(EXPECTED_MAP, replaceMapExpected, replaceMap.m); assertEquals(null, replaceMapExpected.replace("d", 3), replaceMap.replace("d", 3)); assertEquals(EXPECTED_MAP, replaceMapExpected, replaceMap.m); replaceMap = m(String.class, Number.class).i("a", 3).i("b", 1).i("c", 2); replaceMapExpected = m(String.class, Number.class).i("a", 3).i("b", 1).i("c", 2).m; assertEquals(true, replaceMapExpected.replace("a", 3, 0), replaceMap.replace("a", 3, 0)); assertEquals(EXPECTED_MAP, replaceMapExpected, replaceMap.m); assertEquals(false, replaceMapExpected.replace("d", 4, 5), replaceMap.replace("d", 4, 5)); assertEquals(EXPECTED_MAP, replaceMapExpected, replaceMap.m); } @Test public void testRemove() { // Remove individual entries at index
// Path: src/main/java/ch/codebulb/lambdaomega/L.java // public static <T> L<T> l() { // return new L<>(new ArrayList<>()); // } // // Path: src/main/java/ch/codebulb/lambdaomega/L.java // public static <T> List<T> list(T... ts) { // return l(ts).l; // } // // Path: src/main/java/ch/codebulb/lambdaomega/M.java // public static <K, V> E<K, V> e(K k, V v) { // return new E(k, v); // } // // Path: src/main/java/ch/codebulb/lambdaomega/M.java // public static M m() { // return m(new LinkedHashMap<>()); // } // // Path: src/main/java/ch/codebulb/lambdaomega/S.java // public static <T> Set<T> set(T... ts) { // return C.toSet(ts); // } // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static final List<Integer> EXPECTED_LIST = new ArrayList<>(); // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static final Map<String, Integer> EXPECTED_MAP = new LinkedHashMap<>(); // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static final Map<String, Integer> EXPECTED_MAP_2_ELEMENTS = new LinkedHashMap<>(); // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static <T> void assertEquals(T expected, T... actual) { // Arrays.stream(actual).forEach(it -> Assert.assertEquals(expected, it)); // } // // Path: src/main/java/ch/codebulb/lambdaomega/abstractions/IndexedListI.java // public static class IndexAlreadyPresentException extends RuntimeException { // // cannot use generics in Throwable // public final Object key; // public final Object previousValue; // // public IndexAlreadyPresentException(Object key, Object previousValue) { // super("Duplicate key found in map. Use #set(...) to override a value. Key: " + key + ", previous value: " + previousValue); // this.key = key; // this.previousValue = previousValue; // } // } // Path: src/test/java/ch/codebulb/lambdaomega/MBaseIndexedTest.java import static ch.codebulb.lambdaomega.L.l; import static ch.codebulb.lambdaomega.L.list; import static ch.codebulb.lambdaomega.M.e; import static ch.codebulb.lambdaomega.M.m; import static ch.codebulb.lambdaomega.S.set; import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_LIST; import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_MAP; import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_MAP_2_ELEMENTS; import static ch.codebulb.lambdaomega.TestUtil.assertEquals; import ch.codebulb.lambdaomega.abstractions.IndexedListI.IndexAlreadyPresentException; import java.util.Map; import static org.junit.Assert.fail; import org.junit.Test; assertEquals(EXPECTED_MAP, m("a", 3).i("b", 1).i("c", 2).Set("a", 0).m); assertEquals(EXPECTED_MAP, m("a", 3).i("b", 1).i("c", 2).s("a", 0).m); M<String, Number> replaceMap = m(String.class, Number.class).i("a", 3).i("b", 1).i("c", 2); assertEquals(EXPECTED_MAP, replaceMap.set("a", 0), replaceMap.m); assertEquals(EXPECTED_MAP, m("a", 0).SetAll(m("b", 1).m, m("c", 2).m).m); assertEquals(EXPECTED_MAP, m("a", 0).SetAll(m("b", 1), m("c", 2)).m); assertEquals(EXPECTED_MAP, m("a", 0).S(m("b", 1).m, m("c", 2).m).m); assertEquals(EXPECTED_MAP, m("a", 0).S(m("b", 1), m("c", 2)).m); assertEquals(EXPECTED_MAP, m("a", 0).setAll(m("b", 1).m, m("c", 2).m)); assertEquals(EXPECTED_MAP, m("a", 0).setAll(m("b", 1), m("c", 2))); replaceMap = m(String.class, Number.class).i("a", 3).i("b", 1).i("c", 2); Map<String, Number> replaceMapExpected = m(String.class, Number.class).i("a", 3).i("b", 1).i("c", 2).m; assertEquals(3, replaceMapExpected.replace("a", 0), replaceMap.replace("a", 0)); assertEquals(EXPECTED_MAP, replaceMapExpected, replaceMap.m); assertEquals(null, replaceMapExpected.replace("d", 3), replaceMap.replace("d", 3)); assertEquals(EXPECTED_MAP, replaceMapExpected, replaceMap.m); replaceMap = m(String.class, Number.class).i("a", 3).i("b", 1).i("c", 2); replaceMapExpected = m(String.class, Number.class).i("a", 3).i("b", 1).i("c", 2).m; assertEquals(true, replaceMapExpected.replace("a", 3, 0), replaceMap.replace("a", 3, 0)); assertEquals(EXPECTED_MAP, replaceMapExpected, replaceMap.m); assertEquals(false, replaceMapExpected.replace("d", 4, 5), replaceMap.replace("d", 4, 5)); assertEquals(EXPECTED_MAP, replaceMapExpected, replaceMap.m); } @Test public void testRemove() { // Remove individual entries at index
assertEquals(EXPECTED_MAP, m("d", 3).i("e", 4).i("a", 0).i("b", 1).i("c", 2).DeleteKey("d", "e").m);
codebulb/LambdaOmega
src/test/java/ch/codebulb/lambdaomega/MBaseIndexedTest.java
// Path: src/main/java/ch/codebulb/lambdaomega/L.java // public static <T> L<T> l() { // return new L<>(new ArrayList<>()); // } // // Path: src/main/java/ch/codebulb/lambdaomega/L.java // public static <T> List<T> list(T... ts) { // return l(ts).l; // } // // Path: src/main/java/ch/codebulb/lambdaomega/M.java // public static <K, V> E<K, V> e(K k, V v) { // return new E(k, v); // } // // Path: src/main/java/ch/codebulb/lambdaomega/M.java // public static M m() { // return m(new LinkedHashMap<>()); // } // // Path: src/main/java/ch/codebulb/lambdaomega/S.java // public static <T> Set<T> set(T... ts) { // return C.toSet(ts); // } // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static final List<Integer> EXPECTED_LIST = new ArrayList<>(); // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static final Map<String, Integer> EXPECTED_MAP = new LinkedHashMap<>(); // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static final Map<String, Integer> EXPECTED_MAP_2_ELEMENTS = new LinkedHashMap<>(); // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static <T> void assertEquals(T expected, T... actual) { // Arrays.stream(actual).forEach(it -> Assert.assertEquals(expected, it)); // } // // Path: src/main/java/ch/codebulb/lambdaomega/abstractions/IndexedListI.java // public static class IndexAlreadyPresentException extends RuntimeException { // // cannot use generics in Throwable // public final Object key; // public final Object previousValue; // // public IndexAlreadyPresentException(Object key, Object previousValue) { // super("Duplicate key found in map. Use #set(...) to override a value. Key: " + key + ", previous value: " + previousValue); // this.key = key; // this.previousValue = previousValue; // } // }
import static ch.codebulb.lambdaomega.L.l; import static ch.codebulb.lambdaomega.L.list; import static ch.codebulb.lambdaomega.M.e; import static ch.codebulb.lambdaomega.M.m; import static ch.codebulb.lambdaomega.S.set; import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_LIST; import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_MAP; import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_MAP_2_ELEMENTS; import static ch.codebulb.lambdaomega.TestUtil.assertEquals; import ch.codebulb.lambdaomega.abstractions.IndexedListI.IndexAlreadyPresentException; import java.util.Map; import static org.junit.Assert.fail; import org.junit.Test;
replaceMapExpected = m(String.class, Number.class).i("a", 3).i("b", 1).i("c", 2).m; assertEquals(true, replaceMapExpected.replace("a", 3, 0), replaceMap.replace("a", 3, 0)); assertEquals(EXPECTED_MAP, replaceMapExpected, replaceMap.m); assertEquals(false, replaceMapExpected.replace("d", 4, 5), replaceMap.replace("d", 4, 5)); assertEquals(EXPECTED_MAP, replaceMapExpected, replaceMap.m); } @Test public void testRemove() { // Remove individual entries at index assertEquals(EXPECTED_MAP, m("d", 3).i("e", 4).i("a", 0).i("b", 1).i("c", 2).DeleteKey("d", "e").m); assertEquals(EXPECTED_MAP, m("d", 3).i("e", 4).i("a", 0).i("b", 1).i("c", 2).d("d", "e").m); assertEquals(EXPECTED_MAP, m("d", 3).i("e", 4).i("a", 0).i("b", 1).i("c", 2).deleteKey("d", "e")); assertEquals(EXPECTED_MAP, m("d", 3).i("e", 4).i("a", 0).i("b", 1).i("c", 2).DeleteValue(3, 4).m); assertEquals(EXPECTED_MAP, m("d", 3).i("e", 4).i("a", 0).i("b", 1).i("c", 2).deleteValue(3, 4)); assertEquals(EXPECTED_MAP, m("d", 3).i("e", 3).i("a", 0).i("b", 1).i("c", 2).deleteValue(3, 3)); assertEquals(EXPECTED_MAP, m("d", 3).i("e", 4).i("a", 0).i("b", 1).i("c", 2).deleteValue(3, 4, -1)); // Conditional remove M<String, Number> removeMap = m(String.class, Number.class).i("d", 3).i("a", 0).i("b", 1).i("c", 2); Map<String, Number> removeMapExpected = m(String.class, Number.class).i("d", 3).i("a", 0).i("b", 1).i("c", 2).m; assertEquals(true, removeMap.deleteIfMatches("d", 3)); assertEquals(true, removeMapExpected.remove("d", 3)); assertEquals(EXPECTED_MAP, removeMap.m); assertEquals(false, removeMap.deleteIfMatches("a", 4)); assertEquals(false, removeMapExpected.remove("a", 4)); assertEquals(EXPECTED_MAP, removeMapExpected); // Remove all entries
// Path: src/main/java/ch/codebulb/lambdaomega/L.java // public static <T> L<T> l() { // return new L<>(new ArrayList<>()); // } // // Path: src/main/java/ch/codebulb/lambdaomega/L.java // public static <T> List<T> list(T... ts) { // return l(ts).l; // } // // Path: src/main/java/ch/codebulb/lambdaomega/M.java // public static <K, V> E<K, V> e(K k, V v) { // return new E(k, v); // } // // Path: src/main/java/ch/codebulb/lambdaomega/M.java // public static M m() { // return m(new LinkedHashMap<>()); // } // // Path: src/main/java/ch/codebulb/lambdaomega/S.java // public static <T> Set<T> set(T... ts) { // return C.toSet(ts); // } // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static final List<Integer> EXPECTED_LIST = new ArrayList<>(); // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static final Map<String, Integer> EXPECTED_MAP = new LinkedHashMap<>(); // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static final Map<String, Integer> EXPECTED_MAP_2_ELEMENTS = new LinkedHashMap<>(); // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static <T> void assertEquals(T expected, T... actual) { // Arrays.stream(actual).forEach(it -> Assert.assertEquals(expected, it)); // } // // Path: src/main/java/ch/codebulb/lambdaomega/abstractions/IndexedListI.java // public static class IndexAlreadyPresentException extends RuntimeException { // // cannot use generics in Throwable // public final Object key; // public final Object previousValue; // // public IndexAlreadyPresentException(Object key, Object previousValue) { // super("Duplicate key found in map. Use #set(...) to override a value. Key: " + key + ", previous value: " + previousValue); // this.key = key; // this.previousValue = previousValue; // } // } // Path: src/test/java/ch/codebulb/lambdaomega/MBaseIndexedTest.java import static ch.codebulb.lambdaomega.L.l; import static ch.codebulb.lambdaomega.L.list; import static ch.codebulb.lambdaomega.M.e; import static ch.codebulb.lambdaomega.M.m; import static ch.codebulb.lambdaomega.S.set; import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_LIST; import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_MAP; import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_MAP_2_ELEMENTS; import static ch.codebulb.lambdaomega.TestUtil.assertEquals; import ch.codebulb.lambdaomega.abstractions.IndexedListI.IndexAlreadyPresentException; import java.util.Map; import static org.junit.Assert.fail; import org.junit.Test; replaceMapExpected = m(String.class, Number.class).i("a", 3).i("b", 1).i("c", 2).m; assertEquals(true, replaceMapExpected.replace("a", 3, 0), replaceMap.replace("a", 3, 0)); assertEquals(EXPECTED_MAP, replaceMapExpected, replaceMap.m); assertEquals(false, replaceMapExpected.replace("d", 4, 5), replaceMap.replace("d", 4, 5)); assertEquals(EXPECTED_MAP, replaceMapExpected, replaceMap.m); } @Test public void testRemove() { // Remove individual entries at index assertEquals(EXPECTED_MAP, m("d", 3).i("e", 4).i("a", 0).i("b", 1).i("c", 2).DeleteKey("d", "e").m); assertEquals(EXPECTED_MAP, m("d", 3).i("e", 4).i("a", 0).i("b", 1).i("c", 2).d("d", "e").m); assertEquals(EXPECTED_MAP, m("d", 3).i("e", 4).i("a", 0).i("b", 1).i("c", 2).deleteKey("d", "e")); assertEquals(EXPECTED_MAP, m("d", 3).i("e", 4).i("a", 0).i("b", 1).i("c", 2).DeleteValue(3, 4).m); assertEquals(EXPECTED_MAP, m("d", 3).i("e", 4).i("a", 0).i("b", 1).i("c", 2).deleteValue(3, 4)); assertEquals(EXPECTED_MAP, m("d", 3).i("e", 3).i("a", 0).i("b", 1).i("c", 2).deleteValue(3, 3)); assertEquals(EXPECTED_MAP, m("d", 3).i("e", 4).i("a", 0).i("b", 1).i("c", 2).deleteValue(3, 4, -1)); // Conditional remove M<String, Number> removeMap = m(String.class, Number.class).i("d", 3).i("a", 0).i("b", 1).i("c", 2); Map<String, Number> removeMapExpected = m(String.class, Number.class).i("d", 3).i("a", 0).i("b", 1).i("c", 2).m; assertEquals(true, removeMap.deleteIfMatches("d", 3)); assertEquals(true, removeMapExpected.remove("d", 3)); assertEquals(EXPECTED_MAP, removeMap.m); assertEquals(false, removeMap.deleteIfMatches("a", 4)); assertEquals(false, removeMapExpected.remove("a", 4)); assertEquals(EXPECTED_MAP, removeMapExpected); // Remove all entries
assertEquals(EXPECTED_MAP, m("d", 3).i("e", 4).i("f", 5).i("a", 0).i("b", 1).i("c", 2).DeleteAllKeys(list("d"), list("e", "f")).m);
codebulb/LambdaOmega
src/test/java/ch/codebulb/lambdaomega/MBaseIndexedTest.java
// Path: src/main/java/ch/codebulb/lambdaomega/L.java // public static <T> L<T> l() { // return new L<>(new ArrayList<>()); // } // // Path: src/main/java/ch/codebulb/lambdaomega/L.java // public static <T> List<T> list(T... ts) { // return l(ts).l; // } // // Path: src/main/java/ch/codebulb/lambdaomega/M.java // public static <K, V> E<K, V> e(K k, V v) { // return new E(k, v); // } // // Path: src/main/java/ch/codebulb/lambdaomega/M.java // public static M m() { // return m(new LinkedHashMap<>()); // } // // Path: src/main/java/ch/codebulb/lambdaomega/S.java // public static <T> Set<T> set(T... ts) { // return C.toSet(ts); // } // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static final List<Integer> EXPECTED_LIST = new ArrayList<>(); // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static final Map<String, Integer> EXPECTED_MAP = new LinkedHashMap<>(); // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static final Map<String, Integer> EXPECTED_MAP_2_ELEMENTS = new LinkedHashMap<>(); // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static <T> void assertEquals(T expected, T... actual) { // Arrays.stream(actual).forEach(it -> Assert.assertEquals(expected, it)); // } // // Path: src/main/java/ch/codebulb/lambdaomega/abstractions/IndexedListI.java // public static class IndexAlreadyPresentException extends RuntimeException { // // cannot use generics in Throwable // public final Object key; // public final Object previousValue; // // public IndexAlreadyPresentException(Object key, Object previousValue) { // super("Duplicate key found in map. Use #set(...) to override a value. Key: " + key + ", previous value: " + previousValue); // this.key = key; // this.previousValue = previousValue; // } // }
import static ch.codebulb.lambdaomega.L.l; import static ch.codebulb.lambdaomega.L.list; import static ch.codebulb.lambdaomega.M.e; import static ch.codebulb.lambdaomega.M.m; import static ch.codebulb.lambdaomega.S.set; import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_LIST; import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_MAP; import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_MAP_2_ELEMENTS; import static ch.codebulb.lambdaomega.TestUtil.assertEquals; import ch.codebulb.lambdaomega.abstractions.IndexedListI.IndexAlreadyPresentException; import java.util.Map; import static org.junit.Assert.fail; import org.junit.Test;
assertEquals(EXPECTED_MAP, replaceMapExpected, replaceMap.m); } @Test public void testRemove() { // Remove individual entries at index assertEquals(EXPECTED_MAP, m("d", 3).i("e", 4).i("a", 0).i("b", 1).i("c", 2).DeleteKey("d", "e").m); assertEquals(EXPECTED_MAP, m("d", 3).i("e", 4).i("a", 0).i("b", 1).i("c", 2).d("d", "e").m); assertEquals(EXPECTED_MAP, m("d", 3).i("e", 4).i("a", 0).i("b", 1).i("c", 2).deleteKey("d", "e")); assertEquals(EXPECTED_MAP, m("d", 3).i("e", 4).i("a", 0).i("b", 1).i("c", 2).DeleteValue(3, 4).m); assertEquals(EXPECTED_MAP, m("d", 3).i("e", 4).i("a", 0).i("b", 1).i("c", 2).deleteValue(3, 4)); assertEquals(EXPECTED_MAP, m("d", 3).i("e", 3).i("a", 0).i("b", 1).i("c", 2).deleteValue(3, 3)); assertEquals(EXPECTED_MAP, m("d", 3).i("e", 4).i("a", 0).i("b", 1).i("c", 2).deleteValue(3, 4, -1)); // Conditional remove M<String, Number> removeMap = m(String.class, Number.class).i("d", 3).i("a", 0).i("b", 1).i("c", 2); Map<String, Number> removeMapExpected = m(String.class, Number.class).i("d", 3).i("a", 0).i("b", 1).i("c", 2).m; assertEquals(true, removeMap.deleteIfMatches("d", 3)); assertEquals(true, removeMapExpected.remove("d", 3)); assertEquals(EXPECTED_MAP, removeMap.m); assertEquals(false, removeMap.deleteIfMatches("a", 4)); assertEquals(false, removeMapExpected.remove("a", 4)); assertEquals(EXPECTED_MAP, removeMapExpected); // Remove all entries assertEquals(EXPECTED_MAP, m("d", 3).i("e", 4).i("f", 5).i("a", 0).i("b", 1).i("c", 2).DeleteAllKeys(list("d"), list("e", "f")).m); assertEquals(EXPECTED_MAP, m("d", 3).i("e", 4).i("f", 5).i("a", 0).i("b", 1).i("c", 2).D(list("d"), list("e", "f")).m); assertEquals(EXPECTED_MAP, m("d", 3).i("e", 4).i("f", 5).i("a", 0).i("b", 1).i("c", 2).deleteAllKeys(list("d"), list("e", "f")));
// Path: src/main/java/ch/codebulb/lambdaomega/L.java // public static <T> L<T> l() { // return new L<>(new ArrayList<>()); // } // // Path: src/main/java/ch/codebulb/lambdaomega/L.java // public static <T> List<T> list(T... ts) { // return l(ts).l; // } // // Path: src/main/java/ch/codebulb/lambdaomega/M.java // public static <K, V> E<K, V> e(K k, V v) { // return new E(k, v); // } // // Path: src/main/java/ch/codebulb/lambdaomega/M.java // public static M m() { // return m(new LinkedHashMap<>()); // } // // Path: src/main/java/ch/codebulb/lambdaomega/S.java // public static <T> Set<T> set(T... ts) { // return C.toSet(ts); // } // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static final List<Integer> EXPECTED_LIST = new ArrayList<>(); // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static final Map<String, Integer> EXPECTED_MAP = new LinkedHashMap<>(); // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static final Map<String, Integer> EXPECTED_MAP_2_ELEMENTS = new LinkedHashMap<>(); // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static <T> void assertEquals(T expected, T... actual) { // Arrays.stream(actual).forEach(it -> Assert.assertEquals(expected, it)); // } // // Path: src/main/java/ch/codebulb/lambdaomega/abstractions/IndexedListI.java // public static class IndexAlreadyPresentException extends RuntimeException { // // cannot use generics in Throwable // public final Object key; // public final Object previousValue; // // public IndexAlreadyPresentException(Object key, Object previousValue) { // super("Duplicate key found in map. Use #set(...) to override a value. Key: " + key + ", previous value: " + previousValue); // this.key = key; // this.previousValue = previousValue; // } // } // Path: src/test/java/ch/codebulb/lambdaomega/MBaseIndexedTest.java import static ch.codebulb.lambdaomega.L.l; import static ch.codebulb.lambdaomega.L.list; import static ch.codebulb.lambdaomega.M.e; import static ch.codebulb.lambdaomega.M.m; import static ch.codebulb.lambdaomega.S.set; import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_LIST; import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_MAP; import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_MAP_2_ELEMENTS; import static ch.codebulb.lambdaomega.TestUtil.assertEquals; import ch.codebulb.lambdaomega.abstractions.IndexedListI.IndexAlreadyPresentException; import java.util.Map; import static org.junit.Assert.fail; import org.junit.Test; assertEquals(EXPECTED_MAP, replaceMapExpected, replaceMap.m); } @Test public void testRemove() { // Remove individual entries at index assertEquals(EXPECTED_MAP, m("d", 3).i("e", 4).i("a", 0).i("b", 1).i("c", 2).DeleteKey("d", "e").m); assertEquals(EXPECTED_MAP, m("d", 3).i("e", 4).i("a", 0).i("b", 1).i("c", 2).d("d", "e").m); assertEquals(EXPECTED_MAP, m("d", 3).i("e", 4).i("a", 0).i("b", 1).i("c", 2).deleteKey("d", "e")); assertEquals(EXPECTED_MAP, m("d", 3).i("e", 4).i("a", 0).i("b", 1).i("c", 2).DeleteValue(3, 4).m); assertEquals(EXPECTED_MAP, m("d", 3).i("e", 4).i("a", 0).i("b", 1).i("c", 2).deleteValue(3, 4)); assertEquals(EXPECTED_MAP, m("d", 3).i("e", 3).i("a", 0).i("b", 1).i("c", 2).deleteValue(3, 3)); assertEquals(EXPECTED_MAP, m("d", 3).i("e", 4).i("a", 0).i("b", 1).i("c", 2).deleteValue(3, 4, -1)); // Conditional remove M<String, Number> removeMap = m(String.class, Number.class).i("d", 3).i("a", 0).i("b", 1).i("c", 2); Map<String, Number> removeMapExpected = m(String.class, Number.class).i("d", 3).i("a", 0).i("b", 1).i("c", 2).m; assertEquals(true, removeMap.deleteIfMatches("d", 3)); assertEquals(true, removeMapExpected.remove("d", 3)); assertEquals(EXPECTED_MAP, removeMap.m); assertEquals(false, removeMap.deleteIfMatches("a", 4)); assertEquals(false, removeMapExpected.remove("a", 4)); assertEquals(EXPECTED_MAP, removeMapExpected); // Remove all entries assertEquals(EXPECTED_MAP, m("d", 3).i("e", 4).i("f", 5).i("a", 0).i("b", 1).i("c", 2).DeleteAllKeys(list("d"), list("e", "f")).m); assertEquals(EXPECTED_MAP, m("d", 3).i("e", 4).i("f", 5).i("a", 0).i("b", 1).i("c", 2).D(list("d"), list("e", "f")).m); assertEquals(EXPECTED_MAP, m("d", 3).i("e", 4).i("f", 5).i("a", 0).i("b", 1).i("c", 2).deleteAllKeys(list("d"), list("e", "f")));
assertEquals(EXPECTED_MAP, m("d", 3).i("e", 4).i("f", 5).i("a", 0).i("b", 1).i("c", 2).DeleteAllKeys(l("d"), l("e", "f")).m);
codebulb/LambdaOmega
src/main/java/ch/codebulb/lambdaomega/C.java
// Path: src/main/java/ch/codebulb/lambdaomega/M.java // public static class E<K, V> implements Comparable<E<K, V>> { // public final K k; // public final V v; // // public E(K k, V v) { // this.k = k; // this.v = v; // } // // public Map.Entry<K, V> toEntry() { // return new AbstractMap.SimpleEntry<>(k, v); // } // // public K getK() { // return k; // } // // public V getV() { // return v; // } // // @Override // public int hashCode() { // int hash = 7; // hash = 59 * hash + Objects.hashCode(this.k); // hash = 59 * hash + Objects.hashCode(this.v); // return hash; // } // // @Override // public boolean equals(Object obj) { // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // final E<?, ?> other = (E<?, ?>) obj; // if (!Objects.equals(this.k, other.k)) { // return false; // } // if (!Objects.equals(this.v, other.v)) { // return false; // } // return true; // } // // @Override // public String toString() { // return "e(" + k + ", " + v + ')'; // } // // @Override // public int compareTo(E<K, V> obj) { // if (obj == null) { // return 1; // } // // if (!(k instanceof Comparable)) { // throw new ClassCastException(k.getClass().getName() + " cannot be cast to java.lang.Comparable"); // } // int ret = ((Comparable<K>)k).compareTo(obj.k); // if (ret != 0) { // return ret; // } // // if (!(v instanceof Comparable)) { // throw new ClassCastException(v.getClass().getName() + " cannot be cast to java.lang.Comparable"); // } // ret = ((Comparable<V>)v).compareTo(obj.v); // // return ret; // } // } // // Path: src/main/java/ch/codebulb/lambdaomega/U.java // public static <T> boolean any(Predicate<T> predicate, T... candidates) { // return C.toStream(candidates).anyMatch(predicate); // } // // Path: src/main/java/ch/codebulb/lambdaomega/abstractions/OmegaObject.java // public abstract class OmegaObject { // /** // * Prints itself to the standard output. // */ // public void println() { // U.println(this); // } // } // // Path: src/main/java/ch/codebulb/lambdaomega/abstractions/ReadonlyIndexedI.java // public interface ReadonlyIndexedI<K, V> extends I<K, V> { // // } // // Path: src/main/java/ch/codebulb/lambdaomega/abstractions/StreamableI.java // public interface StreamableI { // /** // * Returns <code>true</code>, if the data structure is parallel streamed. // */ // public boolean isParallel(); // }
import ch.codebulb.lambdaomega.M.E; import static ch.codebulb.lambdaomega.U.any; import ch.codebulb.lambdaomega.abstractions.OmegaObject; import ch.codebulb.lambdaomega.abstractions.ReadonlyIndexedI; import ch.codebulb.lambdaomega.abstractions.StreamableI; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; import java.util.IdentityHashMap; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.PriorityQueue; import java.util.Properties; import java.util.Set; import java.util.Stack; import java.util.TreeMap; import java.util.TreeSet; import java.util.WeakHashMap; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedDeque; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ConcurrentSkipListMap; import java.util.concurrent.ConcurrentSkipListSet; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CopyOnWriteArraySet; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.LinkedTransferQueue; import java.util.concurrent.PriorityBlockingQueue; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; import java.util.stream.StreamSupport;
/** * @see #Parallel() */ public C<T, K, V> Par() { return Parallel(); } /** * Turns the wrapped data structure sequentially streamed. */ public C<T, K, V> Sequential() { parallel = false; return this; } /** * @see #Sequential() */ public C<T, K, V> Seq() { return Sequential(); } public <C> C to(Class<C> format) { return to(stream(), format); } public static <T, C> C to(Stream<T> stream, Class<C> format) { // We have to copy the stream just in case we want to use its size (cannot open a stream twice) List<T> collectedStream = stream.collect(Collectors.toList());
// Path: src/main/java/ch/codebulb/lambdaomega/M.java // public static class E<K, V> implements Comparable<E<K, V>> { // public final K k; // public final V v; // // public E(K k, V v) { // this.k = k; // this.v = v; // } // // public Map.Entry<K, V> toEntry() { // return new AbstractMap.SimpleEntry<>(k, v); // } // // public K getK() { // return k; // } // // public V getV() { // return v; // } // // @Override // public int hashCode() { // int hash = 7; // hash = 59 * hash + Objects.hashCode(this.k); // hash = 59 * hash + Objects.hashCode(this.v); // return hash; // } // // @Override // public boolean equals(Object obj) { // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // final E<?, ?> other = (E<?, ?>) obj; // if (!Objects.equals(this.k, other.k)) { // return false; // } // if (!Objects.equals(this.v, other.v)) { // return false; // } // return true; // } // // @Override // public String toString() { // return "e(" + k + ", " + v + ')'; // } // // @Override // public int compareTo(E<K, V> obj) { // if (obj == null) { // return 1; // } // // if (!(k instanceof Comparable)) { // throw new ClassCastException(k.getClass().getName() + " cannot be cast to java.lang.Comparable"); // } // int ret = ((Comparable<K>)k).compareTo(obj.k); // if (ret != 0) { // return ret; // } // // if (!(v instanceof Comparable)) { // throw new ClassCastException(v.getClass().getName() + " cannot be cast to java.lang.Comparable"); // } // ret = ((Comparable<V>)v).compareTo(obj.v); // // return ret; // } // } // // Path: src/main/java/ch/codebulb/lambdaomega/U.java // public static <T> boolean any(Predicate<T> predicate, T... candidates) { // return C.toStream(candidates).anyMatch(predicate); // } // // Path: src/main/java/ch/codebulb/lambdaomega/abstractions/OmegaObject.java // public abstract class OmegaObject { // /** // * Prints itself to the standard output. // */ // public void println() { // U.println(this); // } // } // // Path: src/main/java/ch/codebulb/lambdaomega/abstractions/ReadonlyIndexedI.java // public interface ReadonlyIndexedI<K, V> extends I<K, V> { // // } // // Path: src/main/java/ch/codebulb/lambdaomega/abstractions/StreamableI.java // public interface StreamableI { // /** // * Returns <code>true</code>, if the data structure is parallel streamed. // */ // public boolean isParallel(); // } // Path: src/main/java/ch/codebulb/lambdaomega/C.java import ch.codebulb.lambdaomega.M.E; import static ch.codebulb.lambdaomega.U.any; import ch.codebulb.lambdaomega.abstractions.OmegaObject; import ch.codebulb.lambdaomega.abstractions.ReadonlyIndexedI; import ch.codebulb.lambdaomega.abstractions.StreamableI; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; import java.util.IdentityHashMap; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.PriorityQueue; import java.util.Properties; import java.util.Set; import java.util.Stack; import java.util.TreeMap; import java.util.TreeSet; import java.util.WeakHashMap; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedDeque; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ConcurrentSkipListMap; import java.util.concurrent.ConcurrentSkipListSet; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CopyOnWriteArraySet; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.LinkedTransferQueue; import java.util.concurrent.PriorityBlockingQueue; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; import java.util.stream.StreamSupport; /** * @see #Parallel() */ public C<T, K, V> Par() { return Parallel(); } /** * Turns the wrapped data structure sequentially streamed. */ public C<T, K, V> Sequential() { parallel = false; return this; } /** * @see #Sequential() */ public C<T, K, V> Seq() { return Sequential(); } public <C> C to(Class<C> format) { return to(stream(), format); } public static <T, C> C to(Stream<T> stream, Class<C> format) { // We have to copy the stream just in case we want to use its size (cannot open a stream twice) List<T> collectedStream = stream.collect(Collectors.toList());
if (any(it -> format.isAssignableFrom(it),
codebulb/LambdaOmega
src/main/java/ch/codebulb/lambdaomega/C.java
// Path: src/main/java/ch/codebulb/lambdaomega/M.java // public static class E<K, V> implements Comparable<E<K, V>> { // public final K k; // public final V v; // // public E(K k, V v) { // this.k = k; // this.v = v; // } // // public Map.Entry<K, V> toEntry() { // return new AbstractMap.SimpleEntry<>(k, v); // } // // public K getK() { // return k; // } // // public V getV() { // return v; // } // // @Override // public int hashCode() { // int hash = 7; // hash = 59 * hash + Objects.hashCode(this.k); // hash = 59 * hash + Objects.hashCode(this.v); // return hash; // } // // @Override // public boolean equals(Object obj) { // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // final E<?, ?> other = (E<?, ?>) obj; // if (!Objects.equals(this.k, other.k)) { // return false; // } // if (!Objects.equals(this.v, other.v)) { // return false; // } // return true; // } // // @Override // public String toString() { // return "e(" + k + ", " + v + ')'; // } // // @Override // public int compareTo(E<K, V> obj) { // if (obj == null) { // return 1; // } // // if (!(k instanceof Comparable)) { // throw new ClassCastException(k.getClass().getName() + " cannot be cast to java.lang.Comparable"); // } // int ret = ((Comparable<K>)k).compareTo(obj.k); // if (ret != 0) { // return ret; // } // // if (!(v instanceof Comparable)) { // throw new ClassCastException(v.getClass().getName() + " cannot be cast to java.lang.Comparable"); // } // ret = ((Comparable<V>)v).compareTo(obj.v); // // return ret; // } // } // // Path: src/main/java/ch/codebulb/lambdaomega/U.java // public static <T> boolean any(Predicate<T> predicate, T... candidates) { // return C.toStream(candidates).anyMatch(predicate); // } // // Path: src/main/java/ch/codebulb/lambdaomega/abstractions/OmegaObject.java // public abstract class OmegaObject { // /** // * Prints itself to the standard output. // */ // public void println() { // U.println(this); // } // } // // Path: src/main/java/ch/codebulb/lambdaomega/abstractions/ReadonlyIndexedI.java // public interface ReadonlyIndexedI<K, V> extends I<K, V> { // // } // // Path: src/main/java/ch/codebulb/lambdaomega/abstractions/StreamableI.java // public interface StreamableI { // /** // * Returns <code>true</code>, if the data structure is parallel streamed. // */ // public boolean isParallel(); // }
import ch.codebulb.lambdaomega.M.E; import static ch.codebulb.lambdaomega.U.any; import ch.codebulb.lambdaomega.abstractions.OmegaObject; import ch.codebulb.lambdaomega.abstractions.ReadonlyIndexedI; import ch.codebulb.lambdaomega.abstractions.StreamableI; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; import java.util.IdentityHashMap; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.PriorityQueue; import java.util.Properties; import java.util.Set; import java.util.Stack; import java.util.TreeMap; import java.util.TreeSet; import java.util.WeakHashMap; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedDeque; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ConcurrentSkipListMap; import java.util.concurrent.ConcurrentSkipListSet; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CopyOnWriteArraySet; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.LinkedTransferQueue; import java.util.concurrent.PriorityBlockingQueue; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; import java.util.stream.StreamSupport;
return new LinkedHashSet<T>(); } if (format.isAssignableFrom(LinkedList.class)) { return new LinkedList<T>(); } if (format.isAssignableFrom(LinkedTransferQueue.class)) { return new LinkedTransferQueue<T>(); } if (format.isAssignableFrom(PriorityBlockingQueue.class)) { return new PriorityBlockingQueue<T>(); } if (format.isAssignableFrom(PriorityQueue.class)) { return new PriorityQueue<T>(); } if (format.isAssignableFrom(Stack.class)) { return new Stack<T>(); } // TODO What about SynchronousQueue? if (format.isAssignableFrom(TreeSet.class)) { return new TreeSet<T>(); } // Vector is considered "obsolete" throw new IllegalArgumentException("Return type not supported: " + format); })); } if (any(it -> format.isAssignableFrom(it), ConcurrentHashMap.class, ConcurrentSkipListMap.class)) {
// Path: src/main/java/ch/codebulb/lambdaomega/M.java // public static class E<K, V> implements Comparable<E<K, V>> { // public final K k; // public final V v; // // public E(K k, V v) { // this.k = k; // this.v = v; // } // // public Map.Entry<K, V> toEntry() { // return new AbstractMap.SimpleEntry<>(k, v); // } // // public K getK() { // return k; // } // // public V getV() { // return v; // } // // @Override // public int hashCode() { // int hash = 7; // hash = 59 * hash + Objects.hashCode(this.k); // hash = 59 * hash + Objects.hashCode(this.v); // return hash; // } // // @Override // public boolean equals(Object obj) { // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // final E<?, ?> other = (E<?, ?>) obj; // if (!Objects.equals(this.k, other.k)) { // return false; // } // if (!Objects.equals(this.v, other.v)) { // return false; // } // return true; // } // // @Override // public String toString() { // return "e(" + k + ", " + v + ')'; // } // // @Override // public int compareTo(E<K, V> obj) { // if (obj == null) { // return 1; // } // // if (!(k instanceof Comparable)) { // throw new ClassCastException(k.getClass().getName() + " cannot be cast to java.lang.Comparable"); // } // int ret = ((Comparable<K>)k).compareTo(obj.k); // if (ret != 0) { // return ret; // } // // if (!(v instanceof Comparable)) { // throw new ClassCastException(v.getClass().getName() + " cannot be cast to java.lang.Comparable"); // } // ret = ((Comparable<V>)v).compareTo(obj.v); // // return ret; // } // } // // Path: src/main/java/ch/codebulb/lambdaomega/U.java // public static <T> boolean any(Predicate<T> predicate, T... candidates) { // return C.toStream(candidates).anyMatch(predicate); // } // // Path: src/main/java/ch/codebulb/lambdaomega/abstractions/OmegaObject.java // public abstract class OmegaObject { // /** // * Prints itself to the standard output. // */ // public void println() { // U.println(this); // } // } // // Path: src/main/java/ch/codebulb/lambdaomega/abstractions/ReadonlyIndexedI.java // public interface ReadonlyIndexedI<K, V> extends I<K, V> { // // } // // Path: src/main/java/ch/codebulb/lambdaomega/abstractions/StreamableI.java // public interface StreamableI { // /** // * Returns <code>true</code>, if the data structure is parallel streamed. // */ // public boolean isParallel(); // } // Path: src/main/java/ch/codebulb/lambdaomega/C.java import ch.codebulb.lambdaomega.M.E; import static ch.codebulb.lambdaomega.U.any; import ch.codebulb.lambdaomega.abstractions.OmegaObject; import ch.codebulb.lambdaomega.abstractions.ReadonlyIndexedI; import ch.codebulb.lambdaomega.abstractions.StreamableI; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; import java.util.IdentityHashMap; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.PriorityQueue; import java.util.Properties; import java.util.Set; import java.util.Stack; import java.util.TreeMap; import java.util.TreeSet; import java.util.WeakHashMap; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedDeque; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ConcurrentSkipListMap; import java.util.concurrent.ConcurrentSkipListSet; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CopyOnWriteArraySet; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.LinkedTransferQueue; import java.util.concurrent.PriorityBlockingQueue; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; import java.util.stream.StreamSupport; return new LinkedHashSet<T>(); } if (format.isAssignableFrom(LinkedList.class)) { return new LinkedList<T>(); } if (format.isAssignableFrom(LinkedTransferQueue.class)) { return new LinkedTransferQueue<T>(); } if (format.isAssignableFrom(PriorityBlockingQueue.class)) { return new PriorityBlockingQueue<T>(); } if (format.isAssignableFrom(PriorityQueue.class)) { return new PriorityQueue<T>(); } if (format.isAssignableFrom(Stack.class)) { return new Stack<T>(); } // TODO What about SynchronousQueue? if (format.isAssignableFrom(TreeSet.class)) { return new TreeSet<T>(); } // Vector is considered "obsolete" throw new IllegalArgumentException("Return type not supported: " + format); })); } if (any(it -> format.isAssignableFrom(it), ConcurrentHashMap.class, ConcurrentSkipListMap.class)) {
return (C)collectedStream.stream().collect(Collectors.toConcurrentMap(it -> ((E)it).k, it -> ((E)it).v, (x, y) -> x, () -> {
codebulb/LambdaOmega
src/main/java/ch/codebulb/lambdaomega/V2.java
// Path: src/main/java/ch/codebulb/lambdaomega/L.java // public static <T> List<T> list(T... ts) { // return l(ts).l; // } // // Path: src/main/java/ch/codebulb/lambdaomega/abstractions/OmegaObject.java // public abstract class OmegaObject { // /** // * Prints itself to the standard output. // */ // public void println() { // U.println(this); // } // } // // Path: src/main/java/ch/codebulb/lambdaomega/abstractions/ReadonlyIndexedI.java // public interface ReadonlyIndexedI<K, V> extends I<K, V> { // // }
import static ch.codebulb.lambdaomega.L.list; import ch.codebulb.lambdaomega.abstractions.OmegaObject; import ch.codebulb.lambdaomega.abstractions.ReadonlyIndexedI; import java.util.List; import java.util.Objects; import java.util.function.Function;
package ch.codebulb.lambdaomega; /** * The "V2" stands for "2d vector". This is an implementation of a 2-dimensional vector = a 2-ary tuple.<p/> * * The constructor of this class is not visible; use the convenience {@link #v(Object, Object)} method to create a new instance of this class. * It's best practice to statically import this function in client code. * * @param <X> the type of the 1st element * @param <Y> the type of the 2nd element */ public class V2<X, Y> extends OmegaObject implements ReadonlyIndexedI<Integer, Object> { private X x; private Y y; private Function<Integer, Object> defaultFunction; V2(X x, Y y) { this.x = x; this.y = y; } /** * Creates a {@link V2} consisting of the value pair <code>x</code>, <code>y</code>. */ public static <X, Y> V2<X, Y> v(X x, Y y) { return new V2(x, y); } /** * Turns this vector into a {@link LV2} with subsequent {@link LV2#a(Object, Object)} call. */ public LV2<X, Y> a(X x, Y y) {
// Path: src/main/java/ch/codebulb/lambdaomega/L.java // public static <T> List<T> list(T... ts) { // return l(ts).l; // } // // Path: src/main/java/ch/codebulb/lambdaomega/abstractions/OmegaObject.java // public abstract class OmegaObject { // /** // * Prints itself to the standard output. // */ // public void println() { // U.println(this); // } // } // // Path: src/main/java/ch/codebulb/lambdaomega/abstractions/ReadonlyIndexedI.java // public interface ReadonlyIndexedI<K, V> extends I<K, V> { // // } // Path: src/main/java/ch/codebulb/lambdaomega/V2.java import static ch.codebulb.lambdaomega.L.list; import ch.codebulb.lambdaomega.abstractions.OmegaObject; import ch.codebulb.lambdaomega.abstractions.ReadonlyIndexedI; import java.util.List; import java.util.Objects; import java.util.function.Function; package ch.codebulb.lambdaomega; /** * The "V2" stands for "2d vector". This is an implementation of a 2-dimensional vector = a 2-ary tuple.<p/> * * The constructor of this class is not visible; use the convenience {@link #v(Object, Object)} method to create a new instance of this class. * It's best practice to statically import this function in client code. * * @param <X> the type of the 1st element * @param <Y> the type of the 2nd element */ public class V2<X, Y> extends OmegaObject implements ReadonlyIndexedI<Integer, Object> { private X x; private Y y; private Function<Integer, Object> defaultFunction; V2(X x, Y y) { this.x = x; this.y = y; } /** * Creates a {@link V2} consisting of the value pair <code>x</code>, <code>y</code>. */ public static <X, Y> V2<X, Y> v(X x, Y y) { return new V2(x, y); } /** * Turns this vector into a {@link LV2} with subsequent {@link LV2#a(Object, Object)} call. */ public LV2<X, Y> a(X x, Y y) {
return new LV2(list(this)).a(x, y);
codebulb/LambdaOmega
src/main/java/ch/codebulb/lambdaomega/U.java
// Path: src/main/java/ch/codebulb/lambdaomega/L.java // public static <T> L<T> l() { // return new L<>(new ArrayList<>()); // } // // Path: src/main/java/ch/codebulb/lambdaomega/V2.java // public static <X, Y> V2<X, Y> v(X x, Y y) { // return new V2(x, y); // }
import static ch.codebulb.lambdaomega.L.l; import static ch.codebulb.lambdaomega.V2.v; import java.util.function.Predicate; import java.util.function.Supplier;
package ch.codebulb.lambdaomega; /** * The "U" stands for "utils". Provides common static helper methods. */ public class U { private U() {} /** * Prints the object provided to the standard output. */ public static void println(Object out) { System.out.println(out); } /** * Creates a {@link Choice}. */ public static <T> Choice<T> Choose(boolean predicate, Supplier<T> function) { return new Choice<>(predicate, function); } /** * Returns <code>true</code> if the <code>predicate</code> provided is <code>true</code> for at least one of the <code>candidates</code>. */ public static <T> boolean any(Predicate<T> predicate, T... candidates) { return C.toStream(candidates).anyMatch(predicate); } /** * Represents a simple choice tree. This structure can be used as an alternative to * an <code>if</code> / <code>else if</code> / <code>else</code> structure with optionally enforced choice.<p/> * * The constructor of this class is not visible; use the convenience {@link U#Choose(boolean, Supplier)} method to create a new instance of this class. * It's best practice to statically import this function in client code. * * @param <T> the return type */ public static class Choice<T> { private final L<V2<Boolean, Supplier<T>>> choices; Choice(boolean predicate, Supplier<T> function) {
// Path: src/main/java/ch/codebulb/lambdaomega/L.java // public static <T> L<T> l() { // return new L<>(new ArrayList<>()); // } // // Path: src/main/java/ch/codebulb/lambdaomega/V2.java // public static <X, Y> V2<X, Y> v(X x, Y y) { // return new V2(x, y); // } // Path: src/main/java/ch/codebulb/lambdaomega/U.java import static ch.codebulb.lambdaomega.L.l; import static ch.codebulb.lambdaomega.V2.v; import java.util.function.Predicate; import java.util.function.Supplier; package ch.codebulb.lambdaomega; /** * The "U" stands for "utils". Provides common static helper methods. */ public class U { private U() {} /** * Prints the object provided to the standard output. */ public static void println(Object out) { System.out.println(out); } /** * Creates a {@link Choice}. */ public static <T> Choice<T> Choose(boolean predicate, Supplier<T> function) { return new Choice<>(predicate, function); } /** * Returns <code>true</code> if the <code>predicate</code> provided is <code>true</code> for at least one of the <code>candidates</code>. */ public static <T> boolean any(Predicate<T> predicate, T... candidates) { return C.toStream(candidates).anyMatch(predicate); } /** * Represents a simple choice tree. This structure can be used as an alternative to * an <code>if</code> / <code>else if</code> / <code>else</code> structure with optionally enforced choice.<p/> * * The constructor of this class is not visible; use the convenience {@link U#Choose(boolean, Supplier)} method to create a new instance of this class. * It's best practice to statically import this function in client code. * * @param <T> the return type */ public static class Choice<T> { private final L<V2<Boolean, Supplier<T>>> choices; Choice(boolean predicate, Supplier<T> function) {
choices = l(v(predicate, function));
codebulb/LambdaOmega
src/main/java/ch/codebulb/lambdaomega/U.java
// Path: src/main/java/ch/codebulb/lambdaomega/L.java // public static <T> L<T> l() { // return new L<>(new ArrayList<>()); // } // // Path: src/main/java/ch/codebulb/lambdaomega/V2.java // public static <X, Y> V2<X, Y> v(X x, Y y) { // return new V2(x, y); // }
import static ch.codebulb.lambdaomega.L.l; import static ch.codebulb.lambdaomega.V2.v; import java.util.function.Predicate; import java.util.function.Supplier;
package ch.codebulb.lambdaomega; /** * The "U" stands for "utils". Provides common static helper methods. */ public class U { private U() {} /** * Prints the object provided to the standard output. */ public static void println(Object out) { System.out.println(out); } /** * Creates a {@link Choice}. */ public static <T> Choice<T> Choose(boolean predicate, Supplier<T> function) { return new Choice<>(predicate, function); } /** * Returns <code>true</code> if the <code>predicate</code> provided is <code>true</code> for at least one of the <code>candidates</code>. */ public static <T> boolean any(Predicate<T> predicate, T... candidates) { return C.toStream(candidates).anyMatch(predicate); } /** * Represents a simple choice tree. This structure can be used as an alternative to * an <code>if</code> / <code>else if</code> / <code>else</code> structure with optionally enforced choice.<p/> * * The constructor of this class is not visible; use the convenience {@link U#Choose(boolean, Supplier)} method to create a new instance of this class. * It's best practice to statically import this function in client code. * * @param <T> the return type */ public static class Choice<T> { private final L<V2<Boolean, Supplier<T>>> choices; Choice(boolean predicate, Supplier<T> function) {
// Path: src/main/java/ch/codebulb/lambdaomega/L.java // public static <T> L<T> l() { // return new L<>(new ArrayList<>()); // } // // Path: src/main/java/ch/codebulb/lambdaomega/V2.java // public static <X, Y> V2<X, Y> v(X x, Y y) { // return new V2(x, y); // } // Path: src/main/java/ch/codebulb/lambdaomega/U.java import static ch.codebulb.lambdaomega.L.l; import static ch.codebulb.lambdaomega.V2.v; import java.util.function.Predicate; import java.util.function.Supplier; package ch.codebulb.lambdaomega; /** * The "U" stands for "utils". Provides common static helper methods. */ public class U { private U() {} /** * Prints the object provided to the standard output. */ public static void println(Object out) { System.out.println(out); } /** * Creates a {@link Choice}. */ public static <T> Choice<T> Choose(boolean predicate, Supplier<T> function) { return new Choice<>(predicate, function); } /** * Returns <code>true</code> if the <code>predicate</code> provided is <code>true</code> for at least one of the <code>candidates</code>. */ public static <T> boolean any(Predicate<T> predicate, T... candidates) { return C.toStream(candidates).anyMatch(predicate); } /** * Represents a simple choice tree. This structure can be used as an alternative to * an <code>if</code> / <code>else if</code> / <code>else</code> structure with optionally enforced choice.<p/> * * The constructor of this class is not visible; use the convenience {@link U#Choose(boolean, Supplier)} method to create a new instance of this class. * It's best practice to statically import this function in client code. * * @param <T> the return type */ public static class Choice<T> { private final L<V2<Boolean, Supplier<T>>> choices; Choice(boolean predicate, Supplier<T> function) {
choices = l(v(predicate, function));
codebulb/LambdaOmega
src/test/java/ch/codebulb/lambdaomega/LToMapTest.java
// Path: src/main/java/ch/codebulb/lambdaomega/L.java // public static <T> L<T> l() { // return new L<>(new ArrayList<>()); // } // // Path: src/main/java/ch/codebulb/lambdaomega/M.java // public static M m() { // return m(new LinkedHashMap<>()); // } // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static <T> void assertEquals(T expected, T... actual) { // Arrays.stream(actual).forEach(it -> Assert.assertEquals(expected, it)); // }
import static ch.codebulb.lambdaomega.L.l; import static ch.codebulb.lambdaomega.M.m; import static ch.codebulb.lambdaomega.TestUtil.assertEquals; import org.junit.Test;
package ch.codebulb.lambdaomega; // Separated from other tests, because here, we want to explicitly call #toMap() public class LToMapTest { @Test public void testToMap() {
// Path: src/main/java/ch/codebulb/lambdaomega/L.java // public static <T> L<T> l() { // return new L<>(new ArrayList<>()); // } // // Path: src/main/java/ch/codebulb/lambdaomega/M.java // public static M m() { // return m(new LinkedHashMap<>()); // } // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static <T> void assertEquals(T expected, T... actual) { // Arrays.stream(actual).forEach(it -> Assert.assertEquals(expected, it)); // } // Path: src/test/java/ch/codebulb/lambdaomega/LToMapTest.java import static ch.codebulb.lambdaomega.L.l; import static ch.codebulb.lambdaomega.M.m; import static ch.codebulb.lambdaomega.TestUtil.assertEquals; import org.junit.Test; package ch.codebulb.lambdaomega; // Separated from other tests, because here, we want to explicitly call #toMap() public class LToMapTest { @Test public void testToMap() {
assertEquals(m(0, "a").i(1, "b").i(2, "c").m, l("a", "b", "c").toMap());
codebulb/LambdaOmega
src/test/java/ch/codebulb/lambdaomega/LToMapTest.java
// Path: src/main/java/ch/codebulb/lambdaomega/L.java // public static <T> L<T> l() { // return new L<>(new ArrayList<>()); // } // // Path: src/main/java/ch/codebulb/lambdaomega/M.java // public static M m() { // return m(new LinkedHashMap<>()); // } // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static <T> void assertEquals(T expected, T... actual) { // Arrays.stream(actual).forEach(it -> Assert.assertEquals(expected, it)); // }
import static ch.codebulb.lambdaomega.L.l; import static ch.codebulb.lambdaomega.M.m; import static ch.codebulb.lambdaomega.TestUtil.assertEquals; import org.junit.Test;
package ch.codebulb.lambdaomega; // Separated from other tests, because here, we want to explicitly call #toMap() public class LToMapTest { @Test public void testToMap() {
// Path: src/main/java/ch/codebulb/lambdaomega/L.java // public static <T> L<T> l() { // return new L<>(new ArrayList<>()); // } // // Path: src/main/java/ch/codebulb/lambdaomega/M.java // public static M m() { // return m(new LinkedHashMap<>()); // } // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static <T> void assertEquals(T expected, T... actual) { // Arrays.stream(actual).forEach(it -> Assert.assertEquals(expected, it)); // } // Path: src/test/java/ch/codebulb/lambdaomega/LToMapTest.java import static ch.codebulb.lambdaomega.L.l; import static ch.codebulb.lambdaomega.M.m; import static ch.codebulb.lambdaomega.TestUtil.assertEquals; import org.junit.Test; package ch.codebulb.lambdaomega; // Separated from other tests, because here, we want to explicitly call #toMap() public class LToMapTest { @Test public void testToMap() {
assertEquals(m(0, "a").i(1, "b").i(2, "c").m, l("a", "b", "c").toMap());
codebulb/LambdaOmega
src/test/java/ch/codebulb/lambdaomega/LToMapTest.java
// Path: src/main/java/ch/codebulb/lambdaomega/L.java // public static <T> L<T> l() { // return new L<>(new ArrayList<>()); // } // // Path: src/main/java/ch/codebulb/lambdaomega/M.java // public static M m() { // return m(new LinkedHashMap<>()); // } // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static <T> void assertEquals(T expected, T... actual) { // Arrays.stream(actual).forEach(it -> Assert.assertEquals(expected, it)); // }
import static ch.codebulb.lambdaomega.L.l; import static ch.codebulb.lambdaomega.M.m; import static ch.codebulb.lambdaomega.TestUtil.assertEquals; import org.junit.Test;
package ch.codebulb.lambdaomega; // Separated from other tests, because here, we want to explicitly call #toMap() public class LToMapTest { @Test public void testToMap() {
// Path: src/main/java/ch/codebulb/lambdaomega/L.java // public static <T> L<T> l() { // return new L<>(new ArrayList<>()); // } // // Path: src/main/java/ch/codebulb/lambdaomega/M.java // public static M m() { // return m(new LinkedHashMap<>()); // } // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static <T> void assertEquals(T expected, T... actual) { // Arrays.stream(actual).forEach(it -> Assert.assertEquals(expected, it)); // } // Path: src/test/java/ch/codebulb/lambdaomega/LToMapTest.java import static ch.codebulb.lambdaomega.L.l; import static ch.codebulb.lambdaomega.M.m; import static ch.codebulb.lambdaomega.TestUtil.assertEquals; import org.junit.Test; package ch.codebulb.lambdaomega; // Separated from other tests, because here, we want to explicitly call #toMap() public class LToMapTest { @Test public void testToMap() {
assertEquals(m(0, "a").i(1, "b").i(2, "c").m, l("a", "b", "c").toMap());
codebulb/LambdaOmega
src/main/java/ch/codebulb/lambdaomega/Promise.java
// Path: src/main/java/ch/codebulb/lambdaomega/L.java // public static <T> L<T> l() { // return new L<>(new ArrayList<>()); // } // // Path: src/main/java/ch/codebulb/lambdaomega/U.java // public class U { // private U() {} // // /** // * Prints the object provided to the standard output. // */ // public static void println(Object out) { // System.out.println(out); // } // // /** // * Creates a {@link Choice}. // */ // public static <T> Choice<T> Choose(boolean predicate, Supplier<T> function) { // return new Choice<>(predicate, function); // } // // /** // * Returns <code>true</code> if the <code>predicate</code> provided is <code>true</code> for at least one of the <code>candidates</code>. // */ // public static <T> boolean any(Predicate<T> predicate, T... candidates) { // return C.toStream(candidates).anyMatch(predicate); // } // // /** // * Represents a simple choice tree. This structure can be used as an alternative to // * an <code>if</code> / <code>else if</code> / <code>else</code> structure with optionally enforced choice.<p/> // * // * The constructor of this class is not visible; use the convenience {@link U#Choose(boolean, Supplier)} method to create a new instance of this class. // * It's best practice to statically import this function in client code. // * // * @param <T> the return type // */ // public static class Choice<T> { // private final L<V2<Boolean, Supplier<T>>> choices; // // Choice(boolean predicate, Supplier<T> function) { // choices = l(v(predicate, function)); // } // // /** // * Adds an "or" joined option. // */ // public Choice<T> Or(boolean predicate, Supplier<T> function) { // choices.a(v(predicate, function)); // return this; // } // // /** // * Returns the result of the first "or" option which evaluates to <code>true</code> or the default value provided if there is no valid option. // */ // public T or(T defaultValue) { // V2<Boolean, Supplier<T>> choice = choices.find(it -> it.get0() == true); // return choice != null ? choice.get1().get() : defaultValue; // } // // /** // * Returns the result of the first "or" option which evaluates to <code>true</code> or <code>null</code> if there is no valid option. // */ // public T orNull() { // return or(null); // } // // /** // * Returns the result of the first "or" option which evaluates to <code>true</code> or throws a {@link NoValidChoiceException} if there is no valid option. // */ // public T orThrow() throws NoValidChoiceException { // V2<Boolean, Supplier<T>> choice = choices.find(it -> it.get0() == true); // if (choice != null) { // return choice.get1().get(); // } // else { // throw new NoValidChoiceException(); // } // } // // /** // * Signals that none of the {@link Choice}s provided resolved to <code>true</code>. // */ // public static class NoValidChoiceException extends Exception { // // } // } // } // // Path: src/main/java/ch/codebulb/lambdaomega/abstractions/OmegaObject.java // public abstract class OmegaObject { // /** // * Prints itself to the standard output. // */ // public void println() { // U.println(this); // } // }
import static ch.codebulb.lambdaomega.L.l; import static ch.codebulb.lambdaomega.U.*; import ch.codebulb.lambdaomega.abstractions.OmegaObject; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executor; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.function.BiConsumer; import java.util.function.BiFunction; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier;
public CompletionStage<U> apply(T t) { return fn.apply(t).wrapped; } }; } /** * @see #then(Function, boolean, Executor) */ public <U> Promise<U> then(Function<? super T, ? extends Promise<U>> fn, boolean async) { return then(fn, async, null); } /** * @see #then(Function, boolean, Executor) */ public <U> Promise<U> then(Function<? super T, ? extends Promise<U>> fn) { return then(fn, false); } /** * Like {@link CompletableFuture#allOf(CompletableFuture...)}, but includes a bugfix for the problem described * <a href="http://www.codebulb.ch/2015/07/completablefuture-clean-callbacks-with-java-8s-promises-part-4.html#advanced">here</a>: * "Unfortunately, the resulting combined promise is of type <code>&lt;{@link Void}&gt;</code>, leading to the ridiculous need to create a * listener which takes a single parameter of type {@link Void}. Typically, we would much rather like to have a resulting * promise working with the collected results of the combined promises, i.e. of Type <code>&lt;List&lt;�&gt;&gt;</code>." * This problem is fixed in this implementation. */ public static <T> Promise<List<T>> allOf(Promise<T>... cfs) { Promise<Void> allDoneFuture = new Promise<>(
// Path: src/main/java/ch/codebulb/lambdaomega/L.java // public static <T> L<T> l() { // return new L<>(new ArrayList<>()); // } // // Path: src/main/java/ch/codebulb/lambdaomega/U.java // public class U { // private U() {} // // /** // * Prints the object provided to the standard output. // */ // public static void println(Object out) { // System.out.println(out); // } // // /** // * Creates a {@link Choice}. // */ // public static <T> Choice<T> Choose(boolean predicate, Supplier<T> function) { // return new Choice<>(predicate, function); // } // // /** // * Returns <code>true</code> if the <code>predicate</code> provided is <code>true</code> for at least one of the <code>candidates</code>. // */ // public static <T> boolean any(Predicate<T> predicate, T... candidates) { // return C.toStream(candidates).anyMatch(predicate); // } // // /** // * Represents a simple choice tree. This structure can be used as an alternative to // * an <code>if</code> / <code>else if</code> / <code>else</code> structure with optionally enforced choice.<p/> // * // * The constructor of this class is not visible; use the convenience {@link U#Choose(boolean, Supplier)} method to create a new instance of this class. // * It's best practice to statically import this function in client code. // * // * @param <T> the return type // */ // public static class Choice<T> { // private final L<V2<Boolean, Supplier<T>>> choices; // // Choice(boolean predicate, Supplier<T> function) { // choices = l(v(predicate, function)); // } // // /** // * Adds an "or" joined option. // */ // public Choice<T> Or(boolean predicate, Supplier<T> function) { // choices.a(v(predicate, function)); // return this; // } // // /** // * Returns the result of the first "or" option which evaluates to <code>true</code> or the default value provided if there is no valid option. // */ // public T or(T defaultValue) { // V2<Boolean, Supplier<T>> choice = choices.find(it -> it.get0() == true); // return choice != null ? choice.get1().get() : defaultValue; // } // // /** // * Returns the result of the first "or" option which evaluates to <code>true</code> or <code>null</code> if there is no valid option. // */ // public T orNull() { // return or(null); // } // // /** // * Returns the result of the first "or" option which evaluates to <code>true</code> or throws a {@link NoValidChoiceException} if there is no valid option. // */ // public T orThrow() throws NoValidChoiceException { // V2<Boolean, Supplier<T>> choice = choices.find(it -> it.get0() == true); // if (choice != null) { // return choice.get1().get(); // } // else { // throw new NoValidChoiceException(); // } // } // // /** // * Signals that none of the {@link Choice}s provided resolved to <code>true</code>. // */ // public static class NoValidChoiceException extends Exception { // // } // } // } // // Path: src/main/java/ch/codebulb/lambdaomega/abstractions/OmegaObject.java // public abstract class OmegaObject { // /** // * Prints itself to the standard output. // */ // public void println() { // U.println(this); // } // } // Path: src/main/java/ch/codebulb/lambdaomega/Promise.java import static ch.codebulb.lambdaomega.L.l; import static ch.codebulb.lambdaomega.U.*; import ch.codebulb.lambdaomega.abstractions.OmegaObject; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executor; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.function.BiConsumer; import java.util.function.BiFunction; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; public CompletionStage<U> apply(T t) { return fn.apply(t).wrapped; } }; } /** * @see #then(Function, boolean, Executor) */ public <U> Promise<U> then(Function<? super T, ? extends Promise<U>> fn, boolean async) { return then(fn, async, null); } /** * @see #then(Function, boolean, Executor) */ public <U> Promise<U> then(Function<? super T, ? extends Promise<U>> fn) { return then(fn, false); } /** * Like {@link CompletableFuture#allOf(CompletableFuture...)}, but includes a bugfix for the problem described * <a href="http://www.codebulb.ch/2015/07/completablefuture-clean-callbacks-with-java-8s-promises-part-4.html#advanced">here</a>: * "Unfortunately, the resulting combined promise is of type <code>&lt;{@link Void}&gt;</code>, leading to the ridiculous need to create a * listener which takes a single parameter of type {@link Void}. Typically, we would much rather like to have a resulting * promise working with the collected results of the combined promises, i.e. of Type <code>&lt;List&lt;�&gt;&gt;</code>." * This problem is fixed in this implementation. */ public static <T> Promise<List<T>> allOf(Promise<T>... cfs) { Promise<Void> allDoneFuture = new Promise<>(
CompletableFuture.allOf(l(cfs).map(it -> it.wrapped)
codebulb/LambdaOmega
src/test/java/ch/codebulb/lambdaomega/FunctionalITest.java
// Path: src/main/java/ch/codebulb/lambdaomega/abstractions/FunctionalI.java // @FunctionalInterface // public interface FunctionalI<T, R> extends Function<T, R>, Predicate<T>, Consumer<T>, Supplier<R>, // IntUnaryOperator, LongUnaryOperator, DoubleUnaryOperator, // IntFunction<R>, LongFunction<R>, DoubleFunction<R>, // ToIntFunction<T>, ToLongFunction<T>, ToDoubleFunction<T>, // IntToLongFunction, IntToDoubleFunction, LongToIntFunction, LongToDoubleFunction, DoubleToIntFunction, DoubleToLongFunction, // IntPredicate, LongPredicate, DoublePredicate, // IntConsumer, LongConsumer, DoubleConsumer, // IntSupplier, LongSupplier, DoubleSupplier, BooleanSupplier { // // /** // * Calls this function with the given arguments. // */ // public R call(T t); // // /** // * Calls this function without arguments / with <code>null</code> as argument. // */ // public default R call() { // return call(null); // } // // @Override // public default R apply(T t) { // return call(t); // } // // @Override // public default FunctionalI<T, R> negate() { // Predicate<T> predicate = t -> this.test(t); // // return new FunctionalI<T, R>() { // @Override // public R call(T t) { // return (R)(Boolean)predicate.negate().test(t); // } // }; // } // // @Override // public default boolean test(T t) { // return (Boolean)call(t); // } // // @Override // public default void accept(T t) { // call(t); // } // // @Override // public default R get() { // return call(null); // } // // @Override // public default int applyAsInt(int operand) { // return (Integer)call((T) Integer.valueOf(operand)); // } // // @Override // public default long applyAsLong(long operand) { // return (Long)call((T) Long.valueOf(operand)); // } // // @Override // public default double applyAsDouble(double operand) { // return (Double)call((T) Double.valueOf(operand)); // } // // @Override // public default R apply(int value) { // return call((T) Integer.valueOf(value)); // } // // @Override // public default R apply(long value) { // return call((T) Long.valueOf(value)); // } // // @Override // public default R apply(double value) { // return call((T) Double.valueOf(value)); // } // // @Override // public default int applyAsInt(T value) { // return (Integer)call(value); // } // // @Override // public default long applyAsLong(T value) { // return (Long)call(value); // } // // @Override // public default double applyAsDouble(T value) { // return (Double)call(value); // } // // @Override // public default long applyAsLong(int value) { // return (Long)call((T) Integer.valueOf(value)); // } // // @Override // public default double applyAsDouble(int value) { // return (Double)call((T) Integer.valueOf(value)); // } // // @Override // public default int applyAsInt(long value) { // return (Integer)call((T) Long.valueOf(value)); // } // // @Override // public default double applyAsDouble(long value) { // return (Double)call((T) Long.valueOf(value)); // } // // @Override // public default int applyAsInt(double value) { // return (Integer)call((T) Double.valueOf(value)); // } // // @Override // public default long applyAsLong(double value) { // return (Long)call((T) Double.valueOf(value)); // } // // @Override // public default boolean test(int value) { // return (Boolean)call((T) Integer.valueOf(value)); // } // // @Override // public default boolean test(long value) { // return (Boolean)call((T) Long.valueOf(value)); // } // // @Override // public default boolean test(double value) { // return (Boolean)call((T) Double.valueOf(value)); // } // // @Override // public default void accept(int value) { // call((T) Integer.valueOf(value)); // } // // @Override // public default void accept(long value) { // call((T) Long.valueOf(value)); // } // // @Override // public default void accept(double value) { // call((T) Double.valueOf(value)); // } // // @Override // public default int getAsInt() { // return (Integer)call(null); // } // // @Override // public default long getAsLong() { // return (Long)call(null); // } // // @Override // public default double getAsDouble() { // return (Double)call(null); // } // // @Override // public default boolean getAsBoolean() { // return (Boolean)call(null); // } // }
import ch.codebulb.lambdaomega.abstractions.FunctionalI; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Test;
package ch.codebulb.lambdaomega; public class FunctionalITest { @Test public void testNegate() {
// Path: src/main/java/ch/codebulb/lambdaomega/abstractions/FunctionalI.java // @FunctionalInterface // public interface FunctionalI<T, R> extends Function<T, R>, Predicate<T>, Consumer<T>, Supplier<R>, // IntUnaryOperator, LongUnaryOperator, DoubleUnaryOperator, // IntFunction<R>, LongFunction<R>, DoubleFunction<R>, // ToIntFunction<T>, ToLongFunction<T>, ToDoubleFunction<T>, // IntToLongFunction, IntToDoubleFunction, LongToIntFunction, LongToDoubleFunction, DoubleToIntFunction, DoubleToLongFunction, // IntPredicate, LongPredicate, DoublePredicate, // IntConsumer, LongConsumer, DoubleConsumer, // IntSupplier, LongSupplier, DoubleSupplier, BooleanSupplier { // // /** // * Calls this function with the given arguments. // */ // public R call(T t); // // /** // * Calls this function without arguments / with <code>null</code> as argument. // */ // public default R call() { // return call(null); // } // // @Override // public default R apply(T t) { // return call(t); // } // // @Override // public default FunctionalI<T, R> negate() { // Predicate<T> predicate = t -> this.test(t); // // return new FunctionalI<T, R>() { // @Override // public R call(T t) { // return (R)(Boolean)predicate.negate().test(t); // } // }; // } // // @Override // public default boolean test(T t) { // return (Boolean)call(t); // } // // @Override // public default void accept(T t) { // call(t); // } // // @Override // public default R get() { // return call(null); // } // // @Override // public default int applyAsInt(int operand) { // return (Integer)call((T) Integer.valueOf(operand)); // } // // @Override // public default long applyAsLong(long operand) { // return (Long)call((T) Long.valueOf(operand)); // } // // @Override // public default double applyAsDouble(double operand) { // return (Double)call((T) Double.valueOf(operand)); // } // // @Override // public default R apply(int value) { // return call((T) Integer.valueOf(value)); // } // // @Override // public default R apply(long value) { // return call((T) Long.valueOf(value)); // } // // @Override // public default R apply(double value) { // return call((T) Double.valueOf(value)); // } // // @Override // public default int applyAsInt(T value) { // return (Integer)call(value); // } // // @Override // public default long applyAsLong(T value) { // return (Long)call(value); // } // // @Override // public default double applyAsDouble(T value) { // return (Double)call(value); // } // // @Override // public default long applyAsLong(int value) { // return (Long)call((T) Integer.valueOf(value)); // } // // @Override // public default double applyAsDouble(int value) { // return (Double)call((T) Integer.valueOf(value)); // } // // @Override // public default int applyAsInt(long value) { // return (Integer)call((T) Long.valueOf(value)); // } // // @Override // public default double applyAsDouble(long value) { // return (Double)call((T) Long.valueOf(value)); // } // // @Override // public default int applyAsInt(double value) { // return (Integer)call((T) Double.valueOf(value)); // } // // @Override // public default long applyAsLong(double value) { // return (Long)call((T) Double.valueOf(value)); // } // // @Override // public default boolean test(int value) { // return (Boolean)call((T) Integer.valueOf(value)); // } // // @Override // public default boolean test(long value) { // return (Boolean)call((T) Long.valueOf(value)); // } // // @Override // public default boolean test(double value) { // return (Boolean)call((T) Double.valueOf(value)); // } // // @Override // public default void accept(int value) { // call((T) Integer.valueOf(value)); // } // // @Override // public default void accept(long value) { // call((T) Long.valueOf(value)); // } // // @Override // public default void accept(double value) { // call((T) Double.valueOf(value)); // } // // @Override // public default int getAsInt() { // return (Integer)call(null); // } // // @Override // public default long getAsLong() { // return (Long)call(null); // } // // @Override // public default double getAsDouble() { // return (Double)call(null); // } // // @Override // public default boolean getAsBoolean() { // return (Boolean)call(null); // } // } // Path: src/test/java/ch/codebulb/lambdaomega/FunctionalITest.java import ch.codebulb.lambdaomega.abstractions.FunctionalI; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Test; package ch.codebulb.lambdaomega; public class FunctionalITest { @Test public void testNegate() {
FunctionalI<Integer, Boolean> predicateFunctional = x -> x < 10;
codebulb/LambdaOmega
src/test/java/ch/codebulb/lambdaomega/UTest.java
// Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // class TestUtil { // public static final List<Integer> EXPECTED_LIST = new ArrayList<>(); // static { // EXPECTED_LIST.add(0); // EXPECTED_LIST.add(1); // EXPECTED_LIST.add(2); // } // // public static final List<List<Integer>> EXPECTED_NESTED_LIST = new ArrayList<>(); // static { // EXPECTED_NESTED_LIST.add(EXPECTED_LIST); // EXPECTED_NESTED_LIST.add(EXPECTED_LIST); // } // // public static final Map<String, Integer> EXPECTED_MAP = new LinkedHashMap<>(); // static { // EXPECTED_MAP.put("a", 0); // EXPECTED_MAP.put("b", 1); // EXPECTED_MAP.put("c", 2); // } // // public static final Map<String, Integer> EXPECTED_MAP_2_ELEMENTS = new LinkedHashMap<>(); // static { // EXPECTED_MAP_2_ELEMENTS.put("a", 0); // EXPECTED_MAP_2_ELEMENTS.put("b", 1); // } // // public static final Set<Integer> EXPECTED_SET = new LinkedHashSet<>(); // static { // EXPECTED_SET.add(0); // EXPECTED_SET.add(1); // EXPECTED_SET.add(2); // } // // public static final Set<Set<Integer>> EXPECTED_NESTED_SET = new LinkedHashSet<>(); // static { // EXPECTED_NESTED_SET.add(EXPECTED_SET); // // Set<Integer> set2 = new LinkedHashSet<>(); // set2.add(3); // set2.add(4); // set2.add(5); // EXPECTED_NESTED_SET.add(set2); // } // // public static <T> void assertEquals(T expected, T... actual) { // Arrays.stream(actual).forEach(it -> Assert.assertEquals(expected, it)); // } // } // // Path: src/main/java/ch/codebulb/lambdaomega/U.java // public static <T> Choice<T> Choose(boolean predicate, Supplier<T> function) { // return new Choice<>(predicate, function); // }
import static ch.codebulb.lambdaomega.TestUtil.*; import static ch.codebulb.lambdaomega.U.Choose; import static org.junit.Assert.fail; import org.junit.Test;
package ch.codebulb.lambdaomega; public class UTest { private int actual; @Test public void testChoose() { // With return value
// Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // class TestUtil { // public static final List<Integer> EXPECTED_LIST = new ArrayList<>(); // static { // EXPECTED_LIST.add(0); // EXPECTED_LIST.add(1); // EXPECTED_LIST.add(2); // } // // public static final List<List<Integer>> EXPECTED_NESTED_LIST = new ArrayList<>(); // static { // EXPECTED_NESTED_LIST.add(EXPECTED_LIST); // EXPECTED_NESTED_LIST.add(EXPECTED_LIST); // } // // public static final Map<String, Integer> EXPECTED_MAP = new LinkedHashMap<>(); // static { // EXPECTED_MAP.put("a", 0); // EXPECTED_MAP.put("b", 1); // EXPECTED_MAP.put("c", 2); // } // // public static final Map<String, Integer> EXPECTED_MAP_2_ELEMENTS = new LinkedHashMap<>(); // static { // EXPECTED_MAP_2_ELEMENTS.put("a", 0); // EXPECTED_MAP_2_ELEMENTS.put("b", 1); // } // // public static final Set<Integer> EXPECTED_SET = new LinkedHashSet<>(); // static { // EXPECTED_SET.add(0); // EXPECTED_SET.add(1); // EXPECTED_SET.add(2); // } // // public static final Set<Set<Integer>> EXPECTED_NESTED_SET = new LinkedHashSet<>(); // static { // EXPECTED_NESTED_SET.add(EXPECTED_SET); // // Set<Integer> set2 = new LinkedHashSet<>(); // set2.add(3); // set2.add(4); // set2.add(5); // EXPECTED_NESTED_SET.add(set2); // } // // public static <T> void assertEquals(T expected, T... actual) { // Arrays.stream(actual).forEach(it -> Assert.assertEquals(expected, it)); // } // } // // Path: src/main/java/ch/codebulb/lambdaomega/U.java // public static <T> Choice<T> Choose(boolean predicate, Supplier<T> function) { // return new Choice<>(predicate, function); // } // Path: src/test/java/ch/codebulb/lambdaomega/UTest.java import static ch.codebulb.lambdaomega.TestUtil.*; import static ch.codebulb.lambdaomega.U.Choose; import static org.junit.Assert.fail; import org.junit.Test; package ch.codebulb.lambdaomega; public class UTest { private int actual; @Test public void testChoose() { // With return value
actual = Choose(false, () -> 1).Or(true, () -> 2).Or(true, () -> 3).orNull();
codebulb/LambdaOmega
src/test/java/ch/codebulb/lambdaomega/MBaseSequentialTest.java
// Path: src/main/java/ch/codebulb/lambdaomega/L.java // public static <T> L<T> l() { // return new L<>(new ArrayList<>()); // } // // Path: src/main/java/ch/codebulb/lambdaomega/L.java // public static <T> List<T> list(T... ts) { // return l(ts).l; // } // // Path: src/main/java/ch/codebulb/lambdaomega/M.java // public static <K, V> E<K, V> e(K k, V v) { // return new E(k, v); // } // // Path: src/main/java/ch/codebulb/lambdaomega/M.java // public static M m() { // return m(new LinkedHashMap<>()); // } // // Path: src/main/java/ch/codebulb/lambdaomega/S.java // public static <T> Set<T> set(T... ts) { // return C.toSet(ts); // } // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static final Map<String, Integer> EXPECTED_MAP = new LinkedHashMap<>(); // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static <T> void assertEquals(T expected, T... actual) { // Arrays.stream(actual).forEach(it -> Assert.assertEquals(expected, it)); // }
import static ch.codebulb.lambdaomega.L.l; import static ch.codebulb.lambdaomega.L.list; import static ch.codebulb.lambdaomega.M.e; import static ch.codebulb.lambdaomega.M.m; import static ch.codebulb.lambdaomega.S.set; import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_MAP; import static ch.codebulb.lambdaomega.TestUtil.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Test;
package ch.codebulb.lambdaomega; /** * Test cases for the {@link M} implementation for {@link SequentialI}. */ public class MBaseSequentialTest { @Test public void testConvert() {
// Path: src/main/java/ch/codebulb/lambdaomega/L.java // public static <T> L<T> l() { // return new L<>(new ArrayList<>()); // } // // Path: src/main/java/ch/codebulb/lambdaomega/L.java // public static <T> List<T> list(T... ts) { // return l(ts).l; // } // // Path: src/main/java/ch/codebulb/lambdaomega/M.java // public static <K, V> E<K, V> e(K k, V v) { // return new E(k, v); // } // // Path: src/main/java/ch/codebulb/lambdaomega/M.java // public static M m() { // return m(new LinkedHashMap<>()); // } // // Path: src/main/java/ch/codebulb/lambdaomega/S.java // public static <T> Set<T> set(T... ts) { // return C.toSet(ts); // } // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static final Map<String, Integer> EXPECTED_MAP = new LinkedHashMap<>(); // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static <T> void assertEquals(T expected, T... actual) { // Arrays.stream(actual).forEach(it -> Assert.assertEquals(expected, it)); // } // Path: src/test/java/ch/codebulb/lambdaomega/MBaseSequentialTest.java import static ch.codebulb.lambdaomega.L.l; import static ch.codebulb.lambdaomega.L.list; import static ch.codebulb.lambdaomega.M.e; import static ch.codebulb.lambdaomega.M.m; import static ch.codebulb.lambdaomega.S.set; import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_MAP; import static ch.codebulb.lambdaomega.TestUtil.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Test; package ch.codebulb.lambdaomega; /** * Test cases for the {@link M} implementation for {@link SequentialI}. */ public class MBaseSequentialTest { @Test public void testConvert() {
assertEquals(set(e("a", 0), e("b", 1), e("c", 2)), m("a", 0).i("b", 1).i("c", 2).toSet());
codebulb/LambdaOmega
src/test/java/ch/codebulb/lambdaomega/MBaseSequentialTest.java
// Path: src/main/java/ch/codebulb/lambdaomega/L.java // public static <T> L<T> l() { // return new L<>(new ArrayList<>()); // } // // Path: src/main/java/ch/codebulb/lambdaomega/L.java // public static <T> List<T> list(T... ts) { // return l(ts).l; // } // // Path: src/main/java/ch/codebulb/lambdaomega/M.java // public static <K, V> E<K, V> e(K k, V v) { // return new E(k, v); // } // // Path: src/main/java/ch/codebulb/lambdaomega/M.java // public static M m() { // return m(new LinkedHashMap<>()); // } // // Path: src/main/java/ch/codebulb/lambdaomega/S.java // public static <T> Set<T> set(T... ts) { // return C.toSet(ts); // } // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static final Map<String, Integer> EXPECTED_MAP = new LinkedHashMap<>(); // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static <T> void assertEquals(T expected, T... actual) { // Arrays.stream(actual).forEach(it -> Assert.assertEquals(expected, it)); // }
import static ch.codebulb.lambdaomega.L.l; import static ch.codebulb.lambdaomega.L.list; import static ch.codebulb.lambdaomega.M.e; import static ch.codebulb.lambdaomega.M.m; import static ch.codebulb.lambdaomega.S.set; import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_MAP; import static ch.codebulb.lambdaomega.TestUtil.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Test;
package ch.codebulb.lambdaomega; /** * Test cases for the {@link M} implementation for {@link SequentialI}. */ public class MBaseSequentialTest { @Test public void testConvert() {
// Path: src/main/java/ch/codebulb/lambdaomega/L.java // public static <T> L<T> l() { // return new L<>(new ArrayList<>()); // } // // Path: src/main/java/ch/codebulb/lambdaomega/L.java // public static <T> List<T> list(T... ts) { // return l(ts).l; // } // // Path: src/main/java/ch/codebulb/lambdaomega/M.java // public static <K, V> E<K, V> e(K k, V v) { // return new E(k, v); // } // // Path: src/main/java/ch/codebulb/lambdaomega/M.java // public static M m() { // return m(new LinkedHashMap<>()); // } // // Path: src/main/java/ch/codebulb/lambdaomega/S.java // public static <T> Set<T> set(T... ts) { // return C.toSet(ts); // } // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static final Map<String, Integer> EXPECTED_MAP = new LinkedHashMap<>(); // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static <T> void assertEquals(T expected, T... actual) { // Arrays.stream(actual).forEach(it -> Assert.assertEquals(expected, it)); // } // Path: src/test/java/ch/codebulb/lambdaomega/MBaseSequentialTest.java import static ch.codebulb.lambdaomega.L.l; import static ch.codebulb.lambdaomega.L.list; import static ch.codebulb.lambdaomega.M.e; import static ch.codebulb.lambdaomega.M.m; import static ch.codebulb.lambdaomega.S.set; import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_MAP; import static ch.codebulb.lambdaomega.TestUtil.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Test; package ch.codebulb.lambdaomega; /** * Test cases for the {@link M} implementation for {@link SequentialI}. */ public class MBaseSequentialTest { @Test public void testConvert() {
assertEquals(set(e("a", 0), e("b", 1), e("c", 2)), m("a", 0).i("b", 1).i("c", 2).toSet());
codebulb/LambdaOmega
src/test/java/ch/codebulb/lambdaomega/MBaseSequentialTest.java
// Path: src/main/java/ch/codebulb/lambdaomega/L.java // public static <T> L<T> l() { // return new L<>(new ArrayList<>()); // } // // Path: src/main/java/ch/codebulb/lambdaomega/L.java // public static <T> List<T> list(T... ts) { // return l(ts).l; // } // // Path: src/main/java/ch/codebulb/lambdaomega/M.java // public static <K, V> E<K, V> e(K k, V v) { // return new E(k, v); // } // // Path: src/main/java/ch/codebulb/lambdaomega/M.java // public static M m() { // return m(new LinkedHashMap<>()); // } // // Path: src/main/java/ch/codebulb/lambdaomega/S.java // public static <T> Set<T> set(T... ts) { // return C.toSet(ts); // } // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static final Map<String, Integer> EXPECTED_MAP = new LinkedHashMap<>(); // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static <T> void assertEquals(T expected, T... actual) { // Arrays.stream(actual).forEach(it -> Assert.assertEquals(expected, it)); // }
import static ch.codebulb.lambdaomega.L.l; import static ch.codebulb.lambdaomega.L.list; import static ch.codebulb.lambdaomega.M.e; import static ch.codebulb.lambdaomega.M.m; import static ch.codebulb.lambdaomega.S.set; import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_MAP; import static ch.codebulb.lambdaomega.TestUtil.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Test;
package ch.codebulb.lambdaomega; /** * Test cases for the {@link M} implementation for {@link SequentialI}. */ public class MBaseSequentialTest { @Test public void testConvert() {
// Path: src/main/java/ch/codebulb/lambdaomega/L.java // public static <T> L<T> l() { // return new L<>(new ArrayList<>()); // } // // Path: src/main/java/ch/codebulb/lambdaomega/L.java // public static <T> List<T> list(T... ts) { // return l(ts).l; // } // // Path: src/main/java/ch/codebulb/lambdaomega/M.java // public static <K, V> E<K, V> e(K k, V v) { // return new E(k, v); // } // // Path: src/main/java/ch/codebulb/lambdaomega/M.java // public static M m() { // return m(new LinkedHashMap<>()); // } // // Path: src/main/java/ch/codebulb/lambdaomega/S.java // public static <T> Set<T> set(T... ts) { // return C.toSet(ts); // } // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static final Map<String, Integer> EXPECTED_MAP = new LinkedHashMap<>(); // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static <T> void assertEquals(T expected, T... actual) { // Arrays.stream(actual).forEach(it -> Assert.assertEquals(expected, it)); // } // Path: src/test/java/ch/codebulb/lambdaomega/MBaseSequentialTest.java import static ch.codebulb.lambdaomega.L.l; import static ch.codebulb.lambdaomega.L.list; import static ch.codebulb.lambdaomega.M.e; import static ch.codebulb.lambdaomega.M.m; import static ch.codebulb.lambdaomega.S.set; import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_MAP; import static ch.codebulb.lambdaomega.TestUtil.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Test; package ch.codebulb.lambdaomega; /** * Test cases for the {@link M} implementation for {@link SequentialI}. */ public class MBaseSequentialTest { @Test public void testConvert() {
assertEquals(set(e("a", 0), e("b", 1), e("c", 2)), m("a", 0).i("b", 1).i("c", 2).toSet());
codebulb/LambdaOmega
src/test/java/ch/codebulb/lambdaomega/MBaseSequentialTest.java
// Path: src/main/java/ch/codebulb/lambdaomega/L.java // public static <T> L<T> l() { // return new L<>(new ArrayList<>()); // } // // Path: src/main/java/ch/codebulb/lambdaomega/L.java // public static <T> List<T> list(T... ts) { // return l(ts).l; // } // // Path: src/main/java/ch/codebulb/lambdaomega/M.java // public static <K, V> E<K, V> e(K k, V v) { // return new E(k, v); // } // // Path: src/main/java/ch/codebulb/lambdaomega/M.java // public static M m() { // return m(new LinkedHashMap<>()); // } // // Path: src/main/java/ch/codebulb/lambdaomega/S.java // public static <T> Set<T> set(T... ts) { // return C.toSet(ts); // } // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static final Map<String, Integer> EXPECTED_MAP = new LinkedHashMap<>(); // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static <T> void assertEquals(T expected, T... actual) { // Arrays.stream(actual).forEach(it -> Assert.assertEquals(expected, it)); // }
import static ch.codebulb.lambdaomega.L.l; import static ch.codebulb.lambdaomega.L.list; import static ch.codebulb.lambdaomega.M.e; import static ch.codebulb.lambdaomega.M.m; import static ch.codebulb.lambdaomega.S.set; import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_MAP; import static ch.codebulb.lambdaomega.TestUtil.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Test;
package ch.codebulb.lambdaomega; /** * Test cases for the {@link M} implementation for {@link SequentialI}. */ public class MBaseSequentialTest { @Test public void testConvert() {
// Path: src/main/java/ch/codebulb/lambdaomega/L.java // public static <T> L<T> l() { // return new L<>(new ArrayList<>()); // } // // Path: src/main/java/ch/codebulb/lambdaomega/L.java // public static <T> List<T> list(T... ts) { // return l(ts).l; // } // // Path: src/main/java/ch/codebulb/lambdaomega/M.java // public static <K, V> E<K, V> e(K k, V v) { // return new E(k, v); // } // // Path: src/main/java/ch/codebulb/lambdaomega/M.java // public static M m() { // return m(new LinkedHashMap<>()); // } // // Path: src/main/java/ch/codebulb/lambdaomega/S.java // public static <T> Set<T> set(T... ts) { // return C.toSet(ts); // } // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static final Map<String, Integer> EXPECTED_MAP = new LinkedHashMap<>(); // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static <T> void assertEquals(T expected, T... actual) { // Arrays.stream(actual).forEach(it -> Assert.assertEquals(expected, it)); // } // Path: src/test/java/ch/codebulb/lambdaomega/MBaseSequentialTest.java import static ch.codebulb.lambdaomega.L.l; import static ch.codebulb.lambdaomega.L.list; import static ch.codebulb.lambdaomega.M.e; import static ch.codebulb.lambdaomega.M.m; import static ch.codebulb.lambdaomega.S.set; import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_MAP; import static ch.codebulb.lambdaomega.TestUtil.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Test; package ch.codebulb.lambdaomega; /** * Test cases for the {@link M} implementation for {@link SequentialI}. */ public class MBaseSequentialTest { @Test public void testConvert() {
assertEquals(set(e("a", 0), e("b", 1), e("c", 2)), m("a", 0).i("b", 1).i("c", 2).toSet());
codebulb/LambdaOmega
src/test/java/ch/codebulb/lambdaomega/MBaseSequentialTest.java
// Path: src/main/java/ch/codebulb/lambdaomega/L.java // public static <T> L<T> l() { // return new L<>(new ArrayList<>()); // } // // Path: src/main/java/ch/codebulb/lambdaomega/L.java // public static <T> List<T> list(T... ts) { // return l(ts).l; // } // // Path: src/main/java/ch/codebulb/lambdaomega/M.java // public static <K, V> E<K, V> e(K k, V v) { // return new E(k, v); // } // // Path: src/main/java/ch/codebulb/lambdaomega/M.java // public static M m() { // return m(new LinkedHashMap<>()); // } // // Path: src/main/java/ch/codebulb/lambdaomega/S.java // public static <T> Set<T> set(T... ts) { // return C.toSet(ts); // } // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static final Map<String, Integer> EXPECTED_MAP = new LinkedHashMap<>(); // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static <T> void assertEquals(T expected, T... actual) { // Arrays.stream(actual).forEach(it -> Assert.assertEquals(expected, it)); // }
import static ch.codebulb.lambdaomega.L.l; import static ch.codebulb.lambdaomega.L.list; import static ch.codebulb.lambdaomega.M.e; import static ch.codebulb.lambdaomega.M.m; import static ch.codebulb.lambdaomega.S.set; import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_MAP; import static ch.codebulb.lambdaomega.TestUtil.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Test;
package ch.codebulb.lambdaomega; /** * Test cases for the {@link M} implementation for {@link SequentialI}. */ public class MBaseSequentialTest { @Test public void testConvert() { assertEquals(set(e("a", 0), e("b", 1), e("c", 2)), m("a", 0).i("b", 1).i("c", 2).toSet()); assertEquals(m("a", 0).i("b", 1).i("c", 2).m, m("a", 0).i("b", 1).i("c", 2).toMap()); } @Test public void testCollection() { assertEquals(0, m().size()); assertEquals(3, m("a", 0).i("b", 1).i("c", 2).size()); assertTrue(m().isEmpty()); assertFalse(m("a", 0).i("b", 1).i("c", 2).isEmpty()); assertEquals(set(), m("a", 0).i("b", 1).i("c", 2).clear()); } @Test public void testAdd() { // Add individual elements
// Path: src/main/java/ch/codebulb/lambdaomega/L.java // public static <T> L<T> l() { // return new L<>(new ArrayList<>()); // } // // Path: src/main/java/ch/codebulb/lambdaomega/L.java // public static <T> List<T> list(T... ts) { // return l(ts).l; // } // // Path: src/main/java/ch/codebulb/lambdaomega/M.java // public static <K, V> E<K, V> e(K k, V v) { // return new E(k, v); // } // // Path: src/main/java/ch/codebulb/lambdaomega/M.java // public static M m() { // return m(new LinkedHashMap<>()); // } // // Path: src/main/java/ch/codebulb/lambdaomega/S.java // public static <T> Set<T> set(T... ts) { // return C.toSet(ts); // } // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static final Map<String, Integer> EXPECTED_MAP = new LinkedHashMap<>(); // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static <T> void assertEquals(T expected, T... actual) { // Arrays.stream(actual).forEach(it -> Assert.assertEquals(expected, it)); // } // Path: src/test/java/ch/codebulb/lambdaomega/MBaseSequentialTest.java import static ch.codebulb.lambdaomega.L.l; import static ch.codebulb.lambdaomega.L.list; import static ch.codebulb.lambdaomega.M.e; import static ch.codebulb.lambdaomega.M.m; import static ch.codebulb.lambdaomega.S.set; import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_MAP; import static ch.codebulb.lambdaomega.TestUtil.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Test; package ch.codebulb.lambdaomega; /** * Test cases for the {@link M} implementation for {@link SequentialI}. */ public class MBaseSequentialTest { @Test public void testConvert() { assertEquals(set(e("a", 0), e("b", 1), e("c", 2)), m("a", 0).i("b", 1).i("c", 2).toSet()); assertEquals(m("a", 0).i("b", 1).i("c", 2).m, m("a", 0).i("b", 1).i("c", 2).toMap()); } @Test public void testCollection() { assertEquals(0, m().size()); assertEquals(3, m("a", 0).i("b", 1).i("c", 2).size()); assertTrue(m().isEmpty()); assertFalse(m("a", 0).i("b", 1).i("c", 2).isEmpty()); assertEquals(set(), m("a", 0).i("b", 1).i("c", 2).clear()); } @Test public void testAdd() { // Add individual elements
assertEquals(EXPECTED_MAP, m("a", 0).i("b", 1).Add(e("c", 2)).m);
codebulb/LambdaOmega
src/test/java/ch/codebulb/lambdaomega/MBaseSequentialTest.java
// Path: src/main/java/ch/codebulb/lambdaomega/L.java // public static <T> L<T> l() { // return new L<>(new ArrayList<>()); // } // // Path: src/main/java/ch/codebulb/lambdaomega/L.java // public static <T> List<T> list(T... ts) { // return l(ts).l; // } // // Path: src/main/java/ch/codebulb/lambdaomega/M.java // public static <K, V> E<K, V> e(K k, V v) { // return new E(k, v); // } // // Path: src/main/java/ch/codebulb/lambdaomega/M.java // public static M m() { // return m(new LinkedHashMap<>()); // } // // Path: src/main/java/ch/codebulb/lambdaomega/S.java // public static <T> Set<T> set(T... ts) { // return C.toSet(ts); // } // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static final Map<String, Integer> EXPECTED_MAP = new LinkedHashMap<>(); // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static <T> void assertEquals(T expected, T... actual) { // Arrays.stream(actual).forEach(it -> Assert.assertEquals(expected, it)); // }
import static ch.codebulb.lambdaomega.L.l; import static ch.codebulb.lambdaomega.L.list; import static ch.codebulb.lambdaomega.M.e; import static ch.codebulb.lambdaomega.M.m; import static ch.codebulb.lambdaomega.S.set; import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_MAP; import static ch.codebulb.lambdaomega.TestUtil.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Test;
package ch.codebulb.lambdaomega; /** * Test cases for the {@link M} implementation for {@link SequentialI}. */ public class MBaseSequentialTest { @Test public void testConvert() { assertEquals(set(e("a", 0), e("b", 1), e("c", 2)), m("a", 0).i("b", 1).i("c", 2).toSet()); assertEquals(m("a", 0).i("b", 1).i("c", 2).m, m("a", 0).i("b", 1).i("c", 2).toMap()); } @Test public void testCollection() { assertEquals(0, m().size()); assertEquals(3, m("a", 0).i("b", 1).i("c", 2).size()); assertTrue(m().isEmpty()); assertFalse(m("a", 0).i("b", 1).i("c", 2).isEmpty()); assertEquals(set(), m("a", 0).i("b", 1).i("c", 2).clear()); } @Test public void testAdd() { // Add individual elements assertEquals(EXPECTED_MAP, m("a", 0).i("b", 1).Add(e("c", 2)).m); assertEquals(EXPECTED_MAP, m("a", 0).i("b", 1).a(e("c", 2)).m); assertEquals(set(e("a", 0), e("b", 1), e("c", 2)), m("a", 0).i("b", 1).add(e("c", 2))); assertEquals(EXPECTED_MAP, m(Number.class).Add(e("a", 0), e("b", 1), e("c", 2)).m); assertEquals(EXPECTED_MAP, m(Number.class).a(e("a", 0), e("b", 1), e("c", 2)).m); assertEquals(set(e("a", 0), e("b", 1), e("c", 2)), m(Number.class).add(e("a", 0), e("b", 1), e("c", 2))); // Add all entries
// Path: src/main/java/ch/codebulb/lambdaomega/L.java // public static <T> L<T> l() { // return new L<>(new ArrayList<>()); // } // // Path: src/main/java/ch/codebulb/lambdaomega/L.java // public static <T> List<T> list(T... ts) { // return l(ts).l; // } // // Path: src/main/java/ch/codebulb/lambdaomega/M.java // public static <K, V> E<K, V> e(K k, V v) { // return new E(k, v); // } // // Path: src/main/java/ch/codebulb/lambdaomega/M.java // public static M m() { // return m(new LinkedHashMap<>()); // } // // Path: src/main/java/ch/codebulb/lambdaomega/S.java // public static <T> Set<T> set(T... ts) { // return C.toSet(ts); // } // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static final Map<String, Integer> EXPECTED_MAP = new LinkedHashMap<>(); // // Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java // public static <T> void assertEquals(T expected, T... actual) { // Arrays.stream(actual).forEach(it -> Assert.assertEquals(expected, it)); // } // Path: src/test/java/ch/codebulb/lambdaomega/MBaseSequentialTest.java import static ch.codebulb.lambdaomega.L.l; import static ch.codebulb.lambdaomega.L.list; import static ch.codebulb.lambdaomega.M.e; import static ch.codebulb.lambdaomega.M.m; import static ch.codebulb.lambdaomega.S.set; import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_MAP; import static ch.codebulb.lambdaomega.TestUtil.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Test; package ch.codebulb.lambdaomega; /** * Test cases for the {@link M} implementation for {@link SequentialI}. */ public class MBaseSequentialTest { @Test public void testConvert() { assertEquals(set(e("a", 0), e("b", 1), e("c", 2)), m("a", 0).i("b", 1).i("c", 2).toSet()); assertEquals(m("a", 0).i("b", 1).i("c", 2).m, m("a", 0).i("b", 1).i("c", 2).toMap()); } @Test public void testCollection() { assertEquals(0, m().size()); assertEquals(3, m("a", 0).i("b", 1).i("c", 2).size()); assertTrue(m().isEmpty()); assertFalse(m("a", 0).i("b", 1).i("c", 2).isEmpty()); assertEquals(set(), m("a", 0).i("b", 1).i("c", 2).clear()); } @Test public void testAdd() { // Add individual elements assertEquals(EXPECTED_MAP, m("a", 0).i("b", 1).Add(e("c", 2)).m); assertEquals(EXPECTED_MAP, m("a", 0).i("b", 1).a(e("c", 2)).m); assertEquals(set(e("a", 0), e("b", 1), e("c", 2)), m("a", 0).i("b", 1).add(e("c", 2))); assertEquals(EXPECTED_MAP, m(Number.class).Add(e("a", 0), e("b", 1), e("c", 2)).m); assertEquals(EXPECTED_MAP, m(Number.class).a(e("a", 0), e("b", 1), e("c", 2)).m); assertEquals(set(e("a", 0), e("b", 1), e("c", 2)), m(Number.class).add(e("a", 0), e("b", 1), e("c", 2))); // Add all entries
assertEquals(EXPECTED_MAP, m(Number.class).AddAll(list(e("a", 0), e("b", 1), e("c", 2))).m);