private void assertCompletionContains(
      String completionText, PsiElement context, String[] expectedItems, String[] disallowedItems) {
    SmaliCodeFragmentFactory codeFragmentFactory = new SmaliCodeFragmentFactory();
    JavaCodeFragment fragment =
        codeFragmentFactory.createCodeFragment(
            new TextWithImportsImpl(CodeFragmentKind.EXPRESSION, completionText),
            context,
            getProject());

    Editor editor = createEditor(fragment.getVirtualFile());
    editor.getCaretModel().moveToOffset(completionText.length());

    new CodeCompletionHandlerBase(CompletionType.BASIC).invokeCompletion(getProject(), editor);
    List<LookupElement> elements =
        LookupManager.getInstance(getProject()).getActiveLookup().getItems();

    HashSet expectedSet = Sets.newHashSet(expectedItems);
    HashSet disallowedSet = Sets.newHashSet(disallowedItems);

    for (LookupElement element : elements) {
      expectedSet.remove(element.toString());
      Assert.assertFalse(disallowedSet.contains(element.toString()));
    }

    Assert.assertTrue(expectedSet.size() == 0);
  }
Esempio n. 2
0
  public void loadGridNet(String mapGrid) throws IOException {
    Preconditions.checkArgument(!Strings.isNullOrEmpty(mapGrid));

    logger.debug("loading {}...", mapGrid);

    CSVReader reader = new CSVReader(new FileReader(mapGrid), ',', '"', 1);
    String[] row;
    while ((row = reader.readNext()) != null) {
      String gridId = row[1].trim();
      String dmRoads = row[2].trim();
      String gjRoads = row[3].trim();

      Set<String> x =
          Sets.newHashSet(Splitter.on('|').trimResults().omitEmptyStrings().split(dmRoads));
      Set<String> y =
          Sets.newHashSet(Splitter.on('|').trimResults().omitEmptyStrings().split(gjRoads));
      if (x.size() > 0 || y.size() > 0) {
        MapGrid grid = new MapGrid();
        grid.dmRoads = x;
        grid.gjRoads = y;

        gridNet.put(gridId, grid);
        //                logger.debug("{},{},{}", gridId, x, y);
      }
    }

    reader.close();
  }
Esempio n. 3
0
 public Set<TableDefinition> getTableDefinitions(String databaseName) {
   Map<String, TableDefinition> tableDefinitionMap = tableDefinitions.get(databaseName);
   if (tableDefinitionMap != null) {
     return Sets.newHashSet(tableDefinitions.get(databaseName).values());
   }
   return Sets.newHashSet();
 }
Esempio n. 4
0
  private void deleteFromAllAuthorities(
      Predicate<RoleGrantedAuthority> predicate, String commitMessage, User currentUser)
      throws IOException, GitAPIException {

    ILockedRepository repo = null;
    try {
      List<String> users = listUsers();
      users.add(ANONYMOUS_USER_LOGIN_NAME);
      repo = globalRepositoryManager.getProjectCentralRepository(REPOSITORY_NAME, false);
      boolean anyChanged = false;
      for (String loginName : users) {
        Set<RoleGrantedAuthority> authorities =
            Sets.newHashSet(getUserAuthorities(loginName, repo));
        Set<RoleGrantedAuthority> newAuthorities =
            Sets.newHashSet(Sets.filter(authorities, predicate));
        if (!newAuthorities.equals(authorities)) {
          saveUserAuthorities(loginName, newAuthorities, repo, currentUser, false);
          anyChanged = true;
        }
      }

      if (anyChanged) {
        PersonIdent ident = new PersonIdent(currentUser.getLoginName(), currentUser.getEmail());
        Git.wrap(repo.r())
            .commit()
            .setAuthor(ident)
            .setCommitter(ident)
            .setMessage(commitMessage)
            .call();
      }
    } finally {
      Util.closeQuietly(repo);
    }
  }
  @Test
  public void testCoveringPartitions() {
    Iterable<PartitionView<TestRecord>> partitions = unpartitioned.getCoveringPartitions();
    Assert.assertEquals(
        "Should have a single partition view at the root",
        unpartitioned.getPartitionView(URI.create("file:/tmp/datasets/unpartitioned")),
        Iterables.getOnlyElement(partitions));

    partitions = partitioned.getCoveringPartitions();
    Set<PartitionView<TestRecord>> expected = Sets.newHashSet();
    expected.add(
        partitioned.getPartitionView(URI.create("file:/tmp/datasets/partitioned/id_hash=0")));
    expected.add(
        partitioned.getPartitionView(new Path("file:/tmp/datasets/partitioned/id_hash=1")));
    expected.add(
        partitioned.getPartitionView(URI.create("file:/tmp/datasets/partitioned/id_hash=2")));
    expected.add(
        partitioned.getPartitionView(new Path("file:/tmp/datasets/partitioned/id_hash=3")));
    Assert.assertEquals(
        "Should have a partition view for each partition", expected, Sets.newHashSet(partitions));

    PartitionView<TestRecord> partition0 =
        partitioned.getPartitionView(URI.create("file:/tmp/datasets/partitioned/id_hash=0"));
    partition0.deleteAll();
    expected.remove(partition0);
    Assert.assertEquals(
        "Should have a partition view for each partition", expected, Sets.newHashSet(partitions));
  }
