Java Code Examples for com.google.common.collect.Sets#newLinkedHashSet()

The following examples show how to use com.google.common.collect.Sets#newLinkedHashSet() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: StrategoRuntimeFacetFromESV.java    From spoofax with Apache License 2.0 6 votes vote down vote up
public static StrategoRuntimeFacet create(IStrategoAppl esv, FileObject location) throws FileSystemException {
    final Set<FileObject> strategoFiles = providerResources(esv, location);
    // Use LinkedHashSet to maintain ordering.
    final Set<FileObject> ctreeFiles = Sets.newLinkedHashSet();
    for(FileObject strategoFile : strategoFiles) {
        final String extension = strategoFile.getName().getExtension();
        switch (extension) {
            case "ctree":
                ctreeFiles.add(strategoFile);
                break;
            case "jar":
                break;
            default:
                logger.warn("Stratego provider file {} has unknown extension {}, ignoring", strategoFile, extension);
                break;
        }
    }

    return new StrategoRuntimeFacet(ctreeFiles);
}
 
Example 2
Source File: FlagUtils.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
/**
 * @throws an IllegalStateException if there are fields required (nullable=false) which are unset 
 * @throws wrapped IllegalAccessException
 */
public static void checkRequiredFields(Object o) {
    try {
        Set<String> unsetFields = Sets.newLinkedHashSet();
        for (Map.Entry<Field, SetFromFlag> entry : getAnnotatedFields(o.getClass()).entrySet()) {
            Field f = entry.getKey();
            SetFromFlag cf = entry.getValue();
            if (!cf.nullable()) {
                String flagName = elvis(cf.value(), f.getName());
                if (!f.isAccessible()) f.setAccessible(true);
                Object v = f.get(o);
                if (v==null) unsetFields.add(flagName);
            }
        }
        if (groovyTruth(unsetFields)) {
            throw new IllegalStateException("Missing required "+(unsetFields.size()>1 ? "fields" : "field")+": "+unsetFields);
        }
    } catch (IllegalAccessException e) {
        throw Throwables.propagate(e);
    }
}
 
Example 3
Source File: FileInclusionManager.java    From BashSupport with Apache License 2.0 5 votes vote down vote up
/**
 * Finds all files which include the given file.
 * The bash files of the module are checked if they include the file.
 *
 * @param project The project
 * @param file    The file for which the includers should be found.
 * @return
 */
@NotNull
public static Set<BashFile> findIncluders(@NotNull Project project, @NotNull PsiFile file) {
    if (DumbService.isDumb(project)) {
        return Collections.emptySet();
    }

    GlobalSearchScope searchScope = BashSearchScopes.moduleScope(file);

    String filename = file.getName();
    if (StringUtils.isEmpty(filename)) {
        return Collections.emptySet();
    }

    Collection<BashIncludeCommand> includeCommands = StubIndex.getElements(BashIncludedFilenamesIndex.KEY, filename, project, BashSearchScopes.bashOnly(searchScope), BashIncludeCommand.class);
    if (includeCommands == null || includeCommands.isEmpty()) {
        return Collections.emptySet();
    }

    Set<BashFile> includers = Sets.newLinkedHashSet();
    for (BashIncludeCommand command : includeCommands) {
        BashFile includer = (BashFile) BashPsiUtils.findFileContext(command);

        if (!file.equals(includer)) {
            includers.add(includer);
        }
    }

    return includers;
}
 
Example 4
Source File: ConfigMapViewWithStringKeys.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public Set<String> keySet() {
    LinkedHashSet<String> result = Sets.newLinkedHashSet();
    Set<Map.Entry<ConfigKey<?>, Object>> set = target.getAllConfig().entrySet();
    for (final Map.Entry<ConfigKey<?>, Object> entry: set) {
        result.add(entry.getKey().getName());
    }
    return result;
}
 
Example 5
Source File: ServiceDaoJdbc.java    From OpenCue with Apache License 2.0 5 votes vote down vote up
public static LinkedHashSet<String> splitTags(String tags) {
    LinkedHashSet<String> set = Sets.newLinkedHashSet();
    for(String s: tags.split(SPLITTER)) {
       set.add(s.replaceAll(" ", ""));
    }
    return set;
}
 
