@JsonCreator public SessionRepresentation( @JsonProperty("user") String user, @JsonProperty("source") Optional<String> source, @JsonProperty("catalog") String catalog, @JsonProperty("schema") String schema, @JsonProperty("timeZoneKey") TimeZoneKey timeZoneKey, @JsonProperty("locale") Locale locale, @JsonProperty("remoteUserAddress") Optional<String> remoteUserAddress, @JsonProperty("userAgent") Optional<String> userAgent, @JsonProperty("startTime") long startTime, @JsonProperty("systemProperties") Map<String, String> systemProperties, @JsonProperty("catalogProperties") Map<String, Map<String, String>> catalogProperties) { this.user = requireNonNull(user, "user is null"); this.source = requireNonNull(source, "source is null"); this.catalog = requireNonNull(catalog, "catalog is null"); this.schema = requireNonNull(schema, "schema is null"); this.timeZoneKey = requireNonNull(timeZoneKey, "timeZoneKey is null"); this.locale = requireNonNull(locale, "locale is null"); this.remoteUserAddress = requireNonNull(remoteUserAddress, "remoteUserAddress is null"); this.userAgent = requireNonNull(userAgent, "userAgent is null"); this.startTime = startTime; this.systemProperties = ImmutableMap.copyOf(systemProperties); ImmutableMap.Builder<String, Map<String, String>> catalogPropertiesBuilder = ImmutableMap.<String, Map<String, String>>builder(); for (Entry<String, Map<String, String>> entry : catalogProperties.entrySet()) { catalogPropertiesBuilder.put(entry.getKey(), ImmutableMap.copyOf(entry.getValue())); } this.catalogProperties = catalogPropertiesBuilder.build(); }
private KnownBuildRuleTypes( Set<Description<?>> descriptions, Map<BuildRuleType, BuildRuleFactory<?>> factories, Map<String, BuildRuleType> types) { this.descriptions = ImmutableSet.copyOf(descriptions); this.factories = ImmutableMap.copyOf(factories); this.types = ImmutableMap.copyOf(types); }
public void testCopyOf() { Map<String, Integer> original = new LinkedHashMap<String, Integer>(); original.put("one", 1); original.put("two", 2); original.put("three", 3); ImmutableMap<String, Integer> copy = ImmutableMap.copyOf(original); assertMapEquals(copy, "one", 1, "two", 2, "three", 3); assertSame(copy, ImmutableMap.copyOf(copy)); }
private KnownBuildRuleTypes( Map<BuildRuleType, Description<?>> descriptions, Map<String, BuildRuleType> types, FlavorDomain<CxxPlatform> cxxPlatforms, CxxPlatform defaultCxxPlatforms) { this.descriptions = ImmutableMap.copyOf(descriptions); this.types = ImmutableMap.copyOf(types); this.cxxPlatforms = cxxPlatforms; this.defaultCxxPlatforms = defaultCxxPlatforms; }
private SoySauceImpl( CompiledTemplates templates, GuiceSimpleScope apiCallScope, SoyValueHelper converter, ImmutableMap<String, ? extends SoyJavaFunction> functions, ImmutableMap<String, ? extends SoyJavaPrintDirective> printDirectives) { this.templates = checkNotNull(templates); this.apiCallScope = checkNotNull(apiCallScope); this.converter = checkNotNull(converter); this.functions = ImmutableMap.copyOf(functions); this.printDirectives = ImmutableMap.copyOf(printDirectives); }
private Info( Map<Class<? extends TransitiveInfoProvider>, TransitiveInfoProvider> providers, Map<String, NestedSet<Artifact>> outputGroups, CcCompilationOutputs compilationOutputs, CcLinkingOutputs linkingOutputs, CcLinkingOutputs linkingOutputsExcludingPrecompiledLibraries, CppCompilationContext context) { this.providers = ImmutableMap.copyOf(providers); this.outputGroups = ImmutableMap.copyOf(outputGroups); this.compilationOutputs = compilationOutputs; this.linkingOutputs = linkingOutputs; this.linkingOutputsExcludingPrecompiledLibraries = linkingOutputsExcludingPrecompiledLibraries; this.context = context; }
@Override public IAttribute createMergedAttribute(Object object, Collection<INode> nodesToMerge) { INode attributeKey = (INode) object; // Merge Numeric int support = ClassitMaxCategoryUtilitySearcher.calcSupportOfAttribute(attributeKey, nodesToMerge); if (support < 1) { TBLogger.getLogger(getClass().getName()) .severe("Attempt to initialize attribute object with support smaller 1."); System.exit(-1); } double sumOfRatings = ClassitMaxCategoryUtilitySearcher.calcSumOfRatingsOfAttribute(attributeKey, nodesToMerge); // double average = sumOfRatings / (double) support; double sumOfSquaredRatings = ClassitMaxCategoryUtilitySearcher.calcSumOfSquaredRatingsOfAttribute( attributeKey, nodesToMerge); // double stdDev = ClassitMaxCategoryUtilitySearcher.calcStdDevOfAttribute(attributeKey, // merge); // Merge Nominal int totalLeafCount = 0; for (INode node : nodesToMerge) { totalLeafCount += node.getNumberOfLeafNodes(); } Map<Object, Double> attMap = ImmutableMap.copyOf( CobwebMaxCategoryUtilitySearcher.calculateAttributeProbabilities( (INode) object, nodesToMerge, totalLeafCount)); return new SharedAttribute(support, sumOfRatings, sumOfSquaredRatings, attMap); }
public ClassMeta( Class<?> cls, URL loadedSource, ApiInfo api, Map<File, Set<String>> providerMods) { this.cls = cls; this.loadedSource = loadedSource; this.api = api; this.providerMods = ImmutableMap.copyOf(providerMods); }
public Builder labels(final Map<String, String> labels) { if (labels != null && !labels.isEmpty()) { this.labels = ImmutableMap.copyOf(labels); } return this; }
@ConstructorProperties({ "id", "links", "orderedSelfReferences", "name", "progress", "serverRef", "status", "metadata", "created", "updated" }) protected Image( int id, List<Map<String, String>> links, @Nullable Map<LinkType, URI> orderedSelfReferences, @Nullable String name, @Nullable Integer progress, @Nullable String serverRef, @Nullable ImageStatus status, @Nullable Map<String, String> metadata, @Nullable Date created, @Nullable Date updated) { super(id, links, orderedSelfReferences); this.name = name; this.progress = progress; this.serverRef = serverRef; this.status = status == null ? ImageStatus.UNKNOWN : status; this.metadata = metadata == null ? ImmutableMap.<String, String>of() : ImmutableMap.copyOf(checkNotNull(metadata, "metadata")); this.created = created; this.updated = updated; }
@Override public Map<String, String> apply(String strongName) { try { // Can't use ImmutableMap.Builder since we may have duplicate keys like $clinit. Map<String, String> out = new HashMap<String, String>(); BufferedReader bin = new BufferedReader( new InputStreamReader( symbolMapsDirectory.getSymbolMapInputStream(strongName))); try { String line; while ((line = bin.readLine()) != null) { if (line.charAt(0) == '#') { continue; } int idx = line.indexOf(','); out.put(line.substring(0, idx), line.substring(idx + 1)); } } finally { bin.close(); } return ImmutableMap.copyOf(out); } catch (IOException e) { log.log(Level.WARNING, "Symbol map not found: " + strongName, e); // use empty symbol map to avoid repeated loads return ImmutableMap.of(); } }
public MultiModel( ResourceLocation location, IModel base, IModelState baseState, Map<String, Pair<IModel, IModelState>> parts) { this(location, base, baseState, ImmutableMap.copyOf(parts)); }
private ReflectionParametricScalar( Signature signature, String description, boolean hidden, Map<Signature, Implementation> exactImplementations, List<Implementation> specializedImplementations, List<Implementation> implementations, boolean deterministic) { super( signature.getName(), signature.getTypeParameterRequirements(), signature.getReturnType().toString(), signature .getArgumentTypes() .stream() .map(TypeSignature::toString) .collect(toImmutableList())); this.description = description; this.hidden = hidden; this.exactImplementations = ImmutableMap.copyOf(requireNonNull(exactImplementations, "exactImplementations is null")); this.specializedImplementations = ImmutableList.copyOf( requireNonNull(specializedImplementations, "specializedImplementations is null")); this.implementations = ImmutableList.copyOf(requireNonNull(implementations, "implementations is null")); this.deterministic = deterministic; }
@Test public void sanitizeSymlinkedWorkingDirectory() throws IOException { TemporaryFolder folder = new TemporaryFolder(); folder.create(); // Setup up a symlink to our working directory. Path symlinkedRoot = folder.getRoot().toPath().resolve("symlinked-root"); java.nio.file.Files.createSymbolicLink(symlinkedRoot, tmp.getRootPath()); // Run the build, setting PWD to the above symlink. Typically, this causes compilers to use // the symlinked directory, even though it's not the right project root. Map<String, String> envCopy = Maps.newHashMap(System.getenv()); envCopy.put("PWD", symlinkedRoot.toString()); workspace .runBuckCommandWithEnvironmentAndContext( tmp.getRootPath(), Optional.<NGContext>absent(), Optional.<BuckEventListener>absent(), Optional.of(ImmutableMap.copyOf(envCopy)), "build", "//:simple#default,static") .assertSuccess(); // Verify that we still sanitized this path correctly. Path lib = workspace.getPath("buck-out/gen/simple#default,static/libsimple.a"); String contents = Files.asByteSource(lib.toFile()).asCharSource(Charsets.ISO_8859_1).read(); assertFalse(lib.toString(), contents.contains(tmp.getRootPath().toString())); assertFalse(lib.toString(), contents.contains(symlinkedRoot.toString())); folder.delete(); }
private int executeCCompilation( ExecutionContext context, ImmutableList.Builder<Path> linkerInputs) throws IOException, InterruptedException { ImmutableList.Builder<String> cCompileFlags = ImmutableList.builder(); cCompileFlags.addAll(ocamlContext.getCCompileFlags()); cCompileFlags.addAll(ocamlContext.getCommonCFlags()); CxxPreprocessorInput cxxPreprocessorInput = ocamlContext.getCxxPreprocessorInput(); for (SourcePath cSrc : ocamlContext.getCInput()) { Path outputPath = ocamlContext.getCOutput(resolver.getAbsolutePath(cSrc)); linkerInputs.add(outputPath); Step compileStep = new OCamlCCompileStep( resolver, filesystem.getRootPath(), new OCamlCCompileStep.Args( cCompilerEnvironment, cCompiler, ocamlContext.getOcamlCompiler().get(), outputPath, cSrc, cCompileFlags.build(), ImmutableMap.copyOf(cxxPreprocessorInput.getIncludes().getNameToPathMap()))); int compileExitCode = compileStep.execute(context); if (compileExitCode != 0) { return compileExitCode; } } return 0; }
public CypherPart memberToCypher(CypherParts parts, List<?> top) { final ArrayList<String> outDependencies = new ArrayList<>(); final LinkedHashMap<String, Object> outParams = new LinkedHashMap<>(); // ensure gene is prepared final List<?> gene = (List<?>) top.get(1); final String geneVarName = varNameForGene(gene); if (!parts.nodes.containsKey(geneVarName)) { final CypherPart geneCypher = customNodeToCypher(gene); parts.nodes.put(geneVarName, geneCypher); } customNodeToMatch(gene, outDependencies, outParams); // ensure concept is prepared final List<?> concept = (List<?>) top.get(2); final String conceptVarName = varNameForConcept(concept); if (!parts.nodes.containsKey(conceptVarName)) { final CypherPart conceptCypher = customNodeToCypher(concept); parts.nodes.put(conceptVarName, conceptCypher); } customNodeToMatch(concept, outDependencies, outParams); final String create = String.format("CREATE UNIQUE (%s) -[:rdf_type]-> (%s)", geneVarName, conceptVarName); final CypherPart part = new CypherPart( null, ImmutableMap.copyOf(outParams), create, ImmutableList.copyOf(outDependencies)); parts.relationships.add(part); return part; }
public CypherPart inheritanceToCypher(CypherParts parts, List<?> top) { final ArrayList<String> outDependencies = new ArrayList<>(); final LinkedHashMap<String, Object> outParams = new LinkedHashMap<>(); // ensure a is prepared final List<?> a = (List<?>) top.get(1); final String aType = typeNameFor(a); final String aVarName = varNameFor(aType, a); if (!parts.nodes.containsKey(aVarName)) { final CypherPart aCypher = customNodeToCypher(a); parts.nodes.put(aVarName, aCypher); } customNodeToMatch(a, outDependencies, outParams); // ensure b is prepared final List<?> b = (List<?>) top.get(2); final String bType = typeNameFor(b); final String bVarName = varNameFor(bType, b); if (!parts.nodes.containsKey(bVarName)) { final CypherPart bCypher = customNodeToCypher(b); parts.nodes.put(bVarName, bCypher); } customNodeToMatch(b, outDependencies, outParams); final String create = String.format("CREATE UNIQUE (%s) -[:rdfs_subClassOf]-> (%s)", aVarName, bVarName); final CypherPart part = new CypherPart( null, ImmutableMap.copyOf(outParams), create, ImmutableList.copyOf(outDependencies)); parts.relationships.add(part); return part; }
@Before public void setUp() throws IOException, InterruptedException { console = new TestConsole(); workspace = TestDataHelper.createProjectWorkspaceForScenario(this, "target_command", tmp); workspace.setUp(); filesystem = new ProjectFilesystem(workspace.getDestPath().toRealPath().normalize()); Cell cell = new TestCellBuilder().setFilesystem(filesystem).build(); AndroidDirectoryResolver androidDirectoryResolver = new FakeAndroidDirectoryResolver(); ArtifactCache artifactCache = new NoopArtifactCache(); BuckEventBus eventBus = BuckEventBusFactory.newInstance(); objectMapper = new ObjectMapper(); targetsCommand = new TargetsCommand(); params = CommandRunnerParamsForTesting.createCommandRunnerParamsForTesting( console, cell, androidDirectoryResolver, artifactCache, eventBus, FakeBuckConfig.builder().build(), Platform.detect(), ImmutableMap.copyOf(System.getenv()), new FakeJavaPackageFinder(), objectMapper, Optional.<WebServer>absent()); executor = MoreExecutors.listeningDecorator(Executors.newSingleThreadExecutor()); }
private void installSecondaryDexFiles() throws Exception { final ImmutableMap<String, Path> hashToSources = getRequiredDexFiles(); final ImmutableSet<String> requiredHashes = hashToSources.keySet(); final ImmutableSet<String> presentHashes = prepareSecondaryDexDir(requiredHashes); final Set<String> hashesToInstall = Sets.difference(requiredHashes, presentHashes); Map<String, Path> filesToInstallByHash = Maps.filterKeys(hashToSources, Predicates.in(hashesToInstall)); // This is a bit gross. It was a late addition. Ideally, we could eliminate this, but // it wouldn't be terrible if we don't. We store the dexed jars on the device // with the full SHA-1 hashes in their names. This is the format that the loader uses // internally, so ideally we would just load them in place. However, the code currently // expects to be able to copy the jars from a directory that matches the name in the // metadata file, like "secondary-1.dex.jar". We don't want to give up putting the // hashes in the file names (because we use that to skip re-uploads), so just hack // the metadata file to have hash-like names. String metadataContents = com.google.common.io.Files.toString( projectFilesystem .resolve(exopackageInfo.getDexInfo().get().getMetadata()) .toFile(), Charsets.UTF_8) .replaceAll( "secondary-(\\d+)\\.dex\\.jar (\\p{XDigit}{40}) ", "secondary-$2.dex.jar $2 "); installFiles( "secondary_dex", ImmutableMap.copyOf(filesToInstallByHash), metadataContents, "secondary-%s.dex.jar", SECONDARY_DEX_DIR); }
public LiveMarketDataProviderFactory( LiveDataFactory defaultFactory, Map<String, LiveDataFactory> namedFactories) { ArgumentChecker.notNull(defaultFactory, "defaultFactory"); ArgumentChecker.notNull(namedFactories, "namedFactories"); _defaultFactory = defaultFactory; _namedFactories = ImmutableMap.copyOf(namedFactories); }
@JsonCreator public TopNNode( @JsonProperty("id") PlanNodeId id, @JsonProperty("source") PlanNode source, @JsonProperty("count") long count, @JsonProperty("orderBy") List<Symbol> orderBy, @JsonProperty("orderings") Map<Symbol, SortOrder> orderings, @JsonProperty("partial") boolean partial, @JsonProperty("sampleWeight") Optional<Symbol> sampleWeight) { super(id); Preconditions.checkNotNull(source, "source is null"); Preconditions.checkArgument(count > 0, "count must be positive"); Preconditions.checkNotNull(orderBy, "orderBy is null"); Preconditions.checkArgument(!orderBy.isEmpty(), "orderBy is empty"); Preconditions.checkArgument( orderings.size() == orderBy.size(), "orderBy and orderings sizes don't match"); Preconditions.checkNotNull(sampleWeight, "sampleWeight is null"); if (sampleWeight.isPresent()) { Preconditions.checkArgument( source.getOutputSymbols().contains(sampleWeight.get()), "source does not output sample weight"); } this.source = source; this.count = count; this.orderBy = ImmutableList.copyOf(orderBy); this.orderings = ImmutableMap.copyOf(orderings); this.partial = partial; this.sampleWeight = sampleWeight; }
private Implementation( Signature signature, boolean nullable, List<Boolean> nullableArguments, MethodHandle methodHandle, List<ImplementationDependency> dependencies, Optional<MethodHandle> constructor, List<ImplementationDependency> constructorDependencies, List<Class<?>> argumentNativeContainerTypes, Map<String, Class<?>> specializedTypeParameters) { this.signature = requireNonNull(signature, "signature is null"); this.nullable = nullable; this.nullableArguments = ImmutableList.copyOf(requireNonNull(nullableArguments, "nullableArguments is null")); this.methodHandle = requireNonNull(methodHandle, "methodHandle is null"); this.dependencies = ImmutableList.copyOf(requireNonNull(dependencies, "dependencies is null")); this.constructor = requireNonNull(constructor, "constructor is null"); this.constructorDependencies = ImmutableList.copyOf( requireNonNull(constructorDependencies, "constructorDependencies is null")); this.argumentNativeContainerTypes = ImmutableList.copyOf( requireNonNull(argumentNativeContainerTypes, "argumentNativeContainerTypes is null")); this.specializedTypeParameters = ImmutableMap.copyOf( requireNonNull(specializedTypeParameters, "specializedTypeParameters is null")); }
@Override public Map<Symbol, Symbol> visitProject(ProjectNode node, Set<Symbol> lookupSymbols) { // Map from output Symbols to source Symbols Map<Symbol, Symbol> directSymbolTranslationOutputMap = Maps.transformValues( Maps.filterValues(node.getAssignments(), SymbolReference.class::isInstance), Symbol::from); Map<Symbol, Symbol> outputToSourceMap = lookupSymbols .stream() .filter(directSymbolTranslationOutputMap.keySet()::contains) .collect(toImmutableMap(identity(), directSymbolTranslationOutputMap::get)); checkState( !outputToSourceMap.isEmpty(), "No lookup symbols were able to pass through the projection"); // Map from source Symbols to underlying index source Symbols Map<Symbol, Symbol> sourceToIndexMap = node.getSource().accept(this, ImmutableSet.copyOf(outputToSourceMap.values())); // Generate the Map the connects lookup symbols to underlying index source symbols Map<Symbol, Symbol> outputToIndexMap = Maps.transformValues( Maps.filterValues(outputToSourceMap, in(sourceToIndexMap.keySet())), Functions.forMap(sourceToIndexMap)); return ImmutableMap.copyOf(outputToIndexMap); }
public RequestDispatcher(Iterable<GrizzletHandler> grizzlets) { Map<String, Map<HttpMethod, GrizzletHandler>> modifiableHandlersMap = Maps.newHashMap(); for (GrizzletHandler handler : grizzlets) { Map<HttpMethod, GrizzletHandler> handlerByMethod = modifiableHandlersMap.get(handler.getPath()); if (handlerByMethod == null) { handlerByMethod = Maps.newEnumMap(HttpMethod.class); modifiableHandlersMap.put(handler.getPath(), handlerByMethod); } for (HttpMethod method : handler.getMethods()) { GrizzletHandler alreadyHandler = handlerByMethod.put(method, handler); if (alreadyHandler != null) { throw new IllegalArgumentException( "More than one handler detected for path='" + handler.getPath() + "', method='" + method.name() + '\''); } } } for (Map.Entry<String, Map<HttpMethod, GrizzletHandler>> entry : modifiableHandlersMap.entrySet()) { modifiableHandlersMap.put(entry.getKey(), Collections.unmodifiableMap(entry.getValue())); } handlers = ImmutableMap.copyOf(modifiableHandlersMap); }
/** * Verifies that a client timeout will be detected by a Nailgun NGInputStream reading from a * blocking heartbeat stream. */ @Test(expected = InterruptedException.class) public void whenClientTimeoutDetectedThenMainThreadIsInterrupted() throws InterruptedException, IOException { final long timeoutMillis = 100; final long intervalMillis = timeoutMillis * 2; // Interval > timeout to trigger disconnection. final ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario(this, "exclusive_execution", tmp); workspace.setUp(); // Build an NGContext connected to an NGInputStream reading from a stream that will timeout. Thread.currentThread().setName("Test"); try (TestContext context = new TestContext( ImmutableMap.copyOf(System.getenv()), TestContext.createHeartBeatStream(intervalMillis), timeoutMillis)) { final Thread commandThread = Thread.currentThread(); context.addClientListener( new NGClientListener() { @Override public void clientDisconnected() throws InterruptedException { commandThread.interrupt(); } }); Thread.sleep(1000); fail("Should have been interrupted."); } }
/** * In a {@link BuckConfig}, an alias can either refer to a fully-qualified build target, or an * alias defined earlier in the {@code alias} section. The mapping produced by this method * reflects the result of resolving all aliases as values in the {@code alias} section. */ private static ImmutableMap<String, BuildTarget> createAliasToBuildTargetMap( ImmutableMap<String, String> rawAliasMap) { // We use a LinkedHashMap rather than an ImmutableMap.Builder because we want both (1) order to // be preserved, and (2) the ability to inspect the Map while building it up. LinkedHashMap<String, BuildTarget> aliasToBuildTarget = Maps.newLinkedHashMap(); for (Map.Entry<String, String> aliasEntry : rawAliasMap.entrySet()) { String alias = aliasEntry.getKey(); validateAliasName(alias); // Determine whether the mapping is to a build target or to an alias. String value = aliasEntry.getValue(); BuildTarget buildTarget; if (isValidAliasName(value)) { buildTarget = aliasToBuildTarget.get(value); if (buildTarget == null) { throw new HumanReadableException("No alias for: %s.", value); } } else { // Here we parse the alias values with a BuildTargetParser to be strict. We could be looser // and just grab everything between "//" and ":" and assume it's a valid base path. buildTarget = BuildTargetParser.INSTANCE.parse(value, BuildTargetPatternParser.fullyQualified()); } aliasToBuildTarget.put(alias, buildTarget); } return ImmutableMap.copyOf(aliasToBuildTarget); }
@Before public void setUp() throws IOException, InterruptedException { ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario(this, "query_command", tmp); workspace.setUp(); Cell cell = new TestCellBuilder().setFilesystem(new ProjectFilesystem(workspace.getDestPath())).build(); TestConsole console = new TestConsole(); CommandRunnerParams params = CommandRunnerParamsForTesting.createCommandRunnerParamsForTesting( console, cell, new FakeAndroidDirectoryResolver(), new NoopArtifactCache(), BuckEventBusFactory.newInstance(), FakeBuckConfig.builder().build(), Platform.detect(), ImmutableMap.copyOf(System.getenv()), new FakeJavaPackageFinder(), new ObjectMapper(), Optional.<WebServer>absent()); buckQueryEnvironment = new BuckQueryEnvironment(params, /* enableProfiling */ false); cellRoot = workspace.getDestPath(); executor = MoreExecutors.listeningDecorator(Executors.newSingleThreadExecutor()); }
private StagedModelHtmlRenderer(ImmutableList<Stage> renderers) { Map<Class, Stage> map = Maps.newHashMap(); for (Stage stage : renderers) { map.put(stage.target, stage); } stages = ImmutableMap.copyOf(map); }
/** Implements {@link Files#readAttributes(Path, String, LinkOption...)}. */ public ImmutableMap<String, Object> readAttributes(File file, String attributes) { String view = getViewName(attributes); List<String> attrs = getAttributeNames(attributes); if (attrs.size() > 1 && attrs.contains(ALL_ATTRIBUTES)) { // attrs contains * and other attributes throw new IllegalArgumentException("invalid attributes: " + attributes); } Map<String, Object> result = new HashMap<>(); if (attrs.size() == 1 && attrs.contains(ALL_ATTRIBUTES)) { // for 'view:*' format, get all keys for all providers for the view AttributeProvider provider = providersByName.get(view); readAll(file, provider, result); for (String inheritedView : provider.inherits()) { AttributeProvider inheritedProvider = providersByName.get(inheritedView); readAll(file, inheritedProvider, result); } } else { // for 'view:attr1,attr2,etc' for (String attr : attrs) { result.put(attr, getAttribute(file, view, attr)); } } return ImmutableMap.copyOf(result); }
@SuppressWarnings("unchecked") public RpcRouterCodegenInstance( String name, Class<T> type, T routerImpl, Set<Class<? extends BaseIdentity>> contexts, Set<Class<? extends DataContainer>> inputs) { this.name = name; this.listeners = ListenerRegistry.create(); this.serviceType = type; this.invocationProxy = routerImpl; this.contexts = ImmutableSet.copyOf(contexts); Map<Class<? extends BaseIdentity>, RpcRoutingTableImpl<? extends BaseIdentity, T>> mutableRoutingTables = new HashMap<>(); for (Class<? extends BaseIdentity> ctx : contexts) { RpcRoutingTableImpl<? extends BaseIdentity, T> table = new RpcRoutingTableImpl<>(name, ctx, type); @SuppressWarnings("rawtypes") Map invokerView = table.getRoutes(); setRoutingTable(invocationProxy, ctx, invokerView); mutableRoutingTables.put(ctx, table); table.registerRouteChangeListener(this); } this.routingTables = ImmutableMap.copyOf(mutableRoutingTables); }