List of usage examples for com.google.common.collect ImmutableMap forEach
default void forEach(BiConsumer<? super K, ? super V> action)
From source file:com.fatboyindustrial.omnium.Maps.java
/** * Transforms the given map by applying a function to each of the keys. * @param input The input map./*from w w w . java 2 s .c om*/ * @param transform The transformation function to apply to the key. * @param <K1> The original key type. * @param <V> The map value type. * @param <K2> The transformed key type. * @return The new map. */ public static <K1, V, K2> ImmutableMap<K2, V> keyTransform(final ImmutableMap<K1, V> input, final Function<K1, K2> transform) { final ImmutableMap.Builder<K2, V> builder = ImmutableMap.builder(); input.forEach((key, value) -> builder.put(transform.apply(key), value)); return builder.build(); }
From source file:dagger.internal.codegen.SubcomponentNames.java
private static ImmutableMap<Key, String> namesByKey(KeyFactory keyFactory, ImmutableMap<ComponentDescriptor, String> subcomponentNames) { ImmutableMap.Builder<Key, String> builder = ImmutableMap.builder(); subcomponentNames .forEach((component, name) -> component.creatorDescriptor().ifPresent(creatorDescriptor -> { TypeMirror creatorType = creatorDescriptor.typeElement().asType(); builder.put(keyFactory.forSubcomponentCreator(creatorType), name); }));// w w w . j a v a2 s .c o m return builder.build(); }
From source file:com.facebook.buck.core.cell.impl.LocalCellProviderFactory.java
/** Create a cell provider at a given root. */ public static CellProvider create(ProjectFilesystem rootFilesystem, BuckConfig rootConfig, CellConfig rootCellConfigOverrides, ImmutableMap<CellName, Path> cellPathMapping, CellPathResolver rootCellCellPathResolver, BuckModuleManager moduleManager, ToolchainProviderFactory toolchainProviderFactory, ProjectFilesystemFactory projectFilesystemFactory, UnconfiguredBuildTargetFactory unconfiguredBuildTargetFactory) { ImmutableMap<Path, RawConfig> pathToConfigOverrides; try {//w ww . java 2 s. c o m pathToConfigOverrides = rootCellConfigOverrides.getOverridesByPath(cellPathMapping); } catch (InvalidCellOverrideException e) { throw new HumanReadableException(e.getMessage()); } ImmutableSet<Path> allRoots = ImmutableSet.copyOf(cellPathMapping.values()); return new CellProvider(cellProvider -> new CacheLoader<Path, Cell>() { @Override public Cell load(Path cellPath) throws IOException, InterruptedException { Path normalizedCellPath = cellPath.toRealPath().normalize(); Preconditions.checkState(allRoots.contains(normalizedCellPath), "Cell %s outside of transitive closure of root cell (%s).", normalizedCellPath, allRoots); RawConfig configOverrides = Optional.ofNullable(pathToConfigOverrides.get(normalizedCellPath)) .orElse(RawConfig.of(ImmutableMap.of())); Config config = Configs.createDefaultConfig(normalizedCellPath, configOverrides); ImmutableMap<String, Path> cellMapping = DefaultCellPathResolver .getCellPathsFromConfigRepositoriesSection(cellPath, config.get(DefaultCellPathResolver.REPOSITORIES_SECTION)); // The cell should only contain a subset of cell mappings of the root cell. cellMapping.forEach((name, path) -> { Path pathInRootResolver = rootCellCellPathResolver.getCellPaths().get(name); if (pathInRootResolver == null) { throw new HumanReadableException( "In the config of %s: %s.%s must exist in the root cell's cell mappings.", cellPath.toString(), DefaultCellPathResolver.REPOSITORIES_SECTION, name); } else if (!pathInRootResolver.equals(path)) { throw new HumanReadableException( "In the config of %s: %s.%s must point to the same directory as the root " + "cell's cell mapping: (root) %s != (current) %s", cellPath.toString(), DefaultCellPathResolver.REPOSITORIES_SECTION, name, pathInRootResolver, path); } }); CellPathResolver cellPathResolver = new CellPathResolverView(rootCellCellPathResolver, cellMapping.keySet(), cellPath); Optional<EmbeddedCellBuckOutInfo> embeddedCellBuckOutInfo = Optional.empty(); Optional<String> canonicalCellName = cellPathResolver.getCanonicalCellName(normalizedCellPath); if (rootConfig.getView(BuildBuckConfig.class).isEmbeddedCellBuckOutEnabled() && canonicalCellName.isPresent()) { embeddedCellBuckOutInfo = Optional .of(EmbeddedCellBuckOutInfo.of(rootFilesystem.resolve(rootFilesystem.getRootPath()), rootFilesystem.getBuckPaths(), canonicalCellName.get())); } ProjectFilesystem cellFilesystem = projectFilesystemFactory .createProjectFilesystem(normalizedCellPath, config, embeddedCellBuckOutInfo); BuckConfig buckConfig = new BuckConfig(config, cellFilesystem, rootConfig.getArchitecture(), rootConfig.getPlatform(), rootConfig.getEnvironment(), buildTargetName -> unconfiguredBuildTargetFactory.create(cellPathResolver, buildTargetName)); RuleKeyConfiguration ruleKeyConfiguration = ConfigRuleKeyConfigurationFactory.create(buckConfig, moduleManager); ToolchainProvider toolchainProvider = toolchainProviderFactory.create(buckConfig, cellFilesystem, ruleKeyConfiguration); // TODO(13777679): cells in other watchman roots do not work correctly. return ImmutableCell.of(cellPathResolver.getKnownRoots(), canonicalCellName, cellFilesystem, buckConfig, cellProvider, toolchainProvider, ruleKeyConfiguration, cellPathResolver); } }, cellProvider -> RootCellFactory.create(cellProvider, rootCellCellPathResolver, toolchainProviderFactory, rootFilesystem, moduleManager, rootConfig)); }
From source file:com.facebook.buck.cxx.toolchain.objectfile.Machos.java
/** * Relativize paths in OSO entries.//from w w w . j a v a2s. c o m * * <p>OSO entries point to other files containing debug information. These are generated by the * linker as absolute paths. */ static void relativizeOsoSymbols(FileChannel file, ImmutableMap<Path, Path> cellRoots) throws IOException, MachoException { cellRoots.forEach((from, to) -> { Preconditions.checkArgument(from.isAbsolute()); Preconditions.checkArgument(!to.isAbsolute()); }); long size = file.size(); MappedByteBuffer map = file.map(FileChannel.MapMode.READ_WRITE, 0, size); MachoHeader header = getHeader(map); int symbolTableOffset = 0; int symbolTableCount = 0; int stringTableOffset = 0; int stringTableSizePosition = 0; int stringTableSize = 0; boolean symbolTableSegmentFound = false; int segmentSizePosition = 0; int segmentSize = 0; boolean linkEditSegmentFound = false; int segmentFileSizePosition = 0; int segmentFileSize = 0; int segment64FileSizePosition = 0; long segment64FileSize = 0; int commandsCount = header.getCommandsCount(); for (int i = 0; i < commandsCount; i++) { int commandStart = map.position(); // NOPMD int command = ObjectFileScrubbers.getLittleEndianInt(map); int commandSize = ObjectFileScrubbers.getLittleEndianInt(map); // NOPMD switch (command) { case LC_SYMTAB: symbolTableOffset = ObjectFileScrubbers.getLittleEndianInt(map); symbolTableCount = ObjectFileScrubbers.getLittleEndianInt(map); stringTableOffset = ObjectFileScrubbers.getLittleEndianInt(map); stringTableSizePosition = map.position(); stringTableSize = ObjectFileScrubbers.getLittleEndianInt(map); symbolTableSegmentFound = true; break; case LC_SEGMENT: byte[] segmentNameBytes = ObjectFileScrubbers.getBytes(map, 16); String segmentName = new String(segmentNameBytes, Charsets.US_ASCII); if (segmentName.startsWith(LINKEDIT)) { linkEditSegmentFound = true; /* vm address */ ObjectFileScrubbers.getLittleEndianInt(map); /* vm size */ ObjectFileScrubbers.getLittleEndianInt(map); /* segment file offset */ ObjectFileScrubbers.getLittleEndianInt(map); segmentFileSizePosition = map.position(); segmentFileSize = ObjectFileScrubbers.getLittleEndianInt(map); /* maximum vm protection */ ObjectFileScrubbers.getLittleEndianInt(map); /* initial vm protection */ ObjectFileScrubbers.getLittleEndianInt(map); /* number of sections */ ObjectFileScrubbers.getLittleEndianInt(map); /* flags */ ObjectFileScrubbers.getLittleEndianInt(map); if (segmentSizePosition != 0) { throw new MachoException("multiple map segment commands map string table"); } segmentSizePosition = segmentFileSizePosition; segmentSize = segmentFileSize; } break; case LC_SEGMENT_64: byte[] segment64NameBytes = ObjectFileScrubbers.getBytes(map, 16); String segment64Name = new String(segment64NameBytes, Charsets.US_ASCII); if (segment64Name.startsWith(LINKEDIT)) { linkEditSegmentFound = true; /* vm address */ ObjectFileScrubbers.getLittleEndianLong(map); /* vm size */ ObjectFileScrubbers.getLittleEndianLong(map); /* segment file offset */ ObjectFileScrubbers.getLittleEndianLong(map); segment64FileSizePosition = map.position(); segment64FileSize = ObjectFileScrubbers.getLittleEndianLong(map); /* maximum vm protection */ ObjectFileScrubbers.getLittleEndianInt(map); /* initial vm protection */ ObjectFileScrubbers.getLittleEndianInt(map); /* number of sections */ ObjectFileScrubbers.getLittleEndianInt(map); /* flags */ ObjectFileScrubbers.getLittleEndianInt(map); if (segmentSizePosition != 0) { throw new MachoException("multiple map segment commands map string table"); } segmentSizePosition = segment64FileSizePosition; if (segment64FileSize > Ints.MAX_POWER_OF_TWO) { throw new MachoException("map segment file size too big"); } segmentSize = (int) segment64FileSize; } break; } map.position(commandStart + commandSize); } if (!linkEditSegmentFound) { /*The OSO entries are identified in segments named __LINKEDIT. If no segment is found with that name, there is nothing to scrub.*/ return; } if (!symbolTableSegmentFound) { throw new MachoException("LC_SYMTAB command not found"); } if (stringTableOffset + stringTableSize != size) { throw new MachoException("String table does not end at end of file"); } if (stringTableSize == 0) { return; } if (segmentSizePosition == 0 || segmentSize == 0) { throw new MachoException("LC_SEGMENT or LC_SEGMENT_64 command for string table not found"); } map.position(stringTableOffset); if (map.get() != 0x20) { throw new MachoException("First character in the string table is not a space"); } if (map.get() != 0x00) { throw new MachoException("Second character in the string table is not a NUL"); } int currentStringTableOffset = map.position(); byte[] stringTableBytes = new byte[stringTableSize]; map.position(stringTableOffset); map.get(stringTableBytes); ByteBuffer stringTable = ByteBuffer.wrap(stringTableBytes); map.position(symbolTableOffset); Map<Integer, Integer> strings = new HashMap<>(); for (int i = 0; i < symbolTableCount; i++) { int stringTableIndexPosition = map.position(); int stringTableIndex = ObjectFileScrubbers.getLittleEndianInt(map); byte type = map.get(); /* section */ map.get(); /* description */ ObjectFileScrubbers.getLittleEndianShort(map); int valuePosition = map.position(); if (header.getIs64Bit()) { /* value */ ObjectFileScrubbers.getLittleEndianLong(map); } else { /* value */ ObjectFileScrubbers.getLittleEndianInt(map); } if (stringTableIndex < 2) { continue; } int position = map.position(); try { int newStringTableIndex; if (strings.containsKey(stringTableIndex)) { newStringTableIndex = strings.get(stringTableIndex); } else { stringTable.position(stringTableIndex); String string = ObjectFileScrubbers.getAsciiString(stringTable); if (type == N_OSO) { for (Map.Entry<Path, Path> root : cellRoots.entrySet()) { String rootPrefix = root.getKey() + "/"; if (string.startsWith(rootPrefix)) { String replacementPrefix = root.getValue().toString(); if (replacementPrefix.equals("")) { replacementPrefix = "."; } string = replacementPrefix + "/" + string.substring(rootPrefix.length()); } } map.position(valuePosition); int lastModifiedValue = ObjectFileCommonModificationDate.COMMON_MODIFICATION_TIME_STAMP; if (header.getIs64Bit()) { ObjectFileScrubbers.putLittleEndianLong(map, lastModifiedValue); } else { ObjectFileScrubbers.putLittleEndianInt(map, lastModifiedValue); } } map.position(currentStringTableOffset); ObjectFileScrubbers.putAsciiString(map, string); newStringTableIndex = currentStringTableOffset - stringTableOffset; currentStringTableOffset = map.position(); strings.put(stringTableIndex, newStringTableIndex); } map.position(stringTableIndexPosition); ObjectFileScrubbers.putLittleEndianInt(map, newStringTableIndex); } finally { map.position(position); } } map.position(stringTableSizePosition); int newStringTableSize = currentStringTableOffset - stringTableOffset; ObjectFileScrubbers.putLittleEndianInt(map, newStringTableSize); map.position(segmentSizePosition); ObjectFileScrubbers.putLittleEndianInt(map, segmentSize + (newStringTableSize - stringTableSize)); file.truncate(currentStringTableOffset); }
From source file:org.onosproject.ra.cli.GlobalPrefixesListCommand.java
private void printGlobalPrefixes(ImmutableMap<DeviceId, List<InterfaceIpAddress>> globalPrefixes) { globalPrefixes.forEach(((deviceId, interfaceIpAddresses) -> { print("%s", deviceId); interfaceIpAddresses.forEach(interfaceIpAddress -> print(" %s", interfaceIpAddress)); }));/* w ww . java 2s. c o m*/ }
From source file:org.locationtech.geogig.rocksdb.RocksConnectionManager.java
@Override protected DBHandle connect(DBConfig dbconfig) { LOG.debug("opening {}", dbconfig); RocksDB.loadLibrary();/*from www . ja v a 2 s . c o m*/ org.rocksdb.DBOptions dbOptions = new org.rocksdb.DBOptions(); dbOptions.setCreateIfMissing(true)// .setAdviseRandomOnOpen(true)// .setAllowMmapReads(true)// .setAllowMmapWrites(true)// .setAllowOsBuffer(true)// .setBytesPerSync(64 * 1024 * 1024); RocksDB db; final String path = dbconfig.getDbPath(); final List<String> colFamilyNames; try { colFamilyNames = Lists.transform(RocksDB.listColumnFamilies(new Options(), path), (ba) -> new String(ba, Charsets.UTF_8)); } catch (RocksDBException e) { dbOptions.close(); throw Throwables.propagate(e); } // at least the "default" column family shall exists if the db was already created final boolean dbExists = !colFamilyNames.isEmpty(); final boolean metadataExists = colFamilyNames.contains("metadata"); final boolean readOnly = dbconfig.isReadOnly(); @Nullable ColumnFamilyHandle metadata = null; Map<String, ColumnFamilyHandle> extraColumns = new HashMap<>(); try { List<ColumnFamilyDescriptor> colDescriptors = new ArrayList<>(); for (String name : colFamilyNames) { byte[] colFamilyName = name.getBytes(Charsets.UTF_8); ColumnFamilyOptions colFamilyOptions = newColFamilyOptions(); colDescriptors.add(new ColumnFamilyDescriptor(colFamilyName, colFamilyOptions)); } DBHandle dbHandle; if (readOnly) { List<ColumnFamilyHandle> colFamiliesTarget = new ArrayList<>(); Preconditions.checkState(dbExists, "database does not exist: %s", path); db = RocksDB.openReadOnly(dbOptions, path, colDescriptors, colFamiliesTarget); if (metadataExists) { metadata = colFamiliesTarget.get(colFamilyNames.indexOf("metadata")); } for (int i = 0; i < colDescriptors.size(); i++) { String name = colFamilyNames.get(i); if (!"metadata".equals(name)) { ColumnFamilyHandle handle = colFamiliesTarget.get(i); extraColumns.put(name, handle); } } dbHandle = new DBHandle(dbconfig, dbOptions, db, metadata, extraColumns); } else { if (!dbExists) { colDescriptors.add(newColDescriptor("default")); for (String name : dbconfig.getColumnFamilyNames()) { if (colFamilyNames.indexOf(name) > -1) { colDescriptors.add(newColDescriptor(name)); } } } List<ColumnFamilyHandle> colFamiliesTarget = new ArrayList<>(); db = RocksDB.open(dbOptions, path, colDescriptors, colFamiliesTarget); if (metadataExists) { metadata = colFamiliesTarget.get(colFamilyNames.indexOf("metadata")); } else { ColumnFamilyDescriptor mdd = newColDescriptor("metadata"); metadata = db.createColumnFamily(mdd); } for (String name : dbconfig.getColumnFamilyNames()) { ColumnFamilyDescriptor colDescriptor; ColumnFamilyHandle colHandle; if (colFamilyNames.indexOf(name) == -1) { colDescriptor = newColDescriptor(name); colHandle = db.createColumnFamily(colDescriptor); } else { int colIndex = colFamilyNames.indexOf(name); colHandle = colFamiliesTarget.get(colIndex); } extraColumns.put(name, colHandle); } dbHandle = new DBHandle(dbconfig, dbOptions, db, metadata, extraColumns); // save default metadata if (!dbExists) { ImmutableMap<String, String> defaultMetadata = dbconfig.getDefaultMetadata(); defaultMetadata.forEach((k, v) -> dbHandle.setMetadata(k, v)); } } return dbHandle; } catch (Exception e) { throw Throwables.propagate(e); } }
From source file:com.facebook.buck.rules.modern.impl.DefaultClassInfo.java
DefaultClassInfo(Class<?> clazz, Optional<ClassInfo<? super T>> superInfo) { this.type = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, clazz.getSimpleName()).intern(); this.superInfo = superInfo; Optional<Class<?>> immutableBase = findImmutableBase(clazz); ImmutableList.Builder<FieldInfo<?>> fieldsBuilder = ImmutableList.builder(); if (immutableBase.isPresent()) { ImmutableMap<Field, Boolean> parameterFields = parameterFieldsFromFields(clazz); ImmutableMap<Field, Method> parameterMethods = findMethodsForFields(parameterFields.keySet(), clazz); parameterFields.forEach((field, isLazy) -> { Method method = parameterMethods.get(field); if (method == null) { return; }/*from w w w . j av a 2 s . co m*/ AddToRuleKey addAnnotation = method.getAnnotation(AddToRuleKey.class); // TODO(cjhopman): Add @ExcludeFromRuleKey annotation and require that all fields are // either explicitly added or explicitly excluded. Optional<CustomFieldBehavior> customBehavior = Optional .ofNullable(method.getDeclaredAnnotation(CustomFieldBehavior.class)); if (addAnnotation != null && !addAnnotation.stringify()) { if (isLazy) { throw new RuntimeException( "@Value.Lazy fields cannot be @AddToRuleKey, change it to @Value.Derived."); } Nullable methodNullable = method.getAnnotation(Nullable.class); boolean methodOptional = Optional.class.isAssignableFrom(method.getReturnType()); fieldsBuilder.add( forFieldWithBehavior(field, methodNullable != null || methodOptional, customBehavior)); } else { fieldsBuilder.add(excludedField(field, customBehavior)); } }); } else { for (final Field field : clazz.getDeclaredFields()) { // TODO(cjhopman): Make this a Precondition. if (!Modifier.isFinal(field.getModifiers())) { LOG.warn("All fields of a Buildable must be final (%s.%s)", clazz.getSimpleName(), field.getName()); } if (Modifier.isStatic(field.getModifiers())) { continue; } field.setAccessible(true); Optional<CustomFieldBehavior> customBehavior = Optional .ofNullable(field.getDeclaredAnnotation(CustomFieldBehavior.class)); AddToRuleKey addAnnotation = field.getAnnotation(AddToRuleKey.class); // TODO(cjhopman): Add @ExcludeFromRuleKey annotation and require that all fields are either // explicitly added or explicitly excluded. if (addAnnotation != null && !addAnnotation.stringify()) { fieldsBuilder.add(forFieldWithBehavior(field, field.getAnnotation(Nullable.class) != null, customBehavior)); } else { fieldsBuilder.add(excludedField(field, customBehavior)); } } } if (clazz.isMemberClass()) { // TODO(cjhopman): This should also iterate over the outer class's class hierarchy. Class<?> outerClazz = clazz.getDeclaringClass(); // I don't think this can happen, but if it does, this needs to be updated to handle it // correctly. Preconditions.checkArgument( !outerClazz.isAnonymousClass() && !outerClazz.isMemberClass() && !outerClazz.isLocalClass()); for (final Field field : outerClazz.getDeclaredFields()) { field.setAccessible(true); if (!Modifier.isStatic(field.getModifiers())) { continue; } // TODO(cjhopman): Make this a Precondition. if (!Modifier.isFinal(field.getModifiers())) { LOG.warn("All static fields of a Buildable's outer class must be final (%s.%s)", outerClazz.getSimpleName(), field.getName()); } } } this.fields = fieldsBuilder.build(); }
From source file:net.navatwo.jfxproperties.RealPropertyObjectBuilder.java
/** * Provides a breadth-first component to build up the tree of all of the {@link PropertyObject} found * in the {@link #base} type's hierarchy. * * @param cache Known {@link PropertyObject} instances to save lookup times * @return Mapping of classes to their associated {@link PropertyObject} value *//*from w w w .ja v a2 s .co m*/ ImmutableMap<Class<?>, PropertyObject<?>> build(ImmutableMap<Class<?>, PropertyObject<?>> cache) { logger.traceEntry("Builder.RealBuilder#build(cache: {} entries)", cache.size()); // Utilize the cache by adding all the known entites to the #allCollectors field cache.forEach( (type, propertyObject) -> allCollectors.put(type, new TypePropertiesCollector(propertyObject))); // Do a breadth-first search from the bottom of the class hierarchy // and add fields/methods as they're found. If a type has interfaces, we // check those, too! // "visit" action is done by creating a new TypePropertiesCollector to visit the class found. Deque<Class<?>> q = new ArrayDeque<>(); q.addLast(base.getRawType()); visited.add(Object.class); // do this so it never tries to keep going higher // Mark all of the known classes as visited visited.addAll(allCollectors.keySet()); // Do a DFS via the TypePropertiesCollector#collect method while (!q.isEmpty()) { final Class<?> currentClazz = q.pop(); final TypeToken<?> current = base.resolveType(currentClazz); if (isTypeBadPredicate.test(currentClazz) || visited.contains(currentClazz)) { continue; } TypePropertiesCollector c = new TypePropertiesCollector(current); c.collect(q); allCollectors.put(currentClazz, c); } logger.trace("Finished breadth-first search to find all fields/methods"); throwIfPropertyErrors(); // Do a DFS to build up all of the Collectors Deque<TypePropertiesCollector> dfsPath = new ArrayDeque<>(); buildHierarchyRec(dfsPath, new HashSet<>(), allCollectors.get(base.getRawType())); Map<Class<?>, PropertyObject<?>> builtObjects = new HashMap<>(); while (!dfsPath.isEmpty()) { TypePropertiesCollector current = dfsPath.pop(); TypeToken<?> type = current.getBase(); // Get the super TypePropertiesCollectors List<? extends PropertyObject<?>> supers = Stream .concat(Stream.of(type.getRawType().getSuperclass()), Arrays.stream(type.getRawType().getInterfaces())) .filter(Objects::nonNull).filter(isTypeBadPredicate.negate()).map(t -> { PropertyObject<?> po = builtObjects.get(t); checkState(po != null, "PropertyObject not loaded before super requested, " + "super: %s, base: %s", t, type); return po; }).collect(Collectors.toList()); @SuppressWarnings("unchecked") // I hate this, but its required :( PropertyObject<?> po = (PropertyObject<?>) new PropertyObject(type, supers, current.ignoredProperties, current.propertyTypes, current.fieldsMap, current.methodsMap); builtObjects.put(type.getRawType(), po); } // Now the maps have all been filled, we pass the values to the PropertyObject constructor to // let it decide how to format them. return logger.traceExit(ImmutableMap.copyOf(builtObjects)); }