Example 6
Source File: AliasKeywords.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
AliasKeywords(AbstractCompiler compiler) {
  this.compiler = compiler;
  aliasSpecifications = createAliasSpecifications();
  aliasTypes = Maps.newLinkedHashMap();
  aliasNames = Sets.newLinkedHashSet();
  for (AliasSpecification specification : aliasSpecifications) {
    aliasTypes.put(specification.getTokenId(), specification);
    aliasNames.add(specification.getAliasName());
  }
}
 
Example 7
Source File: DynamicClusterImpl.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
protected List<Location> getNonFailedSubLocations() {
    List<Location> result = Lists.newArrayList();
    Set<Location> failed = Sets.newLinkedHashSet();
    List<Location> subLocations = findSubLocations(getLocation(true));
    Set<Location> oldFailedSubLocations = getAttribute(FAILED_SUB_LOCATIONS);
    if (oldFailedSubLocations == null)
        oldFailedSubLocations = ImmutableSet.<Location> of();

    for (Location subLocation : subLocations) {
        if (getZoneFailureDetector().hasFailed(subLocation)) {
            failed.add(subLocation);
        } else {
            result.add(subLocation);
        }
    }

    Set<Location> newlyFailed = Sets.difference(failed, oldFailedSubLocations);
    Set<Location> newlyRecovered = Sets.difference(oldFailedSubLocations, failed);
    sensors().set(FAILED_SUB_LOCATIONS, failed);
    sensors().set(SUB_LOCATIONS, result);
    if (newlyFailed.size() > 0) {
        LOG.warn("Detected probably zone failures for {}: {}", this, newlyFailed);
    }
    if (newlyRecovered.size() > 0) {
        LOG.warn("Detected probably zone recoveries for {}: {}", this, newlyRecovered);
    }

    return result;
}
 
Example 8
Source File: ProblemAnnotationHover.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected Object getHoverInfoInternal(final ITextViewer textViewer, final int lineNumber, final int offset) {
	final Set<String> messages = Sets.newLinkedHashSet();
	List<Annotation> annotations = getAnnotations(lineNumber, offset);
	for (Annotation annotation : annotations) {
		String text = annotation.getText();
		if (text != null) {
			messages.add(text.trim());
		}
	}
	if (messages.size() > 0)
		return formatInfo(messages);
	return null;
}
 
Example 9
Source File: AbstractRedisClient.java    From nano-framework with Apache License 2.0 5 votes vote down vote up
@Override
public <T> Set<T> spop(final String key, final int count, final TypeReference<T> type) {
    Assert.notNull(type);
    final Set<String> values = spop(key, count);
    if (!values.isEmpty()) {
        final Set<T> newValues = Sets.newLinkedHashSet();
        for (String value : values) {
            newValues.add(parseObject(value, type));
        }

        return newValues;
    }

    return Collections.emptySet();
}
 
Example 10
Source File: App.java    From jweb-cms with GNU Affero General Public License v3.0 5 votes vote down vote up
private List<String> orderedModules() {
    if (orderedModules == null) {
        Graph<String> graph = createGraph();
        Deque<String> readyModules = Lists.newLinkedList();
        for (String node : graph.nodes()) {
            if (graph.predecessors(node).isEmpty()) {
                readyModules.push(node);
            }
        }
        Set<String> visited = Sets.newLinkedHashSet();
        while (!readyModules.isEmpty()) {
            String moduleName = readyModules.pollFirst();
            visited.add(moduleName);

            Set<String> successors = graph.successors(moduleName);
            for (String successor : successors) {
                ModuleNode moduleNode = moduleNode(successor).orElseThrow();
                boolean ready = true;
                for (String dependency : moduleNode.module.dependencies()) {
                    if (isInstalled(dependency) && !visited.contains(dependency)) {
                        ready = false;
                        break;
                    }
                }
                if (ready && !visited.contains(successor)) {
                    readyModules.add(successor);
                }
            }
        }
        orderedModules = ImmutableList.copyOf(visited);
    }
    return orderedModules;
}
 