Esempio n. 6
0
  public Set<User> getUsers(PermissionContext ctx, String groupName) {
    if (groupName == null) {
      return Sets.newHashSet(UserUtils.getAllUsers());
    }

    return Sets.newHashSet(getUserUtil().getAllUsersInGroupNamesUnsorted(singletonList(groupName)));
  }
Esempio n. 7
0
  public double isBashFile(File file, String data, Project project) {
    ParserDefinition definition =
        LanguageParserDefinitions.INSTANCE.forLanguage(BashFileType.BASH_LANGUAGE);

    Lexer lexer = definition.createLexer(project);
    lexer.start(data);

    int tokenCount = 0;
    Set<IElementType> tokenSet = Sets.newHashSet();
    Set<Integer> modeSet = Sets.newHashSet();
    while (lexer.getTokenType() != BashTokenTypes.BAD_CHARACTER && lexer.getTokenType() != null) {
      tokenSet.add(lexer.getTokenType());
      modeSet.add(lexer.getState());

      lexer.advance();
      tokenCount++;
    }

    double score = 0;
    if (lexer.getTokenType() == BashTokenTypes.BAD_CHARACTER) {
      score -= badCharacterWeight;
    }

    if (tokenCount > 4) {
      score += tokenLimitWeight;
    }

    score += Math.min(0.45, (double) tokenSet.size() * tokenWeight);
    score += Math.min(0.45, (double) modeSet.size() * modeWeight);

    return score;
  }
Esempio n. 8
0
  private final void bindResourceToLocalContainer(
      final Class<?> resource, final Class<?> container) {
    final Set<Method> nonAbstractMethods =
        Sets.newHashSet(resource.getMethods())
            .stream()
            .filter(method -> !Modifier.isAbstract(method.getModifiers()))
            .collect(Collectors.toSet());
    Preconditions.checkState(
        !nonAbstractMethods.isEmpty(),
        "Found non-abstract methods in " + resource + ": " + nonAbstractMethods);

    final Set<Method> abstractMethods =
        Sets.newHashSet(resource.getMethods())
            .stream()
            .filter(method -> Modifier.isAbstract(method.getModifiers()))
            .collect(Collectors.toSet());

    for (final Method resourceMethod : abstractMethods) {
      final Method containerMethod = findMatchingMethod(container, resourceMethod);
      if (containerMethod != null) {
        this.resourceToContainer.put(resourceMethod, containerMethod);
      }
    }

    bindResourceToContainer(resource, injector.getInstance(container));
  }
