src_fm_fc_ms_ff
stringlengths 43
86.8k
| target
stringlengths 20
276k
|
---|---|
API { @NotNull public static List<String> generateCDepCall( @NotNull GeneratorEnvironment environment, String ... args) throws MalformedURLException { List<String> result = new ArrayList<>(); result.addAll(callCDep(environment)); Collections.addAll(result, args); return result; } @NotNull static List<String> generateCDepCall(
@NotNull GeneratorEnvironment environment,
String ... args); }
|
@Test public void testExecute() throws Exception { String result = execute(API.generateCDepCall(environment, "show", "folders")); System.out.print(result); assertThat(result).contains("cdep"); }
|
CMakeGenerator { @NotNull public String create() { append("# GENERATED FILE. DO NOT EDIT.\n"); append(readCmakeLibraryFunctions()); for (StatementExpression findFunction : table.findFunctions.values()) { indent = 0; visit(findFunction); require(indent == 0); } append("\nfunction(add_all_cdep_dependencies target)\n"); for (StatementExpression findFunction : table.findFunctions.values()) { FindModuleExpression finder = getFindFunction(findFunction); String function = getAddDependencyFunctionName(finder.coordinate); append(" %s(${target})\n", function); } append("endfunction(add_all_cdep_dependencies)\n"); return sb.toString(); } CMakeGenerator(@NotNull GeneratorEnvironment environment, @NotNull FunctionTableExpression table); void generate(); @NotNull String create(); }
|
@Test public void fuzzTest() { QuickCheck.forAll(new CDepManifestYmlGenerator(), new AbstractCharacteristic<CDepManifestYml>() { @Override protected void doSpecify(CDepManifestYml any) throws Throwable { String capture = CDepManifestYmlUtils.convertManifestToString(any); CDepManifestYml readAny = CDepManifestYmlUtils.convertStringToManifest(capture); try { Invariant.pushScope(false); BuildFindModuleFunctionTable builder = new BuildFindModuleFunctionTable(); builder.addManifest(new ResolvedManifest(new URL("https: FunctionTableExpression table = builder.build(); String result = new CMakeGenerator(environment, table).create(); } finally { Invariant.popScope(); } } }); }
@Test public void testBoost() throws Exception { BuildFindModuleFunctionTable builder = new BuildFindModuleFunctionTable(); builder.addManifest(ResolvedManifests.boost().manifest); FunctionTableExpression table = builder.build(); String result = new CMakeGenerator(environment, table).create(); System.out.printf(result); }
@Test public void testRequires() throws Exception { BuildFindModuleFunctionTable builder = new BuildFindModuleFunctionTable(); builder.addManifest(ResolvedManifests.multipleRequires().manifest); FunctionTableExpression table = builder.build(); String result = new CMakeGenerator(environment, table).create(); System.out.printf(result); assertThat(result).contains("target_compile_features(${target} PRIVATE " + "cxx_auto_type cxx_decltype)"); }
|
CMakeGenerator { public void generate() throws IOException { File file = getCMakeConfigurationFile(); String text = create(); info("Generating %s\n", file); FileUtils.writeTextToFile(file, text); } CMakeGenerator(@NotNull GeneratorEnvironment environment, @NotNull FunctionTableExpression table); void generate(); @NotNull String create(); }
|
@Test public void testAllResolvedManifests() throws Exception { Map<String, String> expected = new HashMap<>(); expected.put("admob", "Reference com.github.jomof:firebase/app:2.1.3-rev8 was not found, " + "needed by com.github.jomof:firebase/admob:2.1.3-rev8"); expected.put("fuzz1", "Could not parse main manifest coordinate []"); boolean unexpectedFailures = false; for (ResolvedManifests.NamedManifest manifest : ResolvedManifests.all()) { BuildFindModuleFunctionTable builder = new BuildFindModuleFunctionTable(); builder.addManifest(manifest.resolved); String expectedFailure = expected.get(manifest.name); try { FunctionTableExpression table = builder.build(); new CMakeGenerator(environment, table).generate(); if (expectedFailure != null) { fail("Expected failure"); } } catch (RuntimeException e) { if (expectedFailure == null || !expectedFailure.equals(e.getMessage())) { System.out.printf("expected.put(\"%s\", \"%s\")\n", manifest.name, e.getMessage()); unexpectedFailures = true; } } } if (unexpectedFailures) { throw new RuntimeException("Unexpected failures. See console."); } }
@Test public void testAllResolvedManifests() throws Exception { Map<String, String> expected = new LinkedHashMap<>(); expected.put("admob", "Reference com.github.jomof:firebase/app:2.1.3-rev8 was not found, " + "needed by com.github.jomof:firebase/admob:2.1.3-rev8"); expected.put("fuzz1", "Could not parse main manifest coordinate []"); boolean unexpectedFailures = false; for (ResolvedManifests.NamedManifest manifest : ResolvedManifests.all()) { BuildFindModuleFunctionTable builder = new BuildFindModuleFunctionTable(); if(Objects.equals(manifest.name, "curlAndroid")) { builder.addManifest(ResolvedManifests.zlibAndroid().manifest); builder.addManifest(ResolvedManifests.boringSSLAndroid().manifest); } builder.addManifest(manifest.resolved); String expectedFailure = expected.get(manifest.name); try { FunctionTableExpression table = builder.build(); new CMakeGenerator(environment, table).generate(); if (expectedFailure != null) { fail("Expected failure"); } } catch (RuntimeException e) { if (expectedFailure == null || !expectedFailure.equals(e.getMessage())) { System.out.printf("expected.put(\"%s\", \"%s\")\n", manifest.name, e.getMessage()); unexpectedFailures = true; } } } if (unexpectedFailures) { throw new RuntimeException("Unexpected failures. See console."); } }
|
CxxLanguageStandardRewritingVisitor extends RewritingVisitor { @Override protected Expression visitModuleExpression(@NotNull ModuleExpression expr) { ModuleArchiveExpression archive = expr.archive; CxxLanguageFeatures requires[] = archive.requires; if (requires.length == 0) { return super.visitModuleExpression(expr); } archive = new ModuleArchiveExpression(archive.file, archive.sha256, archive.size, archive.include, archive.includePath, archive.libs, archive.libraryPaths, new CxxLanguageFeatures[0]); List<ConstantExpression> features = new ArrayList<>(); for (CxxLanguageFeatures require : requires) { features.add(constant(require)); } int minimumLanguageStandard = 0; for (CxxLanguageFeatures require : requires) { minimumLanguageStandard = Math.max( minimumLanguageStandard, require.standard); } List<StatementExpression> exprs = new ArrayList<>(); exprs.add( ifSwitch( supportsCompilerFeatures(), requiresCompilerFeatures(array(features.toArray(new ConstantExpression[requires.length]))), requireMinimumCxxCompilerStandard(constant(minimumLanguageStandard)))); exprs.add(archive); return new MultiStatementExpression(exprs.toArray(new StatementExpression[exprs.size()])); } }
|
@Test public void testSimple() throws Exception { GlobalBuildEnvironmentExpression globals = new GlobalBuildEnvironmentExpression(); CxxLanguageStandardRewritingVisitor rewriter = new CxxLanguageStandardRewritingVisitor(); rewriter.visit(globals); ModuleArchiveExpression archive = makeArchive(CxxLanguageFeatures.cxx_alignof); ModuleExpression module = new ModuleExpression(archive, new HashSet<Coordinate>()); Expression result = ((MultiStatementExpression) rewriter.visitModuleExpression(module)).statements[0]; InterpretingVisitor interpreter = new InterpretingVisitor(); Object callvalue = interpreter.visit(result); assertThat(callvalue.getClass()).isEqualTo(CxxLanguageFeatures[].class); }
@Test public void testSimpleStandard17() throws Exception { GlobalBuildEnvironmentExpression globals = new GlobalBuildEnvironmentExpression(); CxxLanguageStandardRewritingVisitor rewriter = new CxxLanguageStandardRewritingVisitor(); rewriter.visit(globals); ModuleArchiveExpression archive = makeArchive(CxxLanguageFeatures.cxx_std_17); ModuleExpression module = new ModuleExpression(archive, new HashSet<Coordinate>()); Expression result = ((MultiStatementExpression) rewriter.visitModuleExpression(module)).statements[0]; InterpretingVisitor interpreter = new InterpretingVisitor(); Object callvalue = interpreter.visit(result); assertThat(callvalue.getClass()).isEqualTo(CxxLanguageFeatures[].class); }
|
NdkBuildGenerator extends AbstractNdkBuildGenerator { public void generate(FunctionTableExpression expr) { expr = (FunctionTableExpression) new JoinedFileToStringRewriter("(", ")").visitFunctionTableExpression(expr); visit(expr); } NdkBuildGenerator(@NotNull GeneratorEnvironment environment); void generate(FunctionTableExpression expr); }
|
@Test public void fuzzTest() { QuickCheck.forAll(new CDepManifestYmlGenerator(), new AbstractCharacteristic<CDepManifestYml>() { @Override protected void doSpecify(CDepManifestYml any) throws Throwable { String capture = CDepManifestYmlUtils.convertManifestToString(any); CDepManifestYml readAny = CDepManifestYmlUtils.convertStringToManifest(capture); try { Invariant.pushScope(false); BuildFindModuleFunctionTable builder = new BuildFindModuleFunctionTable(); builder.addManifest(new ResolvedManifest(new URL("https: FunctionTableExpression table = builder.build(); new NdkBuildGenerator(environment).generate(table); } finally { Invariant.popScope(); } } }); }
@Test public void testBoost() throws Exception { BuildFindModuleFunctionTable builder = new BuildFindModuleFunctionTable(); builder.addManifest(ResolvedManifests.boost().manifest); FunctionTableExpression table = builder.build(); new NdkBuildGenerator(environment).generate(table); }
@Test public void testOpenssl() throws Exception { BuildFindModuleFunctionTable builder = new BuildFindModuleFunctionTable(); builder.addManifest(ResolvedManifests.openssl().manifest); FunctionTableExpression table = builder.build(); new NdkBuildGenerator(environment).generate(table); }
@Test public void testMultiple() throws Exception { BuildFindModuleFunctionTable builder = new BuildFindModuleFunctionTable(); builder.addManifest(ResolvedManifests.boost().manifest); builder.addManifest(ResolvedManifests.sqliteAndroid().manifest); FunctionTableExpression table = builder.build(); new NdkBuildGenerator(environment).generate(table); }
@Test public void testRequires() throws Exception { BuildFindModuleFunctionTable builder = new BuildFindModuleFunctionTable(); builder.addManifest(ResolvedManifests.multipleRequires().manifest); FunctionTableExpression table = builder.build(); new NdkBuildGenerator(environment).generate(table); }
@Test public void testAllResolvedManifests() throws Exception { Map<String, String> expected = new HashMap<>(); expected.put("admob", "Reference com.github.jomof:firebase/app:2.1.3-rev8 was not found, " + "needed by com.github.jomof:firebase/admob:2.1.3-rev8"); expected.put("fuzz1", "Could not parse main manifest coordinate []"); boolean unexpectedFailures = false; for (ResolvedManifests.NamedManifest manifest : ResolvedManifests.all()) { BuildFindModuleFunctionTable builder = new BuildFindModuleFunctionTable(); builder.addManifest(manifest.resolved); String expectedFailure = expected.get(manifest.name); try { FunctionTableExpression table = builder.build(); new NdkBuildGenerator(environment).generate(table); if (expectedFailure != null) { fail("Expected failure"); } } catch (RuntimeException e) { if (expectedFailure == null || !expectedFailure.equals(e.getMessage())) { System.out.printf("expected.put(\"%s\", \"%s\")\n", manifest.name, e.getMessage()); unexpectedFailures = true; } } } if (unexpectedFailures) { throw new RuntimeException("Unexpected failures. See console."); } }
|
GithubStyleUrlCoordinateResolver extends CoordinateResolver { @Nullable @Override public ResolvedManifest resolve(@NotNull ManifestProvider environment, @NotNull SoftNameDependency dependency) throws IOException, NoSuchAlgorithmException { String coordinate = dependency.compile; assert coordinate != null; Matcher match = pattern.matcher(coordinate); if (match.find()) { String baseUrl = match.group(1); String segments[] = baseUrl.split("\\."); String groupId = ""; for (int i = 0; i < segments.length; ++i) { groupId += segments[segments.length - i - 1]; groupId += "."; } String user = match.group(2); groupId += user; String artifactId = match.group(3); Version version = new Version(match.group(4)); String subArtifact = match.group(5); if (subArtifact.length() > 0) { require(subArtifact.startsWith("-"), "Url is incorrectly formed at '%s': %s", subArtifact, coordinate); artifactId += "/" + subArtifact.substring(1); } Coordinate provisionalCoordinate = new Coordinate(groupId, artifactId, version); CDepManifestYml cdepManifestYml = environment.tryGetManifest(provisionalCoordinate, new URL(coordinate)); if (cdepManifestYml == null) { return null; } require(groupId.equals(cdepManifestYml.coordinate.groupId), "groupId '%s' from manifest did not agree with github url %s", cdepManifestYml.coordinate.groupId, coordinate); require(artifactId.startsWith(cdepManifestYml.coordinate.artifactId), "artifactId '%s' from manifest did not agree with '%s' from github url %s", artifactId, cdepManifestYml.coordinate.artifactId, coordinate); require(version.equals(cdepManifestYml.coordinate.version), "version '%s' from manifest did not agree with version %s github url %s", cdepManifestYml.coordinate.version, version, coordinate); return new ResolvedManifest(new URL(coordinate), cdepManifestYml); } return null; } @Nullable @Override ResolvedManifest resolve(@NotNull ManifestProvider environment, @NotNull SoftNameDependency dependency); }
|
@Test public void testSimple() throws Exception { ResolvedManifest resolved = new GithubStyleUrlCoordinateResolver().resolve(environment, new SoftNameDependency ("https: assert resolved != null; assert resolved.cdepManifestYml.coordinate != null; assertThat(resolved.cdepManifestYml.coordinate.groupId).isEqualTo("com.github.jomof"); assertThat(resolved.cdepManifestYml.coordinate.artifactId).isEqualTo("cmakeify"); assertThat(resolved.cdepManifestYml.coordinate.version.value).isEqualTo("0.0.81"); assert resolved.cdepManifestYml.android != null; assert resolved.cdepManifestYml.android.archives != null; assertThat(resolved.cdepManifestYml.android.archives.length).isEqualTo(8); }
@Test public void testCompound() throws Exception { ResolvedManifest resolved = new GithubStyleUrlCoordinateResolver().resolve(environment, new SoftNameDependency ("https: assert resolved != null; assert resolved.cdepManifestYml.coordinate != null; assertThat(resolved.cdepManifestYml.coordinate.groupId).isEqualTo("com.github.jomof"); assertThat(resolved.cdepManifestYml.coordinate.artifactId).isEqualTo("firebase/database"); assertThat(resolved.cdepManifestYml.coordinate.version.value).isEqualTo("2.1.3-rev5"); assert resolved.cdepManifestYml.android != null; assert resolved.cdepManifestYml.android.archives != null; assertThat(resolved.cdepManifestYml.android.archives.length).isEqualTo(21); }
@Test public void testMissing() throws Exception { ResolvedManifest resolved = new GithubStyleUrlCoordinateResolver().resolve(environment, new SoftNameDependency ("https: assertThat(resolved).isNull(); }
|
Resolver { @Nullable public ResolvedManifest resolveAny(@NotNull SoftNameDependency dependency) throws IOException, NoSuchAlgorithmException { ResolvedManifest resolved = null; for (CoordinateResolver resolver : resolvers) { ResolvedManifest attempt = resolver.resolve(manifestProvider, dependency); if (attempt != null) { require(resolved == null, "Multiple resolvers matched coordinate: " + dependency.compile); resolved = attempt; } } if (resolved != null) { CDepManifestYmlUtils.checkManifestSanity(resolved.cdepManifestYml); } return resolved; } Resolver(ManifestProvider manifestProvider); Resolver(ManifestProvider manifestProvider, CoordinateResolver resolvers[]); @NotNull ResolutionScope resolveAll(@NotNull SoftNameDependency[] roots); void resolveAll(@NotNull ResolutionScope scope); @Nullable ResolvedManifest resolveAny(@NotNull SoftNameDependency dependency); }
|
@Test public void twoResolversMatch() throws Exception { ManifestProvider provider = mock(ManifestProvider.class); when(provider.tryGetManifest(ADMOB_COORDINATE, new URL(ADMOB_URL))).thenReturn(ADMOB_MANIFEST); CoordinateResolver resolvers[] = new CoordinateResolver[]{new GithubReleasesCoordinateResolver(), new GithubReleasesCoordinateResolver()}; Resolver resolver = new Resolver(provider, resolvers); try { assert ADMOB_COORDINATE != null; resolver.resolveAny(new SoftNameDependency(ADMOB_COORDINATE.toString())); fail("Expected exception"); } catch (RuntimeException e) { assertThat(e).hasMessage("Multiple resolvers matched coordinate: com.github.jomof:firebase/admob:2.1.3-rev7"); } }
|
Resolver { @NotNull public ResolutionScope resolveAll(@NotNull SoftNameDependency[] roots) throws IOException, NoSuchAlgorithmException { ResolutionScope scope = new ResolutionScope(roots); resolveAll(scope); return scope; } Resolver(ManifestProvider manifestProvider); Resolver(ManifestProvider manifestProvider, CoordinateResolver resolvers[]); @NotNull ResolutionScope resolveAll(@NotNull SoftNameDependency[] roots); void resolveAll(@NotNull ResolutionScope scope); @Nullable ResolvedManifest resolveAny(@NotNull SoftNameDependency dependency); }
|
@Test public void testScopeUnresolvableDependencyResolve() throws Exception { ManifestProvider provider = mock(ManifestProvider.class); when(provider.tryGetManifest(ADMOB_COORDINATE, new URL(ADMOB_URL))).thenReturn(ADMOB_MISSING_DEPENDENCY_MANIFEST); Resolver resolver = new Resolver(provider); try { assert ADMOB_COORDINATE != null; resolver.resolveAll(new SoftNameDependency[]{new SoftNameDependency(ADMOB_COORDINATE.toString())}); fail("Expected exception"); } catch (RuntimeException e) { assertThat(e).hasMessage("Archive com.github.jomof:firebase/admob:2.1.3-rev7 is missing include"); } }
@Test public void testScopeMalformedDependencyResolve() throws Exception { ManifestProvider provider = mock(ManifestProvider.class); when(provider.tryGetManifest(ADMOB_COORDINATE, new URL(ADMOB_URL))).thenReturn(ADMOB_BROKEN_DEPENDENCY_MANIFEST); Resolver resolver = new Resolver(provider); try { assert ADMOB_COORDINATE != null; resolver.resolveAll(new SoftNameDependency[]{new SoftNameDependency(ADMOB_COORDINATE.toString())}); fail("Expected exception"); } catch (RuntimeException e) { assertThat(e).hasMessage("Archive com.github.jomof:firebase/admob:2.1.3-rev7 is missing include"); } }
@Test public void testEmptyScopeResolution() throws Exception { ManifestProvider provider = mock(ManifestProvider.class); when(provider.tryGetManifest(ADMOB_COORDINATE, new URL(ADMOB_URL))).thenReturn(ADMOB_MISSING_DEPENDENCY_MANIFEST); Resolver resolver = new Resolver(provider); ResolutionScope scope = resolver.resolveAll(new SoftNameDependency[]{}); assertThat(scope.isResolutionComplete()).isTrue(); assertThat(scope.getResolutions()).hasSize(0); }
|
GithubReleasesCoordinateResolver extends CoordinateResolver { @Nullable @Override public ResolvedManifest resolve(@NotNull ManifestProvider environment, @NotNull SoftNameDependency dependency) throws IOException, NoSuchAlgorithmException { String coordinate = dependency.compile; assert coordinate != null; Matcher match = pattern.matcher(coordinate); if (match.find()) { String user = match.group(1); String artifactId = match.group(2); String version = match.group(3); String subArtifact = ""; if (artifactId.contains("/")) { int pos = artifactId.indexOf("/"); subArtifact = "-" + artifactId.substring(pos + 1); artifactId = artifactId.substring(0, pos); } String manifest = String.format("https: user, artifactId, version, subArtifact); return urlResolver.resolve(environment, new SoftNameDependency(manifest)); } return null; } @Nullable @Override ResolvedManifest resolve(@NotNull ManifestProvider environment, @NotNull SoftNameDependency dependency); }
|
@Test public void testCompound() throws Exception { ResolvedManifest resolved = new GithubReleasesCoordinateResolver().resolve(environment, new SoftNameDependency("com.github" + ".jomof:firebase/database:2.1.3-rev5")); assert resolved != null; assert resolved.cdepManifestYml.coordinate != null; assertThat(resolved.cdepManifestYml.coordinate.groupId).isEqualTo("com.github.jomof"); assertThat(resolved.cdepManifestYml.coordinate.artifactId).isEqualTo("firebase/database"); assertThat(resolved.cdepManifestYml.coordinate.version.value).isEqualTo("2.1.3-rev5"); assert resolved.cdepManifestYml.android != null; assert resolved.cdepManifestYml.android.archives != null; assertThat(resolved.cdepManifestYml.android.archives.length).isEqualTo(21); }
|
ResolutionScope { public boolean isResolutionComplete() { return unresolved.isEmpty(); } ResolutionScope(@NotNull SoftNameDependency[] roots); ResolutionScope(); void addUnresolved(@NotNull SoftNameDependency softname); boolean isResolutionComplete(); @NotNull Collection<SoftNameDependency> getUnresolvedReferences(); @NotNull Collection<String> getUnresolvableReferences(); @NotNull Unresolvable getUnresolveableReason(@NotNull String softname); void recordResolved(@NotNull SoftNameDependency softname,
@NotNull ResolvedManifest resolved,
@NotNull List<HardNameDependency> transitiveDependencies); void recordUnresolvable(@NotNull SoftNameDependency softname); @NotNull ResolvedManifest getResolution(@NotNull String name); @NotNull Collection<String> getResolutions(); @NotNull Collection<Coordinate> getUnificationWinners(); @NotNull Collection<Coordinate> getUnificationLosers(); @NotNull
final public Map<Coordinate, List<Coordinate>> forwardEdges; @NotNull
final public Map<Coordinate, List<Coordinate>> backwardEdges; }
|
@Test public void testNoRoots() throws IOException { ResolutionScope scope = new ResolutionScope(new SoftNameDependency[0]); assertThat(scope.isResolutionComplete()).isTrue(); }
|
PathMapping { public static PathMapping[] parse(@NotNull String text) { List<PathMapping> result = new ArrayList<>(); String[] mappings = text.split("\\|"); for (String mapping : mappings) { String[] fromTo = mapping.split("->"); if (fromTo.length == 1) { if (fromTo[0].endsWith("/...")) { File baseFolder = new File(fromTo[0].substring(0, fromTo[0].length() - 4)); for (File from : FileUtils.listFileTree(baseFolder)) { File to = new File(from.getPath().substring(baseFolder.getPath().length() + 1)); result.add(new PathMapping(from, to)); } } else { result.add(new PathMapping( new File(fromTo[0].trim()), new File(new File(fromTo[0].trim()).getName()))); } } else if (fromTo.length == 2) { result.add(new PathMapping( new File(fromTo[0].trim()), new File( fromTo[1].trim()))); } } return result.toArray(new PathMapping[result.size()]); } private PathMapping(File from, File to); static PathMapping[] parse(@NotNull String text); final public File from; final public File to; }
|
@Test public void simple() { PathMapping mappings[] = PathMapping.parse("myfile.h"); assertThat(mappings).hasLength(1); assertThat(mappings[0].from).isEqualTo(new File("myfile.h")); assertThat(mappings[0].to).isEqualTo(new File("myfile.h")); }
@Test public void simplePair() { PathMapping mappings[] = PathMapping.parse( "../third_party/tinydir/tinydir.h " + "-> tinydir/tinydir.h"); assertThat(mappings).hasLength(1); assertThat(mappings[0].from.getName()).isEqualTo("tinydir.h"); assertThat(mappings[0].from.getParentFile().getName()).isEqualTo("tinydir"); assertThat(mappings[0].to.getName()).isEqualTo("tinydir.h"); assertThat(mappings[0].to.getParentFile().getName()).isEqualTo("tinydir"); assertThat(mappings[0].to.isAbsolute()).isEqualTo(false); }
@Test public void expandSimple() { PathMapping mappings[] = PathMapping.parse("../third_party/vectorial/include/..."); assertThat(mappings).hasLength(21); }
@Test public void doubleRecursive() { PathMapping mappings[] = PathMapping.parse( "../third_party/tinydir/...|../third_party/stb/..."); }
|
Fullfill { @NotNull public static List<File> multiple( GeneratorEnvironment environment, @NotNull File templates[], File outputFolder, @NotNull File sourceFolder, String version) throws IOException, NoSuchAlgorithmException { List<File> result = new ArrayList<>(); CDepManifestYml manifests[] = new CDepManifestYml[templates.length]; File layout = new File(outputFolder, "layout"); if (!layout.isDirectory()) { layout.mkdirs(); } File staging = new File(outputFolder, "staging"); if (!staging.isDirectory()) { staging.mkdirs(); } for (int i = 0; i < manifests.length; ++i) { String body = FileUtils.readAllText(templates[i]); manifests[i] = CDepManifestYmlUtils.convertStringToManifest(body); } SubstituteStringsRewriter substitutor = new SubstituteStringsRewriter() .replace("${source}", sourceFolder.getAbsolutePath()) .replace("${layout}", layout.getAbsolutePath()) .replace("${version}", version); for (int i = 0; i < manifests.length; ++i) { manifests[i] = substitutor.visitCDepManifestYml(manifests[i]); } Resolver resolver = new Resolver(environment); ResolutionScope scope = new ResolutionScope(); infoln("Fullfilling %s manifests", templates.length); for (int i = 0; i < manifests.length; ++i) { Coordinate coordinate = manifests[i].coordinate; FillMissingFieldsBasedOnFilepathRewriter filler = new FillMissingFieldsBasedOnFilepathRewriter(); infoln(" guessing archive details from path names in %s", coordinate); manifests[i] = filler.visitCDepManifestYml(manifests[i]); if (errorsInScope() > 0) { return result; } ZipFilesRewriter zipper = new ZipFilesRewriter(layout, staging); infoln(" zipping files referenced in %s", coordinate); manifests[i] = zipper.visitCDepManifestYml(manifests[i]); result.addAll(zipper.getZips()); if (errorsInScope() > 0) { return result; } FileHashAndSizeRewriter hasher = new FileHashAndSizeRewriter(layout); infoln(" computing hashes and file sizes of archives in %s", coordinate); manifests[i] = hasher.visitCDepManifestYml(manifests[i]); if (errorsInScope() > 0) { return result; } DependencyHashRewriter dependencyHasher = new DependencyHashRewriter(environment); infoln(" hashing dependencies in %s", coordinate); manifests[i] = dependencyHasher.visitCDepManifestYml(manifests[i]); if (errorsInScope() > 0) { return result; } File output = new File(layout, templates[i].getName()); infoln(" writing manifest file %s", new File(".") .toURI().relativize(output.toURI()).getPath()); String body = CDepManifestYmlUtils.convertManifestToString(manifests[i]); FileUtils.writeTextToFile(output, body); result.add(output); if (errorsInScope() > 0) { return result; } infoln(" checking sanity of result %s", coordinate); CDepManifestYml readFromDisk = CDepManifestYmlUtils.convertStringToManifest( FileUtils.readAllText(output)); CDepManifestYmlEquality.areDeeplyIdentical(manifests[i], readFromDisk); if (errorsInScope() > 0) { return result; } CDepManifestYmlUtils.checkManifestSanity(manifests[i]); SoftNameDependency softname = new SoftNameDependency(coordinate.toString()); scope.addUnresolved(softname); scope.recordResolved( softname, new ResolvedManifest(output.toURI().toURL(), manifests[i]), CDepManifestYmlUtils.getTransitiveDependencies(manifests[i])); if (errorsInScope() > 0) { return result; } } infoln(" checking consistency of all manifests"); resolver.resolveAll(scope); BuildFindModuleFunctionTable table = new BuildFindModuleFunctionTable(); GeneratorEnvironmentUtils.addAllResolvedToTable(table, scope); table.build(); if (errorsInScope() > 0) { return result; } return result; } @NotNull static List<File> multiple(
GeneratorEnvironment environment,
@NotNull File templates[],
File outputFolder,
@NotNull File sourceFolder,
String version); }
|
@Test public void testBasicSTB() throws Exception { File templates[] = templates( new File("../third_party/stb/cdep/")); File output = new File(".test-files/testBasicSTB").getAbsoluteFile(); Fullfill.multiple(environment, templates, output, new File("../third_party/stb"), "1.2.3"); }
@Test public void testBasicTinyDir() throws Exception { File templates[] = templates( new File("../third_party/tinydir/")); File output = new File(".test-files/testBasicTinyDir").getAbsoluteFile(); List<File> result = Fullfill.multiple(environment, templates, output, new File("../third_party/tinydir"), "1.2.3"); assertThat(result).hasSize(2); }
@Test public void testBasicVectorial() throws Exception { File templates[] = templates( new File("../third_party/vectorial/cdep")); File output = new File(".test-files/testBasicVectorial").getAbsoluteFile(); List<File> result = Fullfill.multiple(environment, templates, output, new File("../third_party/vectorial"), "1.2.3"); assertThat(result).hasSize(2); }
@Test public void testBasicMathFu() throws Exception { File templates[] = templates( new File("../third_party/mathfu/cdep")); File output = new File(".test-files/testBasicMathFu").getAbsoluteFile(); List<File> result = Fullfill.multiple(environment, templates, output, new File("../third_party/mathfu"), "1.2.3"); assertThat(result).hasSize(2); File manifestFile = new File(output, "layout"); manifestFile = new File(manifestFile, "cdep-manifest.yml"); CDepManifestYml manifest = CDepManifestYmlUtils.convertStringToManifest(FileUtils.readAllText(manifestFile)); assertThat(manifest.dependencies[0].sha256).isNotNull(); assertThat(manifest.dependencies[0].sha256).isNotEmpty(); }
@Test public void testMiniFirebase() throws Exception { File templates[] = new File[]{ new File("../third_party/mini-firebase/cdep-manifest-app.yml"), new File("../third_party/mini-firebase/cdep-manifest-database.yml") }; File output = new File(".test-files/testMiniFirebase").getAbsoluteFile(); output.delete(); List<File> result = Fullfill.multiple(environment, templates, output, new File("../third_party/mini-firebase/firebase_cpp_sdk"), "1.2.3"); File manifestFile = new File(output, "layout"); manifestFile = new File(manifestFile, "cdep-manifest-database.yml"); CDepManifestYml manifest = CDepManifestYmlUtils.convertStringToManifest(FileUtils.readAllText(manifestFile)); assertThat(manifest.dependencies[0].sha256).isNotNull(); assertThat(manifest.dependencies[0].sha256).isNotEmpty(); assertThat(manifest.android.archives[0].file.contains("+")).isFalse(); }
@Test public void testSqlite() throws Exception { ResolvedManifests.TestManifest manifest = ResolvedManifests.sqlite(); File outputFolder = new File(".test-files/TestFullfill/testSqlite").getAbsoluteFile(); outputFolder.delete(); outputFolder.mkdirs(); File manifestFile = new File(outputFolder, "cdep-manifest.yml"); FileUtils.writeTextToFile(manifestFile, manifest.body); Fullfill.multiple( environment, new File[]{manifestFile}, new File(outputFolder, "output"), new File(outputFolder, "source"), "1.2.3"); }
@Test public void testRe2() throws Exception { ResolvedManifests.TestManifest manifest = ResolvedManifests.sqlite(); File outputFolder = new File(".test-files/TestFullfill/re2").getAbsoluteFile(); outputFolder.delete(); outputFolder.mkdirs(); File manifestFile = new File(outputFolder, "cdep-manifest.yml"); FileUtils.writeTextToFile(manifestFile, manifest.body); List<File> results = Fullfill.multiple( environment, new File[]{manifestFile}, new File(outputFolder, "output"), new File(outputFolder, "source"), "1.2.3"); CDepManifestYml result = CDepManifestYmlUtils.convertStringToManifest(FileUtils.readAllText(results.get(0))); assertThat(result).hasCoordinate(new Coordinate("com.github.jomof", "sqlite", new Version("0.0.0"))); assertThat(result).hasArchiveNamed("sqlite-android-gnustl-platform-21.zip"); }
@Test public void testAllResolvedManifests() throws Exception { Map<String, String> expected = new HashMap<>(); expected.put("sqliteLinuxMultiple", "Package 'com.github.jomof:sqlite:0.0.0' has multiple linux archives. Only one is allowed."); expected.put("archiveMissingSize", "Archive com.github.jomof:vectorial:0.0.0 is missing size or it is zero"); expected.put("indistinguishableAndroidArchives", "Android archive com.github.jomof:firebase/app:0.0.0 file archive2.zip is indistinguishable at build time from " + "archive1.zip given the information in the manifest"); expected.put("archiveMissingSha256", "Could not hash file bob.zip because it didn't exist"); expected.put("archiveMissingFile", "Package 'com.github.jomof:vectorial:0.0.0' does not contain any files"); expected.put("admob", "Archive com.github.jomof:firebase/admob:2.1.3-rev8 is missing include"); expected.put("fuzz1", "Dependency had no compile field"); boolean unexpectedFailure = false; for (ResolvedManifests.NamedManifest manifest : ResolvedManifests.all()) { File outputFolder = new File(".test-files/TestFullfill/testAllResolvedManifests/" + manifest.name).getAbsoluteFile(); outputFolder.delete(); outputFolder.mkdirs(); String key = manifest.name; String expectedFailure = expected.get(key); File manifestFile = new File(outputFolder, "cdep-manifest.yml"); FileUtils.writeTextToFile(manifestFile, manifest.body); try { Fullfill.multiple( environment, new File[]{manifestFile}, new File(outputFolder, "output"), new File(outputFolder, "source"), "1.2.3"); if (expectedFailure != null) { require(false, "Expected failure in %s: '%s'", manifest.name, expectedFailure); } } catch (RuntimeException e) { if (!(e.getClass().equals(RuntimeException.class))) { throw e; } if (e.getMessage() == null) { throw e; } if (e.getMessage().contains("Could not zip file")) { continue; } if (!e.getMessage().equals(expectedFailure)) { System.out.printf("expected.put(\"%s\", \"%s\");\n", key, e.getMessage()); unexpectedFailure = true; } } } if (unexpectedFailure) { throw new RuntimeException("Unexpected failures. See console."); } }
@Test public void fuzzTest() { QuickCheck.forAll(new CDepManifestYmlGenerator(), new AbstractCharacteristic<CDepManifestYml>() { @Override protected void doSpecify(CDepManifestYml any) throws Throwable { File outputFolder = new File(".test-files/TestFullfill/fuzzTest/" + "fuzzTest").getAbsoluteFile(); outputFolder.delete(); outputFolder.mkdirs(); File manifestFile = new File(outputFolder, "cdep-manifest.yml"); String body = CDepManifestYmlUtils.convertManifestToString(any); FileUtils.writeTextToFile(manifestFile, body); ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); PrintStream originalOut = null; PrintStream originalErr = null; try { Invariant.pushScope(); originalOut = IO.setOut(ps); originalErr = IO.setErr(ps); Fullfill.multiple( environment, new File[]{manifestFile}, new File(outputFolder, "output"), new File(outputFolder, "source"), "1.2.3"); } catch(Throwable e) { System.out.print(body); throw e; } finally { IO.setOut(originalOut); IO.setErr(originalErr); Invariant.popScope(); } } }); }
|
RewritingVisitor { @NotNull public Expression visit(@NotNull Expression expr) { Expression prior = identity.get(expr); if (prior != null) { return prior; } identity.put(expr, visitNoIdentity(expr)); return visit(expr); } @NotNull Expression visit(@NotNull Expression expr); @NotNull Expression visitFunctionTableExpression(@NotNull FunctionTableExpression expr); }
|
@Test public void testNullInclude() throws Exception { new RewritingVisitor().visit(archive(new URL("https: null, new String[0], new Expression[0], new CxxLanguageFeatures[0])); }
@Test public void testAllResolvedManifests() throws Exception { Map<String, String> expected = new HashMap<>(); expected.put("admob", "Reference com.github.jomof:firebase/app:2.1.3-rev8 was not found"); expected.put("fuzz1", "Could not parse main manifest coordinate []"); for (ResolvedManifests.NamedManifest manifest : ResolvedManifests.all()) { BuildFindModuleFunctionTable builder = new BuildFindModuleFunctionTable(); builder.addManifest(manifest.resolved); String expectedFailure = expected.get(manifest.name); try { new RewritingVisitor().visit(builder.build()); if (expectedFailure != null) { fail("Expected failure"); } } catch (RuntimeException e) { if (expectedFailure == null) { throw e; } assertThat(e.getMessage()).contains(expectedFailure); } } }
@Test public void testNullInclude() throws Exception { new RewritingVisitor().visit(archive(new URL("https: null, new String[0], new Expression[0], null, new CxxLanguageFeatures[0])); }
@Test public void testAllResolvedManifests() throws Exception { Map<String, String> expected = new LinkedHashMap<>(); expected.put("admob", "Reference com.github.jomof:firebase/app:2.1.3-rev8 was not found"); expected.put("fuzz1", "Could not parse main manifest coordinate []"); for (ResolvedManifests.NamedManifest manifest : ResolvedManifests.all()) { BuildFindModuleFunctionTable builder = new BuildFindModuleFunctionTable(); if(Objects.equals(manifest.name, "curlAndroid")) { builder.addManifest(ResolvedManifests.zlibAndroid().manifest); builder.addManifest(ResolvedManifests.boringSSLAndroid().manifest); } builder.addManifest(manifest.resolved); String expectedFailure = expected.get(manifest.name); try { new RewritingVisitor().visit(builder.build()); if (expectedFailure != null) { fail("Expected failure"); } } catch (RuntimeException e) { if (expectedFailure == null) { throw e; } assertThat(e.getMessage()).contains(expectedFailure); } } }
|
EnvironmentUtils { @NotNull public static File getPackageLevelIncludeFolder(@NotNull GeneratorEnvironment environment, @NotNull String coordinate) throws IOException, NoSuchAlgorithmException, URISyntaxException { ResolvedManifest resolved = resolveManifest(environment, coordinate); return getPackageLevelIncludeFolder(environment, coordinate, resolved); } @NotNull static File getPackageLevelIncludeFolder(@NotNull GeneratorEnvironment environment, @NotNull String coordinate); }
|
@Test public void testAllResolvedManifests() throws Exception { Map<String, String> expected = new HashMap<>(); expected.put("sqliteiOS", "'sqliteiOS' does not have archive"); expected.put("sqliteAndroid", "'sqliteAndroid' does not have archive"); expected.put("sqliteLinuxMultiple", "'sqliteLinuxMultiple' does not have archive"); expected.put("sqliteLinux", "'sqliteLinux' does not have archive"); expected.put("sqlite", "'sqlite' does not have archive"); expected.put("archiveMissingFile", "'archiveMissingFile' does not have archive.include.file"); expected.put("singleABI", "'singleABI' does not have archive"); expected.put("singleABISqlite", "'singleABISqlite' does not have archive"); expected.put("archiveMissingSha256", "'archiveMissingSha256' does not have archive.include"); expected.put("admob", "'admob' does not have archive.include"); expected.put("templateWithNullArchives", "'templateWithNullArchives' does not have " + "archive.include"); expected.put("templateWithOnlyFile", "'templateWithOnlyFile' does not have archive.include"); expected.put("fuzz1", "'fuzz1' does not have archive"); expected.put("fuzz2", "Illegal character in path at index 2: ,S`&|[x0q;J.$9D#P6FUDG>+&69ZXG"); boolean unexpectedFailure = false; for (ResolvedManifests.NamedManifest manifest : ResolvedManifests.all()) { String key = manifest.name; String expectedFailure = expected.get(key); try { EnvironmentUtils.getPackageLevelIncludeFolder(environment, key, manifest.resolved); if (expectedFailure != null) { fail("Expected failure"); } } catch (RuntimeException e) { if (e.getMessage() == null) { throw e; } if (!e.getMessage().equals(expectedFailure)) { e.printStackTrace(); System.out.printf("expected.put(\"%s\", \"%s\");\n", key, e.getMessage()); unexpectedFailure = true; } } } if (unexpectedFailure) { throw new RuntimeException("Unexpected failures. See console."); } }
@Test public void testAllResolvedManifests() throws Exception { Map<String, String> expected = new LinkedHashMap<>(); expected.put("sqliteiOS", "'sqliteiOS' does not have archive"); expected.put("sqliteAndroid", "'sqliteAndroid' does not have archive"); expected.put("sqliteLinuxMultiple", "'sqliteLinuxMultiple' does not have archive"); expected.put("sqliteLinux", "'sqliteLinux' does not have archive"); expected.put("sqlite", "'sqlite' does not have archive"); expected.put("archiveMissingFile", "'archiveMissingFile' does not have archive.include.file"); expected.put("singleABI", "'singleABI' does not have archive"); expected.put("singleABISqlite", "'singleABISqlite' does not have archive"); expected.put("archiveMissingSha256", "'archiveMissingSha256' does not have archive.include"); expected.put("admob", "'admob' does not have archive.include"); expected.put("templateWithNullArchives", "'templateWithNullArchives' does not have " + "archive.include"); expected.put("templateWithOnlyFile", "'templateWithOnlyFile' does not have archive.include"); expected.put("fuzz1", "'fuzz1' does not have archive"); expected.put("fuzz2", "Illegal character in path at index 2: ,S`&|[x0q;J.$9D#P6FUDG>+&69ZXG"); boolean unexpectedFailure = false; for (ResolvedManifests.NamedManifest manifest : ResolvedManifests.all()) { String key = manifest.name; String expectedFailure = expected.get(key); try { EnvironmentUtils.getPackageLevelIncludeFolder(environment, key, manifest.resolved); if (expectedFailure != null) { fail("Expected failure"); } } catch (RuntimeException e) { if (e.getMessage() == null) { throw e; } if (!e.getMessage().equals(expectedFailure)) { e.printStackTrace(); System.out.printf("expected.put(\"%s\", \"%s\");\n", key, e.getMessage()); unexpectedFailure = true; } } } if (unexpectedFailure) { throw new RuntimeException("Unexpected failures. See console."); } }
|
VersionUtils { static String checkVersion(@NotNull Version version) { String[] pointSections = version.value.split("\\."); String EXPECTED = "major.minor.point[-tweak]"; if (pointSections.length == 1) { return String.format("expected %s but there were no dots", EXPECTED); } if (pointSections.length == 2) { return String.format("expected %s but there was only one dot", EXPECTED); } if (pointSections.length > 3) { return String.format("expected %s but there were %s dots", EXPECTED, pointSections.length - 1); } if (pointSections.length == 0) { return String.format("expected %s but there was only a dot", EXPECTED); } if (!StringUtils.isNumeric(pointSections[0])) { return String.format("expected %s but major version '%s' wasn't a number", EXPECTED, pointSections[0]); } if (!StringUtils.isNumeric(pointSections[1])) { return String.format("expected %s but minor version '%s' wasn't a number", EXPECTED, pointSections[1]); } if (pointSections[2].contains("-")) { int dashPosition = pointSections[2].indexOf('-'); String pointVersion = pointSections[2].substring(0, dashPosition); if (!StringUtils.isNumeric(pointVersion)) { return String.format("expected %s but point version '%s' wasn't a number", EXPECTED, pointVersion); } } else { if (!StringUtils.isNumeric(pointSections[2])) { return String.format("expected %s but point version '%s' wasn't a number", EXPECTED, pointSections[2]); } } return null; } final static Comparator<Version> ASCENDING_COMPARATOR; final static Comparator<Version> DESCENDING_COMPARATOR; }
|
@Test public void simple() { assertThat(VersionUtils.checkVersion(version("1.2.3"))).isNull(); }
@Test public void tweak() { assertThat(VersionUtils.checkVersion(version("1.2.3-rev9"))).isNull(); }
@Test public void majorNotNumber() { assertThat(VersionUtils.checkVersion(version("x.2.3"))) .isEqualTo("expected major.minor.point[-tweak] but major version 'x' wasn't a number"); }
@Test public void minorNotNumber() { assertThat(VersionUtils.checkVersion(version("1.y.3"))) .isEqualTo("expected major.minor.point[-tweak] but minor version 'y' wasn't a number"); }
@Test public void pointNotNumber() { assertThat(VersionUtils.checkVersion(version("1.2.z"))) .isEqualTo("expected major.minor.point[-tweak] but point version 'z' wasn't a number"); }
@Test public void pointWithTweakNotNumber() { assertThat(VersionUtils.checkVersion(version("1.2.1z-rev8"))) .isEqualTo("expected major.minor.point[-tweak] but point version '1z' wasn't a number"); }
@Test public void noDots() { assertThat(VersionUtils.checkVersion(version("1"))) .isEqualTo("expected major.minor.point[-tweak] but there were no dots"); }
@Test public void oneDot() { assertThat(VersionUtils.checkVersion(version("1.2"))) .isEqualTo("expected major.minor.point[-tweak] but there was only one dot"); }
@Test public void fourDots() { assertThat(VersionUtils.checkVersion(version("1.2.3.4"))) .isEqualTo("expected major.minor.point[-tweak] but there were 3 dots"); }
@Test public void fuzzTest() { for (int i = 0; i < 10; ++i) QuickCheck.forAll(new VersionGenerator(), new AbstractCharacteristic<Version>() { @Override protected void doSpecify(Version any) throws Throwable { VersionUtils.checkVersion(any); } }); }
|
CommandLineUtils { @NotNull public static String getLibraryNameFromLibraryFilename(@NotNull File library) { String name = library.getName(); if (failIf(!name.startsWith("lib"), "Library name from manifest wasn't in the form libXXXX.a")) { return name; } if (failIf(!name.endsWith(".a"), "Library name from manifest wasn't in the form libXXXX.a")) { return name; } name = name.substring(3, name.length() - 2); return name; } @NotNull static String getLibraryNameFromLibraryFilename(@NotNull File library); }
|
@Test public void testBasic() { assertThat(CommandLineUtils.getLibraryNameFromLibraryFilename( new File("/path/to/libmyfile.a"))).isEqualTo("myfile"); }
|
StringUtils { public static boolean isNumeric(@NotNull String str) { for (char c : str.toCharArray()) { if (!Character.isDigit(c)) { return false; } } return true; } static boolean isNumeric(@NotNull String str); static String joinOn(String delimiter, @NotNull Object array[]); static String joinOn(String delimiter, @NotNull Collection<String> strings); static String joinOn(String delimiter, @NotNull String ... strings); static String joinOnSkipNullOrEmpty(String delimiter, @NotNull String ... strings); @NotNull static String nullToEmpty(@Nullable String value); @NotNull static String[] singletonArrayOrEmpty(@Nullable String value); @NotNull static String whitespace(int indent); @NotNull static String safeFormat(@NotNull String format, Object ... args); static boolean containsAny(@NotNull String value, @NotNull String chars); @NotNull static String firstAvailable(@NotNull String value, int n); static boolean startsWithAny(@NotNull String value, @NotNull String chars); }
|
@Test public void isNumeric() throws Exception { assertThat(StringUtils.isNumeric("x")).isFalse(); assertThat(StringUtils.isNumeric("1")).isTrue(); }
@Test public void checkIsNumber() { assertThat(StringUtils.isNumeric("1")).isTrue(); }
@Test public void checkIsNotNumber() { assertThat(StringUtils.isNumeric("x")).isFalse(); }
|
StringUtils { public static String joinOn(String delimiter, @NotNull Object array[]) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < array.length; ++i) { if (i != 0) { sb.append(delimiter); } sb.append(array[i]); } return sb.toString(); } static boolean isNumeric(@NotNull String str); static String joinOn(String delimiter, @NotNull Object array[]); static String joinOn(String delimiter, @NotNull Collection<String> strings); static String joinOn(String delimiter, @NotNull String ... strings); static String joinOnSkipNullOrEmpty(String delimiter, @NotNull String ... strings); @NotNull static String nullToEmpty(@Nullable String value); @NotNull static String[] singletonArrayOrEmpty(@Nullable String value); @NotNull static String whitespace(int indent); @NotNull static String safeFormat(@NotNull String format, Object ... args); static boolean containsAny(@NotNull String value, @NotNull String chars); @NotNull static String firstAvailable(@NotNull String value, int n); static boolean startsWithAny(@NotNull String value, @NotNull String chars); }
|
@Test public void joinOn() throws Exception { assertThat(StringUtils.joinOn("+", "1", "2", "3")).isEqualTo("1+2+3"); }
@Test public void joinOn1() throws Exception { assertThat(StringUtils.joinOn("+", new Integer[]{1, 2, 3})).isEqualTo("1+2+3"); }
@Test public void joinOn2() throws Exception { List<String> list = new ArrayList<>(); list.add("1"); list.add("3"); assertThat(StringUtils.joinOn("+", list)).isEqualTo("1+3"); }
|
StringUtils { public static String joinOnSkipNullOrEmpty(String delimiter, @NotNull String ... strings) { StringBuilder sb = new StringBuilder(); int i = 0; for (String string : strings) { if (string == null || string.isEmpty()) { continue; } if (i != 0) { sb.append(delimiter); } sb.append(string); ++i; } return sb.toString(); } static boolean isNumeric(@NotNull String str); static String joinOn(String delimiter, @NotNull Object array[]); static String joinOn(String delimiter, @NotNull Collection<String> strings); static String joinOn(String delimiter, @NotNull String ... strings); static String joinOnSkipNullOrEmpty(String delimiter, @NotNull String ... strings); @NotNull static String nullToEmpty(@Nullable String value); @NotNull static String[] singletonArrayOrEmpty(@Nullable String value); @NotNull static String whitespace(int indent); @NotNull static String safeFormat(@NotNull String format, Object ... args); static boolean containsAny(@NotNull String value, @NotNull String chars); @NotNull static String firstAvailable(@NotNull String value, int n); static boolean startsWithAny(@NotNull String value, @NotNull String chars); }
|
@Test public void joinOnSkipNull() throws Exception { assertThat(StringUtils.joinOnSkipNullOrEmpty("+", "1", null, "3")).isEqualTo("1+3"); }
|
Invariant { public static void require(boolean check, @NotNull String format, Object... parameters) { if (check) { return; } report(new RuntimeException(safeFormat(format, parameters))); } @SuppressWarnings("Convert2Diamond") static void pushScope(); static void pushScope(boolean showOutput); static List<RuntimeException> popScope(); static int errorsInScope(); static void fail(@NotNull String format); static void fail(@NotNull String format, Object... parameters); static void require(boolean check, @NotNull String format, Object... parameters); static boolean failIf(boolean check, @NotNull String format, Object... parameters); static void require(boolean check); }
|
@Test public void testRequireFalse() { try { require(false); throw new RuntimeException("Expected an exception"); } catch (RuntimeException e) { assertThat(e).hasMessage("Invariant violation"); } }
@Test public void testRequireTrue() { require(true); }
|
CDepManifestYmlUtils { public static void checkManifestSanity(@NotNull CDepManifestYml cdepManifestYml) { new Checker().visit(cdepManifestYml, CDepManifestYml.class); } @NotNull static String convertManifestToString(@NotNull CDepManifestYml manifest); @NotNull static CDepManifestYml convertStringToManifest(@NotNull String content); static void checkManifestSanity(@NotNull CDepManifestYml cdepManifestYml); @NotNull static List<HardNameDependency> getTransitiveDependencies(@NotNull CDepManifestYml cdepManifestYml); }
|
@Test public void testAllResolvedManifests() throws Exception { Map<String, String> expected = new HashMap<>(); expected.put("admob", "Archive com.github.jomof:firebase/admob:2.1.3-rev8 is missing include"); expected.put("archiveMissingSha256", "Archive com.github.jomof:vectorial:0.0.0 is missing sha256"); expected.put("sqliteLinuxMultiple", "Package 'com.github.jomof:sqlite:0.0.0' has multiple linux archives. Only one is allowed."); expected.put("archiveMissingSize", "Archive com.github.jomof:vectorial:0.0.0 is missing size or it is zero"); expected.put("archiveMissingFile", "Archive com.github.jomof:vectorial:0.0.0 is missing file"); expected.put("templateWithNullArchives", "Package 'com.github.jomof:firebase/app:${version}' " + "has malformed version, expected major.minor.point[-tweak] but there were no dots"); expected.put("templateWithOnlyFile", "Package 'com.github.jomof:firebase/app:${version}' has " + "malformed version, expected major.minor.point[-tweak] but there were no dots"); expected.put("indistinguishableAndroidArchives", "Android archive com.github.jomof:firebase/app:0.0.0 file archive2.zip is indistinguishable at build time from archive1.zip given the information in the manifest"); expected.put("fuzz1", "Manifest was missing coordinate"); expected.put("fuzz2", "Manifest was missing coordinate"); boolean unexpectedFailure = false; for (ResolvedManifests.NamedManifest manifest : ResolvedManifests.all()) { String key = manifest.name; String expectedFailure = expected.get(key); try { CDepManifestYmlUtils.checkManifestSanity(manifest.resolved.cdepManifestYml); if (expectedFailure != null) { fail("Expected failure"); } } catch (RuntimeException e) { if (!e.getMessage().equals(expectedFailure)) { System.out.printf("expected.put(\"%s\", \"%s\");\n", key, e.getMessage()); unexpectedFailure = true; } } } if (unexpectedFailure) { throw new RuntimeException("Unexpected failures. See console."); } }
@Test public void testTwoWayMergeSanity() throws Exception { Map<String, String> expected = new HashMap<>(); expected.put("archiveMissingFile-archiveMissingFile", "Archive com.github.jomof:vectorial:0.0.0 is missing file"); expected.put("archiveMissingSha256-archiveMissingSha256", "Archive com.github.jomof:vectorial:0.0.0 is missing sha256"); expected.put("sqliteLinuxMultiple-sqliteLinuxMultiple", "Package 'com.github.jomof:sqlite:0.0.0' has multiple linux archives. Only one is allowed."); expected.put("sqliteLinuxMultiple-sqlite", "Package 'com.github.jomof:sqlite:0.0.0' has multiple linux archives. Only one is allowed."); expected.put("sqliteLinuxMultiple-singleABI", "Package 'com.github.jomof:sqlite:0.0.0' has multiple linux archives. Only one is allowed."); expected.put("sqliteLinuxMultiple-sqliteLinux", "Package 'com.github.jomof:sqlite:0.0.0' has multiple linux archives. Only one is allowed."); expected.put("archiveMissingSize-archiveMissingSize", "Archive com.github.jomof:vectorial:0.0.0 is missing size or it is zero"); expected.put("admob-admob", "Archive com.github.jomof:firebase/admob:2.1.3-rev8 is missing include"); expected.put("sqlite-sqliteLinuxMultiple", "Package 'com.github.jomof:sqlite:0.0.0' has multiple linux archives. Only one is allowed."); expected.put("singleABISqlite-singleABISqlite", "Package 'com.github.jomof:sqlite:3.16.2-rev45' contains multiple references to the same archive file " + "'sqlite-android-cxx-platform-12-armeabi.zip'"); expected.put("singleABI-sqliteLinuxMultiple", "Package 'com.github.jomof:sqlite:0.0.0' has multiple linux archives. Only one is allowed."); expected.put("singleABI-singleABI", "Package 'com.github.jomof:sqlite:0.0.0' contains multiple references to the same archive file " + "'sqlite-android-cxx-platform-12-armeabi.zip'"); expected.put("sqliteLinux-sqliteLinuxMultiple", "Package 'com.github.jomof:sqlite:0.0.0' has multiple linux archives. Only one is allowed."); expected.put("sqliteLinux-sqliteLinux", "Package 'com.github.jomof:sqlite:0.0.0' has multiple linux archives. Only one is allowed."); expected.put("sqliteiOS-sqliteiOS", "Package 'com.github.jomof:sqlite:3.16.2-rev33' contains multiple references to the same archive file " + "'sqlite-ios-platform-iPhoneOS-architecture-armv7-sdk-9.3.zip'"); expected.put("templateWithNullArchives-templateWithNullArchives", "Package 'com.github.jomof:firebase/" + "app:${version}' has malformed version, expected major.minor.point[-tweak] but there were no dots"); expected.put("templateWithNullArchives-templateWithOnlyFile", "Package 'com.github.jomof:" + "firebase/app:${version}' has malformed version, expected major.minor.point[-tweak] but there were no dots"); expected.put("templateWithOnlyFile-templateWithNullArchives", "Package 'com.github.jomof:firebase/" + "app:${version}' has malformed version, expected major.minor.point[-tweak] but there were no dots"); expected.put("templateWithOnlyFile-templateWithOnlyFile", "Package 'com.github.jomof:firebase/" + "app:${version}' has malformed version, expected major.minor.point[-tweak] but there were no dots"); expected.put("sqlite-sqlite", "Android archive com.github.jomof:sqlite:0.0.0 file sqlite-android-cxx-platform-12.zip is indistinguishable at build time from sqlite-android-cxx-platform-12.zip given the information in the manifest"); expected.put("sqlite-singleABI", "Android archive com.github.jomof:sqlite:0.0.0 file sqlite-android-cxx-platform-12-armeabi.zip is indistinguishable at build time from sqlite-android-cxx-platform-12.zip given the information in the manifest"); expected.put("sqliteAndroid-sqliteAndroid", "Android archive com.github.jomof:sqlite:3.16.2-rev33 file sqlite-android-cxx-platform-12.zip is indistinguishable at build time from sqlite-android-cxx-platform-12.zip given the information in the manifest"); expected.put("singleABI-sqlite", "Android archive com.github.jomof:sqlite:0.0.0 file sqlite-android-cxx-platform-12.zip is indistinguishable at build time from sqlite-android-cxx-platform-12-armeabi.zip given the information in the manifest"); expected.put("singleABI-singleABI", "Android archive com.github.jomof:sqlite:0.0.0 file sqlite-android-cxx-platform-12-armeabi.zip is indistinguishable at build time from sqlite-android-cxx-platform-12-armeabi.zip given the information in the manifest"); expected.put("indistinguishableAndroidArchives-indistinguishableAndroidArchives", "Android archive com.github.jomof:firebase/app:0.0.0 file archive2.zip is indistinguishable at build time from archive1.zip given the information in the manifest"); expected.put("singleABISqlite-singleABISqlite", "Android archive com.github.jomof:sqlite:3.16.2-rev45 file sqlite-android-cxx-platform-12-armeabi.zip is indistinguishable at build time from sqlite-android-cxx-platform-12-armeabi.zip given the information in the manifest"); expected.put("re2-re2", "Android archive com.github.jomof:re2:17.3.1-rev13 file re2-21-armeabi.zip is indistinguishable at build time from re2-21-armeabi.zip given the information in the manifest"); expected.put("fuzz1-fuzz1", "Manifest was missing coordinate"); expected.put("fuzz2-fuzz2", "Manifest was missing coordinate"); expected.put("openssl-openssl", "Android archive com.github.jomof:openssl:1.0.1-e-rev6 file openssl-android-stlport-21-armeabi.zip is indistinguishable at build time from openssl-android-stlport-21-armeabi.zip given the information in the manifest"); boolean somethingUnexpected = false; for (ResolvedManifests.NamedManifest manifest1 : ResolvedManifests.all()) { for (ResolvedManifests.NamedManifest manifest2 : ResolvedManifests.all()) { String key = manifest1.name + "-" + manifest2.name; String expectedFailure = expected.get(key); CDepManifestYml manifest; try { manifest = MergeCDepManifestYmls.merge(manifest1.resolved.cdepManifestYml, manifest2.resolved.cdepManifestYml); } catch (RuntimeException e) { continue; } try { CDepManifestYmlUtils.checkManifestSanity(manifest); if (expectedFailure != null) { TestCase.fail("Expected a failure."); } } catch (RuntimeException e) { String actual = e.getMessage(); if (!actual.equals(expectedFailure)) { System.out.printf("expected.put(\"%s\", \"%s\");\n", key, actual); somethingUnexpected = true; } } } } if (somethingUnexpected) { throw new RuntimeException("Saw unexpected results. See console."); } }
|
CDepManifestYmlUtils { @NotNull public static CDepManifestYml convertStringToManifest(@NotNull String content) { Yaml yaml = new Yaml(new Constructor(CDepManifestYml.class)); CDepManifestYml manifest; try { manifest = (CDepManifestYml) yaml.load( new ByteArrayInputStream(content.getBytes(StandardCharsets .UTF_8))); if (manifest != null) { manifest.sourceVersion = CDepManifestYmlVersion.vlatest; } } catch (YAMLException e) { try { manifest = V3Reader.convertStringToManifest(content); } catch (YAMLException e2) { require(false, e.toString()); return new CDepManifestYml( EMPTY_COORDINATE ); } } require(manifest != null, "Manifest was empty"); assert manifest != null; return new ConvertNullToDefaultRewriter().visitCDepManifestYml(manifest); } @NotNull static String convertManifestToString(@NotNull CDepManifestYml manifest); @NotNull static CDepManifestYml convertStringToManifest(@NotNull String content); static void checkManifestSanity(@NotNull CDepManifestYml cdepManifestYml); @NotNull static List<HardNameDependency> getTransitiveDependencies(@NotNull CDepManifestYml cdepManifestYml); }
|
@Test public void readPartial() throws IOException { CDepManifestYml partial = CDepManifestYmlUtils.convertStringToManifest( FileUtils.readAllText(new File("../third_party/stb/cdep/cdep-manifest-divide.yml"))); }
|
ObjectUtils { @NotNull public static <T> T nullToDefault(@Nullable T value, @NotNull T $default) { if (value == null) { return $default; } @NotNull static T nullToDefault(@Nullable T value, @NotNull T $default) {
if (value == null); }
|
@Test public void nullToDefault() throws Exception { assertThat(ObjectUtils.nullToDefault(null, "bob")).isEqualTo("bob"); assertThat(ObjectUtils.nullToDefault("tom", "bob")).isEqualTo("tom"); }
|
InterpretingVisitor { @Nullable public Object visit(@Nullable Expression expr) { if (expr == null) { return null; } if (expr.getClass().equals(FunctionTableExpression.class)) { return visitFunctionTableExpression((FunctionTableExpression) expr); } if (expr.getClass().equals(FindModuleExpression.class)) { return visitFindModuleExpression((FindModuleExpression) expr); } if (expr.getClass().equals(ParameterExpression.class)) { return visitParameterExpression((ParameterExpression) expr); } if (expr.getClass().equals(IfSwitchExpression.class)) { return visitIfSwitchExpression((IfSwitchExpression) expr); } if (expr.getClass().equals(ConstantExpression.class)) { return visitValueExpression((ConstantExpression) expr); } if (expr.getClass().equals(AssignmentExpression.class)) { return visitAssignmentExpression((AssignmentExpression) expr); } if (expr.getClass().equals(InvokeFunctionExpression.class)) { return visitInvokeFunctionExpression((InvokeFunctionExpression) expr); } if (expr.getClass().equals(ModuleExpression.class)) { return visitModuleExpression((ModuleExpression) expr); } if (expr.getClass().equals(AbortExpression.class)) { return visitAbortExpression((AbortExpression) expr); } if (expr.getClass().equals(ExampleExpression.class)) { return visitExampleExpression((ExampleExpression) expr); } if (expr.getClass().equals(ExternalFunctionExpression.class)) { return visitExternalFunctionExpression((ExternalFunctionExpression) expr); } if (expr.getClass().equals(ArrayExpression.class)) { return visitArrayExpression((ArrayExpression) expr); } if (expr.getClass().equals(AssignmentBlockExpression.class)) { return visitAssignmentBlockExpression((AssignmentBlockExpression) expr); } if (expr.getClass().equals(AssignmentReferenceExpression.class)) { return visitAssignmentReferenceExpression((AssignmentReferenceExpression) expr); } if (expr.getClass().equals(ModuleArchiveExpression.class)) { return visitModuleArchiveExpression((ModuleArchiveExpression) expr); } if (expr.getClass().equals(MultiStatementExpression.class)) { return visitMultiStatementExpression((MultiStatementExpression) expr); } if (expr.getClass().equals(NopExpression.class)) { return visitNopExpression((NopExpression) expr); } if (expr.getClass().equals(GlobalBuildEnvironmentExpression.class)) { return visitGlobalBuildEnvironmentExpression((GlobalBuildEnvironmentExpression) expr); } throw new RuntimeException("intr" + expr.getClass().toString()); } @Nullable Object visit(@Nullable Expression expr); }
|
@Test public void testNullInclude() throws Exception { new InterpretingVisitor().visit(archive(new URL("https: 192L, null, null, new String[0], new Expression[0], new CxxLanguageFeatures[0])); }
@Test public void testNullInclude() throws Exception { new InterpretingVisitor().visit(archive(new URL("https: 192L, null, null, new String[0], new Expression[0], null, new CxxLanguageFeatures[0])); }
|
ReadonlyVisitor { public void visit(@Nullable Expression expr) { if (expr == null) { return; } if (expr.getClass().equals(FunctionTableExpression.class)) { visitFunctionTableExpression((FunctionTableExpression) expr); return; } if (expr.getClass().equals(FindModuleExpression.class)) { visitFindModuleExpression((FindModuleExpression) expr); return; } if (expr.getClass().equals(ParameterExpression.class)) { visitParameterExpression((ParameterExpression) expr); return; } if (expr.getClass().equals(IfSwitchExpression.class)) { visitIfSwitchExpression((IfSwitchExpression) expr); return; } if (expr.getClass().equals(ConstantExpression.class)) { visitConstantExpression((ConstantExpression) expr); return; } if (expr.getClass().equals(AssignmentExpression.class)) { visitAssignmentExpression((AssignmentExpression) expr); return; } if (expr.getClass().equals(InvokeFunctionExpression.class)) { visitInvokeFunctionExpression((InvokeFunctionExpression) expr); return; } if (expr.getClass().equals(ModuleExpression.class)) { visitModuleExpression((ModuleExpression) expr); return; } if (expr.getClass().equals(AbortExpression.class)) { visitAbortExpression((AbortExpression) expr); return; } if (expr.getClass().equals(ExampleExpression.class)) { visitExampleExpression((ExampleExpression) expr); return; } if (expr.getClass().equals(ExternalFunctionExpression.class)) { visitExternalFunctionExpression((ExternalFunctionExpression) expr); return; } if (expr.getClass().equals(ArrayExpression.class)) { visitArrayExpression((ArrayExpression) expr); return; } if (expr.getClass().equals(AssignmentBlockExpression.class)) { visitAssignmentBlockExpression((AssignmentBlockExpression) expr); return; } if (expr.getClass().equals(AssignmentReferenceExpression.class)) { visitAssignmentReferenceExpression((AssignmentReferenceExpression) expr); return; } if (expr.getClass().equals(ModuleArchiveExpression.class)) { visitModuleArchiveExpression((ModuleArchiveExpression) expr); return; } if (expr.getClass().equals(MultiStatementExpression.class)) { visitMultiStatementExpression((MultiStatementExpression) expr); return; } if (expr.getClass().equals(NopExpression.class)) { visitNopExpression((NopExpression) expr); return; } if (expr.getClass().equals(GlobalBuildEnvironmentExpression.class)) { visitGlobalBuildEnvironmentExpression((GlobalBuildEnvironmentExpression) expr); return; } throw new RuntimeException("ro" + expr.getClass().toString()); } void visit(@Nullable Expression expr); }
|
@Test public void testNullInclude() throws Exception { new ReadonlyVisitor().visit(archive(new URL("https: null, null, new String[0], new Expression[0], new CxxLanguageFeatures[0])); }
@Test public void testAllResolvedManifests() throws Exception { Map<String, String> expected = new HashMap<>(); expected.put("admob", "Reference com.github.jomof:firebase/app:2.1.3-rev8 was not found"); expected.put("fuzz1", "Could not parse main manifest coordinate []"); for (ResolvedManifests.NamedManifest manifest : ResolvedManifests.all()) { BuildFindModuleFunctionTable builder = new BuildFindModuleFunctionTable(); builder.addManifest(manifest.resolved); String expectedFailure = expected.get(manifest.name); try { new ReadonlyVisitor().visit(builder.build()); if (expectedFailure != null) { fail("Expected failure"); } } catch (RuntimeException e) { if (expectedFailure == null || !e.getClass().equals(RuntimeException.class)) { throw e; } assertThat(e.getMessage()).contains(expectedFailure); } } }
@Test public void testNullInclude() throws Exception { new ReadonlyVisitor().visit(archive(new URL("https: null, null, new String[0], new Expression[0], null, new CxxLanguageFeatures[0])); }
@Test public void testAllResolvedManifests() throws Exception { Map<String, String> expected = new LinkedHashMap<>(); expected.put("admob", "Reference com.github.jomof:firebase/app:2.1.3-rev8 was not found"); expected.put("fuzz1", "Could not parse main manifest coordinate []"); for (ResolvedManifests.NamedManifest manifest : ResolvedManifests.all()) { BuildFindModuleFunctionTable builder = new BuildFindModuleFunctionTable(); if(Objects.equals(manifest.name, "curlAndroid")) { builder.addManifest(ResolvedManifests.zlibAndroid().manifest); builder.addManifest(ResolvedManifests.boringSSLAndroid().manifest); } builder.addManifest(manifest.resolved); String expectedFailure = expected.get(manifest.name); try { new ReadonlyVisitor().visit(builder.build()); if (expectedFailure != null) { fail("Expected failure"); } } catch (CDepRuntimeException e) { if (expectedFailure == null) { throw e; } assertThat(e.getMessage()).contains(expectedFailure); } } }
|
Bootstrap { public static void main(String[] args) throws Exception { new Bootstrap(getDownloadsFolder(), System.out).go(args); } Bootstrap(File downloadFolder, PrintStream out); static void main(String[] args); }
|
@Test public void testVersion() throws Exception { assertThat(main("--version")).contains(BuildInfo.PROJECT_VERSION); }
@Test public void testCDep() throws Exception { main("https: }
|
FakeService implements Repository { @NonNull @Override public Single<ServiceResponse> fetchResponse(@NonNull DateTime dateTime) { return Single.just(RESPONSE); } @Inject FakeService(); @NonNull @Override Single<ServiceResponse> fetchResponse(@NonNull DateTime dateTime); static final ServiceResponse RESPONSE; }
|
@Test public void should_return_list_of_animals() { TestObserver<ServiceResponse> observer = service.fetchResponse(DateTime.now()).test(); observer.assertNoErrors(); observer.assertValue(FakeService.RESPONSE); }
|
Service implements Repository { @NonNull @Override public Single<ServiceResponse> fetchResponse(@NonNull DateTime dateTime) { try { return api.loadProviderJson(DateHelper.encodeDate(dateTime)) .onErrorResumeNext(this::mapError); } catch (UnsupportedEncodingException e) { return Single.error(e); } } @Inject Service(@NonNull Api api); @NonNull @Override Single<ServiceResponse> fetchResponse(@NonNull DateTime dateTime); }
|
@Test public void should_process_json_payload_from_provider() { ServiceResponse response = ServiceResponse.create(DateTime.now(), Collections.singletonList(Animal.create("Doggy", "dog"))); when(api.loadProviderJson(any())).thenReturn(Single.just(response)); TestObserver<ServiceResponse> observer = service.fetchResponse(DateTime.now()).test(); observer.assertNoErrors(); observer.assertValue(response); }
|
Presenter implements Contract.Presenter { @Override public void onStart() { setLoading(); binder.bind(getAnimals(), this::setAnimals, this::setError, this::setComplete); } Presenter(@NonNull Repository repository,
@NonNull Contract.View view,
@NonNull RxBinder binder,
@NonNull Logger logger); @Override void onStart(); @Override void onStop(); }
|
@Test public void should_show_error_when_fetch_fails() { ServiceException exception = new ServiceException(); when(repository.fetchResponse(any())).thenReturn(Single.error(exception)); presenter.onStart(); verify(view).setViewState(ViewState.Error.create(R.string.error_message)); }
@Test public void should_show_empty_when_fetch_returns_nothing() { when(repository.fetchResponse(any())).thenReturn(Single.just(new ServiceResponse(null, Collections.emptyList()))); presenter.onStart(); verify(view).setViewState(ViewState.Empty.create(R.string.empty_message)); }
|
NamespacesChangesService { public NamespaceChangesStatus approveAll(String serviceName) { NamespaceChangesStatus namespaceChangesStatus = getNamespaceChangesStatus(serviceName); errorList = new ArrayList<>(); if (namespaceChangesStatus != null && namespaceChangesStatus.getNamespaceChanges() != null) { Map<NamespacedList, ActionType> removedNamespacesChangesMap = namespaceChangesStatus.getNamespaceChanges().entrySet().stream() .sorted(timespampComparator) .filter(filterToSave) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); namespaceChangesStatus.setNamespaceChanges(removedNamespacesChangesMap); save(serviceName, namespaceChangesStatus); } if (errorList.size() > 0) { String commaSeparatedFailedNamespacedList = errorList.stream() .map(stringFunction -> stringFunction.toString()) .collect(Collectors.joining(", ")); throw new WebApplicationException(commaSeparatedFailedNamespacedList, Response.status(Response.Status.BAD_REQUEST).entity(new ErrorMessage(commaSeparatedFailedNamespacedList)).build()); } return namespaceChangesStatus; } void save(String serviceName, NamespaceChangesStatus namespaceChangesStatus); NamespaceChangesStatus getNamespaceChangesStatus(String serviceName); NamespaceChangesStatus approve(String serviceName, NamespacedList namespacedList); NamespaceChangesStatus cancelAll(String serviceName); NamespaceChangesStatus cancel(String serviceName, NamespacedList namespacedList); NamespaceChangesStatus approveAll(String serviceName); }
|
@Test public void approveAllTest() { NamespaceChangesStatus namespacesChangesStatusReturned = namespacesChangesService.approveAll(SERVICE_NAME); verify(namespacedListsService, atLeastOnce()).addNamespacedList(namespacedList1); verify(namespacedListsService, atLeastOnce()).addNamespacedList(namespacedList2); verify(namespacedListsService, atLeastOnce()).deleteNamespacedList(namespacedList3.getName()); Assert.assertEquals(0, namespacesChangesStatusReturned.getNamespaceChanges().size()); }
@Test public void approveAllinOrderTest() { InOrder inOrder = inOrder(namespacedListsService); NamespaceChangesStatus namespacesChangesStatusReturned = namespacesChangesService.approveAll(SERVICE_NAME); inOrder.verify(namespacedListsService, atLeastOnce()).addNamespacedList(namespacedList2); inOrder.verify(namespacedListsService, atLeastOnce()).addNamespacedList(namespacedList1); inOrder.verify(namespacedListsService, atLeastOnce()).deleteNamespacedList(namespacedList3.getName()); Assert.assertEquals(0, namespacesChangesStatusReturned.getNamespaceChanges().size()); }
|
ZkPathChildrenCacheWrapper extends BaseCacheWrapper implements IPathChildrenCacheWrapper { @Override public void start(final PathChildrenCache.StartMode startMode) throws DataSourceConnectorException { if (useCache || useCacheWhenNotConnectedToDataSource) { if (! connector.isConnected()) { throw new DataSourceConnectorException("Failed to start cache for path=" + path + " due to no connection"); } try { cache.start(startMode); allowUseCache(); log.debug("Successfully started cache for path={}", path); } catch (Exception e) { log.error("Failed to start cache for path={}", path, e); } } } ZkPathChildrenCacheWrapper(IDataSourceConnector connector,
String path,
boolean dataIsCompressed,
PathChildrenCache cache); @Override void start(final PathChildrenCache.StartMode startMode); @Override void addListener(PathChildrenCacheListener listener); @Override void rebuild(); @Override void close(); @Override void rebuildNode(final String path); @Override Map<String, byte[]> getNodeIdToDataMap(); @Override byte[] getCurrentData(String fullPath); boolean isUseCache(); }
|
@Test public void testStartWithUseCacheExceptionHappens() throws Exception { PathChildrenCache.StartMode startMode = PathChildrenCache.StartMode.POST_INITIALIZED_EVENT; setupCacheThrowsExceptionOnStart(new Exception()); testee = new ZkPathChildrenCacheWrapper(client, "/test", false, cache); testee.start(startMode); }
@Test public void testStartWithUseCacheNoConnection() throws Exception { PathChildrenCache.StartMode startMode = PathChildrenCache.StartMode.POST_INITIALIZED_EVENT; setupCacheThrowsExceptionOnStart(new KeeperException.ConnectionLossException()); testee = new ZkPathChildrenCacheWrapper(client, "/test", false, cache); testee.start(startMode); }
@Test public void testStartWithDoNotUseCache() throws Exception { PathChildrenCache.StartMode startMode = PathChildrenCache.StartMode.POST_INITIALIZED_EVENT; testee = new ZkPathChildrenCacheWrapper(client, "/test", false, null); testee.start(startMode); verify(cache, never()).start(any(PathChildrenCache.StartMode.class)); }
@Test(expected = DataSourceConnectorException.class) public void startCache_WithoutPreloading_Fails_WhenNoConnected() throws DataSourceConnectorException { when(client.isConnected()).thenReturn(false); testee = new ZkPathChildrenCacheWrapper(client, "/test", false, cache); PathChildrenCache.StartMode startMode = PathChildrenCache.StartMode.POST_INITIALIZED_EVENT; testee.start(startMode); }
@Test(expected = DataSourceConnectorException.class) public void startCache_WithPreloading_Fails_WhenNoConnected() throws DataSourceConnectorException { when(client.isConnected()).thenReturn(false); testee = new ZkPathChildrenCacheWrapper(client, "/test", false, cache); PathChildrenCache.StartMode startMode = PathChildrenCache.StartMode.BUILD_INITIAL_CACHE; testee.start(startMode); }
@Test public void testStartWithUseCache() throws Exception { PathChildrenCache.StartMode startMode = PathChildrenCache.StartMode.POST_INITIALIZED_EVENT; testee = new ZkPathChildrenCacheWrapper(client, "/test", false, cache); testee.start(startMode); verify(cache, times(1)).start(startMode); }
|
ZkPathChildrenCacheWrapper extends BaseCacheWrapper implements IPathChildrenCacheWrapper { @Override public void rebuild() { if ((useCache || useCacheWhenNotConnectedToDataSource) && connector.isConnected()) { try { cache.rebuild(); allowUseCache(); log.debug("Successfully rebuilt cache for path={}", path); } catch (Exception e) { log.error("Failed to rebuild cache for path={}", path, e); } } } ZkPathChildrenCacheWrapper(IDataSourceConnector connector,
String path,
boolean dataIsCompressed,
PathChildrenCache cache); @Override void start(final PathChildrenCache.StartMode startMode); @Override void addListener(PathChildrenCacheListener listener); @Override void rebuild(); @Override void close(); @Override void rebuildNode(final String path); @Override Map<String, byte[]> getNodeIdToDataMap(); @Override byte[] getCurrentData(String fullPath); boolean isUseCache(); }
|
@Test public void testRebuildDoNotUseCache() throws Exception { testee = new ZkPathChildrenCacheWrapper(client, "/test", false, null); testee.rebuild(); verify(cache, never()).rebuild(); }
|
ZkPathChildrenCacheWrapper extends BaseCacheWrapper implements IPathChildrenCacheWrapper { @Override public void rebuildNode(final String path) { if (useCache || useCacheWhenNotConnectedToDataSource) { try { cache.rebuildNode(path); log.debug("Successfully rebuilt node cache for path={}", path); } catch (Exception e) { log.error("Failed to rebuild node cache for path={}", path, e); } } } ZkPathChildrenCacheWrapper(IDataSourceConnector connector,
String path,
boolean dataIsCompressed,
PathChildrenCache cache); @Override void start(final PathChildrenCache.StartMode startMode); @Override void addListener(PathChildrenCacheListener listener); @Override void rebuild(); @Override void close(); @Override void rebuildNode(final String path); @Override Map<String, byte[]> getNodeIdToDataMap(); @Override byte[] getCurrentData(String fullPath); boolean isUseCache(); }
|
@Test public void testRebuildNodeDoNotUseCache() throws Exception { testee = new ZkPathChildrenCacheWrapper(client, "/test", false, null); testee.rebuildNode("/test"); verify(cache, never()).rebuildNode(anyString()); }
|
ZkPathChildrenCacheWrapper extends BaseCacheWrapper implements IPathChildrenCacheWrapper { @Override public Map<String, byte[]> getNodeIdToDataMap() throws DataSourceConnectorException { Map<String, byte[]> result = new HashMap<>(); if (isCacheUsageAllowed()) { for (ChildData childData : cache.getCurrentData()) { String nodeId = getRuleId(childData.getPath()); result.put(nodeId, childData.getData()); } } else { List<String> children = connector.getChildren(path); for ( String child : children ) { String fullPath = ZKPaths.makePath(path, child); String nodeId = getRuleId(fullPath); byte[] bytes = getBytesForPath(fullPath); if (bytes != null) { result.put(nodeId, bytes); } else { log.info("ignoring null data for zkPath={}", fullPath); } } } return result; } ZkPathChildrenCacheWrapper(IDataSourceConnector connector,
String path,
boolean dataIsCompressed,
PathChildrenCache cache); @Override void start(final PathChildrenCache.StartMode startMode); @Override void addListener(PathChildrenCacheListener listener); @Override void rebuild(); @Override void close(); @Override void rebuildNode(final String path); @Override Map<String, byte[]> getNodeIdToDataMap(); @Override byte[] getCurrentData(String fullPath); boolean isUseCache(); }
|
@Test public void testGetNodeIdToDataMapDoNotUseCacheDataIsNotCompressed() throws Exception { String key = "test"; byte[] value = "result".getBytes(); testee = new ZkPathChildrenCacheWrapper(client, "/test", false, null); setupZookeeperClientReturnResult("/test", key, value, false); Map<String, byte[]> result = testee.getNodeIdToDataMap(); Assert.assertEquals(key, result.keySet().toArray()[0]); Assert.assertEquals(new String(value), new String((byte[])result.values().toArray()[0])); }
@Test public void testGetNodeIdToDataMapDoNotUseCacheDataIsCompressed() throws Exception { String key = "test"; byte[] value = "result".getBytes(); testee = new ZkPathChildrenCacheWrapper(client, "/test", true, null); setupZookeeperClientReturnResult("/test", key, value, true); Map<String, byte[]> result = testee.getNodeIdToDataMap(); Assert.assertEquals(key, result.keySet().toArray()[0]); Assert.assertEquals(new String(value), new String((byte[])result.values().toArray()[0])); }
@Test public void testGetNodeIdToDataMapDoNotUseCacheNoChildren() throws Exception { testee = new ZkPathChildrenCacheWrapper(client, "/test", true, null); when(client.getChildren("/test")).thenReturn(Collections.<String>emptyList()); Map<String, byte[]> result = testee.getNodeIdToDataMap(); Assert.assertEquals(0, result.size()); }
@Test(expected = RedirectorDataSourceException.class) public void testGetNodeIdToDataMapDoNotUseCacheException() throws Exception { testee = new ZkPathChildrenCacheWrapper(client, "/test", true, null); when(client.getChildren("/test")).thenThrow(new RedirectorDataSourceException("test")); testee.getNodeIdToDataMap(); }
|
ZkPathChildrenCacheWrapper extends BaseCacheWrapper implements IPathChildrenCacheWrapper { @Override public byte[] getCurrentData(String fullPath) throws DataSourceConnectorException { byte[] result = null; if (isCacheUsageAllowed()) { ChildData childData = cache.getCurrentData(fullPath); if (childData != null) { result = childData.getData(); } } else { result = getBytesForPath(fullPath); } return result; } ZkPathChildrenCacheWrapper(IDataSourceConnector connector,
String path,
boolean dataIsCompressed,
PathChildrenCache cache); @Override void start(final PathChildrenCache.StartMode startMode); @Override void addListener(PathChildrenCacheListener listener); @Override void rebuild(); @Override void close(); @Override void rebuildNode(final String path); @Override Map<String, byte[]> getNodeIdToDataMap(); @Override byte[] getCurrentData(String fullPath); boolean isUseCache(); }
|
@Test public void testGetCurrentDataUseCacheNullData() throws Exception { testee = new ZkPathChildrenCacheWrapper(client, "/test", false, cache); when(cache.getCurrentData(anyString())).thenReturn(null); byte[] result = testee.getCurrentData("/test"); Assert.assertNull(result); }
@Test public void testGetCurrentDataDoNotUseCache() throws Exception { testee = new ZkPathChildrenCacheWrapper(client, "/test", false, null); setupZookeeperClientReturnResult("/test", "result".getBytes(), false); byte[] result = testee.getCurrentData("/test"); Assert.assertEquals("result", new String(result)); }
@Test public void testGetCurrentDataDoNotUseCacheCompressed() throws Exception { testee = new ZkPathChildrenCacheWrapper(client, "/test", true, null); setupZookeeperClientReturnResult("/test", "result".getBytes(), true); byte[] result = testee.getCurrentData("/test"); Assert.assertEquals("result", new String(result)); }
@Test public void testGetCurrentDataDoNotUseCacheNullData() throws Exception { testee = new ZkPathChildrenCacheWrapper(client, "/test", false, null); setupZookeeperClientReturnResult("/test", null, false); byte[] result = testee.getCurrentData("/test"); Assert.assertNull(result); }
@Test public void testGetCurrentDataDoNotUseCacheThrowsException() throws Exception { testee = new ZkPathChildrenCacheWrapper(client, "/test", false, null); setupCuratorThrowsException(new DataSourceConnectorException()); Assert.assertNull(testee.getCurrentData("/test")); }
|
StacksService implements IStacksService { @Override public void deleteStack(String serviceName, String dataCenter, String availabilityZone, String flavor) { log.info("Deleting path: for service {}, dataCenter {}, availabilityZone {}, flavor {}", serviceName, dataCenter, availabilityZone, flavor); stacksDAO.deleteStackPath(new XreStackPath(dataCenter, availabilityZone, flavor, serviceName)); } @PostConstruct void init(); @Override ServicePaths getStacksForService(String serviceName); @Override ServicePaths updateStacksForService(String serviceName, ServicePaths servicePaths, Whitelisted whitelisted); @Override Set<String> getAllServiceNames(); @Override Boolean isServiceExists(String serviceName); @Override ServicePaths getStacksForAllServices(); @Override Set<PathItem> getActiveStacksAndFlavors(String serviceName); Set<PathItem> getActiveStacksAndFlavors(String serviceName, ServicePaths servicePaths); @Override HostIPsListWrapper getHostsForStackOnlyAndService(String stackName, String serviceName); @Override HostIPsListWrapper getRandomHostForStackOnlyAndService(String stackOnlyPath, String serviceName); @Override HostIPsListWrapper getHostsForStackAndService(String stackName, String serviceName); @Override HostIPsListWrapper getRandomHostForStackAndService(String stackName, String serviceName); @Override HostIPsListWrapper getHostsForFlavorAndService(String flavorName, String serviceName); @Override HostIPsListWrapper getRandomHostForFlavorAndService(String flavorName, String serviceName); @Override Set<StackData> getAllStacksAndHosts(String serviceName); Boolean isStackNameWithoutFlavor(String stackName); @Override HostIPsListWrapper getAddressByStackOrFlavor(String appName, String stackName, String flavorName); @Override HostIPsListWrapper getRandomAddressByStackOrFlavor(String serviceName, String stackName, String flavorName); @Override void deleteStack(String serviceName, String dataCenter, String availabilityZone, String flavor); @Override synchronized void deleteStacks(Paths paths); void setWhiteListService(IWhiteListService whiteListService); void setInitialDelay(long initialDelay); void setRefreshDelay(long refreshDelay); }
|
@Test public void testDeleteStack() throws Exception { testee.deleteStack("xreGuide", "po", "poc7", "1.40"); verify(stacksDAO, times(1)).deleteStackPath(new XreStackPath("/po/poc7/1.40/xreGuide")); }
|
ZkNodeCacheWrapper extends BaseCacheWrapper implements INodeCacheWrapper { @Override public void start(final boolean buildInitial) throws DataSourceConnectorException { if (useCache || useCacheWhenNotConnectedToDataSource) { if (! connector.isConnected()) { throw new DataSourceConnectorException("Failed to start cache for path=" + path + " due to no connection"); } try { cache.start(buildInitial); allowUseCache(); log.debug("Successfully started cache for path={}", path); } catch (Exception e) { log.error("Failed to start cache for path={} {}", path, e); } } } ZkNodeCacheWrapper(IDataSourceConnector connector, String path, NodeCache cache); ZkNodeCacheWrapper(IDataSourceConnector connector, String path, NodeCache cache, boolean dataIsCompressed, boolean useCache, boolean useCacheWhenNotConnectedToDataSource); ZkNodeCacheWrapper(IDataSourceConnector connector, String path, NodeCache cache, boolean useCache, boolean useCacheWhenNotConnectedToDataSource); @Override void start(final boolean buildInitial); @Override void addListener(NodeCacheListener listener); @Override void rebuild(); @Override void close(); @Override byte[] getCurrentData(); @Override int getCurrentDataVersion(); @Override String getPath(); boolean isUseCache(); }
|
@Test(expected = DataSourceConnectorException.class) public void startCache_WithoutPreloading_Fails_WhenNoConnected() throws DataSourceConnectorException { when(client.isConnected()).thenReturn(false); testee = new ZkNodeCacheWrapper(client, "/test", cache); testee.start(false); }
@Test(expected = DataSourceConnectorException.class) public void startCache_WithPreloading_Fails_WhenNoConnected() throws DataSourceConnectorException { when(client.isConnected()).thenReturn(false); testee = new ZkNodeCacheWrapper(client, "/test", cache); testee.start(true); }
@Test public void testStartUseCacheBuildInitial() throws Exception { testee = new ZkNodeCacheWrapper(client, "/test", cache); testee.start(true); verify(cache, times(1)).start(true); }
@Test public void testStartUseCacheDoNotBuildInitial() throws Exception { testee = new ZkNodeCacheWrapper(client, "/test", cache); testee.start(false); verify(cache, times(1)).start(false); }
@Test public void testStartUseCacheExceptionHappens() throws Exception { setupCacheThrowsExceptionOnStart(new Exception()); testee = new ZkNodeCacheWrapper(client, "/test", cache); testee.start(true); }
@Test public void testStartUseCacheNoConnection() throws Exception { setupCacheThrowsExceptionOnStart(new KeeperException.ConnectionLossException()); testee = new ZkNodeCacheWrapper(client, "/test", cache); testee.start(true); }
@Test public void testStartNotUseCache() throws Exception { testee = new ZkNodeCacheWrapper(client, "/test", null); testee.start(true); verify(cache, never()).start(anyBoolean()); }
|
ZkNodeCacheWrapper extends BaseCacheWrapper implements INodeCacheWrapper { public boolean isUseCache() { return useCache; } ZkNodeCacheWrapper(IDataSourceConnector connector, String path, NodeCache cache); ZkNodeCacheWrapper(IDataSourceConnector connector, String path, NodeCache cache, boolean dataIsCompressed, boolean useCache, boolean useCacheWhenNotConnectedToDataSource); ZkNodeCacheWrapper(IDataSourceConnector connector, String path, NodeCache cache, boolean useCache, boolean useCacheWhenNotConnectedToDataSource); @Override void start(final boolean buildInitial); @Override void addListener(NodeCacheListener listener); @Override void rebuild(); @Override void close(); @Override byte[] getCurrentData(); @Override int getCurrentDataVersion(); @Override String getPath(); boolean isUseCache(); }
|
@Test public void testConstructWithCache() throws Exception { testee = new ZkNodeCacheWrapper(client, "/test", cache); Assert.assertTrue(testee.isUseCache()); }
@Test public void testConstructWithoutCache() throws Exception { testee = new ZkNodeCacheWrapper(client, "/test", null); Assert.assertFalse(testee.isUseCache()); }
|
StacksService implements IStacksService { @Override public synchronized void deleteStacks(Paths paths){ StringBuffer logMsg = new StringBuffer(); logMsg.append("Deleting ").append(paths.getStacks().size()).append(" path(s) for ").append(paths.getServiceName()).append(" application: "); List<String> nonExistingPaths = new ArrayList<>(); for (PathItem item : paths.getStacks()) { try { stacksDAO.deleteStackPath(new XreStackPath(item.getValue(), paths.getServiceName())); logMsg.append(item.getValue()).append("; "); } catch (RedirectorNoNodeInPathException ex) { nonExistingPaths.add(item.getValue()); } } log.info(logMsg.toString()); if (!nonExistingPaths.isEmpty()) { throw new WebApplicationException(getMessageError(nonExistingPaths), Response.Status.BAD_REQUEST); } } @PostConstruct void init(); @Override ServicePaths getStacksForService(String serviceName); @Override ServicePaths updateStacksForService(String serviceName, ServicePaths servicePaths, Whitelisted whitelisted); @Override Set<String> getAllServiceNames(); @Override Boolean isServiceExists(String serviceName); @Override ServicePaths getStacksForAllServices(); @Override Set<PathItem> getActiveStacksAndFlavors(String serviceName); Set<PathItem> getActiveStacksAndFlavors(String serviceName, ServicePaths servicePaths); @Override HostIPsListWrapper getHostsForStackOnlyAndService(String stackName, String serviceName); @Override HostIPsListWrapper getRandomHostForStackOnlyAndService(String stackOnlyPath, String serviceName); @Override HostIPsListWrapper getHostsForStackAndService(String stackName, String serviceName); @Override HostIPsListWrapper getRandomHostForStackAndService(String stackName, String serviceName); @Override HostIPsListWrapper getHostsForFlavorAndService(String flavorName, String serviceName); @Override HostIPsListWrapper getRandomHostForFlavorAndService(String flavorName, String serviceName); @Override Set<StackData> getAllStacksAndHosts(String serviceName); Boolean isStackNameWithoutFlavor(String stackName); @Override HostIPsListWrapper getAddressByStackOrFlavor(String appName, String stackName, String flavorName); @Override HostIPsListWrapper getRandomAddressByStackOrFlavor(String serviceName, String stackName, String flavorName); @Override void deleteStack(String serviceName, String dataCenter, String availabilityZone, String flavor); @Override synchronized void deleteStacks(Paths paths); void setWhiteListService(IWhiteListService whiteListService); void setInitialDelay(long initialDelay); void setRefreshDelay(long refreshDelay); }
|
@Test public void testDeleteStacks() throws Exception { Paths paths = new Paths("xreGuide"); paths.getStacks().add(new PathItem("/po/poc7/1.50", 0, 0)); paths.getStacks().add(new PathItem("/po/poc7/1.51", 0, 0)); paths.getStacks().add(new PathItem("/po/poc2/1.51", 0, 0)); testee.deleteStacks(paths); verify(stacksDAO, times(1)).deleteStackPath(new XreStackPath("/po/poc7/1.50/xreGuide")); verify(stacksDAO, times(1)).deleteStackPath(new XreStackPath("/po/poc7/1.51/xreGuide")); verify(stacksDAO, times(1)).deleteStackPath(new XreStackPath("/po/poc2/1.51/xreGuide")); }
|
ZkNodeCacheWrapper extends BaseCacheWrapper implements INodeCacheWrapper { @Override public void rebuild() { if ((useCache || useCacheWhenNotConnectedToDataSource) && connector.isConnected()) { try { cache.rebuild(); allowUseCache(); log.debug("Successfully rebuild cache for path={}", path); } catch (Exception e) { log.error("Failed to rebuild cache for path={} {}", path, e); } } } ZkNodeCacheWrapper(IDataSourceConnector connector, String path, NodeCache cache); ZkNodeCacheWrapper(IDataSourceConnector connector, String path, NodeCache cache, boolean dataIsCompressed, boolean useCache, boolean useCacheWhenNotConnectedToDataSource); ZkNodeCacheWrapper(IDataSourceConnector connector, String path, NodeCache cache, boolean useCache, boolean useCacheWhenNotConnectedToDataSource); @Override void start(final boolean buildInitial); @Override void addListener(NodeCacheListener listener); @Override void rebuild(); @Override void close(); @Override byte[] getCurrentData(); @Override int getCurrentDataVersion(); @Override String getPath(); boolean isUseCache(); }
|
@Test public void testRebuildDoNotUseCache() throws Exception { testee = new ZkNodeCacheWrapper(client, "/test", null); testee.rebuild(); verify(cache, never()).rebuild(); }
|
ZkNodeCacheWrapper extends BaseCacheWrapper implements INodeCacheWrapper { @Override public byte[] getCurrentData() { byte[] result = null; if (isCacheUsageAllowed()) { ChildData data = cache.getCurrentData(); if (data != null) { result = data.getData(); } } else { try { result = dataIsCompressed ? connector.getDataDecompressed(path) : connector.getData(path); } catch (DataSourceConnectorException e) { log.warn("Failed to get data for zkPath={} {}", path); } } return result; } ZkNodeCacheWrapper(IDataSourceConnector connector, String path, NodeCache cache); ZkNodeCacheWrapper(IDataSourceConnector connector, String path, NodeCache cache, boolean dataIsCompressed, boolean useCache, boolean useCacheWhenNotConnectedToDataSource); ZkNodeCacheWrapper(IDataSourceConnector connector, String path, NodeCache cache, boolean useCache, boolean useCacheWhenNotConnectedToDataSource); @Override void start(final boolean buildInitial); @Override void addListener(NodeCacheListener listener); @Override void rebuild(); @Override void close(); @Override byte[] getCurrentData(); @Override int getCurrentDataVersion(); @Override String getPath(); boolean isUseCache(); }
|
@Test public void testGetCurrentDataUseCacheWithoutData() throws Exception { testee = new ZkNodeCacheWrapper(client, "/test", cache); when(cache.getCurrentData()).thenReturn(null); byte[] result = testee.getCurrentData(); Assert.assertNull(result); }
@Test public void testGetCurrentDataDoNotUseCache() throws Exception { testee = new ZkNodeCacheWrapper(client, "/test", null); setupZookeeperConnectorReturnResult("result".getBytes()); byte[] result = testee.getCurrentData(); Assert.assertEquals("result", new String(result)); }
@Test public void testGetCurrentDataDoNotUseCacheCuratorReturnsNull() throws Exception { testee = new ZkNodeCacheWrapper(client, "/test", null); setupZookeeperConnectorReturnResult(null); byte[] result = testee.getCurrentData(); Assert.assertNull(result); }
@Test public void testGetCurrentDataDoNotUseCacheCuratorThrowsException() throws Exception { testee = new ZkNodeCacheWrapper(client, "/test", null); setupZookeeperConnectorThrowsException(new DataSourceConnectorException()); Assert.assertNull(testee.getCurrentData()); }
|
ZkNodeCacheWrapper extends BaseCacheWrapper implements INodeCacheWrapper { @Override public int getCurrentDataVersion() { int result = RedirectorConstants.NO_MODEL_NODE_VERSION; if (isCacheUsageAllowed()) { ChildData data = cache.getCurrentData(); if (data != null && data.getStat() != null) { result = data.getStat().getVersion(); } } else { try { if (connector.isPathExists(path)) { result = connector.getNodeVersion(path); } else { log.warn("Node {} does not exist", path); } } catch (DataSourceConnectorException e) { log.error("Failed to get data for zkPath={} {}", path, e); } } return result; } ZkNodeCacheWrapper(IDataSourceConnector connector, String path, NodeCache cache); ZkNodeCacheWrapper(IDataSourceConnector connector, String path, NodeCache cache, boolean dataIsCompressed, boolean useCache, boolean useCacheWhenNotConnectedToDataSource); ZkNodeCacheWrapper(IDataSourceConnector connector, String path, NodeCache cache, boolean useCache, boolean useCacheWhenNotConnectedToDataSource); @Override void start(final boolean buildInitial); @Override void addListener(NodeCacheListener listener); @Override void rebuild(); @Override void close(); @Override byte[] getCurrentData(); @Override int getCurrentDataVersion(); @Override String getPath(); boolean isUseCache(); }
|
@Test public void returnVersion_WhenDataStoreHasData_AndCacheIsNotUsed() throws Exception { testee = new ZkNodeCacheWrapper(client, "/test", null); setupZookeeperConnectorReturnVersion(5); int result = testee.getCurrentDataVersion(); Assert.assertEquals(5, result); }
@Test public void returnNoVersion_WhenDataStoreHasNoData_AndCacheIsNotUsed() throws Exception { testee = new ZkNodeCacheWrapper(client, "/test", null); doThrow(new DataSourceConnectorException()).when(client).getNodeVersion(anyString()); int result = testee.getCurrentDataVersion(); Assert.assertEquals(NO_MODEL_NODE_VERSION, result); }
@Test public void returnNoVersion_WhenDataStoreThrowsException_AndCacheIsNotUsed() throws Exception { testee = new ZkNodeCacheWrapper(client, "/test", null); setupZookeeperConnectorThrowsException(new DataSourceConnectorException()); int result = testee.getCurrentDataVersion(); Assert.assertEquals(NO_MODEL_NODE_VERSION, result); }
|
StacksService implements IStacksService { @Override public HostIPsListWrapper getHostsForStackAndService(String stackName, String serviceName) { HostIPsListWrapper result = new HostIPsListWrapper(); result.getHostIPsList().addAll(getNodesAddresses(new XreStackPath(stackName, serviceName))); return result; } @PostConstruct void init(); @Override ServicePaths getStacksForService(String serviceName); @Override ServicePaths updateStacksForService(String serviceName, ServicePaths servicePaths, Whitelisted whitelisted); @Override Set<String> getAllServiceNames(); @Override Boolean isServiceExists(String serviceName); @Override ServicePaths getStacksForAllServices(); @Override Set<PathItem> getActiveStacksAndFlavors(String serviceName); Set<PathItem> getActiveStacksAndFlavors(String serviceName, ServicePaths servicePaths); @Override HostIPsListWrapper getHostsForStackOnlyAndService(String stackName, String serviceName); @Override HostIPsListWrapper getRandomHostForStackOnlyAndService(String stackOnlyPath, String serviceName); @Override HostIPsListWrapper getHostsForStackAndService(String stackName, String serviceName); @Override HostIPsListWrapper getRandomHostForStackAndService(String stackName, String serviceName); @Override HostIPsListWrapper getHostsForFlavorAndService(String flavorName, String serviceName); @Override HostIPsListWrapper getRandomHostForFlavorAndService(String flavorName, String serviceName); @Override Set<StackData> getAllStacksAndHosts(String serviceName); Boolean isStackNameWithoutFlavor(String stackName); @Override HostIPsListWrapper getAddressByStackOrFlavor(String appName, String stackName, String flavorName); @Override HostIPsListWrapper getRandomAddressByStackOrFlavor(String serviceName, String stackName, String flavorName); @Override void deleteStack(String serviceName, String dataCenter, String availabilityZone, String flavor); @Override synchronized void deleteStacks(Paths paths); void setWhiteListService(IWhiteListService whiteListService); void setInitialDelay(long initialDelay); void setRefreshDelay(long refreshDelay); }
|
@Test public void testGetServiceAddressByStack() throws Exception { when(stacksDAO.getAllStackPaths()).thenReturn(getStackPaths("/po/poc1/1.50/xreGuide")); when(stacksDAO.getHosts(new XreStackPath("/po/poc1/1.50/xreGuide"))) .thenReturn(Arrays.asList(new HostIPs("ipv4", "ipv6"), new HostIPs("ipv4_2", "ipv6_2"))); HostIPsListWrapper result = testee.getHostsForStackAndService("/po/poc1/1.50", "xreGuide"); Assert.assertEquals(new HostIPs("ipv4", "ipv6"), result.getHostIPsList().get(0)); Assert.assertEquals(new HostIPs("ipv4_2", "ipv6_2"), result.getHostIPsList().get(1)); }
|
PathHelper implements IPathHelper { @Override public String getRawPath(String... childId) { return baseNodePath + DELIMETER + entityPath + StringUtils.join(childId, DELIMETER); } PathHelper(String basePath, String rootPath, String entityPath); static synchronized IPathHelper getOrCreateHelper(String basePath, String rootPath, String entityPath); @Override String getPath(EntityType entityType); @Override String getPath(EntityType entityType, String... childId); @Override String getRawPath(String... childId); @Override String getPath(); @Override String getPath(String... childId); @Override String getPathByService(String serviceName); @Override String getPathByService(String serviceName, String... childId); @Override String getPathByService(String serviceName, EntityType entityType, String... childId); static IPathHelper getPathHelper(EntityType entityType, String basePath); static IPathHelper getPathHelper(EntityCategory entityCategory, String basePath); static final String DELIMETER; }
|
@Test public void testGetRawPath() throws Exception { IPathHelper helper = PathHelper.getPathHelper(EntityType.STACK, "/test"); Assert.assertEquals("/test/services/PO/POC7/1.45/xreGuide", helper.getRawPath("/PO/POC7/1.45", "xreGuide")); }
|
PathHelper implements IPathHelper { @Override public String getPathByService(String serviceName) { return baseNodePath + DELIMETER + serviceName + getJoinedChildren(entityPath); } PathHelper(String basePath, String rootPath, String entityPath); static synchronized IPathHelper getOrCreateHelper(String basePath, String rootPath, String entityPath); @Override String getPath(EntityType entityType); @Override String getPath(EntityType entityType, String... childId); @Override String getRawPath(String... childId); @Override String getPath(); @Override String getPath(String... childId); @Override String getPathByService(String serviceName); @Override String getPathByService(String serviceName, String... childId); @Override String getPathByService(String serviceName, EntityType entityType, String... childId); static IPathHelper getPathHelper(EntityType entityType, String basePath); static IPathHelper getPathHelper(EntityCategory entityCategory, String basePath); static final String DELIMETER; }
|
@Test public void testGetPathByService() throws Exception { IPathHelper helper = PathHelper.getPathHelper(EntityType.RULE, "/test"); Assert.assertEquals("/test/Redirector/services/xreGuide/rules", helper.getPathByService("xreGuide")); }
|
Distribution extends VisitableExpression implements java.io.Serializable, Expressions { public void setRules(List<Rule> rules) { this.rules = rules; } Distribution(); static Distribution newInstance(Distribution distribution); List<Rule> getRules(); void setRules(List<Rule> rules); void addRule(Rule rule); Server getDefaultServer(); void setDefaultServer(Server server); @Override boolean equals(Object o); @Override int hashCode(); }
|
@Test public void testCreateObject() throws Exception { Distribution distribution = new Distribution(); List<Rule> rules = new ArrayList<>(); for (int i = 0; i < 5; i++) { Rule rule = new Rule(); rule.setPercent(i); Server serv = new Server(); serv.setName("name" + i); serv.setPath("path" + i); serv.setUrl("url" + i); rule.setServer(serv); rules.add(rule); } distribution.setRules(rules); String result = serializeIt(distribution, true); System.out.println(result); assertNotNull(result); }
|
Partners implements Expressions { public void setPartners(Set<Partner> partners) { this.partners = partners; } Set<Partner> getPartners(); void setPartners(Set<Partner> partners); void addPartner(Partner partner); }
|
@Test public void testCreateObject() throws Exception { Partners partners = new Partners(); Set<Partner> partnersList = new LinkedHashSet<>(); for (int y = 0; y < 3; y++) { Set<PartnerProperty> properties = new LinkedHashSet<>(); for (int i = 0; i < 5; i++) { PartnerProperty prop = new PartnerProperty(); prop.setName("id" + i); prop.setValue("xre: properties.add(prop); } Partner newPartner = new Partner("test"); newPartner.setProperties(properties); partnersList.add(newPartner); } partners.setPartners(partnersList); String result = serializeIt(partners, true); System.out.println(result); assertNotNull(result); }
|
ServicePaths { public void setPaths(List<Paths> paths) { this.paths = paths; } ServicePaths(); ServicePaths(List<Paths> paths); List<Paths> getPaths(); Paths getPaths(String serviceName); void setPaths(List<Paths> paths); @Override boolean equals(Object o); @Override int hashCode(); }
|
@Test public void testCreateObject() throws Exception { ServicePaths servicePaths = new ServicePaths(); List<Paths> pathsList = new ArrayList<Paths>(); for (int y = 0; y < 2; y++) { String serviceName = "serviceName" + y; List<PathItem> stacks = new ArrayList<PathItem>(); List<PathItem> flavours = new ArrayList<PathItem>(); for (int i = 0; i < 2; i++) { PathItem stacksPathItem = new PathItem(); stacksPathItem.setActiveNodesCount(i); stacksPathItem.setValue("stackPathValue" + i); stacks.add(stacksPathItem); PathItem flavoursPathItem = new PathItem(); flavoursPathItem.setActiveNodesCount(i); flavoursPathItem.setValue("flavoursPathValue" + i); flavours.add(flavoursPathItem); } Paths newPaths = new Paths(serviceName, stacks, flavours); pathsList.add(newPaths); } servicePaths.setPaths(pathsList); String result = serializeIt(servicePaths, false); Assert.assertNotNull(result); Assert.assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><servicePaths><paths serviceName=\"serviceName0\"><stack nodes=\"0\" nodesWhitelisted=\"0\">stackPathValue0</stack><stack nodes=\"1\" nodesWhitelisted=\"0\">stackPathValue1</stack><flavor nodes=\"0\" nodesWhitelisted=\"0\">flavoursPathValue0</flavor><flavor nodes=\"1\" nodesWhitelisted=\"0\">flavoursPathValue1</flavor></paths><paths serviceName=\"serviceName1\"><stack nodes=\"0\" nodesWhitelisted=\"0\">stackPathValue0</stack><stack nodes=\"1\" nodesWhitelisted=\"0\">stackPathValue1</stack><flavor nodes=\"0\" nodesWhitelisted=\"0\">flavoursPathValue0</flavor><flavor nodes=\"1\" nodesWhitelisted=\"0\">flavoursPathValue1</flavor></paths></servicePaths>", result); }
|
StackData { public Optional<List<HostIPs>> getHosts() { return hosts; } StackData(String path, List<HostIPs> hosts); StackData(String path); StackData(String dataCenter, String availabilityZone, String flavor, String serviceName, List<HostIPs> hosts); StackData(String dataCenter, String availabilityZone, String flavor, String serviceName); String getDataCenter(); String getAvailabilityZone(); String getFlavor(); String getServiceName(); String getPath(); String getStackOnlyPath(); @Override String toString(); Optional<List<HostIPs>> getHosts(); @Override boolean equals(Object o); @Override int hashCode(); }
|
@Test public void testConstructWithHosts() throws Exception { List<HostIPs> hosts = new ArrayList<>(); hosts.add(new HostIPs("ipv4_1", "ipv6_1")); hosts.add(new HostIPs("ipv4_2", "ipv6_2")); StackData stackData = new StackData("/A/B/C/D", hosts); Assert.assertEquals(hosts, stackData.getHosts().get()); }
|
AnnotationScanner { public static Set<Class<?>> getAnnotatedClasses(final Class[] annotations, final String... packages) { Set<String> annotationsToScan = Stream.of(annotations).map(Class::getSimpleName).collect(toSet()); ClassLoader cl = AnnotationScanner.class.getClassLoader(); try { ClassPath cp = ClassPath.from(cl); return Stream.of(packages) .flatMap(packageName -> cp.getTopLevelClassesRecursive(packageName).stream()) .filter(isClassAnnotatedByScannedAnnotations(annotationsToScan)) .map(ClassPath.ClassInfo::load) .collect(toSet()); } catch (IOException e) { log.error("Failed to get annotated classes", e); return Collections.emptySet(); } } static Set<Class<?>> getAnnotatedClasses(final Class[] annotations, final String... packages); }
|
@Test public void annotatedClassesAreFound() throws Exception { Class[] annotations = {Scannable.class}; String[] packages = {"com.comcast.redirector.common.util.annotation.scanner.sample"}; Set<Class<?>> result = AnnotationScanner.getAnnotatedClasses(annotations, packages); Assert.assertTrue(result.contains(Annotated.class)); Assert.assertTrue(result.contains(OneMoreAnnotated.class)); Assert.assertFalse(result.contains(NotAnnotated.class)); Assert.assertFalse(result.contains(AnnotadedByIgnoredAnnotation.class)); }
|
UrlUtils { public static String buildUrl(final String finalBaseUri, final String finalEndpoint) { StringBuffer url = new StringBuffer(); if (finalBaseUri != null) { String baseUri = finalBaseUri.trim(); if (baseUri.endsWith("/")) { url.append(baseUri.substring(0, baseUri.length() - 1)); } else { url.append(baseUri); } if (finalEndpoint != null) { String endpoint = finalEndpoint.trim(); if (endpoint.length() > 0 ) { url.append("/"); if (endpoint.startsWith("/")) { url.append(endpoint.substring(1, endpoint.length())); } else { url.append(endpoint); } } } return url.toString(); } return null; } static String buildUrl(final String finalBaseUri, final String finalEndpoint); }
|
@Test public void testBuildUrl() throws Exception { String expectedString = "http: String actualString = UrlUtils.buildUrl("http: Assert.assertEquals(expectedString, actualString); actualString = UrlUtils.buildUrl("http: Assert.assertEquals(expectedString, actualString); actualString = UrlUtils.buildUrl("http: Assert.assertEquals(expectedString, actualString); actualString = UrlUtils.buildUrl("http: Assert.assertEquals(expectedString, actualString); }
|
ServiceDiscoveryHostJsonSerializer implements ServiceDiscoveryHostDeserializer { @Override public HostIPs deserialize(String data) throws SerializerException { try { HostIPs hostIPs; JSONObject object = new JSONObject(data); if (hasPath(object, HOST_PAYLOAD_NAME, HOST_PARAMETERS_NAME, IPV6_ADDRESS_FIELD_NAME)) { JSONObject parameters = object.getJSONObject(HOST_PAYLOAD_NAME).getJSONObject(HOST_PARAMETERS_NAME); hostIPs = new HostIPs( getStringValueOrNull(parameters, IPV4_ADDRESS_FIELD_NAME), getStringValueOrNull(parameters, IPV6_ADDRESS_FIELD_NAME), getStringValueOrNull(parameters, WEIGHT_FIELD_NAME)); } else { String weight = null; if (hasPath(object, HOST_PAYLOAD_NAME, HOST_PARAMETERS_NAME, "weight")) { JSONObject parameters = object.getJSONObject(HOST_PAYLOAD_NAME).getJSONObject(HOST_PARAMETERS_NAME); weight = getStringValueOrNull(parameters, WEIGHT_FIELD_NAME); } hostIPs = new HostIPs(object.getString(OLD_ADDRESS_FIELD_NAME), null, weight); } return hostIPs; } catch (JSONException e) { throw new SerializerException("failed to parse host " + data, e); } } @Override HostIPs deserialize(String data); static final String IPV4_ADDRESS_FIELD_NAME; static final String IPV6_ADDRESS_FIELD_NAME; static final String WEIGHT_FIELD_NAME; static final String OLD_ADDRESS_FIELD_NAME; }
|
@Test public void testDeserializeItemWithoutIpv4() throws Exception { String input = getPayload(NULL, IPV6_VALUE); HostIPs result = testee.deserialize(input); Assert.assertNull(result.getIpV4Address()); Assert.assertEquals(IPV6_VALUE, result.getIpV6Address()); }
@Test public void testDeserializeItemWithoutIpv6() throws Exception { String input = getPayload(IPV4_VALUE, NULL); HostIPs result = testee.deserialize(input); Assert.assertNull(result.getIpV6Address()); Assert.assertEquals(IPV4_VALUE, result.getIpV4Address()); }
@Test public void testDeserializeItemWithoutParameters() throws Exception { String input = getPayloadWithoutParameters(); HostIPs result = testee.deserialize(input); Assert.assertNull(result.getIpV6Address()); Assert.assertNotNull(result.getIpV4Address()); }
|
StacksService implements IStacksService { @Override public HostIPsListWrapper getHostsForStackOnlyAndService(String stackName, String serviceName) { HostIPsListWrapper result = new HostIPsListWrapper(); List<String> args = Splitter.on(DELIMETER).trimResults().omitEmptyStrings().splitToList(stackName); result.getHostIPsList().addAll(getNodesAddressesFromStackOnly(new XreStackPath(args.get(0), args.get(1), null, serviceName))); return result; } @PostConstruct void init(); @Override ServicePaths getStacksForService(String serviceName); @Override ServicePaths updateStacksForService(String serviceName, ServicePaths servicePaths, Whitelisted whitelisted); @Override Set<String> getAllServiceNames(); @Override Boolean isServiceExists(String serviceName); @Override ServicePaths getStacksForAllServices(); @Override Set<PathItem> getActiveStacksAndFlavors(String serviceName); Set<PathItem> getActiveStacksAndFlavors(String serviceName, ServicePaths servicePaths); @Override HostIPsListWrapper getHostsForStackOnlyAndService(String stackName, String serviceName); @Override HostIPsListWrapper getRandomHostForStackOnlyAndService(String stackOnlyPath, String serviceName); @Override HostIPsListWrapper getHostsForStackAndService(String stackName, String serviceName); @Override HostIPsListWrapper getRandomHostForStackAndService(String stackName, String serviceName); @Override HostIPsListWrapper getHostsForFlavorAndService(String flavorName, String serviceName); @Override HostIPsListWrapper getRandomHostForFlavorAndService(String flavorName, String serviceName); @Override Set<StackData> getAllStacksAndHosts(String serviceName); Boolean isStackNameWithoutFlavor(String stackName); @Override HostIPsListWrapper getAddressByStackOrFlavor(String appName, String stackName, String flavorName); @Override HostIPsListWrapper getRandomAddressByStackOrFlavor(String serviceName, String stackName, String flavorName); @Override void deleteStack(String serviceName, String dataCenter, String availabilityZone, String flavor); @Override synchronized void deleteStacks(Paths paths); void setWhiteListService(IWhiteListService whiteListService); void setInitialDelay(long initialDelay); void setRefreshDelay(long refreshDelay); }
|
@Test public void testGetServiceAddressByStackOnly() throws Exception { when(stacksDAO.getAllStackPaths()).thenReturn(getStackPaths("/po/poc1/1.50/xreGuide")); when(stacksDAO.getHostsByStackOnlyPath(any(XreStackPath.class))) .thenReturn(Arrays.asList(new HostIPs("ipv4", "ipv6"), new HostIPs("ipv4_2", "ipv6_2"))); HostIPsListWrapper result = testee.getHostsForStackOnlyAndService("/po/poc1", "xreGuide"); Assert.assertEquals(new HostIPs("ipv4", "ipv6"), result.getHostIPsList().get(0)); Assert.assertEquals(new HostIPs("ipv4_2", "ipv6_2"), result.getHostIPsList().get(1)); }
|
StacksService implements IStacksService { @Override public HostIPsListWrapper getRandomHostForStackAndService(String stackName, String serviceName) { HostIPsListWrapper result = new HostIPsListWrapper(); Random random = new Random(); XreStackPath xreStackPath = new XreStackPath(stackName, serviceName); int hostCount = stacksDAO.getHostsCount(xreStackPath); if (hostCount > 0) { result.getHostIPsList().add(stacksDAO.getHostByIndex(xreStackPath, random.nextInt(hostCount))); } return result; } @PostConstruct void init(); @Override ServicePaths getStacksForService(String serviceName); @Override ServicePaths updateStacksForService(String serviceName, ServicePaths servicePaths, Whitelisted whitelisted); @Override Set<String> getAllServiceNames(); @Override Boolean isServiceExists(String serviceName); @Override ServicePaths getStacksForAllServices(); @Override Set<PathItem> getActiveStacksAndFlavors(String serviceName); Set<PathItem> getActiveStacksAndFlavors(String serviceName, ServicePaths servicePaths); @Override HostIPsListWrapper getHostsForStackOnlyAndService(String stackName, String serviceName); @Override HostIPsListWrapper getRandomHostForStackOnlyAndService(String stackOnlyPath, String serviceName); @Override HostIPsListWrapper getHostsForStackAndService(String stackName, String serviceName); @Override HostIPsListWrapper getRandomHostForStackAndService(String stackName, String serviceName); @Override HostIPsListWrapper getHostsForFlavorAndService(String flavorName, String serviceName); @Override HostIPsListWrapper getRandomHostForFlavorAndService(String flavorName, String serviceName); @Override Set<StackData> getAllStacksAndHosts(String serviceName); Boolean isStackNameWithoutFlavor(String stackName); @Override HostIPsListWrapper getAddressByStackOrFlavor(String appName, String stackName, String flavorName); @Override HostIPsListWrapper getRandomAddressByStackOrFlavor(String serviceName, String stackName, String flavorName); @Override void deleteStack(String serviceName, String dataCenter, String availabilityZone, String flavor); @Override synchronized void deleteStacks(Paths paths); void setWhiteListService(IWhiteListService whiteListService); void setInitialDelay(long initialDelay); void setRefreshDelay(long refreshDelay); }
|
@Test public void testGetRandomServiceAddressByStack() throws Exception { HostIPs hostIps1 = new HostIPs("ipv4", "ipv6"); HostIPs hostIps2 = new HostIPs("ipv4_2", "ipv6_2"); when(stacksDAO.getAllStackPaths()).thenReturn(getStackPaths("/po/poc1/1.50/xreGuide")); when(stacksDAO.getHostsCount(new XreStackPath("/po/poc1/1.50/xreGuide"))).thenReturn(2); when(stacksDAO.getHostByIndex(new XreStackPath("/po/poc1/1.50/xreGuide"), 0)).thenReturn(hostIps1); when(stacksDAO.getHostByIndex(new XreStackPath("/po/poc1/1.50/xreGuide"), 1)).thenReturn(hostIps2); int returnFirstAddressCount = 0; int returnSecondAddressCount = 0; for (int i = 0; i < 100; i++) { HostIPsListWrapper result = testee.getRandomHostForStackAndService("/po/poc1/1.50", "xreGuide"); Assert.assertTrue(result.getHostIPsList().size() == 1); HostIPs resultHostIps = result.getHostIPsList().get(0); if (new HostIPs("ipv4", "ipv6").equals(resultHostIps)) { returnFirstAddressCount ++; } if (new HostIPs("ipv4_2", "ipv6_2").equals(resultHostIps)) { returnSecondAddressCount ++; } Assert.assertTrue(hostIps1.equals(resultHostIps) || hostIps2.equals(resultHostIps)); } Assert.assertTrue(returnFirstAddressCount > 0); Assert.assertTrue(returnSecondAddressCount > 0); }
|
StacksService implements IStacksService { @Override public HostIPsListWrapper getRandomHostForStackOnlyAndService(String stackOnlyPath, String serviceName) { XreStackPath noFlavorStackPath = getNoFlavorXreStackPath(stackOnlyPath, serviceName); List<String> flavors = getFlavorsFromStackOnly(noFlavorStackPath); Collections.shuffle(flavors); for (String flavorName : flavors) { try { List<HostIPs> randomIp = getRandomHostForStackAndService(stackOnlyPath + DELIMETER + flavorName, serviceName).getHostIPsList(); if (randomIp.size() > 0) { HostIPsListWrapper result = new HostIPsListWrapper(); result.getHostIPsList().addAll(randomIp); return result; } } catch (Exception ignore) { log.info("Exception '{}' was caught and ignored while getting random host by stack name without flavor", ignore.getMessage()); } } return new HostIPsListWrapper(); } @PostConstruct void init(); @Override ServicePaths getStacksForService(String serviceName); @Override ServicePaths updateStacksForService(String serviceName, ServicePaths servicePaths, Whitelisted whitelisted); @Override Set<String> getAllServiceNames(); @Override Boolean isServiceExists(String serviceName); @Override ServicePaths getStacksForAllServices(); @Override Set<PathItem> getActiveStacksAndFlavors(String serviceName); Set<PathItem> getActiveStacksAndFlavors(String serviceName, ServicePaths servicePaths); @Override HostIPsListWrapper getHostsForStackOnlyAndService(String stackName, String serviceName); @Override HostIPsListWrapper getRandomHostForStackOnlyAndService(String stackOnlyPath, String serviceName); @Override HostIPsListWrapper getHostsForStackAndService(String stackName, String serviceName); @Override HostIPsListWrapper getRandomHostForStackAndService(String stackName, String serviceName); @Override HostIPsListWrapper getHostsForFlavorAndService(String flavorName, String serviceName); @Override HostIPsListWrapper getRandomHostForFlavorAndService(String flavorName, String serviceName); @Override Set<StackData> getAllStacksAndHosts(String serviceName); Boolean isStackNameWithoutFlavor(String stackName); @Override HostIPsListWrapper getAddressByStackOrFlavor(String appName, String stackName, String flavorName); @Override HostIPsListWrapper getRandomAddressByStackOrFlavor(String serviceName, String stackName, String flavorName); @Override void deleteStack(String serviceName, String dataCenter, String availabilityZone, String flavor); @Override synchronized void deleteStacks(Paths paths); void setWhiteListService(IWhiteListService whiteListService); void setInitialDelay(long initialDelay); void setRefreshDelay(long refreshDelay); }
|
@Test public void testGetRandomServiceAddressByStackWithoutFlavor() throws Exception { HostIPs hostIps1 = new HostIPs("ipv4", "ipv6"); HostIPs hostIps2 = new HostIPs("ipv4_2", "ipv6_2"); List<String> flavors = new ArrayList<>(2); flavors.add("1.50"); flavors.add("1.49"); when(stacksDAO.getAllStackPaths()).thenReturn(getStackPaths("/po/poc1/1.50/xreGuide")); when(stacksDAO.getHostsCount(new XreStackPath("/po/poc1/1.50/xreGuide"))).thenReturn(1); when(stacksDAO.getHostsCount(new XreStackPath("/po/poc1/1.49/xreGuide"))).thenReturn(1); when(stacksDAO.getFlavorsByStackOnlyPath(any(XreStackPath.class))).thenReturn(flavors); when(stacksDAO.getHostByIndex(new XreStackPath("/po/poc1/1.50/xreGuide"), 0)).thenReturn(hostIps1); when(stacksDAO.getHostByIndex(new XreStackPath("/po/poc1/1.49/xreGuide"), 0)).thenReturn(hostIps2); int returnFirstAddressCount = 0; int returnSecondAddressCount = 0; for (int i = 0; i < 100; i++) { HostIPsListWrapper result = testee.getRandomHostForStackOnlyAndService("/po/poc1", "xreGuide"); Assert.assertTrue(result.getHostIPsList().size() == 1); HostIPs resultHostIps = result.getHostIPsList().get(0); if (new HostIPs("ipv4", "ipv6").equals(resultHostIps)) { returnFirstAddressCount ++; } if (new HostIPs("ipv4_2", "ipv6_2").equals(resultHostIps)) { returnSecondAddressCount ++; } Assert.assertTrue(hostIps1.equals(resultHostIps) || hostIps2.equals(resultHostIps)); } Assert.assertTrue(returnFirstAddressCount > 0); Assert.assertTrue(returnSecondAddressCount > 0); }
|
StacksService implements IStacksService { @Override public HostIPsListWrapper getHostsForFlavorAndService(String flavorName, String serviceName) { HostIPsListWrapper result = new HostIPsListWrapper(); for (XreStackPath stack : getStackPathsForServiceAndFlavor(serviceName, flavorName)) { result.getHostIPsList().addAll(getNodesAddresses(stack)); } return result; } @PostConstruct void init(); @Override ServicePaths getStacksForService(String serviceName); @Override ServicePaths updateStacksForService(String serviceName, ServicePaths servicePaths, Whitelisted whitelisted); @Override Set<String> getAllServiceNames(); @Override Boolean isServiceExists(String serviceName); @Override ServicePaths getStacksForAllServices(); @Override Set<PathItem> getActiveStacksAndFlavors(String serviceName); Set<PathItem> getActiveStacksAndFlavors(String serviceName, ServicePaths servicePaths); @Override HostIPsListWrapper getHostsForStackOnlyAndService(String stackName, String serviceName); @Override HostIPsListWrapper getRandomHostForStackOnlyAndService(String stackOnlyPath, String serviceName); @Override HostIPsListWrapper getHostsForStackAndService(String stackName, String serviceName); @Override HostIPsListWrapper getRandomHostForStackAndService(String stackName, String serviceName); @Override HostIPsListWrapper getHostsForFlavorAndService(String flavorName, String serviceName); @Override HostIPsListWrapper getRandomHostForFlavorAndService(String flavorName, String serviceName); @Override Set<StackData> getAllStacksAndHosts(String serviceName); Boolean isStackNameWithoutFlavor(String stackName); @Override HostIPsListWrapper getAddressByStackOrFlavor(String appName, String stackName, String flavorName); @Override HostIPsListWrapper getRandomAddressByStackOrFlavor(String serviceName, String stackName, String flavorName); @Override void deleteStack(String serviceName, String dataCenter, String availabilityZone, String flavor); @Override synchronized void deleteStacks(Paths paths); void setWhiteListService(IWhiteListService whiteListService); void setInitialDelay(long initialDelay); void setRefreshDelay(long refreshDelay); }
|
@Test public void testGetServiceAddressByFlavor() throws Exception { when(stacksDAO.getAllStackPaths()).thenReturn( getStackPaths("/po/poc1/1.50/xreGuide", "/po/poc2/1.50/xreGuide", "/po/poc3/1.50/xreGuide")); when(stacksDAO.getHosts(new XreStackPath("/po/poc1/1.50/xreGuide"))) .thenReturn(Arrays.asList(new HostIPs("ipv4", "ipv6"), new HostIPs("ipv4_2", "ipv6_2"))); when(stacksDAO.getHosts(new XreStackPath("/po/poc2/1.50/xreGuide"))) .thenReturn(Arrays.asList(new HostIPs("ipv4_3", "ipv6_3"))); HostIPsListWrapper result = testee.getHostsForFlavorAndService("1.50", "xreGuide"); Assert.assertEquals(new HostIPs("ipv4", "ipv6"), result.getHostIPsList().get(0)); Assert.assertEquals(new HostIPs("ipv4_2", "ipv6_2"), result.getHostIPsList().get(1)); Assert.assertEquals(new HostIPs("ipv4_3", "ipv6_3"), result.getHostIPsList().get(2)); }
|
StacksService implements IStacksService { @Override public HostIPsListWrapper getRandomHostForFlavorAndService(String flavorName, String serviceName) { List<XreStackPath> stacks = new ArrayList<>(getStackPathsForServiceAndFlavor(serviceName, flavorName)); Collections.shuffle(stacks); HostIPsListWrapper result = new HostIPsListWrapper(); for (XreStackPath xreStackPath : stacks) { result = getRandomHostForStackAndService(xreStackPath.getStackAndFlavorPath(), serviceName); if (result.getHostIPsList().size() > 0) { return result; } } return result; } @PostConstruct void init(); @Override ServicePaths getStacksForService(String serviceName); @Override ServicePaths updateStacksForService(String serviceName, ServicePaths servicePaths, Whitelisted whitelisted); @Override Set<String> getAllServiceNames(); @Override Boolean isServiceExists(String serviceName); @Override ServicePaths getStacksForAllServices(); @Override Set<PathItem> getActiveStacksAndFlavors(String serviceName); Set<PathItem> getActiveStacksAndFlavors(String serviceName, ServicePaths servicePaths); @Override HostIPsListWrapper getHostsForStackOnlyAndService(String stackName, String serviceName); @Override HostIPsListWrapper getRandomHostForStackOnlyAndService(String stackOnlyPath, String serviceName); @Override HostIPsListWrapper getHostsForStackAndService(String stackName, String serviceName); @Override HostIPsListWrapper getRandomHostForStackAndService(String stackName, String serviceName); @Override HostIPsListWrapper getHostsForFlavorAndService(String flavorName, String serviceName); @Override HostIPsListWrapper getRandomHostForFlavorAndService(String flavorName, String serviceName); @Override Set<StackData> getAllStacksAndHosts(String serviceName); Boolean isStackNameWithoutFlavor(String stackName); @Override HostIPsListWrapper getAddressByStackOrFlavor(String appName, String stackName, String flavorName); @Override HostIPsListWrapper getRandomAddressByStackOrFlavor(String serviceName, String stackName, String flavorName); @Override void deleteStack(String serviceName, String dataCenter, String availabilityZone, String flavor); @Override synchronized void deleteStacks(Paths paths); void setWhiteListService(IWhiteListService whiteListService); void setInitialDelay(long initialDelay); void setRefreshDelay(long refreshDelay); }
|
@Test public void testGetRandomServiceAddressByFlavor() throws Exception { HostIPs hostIps1 = new HostIPs("ipv4", "ipv6"); HostIPs hostIps2 = new HostIPs("ipv4_2", "ipv6_2"); HostIPs hostIps3 = new HostIPs("ipv4_3", "ipv6_3"); when(stacksDAO.getAllStackPaths()).thenReturn( getStackPaths("/po/poc1/1.50/xreGuide", "/po/poc2/1.50/xreGuide")); when(stacksDAO.getHostsCount(new XreStackPath("/po/poc1/1.50/xreGuide"))).thenReturn(2); when(stacksDAO.getHostsCount(new XreStackPath("/po/poc2/1.50/xreGuide"))).thenReturn(1); when(stacksDAO.getHostsCount(new XreStackPath("/po/poc3/1.50/xreGuide"))).thenReturn(0); when(stacksDAO.getHostByIndex(new XreStackPath("/po/poc1/1.50/xreGuide"), 0)).thenReturn(hostIps1); when(stacksDAO.getHostByIndex(new XreStackPath("/po/poc1/1.50/xreGuide"), 1)).thenReturn(hostIps2); when(stacksDAO.getHostByIndex(new XreStackPath("/po/poc2/1.50/xreGuide"), 0)).thenReturn(hostIps3); int [] returnAddressesCount = {0, 0, 0}; for (int i = 0; i < 100; i++) { HostIPsListWrapper result = testee.getRandomHostForFlavorAndService("1.50", "xreGuide"); Assert.assertTrue(result.getHostIPsList().size() == 1); HostIPs resultHostIps = result.getHostIPsList().get(0); if (hostIps1.equals(resultHostIps)) { returnAddressesCount [0] ++; } if (hostIps2.equals(resultHostIps)) { returnAddressesCount [1] ++; } if (hostIps3.equals(resultHostIps)) { returnAddressesCount [2] ++; } Assert.assertTrue(hostIps1.equals(resultHostIps) || hostIps2.equals(resultHostIps) || hostIps3.equals(resultHostIps)); } for (int i = 0; i < returnAddressesCount.length ; i++) { Assert.assertTrue(returnAddressesCount [i] > 0); } }
|
StacksService implements IStacksService { @Override public Set<StackData> getAllStacksAndHosts(String serviceName) { return FluentIterable .from(getStackPathsForService(serviceName)) .transform(new Function<XreStackPath, StackData>() { @Override public StackData apply(XreStackPath input) { try { return new StackData(input.getPath(), getNodesAddresses(input)); } catch (RedirectorDataSourceException e) { throw new ServiceException("failed to get hosts for " + input.getPath(), e); } } }) .toSet(); } @PostConstruct void init(); @Override ServicePaths getStacksForService(String serviceName); @Override ServicePaths updateStacksForService(String serviceName, ServicePaths servicePaths, Whitelisted whitelisted); @Override Set<String> getAllServiceNames(); @Override Boolean isServiceExists(String serviceName); @Override ServicePaths getStacksForAllServices(); @Override Set<PathItem> getActiveStacksAndFlavors(String serviceName); Set<PathItem> getActiveStacksAndFlavors(String serviceName, ServicePaths servicePaths); @Override HostIPsListWrapper getHostsForStackOnlyAndService(String stackName, String serviceName); @Override HostIPsListWrapper getRandomHostForStackOnlyAndService(String stackOnlyPath, String serviceName); @Override HostIPsListWrapper getHostsForStackAndService(String stackName, String serviceName); @Override HostIPsListWrapper getRandomHostForStackAndService(String stackName, String serviceName); @Override HostIPsListWrapper getHostsForFlavorAndService(String flavorName, String serviceName); @Override HostIPsListWrapper getRandomHostForFlavorAndService(String flavorName, String serviceName); @Override Set<StackData> getAllStacksAndHosts(String serviceName); Boolean isStackNameWithoutFlavor(String stackName); @Override HostIPsListWrapper getAddressByStackOrFlavor(String appName, String stackName, String flavorName); @Override HostIPsListWrapper getRandomAddressByStackOrFlavor(String serviceName, String stackName, String flavorName); @Override void deleteStack(String serviceName, String dataCenter, String availabilityZone, String flavor); @Override synchronized void deleteStacks(Paths paths); void setWhiteListService(IWhiteListService whiteListService); void setInitialDelay(long initialDelay); void setRefreshDelay(long refreshDelay); }
|
@Test public void testGetAllStacksAndHosts() throws Exception { when(stacksDAO.getAllStackPaths()).thenReturn( new LinkedHashSet<>(Arrays.asList( new XreStackPath("/po/poc1/1.50/xreGuide"), new XreStackPath("/po/poc2/1.50/xreGuide")))); when(stacksDAO.getHosts(new XreStackPath("/po/poc1/1.50/xreGuide"))) .thenReturn(Arrays.asList(new HostIPs("ipv4", "ipv6"), new HostIPs("ipv4_2", "ipv6_2"))); when(stacksDAO.getHosts(new XreStackPath("/po/poc2/1.50/xreGuide"))) .thenReturn(Arrays.asList(new HostIPs("ipv4_3", "ipv6_3"))); StackData[] stacks = testee.getAllStacksAndHosts("xreGuide").toArray(new StackData[]{}); Assert.assertEquals("/po/poc1/1.50/xreGuide", stacks[0].getPath()); Assert.assertEquals("ipv4", stacks[0].getHosts().get().get(0).getIpV4Address()); Assert.assertEquals("ipv6", stacks[0].getHosts().get().get(0).getIpV6Address()); Assert.assertEquals("ipv4_2", stacks[0].getHosts().get().get(1).getIpV4Address()); Assert.assertEquals("ipv6_2", stacks[0].getHosts().get().get(1).getIpV6Address()); Assert.assertEquals("/po/poc2/1.50/xreGuide", stacks[1].getPath()); Assert.assertEquals("ipv4_3", stacks[1].getHosts().get().get(0).getIpV4Address()); Assert.assertEquals("ipv6_3", stacks[1].getHosts().get().get(0).getIpV6Address()); }
|
NextWhitelistedEntityViewService implements IEntityViewService<Whitelisted> { @Override public Whitelisted getEntity(String serviceName) { PendingChangesStatus pendingChangesStatus = changesStatusService.getPendingChangesStatus(serviceName); return getWhitelistedPendingPreview(serviceName, pendingChangesStatus); } @Override Whitelisted getEntity(String serviceName); @Override Whitelisted getEntity(PendingChangesStatus pendingChangesStatus, Whitelisted currentEntity); void setChangesStatusService(IChangesStatusService changesStatusService); }
|
@Test public void testGetEntity() throws Exception { String serviceName = "xreGuide"; Whitelisted currentWhitelist = new Whitelisted(); currentWhitelist.setPaths(new ArrayList<String>() {{ add("/P0/1.55"); add("/P1/3.44"); }}); when(whiteListService.getWhitelistedStacks(serviceName)).thenReturn(currentWhitelist); PendingChangesStatus pendingChangesStatus = new PendingChangesStatus(); Map<String, PendingChange> whitelistedChanges = new HashMap<>(); PendingChangesHelper.putPendingChange(whitelistedChanges, Integer.toString("/P0/3.355".hashCode()), new Value("/P0/3.355"), null, ActionType.ADD); PendingChangesHelper.putPendingChange(whitelistedChanges, Integer.toString("/P2/3.22".hashCode()), new Value("/P2/3.22"), null, ActionType.ADD); PendingChangesHelper.putPendingChange(whitelistedChanges, Integer.toString("/P1/3.44".hashCode()), null, new Value("/P1/3.44"), ActionType.DELETE); pendingChangesStatus.setWhitelisted(whitelistedChanges); when(changesStatusService.getPendingChangesStatus(serviceName)).thenReturn(pendingChangesStatus); Whitelisted whitelisted = testee.getEntity(serviceName); Assert.assertEquals("/P0/1.55", whitelisted.getPaths().get(0)); Assert.assertEquals("/P2/3.22", whitelisted.getPaths().get(1)); Assert.assertEquals("/P0/3.355", whitelisted.getPaths().get(2)); }
|
NextFlavorRulesEntityViewService implements IEntityViewService<SelectServer> { @Override public SelectServer getEntity(String serviceName) { PendingChangesStatus pendingChanges = changesStatusService.getPendingChangesStatus(serviceName); SelectServer rules = flavorRulesService.getAllRules(serviceName); return getEntity(pendingChanges, rules); } @Override SelectServer getEntity(String serviceName); @Override SelectServer getEntity(PendingChangesStatus pendingChangesStatus, SelectServer currentEntity); }
|
@Test public void testGetEntity() throws Exception { String serviceName = "xreGuide"; Distribution distribution = new Distribution(); distribution.setDefaultServer(ServerHelper.prepareServer(RedirectorConstants.DEFAULT_SERVER_NAME, "NewDefaultFlavor")); SelectServer expectedSelectServer = RulesUtils.buildSelectServer( prepareSimpleFlavorRules(new HashMap<Expressions, String>() {{ put(new Equals("mac", "receiverMacAddress1"), "rule2-flavor"); }}), distribution ); Collection<IfExpression> rules = prepareSimpleFlavorRules(new HashMap<Expressions, String>() {{ put(new Equals("receiverType", "Native"), "rule1-flavor"); put(new Equals("mac", "receiverMacAddress"), "rule2-flavor"); }}); SelectServer currentSelectServer = new SelectServer(); PendingChangesStatus pendingChangesStatus = getPendingChangesStatus(); currentSelectServer.setItems(rules); currentSelectServer.setDistribution(distribution); when(flavorRulesService.getAllRules(serviceName)).thenReturn(currentSelectServer); when(changesStatusService.getPendingChangesStatus(serviceName)).thenReturn(pendingChangesStatus); SelectServer selectServer = testee.getEntity(serviceName); verifyRuleExpressionsEqual(expectedSelectServer.getItems(), selectServer.getItems()); assertEquals(expectedSelectServer.getDistribution(), selectServer.getDistribution()); }
|
NextUrlRulesEntityViewService implements IEntityViewService<URLRules> { @Override public URLRules getEntity(String serviceName) { PendingChangesStatus pendingChanges = changesStatusService.getPendingChangesStatus(serviceName); Collection<IfExpression> urlRules = PendingRulesPreviewHelper.mergeRules( RulesUtils.mapFromCollection(urlRulesService.getUrlRules(serviceName)), pendingChanges.getUrlRules()); PendingChange defaultUrlParamChange = pendingChanges.getUrlParams().get(RedirectorConstants.DEFAULT_SERVER_NAME); Default defaultUrlParams = new Default(); if (defaultUrlParamChange != null) { defaultUrlParams.setUrlRule((UrlRule) defaultUrlParamChange.getChangedExpression()); } else { defaultUrlParams.setUrlRule(urlParamsService.getUrlParams(serviceName)); } return RulesUtils.buildURLRules(urlRules, defaultUrlParams); } @Override URLRules getEntity(String serviceName); @Override URLRules getEntity(PendingChangesStatus pendingChangesStatus, URLRules currentEntity); }
|
@Test public void testGetEntity() throws Exception { String serviceName = "xreGuide"; Collection<IfExpression> rules = new ArrayList<>(); rules.add(UrlRuleExpressionsHelper.getUrlRuleIfExpression(new Equals("receiverType", "Native"), "protocol1", IpProtocolVersion.IPV4.getVersionString())); rules.add(UrlRuleExpressionsHelper.getUrlRuleIfExpression(new Equals("mac", "receiverMacAddress"), "protocol2", IpProtocolVersion.IPV6.getVersionString())); when(urlRulesService.getUrlRules(serviceName)).thenReturn(rules); when(urlParamsService.getUrlParams(serviceName)) .thenReturn(UrlRuleExpressionsHelper.prepareUrlParams("DefaultProtocol", IpProtocolVersion.IPV4.getVersionString())); PendingChangesStatus pendingChangesStatus = new PendingChangesStatus(); Map<String, PendingChange> urlRulesChanges = new HashMap<>(); PendingChangesHelper.putPendingChange(urlRulesChanges, UrlRuleExpressionsHelper.getRuleIdByProtocolAndIp("protocol1", IpProtocolVersion.IPV4.getVersionString()), UrlRuleExpressionsHelper.getUrlRuleIfExpression(new Equals("receiverType", "changed"), "protocol1", IpProtocolVersion.IPV4.getVersionString()), UrlRuleExpressionsHelper.getUrlRuleIfExpression(new Equals("receiverType", "Native"), "protocol1", IpProtocolVersion.IPV4.getVersionString()), ActionType.UPDATE); PendingChangesHelper.putPendingChange(urlRulesChanges, UrlRuleExpressionsHelper.getRuleIdByProtocolAndIp("protocol2", IpProtocolVersion.IPV6.getVersionString()), null, UrlRuleExpressionsHelper.getUrlRuleIfExpression(new Equals("mac", "receiverMacAddress"), "protocol2", IpProtocolVersion.IPV6.getVersionString()), ActionType.DELETE); PendingChangesHelper.putPendingChange(urlRulesChanges, UrlRuleExpressionsHelper.getRuleIdByProtocolAndIp("newProtocol", IpProtocolVersion.IPV6.getVersionString()), UrlRuleExpressionsHelper.getUrlRuleIfExpression(new Equals("newParameter", "newValue"), "newProtocol", IpProtocolVersion.IPV6.getVersionString()), null, ActionType.UPDATE); pendingChangesStatus.setUrlRules(urlRulesChanges); Map<String, PendingChange> urlParamsChanges = new HashMap<>(); PendingChangesHelper.putPendingChange(urlParamsChanges, RedirectorConstants.DEFAULT_SERVER_NAME, UrlRuleExpressionsHelper.prepareUrlParams("changedDefaultProtocol", IpProtocolVersion.IPV6.getVersionString()), UrlRuleExpressionsHelper.prepareUrlParams("DefaultProtocol", IpProtocolVersion.IPV4.getVersionString()), ActionType.UPDATE); pendingChangesStatus.setUrlParams(urlParamsChanges); when(changesStatusService.getPendingChangesStatus(serviceName)).thenReturn(pendingChangesStatus); URLRules expectedUrlRules = new URLRules(); Collection<IfExpression> expectedRules = new ArrayList<>(); expectedRules.add(UrlRuleExpressionsHelper.getUrlRuleIfExpression(new Equals("receiverType", "changed"), "protocol1", IpProtocolVersion.IPV4.getVersionString())); expectedRules.add(UrlRuleExpressionsHelper.getUrlRuleIfExpression(new Equals("newParameter", "newValue"), "newProtocol", IpProtocolVersion.IPV6.getVersionString())); expectedUrlRules.setItems(expectedRules); Default expectedDefaultUrlRule = new Default(); expectedDefaultUrlRule.setUrlRule(UrlRuleExpressionsHelper.prepareUrlParams("changedDefaultProtocol", IpProtocolVersion.IPV6.getVersionString())); expectedUrlRules.setDefaultStatement(expectedDefaultUrlRule); URLRules result = testee.getEntity(serviceName); verifyRuleExpressionsEqual(expectedUrlRules.getItems(), result.getItems()); Assert.assertEquals(expectedUrlRules.getDefaultStatement().getUrlRule(), result.getDefaultStatement().getUrlRule()); }
|
NextDistributionEntityViewService implements IEntityViewService<Distribution> { @Override public Distribution getEntity(String serviceName) { PendingChangesStatus pendingChangesStatus = changesStatusService.getPendingChangesStatus(serviceName); return getDistributionPendingPreview(serviceName, pendingChangesStatus); } @Override Distribution getEntity(String serviceName); @Override Distribution getEntity(PendingChangesStatus pendingChangesStatus, Distribution currentDistribution); void setChangesStatusService(IChangesStatusService changesStatusService); }
|
@Test public void testGetEntity() throws Exception { String serviceName = "xreGuide"; DistributionBuilder builder = new DistributionBuilder(); Distribution currentDistribution = builder. withRule(newDistributionRule(0, 10f, newSimpleServerForFlavor("1.40"))). withRule(newDistributionRule(1, 20f, newSimpleServerForFlavor("1.41"))). withRule(newDistributionRule(2, 30f, newSimpleServerForFlavor("1.42"))). build(); when(distributionService.getDistribution(serviceName)).thenReturn(currentDistribution); PendingChangesStatus pendingChangesStatus = new PendingChangesStatus(); Map<String, PendingChange> distributionChanges = new HashMap<>(); PendingChangesHelper.putDistributionChange(distributionChanges, 0, 10.0f, "1.40", ActionType.DELETE); PendingChangesHelper.putDistributionChange(distributionChanges, 1, 15.0f, "1.40-SNAPSHOT", ActionType.UPDATE); PendingChangesHelper.putDistributionChange(distributionChanges, 3, 35.0f, "1.44", ActionType.ADD); pendingChangesStatus.setDistributions(distributionChanges); when(changesStatusService.getPendingChangesStatus(serviceName)).thenReturn(pendingChangesStatus); Distribution distribution = testee.getEntity(serviceName); verifyRulesAreEqual(getRule(0, 15.0f, "1.40-SNAPSHOT"), distribution.getRules().get(0)); verifyRulesAreEqual(getRule(1, 30.0f, "1.42"), distribution.getRules().get(1)); verifyRulesAreEqual(getRule(2, 35.0f, "1.44"), distribution.getRules().get(2)); }
|
ListServiceDAO extends BaseListDAO<T> implements IListServiceDAO<T> { @Override public T getById(String serviceName, String id) { try { return getByPath(pathHelper.getPathByService(serviceName, id), getCache(serviceName)); } catch (DataSourceConnectorException e) { throw new RedirectorDataSourceException(e); } } ListServiceDAO(Class<T> clazz,
Serializer marshalling,
IDataSourceConnector connector,
IPathHelper pathHelper,
boolean isCompressed,
boolean useCache); @Override List<T> getAll(String serviceName); @Override Map<String, T> getAllInMap(String serviceName); @Override T getById(String serviceName, String id); @Override void saveById(T data, String serviceName, String id); @Override void deleteById(String serviceName, String id); @Override void addCacheListener(String serviceName, ICacheListener listener); }
|
@Test public void testGetById() throws Exception { String id = "id"; String service = "service"; String resultSerialized = "testModel"; setupCacheReturnOne(resultSerialized); setupDeserialize(resultSerialized, new TestModel(id)); TestModel result = testee.getById(service, id); Assert.assertEquals(id, result.getId()); }
@Test(expected = RedirectorNoConnectionToDataSourceException.class) public void testGetByIdExceptionHappens() throws Exception { setupExceptionOnGetOne(new RedirectorNoConnectionToDataSourceException(new Exception())); testee.getById(ANY_SERVICE, ANY_ID); }
@Test(expected = RedirectorNoConnectionToDataSourceException.class) public void testGetByIdNoConnection() throws Exception { setupExceptionOnGetOne(new RedirectorNoConnectionToDataSourceException(new KeeperException.ConnectionLossException())); testee.getById(ANY_SERVICE, ANY_ID); }
@Test public void testGetByIdCantDeserialize() throws Exception { String id = "id"; String service = "service"; String resultSerialized = "testModel"; setupCacheReturnOne(resultSerialized); setupDeserializeThrowsException(); TestModel result = testee.getById(service, id); Assert.assertNull(result); }
|
ListServiceDAO extends BaseListDAO<T> implements IListServiceDAO<T> { @Override public List<T> getAll(String serviceName) { try { return getAll(getCache(serviceName)); } catch (DataSourceConnectorException e) { throw new RedirectorDataSourceException(e); } } ListServiceDAO(Class<T> clazz,
Serializer marshalling,
IDataSourceConnector connector,
IPathHelper pathHelper,
boolean isCompressed,
boolean useCache); @Override List<T> getAll(String serviceName); @Override Map<String, T> getAllInMap(String serviceName); @Override T getById(String serviceName, String id); @Override void saveById(T data, String serviceName, String id); @Override void deleteById(String serviceName, String id); @Override void addCacheListener(String serviceName, ICacheListener listener); }
|
@Test public void testGetAll() throws Exception { String id = "id"; String service = "service"; String resultSerialized = "testModel"; setupCacheReturnMap(id, resultSerialized); setupDeserialize(resultSerialized, new TestModel(id)); List<TestModel> result = testee.getAll(service); Assert.assertEquals(id, result.get(0).getId()); }
@Test(expected = RedirectorDataSourceException.class) public void testGetAllExceptionHappens() throws Exception { setupExceptionOnGetAll(new RedirectorDataSourceException(new Exception())); testee.getAll(ANY_SERVICE); }
@Test(expected = RedirectorNoNodeInPathException.class) public void testGetAllNoConnection() throws Exception { setupExceptionOnGetAll(new RedirectorNoNodeInPathException(new KeeperException.ConnectionLossException())); testee.getAll(ANY_SERVICE); }
@Test public void testGetAllCantSerialize() throws Exception { String id = "id"; String resultSerialized = "testModel"; setupCacheReturnMap(id, resultSerialized); setupDeserializeThrowsException(); List<TestModel> result = testee.getAll(ANY_SERVICE); Assert.assertEquals(0, result.size()); }
|
NamespacesChangesService { public NamespaceChangesStatus approve(String serviceName, NamespacedList namespacedList) { NamespaceChangesStatus namespaceChangesStatus = getNamespaceChangesStatus(serviceName); errorList = null; if (namespaceChangesStatus != null && namespaceChangesStatus.getNamespaceChanges() != null && namespacedList != null) { Map<NamespacedList, ActionType> removedNamespacesChangesMap = namespaceChangesStatus.getNamespaceChanges().entrySet().stream() .filter(filterToSaveAlone(namespacedList)) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); namespaceChangesStatus.setNamespaceChanges(removedNamespacesChangesMap); save(serviceName, namespaceChangesStatus); } if (errorList != null) { throw new WebApplicationException(FAILED_TO_SAVE_NAMESPACE_DUE_TO_VALIDATION_ERROR, Response.status(Response.Status.BAD_REQUEST).entity(new ErrorMessage(FAILED_TO_SAVE_NAMESPACE_DUE_TO_VALIDATION_ERROR)).build()); } return namespaceChangesStatus; } void save(String serviceName, NamespaceChangesStatus namespaceChangesStatus); NamespaceChangesStatus getNamespaceChangesStatus(String serviceName); NamespaceChangesStatus approve(String serviceName, NamespacedList namespacedList); NamespaceChangesStatus cancelAll(String serviceName); NamespaceChangesStatus cancel(String serviceName, NamespacedList namespacedList); NamespaceChangesStatus approveAll(String serviceName); }
|
@Test public void approveTest() { NamespaceChangesStatus namespacesChangesStatusReturned = namespacesChangesService.approve(SERVICE_NAME, namespacedList1); verify(namespacedListsService, atLeastOnce()).addNamespacedList(namespacedList1); Assert.assertEquals(2, namespacesChangesStatusReturned.getNamespaceChanges().size()); }
|
ListServiceDAO extends BaseListDAO<T> implements IListServiceDAO<T> { @Override public void saveById(T data, String serviceName, String id) throws SerializerException { try { saveByPath(data, pathHelper.getPathByService(serviceName, id), getCache(serviceName)); } catch (DataSourceConnectorException e) { throw new RedirectorDataSourceException(e); } } ListServiceDAO(Class<T> clazz,
Serializer marshalling,
IDataSourceConnector connector,
IPathHelper pathHelper,
boolean isCompressed,
boolean useCache); @Override List<T> getAll(String serviceName); @Override Map<String, T> getAllInMap(String serviceName); @Override T getById(String serviceName, String id); @Override void saveById(T data, String serviceName, String id); @Override void deleteById(String serviceName, String id); @Override void addCacheListener(String serviceName, ICacheListener listener); }
|
@Test public void testSaveById() throws Exception { String path = "/path"; String resultSerialized = "testModel"; setupPathHelperReturn(path); setupSerialize(resultSerialized); testee.saveById(new TestModel("id"), ANY_SERVICE, ANY_ID); verifySave(resultSerialized, path); verify(getWrapper(), times(1)).rebuildNode(path); }
@Test(expected = RedirectorNoConnectionToDataSourceException.class) public void testSaveByIdExceptionHappens() throws Exception { String path = "/path"; String resultSerialized = "testModel"; setupPathHelperReturn(path); setupSerialize(resultSerialized); setupExceptionOnSave(new RedirectorNoConnectionToDataSourceException(new Exception())); testee.saveById(new TestModel(ANY_ID), ANY_SERVICE, ANY_ID); }
@Test(expected = RedirectorNoConnectionToDataSourceException.class) public void testSaveByIdNoConnection() throws Exception { String path = "/path"; String resultSerialized = "testModel"; setupPathHelperReturn(path); setupSerialize(resultSerialized); setupExceptionOnSave(new RedirectorNoConnectionToDataSourceException(new Exception())); testee.saveById(new TestModel(ANY_ID), ANY_SERVICE, ANY_ID); }
@Test(expected = SerializerException.class) public void testSaveByIdCantSerialize() throws Exception { String path = "/path"; setupPathHelperReturn(path); setupSerializeThrowsException(); testee.saveById(new TestModel(ANY_ID), ANY_SERVICE, ANY_ID); }
|
ListServiceDAO extends BaseListDAO<T> implements IListServiceDAO<T> { @Override public void deleteById(String serviceName, String id) { try { super.deleteByPath(pathHelper.getPathByService(serviceName, id), getCache(serviceName)); } catch (DataSourceConnectorException e) { throw new RedirectorDataSourceException(e); } } ListServiceDAO(Class<T> clazz,
Serializer marshalling,
IDataSourceConnector connector,
IPathHelper pathHelper,
boolean isCompressed,
boolean useCache); @Override List<T> getAll(String serviceName); @Override Map<String, T> getAllInMap(String serviceName); @Override T getById(String serviceName, String id); @Override void saveById(T data, String serviceName, String id); @Override void deleteById(String serviceName, String id); @Override void addCacheListener(String serviceName, ICacheListener listener); }
|
@Test public void testDeleteById() throws Exception { String path = "/path"; setupPathHelperReturn(path); testee.deleteById(ANY_SERVICE, ANY_ID); verify(connector, times(1)).delete(path); verify(getWrapper(), times(1)).rebuild(); }
@Test(expected = RedirectorDataSourceException.class) public void testDeleteByIdExceptionHappens() throws Exception { String path = "/path"; setupPathHelperReturn(path); setupExceptionOnDelete(new RedirectorDataSourceException(new Exception())); testee.deleteById(ANY_SERVICE, ANY_ID); }
@Test(expected = RedirectorNoConnectionToDataSourceException.class) public void testDeleteByIdNoConnection() throws Exception { String path = "/path"; setupPathHelperReturn(path); setupExceptionOnDelete(new RedirectorNoConnectionToDataSourceException(new Exception())); testee.deleteById(ANY_SERVICE, ANY_ID); }
|
SimpleDAO extends BaseDAO<T> implements ISimpleDAO<T>, ICacheableDAO { @Override public T get() { try { return deserializeOrReturnNull(getCache().getCurrentData()); } catch (DataSourceConnectorException e) { throw new RedirectorDataSourceException(e); } } SimpleDAO(Class<T> clazz,
Serializer marshalling,
IDataSourceConnector connector,
IPathHelper pathHelper,
boolean compressed,
boolean useCache); @Override T get(); @Override void save(T data); @Override void addCacheListener(ICacheListener listener); @Override synchronized void rebuildCache(); @Override void close(); }
|
@Test public void testGet() throws Exception { String id = "id"; String resultSerialized = "testModel"; setupCacheReturnResult(resultSerialized); setupDeserialize(resultSerialized, new TestModel(id)); TestModel result = testee.get(); assertEquals(id, result.getId()); }
@Test public void testGetExceptionHappens() throws Exception { exception.expect(RedirectorDataSourceException.class); setupExceptionOnGetOne(new RedirectorDataSourceException("Test")); testee.get(); }
@Test public void testGetNoConnection() throws Exception { exception.expect(RedirectorNoConnectionToDataSourceException.class); setupExceptionOnGetOne(new RedirectorNoConnectionToDataSourceException(new KeeperException.ConnectionLossException())); testee.get(); }
@Test public void testGetCantDeserialize() throws Exception { String resultSerialized = "testModel"; setupCacheReturnResult(resultSerialized); setupDeserializeThrowsException(); TestModel result = testee.get(); assertNull(result); }
|
NamespacesChangesService { public NamespaceChangesStatus cancel(String serviceName, NamespacedList namespacedList) { NamespaceChangesStatus namespaceChangesStatus = getNamespaceChangesStatus(serviceName); namespaceChangesStatus.getNamespaceChanges().remove(namespacedList); save(serviceName, namespaceChangesStatus); return namespaceChangesStatus; } void save(String serviceName, NamespaceChangesStatus namespaceChangesStatus); NamespaceChangesStatus getNamespaceChangesStatus(String serviceName); NamespaceChangesStatus approve(String serviceName, NamespacedList namespacedList); NamespaceChangesStatus cancelAll(String serviceName); NamespaceChangesStatus cancel(String serviceName, NamespacedList namespacedList); NamespaceChangesStatus approveAll(String serviceName); }
|
@Test public void cancelTest() { NamespaceChangesStatus namespacesChangesStatusReturned = namespacesChangesService.cancel(SERVICE_NAME, namespacedList1); verify(namespacedListsService, never()).addNamespacedList(namespacedList1); Assert.assertEquals(2, namespacesChangesStatusReturned.getNamespaceChanges().size()); }
|
SimpleDAO extends BaseDAO<T> implements ISimpleDAO<T>, ICacheableDAO { @Override public void save(T data) throws SerializerException { try { save(serialize(data), pathHelper.getPath()); } catch (DataSourceConnectorException e) { throw new RedirectorDataSourceException(e); } } SimpleDAO(Class<T> clazz,
Serializer marshalling,
IDataSourceConnector connector,
IPathHelper pathHelper,
boolean compressed,
boolean useCache); @Override T get(); @Override void save(T data); @Override void addCacheListener(ICacheListener listener); @Override synchronized void rebuildCache(); @Override void close(); }
|
@Test public void testSave() throws Exception { String path = "/path"; String resultSerialized = "testModel"; setupPathHelperReturn(path); setupSerialize(resultSerialized); testee.save(new TestModel(ANY_ID)); verifySave(resultSerialized, path); }
@Test public void testSaveExceptionHappens() throws Exception { exception.expect(RedirectorDataSourceException.class); String path = "/path"; String resultSerialized = "testModel"; setupPathHelperReturn(path); setupSerialize(resultSerialized); setupExceptionOnSave(new RedirectorDataSourceException("Test")); testee.save(new TestModel(ANY_ID)); }
@Test public void testSaveNoConnection() throws Exception { exception.expect(RedirectorDataSourceException.class); String path = "/path"; String resultSerialized = "testModel"; setupPathHelperReturn(path); setupSerialize(resultSerialized); setupExceptionOnSave(new RedirectorDataSourceException(new Exception())); testee.save(new TestModel(ANY_ID)); }
@Test public void testSaveCantSerialize() throws Exception { exception.expect(SerializerException.class); String path = "/path"; setupPathHelperReturn(path); setupSerializeThrowsException(); testee.save(new TestModel(ANY_ID)); }
|
TransactionalDAO implements ITransactionalDAO { @Override public ITransaction beginTransaction() { return new Transaction(); } TransactionalDAO(IDataSourceConnector connector, Serializer serializer, IRegisteringDAOFactory daoFactory); @Override ITransaction beginTransaction(); }
|
@Test public void testCommitAndRebuildCache() throws Exception { ICacheableDAO mockCacheableDAO = mock(ICacheableDAO.class); IDataSourceConnector.Transaction mockTransaction = mock(IDataSourceConnector.Transaction.class); when(connector.createTransaction()).thenReturn(mockTransaction); when(serializer.serialize(anyObject(), anyBoolean())).thenReturn(ANY_SERIALIZED_DATA); when(daoFactory.getRegisteredCacheableDAO(any(EntityType.class))).thenReturn(mockCacheableDAO); ITransactionalDAO.ITransaction transaction = testee.beginTransaction(); transaction.save(new IfExpression(), EntityType.RULE, ANY_SERVICE, ANY_ID); transaction.save(new Server(), EntityType.SERVER, ANY_SERVICE, ANY_ID); transaction.save(new Whitelisted(), EntityType.WHITELIST, ANY_SERVICE); transaction.operationByActionType(new IfExpression(), EntityType.URL_RULE, ANY_SERVICE, ANY_ID, ActionType.DELETE); transaction.incVersion(EntityType.MODEL_CHANGED, ANY_SERVICE); transaction.commit(); verify(mockTransaction, times(1)).commit(); }
@Test(expected = RedirectorDataSourceException.class) public void testExceptionOnSerialize() throws Exception { when(serializer.serialize(anyObject(), anyBoolean())).thenReturn(null); ITransactionalDAO.ITransaction transaction = testee.beginTransaction(); transaction.save(new IfExpression(), EntityType.RULE, ANY_SERVICE, ANY_ID); }
|
SimpleServiceDAO extends BaseDAO<T> implements ISimpleServiceDAO<T>, ICacheableDAO { @Override public T get(String serviceName) { try { return deserializeOrReturnNull(getCache(serviceName).getCurrentData()); } catch (DataSourceConnectorException e) { throw new RedirectorDataSourceException(e); } } SimpleServiceDAO(Class<T> clazz,
Serializer marshalling,
IDataSourceConnector connector,
IPathHelper pathHelper,
boolean isCompressed,
boolean useCache,
boolean useCacheWhenNotConnectedToDataSource); SimpleServiceDAO(Class<T> clazz,
Serializer marshalling,
IDataSourceConnector zookeeperConnector,
IPathHelper pathHelper,
boolean isCompressed,
boolean useCache); @Override T get(String serviceName); @Override void save(T data, String serviceName); @Override void delete(String serviceName); @Override int getObjectVersion(String serviceName); @Override synchronized void rebuildCache(); @Override void addCacheListener(String serviceName, ICacheListener listener); @Override void close(); }
|
@Test public void testGet() throws Exception { String id = "id"; String resultSerialized = "testModel"; setupCacheReturnResult(resultSerialized); setupDeserialize(resultSerialized, new TestModel(id)); TestModel result = testee.get(ANY_SERVICE); Assert.assertEquals(id, result.getId()); }
@Test(expected = RedirectorDataSourceException.class) public void testGetExceptionHappens() throws Exception { setupExceptionOnGetOne(new RedirectorDataSourceException(new Exception())); testee.get(ANY_SERVICE); }
@Test(expected = RedirectorNoConnectionToDataSourceException.class) public void testGetNoConnection() throws Exception { setupExceptionOnGetOne(new RedirectorNoConnectionToDataSourceException(new KeeperException.ConnectionLossException())); testee.get(ANY_SERVICE); }
@Test public void testGetCantDeserialize() throws Exception { String resultSerialized = "testModel"; setupCacheReturnResult(resultSerialized); setupDeserializeThrowsException(); TestModel result = testee.get(ANY_SERVICE); Assert.assertNull(result); }
|
NamespacesChangesService { public NamespaceChangesStatus cancelAll(String serviceName) { NamespaceChangesStatus namespaceChangesStatus = getNamespaceChangesStatus(serviceName); namespaceChangesStatus.clear(); save(serviceName, namespaceChangesStatus); return namespaceChangesStatus; } void save(String serviceName, NamespaceChangesStatus namespaceChangesStatus); NamespaceChangesStatus getNamespaceChangesStatus(String serviceName); NamespaceChangesStatus approve(String serviceName, NamespacedList namespacedList); NamespaceChangesStatus cancelAll(String serviceName); NamespaceChangesStatus cancel(String serviceName, NamespacedList namespacedList); NamespaceChangesStatus approveAll(String serviceName); }
|
@Test public void cancelAllTest() { NamespaceChangesStatus namespacesChangesStatusReturned = namespacesChangesService.cancelAll(SERVICE_NAME); Assert.assertEquals(0, namespacesChangesStatusReturned.getNamespaceChanges().size()); verify(namespacedListsService, never()).addNamespacedList(namespacedList1); verify(namespacedListsService, never()).addNamespacedList(namespacedList2); verify(namespacedListsService, never()).deleteNamespacedList(namespacedList3.getName()); }
|
SimpleServiceDAO extends BaseDAO<T> implements ISimpleServiceDAO<T>, ICacheableDAO { @Override public void save(T data, String serviceName) throws SerializerException { try { save(serialize(data), pathHelper.getPathByService(serviceName)); rebuildCache(serviceName); } catch (DataSourceConnectorException e){ throw new RedirectorDataSourceException(e); } } SimpleServiceDAO(Class<T> clazz,
Serializer marshalling,
IDataSourceConnector connector,
IPathHelper pathHelper,
boolean isCompressed,
boolean useCache,
boolean useCacheWhenNotConnectedToDataSource); SimpleServiceDAO(Class<T> clazz,
Serializer marshalling,
IDataSourceConnector zookeeperConnector,
IPathHelper pathHelper,
boolean isCompressed,
boolean useCache); @Override T get(String serviceName); @Override void save(T data, String serviceName); @Override void delete(String serviceName); @Override int getObjectVersion(String serviceName); @Override synchronized void rebuildCache(); @Override void addCacheListener(String serviceName, ICacheListener listener); @Override void close(); }
|
@Test public void testSave() throws Exception { String path = "/path"; String resultSerialized = "testModel"; setupPathHelperReturn(path); setupSerialize(resultSerialized); testee.save(new TestModel(ANY_ID), ANY_SERVICE); verifySave(resultSerialized, path); verify(cacheWrapper, times(1)).rebuild(); }
@Test(expected = RedirectorDataSourceException.class) public void testSaveExceptionHappens() throws Exception { String path = "/path"; String resultSerialized = "testModel"; setupPathHelperReturn(path); setupSerialize(resultSerialized); setupExceptionOnSave(new RedirectorDataSourceException(new Exception())); testee.save(new TestModel(ANY_ID), ANY_SERVICE); }
@Test(expected = RedirectorDataSourceException.class) public void testSaveNoConnection() throws Exception { String path = "/path"; String resultSerialized = "testModel"; setupPathHelperReturn(path); setupSerialize(resultSerialized); setupExceptionOnSave(new RedirectorDataSourceException(new Exception())); testee.save(new TestModel(ANY_ID), ANY_SERVICE); }
@Test(expected = SerializerException.class) public void testSaveCantSerialize() throws Exception { String path = "/path"; setupPathHelperReturn(path); setupSerializeThrowsException(); testee.save(new TestModel(ANY_ID), ANY_SERVICE); }
|
SimpleServiceDAO extends BaseDAO<T> implements ISimpleServiceDAO<T>, ICacheableDAO { @Override public void delete(String serviceName) { try { deleteByPath(pathHelper.getPathByService(serviceName)); rebuildCache(serviceName); } catch (DataSourceConnectorException e){ throw new RedirectorDataSourceException(e); } } SimpleServiceDAO(Class<T> clazz,
Serializer marshalling,
IDataSourceConnector connector,
IPathHelper pathHelper,
boolean isCompressed,
boolean useCache,
boolean useCacheWhenNotConnectedToDataSource); SimpleServiceDAO(Class<T> clazz,
Serializer marshalling,
IDataSourceConnector zookeeperConnector,
IPathHelper pathHelper,
boolean isCompressed,
boolean useCache); @Override T get(String serviceName); @Override void save(T data, String serviceName); @Override void delete(String serviceName); @Override int getObjectVersion(String serviceName); @Override synchronized void rebuildCache(); @Override void addCacheListener(String serviceName, ICacheListener listener); @Override void close(); }
|
@Test public void testDelete() throws Exception { String path = "/path"; setupPathHelperReturn(path); testee.delete(ANY_SERVICE); verify(connector, times(1)).delete(path); verify(cacheWrapper, times(1)).rebuild(); }
@Test(expected = RedirectorDataSourceException.class) public void testDeleteExceptionHappens() throws Exception { String path = "/path"; setupPathHelperReturn(path); setupExceptionOnDelete(new RedirectorDataSourceException(new Exception())); testee.delete(ANY_SERVICE); }
@Test(expected = RedirectorNoConnectionToDataSourceException.class) public void testDeleteNoConnection() throws Exception { String path = "/path"; setupPathHelperReturn(path); setupExceptionOnDelete(new RedirectorNoConnectionToDataSourceException(new Exception())); testee.delete(ANY_SERVICE); }
|
SimpleServiceDAO extends BaseDAO<T> implements ISimpleServiceDAO<T>, ICacheableDAO { @Override public int getObjectVersion(String serviceName) { try { return getCache(serviceName).getCurrentDataVersion(); } catch (DataSourceConnectorException e) { throw new RedirectorDataSourceException(e); } } SimpleServiceDAO(Class<T> clazz,
Serializer marshalling,
IDataSourceConnector connector,
IPathHelper pathHelper,
boolean isCompressed,
boolean useCache,
boolean useCacheWhenNotConnectedToDataSource); SimpleServiceDAO(Class<T> clazz,
Serializer marshalling,
IDataSourceConnector zookeeperConnector,
IPathHelper pathHelper,
boolean isCompressed,
boolean useCache); @Override T get(String serviceName); @Override void save(T data, String serviceName); @Override void delete(String serviceName); @Override int getObjectVersion(String serviceName); @Override synchronized void rebuildCache(); @Override void addCacheListener(String serviceName, ICacheListener listener); @Override void close(); }
|
@Test public void testGetObjectVersion() throws Exception { int version = 5; String path = "/path"; setupPathHelperReturn(path); setupReturnVersion(version); int result = testee.getObjectVersion(ANY_SERVICE); Assert.assertEquals(version, result); }
@Test(expected = RedirectorDataSourceException.class) public void testGetObjectVersionExceptionHappens() throws Exception { String path = "/path"; setupPathHelperReturn(path); setupVersionThrowsException(new RedirectorDataSourceException(new Exception())); testee.getObjectVersion(ANY_SERVICE); }
@Test(expected = RedirectorNoNodeInPathException.class) public void testGetObjectVersionNoConnection() throws Exception { String path = "/path"; setupPathHelperReturn(path); setupVersionThrowsException(new RedirectorNoNodeInPathException(new KeeperException.ConnectionLossException())); testee.getObjectVersion(ANY_SERVICE); }
|
StacksService implements IStacksService { @Override public ServicePaths getStacksForService(String serviceName) { Paths stacksWithNodesCount = getPathsForService(serviceName); return new ServicePaths(Collections.singletonList(stacksWithNodesCount)); } @PostConstruct void init(); @Override ServicePaths getStacksForService(String serviceName); @Override ServicePaths updateStacksForService(String serviceName, ServicePaths servicePaths, Whitelisted whitelisted); @Override Set<String> getAllServiceNames(); @Override Boolean isServiceExists(String serviceName); @Override ServicePaths getStacksForAllServices(); @Override Set<PathItem> getActiveStacksAndFlavors(String serviceName); Set<PathItem> getActiveStacksAndFlavors(String serviceName, ServicePaths servicePaths); @Override HostIPsListWrapper getHostsForStackOnlyAndService(String stackName, String serviceName); @Override HostIPsListWrapper getRandomHostForStackOnlyAndService(String stackOnlyPath, String serviceName); @Override HostIPsListWrapper getHostsForStackAndService(String stackName, String serviceName); @Override HostIPsListWrapper getRandomHostForStackAndService(String stackName, String serviceName); @Override HostIPsListWrapper getHostsForFlavorAndService(String flavorName, String serviceName); @Override HostIPsListWrapper getRandomHostForFlavorAndService(String flavorName, String serviceName); @Override Set<StackData> getAllStacksAndHosts(String serviceName); Boolean isStackNameWithoutFlavor(String stackName); @Override HostIPsListWrapper getAddressByStackOrFlavor(String appName, String stackName, String flavorName); @Override HostIPsListWrapper getRandomAddressByStackOrFlavor(String serviceName, String stackName, String flavorName); @Override void deleteStack(String serviceName, String dataCenter, String availabilityZone, String flavor); @Override synchronized void deleteStacks(Paths paths); void setWhiteListService(IWhiteListService whiteListService); void setInitialDelay(long initialDelay); void setRefreshDelay(long refreshDelay); }
|
@Test public void testGetStacksForService() throws Exception { String serviceName = "xreGuide"; when(stacksDAO.getAllStackPaths()).thenReturn( getStackPaths("/po/poc1/1.50/xreGuide", "/po/poc2/1.50/xreGuide", "/po/poc1/1.52/xreApp")); when(stacksDAO.getHostsCount(new XreStackPath("/po/poc1/1.50/xreGuide"))).thenReturn(5); when(stacksDAO.getHostsCount(new XreStackPath("/po/poc2/1.50/xreGuide"))).thenReturn(6); setupWhitelistedService(); ServicePaths result = testee.getStacksForService(serviceName); Assert.assertEquals(1, result.getPaths().size()); Paths paths = result.getPaths().get(0); Assert.assertEquals(serviceName, paths.getServiceName()); Assert.assertEquals(1, paths.getFlavors().size()); Assert.assertEquals(2, paths.getStacks().size()); verifyPathItem("1.50", 11, paths.getFlavors().get(0)); verifyPathItem("/po/poc1/1.50", 5, paths.getStacks().get(0)); verifyPathItem("/po/poc2/1.50", 6, paths.getStacks().get(1)); }
@Test public void testGetStacksForServiceWithWhitelistedNodes() throws Exception { String serviceName = "xreGuide"; when(stacksDAO.getAllStackPaths()).thenReturn( getStackPaths("/po/poc1/1.50/xreGuide", "/po/poc2/1.50/xreGuide", "/po/poc1/1.52/xreApp")); when(stacksDAO.getHostsCount(new XreStackPath("/po/poc1/1.50/xreGuide"))).thenReturn(5); when(stacksDAO.getHostsCount(new XreStackPath("/po/poc2/1.50/xreGuide"))).thenReturn(6); setupWhitelistedService("/po/poc1"); ServicePaths result = testee.getStacksForService(serviceName); Assert.assertEquals(1, result.getPaths().size()); Paths paths = result.getPaths().get(0); Assert.assertEquals(serviceName, paths.getServiceName()); Assert.assertEquals(1, paths.getFlavors().size()); Assert.assertEquals(2, paths.getStacks().size()); verifyPathItem("1.50", 11, 5, paths.getFlavors().get(0)); verifyPathItem("/po/poc1/1.50", 5, 5, paths.getStacks().get(0)); verifyPathItem("/po/poc2/1.50", 6, 0, paths.getStacks().get(1)); }
|
StacksDAO implements IStacksDAO { @Override public Set<XreStackPath> getAllStackPaths() { return stacksCache.getAllStackPaths(); } StacksDAO(IDataSourceConnector connector); @Override Set<XreStackPath> getAllStackPaths(); @Override Set<XreStackPath> getAllStackPaths(final Set<String> applicationsToExclude); @Override Collection<HostIPs> getHosts(XreStackPath path); @Override Collection<HostIPs> getHostsByStackOnlyPath(XreStackPath path); @Override List<String> getFlavorsByStackOnlyPath(XreStackPath path); @Override HostIPs getHostByIndex(XreStackPath path, int index); @Override void deleteStackPath(XreStackPath xreStackPath); @Override int getHostsCount(XreStackPath path); @Override Set<String> getAllAppNamesRegisteredInStacks(); @Override void addCacheListener(ICacheListener listener); }
|
@Test public void testGetAllStackPaths() throws Exception { when(connector.getBasePath()).thenReturn(""); setupCacheResult(STACKS_PATH, "PO", "BR"); setupCacheResult(STACKS_PATH + "/PO", "POC1", "POC2"); setupCacheResult(STACKS_PATH + "/PO/POC1", "1.40"); setupCacheResult(STACKS_PATH + "/PO/POC1/1.40", "xreGuide"); setupCacheResult(STACKS_PATH + "/PO/POC2", "1.40", "1.41"); setupCacheResult(STACKS_PATH + "/PO/POC2/1.40", "xreGuide", "pandora"); setupCacheResult(STACKS_PATH + "/PO/POC2/1.41", "xreGuide", "sports"); setupCacheResult(STACKS_PATH + "/BR", "BRC1", "BRC2"); setupCacheResult(STACKS_PATH + "/BR/BRC2", "1.41", "1.42"); setupCacheResult(STACKS_PATH + "/BR/BRC2/1.41", "xreGuide"); StacksDAO testee = new StacksDAO(connector); XreStackPath[] result = testee.getAllStackPaths().toArray(new XreStackPath[]{}); Assert.assertEquals("/PO/POC1/1.40/xreGuide", result[0].getPath()); Assert.assertEquals("/PO/POC2/1.40/xreGuide", result[1].getPath()); Assert.assertEquals("/PO/POC2/1.40/pandora", result[2].getPath()); Assert.assertEquals("/PO/POC2/1.41/xreGuide", result[3].getPath()); Assert.assertEquals("/PO/POC2/1.41/sports", result[4].getPath()); Assert.assertEquals("/BR/BRC2/1.41/xreGuide", result[5].getPath()); }
@Test public void testGetAllStackPathsWithBasePath() throws Exception { when(connector.getBasePath()).thenReturn("/base"); setupCacheResult("/base" + STACKS_PATH, "PO", "BR"); setupCacheResult("/base" + STACKS_PATH + "/PO", "POC1", "POC2"); setupCacheResult("/base" + STACKS_PATH + "/PO/POC1", "1.40"); setupCacheResult("/base" + STACKS_PATH + "/PO/POC1/1.40", "xreGuide"); StacksDAO testee = new StacksDAO(connector); XreStackPath[] result = testee.getAllStackPaths().toArray(new XreStackPath[]{}); Assert.assertEquals("/PO/POC1/1.40/xreGuide", result[0].getPath()); }
|
StacksDAO implements IStacksDAO { @Override public Collection<HostIPs> getHosts(XreStackPath path) { return stacksCache.getHostsRunningAppVersionOnStack(path); } StacksDAO(IDataSourceConnector connector); @Override Set<XreStackPath> getAllStackPaths(); @Override Set<XreStackPath> getAllStackPaths(final Set<String> applicationsToExclude); @Override Collection<HostIPs> getHosts(XreStackPath path); @Override Collection<HostIPs> getHostsByStackOnlyPath(XreStackPath path); @Override List<String> getFlavorsByStackOnlyPath(XreStackPath path); @Override HostIPs getHostByIndex(XreStackPath path, int index); @Override void deleteStackPath(XreStackPath xreStackPath); @Override int getHostsCount(XreStackPath path); @Override Set<String> getAllAppNamesRegisteredInStacks(); @Override void addCacheListener(ICacheListener listener); }
|
@Test public void testGetHosts() throws Exception { String path = "/PO/POC1/1.40/xreGuide"; when(connector.getBasePath()).thenReturn(""); setupGetChildrenResult(STACKS_PATH + path, Arrays.asList("host1", "host2")); setupGetDataResult(STACKS_PATH + path + "/host1", "host1Data"); setupHostDeserializeResult("host1Data", new HostIPs("host1ipv4", "host1ipv6")); setupGetDataResult(STACKS_PATH + path + "/host2", "host2Data"); setupHostDeserializeResult("host2Data", new HostIPs("host2ipv4", "host2ipv6")); setupNodeExists(STACKS_PATH + path, true); StacksDAO testee = new StacksDAO(connector); HostIPs[] result = testee.getHosts(new XreStackPath(path)).toArray(new HostIPs[]{}); Assert.assertEquals("host1ipv4", result[0].getIpV4Address()); Assert.assertEquals("host1ipv6", result[0].getIpV6Address()); Assert.assertEquals("host2ipv4", result[1].getIpV4Address()); Assert.assertEquals("host2ipv6", result[1].getIpV6Address()); }
@Test public void testGetHostsFromCache() throws Exception { String path = "/PO/POC1/1.40/xreGuide"; when(connector.isCacheHosts()).thenReturn(true); when(connector.getBasePath()).thenReturn(""); setupGetRawHostsResult(STACKS_PATH + path, Arrays.asList("host1Data", "host2Data")); setupHostDeserializeResult("host1Data", new HostIPs("host1ipv4", "host1ipv6")); setupHostDeserializeResult("host2Data", new HostIPs("host2ipv4", "host2ipv6")); StacksDAO testee = new StacksDAO(connector); HostIPs[] result = testee.getHosts(new XreStackPath(path)).toArray(new HostIPs[]{}); Assert.assertEquals("host1ipv4", result[0].getIpV4Address()); Assert.assertEquals("host1ipv6", result[0].getIpV6Address()); Assert.assertEquals("host2ipv4", result[1].getIpV4Address()); Assert.assertEquals("host2ipv6", result[1].getIpV6Address()); }
@Test public void testGetHostsSkipsNoNodeInZookeeperException() throws Exception { String path = "/PO/POC1/1.40/xreGuide"; when(connector.getBasePath()).thenReturn(""); setupGetChildrenResult(STACKS_PATH + path, Arrays.asList("host1", "host2")); setupGetDataResult(STACKS_PATH + path + "/host1", "host1Data"); setupHostDeserializeResult("host1Data", new HostIPs("host1ipv4", "host1ipv6")); setupGetDataThrowsException(STACKS_PATH + path + "/host2", new NoNodeInZookeeperException()); setupNodeExists(STACKS_PATH + path, true); StacksDAO testee = new StacksDAO(connector); HostIPs[] result = testee.getHosts(new XreStackPath(path)).toArray(new HostIPs[]{}); Assert.assertEquals(1, result.length); Assert.assertEquals("host1ipv4", result[0].getIpV4Address()); Assert.assertEquals("host1ipv6", result[0].getIpV6Address()); }
|
StacksDAO implements IStacksDAO { @Override public void deleteStackPath(XreStackPath xreStackPath){ stacksDeleter.deleteStackPath(xreStackPath); } StacksDAO(IDataSourceConnector connector); @Override Set<XreStackPath> getAllStackPaths(); @Override Set<XreStackPath> getAllStackPaths(final Set<String> applicationsToExclude); @Override Collection<HostIPs> getHosts(XreStackPath path); @Override Collection<HostIPs> getHostsByStackOnlyPath(XreStackPath path); @Override List<String> getFlavorsByStackOnlyPath(XreStackPath path); @Override HostIPs getHostByIndex(XreStackPath path, int index); @Override void deleteStackPath(XreStackPath xreStackPath); @Override int getHostsCount(XreStackPath path); @Override Set<String> getAllAppNamesRegisteredInStacks(); @Override void addCacheListener(ICacheListener listener); }
|
@Test public void testDeleteStackPath() throws Exception { when(connector.getBasePath()).thenReturn(""); when(connector.isPathExists(anyString())).thenReturn(true); setupGetChildrenResult(STACKS_PATH + "/PO/POC1/1.40/xreGuide", Collections.<String>emptyList()); setupGetChildrenResult(STACKS_PATH + "/PO/POC1/1.40", Collections.<String>emptyList()); setupGetChildrenResult(STACKS_PATH + "/PO/POC1", Collections.<String>emptyList()); setupGetChildrenResult(STACKS_PATH + "/PO", Collections.<String>emptyList()); StacksDAO testee = new StacksDAO(connector); testee.deleteStackPath(new XreStackPath("/PO/POC1/1.40/xreGuide")); verify(connector, times(1)).delete(STACKS_PATH + "/PO/POC1/1.40/xreGuide"); verify(connector, times(1)).delete(STACKS_PATH + "/PO/POC1/1.40"); verify(connector, times(1)).delete(STACKS_PATH + "/PO/POC1"); verify(connector, times(1)).delete(STACKS_PATH + "/PO"); }
@Test public void testDeleteStackPathNodeHasChildren() throws Exception { when(connector.getBasePath()).thenReturn(""); when(connector.isPathExists(anyString())).thenReturn(true); setupGetChildrenResult(STACKS_PATH + "/PO/POC1/1.40/xreGuide", Collections.<String>emptyList()); setupGetChildrenResult(STACKS_PATH + "/PO/POC1/1.40", Collections.<String>emptyList()); setupGetChildrenResult(STACKS_PATH + "/PO/POC1", Collections.<String>emptyList()); setupGetChildrenResult(STACKS_PATH + "/PO", Arrays.asList("POC2", "POC3")); StacksDAO testee = new StacksDAO(connector); testee.deleteStackPath(new XreStackPath("/PO/POC1/1.40/xreGuide")); verify(connector, times(1)).delete(STACKS_PATH + "/PO/POC1/1.40/xreGuide"); verify(connector, times(1)).delete(STACKS_PATH + "/PO/POC1/1.40"); verify(connector, times(1)).delete(STACKS_PATH + "/PO/POC1"); verify(connector, never()).delete(STACKS_PATH + "/PO"); }
|
StacksDAO implements IStacksDAO { @Override public int getHostsCount(XreStackPath path) { try { return stacksCache.getHostsCount(path); } catch (DataSourceConnectorException e) { throw new RedirectorDataSourceException("failed to get hosts count", e); } } StacksDAO(IDataSourceConnector connector); @Override Set<XreStackPath> getAllStackPaths(); @Override Set<XreStackPath> getAllStackPaths(final Set<String> applicationsToExclude); @Override Collection<HostIPs> getHosts(XreStackPath path); @Override Collection<HostIPs> getHostsByStackOnlyPath(XreStackPath path); @Override List<String> getFlavorsByStackOnlyPath(XreStackPath path); @Override HostIPs getHostByIndex(XreStackPath path, int index); @Override void deleteStackPath(XreStackPath xreStackPath); @Override int getHostsCount(XreStackPath path); @Override Set<String> getAllAppNamesRegisteredInStacks(); @Override void addCacheListener(ICacheListener listener); }
|
@Test public void testGetHostsCount() throws Exception { String path = "/PO/POC1/1.40/xreGuide"; when(connector.getBasePath()).thenReturn("/base"); setupGetChildrenResult("/base" + STACKS_PATH + path, Arrays.asList("host1", "host2", "host3")); setupNodeExists("/base" + STACKS_PATH + path, true); StacksDAO testee = new StacksDAO(connector); int result = testee.getHostsCount(new XreStackPath(path)); Assert.assertEquals(3, result); }
|
ListDAO extends BaseListDAO<T> implements IListDAO<T> { @Override public T getById(String id) { try { return getByPath(pathHelper.getPath(id), getCache()); } catch (DataSourceConnectorException e) { throw new RedirectorDataSourceException(e); } } ListDAO(Class<T> clazz,
Serializer marshalling,
IDataSourceConnector connector,
IPathHelper pathHelper,
boolean isCompressed,
boolean useCache); @Override List<T> getAll(); @Override List<String> getAllIDs(); @Override T getById(String id); @Override void saveById(T data, String id); @Override void deleteById(String id); @Override void addCacheListener(ICacheListener listener); }
|
@Test public void testGetById() throws Exception { String id = "id"; String resultSerialized = "testModel"; setupCacheReturnOne(resultSerialized); setupDeserialize(resultSerialized, new TestModel(id)); TestModel result = testee.getById(id); Assert.assertEquals(id, result.getId()); }
@Test(expected = RedirectorDataSourceException.class) public void testGetByIdExceptionHappens() throws Exception { setupExceptionOnGetOne(new RedirectorDataSourceException(new Exception())); testee.getById(ANY_ID); }
@Test(expected = RedirectorNoConnectionToDataSourceException.class) public void testGetByIdNoConnection() throws Exception { setupExceptionOnGetOne(new RedirectorNoConnectionToDataSourceException(new KeeperException.ConnectionLossException())); testee.getById(ANY_ID); }
@Test public void testGetByIdCantDeserialize() throws Exception { String id = "id"; String resultSerialized = "testModel"; setupCacheReturnOne(resultSerialized); setupDeserializeThrowsException(); TestModel result = testee.getById(id); Assert.assertNull(result); }
|
ListDAO extends BaseListDAO<T> implements IListDAO<T> { @Override public List<T> getAll() { try { return getAll(getCache()); } catch (DataSourceConnectorException e){ throw new RedirectorDataSourceException(e); } } ListDAO(Class<T> clazz,
Serializer marshalling,
IDataSourceConnector connector,
IPathHelper pathHelper,
boolean isCompressed,
boolean useCache); @Override List<T> getAll(); @Override List<String> getAllIDs(); @Override T getById(String id); @Override void saveById(T data, String id); @Override void deleteById(String id); @Override void addCacheListener(ICacheListener listener); }
|
@Test public void testGetAll() throws Exception { String id = "id"; String resultSerialized = "testModel"; setupCacheReturnMap(id, resultSerialized); setupDeserialize(resultSerialized, new TestModel(id)); List<TestModel> result = testee.getAll(); Assert.assertEquals(id, result.get(0).getId()); }
@Test(expected = RedirectorDataSourceException.class) public void testGetAllExceptionHappens() throws Exception { setupExceptionOnGetAll(new RedirectorDataSourceException(new Exception())); testee.getAll(); }
@Test(expected = RedirectorNoConnectionToDataSourceException.class) public void testGetAllNoConnection() throws Exception { setupExceptionOnGetAll(new RedirectorNoConnectionToDataSourceException(new KeeperException.ConnectionLossException())); testee.getAll(); }
@Test public void testGetAllCantSerialize() throws Exception { String id = "id"; String resultSerialized = "testModel"; setupCacheReturnMap(id, resultSerialized); setupDeserializeThrowsException(); List<TestModel> result = testee.getAll(); Assert.assertEquals(0, result.size()); }
|
ListDAO extends BaseListDAO<T> implements IListDAO<T> { @Override public void saveById(T data, String id) throws SerializerException { try { saveByPath(data, pathHelper.getPath(id), getCache()); } catch (DataSourceConnectorException e) { throw new RedirectorDataSourceException(e); } } ListDAO(Class<T> clazz,
Serializer marshalling,
IDataSourceConnector connector,
IPathHelper pathHelper,
boolean isCompressed,
boolean useCache); @Override List<T> getAll(); @Override List<String> getAllIDs(); @Override T getById(String id); @Override void saveById(T data, String id); @Override void deleteById(String id); @Override void addCacheListener(ICacheListener listener); }
|
@Test public void testSaveById() throws Exception { String path = "/path"; String resultSerialized = "testModel"; setupPathHelperReturn(path); setupSerialize(resultSerialized); testee.saveById(new TestModel(ANY_ID), ANY_ID); if (isCompressed) verify(connector, times(1)).saveCompressed(resultSerialized, path); else verify(connector, times(1)).save(resultSerialized, path); verify(getWrapper()).rebuildNode(path); }
@Test(expected = RedirectorDataSourceException.class) public void testSaveByIdExceptionHappens() throws Exception { String path = "/path"; String resultSerialized = "testModel"; setupPathHelperReturn(path); setupSerialize(resultSerialized); setupExceptionOnSave(new RedirectorDataSourceException("Test")); testee.saveById(new TestModel(ANY_ID), ANY_ID); }
@Test(expected = RedirectorDataSourceException.class) public void testSaveByIdNoConnection() throws Exception { String path = "/path"; String resultSerialized = "testModel"; setupPathHelperReturn(path); setupSerialize(resultSerialized); setupExceptionOnSave(new RedirectorDataSourceException(new Exception())); testee.saveById(new TestModel(ANY_ID), ANY_ID); }
@Test(expected = SerializerException.class) public void testSaveByIdCantSerialize() throws Exception { String path = "/path"; setupPathHelperReturn(path); setupSerializeThrowsException(); testee.saveById(new TestModel(ANY_ID), ANY_ID); }
|
StacksService implements IStacksService { @Override public Set<String> getAllServiceNames() { return stacksDAO.getAllAppNamesRegisteredInStacks(); } @PostConstruct void init(); @Override ServicePaths getStacksForService(String serviceName); @Override ServicePaths updateStacksForService(String serviceName, ServicePaths servicePaths, Whitelisted whitelisted); @Override Set<String> getAllServiceNames(); @Override Boolean isServiceExists(String serviceName); @Override ServicePaths getStacksForAllServices(); @Override Set<PathItem> getActiveStacksAndFlavors(String serviceName); Set<PathItem> getActiveStacksAndFlavors(String serviceName, ServicePaths servicePaths); @Override HostIPsListWrapper getHostsForStackOnlyAndService(String stackName, String serviceName); @Override HostIPsListWrapper getRandomHostForStackOnlyAndService(String stackOnlyPath, String serviceName); @Override HostIPsListWrapper getHostsForStackAndService(String stackName, String serviceName); @Override HostIPsListWrapper getRandomHostForStackAndService(String stackName, String serviceName); @Override HostIPsListWrapper getHostsForFlavorAndService(String flavorName, String serviceName); @Override HostIPsListWrapper getRandomHostForFlavorAndService(String flavorName, String serviceName); @Override Set<StackData> getAllStacksAndHosts(String serviceName); Boolean isStackNameWithoutFlavor(String stackName); @Override HostIPsListWrapper getAddressByStackOrFlavor(String appName, String stackName, String flavorName); @Override HostIPsListWrapper getRandomAddressByStackOrFlavor(String serviceName, String stackName, String flavorName); @Override void deleteStack(String serviceName, String dataCenter, String availabilityZone, String flavor); @Override synchronized void deleteStacks(Paths paths); void setWhiteListService(IWhiteListService whiteListService); void setInitialDelay(long initialDelay); void setRefreshDelay(long refreshDelay); }
|
@Test public void testGetAllServiceNames() throws Exception { when(stacksDAO.getAllAppNamesRegisteredInStacks()).thenReturn( new HashSet<>(Arrays.asList("xreGuide", "xreApp"))); Collection<String> allNames = testee.getAllServiceNames(); Assert.assertTrue(allNames.contains("xreGuide")); Assert.assertTrue(allNames.contains("xreApp")); }
|
ListDAO extends BaseListDAO<T> implements IListDAO<T> { @Override public void deleteById(String id) { try { super.deleteByPath(pathHelper.getPath(id), getCache()); } catch (DataSourceConnectorException e) { throw new RedirectorDataSourceException(e); } } ListDAO(Class<T> clazz,
Serializer marshalling,
IDataSourceConnector connector,
IPathHelper pathHelper,
boolean isCompressed,
boolean useCache); @Override List<T> getAll(); @Override List<String> getAllIDs(); @Override T getById(String id); @Override void saveById(T data, String id); @Override void deleteById(String id); @Override void addCacheListener(ICacheListener listener); }
|
@Test public void testDeleteById() throws Exception { String path = "/path"; setupPathHelperReturn(path); testee.deleteById(ANY_ID); verify(connector, times(1)).delete(path); verify(getWrapper()).rebuild(); }
@Test(expected = RedirectorDataSourceException.class) public void testDeleteByIdExceptionHappens() throws Exception { String path = "/path"; setupPathHelperReturn(path); setupExceptionOnDelete(new RedirectorDataSourceException(new Exception())); testee.deleteById(ANY_ID); }
@Test(expected = RedirectorNoConnectionToDataSourceException.class) public void testDeleteByIdNoConnection() throws Exception { String path = "/path"; setupPathHelperReturn(path); setupExceptionOnDelete(new RedirectorNoConnectionToDataSourceException(new Exception())); testee.deleteById(ANY_ID); }
|
ZookeeperConnector implements IDataSourceConnector, ConnectionStateListener { @Override public boolean isPathExists(String path) throws DataSourceConnectorException { String error = "Can't check if path: " + path + " exists"; return executeOrFailWithError(() -> isNodeExistsInternal(path), error); } @VisibleForTesting ZookeeperConnector(); @VisibleForTesting ZookeeperConnector(CuratorFramework client, String basePath, boolean cacheHosts, IPathCreator pathCreator,
IStacksCache stackCache, INodeCacheFactory nodeCacheFactory, IPathChildrenCacheFactory pathChildrenCacheFactory); ZookeeperConnector(CuratorFramework client, String basePath, boolean cacheHosts); ZookeeperConnector(CuratorFramework client, String basePath, boolean cacheHosts, Function<IServiceDiscovery, Boolean> stacksRefreshListener); ZookeeperConnector(CuratorFramework client, String basePath, boolean cacheHosts, Supplier<IStacksCache> stacksCacheFactory); ZookeeperConnector(CuratorFramework client, String basePath, boolean cacheHosts,
Supplier<IStacksCache> stacksCacheFactory, Function<IServiceDiscovery, Boolean> stacksRefreshListener); @Override void addConnectionListener(ConnectionListener listener); @Override boolean blockUntilConnectedOrTimedOut(); @Override boolean isPathExists(String path); @Override List<String> getChildren(final String path); @Override void saveCompressed(final String data, final String path); @Override void save(String data, String path); @Override void deleteWithChildren(final String path); @Override void delete(String path); @Override void create(final String path); @Override void createEphemeral(final String path); @Override Transaction createTransaction(); @Override byte[] getData(final String path); @Override byte[] getDataDecompressed(final String path); @Override int getNodeVersion(String path); @Override String getBasePath(); @Override boolean isCacheHosts(); @Override void connect(); @Override void disconnect(); @Override IStacksCache getStacksCache(); @Override void addNodeDataChangeListener(String path, IDataListener listener); @Override void addPathChildrenChangeListener(String path, IDataListener listener); @Override INodeCacheWrapper newNodeCacheWrapper(String path, boolean useCache); @Override INodeCacheWrapper newNodeCacheWrapper(String path, boolean useCache, boolean useCacheWhenNotConnectedToDataSource); @Override INodeCacheWrapper newNodeCacheWrapper(String path, boolean useCache, boolean useCacheWhenNotConnectedToDataSource, boolean isCompressed); @Override IPathChildrenCacheWrapper newPathChildrenCacheWrapper(String path, boolean useCache); @Override IPathChildrenCacheWrapper newPathChildrenCacheWrapper(String path, boolean dataIsCompressed, ThreadFactory threadFactory, boolean useCache); @Override void stateChanged(CuratorFramework client, ConnectionState newState); @Override boolean isConnected(); @Override SharedInterProcessLock createLock(String path); }
|
@Test public void testIsZNodeExists() throws Exception { String existingPath = "/test/NodeA"; setupCheckExists(existingPath, true); String nonExistingPath = "/test/NodeB"; setupCheckExists(nonExistingPath, false); Assert.assertTrue(testee.isPathExists(existingPath)); Assert.assertFalse(testee.isPathExists(nonExistingPath)); }
|
ZookeeperConnector implements IDataSourceConnector, ConnectionStateListener { @Override public List<String> getChildren(final String path) throws DataSourceConnectorException { String error = "Can't get children for path: " + path; return executeOrFailWithError(() -> getConnectedClientOrFailFast().getChildren().forPath(path) , error ); } @VisibleForTesting ZookeeperConnector(); @VisibleForTesting ZookeeperConnector(CuratorFramework client, String basePath, boolean cacheHosts, IPathCreator pathCreator,
IStacksCache stackCache, INodeCacheFactory nodeCacheFactory, IPathChildrenCacheFactory pathChildrenCacheFactory); ZookeeperConnector(CuratorFramework client, String basePath, boolean cacheHosts); ZookeeperConnector(CuratorFramework client, String basePath, boolean cacheHosts, Function<IServiceDiscovery, Boolean> stacksRefreshListener); ZookeeperConnector(CuratorFramework client, String basePath, boolean cacheHosts, Supplier<IStacksCache> stacksCacheFactory); ZookeeperConnector(CuratorFramework client, String basePath, boolean cacheHosts,
Supplier<IStacksCache> stacksCacheFactory, Function<IServiceDiscovery, Boolean> stacksRefreshListener); @Override void addConnectionListener(ConnectionListener listener); @Override boolean blockUntilConnectedOrTimedOut(); @Override boolean isPathExists(String path); @Override List<String> getChildren(final String path); @Override void saveCompressed(final String data, final String path); @Override void save(String data, String path); @Override void deleteWithChildren(final String path); @Override void delete(String path); @Override void create(final String path); @Override void createEphemeral(final String path); @Override Transaction createTransaction(); @Override byte[] getData(final String path); @Override byte[] getDataDecompressed(final String path); @Override int getNodeVersion(String path); @Override String getBasePath(); @Override boolean isCacheHosts(); @Override void connect(); @Override void disconnect(); @Override IStacksCache getStacksCache(); @Override void addNodeDataChangeListener(String path, IDataListener listener); @Override void addPathChildrenChangeListener(String path, IDataListener listener); @Override INodeCacheWrapper newNodeCacheWrapper(String path, boolean useCache); @Override INodeCacheWrapper newNodeCacheWrapper(String path, boolean useCache, boolean useCacheWhenNotConnectedToDataSource); @Override INodeCacheWrapper newNodeCacheWrapper(String path, boolean useCache, boolean useCacheWhenNotConnectedToDataSource, boolean isCompressed); @Override IPathChildrenCacheWrapper newPathChildrenCacheWrapper(String path, boolean useCache); @Override IPathChildrenCacheWrapper newPathChildrenCacheWrapper(String path, boolean dataIsCompressed, ThreadFactory threadFactory, boolean useCache); @Override void stateChanged(CuratorFramework client, ConnectionState newState); @Override boolean isConnected(); @Override SharedInterProcessLock createLock(String path); }
|
@Test public void testGetChildren() throws Exception { List<String> children = Arrays.asList("child1", "child2", "child3"); List<String> expected = Arrays.asList("child1", "child2", "child3"); setupGetChildren("/path", children); List<String> result = testee.getChildren("/path"); Assert.assertEquals(expected, result); }
|
ZookeeperConnector implements IDataSourceConnector, ConnectionStateListener { @Override public String getBasePath() { return Optional.ofNullable(basePath).orElse(""); } @VisibleForTesting ZookeeperConnector(); @VisibleForTesting ZookeeperConnector(CuratorFramework client, String basePath, boolean cacheHosts, IPathCreator pathCreator,
IStacksCache stackCache, INodeCacheFactory nodeCacheFactory, IPathChildrenCacheFactory pathChildrenCacheFactory); ZookeeperConnector(CuratorFramework client, String basePath, boolean cacheHosts); ZookeeperConnector(CuratorFramework client, String basePath, boolean cacheHosts, Function<IServiceDiscovery, Boolean> stacksRefreshListener); ZookeeperConnector(CuratorFramework client, String basePath, boolean cacheHosts, Supplier<IStacksCache> stacksCacheFactory); ZookeeperConnector(CuratorFramework client, String basePath, boolean cacheHosts,
Supplier<IStacksCache> stacksCacheFactory, Function<IServiceDiscovery, Boolean> stacksRefreshListener); @Override void addConnectionListener(ConnectionListener listener); @Override boolean blockUntilConnectedOrTimedOut(); @Override boolean isPathExists(String path); @Override List<String> getChildren(final String path); @Override void saveCompressed(final String data, final String path); @Override void save(String data, String path); @Override void deleteWithChildren(final String path); @Override void delete(String path); @Override void create(final String path); @Override void createEphemeral(final String path); @Override Transaction createTransaction(); @Override byte[] getData(final String path); @Override byte[] getDataDecompressed(final String path); @Override int getNodeVersion(String path); @Override String getBasePath(); @Override boolean isCacheHosts(); @Override void connect(); @Override void disconnect(); @Override IStacksCache getStacksCache(); @Override void addNodeDataChangeListener(String path, IDataListener listener); @Override void addPathChildrenChangeListener(String path, IDataListener listener); @Override INodeCacheWrapper newNodeCacheWrapper(String path, boolean useCache); @Override INodeCacheWrapper newNodeCacheWrapper(String path, boolean useCache, boolean useCacheWhenNotConnectedToDataSource); @Override INodeCacheWrapper newNodeCacheWrapper(String path, boolean useCache, boolean useCacheWhenNotConnectedToDataSource, boolean isCompressed); @Override IPathChildrenCacheWrapper newPathChildrenCacheWrapper(String path, boolean useCache); @Override IPathChildrenCacheWrapper newPathChildrenCacheWrapper(String path, boolean dataIsCompressed, ThreadFactory threadFactory, boolean useCache); @Override void stateChanged(CuratorFramework client, ConnectionState newState); @Override boolean isConnected(); @Override SharedInterProcessLock createLock(String path); }
|
@Test public void testGetZookeeperBasePath() throws Exception { testee = new ZookeeperConnector(client, "/test", false, pathCreator, stackCache, nodeCacheFactory, pathChildrenCacheFactory); Assert.assertEquals("/test", testee.getBasePath()); }
|
ZookeeperConnector implements IDataSourceConnector, ConnectionStateListener { @Override public byte[] getData(final String path) throws DataSourceConnectorException { String error = "Failed to get data for path " + path; return executeOrFailWithError(() -> getConnectedClientOrFailFast().getData().forPath(path), error); } @VisibleForTesting ZookeeperConnector(); @VisibleForTesting ZookeeperConnector(CuratorFramework client, String basePath, boolean cacheHosts, IPathCreator pathCreator,
IStacksCache stackCache, INodeCacheFactory nodeCacheFactory, IPathChildrenCacheFactory pathChildrenCacheFactory); ZookeeperConnector(CuratorFramework client, String basePath, boolean cacheHosts); ZookeeperConnector(CuratorFramework client, String basePath, boolean cacheHosts, Function<IServiceDiscovery, Boolean> stacksRefreshListener); ZookeeperConnector(CuratorFramework client, String basePath, boolean cacheHosts, Supplier<IStacksCache> stacksCacheFactory); ZookeeperConnector(CuratorFramework client, String basePath, boolean cacheHosts,
Supplier<IStacksCache> stacksCacheFactory, Function<IServiceDiscovery, Boolean> stacksRefreshListener); @Override void addConnectionListener(ConnectionListener listener); @Override boolean blockUntilConnectedOrTimedOut(); @Override boolean isPathExists(String path); @Override List<String> getChildren(final String path); @Override void saveCompressed(final String data, final String path); @Override void save(String data, String path); @Override void deleteWithChildren(final String path); @Override void delete(String path); @Override void create(final String path); @Override void createEphemeral(final String path); @Override Transaction createTransaction(); @Override byte[] getData(final String path); @Override byte[] getDataDecompressed(final String path); @Override int getNodeVersion(String path); @Override String getBasePath(); @Override boolean isCacheHosts(); @Override void connect(); @Override void disconnect(); @Override IStacksCache getStacksCache(); @Override void addNodeDataChangeListener(String path, IDataListener listener); @Override void addPathChildrenChangeListener(String path, IDataListener listener); @Override INodeCacheWrapper newNodeCacheWrapper(String path, boolean useCache); @Override INodeCacheWrapper newNodeCacheWrapper(String path, boolean useCache, boolean useCacheWhenNotConnectedToDataSource); @Override INodeCacheWrapper newNodeCacheWrapper(String path, boolean useCache, boolean useCacheWhenNotConnectedToDataSource, boolean isCompressed); @Override IPathChildrenCacheWrapper newPathChildrenCacheWrapper(String path, boolean useCache); @Override IPathChildrenCacheWrapper newPathChildrenCacheWrapper(String path, boolean dataIsCompressed, ThreadFactory threadFactory, boolean useCache); @Override void stateChanged(CuratorFramework client, ConnectionState newState); @Override boolean isConnected(); @Override SharedInterProcessLock createLock(String path); }
|
@Test public void testGetData() throws Exception { setupGetData("/path", "success".getBytes()); byte[] result = testee.getData("/path"); Assert.assertEquals("success", new String(result)); }
|
ZookeeperConnector implements IDataSourceConnector, ConnectionStateListener { private void save(final String data, final String path, final boolean compressed) throws DataSourceConnectorException { String error = "Can't save data for path: " + path; executeOrFailWithError( () -> { pathCreator.createPath(path); setValue(path, data, compressed); }, error); } @VisibleForTesting ZookeeperConnector(); @VisibleForTesting ZookeeperConnector(CuratorFramework client, String basePath, boolean cacheHosts, IPathCreator pathCreator,
IStacksCache stackCache, INodeCacheFactory nodeCacheFactory, IPathChildrenCacheFactory pathChildrenCacheFactory); ZookeeperConnector(CuratorFramework client, String basePath, boolean cacheHosts); ZookeeperConnector(CuratorFramework client, String basePath, boolean cacheHosts, Function<IServiceDiscovery, Boolean> stacksRefreshListener); ZookeeperConnector(CuratorFramework client, String basePath, boolean cacheHosts, Supplier<IStacksCache> stacksCacheFactory); ZookeeperConnector(CuratorFramework client, String basePath, boolean cacheHosts,
Supplier<IStacksCache> stacksCacheFactory, Function<IServiceDiscovery, Boolean> stacksRefreshListener); @Override void addConnectionListener(ConnectionListener listener); @Override boolean blockUntilConnectedOrTimedOut(); @Override boolean isPathExists(String path); @Override List<String> getChildren(final String path); @Override void saveCompressed(final String data, final String path); @Override void save(String data, String path); @Override void deleteWithChildren(final String path); @Override void delete(String path); @Override void create(final String path); @Override void createEphemeral(final String path); @Override Transaction createTransaction(); @Override byte[] getData(final String path); @Override byte[] getDataDecompressed(final String path); @Override int getNodeVersion(String path); @Override String getBasePath(); @Override boolean isCacheHosts(); @Override void connect(); @Override void disconnect(); @Override IStacksCache getStacksCache(); @Override void addNodeDataChangeListener(String path, IDataListener listener); @Override void addPathChildrenChangeListener(String path, IDataListener listener); @Override INodeCacheWrapper newNodeCacheWrapper(String path, boolean useCache); @Override INodeCacheWrapper newNodeCacheWrapper(String path, boolean useCache, boolean useCacheWhenNotConnectedToDataSource); @Override INodeCacheWrapper newNodeCacheWrapper(String path, boolean useCache, boolean useCacheWhenNotConnectedToDataSource, boolean isCompressed); @Override IPathChildrenCacheWrapper newPathChildrenCacheWrapper(String path, boolean useCache); @Override IPathChildrenCacheWrapper newPathChildrenCacheWrapper(String path, boolean dataIsCompressed, ThreadFactory threadFactory, boolean useCache); @Override void stateChanged(CuratorFramework client, ConnectionState newState); @Override boolean isConnected(); @Override SharedInterProcessLock createLock(String path); }
|
@Test public void testSaveForExistingNode() throws Exception { setupCheckExists("/path", true); testee.save("success", "/path"); verify(pathCreator, times(1)).createPath("/path"); verify(setDataBuilder, times(1)).forPath("/path", "success".getBytes()); }
@Test public void testSaveForNonExistingNode() throws Exception { setupCheckExists("/path", false); testee.save("success", "/path"); verify(pathCreator, times(1)).createPath("/path"); verify(createBuilder, times(1)).forPath("/path", "success".getBytes()); }
|
StacksService implements IStacksService { @Override public ServicePaths getStacksForAllServices(){ List<Paths> allPaths = new ArrayList<>(); for (String serviceName : getAllServiceNames()) { allPaths.add(getPathsForService(serviceName)); } return new ServicePaths(allPaths); } @PostConstruct void init(); @Override ServicePaths getStacksForService(String serviceName); @Override ServicePaths updateStacksForService(String serviceName, ServicePaths servicePaths, Whitelisted whitelisted); @Override Set<String> getAllServiceNames(); @Override Boolean isServiceExists(String serviceName); @Override ServicePaths getStacksForAllServices(); @Override Set<PathItem> getActiveStacksAndFlavors(String serviceName); Set<PathItem> getActiveStacksAndFlavors(String serviceName, ServicePaths servicePaths); @Override HostIPsListWrapper getHostsForStackOnlyAndService(String stackName, String serviceName); @Override HostIPsListWrapper getRandomHostForStackOnlyAndService(String stackOnlyPath, String serviceName); @Override HostIPsListWrapper getHostsForStackAndService(String stackName, String serviceName); @Override HostIPsListWrapper getRandomHostForStackAndService(String stackName, String serviceName); @Override HostIPsListWrapper getHostsForFlavorAndService(String flavorName, String serviceName); @Override HostIPsListWrapper getRandomHostForFlavorAndService(String flavorName, String serviceName); @Override Set<StackData> getAllStacksAndHosts(String serviceName); Boolean isStackNameWithoutFlavor(String stackName); @Override HostIPsListWrapper getAddressByStackOrFlavor(String appName, String stackName, String flavorName); @Override HostIPsListWrapper getRandomAddressByStackOrFlavor(String serviceName, String stackName, String flavorName); @Override void deleteStack(String serviceName, String dataCenter, String availabilityZone, String flavor); @Override synchronized void deleteStacks(Paths paths); void setWhiteListService(IWhiteListService whiteListService); void setInitialDelay(long initialDelay); void setRefreshDelay(long refreshDelay); }
|
@Test public void testGetStacksForAllServices() throws Exception { when(stacksDAO.getAllStackPaths()).thenReturn( getStackPaths("/po/poc1/1.50/xreGuide", "/po/poc2/1.50/xreGuide", "/po/poc1/1.52/xreApp")); when(stacksDAO.getAllAppNamesRegisteredInStacks()).thenReturn( new LinkedHashSet<>(Arrays.asList("xreGuide", "xreApp"))); when(stacksDAO.getHostsCount(new XreStackPath("/po/poc1/1.50/xreGuide"))).thenReturn(5); when(stacksDAO.getHostsCount(new XreStackPath("/po/poc2/1.50/xreGuide"))).thenReturn(6); when(stacksDAO.getHostsCount(new XreStackPath("/po/poc1/1.52/xreApp"))).thenReturn(8); setupWhitelistedService(); ServicePaths result = testee.getStacksForAllServices(); Assert.assertEquals(2, result.getPaths().size()); Paths paths = result.getPaths().get(0); Assert.assertEquals("xreGuide", paths.getServiceName()); Assert.assertEquals(1, paths.getFlavors().size()); Assert.assertEquals(2, paths.getStacks().size()); verifyPathItem("1.50", 11, paths.getFlavors().get(0)); verifyPathItem("/po/poc1/1.50", 5, paths.getStacks().get(0)); verifyPathItem("/po/poc2/1.50", 6, paths.getStacks().get(1)); paths = result.getPaths().get(1); Assert.assertEquals("xreApp", paths.getServiceName()); Assert.assertEquals(1, paths.getFlavors().size()); Assert.assertEquals(1, paths.getStacks().size()); verifyPathItem("1.52", 8, paths.getFlavors().get(0)); verifyPathItem("/po/poc1/1.52", 8, paths.getStacks().get(0)); }
|
ZookeeperConnector implements IDataSourceConnector, ConnectionStateListener { @Override public void saveCompressed(final String data, final String path) throws DataSourceConnectorException { save(data, path, true); } @VisibleForTesting ZookeeperConnector(); @VisibleForTesting ZookeeperConnector(CuratorFramework client, String basePath, boolean cacheHosts, IPathCreator pathCreator,
IStacksCache stackCache, INodeCacheFactory nodeCacheFactory, IPathChildrenCacheFactory pathChildrenCacheFactory); ZookeeperConnector(CuratorFramework client, String basePath, boolean cacheHosts); ZookeeperConnector(CuratorFramework client, String basePath, boolean cacheHosts, Function<IServiceDiscovery, Boolean> stacksRefreshListener); ZookeeperConnector(CuratorFramework client, String basePath, boolean cacheHosts, Supplier<IStacksCache> stacksCacheFactory); ZookeeperConnector(CuratorFramework client, String basePath, boolean cacheHosts,
Supplier<IStacksCache> stacksCacheFactory, Function<IServiceDiscovery, Boolean> stacksRefreshListener); @Override void addConnectionListener(ConnectionListener listener); @Override boolean blockUntilConnectedOrTimedOut(); @Override boolean isPathExists(String path); @Override List<String> getChildren(final String path); @Override void saveCompressed(final String data, final String path); @Override void save(String data, String path); @Override void deleteWithChildren(final String path); @Override void delete(String path); @Override void create(final String path); @Override void createEphemeral(final String path); @Override Transaction createTransaction(); @Override byte[] getData(final String path); @Override byte[] getDataDecompressed(final String path); @Override int getNodeVersion(String path); @Override String getBasePath(); @Override boolean isCacheHosts(); @Override void connect(); @Override void disconnect(); @Override IStacksCache getStacksCache(); @Override void addNodeDataChangeListener(String path, IDataListener listener); @Override void addPathChildrenChangeListener(String path, IDataListener listener); @Override INodeCacheWrapper newNodeCacheWrapper(String path, boolean useCache); @Override INodeCacheWrapper newNodeCacheWrapper(String path, boolean useCache, boolean useCacheWhenNotConnectedToDataSource); @Override INodeCacheWrapper newNodeCacheWrapper(String path, boolean useCache, boolean useCacheWhenNotConnectedToDataSource, boolean isCompressed); @Override IPathChildrenCacheWrapper newPathChildrenCacheWrapper(String path, boolean useCache); @Override IPathChildrenCacheWrapper newPathChildrenCacheWrapper(String path, boolean dataIsCompressed, ThreadFactory threadFactory, boolean useCache); @Override void stateChanged(CuratorFramework client, ConnectionState newState); @Override boolean isConnected(); @Override SharedInterProcessLock createLock(String path); }
|
@Test public void testSaveForExistingNodeCompressed() throws Exception { setupCheckExists("/path", true); testee.saveCompressed("success", "/path"); verify(pathCreator, times(1)).createPath("/path"); verify(setDataCompressible, times(1)).forPath("/path", "success".getBytes()); }
@Test public void testSaveForNonExistingNodeCompressed() throws Exception { setupCheckExists("/path", false); testee.saveCompressed("success", "/path"); verify(pathCreator, times(1)).createPath("/path"); verify(createCompressible, times(1)).forPath("/path", "success".getBytes()); }
|
ZookeeperConnector implements IDataSourceConnector, ConnectionStateListener { @Override public void deleteWithChildren(final String path) throws DataSourceConnectorException { String error = "Can't delete item for path: " + path; executeOrFailWithError( () -> getConnectedClientOrFailFast().delete().deletingChildrenIfNeeded().forPath(path), error); } @VisibleForTesting ZookeeperConnector(); @VisibleForTesting ZookeeperConnector(CuratorFramework client, String basePath, boolean cacheHosts, IPathCreator pathCreator,
IStacksCache stackCache, INodeCacheFactory nodeCacheFactory, IPathChildrenCacheFactory pathChildrenCacheFactory); ZookeeperConnector(CuratorFramework client, String basePath, boolean cacheHosts); ZookeeperConnector(CuratorFramework client, String basePath, boolean cacheHosts, Function<IServiceDiscovery, Boolean> stacksRefreshListener); ZookeeperConnector(CuratorFramework client, String basePath, boolean cacheHosts, Supplier<IStacksCache> stacksCacheFactory); ZookeeperConnector(CuratorFramework client, String basePath, boolean cacheHosts,
Supplier<IStacksCache> stacksCacheFactory, Function<IServiceDiscovery, Boolean> stacksRefreshListener); @Override void addConnectionListener(ConnectionListener listener); @Override boolean blockUntilConnectedOrTimedOut(); @Override boolean isPathExists(String path); @Override List<String> getChildren(final String path); @Override void saveCompressed(final String data, final String path); @Override void save(String data, String path); @Override void deleteWithChildren(final String path); @Override void delete(String path); @Override void create(final String path); @Override void createEphemeral(final String path); @Override Transaction createTransaction(); @Override byte[] getData(final String path); @Override byte[] getDataDecompressed(final String path); @Override int getNodeVersion(String path); @Override String getBasePath(); @Override boolean isCacheHosts(); @Override void connect(); @Override void disconnect(); @Override IStacksCache getStacksCache(); @Override void addNodeDataChangeListener(String path, IDataListener listener); @Override void addPathChildrenChangeListener(String path, IDataListener listener); @Override INodeCacheWrapper newNodeCacheWrapper(String path, boolean useCache); @Override INodeCacheWrapper newNodeCacheWrapper(String path, boolean useCache, boolean useCacheWhenNotConnectedToDataSource); @Override INodeCacheWrapper newNodeCacheWrapper(String path, boolean useCache, boolean useCacheWhenNotConnectedToDataSource, boolean isCompressed); @Override IPathChildrenCacheWrapper newPathChildrenCacheWrapper(String path, boolean useCache); @Override IPathChildrenCacheWrapper newPathChildrenCacheWrapper(String path, boolean dataIsCompressed, ThreadFactory threadFactory, boolean useCache); @Override void stateChanged(CuratorFramework client, ConnectionState newState); @Override boolean isConnected(); @Override SharedInterProcessLock createLock(String path); }
|
@Test public void testDeleteWithChildren() throws Exception { testee.deleteWithChildren("/path"); verify(deleteChildren, times(1)).forPath("/path"); }
|
ZookeeperConnector implements IDataSourceConnector, ConnectionStateListener { @Override public void delete(String path) throws DataSourceConnectorException { String error = "Can't delete item for path: " + path; executeOrFailWithError( () -> getConnectedClientOrFailFast().delete().forPath(path), error); } @VisibleForTesting ZookeeperConnector(); @VisibleForTesting ZookeeperConnector(CuratorFramework client, String basePath, boolean cacheHosts, IPathCreator pathCreator,
IStacksCache stackCache, INodeCacheFactory nodeCacheFactory, IPathChildrenCacheFactory pathChildrenCacheFactory); ZookeeperConnector(CuratorFramework client, String basePath, boolean cacheHosts); ZookeeperConnector(CuratorFramework client, String basePath, boolean cacheHosts, Function<IServiceDiscovery, Boolean> stacksRefreshListener); ZookeeperConnector(CuratorFramework client, String basePath, boolean cacheHosts, Supplier<IStacksCache> stacksCacheFactory); ZookeeperConnector(CuratorFramework client, String basePath, boolean cacheHosts,
Supplier<IStacksCache> stacksCacheFactory, Function<IServiceDiscovery, Boolean> stacksRefreshListener); @Override void addConnectionListener(ConnectionListener listener); @Override boolean blockUntilConnectedOrTimedOut(); @Override boolean isPathExists(String path); @Override List<String> getChildren(final String path); @Override void saveCompressed(final String data, final String path); @Override void save(String data, String path); @Override void deleteWithChildren(final String path); @Override void delete(String path); @Override void create(final String path); @Override void createEphemeral(final String path); @Override Transaction createTransaction(); @Override byte[] getData(final String path); @Override byte[] getDataDecompressed(final String path); @Override int getNodeVersion(String path); @Override String getBasePath(); @Override boolean isCacheHosts(); @Override void connect(); @Override void disconnect(); @Override IStacksCache getStacksCache(); @Override void addNodeDataChangeListener(String path, IDataListener listener); @Override void addPathChildrenChangeListener(String path, IDataListener listener); @Override INodeCacheWrapper newNodeCacheWrapper(String path, boolean useCache); @Override INodeCacheWrapper newNodeCacheWrapper(String path, boolean useCache, boolean useCacheWhenNotConnectedToDataSource); @Override INodeCacheWrapper newNodeCacheWrapper(String path, boolean useCache, boolean useCacheWhenNotConnectedToDataSource, boolean isCompressed); @Override IPathChildrenCacheWrapper newPathChildrenCacheWrapper(String path, boolean useCache); @Override IPathChildrenCacheWrapper newPathChildrenCacheWrapper(String path, boolean dataIsCompressed, ThreadFactory threadFactory, boolean useCache); @Override void stateChanged(CuratorFramework client, ConnectionState newState); @Override boolean isConnected(); @Override SharedInterProcessLock createLock(String path); }
|
@Test public void testDelete() throws Exception { testee.delete("/path"); verify(deleteBuilder, times(1)).forPath("/path"); }
|
ZkPathChildrenCacheWrapper extends BaseCacheWrapper implements IPathChildrenCacheWrapper { public boolean isUseCache() { return useCache; } ZkPathChildrenCacheWrapper(IDataSourceConnector connector,
String path,
boolean dataIsCompressed,
PathChildrenCache cache); @Override void start(final PathChildrenCache.StartMode startMode); @Override void addListener(PathChildrenCacheListener listener); @Override void rebuild(); @Override void close(); @Override void rebuildNode(final String path); @Override Map<String, byte[]> getNodeIdToDataMap(); @Override byte[] getCurrentData(String fullPath); boolean isUseCache(); }
|
@Test public void testConstructWithCache() throws Exception { testee = new ZkPathChildrenCacheWrapper(client, "/test", false, cache); Assert.assertTrue(testee.isUseCache()); }
@Test public void testConstructWithoutCache() throws Exception { testee = new ZkPathChildrenCacheWrapper(client, "/test", false, null); Assert.assertFalse(testee.isUseCache()); }
|
StacksService implements IStacksService { @Override public Set<PathItem> getActiveStacksAndFlavors (String serviceName) { Paths pathsItem = getPathsForService(serviceName); return getActiveStacksAndFlavors(pathsItem); } @PostConstruct void init(); @Override ServicePaths getStacksForService(String serviceName); @Override ServicePaths updateStacksForService(String serviceName, ServicePaths servicePaths, Whitelisted whitelisted); @Override Set<String> getAllServiceNames(); @Override Boolean isServiceExists(String serviceName); @Override ServicePaths getStacksForAllServices(); @Override Set<PathItem> getActiveStacksAndFlavors(String serviceName); Set<PathItem> getActiveStacksAndFlavors(String serviceName, ServicePaths servicePaths); @Override HostIPsListWrapper getHostsForStackOnlyAndService(String stackName, String serviceName); @Override HostIPsListWrapper getRandomHostForStackOnlyAndService(String stackOnlyPath, String serviceName); @Override HostIPsListWrapper getHostsForStackAndService(String stackName, String serviceName); @Override HostIPsListWrapper getRandomHostForStackAndService(String stackName, String serviceName); @Override HostIPsListWrapper getHostsForFlavorAndService(String flavorName, String serviceName); @Override HostIPsListWrapper getRandomHostForFlavorAndService(String flavorName, String serviceName); @Override Set<StackData> getAllStacksAndHosts(String serviceName); Boolean isStackNameWithoutFlavor(String stackName); @Override HostIPsListWrapper getAddressByStackOrFlavor(String appName, String stackName, String flavorName); @Override HostIPsListWrapper getRandomAddressByStackOrFlavor(String serviceName, String stackName, String flavorName); @Override void deleteStack(String serviceName, String dataCenter, String availabilityZone, String flavor); @Override synchronized void deleteStacks(Paths paths); void setWhiteListService(IWhiteListService whiteListService); void setInitialDelay(long initialDelay); void setRefreshDelay(long refreshDelay); }
|
@Test public void testGetActiveStacksAndFlavors() throws Exception { when(stacksDAO.getAllStackPaths()).thenReturn( getStackPaths("/po/poc1/1.50/xreGuide", "/po/poc2/1.50/xreGuide", "/po/poc1/1.52/xreGuide")); when(stacksDAO.getHostsCount(new XreStackPath("/po/poc1/1.50/xreGuide"))).thenReturn(5); when(stacksDAO.getHostsCount(new XreStackPath("/po/poc2/1.50/xreGuide"))).thenReturn(0); when(stacksDAO.getHostsCount(new XreStackPath("/po/poc1/1.52/xreGuide"))).thenReturn(0); setupWhitelistedService(); Set<PathItem> result = testee.getActiveStacksAndFlavors("xreGuide"); Assert.assertTrue(containsInPaths(result, "/po/poc1/1.50")); Assert.assertTrue(containsInPaths(result, "1.50")); Assert.assertFalse(containsInPaths(result, "/po/poc2/1.50")); Assert.assertFalse(containsInPaths(result, "1.51")); }
|
Utils { public static LocalDateTime saneNowPlusDurationForAlarms(Duration duration) { LocalDateTime proposedLDT = Utils.getNow().plus(duration) .withSecondOfMinute(0) .withMillisOfSecond(0); while (DateTimeZone.getDefault().isLocalDateTimeGap(proposedLDT)) { proposedLDT = proposedLDT.plusMinutes(30); } return proposedLDT; } static LocalDateTime getNow(); static int getAppSmallIcon(); static DatePickerDialog getDatePickerDialog(Context context, DatePickerDialog.OnDateSetListener onDateSetListener, int year, int month, int day); static TimePickerDialog getTimePickerDialog(Context context,
TimePickerDialog.OnTimeSetListener onTimeSetListener,
int hour, int minute, boolean is24HourFormat); static void toastTo(final String toastMessage); static PendingIntent getPIInNewStack(Intent intent, int requestCode); static PendingIntent getPIInNewStack(Intent intent, int requestCode, int flags); static int calculateDaysUntil(LocalDateTime until); static String getFormattedMessageForDate(LocalDateTime localDateTime,
@StringRes int stringRed); static int getSharedUniqueId(); static LocalDateTime saneNowPlusDurationForAlarms(Duration duration); static DateTime convertLocalToDTSafely(LocalDateTime localDateTime); }
|
@Test public void saneNowPlusDurationForAlarms() { DateTimeZone.setDefault(DateTimeZone.forID("America/Los_Angeles")); DateTimeUtils.setCurrentMillisFixed(LocalDateTime.parse("2018-03-11T01:34:00") .toDateTime(DateTimeZone.getDefault()).getMillis()); Assert.assertEquals(LocalDateTime.parse("2018-03-11T03:04:00"), Utils.saneNowPlusDurationForAlarms(Duration.standardMinutes(30))); DateTimeUtils.setCurrentMillisOffset(0L); }
|
Utils { public static DateTime convertLocalToDTSafely(LocalDateTime localDateTime) { DateTime convertedDT = null; try { convertedDT = localDateTime.toDateTime(); } catch (IllegalInstantException e) { boolean failed = true; int iteration = 1; while (failed) { try { convertedDT = localDateTime.plusMinutes(30 * iteration).toDateTime(); failed = false; } catch (IllegalInstantException e2) { iteration++; } } Timber.i("Converted date from "+ localDateTime + " to " + convertedDT + " because of DST gap"); } return convertedDT; } static LocalDateTime getNow(); static int getAppSmallIcon(); static DatePickerDialog getDatePickerDialog(Context context, DatePickerDialog.OnDateSetListener onDateSetListener, int year, int month, int day); static TimePickerDialog getTimePickerDialog(Context context,
TimePickerDialog.OnTimeSetListener onTimeSetListener,
int hour, int minute, boolean is24HourFormat); static void toastTo(final String toastMessage); static PendingIntent getPIInNewStack(Intent intent, int requestCode); static PendingIntent getPIInNewStack(Intent intent, int requestCode, int flags); static int calculateDaysUntil(LocalDateTime until); static String getFormattedMessageForDate(LocalDateTime localDateTime,
@StringRes int stringRed); static int getSharedUniqueId(); static LocalDateTime saneNowPlusDurationForAlarms(Duration duration); static DateTime convertLocalToDTSafely(LocalDateTime localDateTime); }
|
@Test public void convertLocalToDTSafely() { DateTimeZone.setDefault(DateTimeZone.forID("America/Los_Angeles")); Assert.assertEquals(LocalDateTime.parse("2018-03-11T03:04:00").toDateTime(DateTimeZone.getDefault()), Utils.convertLocalToDTSafely(LocalDateTime.parse("2018-03-11T02:04:00"))); Assert.assertEquals(LocalDateTime.parse("2018-03-11T03:04:00").toDateTime(DateTimeZone.getDefault()), Utils.convertLocalToDTSafely(LocalDateTime.parse("2018-03-11T02:04:00"))); Assert.assertEquals(LocalDateTime.parse("2018-03-11T03:04:00").toDateTime(DateTimeZone.getDefault()), Utils.convertLocalToDTSafely(LocalDateTime.parse("2018-03-11T02:34:00"))); }
|
ValueMapper { public Object map(final Value message) throws ObjectToIdMappingException { final UUID valueId = message.getObservableObjectId(); if (valueId != null) { return objectRegistry.getByIdOrFail(valueId); } else { return message.getSimpleObjectValue(); } } ValueMapper(final WeakObjectRegistry objectRegistry); Object map(final Value message); Value map(final Object value, final boolean isObservable); }
|
@Test public void shouldReturnSimpleObjectObservedValueForSimpleObjectMessages() { final Value message = new Value("some value"); final Object maped = cut.map(message); assertThat(maped).isSameAs(message.getSimpleObjectValue()); }
@Test public void shouldReturnObservableObjectValueForObservableObjectMessage() { final Object sampleObservableObject = "sample object"; when(objectRegistry.getByIdOrFail(SAMPLE_ID)).thenReturn(sampleObservableObject); final Value message = new Value(SAMPLE_ID); final Object maped = cut.map(message); assertThat(maped).isSameAs(sampleObservableObject); }
@Test public void shouldReturnSimpleObjectMessageForSimpleObjectValue() { final Value message = cut.map("sample object", false); assertThat(message.getObservableObjectId()).isNull(); assertThat(message.getSimpleObjectValue()).isSameAs("sample object"); }
@Test public void shouldReturnObservableObjectMessageForObservableObjectValue() { Object sampleObservableObject = "sample object"; when(objectRegistry.getIdOrFail(sampleObservableObject)).thenReturn(SAMPLE_ID); Value message = cut.map(sampleObservableObject, true); assertThat(message.getObservableObjectId()).isEqualTo(SAMPLE_ID); assertThat(message.getSimpleObjectValue()).isNull(); }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.