Example 11
Source File: JavaProjectPreferencesInitializer.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
@SuppressWarnings("restriction")
@Inject
public void addOwnFileExtensionsToJavaBuildResourceCopyFilter(FileExtensionProvider extensionProvider) {
	@SuppressWarnings("deprecation")
	IScopeContext defaultScope = new DefaultScope();

	// The class org.eclipse.jdt.internal.launching.LaunchingPreferenceInitializer has this very nasty habit 
	// of replacing all RESOURCE_COPY_FILTERs with its own filter. Calling getNode(LaunchingPlugin.ID_PLUGIN) 
	// causes LaunchingPreferenceInitializer to be executed that afterwards we can append our filters safely.    
	// see https://bugs.eclipse.org/bugs/show_bug.cgi?id=395366
	defaultScope.getNode(org.eclipse.jdt.internal.launching.LaunchingPlugin.ID_PLUGIN);

	IEclipsePreferences dnode = defaultScope.getNode(JavaCore.PLUGIN_ID);
	if (dnode == null)
		return;
	Set<String> filters = Sets.newLinkedHashSet();
	for (String filter : dnode.get(JavaCore.CORE_JAVA_BUILD_RESOURCE_COPY_FILTER, "").split(",")) {
		String trimmed = filter.trim();
		if (!"".equals(trimmed))
			filters.add(trimmed);
	}
	for (String ext : extensionProvider.getFileExtensions())
		filters.add("*." + ext);
	dnode.put(JavaCore.CORE_JAVA_BUILD_RESOURCE_COPY_FILTER, Joiner.on(", ").join(filters));
	try {
		dnode.flush();
	} catch (BackingStoreException e) {
		log.error("Error saving preferences", e);
	}
}
 
Example 12
Source File: AggregateClassLoader.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public Enumeration<URL> getResources(String name) throws IOException {
    Set<URL> resources = Sets.newLinkedHashSet();
    Iterator<ClassLoader> cli = iterator();
    while (cli.hasNext()) {
        ClassLoader classLoader=cli.next();
        resources.addAll(Collections.list(classLoader.getResources(name)));
    }
    return Collections.enumeration(resources);
}
 
Example 13
Source File: CubeScanRangePlanner.java    From kylin-on-parquet-v2 with Apache License 2.0 5 votes vote down vote up
private GTScanRange mergeKeyRange(List<GTScanRange> ranges) {
    GTScanRange first = ranges.get(0);
    if (ranges.size() == 1)
        return first;

    GTRecord start = first.pkStart;
    GTRecord end = first.pkEnd;
    Set<GTRecord> newFuzzyKeys = Sets.newLinkedHashSet();

    boolean hasNonFuzzyRange = false;
    for (GTScanRange range : ranges) {
        hasNonFuzzyRange = hasNonFuzzyRange || range.fuzzyKeys.isEmpty();
        newFuzzyKeys.addAll(range.fuzzyKeys);
        end = rangeEndComparator.max(end, range.pkEnd);
    }

    // if any range is non-fuzzy, then all fuzzy keys must be cleared
    // too many fuzzy keys will slow down HBase scan
    if (hasNonFuzzyRange || newFuzzyKeys.size() > maxFuzzyKeys) {
        if (newFuzzyKeys.size() > maxFuzzyKeys) {
            logger.debug("too many FuzzyKeys,  clean it!");
        }
        newFuzzyKeys.clear();
    }

    return new GTScanRange(start, end, Lists.newArrayList(newFuzzyKeys));
}
 
Example 14
Source File: WrapEntry.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Combine all linewrap locators - the maximum values of any LinewrapLocator.
 *
 * @return new lines
 */