Esempio n. 9
0
  @Test
  public void listChildPagePaths() throws IOException, GitAPIException {
    register(globalRepoManager.createProjectCentralRepository(PROJECT, USER));
    register(globalRepoManager.createProjectBranchRepository(PROJECT, BRANCH_1, null));
    saveRandomPage(BRANCH_1, DocumentrConstants.HOME_PAGE_NAME + "/foo"); // $NON-NLS-1$
    saveRandomPage(BRANCH_1, DocumentrConstants.HOME_PAGE_NAME + "/foo/bar"); // $NON-NLS-1$
    saveRandomPage(BRANCH_1, DocumentrConstants.HOME_PAGE_NAME + "/foo/bar/baz"); // $NON-NLS-1$
    saveRandomPage(BRANCH_1, DocumentrConstants.HOME_PAGE_NAME + "/foo/qux"); // $NON-NLS-1$

    Set<String> expected =
        Sets.newHashSet(
            DocumentrConstants.HOME_PAGE_NAME + "/foo/bar", // $NON-NLS-1$
            DocumentrConstants.HOME_PAGE_NAME + "/foo/qux"); // $NON-NLS-1$
    Set<String> result =
        Sets.newHashSet(
            pageStore.listChildPagePaths(
                PROJECT, BRANCH_1, DocumentrConstants.HOME_PAGE_NAME + "/foo")); // $NON-NLS-1$
    assertEquals(expected, result);
    expected =
        Collections.singleton(DocumentrConstants.HOME_PAGE_NAME + "/foo/bar/baz"); // $NON-NLS-1$
    result =
        Sets.newHashSet(
            pageStore.listChildPagePaths(
                PROJECT, BRANCH_1, DocumentrConstants.HOME_PAGE_NAME + "/foo/bar")); // $NON-NLS-1$
    assertEquals(expected, result);
  }
  /** set note authorization information */
  @PUT
  @Path("{noteId}/permissions")
  @ZeppelinApi
  public Response putNotePermissions(@PathParam("noteId") String noteId, String req)
      throws IOException {
    HashMap<String, HashSet> permMap =
        gson.fromJson(req, new TypeToken<HashMap<String, HashSet>>() {}.getType());
    Note note = notebook.getNote(noteId);
    String principal = SecurityUtils.getPrincipal();
    HashSet<String> roles = SecurityUtils.getRoles();
    LOG.info(
        "Set permissions {} {} {} {} {}",
        noteId,
        principal,
        permMap.get("owners"),
        permMap.get("readers"),
        permMap.get("writers"));

    HashSet<String> userAndRoles = new HashSet<String>();
    userAndRoles.add(principal);
    userAndRoles.addAll(roles);
    if (!notebookAuthorization.isOwner(noteId, userAndRoles)) {
      return new JsonResponse<>(
              Status.FORBIDDEN,
              ownerPermissionError(userAndRoles, notebookAuthorization.getOwners(noteId)))
          .build();
    }

    HashSet readers = permMap.get("readers");
    HashSet owners = permMap.get("owners");
    HashSet writers = permMap.get("writers");
    // Set readers, if writers and owners is empty -> set to user requesting the change
    if (readers != null && !readers.isEmpty()) {
      if (writers.isEmpty()) {
        writers = Sets.newHashSet(SecurityUtils.getPrincipal());
      }
      if (owners.isEmpty()) {
        owners = Sets.newHashSet(SecurityUtils.getPrincipal());
      }
    }
    // Set writers, if owners is empty -> set to user requesting the change
    if (writers != null && !writers.isEmpty()) {
      if (owners.isEmpty()) {
        owners = Sets.newHashSet(SecurityUtils.getPrincipal());
      }
    }

    notebookAuthorization.setReaders(noteId, readers);
    notebookAuthorization.setWriters(noteId, writers);
    notebookAuthorization.setOwners(noteId, owners);
    LOG.debug(
        "After set permissions {} {} {}",
        notebookAuthorization.getOwners(noteId),
        notebookAuthorization.getReaders(noteId),
        notebookAuthorization.getWriters(noteId));
    AuthenticationInfo subject = new AuthenticationInfo(SecurityUtils.getPrincipal());
    note.persist(subject);
    notebookServer.broadcastNote(note);
    return new JsonResponse<>(Status.OK).build();
  }
 /**
  * Applies the exclude filter to the found annotations.
  *
  * @param allAnnotations all annotations
  * @return the filtered annotations if there is a filter defined
  */
 private Set<FileAnnotation> applyExcludeFilter(final Set<FileAnnotation> allAnnotations) {
   Set<FileAnnotation> includedAnnotations;
   if (includePatterns.isEmpty()) {
     includedAnnotations = allAnnotations;
   } else {
     includedAnnotations = Sets.newHashSet();
     for (FileAnnotation annotation : allAnnotations) {
       for (Pattern include : includePatterns) {
         if (include.matcher(annotation.getFileName()).matches()) {
           includedAnnotations.add(annotation);
         }
       }
     }
   }
   if (excludePatterns.isEmpty()) {
     return includedAnnotations;
   } else {
     Set<FileAnnotation> excludedAnnotations = Sets.newHashSet(includedAnnotations);
     for (FileAnnotation annotation : includedAnnotations) {
       for (Pattern exclude : excludePatterns) {
         if (exclude.matcher(annotation.getFileName()).matches()) {
           excludedAnnotations.remove(annotation);
         }
       }
     }
     return excludedAnnotations;
   }
 }
