List of usage examples for com.google.common.collect Multimap asMap
Map<K, Collection<V>> asMap();
From source file:com.continuuity.http.BasicHttpResponder.java
@Override public void sendFile(File file, Multimap<String, String> headers) { HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); response.setHeader(HttpHeaders.Names.CONTENT_LENGTH, file.length()); if (keepalive) { response.setHeader(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE); }/*ww w .jav a2 s . c om*/ // Add headers, note will override all headers set by the framework if (headers != null) { for (Map.Entry<String, Collection<String>> entry : headers.asMap().entrySet()) { response.setHeader(entry.getKey(), entry.getValue()); } } // Write the initial line and the header. channel.write(response); // Write the content. ChannelFuture writeFuture; try { FileChannel fc = new RandomAccessFile(file, "r").getChannel(); final FileRegion region = new DefaultFileRegion(fc, 0, file.length()); writeFuture = channel.write(region); writeFuture.addListener(new ChannelFutureProgressListener() { public void operationComplete(ChannelFuture future) { region.releaseExternalResources(); if (!keepalive) { channel.close(); } } @Override public void operationProgressed(ChannelFuture future, long amount, long current, long total) throws Exception { // no-op } }); } catch (IOException e) { throw Throwables.propagate(e); } }
From source file:com.facebook.presto.accumulo.index.ColumnCardinalityCache.java
/** * Gets the cardinality for each {@link AccumuloColumnConstraint}. * Given constraints are expected to be indexed! Who knows what would happen if they weren't! * * @param schema Schema name//from w w w. jav a 2 s . c om * @param table Table name * @param auths Scan authorizations * @param idxConstraintRangePairs Mapping of all ranges for a given constraint * @param earlyReturnThreshold Smallest acceptable cardinality to return early while other tasks complete * @param pollingDuration Duration for polling the cardinality completion service * @return An immutable multimap of cardinality to column constraint, sorted by cardinality from smallest to largest * @throws TableNotFoundException If the metrics table does not exist * @throws ExecutionException If another error occurs; I really don't even know anymore. */ public Multimap<Long, AccumuloColumnConstraint> getCardinalities(String schema, String table, Authorizations auths, Multimap<AccumuloColumnConstraint, Range> idxConstraintRangePairs, long earlyReturnThreshold, Duration pollingDuration) throws ExecutionException, TableNotFoundException { // Submit tasks to the executor to fetch column cardinality, adding it to the Guava cache if necessary CompletionService<Pair<Long, AccumuloColumnConstraint>> executor = new ExecutorCompletionService<>( executorService); idxConstraintRangePairs.asMap().forEach((key, value) -> executor.submit(() -> { long cardinality = getColumnCardinality(schema, table, auths, key.getFamily(), key.getQualifier(), value); LOG.debug("Cardinality for column %s is %s", key.getName(), cardinality); return Pair.of(cardinality, key); })); // Create a multi map sorted by cardinality ListMultimap<Long, AccumuloColumnConstraint> cardinalityToConstraints = MultimapBuilder.treeKeys() .arrayListValues().build(); try { boolean earlyReturn = false; int numTasks = idxConstraintRangePairs.asMap().entrySet().size(); do { // Sleep for the polling duration to allow concurrent tasks to run for this time Thread.sleep(pollingDuration.toMillis()); // Poll each task, retrieving the result if it is done for (int i = 0; i < numTasks; ++i) { Future<Pair<Long, AccumuloColumnConstraint>> futureCardinality = executor.poll(); if (futureCardinality != null && futureCardinality.isDone()) { Pair<Long, AccumuloColumnConstraint> columnCardinality = futureCardinality.get(); cardinalityToConstraints.put(columnCardinality.getLeft(), columnCardinality.getRight()); } } // If the smallest cardinality is present and below the threshold, set the earlyReturn flag Optional<Entry<Long, AccumuloColumnConstraint>> smallestCardinality = cardinalityToConstraints .entries().stream().findFirst(); if (smallestCardinality.isPresent()) { if (smallestCardinality.get().getKey() <= earlyReturnThreshold) { LOG.info("Cardinality %s, is below threshold. Returning early while other tasks finish", smallestCardinality); earlyReturn = true; } } } while (!earlyReturn && cardinalityToConstraints.entries().size() < numTasks); } catch (ExecutionException | InterruptedException e) { if (e instanceof InterruptedException) { Thread.currentThread().interrupt(); } throw new PrestoException(UNEXPECTED_ACCUMULO_ERROR, "Exception when getting cardinality", e); } // Create a copy of the cardinalities return ImmutableMultimap.copyOf(cardinalityToConstraints); }
From source file:com.ngdata.hbaseindexer.indexer.Indexer.java
/** * groups a list of ids by shard//from w w w. j ava2s . c o m * (consider moving this to a BaseSharder class) */ private Map<Integer, Collection<String>> shardByValue(List<String> idsToDelete) { Multimap<Integer, String> map = Multimaps.index(idsToDelete, new Function<String, Integer>() { @Override public Integer apply(@Nullable String id) { try { return sharder.getShard(id); } catch (SharderException e) { throw new RuntimeException("error calculating hash", e); } } }); return map.asMap(); }
From source file:com.proofpoint.discovery.ConfigStore.java
@Inject public ConfigStore(final ConfigStoreConfig config) { Multimap<TypeAndPool, Service> multimap = HashMultimap.create(); for (Entry<String, StaticAnnouncementConfig> entry : config.getAnnouncements().entrySet()) { Service service = new Service(Id.valueOf(UUID.nameUUIDFromBytes(entry.getKey().getBytes(UTF_8))), null, entry.getValue().getType(), entry.getValue().getPool(), "/somewhere/" + entry.getKey(), entry.getValue().getProperties()); multimap.put(/*from w ww . j a v a 2 s. c o m*/ new AutoValue_ConfigStore_TypeAndPool(entry.getValue().getType(), entry.getValue().getPool()), service); } ImmutableTable.Builder<String, String, Collection<Service>> builder = ImmutableTable.builder(); for (Entry<TypeAndPool, Collection<Service>> entry : multimap.asMap().entrySet()) { builder.put(entry.getKey().getType(), entry.getKey().getPool(), ImmutableList.copyOf(entry.getValue())); } table = builder.build(); }
From source file:co.cask.cdap.internal.app.deploy.pipeline.DeletedProgramHandlerStage.java
@Override public void process(ApplicationDeployable appSpec) throws Exception { List<ProgramSpecification> deletedSpecs = store.getDeletedProgramSpecifications(appSpec.getId(), appSpec.getSpecification()); // TODO: this should also delete logs and run records (or not?), and do it for all prohgram types [CDAP-2187] List<String> deletedFlows = Lists.newArrayList(); for (ProgramSpecification spec : deletedSpecs) { //call the deleted spec ProgramType type = ProgramTypes.fromSpecification(spec); Id.Program programId = Id.Program.from(appSpec.getId(), type, spec.getName()); programTerminator.stop(programId); // TODO: Unify with AppFabricHttpHandler.removeApplication // drop all queues and stream states of a deleted flow if (ProgramType.FLOW.equals(type)) { FlowSpecification flowSpecification = (FlowSpecification) spec; // Collects stream name to all group ids consuming that stream Multimap<String, Long> streamGroups = HashMultimap.create(); for (FlowletConnection connection : flowSpecification.getConnections()) { if (connection.getSourceType() == FlowletConnection.Type.STREAM) { long groupId = FlowUtils.generateConsumerGroupId(programId, connection.getTargetName()); streamGroups.put(connection.getSourceName(), groupId); }/*from ww w. j a v a 2s . co m*/ } // Remove all process states and group states for each stream String namespace = String.format("%s.%s", programId.getApplicationId(), programId.getId()); for (Map.Entry<String, Collection<Long>> entry : streamGroups.asMap().entrySet()) { streamConsumerFactory.dropAll(Id.Stream.from(appSpec.getId().getNamespaceId(), entry.getKey()), namespace, entry.getValue()); } queueAdmin.dropAllForFlow(Id.Flow.from(programId.getApplication(), programId.getId())); deletedFlows.add(programId.getId()); } } if (!deletedFlows.isEmpty()) { deleteMetrics(appSpec.getId().getNamespaceId(), appSpec.getId().getId(), deletedFlows); } emit(appSpec); }
From source file:org.apache.calcite.rel.metadata.JaninoRelMetadataProvider.java
private static <M extends Metadata> MetadataHandler<M> load3(MetadataDef<M> def, Multimap<Method, MetadataHandler<M>> map, ImmutableList<Class<? extends RelNode>> relClasses) { final StringBuilder buff = new StringBuilder(); final String name = "GeneratedMetadataHandler_" + def.metadataClass.getSimpleName(); final Set<MetadataHandler> providerSet = new HashSet<>(); final List<Pair<String, MetadataHandler>> providerList = new ArrayList<>(); //noinspection unchecked final ReflectiveRelMetadataProvider.Space space = new ReflectiveRelMetadataProvider.Space((Multimap) map); for (MetadataHandler provider : space.providerMap.values()) { if (providerSet.add(provider)) { providerList.add(Pair.of("provider" + (providerSet.size() - 1), provider)); }//ww w . ja va 2 s .co m } buff.append(" private final java.util.List relClasses;\n"); for (Pair<String, MetadataHandler> pair : providerList) { buff.append(" public final ").append(pair.right.getClass().getName()).append(' ').append(pair.left) .append(";\n"); } buff.append(" public ").append(name).append("(java.util.List relClasses"); for (Pair<String, MetadataHandler> pair : providerList) { buff.append(",\n").append(" ").append(pair.right.getClass().getName()).append(' ') .append(pair.left); } buff.append(") {\n").append(" this.relClasses = relClasses;\n"); for (Pair<String, MetadataHandler> pair : providerList) { buff.append(" this.").append(pair.left).append(" = ").append(pair.left).append(";\n"); } buff.append(" }\n").append(" public ").append(MetadataDef.class.getName()).append(" getDef() {\n") .append(" return ").append(def.metadataClass.getName()).append(".DEF;\n").append(" }\n"); for (Ord<Method> method : Ord.zip(def.methods)) { buff.append(" public ").append(method.e.getReturnType().getName()).append(" ") .append(method.e.getName()).append("(\n").append(" ").append(RelNode.class.getName()) .append(" r,\n").append(" ").append(RelMetadataQuery.class.getName()).append(" mq"); paramList(buff, method.e).append(") {\n"); buff.append(" final java.util.List key = ") .append((method.e.getParameterTypes().length < 4 ? org.apache.calcite.runtime.FlatLists.class : ImmutableList.class).getName()) .append(".of(").append(def.metadataClass.getName()); if (method.i == 0) { buff.append(".DEF"); } else { buff.append(".DEF.methods.get(").append(method.i).append(")"); } buff.append(", r"); safeArgList(buff, method.e).append(");\n").append(" final Object v = mq.map.get(key);\n") .append(" if (v != null) {\n").append(" if (v == ").append(NullSentinel.class.getName()) .append(".ACTIVE) {\n").append(" throw ").append(CyclicMetadataException.class.getName()) .append(".INSTANCE;\n").append(" }\n").append(" return (") .append(method.e.getReturnType().getName()).append(") v;\n").append(" }\n") .append(" mq.map.put(key,").append(NullSentinel.class.getName()).append(".ACTIVE);\n") .append(" try {\n").append(" final ").append(method.e.getReturnType().getName()) .append(" x = ").append(method.e.getName()).append("_(r, mq"); argList(buff, method.e).append(");\n").append(" mq.map.put(key, x);\n").append(" return x;\n") .append(" } catch (").append(NoHandler.class.getName()).append(" e) {\n") .append(" mq.map.remove(key);\n").append(" throw e;\n").append(" }\n") .append(" }\n").append("\n").append(" private ").append(method.e.getReturnType().getName()) .append(" ").append(method.e.getName()).append("_(\n").append(" ") .append(RelNode.class.getName()).append(" r,\n").append(" ") .append(RelMetadataQuery.class.getName()).append(" mq"); paramList(buff, method.e).append(") {\n"); buff.append(" switch (relClasses.indexOf(r.getClass())) {\n"); // Build a list of clauses, grouping clauses that have the same action. final Multimap<String, Integer> clauses = LinkedHashMultimap.create(); final StringBuilder buf2 = new StringBuilder(); for (Ord<Class<? extends RelNode>> relClass : Ord.zip(relClasses)) { if (relClass.e == HepRelVertex.class) { buf2.append(" return ").append(method.e.getName()).append("(((") .append(relClass.e.getName()).append(") r).getCurrentRel(), mq"); argList(buf2, method.e).append(");\n"); } else { final Method handler = space.find(relClass.e, method.e); final String v = findProvider(providerList, handler.getDeclaringClass()); buf2.append(" return ").append(v).append(".").append(method.e.getName()).append("((") .append(handler.getParameterTypes()[0].getName()).append(") r, mq"); argList(buf2, method.e).append(");\n"); } clauses.put(buf2.toString(), relClass.i); buf2.setLength(0); } buf2.append(" throw new ").append(NoHandler.class.getName()).append("(r.getClass());\n") .append(" }\n").append(" }\n"); clauses.put(buf2.toString(), -1); for (Map.Entry<String, Collection<Integer>> pair : clauses.asMap().entrySet()) { if (pair.getValue().contains(relClasses.indexOf(RelNode.class))) { buff.append(" default:\n"); } else { for (Integer integer : pair.getValue()) { buff.append(" case ").append(integer).append(":\n"); } } buff.append(pair.getKey()); } } ClassDeclaration decl = new ClassDeclaration(0, name, Object.class, ImmutableList.<Type>of(), ImmutableList.<MemberDeclaration>of()); final List<Object> argList = new ArrayList<Object>(Pair.right(providerList)); argList.add(0, ImmutableList.copyOf(relClasses)); try { return compile(decl, buff.toString(), def, argList); } catch (CompileException | IOException e) { throw new RuntimeException("Error compiling:\n" + buff, e); } }
From source file:org.apache.archiva.redback.common.ldap.role.DefaultLdapRoleMapperConfiguration.java
public Map<String, Collection<String>> getLdapGroupMappings() { Multimap<String, String> map = ArrayListMultimap.create(); Collection<String> keys = userConf.getKeys(); for (String key : keys) { if (key.startsWith(UserConfigurationKeys.LDAP_GROUPS_ROLE_START_KEY)) { String val = userConf.getString(key); String[] roles = StringUtils.split(val, ','); for (String role : roles) { map.put(StringUtils.substringAfter(key, UserConfigurationKeys.LDAP_GROUPS_ROLE_START_KEY), role);// w w w. j av a 2s. c o m } } } for (Map.Entry<String, List<String>> entry : this.ldapMappings.entrySet()) { map.putAll(entry.getKey(), entry.getValue()); } Map<String, Collection<String>> mappings = map.asMap(); return mappings; }
From source file:org.apache.hadoop.hive.ql.exec.tez.CustomPartitionVertex.java
private void processAllEvents(String inputName, Multimap<Integer, InputSplit> bucketToGroupedSplitMap, boolean secondLevelGroupingDone) throws IOException { int totalInputsCount = 0; List<Integer> numSplitsForTask = new ArrayList<Integer>(); for (Entry<Integer, Collection<InputSplit>> entry : bucketToGroupedSplitMap.asMap().entrySet()) { int bucketNum = entry.getKey(); Collection<InputSplit> initialSplits = entry.getValue(); finalSplits.addAll(initialSplits); for (InputSplit inputSplit : initialSplits) { bucketToTaskMap.put(bucketNum, taskCount); if (secondLevelGroupingDone) { TezGroupedSplit groupedSplit = (TezGroupedSplit) inputSplit; numSplitsForTask.add(groupedSplit.getGroupedSplits().size()); totalInputsCount += groupedSplit.getGroupedSplits().size(); } else { numSplitsForTask.add(1); totalInputsCount += 1;//from w w w . j av a 2 s .c o m } taskCount++; } } inputNameInputSpecMap.put(inputName, InputSpecUpdate.createPerTaskInputSpecUpdate(numSplitsForTask)); // Construct the EdgeManager descriptor to be used by all edges which need // the routing table. EdgeManagerPluginDescriptor hiveEdgeManagerDesc = null; if ((vertexType == VertexType.MULTI_INPUT_INITIALIZED_EDGES) || (vertexType == VertexType.INITIALIZED_EDGES)) { hiveEdgeManagerDesc = EdgeManagerPluginDescriptor.create(CustomPartitionEdge.class.getName()); UserPayload payload = getBytePayload(bucketToTaskMap); hiveEdgeManagerDesc.setUserPayload(payload); } // Replace the edge manager for all vertices which have routing type custom. for (Entry<String, EdgeProperty> edgeEntry : context.getInputVertexEdgeProperties().entrySet()) { if (edgeEntry.getValue().getDataMovementType() == DataMovementType.CUSTOM && edgeEntry.getValue() .getEdgeManagerDescriptor().getClassName().equals(CustomPartitionEdge.class.getName())) { emMap.put(edgeEntry.getKey(), hiveEdgeManagerDesc); } } LOG.info("Task count is " + taskCount + " for input name: " + inputName); List<InputDataInformationEvent> taskEvents = Lists.newArrayListWithCapacity(totalInputsCount); // Re-serialize the splits after grouping. int count = 0; for (InputSplit inputSplit : finalSplits) { if (secondLevelGroupingDone) { TezGroupedSplit tezGroupedSplit = (TezGroupedSplit) inputSplit; for (InputSplit subSplit : tezGroupedSplit.getGroupedSplits()) { if ((subSplit instanceof TezGroupedSplit) == false) { throw new IOException( "Unexpected split type found: " + subSplit.getClass().getCanonicalName()); } MRSplitProto serializedSplit = MRInputHelpers.createSplitProto(subSplit); InputDataInformationEvent diEvent = InputDataInformationEvent.createWithSerializedPayload(count, serializedSplit.toByteString().asReadOnlyByteBuffer()); diEvent.setTargetIndex(count); taskEvents.add(diEvent); } } else { MRSplitProto serializedSplit = MRInputHelpers.createSplitProto(inputSplit); InputDataInformationEvent diEvent = InputDataInformationEvent.createWithSerializedPayload(count, serializedSplit.toByteString().asReadOnlyByteBuffer()); diEvent.setTargetIndex(count); taskEvents.add(diEvent); } count++; } // Set the actual events for the tasks. LOG.info("For input name: " + inputName + " task events size is " + taskEvents.size()); context.addRootInputEvents(inputName, taskEvents); if (inputToGroupedSplitMap.isEmpty() == false) { for (Entry<String, Multimap<Integer, InputSplit>> entry : inputToGroupedSplitMap.entrySet()) { processAllSideEvents(entry.getKey(), entry.getValue()); } setVertexParallelismAndRootInputSpec(inputNameInputSpecMap); inputToGroupedSplitMap.clear(); } // Only done when it is a bucket map join only no SMB. if (numInputsAffectingRootInputSpecUpdate == 1) { setVertexParallelismAndRootInputSpec(inputNameInputSpecMap); } }
From source file:org.openflexo.dg.action.ReinjectDocx.java
public Multimap<EditionPatternInstance, IParsedFlexoEPI> removeConflictingParsedDocX( Multimap<EditionPatternInstance, IParsedFlexoEPI> epis) { Multimap<EditionPatternInstance, IParsedFlexoEPI> episToReinject = ArrayListMultimap.create(); Multimap<String, IParsedFlexoEPI> paths = ArrayListMultimap.create(); for (Entry<EditionPatternInstance, Collection<IParsedFlexoEPI>> e : epis.asMap().entrySet()) { if (e.getValue().size() > 1) { // There are multiple parsed DocX EPI for this EditionPatternInstance // Let's see if it is for the same binding path for (IParsedFlexoEPI epi : e.getValue()) { paths.put(epi.getBindingPath(), epi); }/*w ww. j a v a 2 s . co m*/ for (Entry<String, Collection<IParsedFlexoEPI>> e1 : paths.asMap().entrySet()) { boolean conflict = false; if (e1.getValue().size() > 1) { // There are multiple parsed DocX EPI for the same EPI and the same binding path Object currentValue = e.getKey().evaluate(e1.getKey()); List<IParsedFlexoEPI> modified = new ArrayList<IParsedFlexoEPI>(); for (IParsedFlexoEPI epi : e1.getValue()) { if (!epi.getValue().equals(currentValue)) { modified.add(epi); } } if (modified.size() > 1) { // There is more than one parsed DocX EPI that has a different value than the current one // Let's see if they are not all the same. String value = modified.get(0).getValue(); for (int i = 1; i < modified.size(); i++) { if (!value.equals(modified.get(i).getValue())) { conflict = true; errorReport.append("Conflicting values: ").append(value + " ") .append(modified.get(i).getValue()).append("\n"); break; } } } } if (!conflict) { episToReinject.putAll(e.getKey(), e1.getValue()); } } } else { // There is a single parsed DocX EPI for this EditionPatternInstance episToReinject.putAll(e.getKey(), e.getValue()); } paths.clear(); } return episToReinject; }
From source file:eu.itesla_project.eurostag.network.EsgNetwork.java
public void checkConsistency() { // check there is at least one node and a slack bus if (nodes.size() < 1) { throw new RuntimeException("Network must have at least one node"); }/*from ww w.java2 s . c o m*/ int slackBusCount = 0; for (EsgNode node : nodes.values()) { if (node.isSlackBus()) { slackBusCount++; } } if (slackBusCount == 0) { throw new RuntimeException("Network must have at least one slack bus"); } for (EsgNode node : getNodes()) { if (getArea(node.getArea().toString()) == null) { throw new RuntimeException( "Node '" + node.getName() + "' reference an unknown area '" + node.getArea() + "'"); } } for (EsgLine line : getLines()) { checkBranchName(line.getName()); } for (EsgCouplingDevice device : getCouplingDevices()) { checkBranchName(device.getName()); } for (EsgDissymmetricalBranch branch : getDissymmetricalBranches()) { checkBranchName(branch.getName()); } for (EsgDetailedTwoWindingTransformer transformer : getDetailedTwoWindingTransformers()) { checkBranchName(transformer.getName()); if (transformer.getZbusr() != null && getNode(transformer.getZbusr().toString()) == null) { throw new RuntimeException("Transformer '" + transformer.getName() + "' reference an unknown regulating node '" + transformer.getZbusr() + "'"); } } for (EsgLoad load : getLoads()) { if (getNode(load.getZnodlo().toString()) == null) { throw new RuntimeException("Load '" + load.getZnamlo() + "' reference an unknown connection node '" + load.getZnodlo() + "'"); } } for (EsgGenerator generator : getGenerators()) { if (getNode(generator.getZnodge().toString()) == null) { throw new RuntimeException("Generator '" + generator.getZnamge() + "' reference an unknown connection node '" + generator.getZnodge() + "'"); } if (getNode(generator.getZregnoge().toString()) == null) { throw new RuntimeException("Generator '" + generator.getZnamge() + "' reference an unknown regulating node '" + generator.getZregnoge() + "'"); } } for (EsgCapacitorOrReactorBank bank : getCapacitorOrReactorBanks()) { if (getNode(bank.getZnodba().toString()) == null) { throw new RuntimeException("Capacitor or reactor bank '" + bank.getZnamba() + "' reference an unknown connection node '" + bank.getZnodba() + "'"); } } for (EsgStaticVarCompensator svc : getStaticVarCompensators()) { if (getNode(svc.getZnodsvc().toString()) == null) { throw new RuntimeException("Static VAR compensator '" + svc.getZnamsvc() + "' reference an unknown connection node '" + svc.getZnodsvc() + "'"); } } // Fix generator small reactive range issue List<String> minReactiveRangePb = new ArrayList<>(); for (EsgGenerator g : getGenerators()) { if (g.getXregge() == EsgRegulatingMode.REGULATING && Math.abs(g.getQgmax() - g.getQgmin()) < MIN_REACTIVE_RANGE) { minReactiveRangePb.add(g.getZnamge().toString()); g.setXregge(EsgRegulatingMode.NOT_REGULATING); } } if (minReactiveRangePb.size() > 0) { LOGGER.warn("Reactive range too small, switch regulator off: " + minReactiveRangePb); } // Fix target voltage consistency issue // Eurostag error message example: // ERR-0194.0350:LE GEN CURBH6G0 ESSAIE D'IMPOSER UNE TENSION AU NOEUD BARNAP71 AUQUEL UN AUTRE EQUIPEMENT A DEJA IMPOSE UNE AUTRE TENSION Multimap<String, EsgGenerator> generatorsConnectedToSameNode = HashMultimap.create(); for (EsgGenerator g : getGenerators()) { if (g.getXregge() == EsgRegulatingMode.REGULATING) { generatorsConnectedToSameNode.put(g.getZnodge().toString(), g); } } for (Map.Entry<String, Collection<EsgGenerator>> e : generatorsConnectedToSameNode.asMap().entrySet()) { String nodeName = e.getKey(); Collection<EsgGenerator> generators = e.getValue(); Set<Float> targetVoltageSet = generators.stream().map(EsgGenerator::getVregge) .collect(Collectors.toSet()); if (targetVoltageSet.size() > 1) { Collection<EsgGenerator> connectedGenerators = generators.stream() .filter(g -> g.getXgenest() == EsgConnectionStatus.CONNECTED).collect(Collectors.toList()); targetVoltageSet = connectedGenerators.stream().map(EsgGenerator::getVregge) .collect(Collectors.toSet()); if (targetVoltageSet.size() > 0) { if (targetVoltageSet.size() == 1) { Collection<EsgGenerator> diconnectedGenerators = generators.stream() .filter(g -> g.getXgenest() == EsgConnectionStatus.NOT_CONNECTED) .collect(Collectors.toList()); LOGGER.warn( "Fix target voltage of disconnected generators {} to be consistent with target voltage ({} Kv) of other generators connected to the same node ({})", diconnectedGenerators.stream().map(EsgGenerator::getZnamge).collect( Collectors.toList()), targetVoltageSet.iterator().next(), nodeName); float vregge = targetVoltageSet.iterator().next(); for (EsgGenerator g : diconnectedGenerators) { g.setVregge(vregge); } } else { throw new RuntimeException(connectedGenerators.size() + " generators (" + connectedGenerators.stream().map(EsgGenerator::getZnamge) .collect(Collectors.toList()) + ") are connected to a same node (" + nodeName + ") and try to impose a different target voltage: " + targetVoltageSet); } } } } // check there is no regulating transformer connected to same bus with a different target voltage Multimap<Esg8charName, EsgDetailedTwoWindingTransformer> transformersByRegulatedNode = HashMultimap .create(); for (EsgDetailedTwoWindingTransformer transfo : getDetailedTwoWindingTransformers()) { if (transfo.getXregtr() == EsgDetailedTwoWindingTransformer.RegulatingMode.VOLTAGE) { transformersByRegulatedNode.put(transfo.getZbusr(), transfo); } } for (Map.Entry<Esg8charName, Collection<EsgDetailedTwoWindingTransformer>> e : transformersByRegulatedNode .asMap().entrySet()) { Esg8charName regulatedNode = e.getKey(); Collection<EsgDetailedTwoWindingTransformer> transformers = e.getValue(); Set<Float> targetVoltageSet = transformers.stream().map(EsgDetailedTwoWindingTransformer::getVoltr) .collect(Collectors.toSet()); if (targetVoltageSet.size() > 1) { float chosenTargetVoltage = targetVoltageSet.stream().min(Float::compare).get(); LOGGER.warn("Fix target voltage of transformers {} connected to same regulating bus {}: {} -> {}", transformers.stream().map(EsgDetailedTwoWindingTransformer::getName).collect( Collectors.toList()), regulatedNode, targetVoltageSet, chosenTargetVoltage); for (EsgDetailedTwoWindingTransformer transformer : transformers) { transformer.setVoltr(chosenTargetVoltage); } } } }