protected int combineLinewraps() {
  maxLinewrap = 0;
  minLinewrap = 0;
  int defaultLinewrap = 0;
  final Set<ILinewrapLocator> locators = Sets.newLinkedHashSet(Iterables.filter(entry.getEntryLocators(), ILinewrapLocator.class));
  final ILinewrapLocator requiredLW = line.isFirstEntry(entry) ? line.getInitialLinewrapLocator() : null; // NOPMD NullAssignment
  if (requiredLW != null) {
    locators.add(requiredLW);
  }
  for (ILinewrapLocator locator : locators) {

    switch (locator.getPolicy()) {
    case OVERRIDE:
      return createWrap(locator.getMinWrap(), locator.getDefaultWrap(), locator.getMaxWrap());
    case ADDITIVE:
      minLinewrap += locator.getMinWrap();
      defaultLinewrap += locator.getDefaultWrap();
      maxLinewrap += locator.getMaxWrap();
      break;
    case COMBINED_MAXIMUM:
      minLinewrap = Math.max(minLinewrap, locator.getMinWrap());
      defaultLinewrap = Math.max(defaultLinewrap, locator.getDefaultWrap());
      maxLinewrap = Math.max(maxLinewrap, locator.getMaxWrap());
      break;
    default:
      break;
    }
  }
  return createWrap(minLinewrap, defaultLinewrap, maxLinewrap);
}
 
Example 15
Source File: TaskRunner.java    From bistoury with GNU General Public License v3.0 5 votes vote down vote up
private List<String> parseLockOn(List<String> lines) {
    if (lines.size() < 3) {
        return ImmutableList.of();
    }

    Set<String> lock = Sets.newLinkedHashSet();
    for (int lineIndex = lines.size() - 1; lineIndex >= 2; lineIndex--) {
        String line = lines.get(lineIndex).trim();
        if (line.startsWith("-")) {
            List<String> strs = SPACE_SPLITTER.splitToList(line);
            int lockIdIndex = findLockIdIndex(strs);
            if (lockIdIndex < 0) {
                continue;
            }

            for (int i = 0; i < lockIdIndex; ++i) {
                String str = strs.get(i);
                if (str.contains("lock")) {
                    lock.add(getLockId(strs.get(lockIdIndex)));
                    break;
                } else if (str.contains("wait")) {
                    lock.remove(strs.get(lockIdIndex));
                    break;
                }
            }
        }
    }
    return ImmutableList.copyOf(lock);
}
 
Example 16
Source File: SymlinkForest.java    From bazel with Apache License 2.0 4 votes vote down vote up
/**
 * Performs the filesystem operations to plant the symlink forest.
 *
 * @return the symlinks that have been planted
 */