Esempio n. 12
0
 /**
  * Creates new instance of ClassFrame.
  *
  * @param parent parent frame.
  * @param ident frame name ident.
  */
 ClassFrame(AbstractFrame parent, DetailAST ident) {
   super(parent, ident);
   instanceMembers = Sets.newHashSet();
   instanceMethods = Sets.newHashSet();
   staticMembers = Sets.newHashSet();
   staticMethods = Sets.newHashSet();
 }
Esempio n. 13
0
  @Autowired
  public UrlTokenMonitor(
      ZooKeeperConnection connection,
      ControllerPaths controllerPaths,
      ObjectSerializer objectSerializer,
      UrlTokenDictionary tokenDictionary,
      UrlTokenRepository tokenRepository) {
    ZooKeeperTreeConsistentCallback cb =
        new ZooKeeperTreeConsistentCallback() {
          @Override
          public void treeConsistent(ZooKeeperTreeNode oldRoot, ZooKeeperTreeNode newRoot) {
            onTokenTreeChanged(newRoot);
          }
        };
    this.objectSerializer = objectSerializer;
    this.tokenDictionary = tokenDictionary;
    this.tokenRepository = tokenRepository;

    String nodePath = controllerPaths.getUrlTokens();
    this.tokenNodeWatcher = new ZooKeeperTreeWatcher(connection, 0, nodePath, cb);

    this.tokenChangeListeners = Sets.newHashSet();
    this.previousTokenDtos = Sets.newHashSet();
    this.tokensInitialized = false;
  }
  public static Set<Class<?>> getReferencedClasses(
      Set<Type> referencedTypes, TypescriptServiceGeneratorConfiguration settings) {
    Set<Class<?>> ret = Sets.newHashSet();
    for (Type t : referencedTypes) {
      if (settings.ignoredClasses().contains(t)) {
        continue;
      }

      if (t instanceof Class && ((Class<?>) t).isEnum()) {
        ret.add((Class<?>) t);
        continue;
      }

      // dummy context used for below check
      Context nullContext =
          new Context(new SymbolTable(settings.getSettings()), settings.customTypeProcessor());
      // Don't add any classes that the user has made an exception for
      if (settings.customTypeProcessor().processType(t, nullContext) == null) {
        if (t instanceof Class) {
          ret.add((Class<?>) t);
        } else if (t instanceof ParameterizedType) {
          ParameterizedType parameterized = (ParameterizedType) t;
          ret.addAll(getReferencedClasses(Sets.newHashSet(parameterized.getRawType()), settings));
          ret.addAll(
              getReferencedClasses(
                  Sets.newHashSet(Arrays.asList(parameterized.getActualTypeArguments()).iterator()),
                  settings));
        }
      }
    }
    return ret;
  }
