List of usage examples for com.google.common.collect ImmutableSet.Builder add
boolean add(E e);
From source file:com.facebook.buck.distributed.DistBuildUtil.java
/** Checks whether the given target command line arguments match the Stampede project whitelist */ public static boolean doTargetsMatchProjectWhitelist(List<String> commandArgs, ImmutableSet<String> projectWhitelist, BuckConfig buckConfig) { ImmutableSet.Builder<String> buildTargets = new ImmutableSet.Builder<>(); for (String commandArg : commandArgs) { ImmutableSet<String> buildTargetForAliasAsString = AliasConfig.from(buckConfig) .getBuildTargetForAliasAsString(commandArg); if (buildTargetForAliasAsString.size() > 0) { buildTargets.addAll(buildTargetForAliasAsString); } else {/*from ww w .j a v a 2 s .com*/ // Target was not an alias if (!commandArg.startsWith("//")) { commandArg = "//" + commandArg; } buildTargets.add(commandArg); } } return doTargetsMatchProjectWhitelist(buildTargets.build(), projectWhitelist); }
From source file:com.outerspacecat.icalendar.VEvent.java
/** * Parses a VEVENT component.//ww w .j av a 2 s .c o m * * @param comp the component to parse. Must be non {@code null}. * @return a VEVENT. Never {@code null}. * @throws CalendarParseException if {@code comp} does not represent a valid * VEVENT */ public static VEvent parse(final Component comp) throws CalendarParseException { Preconditions.checkNotNull(comp, "comp required"); Preconditions.checkArgument(comp.getName().equals("VEVENT"), "component name must be VEVENT, saw: " + comp.getName()); Property prop = null; prop = comp.getSingleProperty("DTSTAMP"); ParsedDateTime rawDtStamp = prop.asDateTime(); if (!rawDtStamp.isUtc()) throw new CalendarParseException("DTSTAMP property value must be UTC"); TypedProperty<Instant> dtStamp = new TypedProperty<>( rawDtStamp.getDateTime().atZone(ZoneOffset.UTC).toInstant(), prop.getParameters().values()); prop = comp.getSingleProperty("UID"); TypedProperty<TextType> uid = new TypedProperty<>(prop.asText(), prop.getParameters().values()); prop = comp.getFirstProperty("SEQUENCE"); TypedProperty<Integer> sequence = null; if (prop != null) { int rawSequence = prop.asInteger(); if (rawSequence < 0) throw new CalendarParseException("invalid SEQUENCE: " + rawSequence); sequence = new TypedProperty<>(rawSequence, prop.getParameters().values()); } prop = comp.getFirstProperty("CREATED"); TypedProperty<Instant> created = null; if (prop != null) { ParsedDateTime rawCreated = prop.asDateTime(); if (!rawCreated.isUtc()) throw new CalendarParseException("CREATED property value must be UTC"); created = new TypedProperty<>(rawCreated.getDateTime().atZone(ZoneOffset.UTC).toInstant(), prop.getParameters().values()); } prop = comp.getFirstProperty("LAST-MODIFIED"); TypedProperty<Instant> lastModified = null; if (prop != null) { ParsedDateTime rawLastModified = prop.asDateTime(); if (!rawLastModified.isUtc()) throw new CalendarParseException("LAST-MODIFIED property value must be UTC"); lastModified = new TypedProperty<>(rawLastModified.getDateTime().atZone(ZoneOffset.UTC).toInstant(), prop.getParameters().values()); } Schedule schedule = Schedule.parse(comp.getSingleProperty("DTSTART"), comp.getFirstProperty("DTEND"), comp.getFirstProperty("DURATION")); ImmutableSet.Builder<RRule> rRuleBuilder = ImmutableSet.builder(); for (Property rRuleProp : comp.getProperties().get("RRULE")) rRuleBuilder.add(RRule.parse(rRuleProp)); ImmutableSet<RRule> rRules = rRuleBuilder.build(); ImmutableSet.Builder<RDate> rDateBuilder = ImmutableSet.builder(); for (Property rDateProp : comp.getProperties().get("RDATE")) rDateBuilder.add(RDate.parse(rDateProp)); ImmutableSet<RDate> rDates = rDateBuilder.build(); ImmutableSet.Builder<ExDate> exDateBuilder = ImmutableSet.builder(); for (Property exDateProp : comp.getProperties().get("EXDATE")) exDateBuilder.add(ExDate.parse(exDateProp)); ImmutableSet<ExDate> exDates = exDateBuilder.build(); RecurrenceData recurrenceData = new RecurrenceData(rRules, rDates, exDates); prop = comp.getFirstProperty("ORGANIZER"); TypedProperty<UriType> organizer = null; if (prop != null) organizer = new TypedProperty<>(prop.asUri(), prop.getParameters().values()); prop = comp.getFirstProperty("STATUS"); TypedProperty<TextType> status = null; if (prop != null) status = new TypedProperty<>(prop.asText(), prop.getParameters().values()); prop = comp.getFirstProperty("SUMMARY"); TypedProperty<TextType> summary = null; if (prop != null) summary = new TypedProperty<>(prop.asText(), prop.getParameters().values()); prop = comp.getFirstProperty("DESCRIPTION"); TypedProperty<TextType> description = null; if (prop != null) description = new TypedProperty<>(prop.asText(), prop.getParameters().values()); prop = comp.getFirstProperty("LOCATION"); TypedProperty<TextType> location = null; if (prop != null) location = new TypedProperty<>(prop.asText(), prop.getParameters().values()); prop = comp.getFirstProperty("CLASS"); TypedProperty<TextType> classification = null; if (prop != null) classification = new TypedProperty<>(prop.asText(), prop.getParameters().values()); prop = comp.getFirstProperty("TRANSP"); TypedProperty<Boolean> transparent = null; if (prop != null) { transparent = new TypedProperty<>(prop.getValue().equals("TRANSPARENT"), prop.getParameters().values()); } else { transparent = new TypedProperty<>(false); } prop = comp.getFirstProperty("PRIORITY"); TypedProperty<Integer> priority = null; if (prop != null) { int rawPriority = prop.asInteger(); if (rawPriority < 0 || rawPriority > 9) throw new CalendarParseException("invalid PRIORITY: " + rawPriority); priority = new TypedProperty<>(rawPriority, prop.getParameters().values()); } prop = comp.getFirstProperty("URL"); TypedProperty<UriType> url = null; if (prop != null) url = new TypedProperty<>(prop.asUri(), prop.getParameters().values()); prop = comp.getFirstProperty("GEO"); TypedProperty<GeoType> geo = null; if (prop != null) geo = new TypedProperty<>(prop.asGeo(), prop.getParameters().values()); ImmutableSet.Builder<Attendee> attendeesBuilder = ImmutableSet.builder(); for (Property attendeeProp : comp.getProperties().get("ATTENDEE")) attendeesBuilder.add(Attendee.parse(attendeeProp)); ImmutableSet<Attendee> attendees = attendeesBuilder.build(); ImmutableSet.Builder<TypedProperty<ImmutableSet<TextType>>> categoriesBuilder = ImmutableSet.builder(); for (Property categoryProp : comp.getProperties().get("CATEGORIES")) categoriesBuilder.add(new TypedProperty<ImmutableSet<TextType>>(categoryProp.asTextValues(), categoryProp.getParameters().values())); ImmutableSet<TypedProperty<ImmutableSet<TextType>>> categories = categoriesBuilder.build(); ImmutableSet.Builder<TypedProperty<TextType>> commentsBuilder = ImmutableSet.builder(); for (Property commentProp : comp.getProperties().get("COMMENT")) commentsBuilder .add(new TypedProperty<TextType>(commentProp.asText(), commentProp.getParameters().values())); ImmutableSet<TypedProperty<TextType>> comments = commentsBuilder.build(); ImmutableSet.Builder<TypedProperty<ImmutableSet<TextType>>> resourcesBuilder = ImmutableSet.builder(); for (Property resourceProp : comp.getProperties().get("RESOURCES")) resourcesBuilder.add(new TypedProperty<ImmutableSet<TextType>>(resourceProp.asTextValues(), resourceProp.getParameters().values())); ImmutableSet<TypedProperty<ImmutableSet<TextType>>> resources = resourcesBuilder.build(); ImmutableSet.Builder<TypedProperty<TextType>> contactsBuilder = ImmutableSet.builder(); for (Property contactProp : comp.getProperties().get("CONTACT")) contactsBuilder .add(new TypedProperty<TextType>(contactProp.asText(), contactProp.getParameters().values())); ImmutableSet<TypedProperty<TextType>> contacts = contactsBuilder.build(); return new VEvent(uid, sequence, dtStamp, created, lastModified, schedule, recurrenceData, organizer, status, summary, description, location, classification, transparent, priority, url, geo, attendees, categories, comments, resources, contacts, comp.getPropertiesExcept(RESTRICTED_PROPERTY_NAMES).values(), comp.getComponentsExcept(RESTRICTED_COMPONENT_NAMES).values()); }
From source file:com.github.rinde.rinsim.central.arrays.ArraysSolverValidator.java
/** * Validates the inputs for the {@link MultiVehicleArraysSolver}. This method * checks all properties as defined in//from ww w.j a v a2 s.c o m * {@link MultiVehicleArraysSolver#solve(int[][], int[], int[], int[][], int[], int[][], int[][], int[], int[], SolutionObject[])} * . If the inputs are not correct an {@link IllegalArgumentException} is * thrown. * @param travelTime Parameter as specified by * {@link MultiVehicleArraysSolver#solve(int[][], int[], int[], int[][], int[], int[][], int[][], int[], int[], SolutionObject[])} * . * @param releaseDates Parameter as specified by * {@link MultiVehicleArraysSolver#solve(int[][], int[], int[], int[][], int[], int[][], int[][], int[], int[], SolutionObject[])} * . * @param dueDates Parameter as specified by * {@link MultiVehicleArraysSolver#solve(int[][], int[], int[], int[][], int[], int[][], int[][], int[], int[], SolutionObject[])} * . * @param servicePairs Parameter as specified by * {@link MultiVehicleArraysSolver#solve(int[][], int[], int[], int[][], int[], int[][], int[][], int[], int[], SolutionObject[])} * . * @param serviceTimes Parameter as specified by * {@link MultiVehicleArraysSolver#solve(int[][], int[], int[], int[][], int[], int[][], int[][], int[], int[], SolutionObject[])} * . * @param vehicleTravelTimes Parameter as specified by * {@link MultiVehicleArraysSolver#solve(int[][], int[], int[], int[][], int[], int[][], int[][], int[], int[], SolutionObject[])} * . * @param inventories Parameter as specified by * {@link MultiVehicleArraysSolver#solve(int[][], int[], int[], int[][], int[], int[][], int[][], int[], int[], SolutionObject[])} * . * @param remainingServiceTimes Parameter as specified by * {@link MultiVehicleArraysSolver#solve(int[][], int[], int[], int[][], int[], int[][], int[][], int[], int[], SolutionObject[])} * . * @param currentDestinations Parameter as specified by * {@link MultiVehicleArraysSolver#solve(int[][], int[], int[], int[][], int[], int[][], int[][], int[], int[], SolutionObject[])} * . * @param currentSolutions Parameter as specified by * {@link MultiVehicleArraysSolver#solve(int[][], int[], int[], int[][], int[], int[][], int[][], int[], int[], SolutionObject[])} * . */ public static void validateInputs(int[][] travelTime, int[] releaseDates, int[] dueDates, int[][] servicePairs, int[] serviceTimes, int[][] vehicleTravelTimes, int[][] inventories, int[] remainingServiceTimes, int[] currentDestinations, @Nullable SolutionObject[] currentSolutions) { validateInputs(travelTime, releaseDates, dueDates, servicePairs, serviceTimes); // number of vehicles v final int v = vehicleTravelTimes.length; final int n = travelTime.length; checkArgument(v > 0, "At least one vehicle is required."); checkArgument(v == remainingServiceTimes.length, "Expected a remainingServiceTimes array of size %s, but found one with " + "size %s.", v, remainingServiceTimes.length); checkArgument(currentDestinations.length == v, "The currentDestinations array should be of length v=%s, it is %s.", v, currentDestinations.length); validateVehicleTravelTimes(v, n, vehicleTravelTimes, currentDestinations); final ImmutableSet.Builder<Integer> b = ImmutableSet.builder(); for (int i = 0; i < servicePairs.length; i++) { b.add(servicePairs[i][0]); b.add(servicePairs[i][1]); } final Set<Integer> availLocs = b.build(); final int m = n - 2 - servicePairs.length * 2; checkArgument(inventories.length == m, "Invalid number of inventory entries, must be equal to number of " + "delivery locations: %s, found: %s.", m, servicePairs.length); final Multimap<Integer, Integer> inventoriesMap = HashMultimap.create(); final Set<Integer> parcelsInInventory = newHashSet(); for (int i = 0; i < m; i++) { checkArgument(2 == inventories[i].length, "We expected inventories matrix of size m x 2, but we found m x %s " + "at index %s.", inventories[i].length, i); checkArgument(inventories[i][0] >= 0 && inventories[i][0] < v, "Found a reference to a non-existing vehicle (%s) in inventories at " + "row %s.", inventories[i][0], i); checkArgument(inventories[i][1] >= 1 && inventories[i][1] < n - 1, "Found a reference to a non-existing location (%s) in inventories at" + " row %s.", inventories[i][1], i); checkArgument(!availLocs.contains(inventories[i][1]), "Found a reference to a location (%s) in inventories at row %s which " + "is available, as such, it can not be in the inventory.", inventories[i][1], i); checkArgument(!parcelsInInventory.contains(inventories[i][1]), "Found a duplicate inventory entry, first duplicate at row %s.", i); parcelsInInventory.add(inventories[i][1]); inventoriesMap.put(inventories[i][0], inventories[i][1]); } for (int i = 0; i < v; i++) { checkArgument(remainingServiceTimes[i] >= 0, "Remaining service time must be >= 0, found %s.", remainingServiceTimes[i]); } final ImmutableBiMap.Builder<Integer, Integer> servicePairsBuilder = ImmutableBiMap.builder(); for (int i = 0; i < servicePairs.length; i++) { servicePairsBuilder.put(servicePairs[i][0], servicePairs[i][1]); } final ImmutableBiMap<Integer, Integer> servicePairsMap = servicePairsBuilder.build(); for (int i = 0; i < v; i++) { if (remainingServiceTimes[i] != 0) { checkArgument(currentDestinations[i] != 0); } if (currentDestinations[i] != 0) { final int dest = currentDestinations[i]; checkArgument(dest >= 1 && dest < n - 1, "The destination must be a valid location, it can not be the " + "depot. It is %s.", dest); final boolean isAvailablePickupLoc = servicePairsMap.keySet().contains(dest); final boolean isInInventory = inventoriesMap.containsValue(dest); checkArgument(isAvailablePickupLoc != isInInventory, "The destination location %s must be an available pickup location " + "OR a delivery location which is in the inventory, available " + "pickup loc: %s, in inventory: %s.", dest, isAvailablePickupLoc, isInInventory); if (parcelsInInventory.contains(dest)) { checkArgument(inventoriesMap.get(i).contains(dest), "When a vehicle is moving towards a destination which is a " + "delivery location, it must contain this parcel in its " + "cargo. Vehicle %s, destination %s.", i, dest); } } } if (currentSolutions != null) { validateCurrentSolutions(v, n, currentSolutions, currentDestinations, inventoriesMap, servicePairsMap); } }
From source file:com.facebook.buck.features.go.CGoLibrary.java
public static BuildRule create(BuildRuleParams params, BuildTarget buildTarget, ProjectFilesystem projectFilesystem, ActionGraphBuilder graphBuilder, SourcePathResolver pathResolver, CellPathResolver cellRoots, CxxBuckConfig cxxBuckConfig, GoPlatform platform, CgoLibraryDescriptionArg args, Iterable<BuildTarget> cxxDeps, Tool cgo) { SourcePathRuleFinder ruleFinder = new SourcePathRuleFinder(graphBuilder); CxxDeps allDeps = CxxDeps.builder().addDeps(cxxDeps).addPlatformDeps(args.getPlatformDeps()).build(); // generate C sources with cgo tool (go build writes c files to _obj dir) ImmutableMap<Path, SourcePath> headers = CxxDescriptionEnhancer.parseHeaders(buildTarget, graphBuilder, ruleFinder, pathResolver, Optional.of(platform.getCxxPlatform()), args); HeaderSymlinkTree headerSymlinkTree = getHeaderSymlinkTree(buildTarget, projectFilesystem, ruleFinder, graphBuilder, platform.getCxxPlatform(), cxxDeps, headers); ImmutableSet.Builder<SourcePath> cxxSourcesFromArg = ImmutableSet.builder(); ImmutableSet.Builder<SourcePath> goSourcesFromArg = ImmutableSet.builder(); for (SourceWithFlags srcWithFlags : args.getSrcs()) { SourcePath pth = srcWithFlags.getSourcePath(); String ext = Files.getFileExtension(pathResolver.getAbsolutePath(pth).toString()); if (CxxSource.Type.fromExtension(ext).equals(Optional.of(CxxSource.Type.C))) { cxxSourcesFromArg.add(pth); } else if (ext.equals("go")) { goSourcesFromArg.add(pth);/* ww w . j ava 2s . c o m*/ } } CGoGenSource genSource = (CGoGenSource) graphBuilder .computeIfAbsent(buildTarget.withAppendedFlavors(InternalFlavor.of("cgo-gen-sources")), target -> new CGoGenSource(target, projectFilesystem, ruleFinder, pathResolver, goSourcesFromArg.build(), headerSymlinkTree, cgo, args.getCgoCompilerFlags(), platform)); // generated c files needs to be compiled and linked into a single object // file (equivalent of (_cgo_.o), includes: // * _cgo_export.o // * _cgo_main.o // * all of the *.cgo2.o CxxLink cgoBin = (CxxLink) graphBuilder.computeIfAbsent( buildTarget.withAppendedFlavors(InternalFlavor.of("cgo-first-step")), target -> nativeBinCompilation(target, projectFilesystem, graphBuilder, pathResolver, cellRoots, cxxBuckConfig, platform.getCxxPlatform(), args, new ImmutableList.Builder<BuildRule>().add(genSource) .addAll(allDeps.get(graphBuilder, platform.getCxxPlatform())).build(), new ImmutableMap.Builder<Path, SourcePath>().putAll(headers) .put(pathResolver.getAbsolutePath(genSource.getExportHeader()).getFileName(), genSource.getExportHeader()) .build(), new ImmutableList.Builder<SourcePath>().addAll(cxxSourcesFromArg.build()) .addAll(genSource.getCFiles()).addAll(genSource.getCgoFiles()).build(), args.getLinkerFlags())); // generate cgo_import.h with previously generated object file (_cgo.o) BuildRule cgoImport = graphBuilder.computeIfAbsent( buildTarget.withAppendedFlavors(InternalFlavor.of("cgo-gen-import")), target -> new CGoGenImport(target, projectFilesystem, ruleFinder, pathResolver, cgo, platform, // take first source file in the list to infer the package // name via go list goSourcesFromArg.build().iterator().next(), Objects.requireNonNull(cgoBin.getSourcePathToOutput()))); // filter out compiled object only for the sources we are interested in ImmutableList<String> linkableObjectFiles = Stream.concat( cxxSourcesFromArg.build().stream() .map(x -> pathResolver.getAbsolutePath(x).getFileName().toString()), ImmutableList.of(".cgo2.c", "_cgo_export.c").stream()).collect(ImmutableList.toImmutableList()); // generate final object file (equivalent of _all.o) which includes: // * _cgo_export.o // * all of the *.cgo2.o files ImmutableList<Arg> cxxArgs = ImmutableList.<Arg>builder().addAll(StringArg.from("-r", "-nostdlib")) .addAll(cgoBin.getArgs().stream().filter(FileListableLinkerInputArg.class::isInstance) .map(FileListableLinkerInputArg.class::cast).filter(arg -> { Path pth = pathResolver.getAbsolutePath(arg.getPath()); String fileName = pth.getFileName().toString(); return pth.toString().contains("cgo-first-step") && linkableObjectFiles.stream().anyMatch(x -> fileName.contains(x)); }).collect(ImmutableList.toImmutableList())) .build(); CxxLink cgoAllBin = (CxxLink) graphBuilder.computeIfAbsent( buildTarget.withAppendedFlavors(InternalFlavor.of("cgo-second-step")), target -> CxxLinkableEnhancer.createCxxLinkableBuildRule(cellRoots, cxxBuckConfig, platform.getCxxPlatform(), projectFilesystem, graphBuilder, ruleFinder, target, BuildTargetPaths.getGenPath(projectFilesystem, target, "%s/_all.o"), ImmutableMap.of(), cxxArgs, // collection of selected object files args.getLinkStyle().orElse(Linker.LinkableDepType.STATIC_PIC), CxxLinkOptions.of(), Optional.empty())); // output (referenced later on by GoCompile) provides: // * _cgo_gotypes.go // * _cgo_import.go // * all of the *.cgo1.go files // // the go sources should be appended to sources list and _all.o file should // be appended to the output binary (pack step) return graphBuilder.computeIfAbsent(buildTarget, target -> new CGoLibrary( params.withDeclaredDeps(ImmutableSortedSet.<BuildRule>naturalOrder() .addAll(ruleFinder.filterBuildRuleInputs(cgoAllBin.getSourcePathToOutput())) .addAll(ruleFinder.filterBuildRuleInputs(new Builder<SourcePath>() .addAll(genSource.getGoFiles()) .add(Objects.requireNonNull(cgoImport.getSourcePathToOutput())).build())) .build()).withoutExtraDeps(), target, projectFilesystem, new Builder<SourcePath>().addAll(genSource.getGoFiles()) .add(Objects.requireNonNull(cgoImport.getSourcePathToOutput())).build(), Objects.requireNonNull(cgoAllBin.getSourcePathToOutput()), Objects.requireNonNull(allDeps.get(graphBuilder, platform.getCxxPlatform())))); }
From source file:com.facebook.buck.parser.BuildFileSpec.java
@SuppressWarnings("unchecked") private static ImmutableSet<Path> findBuildFilesUsingWatchman(ProjectFilesystemView filesystemView, WatchmanClient watchmanClient, String watchRoot, Optional<String> projectPrefix, Path basePath, String buildFileName, ImmutableSet<PathMatcher> ignoredPaths) throws IOException, InterruptedException { List<Object> query = Lists.newArrayList("query", watchRoot); Map<String, Object> params = new LinkedHashMap<>(); if (projectPrefix.isPresent()) { params.put("relative_root", projectPrefix.get()); }//w w w .j a v a 2s. com // Get the current state of the filesystem instead of waiting for a fence. params.put("sync_timeout", 0); Path relativeBasePath; if (basePath.isAbsolute()) { Preconditions.checkState(filesystemView.isSubdirOf(basePath)); relativeBasePath = filesystemView.relativize(basePath); } else { relativeBasePath = basePath; } // This should be a relative path from watchRoot/projectPrefix. params.put("path", Lists.newArrayList(relativeBasePath.toString())); // We only care about the paths to each of the files. params.put("fields", Lists.newArrayList("name")); // Query all files matching `buildFileName` which are either regular files or symlinks. params.put("expression", Lists.newArrayList("allof", "exists", Lists.newArrayList("name", buildFileName), // Assume there are no symlinks to build files. Lists.newArrayList("type", "f"))); // TODO(bhamiltoncx): Consider directly adding the white/blacklist paths and globs instead // of filtering afterwards. query.add(params); Optional<? extends Map<String, ? extends Object>> queryResponse = watchmanClient .queryWithTimeout(WATCHMAN_QUERY_TIMEOUT_NANOS, query.toArray()); if (!queryResponse.isPresent()) { throw new IOException( "Timed out after " + WATCHMAN_QUERY_TIMEOUT_NANOS + " ns for Watchman query " + query); } Map<String, ? extends Object> response = queryResponse.get(); String error = (String) response.get("error"); if (error != null) { throw new IOException(String.format("Error from Watchman query %s: %s", query, error)); } String warning = (String) response.get("warning"); if (warning != null) { LOG.warn("Watchman warning from query %s: %s", query, warning); } List<String> files = (List<String>) Objects.requireNonNull(response.get("files")); LOG.verbose("Query %s -> files %s", query, files); ImmutableSet.Builder<Path> builder = ImmutableSet.builderWithExpectedSize(files.size()); for (String file : files) { Path relativePath = Paths.get(file); if (!filesystemView.isIgnored(relativePath) && !matchesIgnoredPath(relativePath, ignoredPaths)) { // To avoid an extra stat() and realpath(), we assume we have no symlinks here // (since Watchman doesn't follow them anyway), and directly resolve the path // instead of using ProjectFilesystem.resolve(). builder.add(filesystemView.resolve(relativePath)); } } return builder.build(); }
From source file:it.unibz.krdb.obda.owlrefplatform.core.dagjgrapht.TBoxReasonerImpl.java
/** * constructs a TBoxReasoner that has a reduced number of classes and properties in each equivalent class * //w w w . j av a 2 s .c o m * - each object property equivalence class contains one property (representative) * except when the representative property is equivalent to its inverse, in which * case the equivalence class contains both the property and its inverse * * - each data property equivalence class contains a single property (representative) * * - each class equivalence class contains the representative and all domains / ranges * of the representatives of property equivalence classes * * in other words, the constructed TBoxReasoner is the restriction to the vocabulary of the representatives * all other symbols are mapped to the nodes via *Equivalences hash-maps * * @param reasoner * @return reduced reasoner */ private static TBoxReasonerImpl getEquivalenceSimplifiedReasoner(TBoxReasoner reasoner) { // OBJECT PROPERTIES // SimpleDirectedGraph<Equivalences<ObjectPropertyExpression>, DefaultEdge> objectProperties = new SimpleDirectedGraph<>( DefaultEdge.class); // create vertices for properties for (Equivalences<ObjectPropertyExpression> node : reasoner.getObjectPropertyDAG()) { ObjectPropertyExpression rep = node.getRepresentative(); ObjectPropertyExpression repInv = rep.getInverse(); Equivalences<ObjectPropertyExpression> reducedNode; if (!node.contains(repInv)) reducedNode = new Equivalences<>(ImmutableSet.of(rep), rep, node.isIndexed()); else // the object property is equivalent to its inverse reducedNode = new Equivalences<>(ImmutableSet.of(rep, repInv), rep, node.isIndexed()); objectProperties.addVertex(reducedNode); } EquivalencesDAGImpl<ObjectPropertyExpression> objectPropertyDAG = EquivalencesDAGImpl.reduce( (EquivalencesDAGImpl<ObjectPropertyExpression>) reasoner.getObjectPropertyDAG(), objectProperties); // DATA PROPERTIES // SimpleDirectedGraph<Equivalences<DataPropertyExpression>, DefaultEdge> dataProperties = new SimpleDirectedGraph<>( DefaultEdge.class); // create vertices for properties for (Equivalences<DataPropertyExpression> node : reasoner.getDataPropertyDAG()) { DataPropertyExpression rep = node.getRepresentative(); Equivalences<DataPropertyExpression> reducedNode = new Equivalences<>(ImmutableSet.of(rep), rep, node.isIndexed()); dataProperties.addVertex(reducedNode); } EquivalencesDAGImpl<DataPropertyExpression> dataPropertyDAG = EquivalencesDAGImpl.reduce( (EquivalencesDAGImpl<DataPropertyExpression>) reasoner.getDataPropertyDAG(), dataProperties); // CLASSES // SimpleDirectedGraph<Equivalences<ClassExpression>, DefaultEdge> classes = new SimpleDirectedGraph<>( DefaultEdge.class); // create vertices for classes for (Equivalences<ClassExpression> node : reasoner.getClassDAG()) { ClassExpression rep = node.getRepresentative(); ImmutableSet.Builder<ClassExpression> reduced = new ImmutableSet.Builder<>(); for (ClassExpression equi : node) { if (equi.equals(rep)) { reduced.add(equi); } else if (equi instanceof OClass) { // an entry is created for a named class //OClass equiClass = (OClass) equi; //classEquivalenceMap.put(equiClass.getName(), (OClass)rep); } else if (equi instanceof ObjectSomeValuesFrom) { // the property of the existential is a representative of its equivalence class if (objectPropertyDAG.getVertex(((ObjectSomeValuesFrom) equi).getProperty()) != null) reduced.add(equi); } else { // the property of the existential is a representative of its equivalence class if (dataPropertyDAG.getVertex(((DataSomeValuesFrom) equi).getProperty()) != null) reduced.add(equi); } } Equivalences<ClassExpression> reducedNode = new Equivalences<>(reduced.build(), rep, node.isIndexed()); classes.addVertex(reducedNode); } EquivalencesDAGImpl<ClassExpression> classDAG = EquivalencesDAGImpl .reduce((EquivalencesDAGImpl<ClassExpression>) reasoner.getClassDAG(), classes); // DATA RANGES // // TODO: a proper implementation is in order here return new TBoxReasonerImpl(classDAG, (EquivalencesDAGImpl<DataRangeExpression>) reasoner.getDataRangeDAG(), objectPropertyDAG, dataPropertyDAG); }
From source file:com.google.devtools.build.lib.rules.cpp.CcBinary.java
private static Runfiles collectRunfiles(RuleContext context, CcLinkingOutputs linkingOutputs, CcLibraryHelper.Info info, LinkStaticness linkStaticness, NestedSet<Artifact> filesToBuild, Iterable<Artifact> fakeLinkerInputs, boolean fake, ImmutableSet<CppSource> cAndCppSources, boolean linkCompileOutputSeparately) { Runfiles.Builder builder = new Runfiles.Builder(context.getWorkspaceName(), context.getConfiguration().legacyExternalRunfiles()); Function<TransitiveInfoCollection, Runfiles> runfilesMapping = CppRunfilesProvider .runfilesFunction(linkStaticness != LinkStaticness.DYNAMIC); builder.addTransitiveArtifacts(filesToBuild); // Add the shared libraries to the runfiles. This adds any shared libraries that are in the // srcs of this target. builder.addArtifacts(linkingOutputs.getLibrariesForRunfiles(true)); builder.addRunfiles(context, RunfilesProvider.DEFAULT_RUNFILES); builder.add(context, runfilesMapping); CcToolchainProvider toolchain = CppHelper.getToolchain(context); // Add the C++ runtime libraries if linking them dynamically. if (linkStaticness == LinkStaticness.DYNAMIC) { builder.addTransitiveArtifacts(toolchain.getDynamicRuntimeLinkInputs()); }/*from w ww. jav a 2 s . c om*/ if (linkCompileOutputSeparately) { builder.addArtifacts( LinkerInputs.toLibraryArtifacts(info.getCcLinkingOutputs().getExecutionDynamicLibraries())); } // For cc_binary and cc_test rules, there is an implicit dependency on // the malloc library package, which is specified by the "malloc" attribute. // As the BUILD encyclopedia says, the "malloc" attribute should be ignored // if linkshared=1. boolean linkshared = isLinkShared(context); if (!linkshared) { TransitiveInfoCollection malloc = CppHelper.mallocForTarget(context); builder.addTarget(malloc, RunfilesProvider.DEFAULT_RUNFILES); builder.addTarget(malloc, runfilesMapping); } if (fake) { // Add the object files, libraries, and linker scripts that are used to // link this executable. builder.addSymlinksToArtifacts(Iterables.filter(fakeLinkerInputs, Artifact.MIDDLEMAN_FILTER)); // The crosstool inputs for the link action are not sufficient; we also need the crosstool // inputs for compilation. Node that these cannot be middlemen because Runfiles does not // know how to expand them. builder.addTransitiveArtifacts(toolchain.getCrosstool()); builder.addTransitiveArtifacts(toolchain.getLibcLink()); // Add the sources files that are used to compile the object files. // We add the headers in the transitive closure and our own sources in the srcs // attribute. We do not provide the auxiliary inputs, because they are only used when we // do FDO compilation, and cc_fake_binary does not support FDO. ImmutableSet.Builder<Artifact> sourcesBuilder = ImmutableSet.<Artifact>builder(); for (CppSource cppSource : cAndCppSources) { sourcesBuilder.add(cppSource.getSource()); } builder.addSymlinksToArtifacts(sourcesBuilder.build()); CppCompilationContext cppCompilationContext = info.getCppCompilationContext(); builder.addSymlinksToArtifacts(cppCompilationContext.getDeclaredIncludeSrcs()); // Add additional files that are referenced from the compile command, like module maps // or header modules. builder.addSymlinksToArtifacts(cppCompilationContext.getAdditionalInputs()); builder.addSymlinksToArtifacts( cppCompilationContext.getTransitiveModules(CppHelper.usePic(context, !isLinkShared(context)))); } return builder.build(); }
From source file:com.facebook.buck.rage.UserInput.java
public static ImmutableSet<Integer> parseRange(String input) { ImmutableSet.Builder<Integer> result = ImmutableSet.builder(); String[] elements = input.split("[, ]+"); for (String element : elements) { Matcher matcher = RANGE_OR_NUMBER.matcher(element); Preconditions.checkArgument(matcher.matches(), "Malformed entry %s.", element); String numberString = matcher.group("num"); String rangeLowString = matcher.group("rangelo"); String rangeHighString = matcher.group("rangehi"); Preconditions.checkArgument(numberString != null || rangeHighString != null, "Malformed entry %s.", element);//from ww w . j ava 2 s. co m if (numberString != null) { result.add(Integer.parseInt(numberString)); } else { int rangeLow = Integer.parseInt(rangeLowString); int rangeHigh = Integer.parseInt(rangeHighString); for (int i = Math.min(rangeLow, rangeHigh); i <= Math.max(rangeLow, rangeHigh); ++i) { result.add(i); } } } return result.build(); }
From source file:eu.eidas.auth.commons.attribute.ImmutableAttributeMap.java
@Nullable public static <T> ImmutableSet<? extends T> toValues( @Nullable Iterable<? extends AttributeValue<T>> attributeValues) { if (null == attributeValues) { return null; }/*from w w w .j a v a 2 s. c om*/ ImmutableSet.Builder<T> builder = ImmutableSet.builder(); for (final AttributeValue<T> attributeValue : attributeValues) { builder.add(attributeValue.getValue()); } return builder.build(); }
From source file:com.google.gdata.model.ElementMetadataImpl.java
private static void addReferencedNamespaces(ElementMetadata<?, ?> metadata, ImmutableSet.Builder<XmlNamespace> builder, Set<ElementKey<?, ?>> added) { // Avoid recursive looping if (added.contains(metadata.getKey())) { return;/* w ww. j a v a2 s . c o m*/ } added.add(metadata.getKey()); // Add namespace for this element (if any) XmlNamespace elemNs = metadata.getName().getNs(); if (elemNs != null) { builder.add(elemNs); } // Add namespace for all attributes (if any) for (AttributeKey<?> attrKey : metadata.getAttributes()) { AttributeMetadata<?> attrMetadata = metadata.bindAttribute(attrKey); XmlNamespace attrNs = attrMetadata.getName().getNs(); if (attrNs != null) { builder.add(attrNs); } } // Add namespace for all child elements (recursively) for (ElementKey<?, ?> elemKey : metadata.getElements()) { ElementMetadata<?, ?> childMetadata = metadata.bindElement(elemKey); addReferencedNamespaces(childMetadata, builder, added); } }