List of usage examples for com.google.common.collect Maps uniqueIndex
public static <K, V> ImmutableMap<K, V> uniqueIndex(Iterator<V> values, Function<? super V, K> keyFunction)
From source file:org.sonar.server.measure.ws.ComponentAction.java
/** * Conditions for best value measure:/*w w w .ja va 2 s . c o m*/ * <ul> * <li>component is a production file or test file</li> * <li>metric is optimized for best value</li> * </ul> */ private static void addBestValuesToMeasures(List<MeasureDto> measures, ComponentDto component, List<MetricDto> metrics) { if (!QUALIFIERS_ELIGIBLE_FOR_BEST_VALUE.contains(component.qualifier())) { return; } List<MetricDtoWithBestValue> metricWithBestValueList = metrics.stream() .filter(MetricDtoFunctions.isOptimizedForBestValue()) .map(new MetricDtoToMetricDtoWithBestValueFunction()) .collect(MoreCollectors.toList(metrics.size())); Map<Integer, MeasureDto> measuresByMetricId = Maps.uniqueIndex(measures, MeasureDto::getMetricId); for (MetricDtoWithBestValue metricWithBestValue : metricWithBestValueList) { if (measuresByMetricId.get(metricWithBestValue.getMetric().getId()) == null) { measures.add(metricWithBestValue.getBestValue()); } } }
From source file:org.estatio.dom.lease.breaks.BreakOption.java
/** * to display in fullcalendar2/*from ww w . jav a 2 s . c o m*/ */ @SuppressWarnings({ "rawtypes", "unchecked" }) @Programmatic @Override public ImmutableMap<String, CalendarEventable> getCalendarEvents() { final ImmutableMap eventsByCalendarName = Maps.uniqueIndex(findEvents(), Event.Functions.GET_CALENDAR_NAME); return eventsByCalendarName; }
From source file:org.sonar.server.plugins.ws.PluginWSCommons.java
static ImmutableMap<String, Plugin> compatiblePluginsByKey( UpdateCenterMatrixFactory updateCenterMatrixFactory) { List<Plugin> compatiblePlugins = compatiblePlugins(updateCenterMatrixFactory); return Maps.uniqueIndex(compatiblePlugins, PluginToKeyFunction.INSTANCE); }
From source file:com.google.api.codegen.config.FieldConfig.java
public static ImmutableMap<String, FieldConfig> toFieldConfigMap(Iterable<FieldConfig> fieldConfigs) { return Maps.uniqueIndex(fieldConfigs, selectFieldLongNameFunction()); }
From source file:org.locationtech.geogig.geotools.geopkg.InterchangeFormat.java
/** * Imports the features from the geopackage based on the existing audit table onto the current * branch. If the head commit of the current branch is different from the commit that the * features were exported from, the features will be merged into the current branch. The calling * function should anticipate the possibility of merge conflicts. * /*from ww w . j a va2 s. c om*/ * @param commitMessage commit message for the imported features * @param authorName author name to use for the commit * @param authorEmail author email to use for the commit * @param tableNames a list of tables to import from the geopackage, if none are specified, all * tables will be imported * @return the commit with the imported features, or the merge commit if it was not a * fast-forward merge */ public GeopkgImportResult importAuditLog(@Nullable String commitMessage, @Nullable String authorName, @Nullable String authorEmail, @Nullable String... tableNames) { final Set<String> importTables = tableNames == null ? ImmutableSet.of() : Sets.newHashSet(tableNames); List<AuditReport> reports = new ArrayList<>(); GeoPackage geopackage; try { geopackage = new GeoPackage(geopackageDbFile); } catch (IOException e) { throw Throwables.propagate(e); } final DataSource dataSource = geopackage.getDataSource(); RevCommit importCommit = null; GeopkgImportResult importResult = null; try (Connection connection = dataSource.getConnection(); GeopkgGeogigMetadata metadata = new GeopkgGeogigMetadata(connection)) { final Map<String, AuditTable> tables = Maps.filterKeys( Maps.uniqueIndex(metadata.getAuditTables(), t -> t.getTableName()), k -> importTables.isEmpty() || importTables.contains(k)); checkState(tables.size() > 0, "No table to import."); Iterator<AuditTable> iter = tables.values().iterator(); ObjectId commitId = iter.next().getCommitId(); while (iter.hasNext()) { checkState(commitId.equals(iter.next().getCommitId()), "Unable to simultaneously import tables with different source commit ids."); } RevCommit commit = context.objectDatabase().getCommit(commitId); RevTree baseTree = context.objectDatabase().getTree(commit.getTreeId()); RevTreeBuilder newTreeBuilder = CanonicalTreeBuilder.create(context.objectDatabase(), baseTree); Map<String, String> fidMappings = null; for (AuditTable t : tables.values()) { fidMappings = metadata.getFidMappings(t.getTableName()); AuditReport report = importAuditLog(geopackage, t, baseTree, newTreeBuilder, fidMappings); reports.add(report); } RevTree newTree = newTreeBuilder.build(); context.objectDatabase().put(newTree); if (authorName == null) { authorName = context.command(ConfigGet.class).setName("user.name").call().orNull(); } if (authorEmail == null) { authorEmail = context.command(ConfigGet.class).setName("user.email").call().orNull(); } CommitBuilder builder = new CommitBuilder(); long timestamp = context.platform().currentTimeMillis(); builder.setParentIds(Arrays.asList(commitId)); builder.setTreeId(newTree.getId()); builder.setCommitterTimestamp(timestamp); builder.setCommitter(authorName); builder.setCommitterEmail(authorEmail); builder.setAuthorTimestamp(timestamp); builder.setAuthor(authorName); builder.setAuthorEmail(authorEmail); if (commitMessage != null) { builder.setMessage(commitMessage); } else { builder.setMessage("Imported features from geopackage."); } importCommit = builder.build(); importResult = new GeopkgImportResult(importCommit); for (AuditReport auditReport : reports) { if (auditReport.newMappings != null) { importResult.newMappings.put(auditReport.table.getFeatureTreePath(), auditReport.newMappings); } } context.objectDatabase().put(importCommit); MergeOp merge = context.command(MergeOp.class).setAuthor(authorName, authorEmail) .addCommit(importCommit.getId()); if (commitMessage != null) { merge.setMessage("Merge: " + commitMessage); } MergeReport report = merge.call(); RevCommit newCommit = report.getMergeCommit(); importResult.newCommit = newCommit; } catch (MergeConflictsException e) { throw new GeopkgMergeConflictsException(e, importResult); } catch (Exception e) { throw Throwables.propagate(e); } finally { geopackage.close(); } return importResult; }
From source file:com.facebook.buck.python.PythonUtil.java
public static PythonPackageComponents getAllComponents(BuildRuleParams params, BuildRuleResolver ruleResolver, SourcePathResolver pathResolver, SourcePathRuleFinder ruleFinder, final PythonPackageComponents packageComponents, final PythonPlatform pythonPlatform, CxxBuckConfig cxxBuckConfig, final CxxPlatform cxxPlatform, ImmutableList<? extends Arg> extraLdflags, final NativeLinkStrategy nativeLinkStrategy, final ImmutableSet<BuildTarget> preloadDeps) throws NoSuchBuildTargetException { final PythonPackageComponents.Builder allComponents = new PythonPackageComponents.Builder( params.getBuildTarget());/*from w ww .ja va2 s . c om*/ final Map<BuildTarget, CxxPythonExtension> extensions = new LinkedHashMap<>(); final Map<BuildTarget, NativeLinkable> nativeLinkableRoots = new LinkedHashMap<>(); final OmnibusRoots.Builder omnibusRoots = OmnibusRoots.builder(cxxPlatform, preloadDeps); // Add the top-level components. allComponents.addComponent(packageComponents, params.getBuildTarget()); // Walk all our transitive deps to build our complete package that we'll // turn into an executable. new AbstractBreadthFirstThrowingTraversal<BuildRule, NoSuchBuildTargetException>(params.getDeps()) { private final ImmutableList<BuildRule> empty = ImmutableList.of(); @Override public Iterable<BuildRule> visit(BuildRule rule) throws NoSuchBuildTargetException { Iterable<BuildRule> deps = empty; if (rule instanceof CxxPythonExtension) { CxxPythonExtension extension = (CxxPythonExtension) rule; NativeLinkTarget target = ((CxxPythonExtension) rule).getNativeLinkTarget(pythonPlatform); extensions.put(target.getBuildTarget(), extension); omnibusRoots.addIncludedRoot(target); List<BuildRule> cxxpydeps = new ArrayList<>(); for (BuildRule dep : rule.getDeps()) { if (dep instanceof CxxPythonExtension) { cxxpydeps.add(dep); } } deps = cxxpydeps; } else if (rule instanceof PythonPackagable) { PythonPackagable packagable = (PythonPackagable) rule; PythonPackageComponents comps = packagable.getPythonPackageComponents(pythonPlatform, cxxPlatform); allComponents.addComponent(comps, rule.getBuildTarget()); if (comps.hasNativeCode(cxxPlatform)) { for (BuildRule dep : rule.getDeps()) { if (dep instanceof NativeLinkable) { NativeLinkable linkable = (NativeLinkable) dep; nativeLinkableRoots.put(linkable.getBuildTarget(), linkable); omnibusRoots.addExcludedRoot(linkable); } } } deps = rule.getDeps(); } else if (rule instanceof NativeLinkable) { NativeLinkable linkable = (NativeLinkable) rule; nativeLinkableRoots.put(linkable.getBuildTarget(), linkable); omnibusRoots.addPotentialRoot(linkable); } return deps; } }.start(); // For the merged strategy, build up the lists of included native linkable roots, and the // excluded native linkable roots. if (nativeLinkStrategy == NativeLinkStrategy.MERGED) { OmnibusRoots roots = omnibusRoots.build(); OmnibusLibraries libraries = Omnibus.getSharedLibraries(params, ruleResolver, pathResolver, ruleFinder, cxxBuckConfig, cxxPlatform, extraLdflags, roots.getIncludedRoots().values(), roots.getExcludedRoots().values()); // Add all the roots from the omnibus link. If it's an extension, add it as a module. // Otherwise, add it as a native library. for (Map.Entry<BuildTarget, OmnibusRoot> root : libraries.getRoots().entrySet()) { CxxPythonExtension extension = extensions.get(root.getKey()); if (extension != null) { allComponents.addModule(extension.getModule(), root.getValue().getPath(), root.getKey()); } else { NativeLinkTarget target = Preconditions.checkNotNull( roots.getIncludedRoots().get(root.getKey()), "%s: linked unexpected omnibus root: %s", params.getBuildTarget(), root.getKey()); NativeLinkTargetMode mode = target.getNativeLinkTargetMode(cxxPlatform); String soname = Preconditions.checkNotNull(mode.getLibraryName().orElse(null), "%s: omnibus library for %s was built without soname", params.getBuildTarget(), root.getKey()); allComponents.addNativeLibraries(Paths.get(soname), root.getValue().getPath(), root.getKey()); } } // Add all remaining libraries as native libraries. for (OmnibusLibrary library : libraries.getLibraries()) { allComponents.addNativeLibraries(Paths.get(library.getSoname()), library.getPath(), params.getBuildTarget()); } } else { // For regular linking, add all extensions via the package components interface. Map<BuildTarget, NativeLinkable> extensionNativeDeps = new LinkedHashMap<>(); for (Map.Entry<BuildTarget, CxxPythonExtension> entry : extensions.entrySet()) { allComponents.addComponent(entry.getValue().getPythonPackageComponents(pythonPlatform, cxxPlatform), entry.getValue().getBuildTarget()); extensionNativeDeps.putAll(Maps.uniqueIndex( entry.getValue().getNativeLinkTarget(pythonPlatform).getNativeLinkTargetDeps(cxxPlatform), HasBuildTarget::getBuildTarget)); } // Add all the native libraries. ImmutableMap<BuildTarget, NativeLinkable> nativeLinkables = NativeLinkables .getTransitiveNativeLinkables(cxxPlatform, Iterables.concat(nativeLinkableRoots.values(), extensionNativeDeps.values())); for (NativeLinkable nativeLinkable : nativeLinkables.values()) { NativeLinkable.Linkage linkage = nativeLinkable.getPreferredLinkage(cxxPlatform); if (nativeLinkableRoots.containsKey(nativeLinkable.getBuildTarget()) || linkage != NativeLinkable.Linkage.STATIC) { ImmutableMap<String, SourcePath> libs = nativeLinkable.getSharedLibraries(cxxPlatform); for (Map.Entry<String, SourcePath> ent : libs.entrySet()) { allComponents.addNativeLibraries(Paths.get(ent.getKey()), ent.getValue(), nativeLinkable.getBuildTarget()); } } } } return allComponents.build(); }
From source file:com.eucalyptus.cluster.proxy.node.Nodes.java
private static void updateServiceConfiguration(final ServiceConfiguration ccConfig, Set<NodeInfo> nodeInfoSet) throws NoSuchElementException { Function<NodeInfo, ServiceConfiguration> setupNode = (Function<NodeInfo, ServiceConfiguration>) new Function<NodeInfo, ServiceConfiguration>() { @Nullable/* ww w .j a v a 2 s . c o m*/ @Override public ServiceConfiguration apply(@Nullable NodeInfo input) { if (Component.State.ENABLED.apply(ccConfig) && !ccConfig.lookupStateMachine().isBusy()) { ServiceConfiguration ncConfig = Nodes.lookup(ccConfig, input.getName()); Component component = Components.lookup(ProxyNodeController.class); if (!component.hasService(ncConfig)) { component.setup(ncConfig); try { Topology.disable(ncConfig); } catch (Exception e) { LOG.debug(e, e); } } return ncConfig; } return Nodes.lookup(ccConfig, input.getName());//GRZE: need to return something in this case, even knowing that the state is unhappy. } }; Predicate<NodeInfo> disableNodes = (Predicate<NodeInfo>) new Predicate<NodeInfo>() { @Override public boolean apply(@Nullable NodeInfo nodeInfo) { try { Topology.disable(Nodes.lookup(ccConfig, nodeInfo.getName())); } catch (Exception e) { } return true; } }; if (Component.State.DISABLED.ordinal() >= ccConfig.lookupState().ordinal()) { Iterables.filter(nodeInfoSet, disableNodes); } Function<ServiceStatusType, String> statusToName = new Function<ServiceStatusType, String>() { @Nullable @Override public String apply(@Nullable ServiceStatusType status) { return status.getServiceId().getName(); } }; Iterable<ServiceConfiguration> nodesConfigs = Iterables.transform(nodeInfoSet, setupNode); if (!nodeInfoSet.isEmpty()) { ClusterDescribeServicesResponseType reply = Nodes.send(new ClusterDescribeServicesType(), toArray(nodesConfigs, ServiceConfiguration.class)); Map<String, ServiceStatusType> statusMap = Maps.uniqueIndex(reply.getServiceStatuses(), statusToName); Map<String, NodeInfo> nodeInfoMap = Maps.uniqueIndex(nodeInfoSet, new Function<NodeInfo, String>() { @Nullable @Override public String apply(@Nullable NodeInfo nodeInfo) { return nodeInfo.getName(); } }); for (ServiceConfiguration ncConfig : nodesConfigs) { Component.State reportedState = Component.State.ENABLED; ServiceStatusType status = statusMap.get(ncConfig.getName()); final NodeInfo nodeInfo = nodeInfoMap.get(ncConfig.getName()); String lastMessage = null; Faults.CheckException checkException = null; TransitionRecord<ServiceConfiguration, Component.State, Component.Transition> tr = null; try { lastMessage = Joiner.on("\n").join(status.getDetails()); tr = ncConfig.lookupStateMachine().getTransitionRecord(); try { reportedState = Component.State .valueOf(Strings.nullToEmpty(status.getLocalState()).toUpperCase()); lastMessage = Joiner.on('\n').join(lastMessage, "Found service status for " + ncConfig.getName() + ": " + reportedState); } catch (IllegalArgumentException e) { lastMessage = Joiner.on('\n').join(lastMessage, "Failed to get service status for " + ncConfig.getName() + "; got " + status.getLocalState()); } if (ncConfig.lookupStateMachine().isBusy()) { //GRZE: here we skip the state update to avoid a race in the async dispatch of transitions. log any state mismatch. if (!ncConfig.lookupState().equals(reportedState)) { lastMessage = Joiner.on('\n').join(lastMessage, "Found state mismatch for node " + ncConfig.getName() + ": reported=" + reportedState + " local=" + ncConfig.getStateMachine()); } else { lastMessage = Joiner.on('\n').join(lastMessage, "Found state for node " + ncConfig.getName() + ": reported=" + reportedState + " local=" + ncConfig.getStateMachine()); } } else { try { if (Component.State.ENABLED.equals(reportedState)) { Topology.enable(ncConfig); } else if (!Component.State.STOPPED.apply(ncConfig)) { //GRZE: Only attempt to reflect the error state when the service is /not/ in the STOPPED state Topology.disable(ncConfig); if (Component.State.NOTREADY.equals(reportedState)) { checkException = Faults.failure(ncConfig, Joiner.on(",").join(status.getDetails())); } } else { Topology.stop(ncConfig); } } catch (Exception e) { LOG.debug(e, e); if (checkException != null) { LOG.debug(checkException); } checkException = Faults.failure(ncConfig, e, Objects.firstNonNull(checkException, Faults.advisory(ncConfig, lastMessage))); } } } finally { checkException = Objects.firstNonNull(checkException, Faults.advisory(ncConfig, lastMessage)); nodeInfo.touch(reportedState, lastMessage, checkException); Faults.submit(ncConfig, tr, checkException); } } } }
From source file:com.eucalyptus.node.Nodes.java
private static void updateServiceConfiguration(final ServiceConfiguration ccConfig, Set<NodeInfo> nodeInfoSet) throws NoSuchElementException { Function<NodeInfo, ServiceConfiguration> setupNode = (Function<NodeInfo, ServiceConfiguration>) new Function<NodeInfo, ServiceConfiguration>() { @Nullable//from w ww. jav a 2 s . co m @Override public ServiceConfiguration apply(@Nullable NodeInfo input) { if (Component.State.ENABLED.apply(ccConfig) && !ccConfig.lookupStateMachine().isBusy()) { ServiceConfiguration ncConfig = Nodes.lookup(ccConfig, input.getName()); Component component = Components.lookup(NodeController.class); if (!component.hasService(ncConfig)) { component.setup(ncConfig); try { Topology.disable(ncConfig); } catch (Exception e) { LOG.debug(e, e); } } return ncConfig; } return Nodes.lookup(ccConfig, input.getName());//GRZE: need to return something in this case, even knowing that the state is unhappy. } }; Predicate<NodeInfo> disableNodes = (Predicate<NodeInfo>) new Predicate<NodeInfo>() { @Override public boolean apply(@Nullable NodeInfo nodeInfo) { try { Topology.disable(Nodes.lookup(ccConfig, nodeInfo.getName())); } catch (Exception e) { } return true; } }; if (Component.State.DISABLED.ordinal() >= ccConfig.lookupState().ordinal()) { Iterables.filter(nodeInfoSet, disableNodes); } Function<ServiceStatusType, String> statusToName = new Function<ServiceStatusType, String>() { @Nullable @Override public String apply(@Nullable ServiceStatusType status) { return status.getServiceId().getName(); } }; Iterable<ServiceConfiguration> nodesConfigs = Iterables.transform(nodeInfoSet, setupNode); if (!nodeInfoSet.isEmpty()) { DescribeServicesResponseType reply = Nodes.send(new DescribeServicesType(), toArray(nodesConfigs, ServiceConfiguration.class)); Map<String, ServiceStatusType> statusMap = Maps.uniqueIndex(reply.getServiceStatuses(), statusToName); Map<String, NodeInfo> nodeInfoMap = Maps.uniqueIndex(nodeInfoSet, new Function<NodeInfo, String>() { @Nullable @Override public String apply(@Nullable NodeInfo nodeInfo) { return nodeInfo.getName(); } }); for (ServiceConfiguration ncConfig : nodesConfigs) { Component.State reportedState = Component.State.ENABLED; ServiceStatusType status = statusMap.get(ncConfig.getName()); final NodeInfo nodeInfo = nodeInfoMap.get(ncConfig.getName()); String lastMessage = null; Faults.CheckException checkException = null; TransitionRecord<ServiceConfiguration, Component.State, Component.Transition> tr = null; try { lastMessage = Joiner.on("\n").join(status.getDetails()); tr = ncConfig.lookupStateMachine().getTransitionRecord(); try { reportedState = Component.State .valueOf(Strings.nullToEmpty(status.getLocalState()).toUpperCase()); lastMessage = Joiner.on('\n').join(lastMessage, "Found service status for " + ncConfig.getName() + ": " + reportedState); } catch (IllegalArgumentException e) { lastMessage = Joiner.on('\n').join(lastMessage, "Failed to get service status for " + ncConfig.getName() + "; got " + status.getLocalState()); } if (ncConfig.lookupStateMachine().isBusy()) { //GRZE: here we skip the state update to avoid a race in the async dispatch of transitions. log any state mismatch. if (!ncConfig.lookupState().equals(reportedState)) { lastMessage = Joiner.on('\n').join(lastMessage, "Found state mismatch for node " + ncConfig.getName() + ": reported=" + reportedState + " local=" + ncConfig.getStateMachine()); } else { lastMessage = Joiner.on('\n').join(lastMessage, "Found state for node " + ncConfig.getName() + ": reported=" + reportedState + " local=" + ncConfig.getStateMachine()); } } else { try { if (Component.State.ENABLED.equals(reportedState)) { Topology.enable(ncConfig); } else if (!Component.State.STOPPED.apply(ncConfig)) { //GRZE: Only attempt to reflect the error state when the service is /not/ in the STOPPED state Topology.disable(ncConfig); if (Component.State.NOTREADY.equals(reportedState)) { checkException = Faults.failure(ncConfig, Joiner.on(",").join(status.getDetails())); } } else { Topology.stop(ncConfig); } } catch (Exception e) { LOG.debug(e, e); if (checkException != null) { LOG.debug(checkException); } checkException = Faults.failure(ncConfig, e, Objects.firstNonNull(checkException, Faults.advisory(ncConfig, lastMessage))); } } } finally { checkException = Objects.firstNonNull(checkException, Faults.advisory(ncConfig, lastMessage)); nodeInfo.touch(reportedState, lastMessage, checkException); Faults.submit(ncConfig, tr, checkException); } } } }
From source file:org.graylog2.security.ldap.LdapSettingsImpl.java
@Override public void setGroupMapping(Map<String, String> mapping) { Map<String, String> internal; if (mapping == null) { internal = Collections.emptyMap(); } else {/* w ww . ja v a 2s . c om*/ // we store ids internally but external users use the group names try { final Map<String, Role> nameToRole = Maps.uniqueIndex(roleService.loadAll(), Roles.roleToNameFunction()); internal = Maps.newHashMap(Maps.transformValues(mapping, new Function<String, String>() { @Nullable @Override public String apply(@Nullable String groupName) { if (groupName == null || !nameToRole.containsKey(groupName)) { return null; } return nameToRole.get(groupName).getId(); } })); } catch (NotFoundException e) { LOG.error("Unable to convert group names to ids", e); throw new IllegalStateException("Unable to convert group names to ids", e); } } // convert the group -> role_id map to a list of {"group" -> group, "role_id" -> roleid } maps fields.put(GROUP_MAPPING_LIST, internal.entrySet().stream().map(entry -> { Map<String, String> m = Maps.newHashMap(); m.put(LDAP_GROUP_MAPPING_NAMEKEY, entry.getKey()); m.put(LDAP_GROUP_MAPPING_ROLEKEY, entry.getValue()); return m; }).collect(Collectors.toList())); }
From source file:com.siemens.sw360.importer.ComponentImportUtils.java
private static ImmutableMap<String, Component> getComponentsByName( List<Component> componentDetailedSummaryForExport) { return Maps.uniqueIndex(componentDetailedSummaryForExport, new Function<Component, String>() { @Override//from w ww . j a va 2s .c o m public String apply(Component input) { return printName(input); } }); }