Esempio n. 15
0
  @GwtIncompatible // unreasonably slow
  public void testAsSetIteration() {
    @SuppressWarnings("unchecked")
    Set<Entry<String, Collection<Integer>>> set =
        newLinkedHashSet(
            asList(
                Maps.immutableEntry("foo", (Collection<Integer>) Sets.newHashSet(2, 3, 6)),
                Maps.immutableEntry("bar", (Collection<Integer>) Sets.newHashSet(4, 5, 10, 11)),
                Maps.immutableEntry("baz", (Collection<Integer>) Sets.newHashSet(7, 8)),
                Maps.immutableEntry("dog", (Collection<Integer>) Sets.newHashSet(9)),
                Maps.immutableEntry("cat", (Collection<Integer>) Sets.newHashSet(12, 13, 14))));
    new IteratorTester<Entry<String, Collection<Integer>>>(
        6, MODIFIABLE, set, IteratorTester.KnownOrder.KNOWN_ORDER) {
      private Multimap<String, Integer> multimap;

      @Override
      protected Iterator<Entry<String, Collection<Integer>>> newTargetIterator() {
        multimap = LinkedHashMultimap.create();
        multimap.putAll("foo", asList(2, 3));
        multimap.putAll("bar", asList(4, 5));
        multimap.putAll("foo", asList(6));
        multimap.putAll("baz", asList(7, 8));
        multimap.putAll("dog", asList(9));
        multimap.putAll("bar", asList(10, 11));
        multimap.putAll("cat", asList(12, 13, 14));
        return multimap.asMap().entrySet().iterator();
      }

      @Override
      protected void verify(List<Entry<String, Collection<Integer>>> elements) {
        assertEquals(newHashSet(elements), multimap.asMap().entrySet());
      }
    }.test();
  }
Esempio n. 16
0
  private void assertBranchesPageIsSharedWith(String branchName, String... expectedBranches)
      throws IOException {

    List<String> branches = pageStore.getBranchesPageIsSharedWith(PROJECT, branchName, PAGE);
    assertEquals(expectedBranches.length, branches.size());
    assertEquals(Sets.newHashSet(expectedBranches), Sets.newHashSet(branches));
  }
Esempio n. 17
0
  private void validateFilterPushDown(GTInfo info) {
    if (!hasFilterPushDown()) return;

    Set<TblColRef> filterColumns = Sets.newHashSet();
    TupleFilter.collectColumns(filterPushDown, filterColumns);

    for (TblColRef col : filterColumns) {
      // filter columns must belong to the table
      info.validateColRef(col);
      // filter columns must be returned to satisfy upper layer evaluation (calcite)
      columns = columns.set(col.getColumnDesc().getZeroBasedIndex());
    }

    // un-evaluatable filter must be removed
    if (!TupleFilter.isEvaluableRecursively(filterPushDown)) {
      Set<TblColRef> unevaluableColumns = Sets.newHashSet();
      filterPushDown = GTUtil.convertFilterUnevaluatable(filterPushDown, info, unevaluableColumns);

      // columns in un-evaluatable filter must be returned without loss so upper layer can do final
      // evaluation
      if (hasAggregation()) {
        for (TblColRef col : unevaluableColumns) {
          aggrGroupBy = aggrGroupBy.set(col.getColumnDesc().getZeroBasedIndex());
        }
      }
    }
  }