public ImmutableList<Path> plantSymlinkForest() throws IOException, AbruptExitException {
  deleteTreesBelowNotPrefixed(execroot, prefix);

  if (siblingRepositoryLayout) {
    // Delete execroot/../<symlinks> to directories representing external repositories.
    for (Path p : execroot.getParentDirectory().getDirectoryEntries()) {
      if (p.isSymbolicLink()) {
        p.deleteTree();
      }
    }
  }

  boolean shouldLinkAllTopLevelItems = false;
  Map<Path, Path> mainRepoLinks = Maps.newLinkedHashMap();
  Set<Root> mainRepoRoots = Sets.newLinkedHashSet();
  Set<Path> externalRepoLinks = Sets.newLinkedHashSet();
  Map<PackageIdentifier, Root> packageRootsForMainRepo = Maps.newLinkedHashMap();
  ImmutableList.Builder<Path> plantedSymlinks = ImmutableList.builder();

  for (Map.Entry<PackageIdentifier, Root> entry : packageRoots.entrySet()) {
    PackageIdentifier pkgId = entry.getKey();
    if (pkgId.equals(LabelConstants.EXTERNAL_PACKAGE_IDENTIFIER)) {
      // //external is a virtual package regardless , don't add it to the symlink tree.
      // Subpackages of
      // external, like //external/foo, are fine though.
      continue;
    }
    RepositoryName repository = pkgId.getRepository();
    if (repository.isMain() || repository.isDefault()) {
      // Record main repo packages.
      packageRootsForMainRepo.put(entry.getKey(), entry.getValue());

      // Record the root of the packages.
      mainRepoRoots.add(entry.getValue());

      // For single root (single package path) case:
      // If root package of the main repo is required, we record the main repo root so that
      // we can later link everything under the main repo's top-level directory.
      // If root package of the main repo is not required, we only record links for
      // directories under the top-level directory that are used in required packages.
      if (pkgId.getPackageFragment().equals(PathFragment.EMPTY_FRAGMENT)) {
        shouldLinkAllTopLevelItems = true;
      } else {
        String baseName = pkgId.getPackageFragment().getSegment(0);
        if (!siblingRepositoryLayout
            && baseName.equals(LabelConstants.EXTERNAL_PATH_PREFIX.getBaseName())) {
          // ignore external/ directory if user has it in the source tree
          // because it conflicts with external repository location.
          continue;
        }
        Path execrootLink = execroot.getRelative(baseName);
        Path sourcePath = entry.getValue().getRelative(pkgId.getSourceRoot().getSegment(0));
        mainRepoLinks.putIfAbsent(execrootLink, sourcePath);
      }
    } else {
      plantSymlinkForExternalRepo(
          plantedSymlinks,
          repository,
          entry.getValue().getRelative(repository.getSourceRoot()),
          externalRepoLinks);
    }
  }

  // TODO(bazel-team): Bazel can find packages in multiple paths by specifying --package_paths,
  // we need a more complex algorithm to build execroot in that case. As --package_path will be
  // removed in the future, we should remove the plantSymlinkForestMultiPackagePath
  // implementation when --package_path is gone.
  if (mainRepoRoots.size() > 1) {
    if (!this.notSymlinkedInExecrootDirectories.isEmpty()) {
      throw new AbruptExitException(
          detailedSymlinkForestExitCode(
              "toplevel_output_directories is not supported together with --package_path option.",
              Code.TOPLEVEL_OUTDIR_PACKAGE_PATH_CONFLICT,
              ExitCode.COMMAND_LINE_ERROR));
    }
    plantSymlinkForestMultiPackagePath(plantedSymlinks, packageRootsForMainRepo);
  } else if (shouldLinkAllTopLevelItems) {
    Path mainRepoRoot = Iterables.getOnlyElement(mainRepoRoots).asPath();
    plantSymlinkForestWithFullMainRepository(plantedSymlinks, mainRepoRoot);
  } else {
    plantSymlinkForestWithPartialMainRepository(plantedSymlinks, mainRepoLinks);
  }

  logger.atInfo().log("Planted symlink forest in %s", execroot);
  return plantedSymlinks.build();
}
 
Example 17
Source File: TargetURISet.java    From xtext-core with Eclipse Public License 2.0 4 votes vote down vote up
protected TargetURISet() {
	uris = Sets.newLinkedHashSet();
	index = HashMultimap.create(4, 4);
}
 
Example 18
Source File: DaemonForkOptions.java    From pushfish-android with BSD 2-Clause "Simplified" License 4 votes vote down vote up
private Set<String> getNormalizedSharedPackages(Iterable<String> allowedPackages) {
    return Sets.newLinkedHashSet(allowedPackages);
}
 
Example 19
Source File: LiveSet.java    From caja with Apache License 2.0 2 votes vote down vote up
/**
 * Yields a {@code LiveSet} with any symbols that occur in both this and
 * other.
 * This is typically used when execution branches, because the {@code LiveSet}
 * at the point branched paths converge is the set of variables that were
 * made live in all branches.
 */
LiveSet intersection(LiveSet other) {
  Set<Pair<String, LexicalScope>> isymbols = Sets.newLinkedHashSet(symbols);
  isymbols.retainAll(other.symbols);
  return isymbols.isEmpty() ? EMPTY : new LiveSet(isymbols);
}
 
Example 20
Source File: StartParameter.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 2 votes vote down vote up
/**
 * Sets the tasks to exclude from this build.
 *
 * @param excludedTaskNames The task names. Can be null.
 */
public void setExcludedTaskNames(Iterable<String> excludedTaskNames) {
    this.excludedTaskNames = Sets.newLinkedHashSet(excludedTaskNames);
}