Esempio n. 18
0
 private static List<ITeam> extractTeamsList(
     List<String> teamsEmployeesStrings, List<IProjectStageSkill> skills) {
   List<ITeam> teams = Lists.newArrayList();
   Set<IEmployee> employees = Sets.newHashSet();
   String teamName = null;
   for (String employeeString : teamsEmployeesStrings) {
     if (Strings.isNullOrEmpty(employeeString.trim())) {
       continue;
     }
     LOGGER.debug("create employee for string: {}", employeeString);
     Iterable<String> strings = Splitter.on('\t').split(employeeString);
     List<String> words = Lists.newArrayList(strings);
     if (!words.get(0).isEmpty()) {
       if (teamName != null) {
         ITeam team = new Team(teamName, employees);
         teams.add(team);
       }
       employees = Sets.newHashSet();
       teamName = words.get(0);
     }
     IEmployee employee = extractEmployee(words, skills);
     employees.add(employee);
   }
   return teams;
 }
  @Parameterized.Parameters(name = "{index}: compression={0}, byteOrder={1}")
  public static Iterable<Object[]> compressionStrategies() {
    final Iterable<CompressedObjectStrategy.CompressionStrategy> compressionStrategies =
        Iterables.transform(
            CompressionStrategyTest.compressionStrategies(),
            new Function<Object[], CompressedObjectStrategy.CompressionStrategy>() {
              @Override
              public CompressedObjectStrategy.CompressionStrategy apply(Object[] input) {
                return (CompressedObjectStrategy.CompressionStrategy) input[0];
              }
            });

    Set<List<Object>> combinations =
        Sets.cartesianProduct(
            Sets.newHashSet(compressionStrategies),
            Sets.newHashSet(ByteOrder.BIG_ENDIAN, ByteOrder.LITTLE_ENDIAN));

    return Iterables.transform(
        combinations,
        new Function<List, Object[]>() {
          @Override
          public Object[] apply(List input) {
            return new Object[] {input.get(0), input.get(1)};
          }
        });
  }
 private void conflictSetChanged(TransformationDebuggerConflictSet set) {
   nextActivations = Sets.newHashSet(set.getNextActivations());
   conflictingActivations = Sets.newHashSet(set.getConflictingActivations());
   for (IDebuggerTargetAgent listener : agents) {
     listener.conflictSetChanged(nextActivations, conflictingActivations);
   }
 }
Esempio n. 21
0
  public void renameRole(String roleName, String newRoleName, User currentUser) throws IOException {
    Assert.hasLength(roleName);
    Assert.hasLength(newRoleName);
    Assert.notNull(currentUser);
    // check that role exists by trying to load it
    getRole(roleName);
    // check that new role does not exist by trying to load it
    try {
      getRole(newRoleName);
      throw new IllegalArgumentException("role already exists: " + newRoleName); // $NON-NLS-1$
    } catch (RoleNotFoundException e) {
      // okay
    }

    log.info("renaming role: {} -> {}", roleName, newRoleName); // $NON-NLS-1$

    ILockedRepository repo = null;
    try {
      repo = globalRepositoryManager.getProjectCentralRepository(REPOSITORY_NAME, false);

      File workingDir = RepositoryUtil.getWorkingDir(repo.r());

      File file = new File(workingDir, roleName + ROLE_SUFFIX);
      File newFile = new File(workingDir, newRoleName + ROLE_SUFFIX);
      FileUtils.copyFile(file, newFile);
      Git git = Git.wrap(repo.r());
      git.rm().addFilepattern(roleName + ROLE_SUFFIX).call();
      git.add().addFilepattern(newRoleName + ROLE_SUFFIX).call();

      List<String> users = listUsers(repo);
      users.add(ANONYMOUS_USER_LOGIN_NAME);
      for (String user : users) {
        List<RoleGrantedAuthority> authorities = getUserAuthorities(user, repo);
        Set<RoleGrantedAuthority> newAuthorities = Sets.newHashSet();
        for (Iterator<RoleGrantedAuthority> iter = authorities.iterator(); iter.hasNext(); ) {
          RoleGrantedAuthority rga = iter.next();
          if (rga.getRoleName().equals(roleName)) {
            RoleGrantedAuthority newRga = new RoleGrantedAuthority(rga.getTarget(), newRoleName);
            newAuthorities.add(newRga);
            iter.remove();
          }
        }
        if (!newAuthorities.isEmpty()) {
          authorities.addAll(newAuthorities);
          saveUserAuthorities(user, Sets.newHashSet(authorities), repo, currentUser, false);
        }
      }

      PersonIdent ident = new PersonIdent(currentUser.getLoginName(), currentUser.getEmail());
      git.commit()
          .setAuthor(ident)
          .setCommitter(ident)
          .setMessage("rename role " + roleName + " to " + newRoleName) // $NON-NLS-1$ //$NON-NLS-2$
          .call();
    } catch (GitAPIException e) {
      throw new IOException(e);
    } finally {
      Util.closeQuietly(repo);
    }
  }
Esempio n. 22
0
  private Set<String> deserialize(String features) {
    if (StringUtils.isBlank(features)) return Sets.newHashSet();

    String[] featureKeys = features.split(",");

    return Sets.newHashSet(featureKeys);
  }
 @Test
 public void testRoleSetAllUnknownGroup() {
   backend.initialize(context);
   assertEquals(
       Sets.newHashSet(),
       backend.getPrivileges(Sets.newHashSet("not-a-group"), ActiveRoleSet.ALL));
 }
Esempio n. 24
0
  private boolean isInDistanceInternal(
      int distance, NetworkNode from, NetworkNode to, TwoNetworkNodes cachePairKey) {
    if (from.equals(to)) return true;

    if (distance == 0) return false;

    if (SimpleNetwork.areNodesConnecting(from, to)) return true;

    // Breadth-first search of the network
    Set<NetworkNode> visitedNodes = Sets.newHashSet();
    visitedNodes.add(from);

    Set<NetworkNode> networkingNodesToTest = Sets.newHashSet();
    listConnectedNotVisitedNetworkingNodes(visitedNodes, from, networkingNodesToTest);
    int distanceSearched = 1;
    while (distanceSearched < distance) {
      distanceSearched++;

      for (NetworkNode nodeToTest : networkingNodesToTest) {
        if (SimpleNetwork.areNodesConnecting(nodeToTest, to)) {
          distanceCache.put(cachePairKey, distanceSearched);
          return true;
        }
        visitedNodes.add(nodeToTest);
      }

      Set<NetworkNode> nextNetworkingNodesToTest = Sets.newHashSet();
      for (NetworkNode nodeToTest : networkingNodesToTest)
        listConnectedNotVisitedNetworkingNodes(visitedNodes, nodeToTest, nextNetworkingNodesToTest);

      networkingNodesToTest = nextNetworkingNodesToTest;
    }

    return false;
  }
Esempio n. 25
0
 @SuppressWarnings({"unchecked", "ConstantConditions"})
 private static void checkResolvedCallsInDiagnostics(BindingContext bindingContext) {
   Set<DiagnosticFactory> diagnosticsStoringResolvedCalls1 =
       Sets.<DiagnosticFactory>newHashSet(
           OVERLOAD_RESOLUTION_AMBIGUITY,
           NONE_APPLICABLE,
           CANNOT_COMPLETE_RESOLVE,
           UNRESOLVED_REFERENCE_WRONG_RECEIVER,
           ASSIGN_OPERATOR_AMBIGUITY,
           ITERATOR_AMBIGUITY);
   Set<DiagnosticFactory> diagnosticsStoringResolvedCalls2 =
       Sets.<DiagnosticFactory>newHashSet(
           COMPONENT_FUNCTION_AMBIGUITY,
           DELEGATE_SPECIAL_FUNCTION_AMBIGUITY,
           DELEGATE_SPECIAL_FUNCTION_NONE_APPLICABLE);
   Diagnostics diagnostics = bindingContext.getDiagnostics();
   for (Diagnostic diagnostic : diagnostics) {
     DiagnosticFactory factory = diagnostic.getFactory();
     if (diagnosticsStoringResolvedCalls1.contains(factory)) {
       assertResolvedCallsAreCompleted(
           diagnostic,
           ((DiagnosticWithParameters1<PsiElement, Collection<? extends ResolvedCall<?>>>)
                   diagnostic)
               .getA());
     }
     if (diagnosticsStoringResolvedCalls2.contains(factory)) {
       assertResolvedCallsAreCompleted(
           diagnostic,
           ((DiagnosticWithParameters2<PsiElement, Object, Collection<? extends ResolvedCall<?>>>)
                   diagnostic)
               .getB());
     }
   }
 }
  protected void configure() {
    variantProductSource = new VariantProductSource();

    given(model.getBaseProduct()).willReturn(baseProduct);
    given(baseProduct.getVariants()).willReturn(Sets.newHashSet(variant3));
    given(model.getVariants()).willReturn(Sets.newHashSet(variant1, variant2));
  }
Esempio n. 27
0
 protected UpdateSubnetOptions() {
   this.name = null;
   this.gatewayIp = null;
   this.enableDhcp = null;
   this.dnsNameServers = Sets.newHashSet();
   this.hostRoutes = Sets.newHashSet();
 }
 /**
  * Creates new instance of ClassFrame.
  *
  * @param parent parent frame
  */
 ClassFrame(LexicalFrame parent) {
   super(parent);
   instanceMembers = Sets.newHashSet();
   instanceMethods = Sets.newHashSet();
   staticMembers = Sets.newHashSet();
   staticMethods = Sets.newHashSet();
 }
Esempio n. 29
0
  @Test
  public void testCreateAndDropTable() throws Exception {
    catalog.createDatabase("tmpdb1", TajoConstants.DEFAULT_TABLESPACE_NAME);
    assertTrue(catalog.existDatabase("tmpdb1"));
    catalog.createDatabase("tmpdb2", TajoConstants.DEFAULT_TABLESPACE_NAME);
    assertTrue(catalog.existDatabase("tmpdb2"));

    TableDesc table1 = createMockupTable("tmpdb1", "table1");
    catalog.createTable(table1);

    TableDesc table2 = createMockupTable("tmpdb2", "table2");
    catalog.createTable(table2);

    Set<String> tmpdb1 = Sets.newHashSet(catalog.getAllTableNames("tmpdb1"));
    assertEquals(1, tmpdb1.size());
    assertTrue(tmpdb1.contains("table1"));

    Set<String> tmpdb2 = Sets.newHashSet(catalog.getAllTableNames("tmpdb2"));
    assertEquals(1, tmpdb2.size());
    assertTrue(tmpdb2.contains("table2"));

    catalog.dropDatabase("tmpdb1");
    assertFalse(catalog.existDatabase("tmpdb1"));

    tmpdb2 = Sets.newHashSet(catalog.getAllTableNames("tmpdb2"));
    assertEquals(1, tmpdb2.size());
    assertTrue(tmpdb2.contains("table2"));

    catalog.dropDatabase("tmpdb2");
    assertFalse(catalog.existDatabase("tmpdb2"));
  }
Esempio n. 30
0
 RenameVars(
     AbstractCompiler compiler,
     String prefix,
     boolean localRenamingOnly,
     boolean preserveFunctionExpressionNames,
     boolean generatePseudoNames,
     boolean shouldShadow,
     VariableMap prevUsedRenameMap,
     @Nullable char[] reservedCharacters,
     @Nullable Set<String> reservedNames) {
   this.compiler = compiler;
   this.prefix = prefix == null ? "" : prefix;
   this.localRenamingOnly = localRenamingOnly;
   this.preserveFunctionExpressionNames = preserveFunctionExpressionNames;
   if (generatePseudoNames) {
     this.pseudoNameMap = Maps.newHashMap();
   } else {
     this.pseudoNameMap = null;
   }
   this.prevUsedRenameMap = prevUsedRenameMap;
   this.reservedCharacters = reservedCharacters;
   this.shouldShadow = shouldShadow;
   if (reservedNames == null) {
     this.reservedNames = Sets.newHashSet();
   } else {
     this.reservedNames = Sets.newHashSet(reservedNames);
   }
 }