Esempio n. 1
1
 private boolean containsColumn(Collection columns, String column) {
   if (columns.contains(column)) return true;
   for (Iterator it = columns.iterator(); it.hasNext(); ) {
     if (((String) it.next()).equalsIgnoreCase(column)) return true;
   }
   return false;
 }
 public static MultiMap<PsiElement, UsageInfo> classifyUsages(
     Collection<? extends PsiElement> elements, UsageInfo[] usages) {
   final MultiMap<PsiElement, UsageInfo> result = new MultiMap<PsiElement, UsageInfo>();
   for (UsageInfo usage : usages) {
     LOG.assertTrue(usage instanceof MoveRenameUsageInfo);
     if (usage.getReference() instanceof LightElement) {
       continue; // filter out implicit references (e.g. from derived class to super class' default
                 // constructor)
     }
     MoveRenameUsageInfo usageInfo = (MoveRenameUsageInfo) usage;
     if (usage instanceof RelatedUsageInfo) {
       final PsiElement relatedElement = ((RelatedUsageInfo) usage).getRelatedElement();
       if (elements.contains(relatedElement)) {
         result.putValue(relatedElement, usage);
       }
     } else {
       PsiElement referenced = usageInfo.getReferencedElement();
       if (elements.contains(referenced)) {
         result.putValue(referenced, usage);
       } else if (referenced != null) {
         PsiElement indirect = referenced.getNavigationElement();
         if (elements.contains(indirect)) {
           result.putValue(indirect, usage);
         }
       }
     }
   }
   return result;
 }
Esempio n. 3
0
  public static void testDetermineMergeParticipantsAndMergeCoords4() {
    Address a = Util.createRandomAddress(),
        b = Util.createRandomAddress(),
        c = Util.createRandomAddress(),
        d = Util.createRandomAddress();
    org.jgroups.util.UUID.add(a, "A");
    org.jgroups.util.UUID.add(b, "B");
    org.jgroups.util.UUID.add(c, "C");
    org.jgroups.util.UUID.add(d, "D");

    View v1 = View.create(a, 1, a, b);
    View v2 = View.create(c, 1, c, d);

    Map<Address, View> map = new HashMap<>();
    map.put(a, v1);
    map.put(b, v1);
    map.put(d, v2);

    StringBuilder sb = new StringBuilder("map:\n");
    for (Map.Entry<Address, View> entry : map.entrySet())
      sb.append(entry.getKey() + ": " + entry.getValue() + "\n");
    System.out.println(sb);

    Collection<Address> merge_participants = Util.determineMergeParticipants(map);
    System.out.println("merge_participants = " + merge_participants);
    assert merge_participants.size() == 3;
    assert merge_participants.contains(a)
        && merge_participants.contains(c)
        && merge_participants.contains(d);

    Collection<Address> merge_coords = Util.determineMergeCoords(map);
    System.out.println("merge_coords = " + merge_coords);
    assert merge_coords.size() == 2;
    assert merge_coords.contains(a) && merge_coords.contains(c);
  }
Esempio n. 4
0
  public void testRegularAndOOBUnicasts2() throws Exception {
    DISCARD discard = new DISCARD();
    ProtocolStack stack = a.getProtocolStack();
    stack.insertProtocol(
        discard, ProtocolStack.BELOW, (Class<? extends Protocol>[]) Util.getUnicastProtocols());

    Address dest = b.getAddress();
    Message m1 = new Message(dest, 1);
    Message m2 = new Message(dest, 2).setFlag(Message.Flag.OOB);
    Message m3 = new Message(dest, 3).setFlag(Message.Flag.OOB);
    Message m4 = new Message(dest, 4);

    MyReceiver receiver = new MyReceiver("B");
    b.setReceiver(receiver);
    a.send(m1);

    discard.setDropDownUnicasts(2);
    a.send(m2); // dropped
    a.send(m3); // dropped
    a.send(m4);

    Collection<Integer> list = receiver.getMsgs();
    int count = 10;
    while (list.size() < 4 && --count > 0) {
      Util.sleep(500); // time for potential retransmission
      sendStableMessages(a, b);
    }
    System.out.println("list = " + list);
    assert list.size() == 4 : "list is " + list;
    assert list.contains(1) && list.contains(2) && list.contains(3) && list.contains(4);
  }
Esempio n. 5
0
  public void testGetFeedsXmlURLs() throws MalformedURLException {
    assertEquals("Please remove all guides from set by this point.", 0, set.getGuidesCount());

    StandardGuide guide1 = new StandardGuide();
    guide1.setTitle("1");
    StandardGuide guide2 = new StandardGuide();
    guide2.setTitle("2");

    DirectFeed feed1 = new DirectFeed();
    feed1.setXmlURL(new URL("file://1"));
    DirectFeed feed2 = new DirectFeed();
    feed2.setXmlURL(new URL("file://2"));
    DirectFeed feed3 = new DirectFeed();
    feed3.setXmlURL(new URL("file://3"));
    DirectFeed feed4 = new DirectFeed();
    feed4.setXmlURL(new URL("file://1"));
    SearchFeed feed5 = new SearchFeed();
    feed5.setBaseTitle("5");

    guide1.add(feed1);
    guide1.add(feed5);
    guide2.add(feed2);
    guide2.add(feed3);
    guide2.add(feed4);

    set.add(guide1);
    set.add(guide2);

    Collection urls = set.getFeedsXmlURLs();
    assertEquals("URL's of network feeds (de-duplicated) should be returned.", 3, urls.size());
    assertTrue(urls.contains(feed1.getXmlURL()));
    assertTrue(urls.contains(feed2.getXmlURL()));
    assertTrue(urls.contains(feed3.getXmlURL()));
  }
  /** @param node Node to remove. */
  public void removeMappedNode(GridNode node) {
    if (mappedDhtNodes.contains(node))
      mappedDhtNodes = new ArrayList<>(F.view(mappedDhtNodes, F.notEqualTo(node)));

    if (mappedNearNodes != null && mappedNearNodes.contains(node))
      mappedNearNodes = new ArrayList<>(F.view(mappedNearNodes, F.notEqualTo(node)));
  }
Esempio n. 7
0
  public void testRegularAndOOBMulticasts() throws Exception {
    DISCARD discard = new DISCARD();
    ProtocolStack stack = a.getProtocolStack();
    stack.insertProtocol(discard, ProtocolStack.BELOW, NAKACK2.class);
    a.setDiscardOwnMessages(true);

    Address dest = null; // send to all
    Message m1 = new Message(dest, null, 1);
    Message m2 = new Message(dest, null, 2);
    m2.setFlag(Message.OOB);
    Message m3 = new Message(dest, null, 3);

    MyReceiver receiver = new MyReceiver("C2");
    b.setReceiver(receiver);
    a.send(m1);
    discard.setDropDownMulticasts(1);
    a.send(m2);
    a.send(m3);

    Util.sleep(500);
    Collection<Integer> list = receiver.getMsgs();
    for (int i = 0; i < 10; i++) {
      System.out.println("list = " + list);
      if (list.size() == 3) break;
      Util.sleep(1000); // give the asynchronous msgs some time to be received
      sendStableMessages(a, b);
    }
    assert list.size() == 3 : "list is " + list;
    assert list.contains(1) && list.contains(2) && list.contains(3);
  }
  /**
   * JUnit.
   *
   * @throws Exception If failed.
   */
  public void testGetAndIncrement() throws Exception {
    Collection<Long> res = new HashSet<>();

    String seqName = UUID.randomUUID().toString();

    for (int i = 0; i < GRID_CNT; i++) {
      Set<Long> retVal =
          compute(grid(i).cluster().forLocal()).call(new GetAndIncrementJob(seqName, RETRIES));

      for (Long l : retVal) assert !res.contains(l) : "Value already was used " + l;

      res.addAll(retVal);
    }

    assert res.size() == GRID_CNT * RETRIES;

    int gapSize = 0;

    for (long i = 0; i < GRID_CNT * RETRIES; i++) {
      if (!res.contains(i)) gapSize++;
      else gapSize = 0;

      assert gapSize <= BATCH_SIZE + 1
          : "Gap above id  " + i + " is " + gapSize + " more than batch size: " + (BATCH_SIZE + 1);
    }
  }
  @Test
  public void testResolveTransitiveDups() throws BundleException, InvalidSyntaxException {
    region(REGION_A).connectRegion(region(REGION_B), createFilter(PACKAGE_B));
    region(REGION_A).connectRegion(region(REGION_C), createFilter(PACKAGE_DUP));
    region(REGION_A).connectRegion(region(REGION_D), createFilter(PACKAGE_DUP));
    region(REGION_B).connectRegion(region(REGION_C), createFilter(PACKAGE_DUP));
    region(REGION_C).connectRegion(region(REGION_D), createFilter(PACKAGE_DUP));
    region(REGION_D).connectRegion(region(REGION_A), createFilter(PACKAGE_DUP));

    this.candidates.add(packageCapability(BUNDLE_A, PACKAGE_DUP));
    this.candidates.add(packageCapability(BUNDLE_B, PACKAGE_DUP));
    this.candidates.add(packageCapability(BUNDLE_C, PACKAGE_DUP));
    this.candidates.add(packageCapability(BUNDLE_D, PACKAGE_DUP));

    Collection<BundleCapability> testCandidates = new ArrayList<BundleCapability>(this.candidates);
    this.resolverHook.filterMatches(bundleRequirement(BUNDLE_A), testCandidates);
    assertTrue(testCandidates.contains(packageCapability(BUNDLE_A, PACKAGE_DUP)));
    assertFalse(testCandidates.contains(packageCapability(BUNDLE_B, PACKAGE_DUP)));
    assertTrue(testCandidates.contains(packageCapability(BUNDLE_C, PACKAGE_DUP)));
    assertTrue(testCandidates.contains(packageCapability(BUNDLE_D, PACKAGE_DUP)));

    testCandidates = new ArrayList<BundleCapability>(this.candidates);
    this.resolverHook.filterMatches(bundleRequirement(BUNDLE_B), testCandidates);
    assertTrue(testCandidates.contains(packageCapability(BUNDLE_A, PACKAGE_DUP)));
    assertTrue(testCandidates.contains(packageCapability(BUNDLE_B, PACKAGE_DUP)));
    assertTrue(testCandidates.contains(packageCapability(BUNDLE_C, PACKAGE_DUP)));
    assertTrue(testCandidates.contains(packageCapability(BUNDLE_D, PACKAGE_DUP)));
  }
Esempio n. 10
0
  /**
   * Tests sending 1, 2 (OOB) and 3, where they are received in the order 1, 3, 2. Message 3 should
   * not get delivered until message 4 is received (http://jira.jboss.com/jira/browse/JGRP-780)
   */
  public void testRegularAndOOBUnicasts() throws Exception {
    DISCARD discard = new DISCARD();
    ProtocolStack stack = a.getProtocolStack();
    stack.insertProtocol(discard, ProtocolStack.BELOW, UNICAST.class, UNICAST2.class);

    Address dest = b.getAddress();
    Message m1 = new Message(dest, null, 1);
    Message m2 = new Message(dest, null, 2);
    m2.setFlag(Message.OOB);
    Message m3 = new Message(dest, null, 3);

    MyReceiver receiver = new MyReceiver("C2");
    b.setReceiver(receiver);
    a.send(m1);
    discard.setDropDownUnicasts(1);
    a.send(m2);
    a.send(m3);

    Collection<Integer> list = receiver.getMsgs();
    int count = 10;
    while (list.size() < 3 && --count > 0) {
      Util.sleep(500); // time for potential retransmission
      sendStableMessages(a, b);
    }

    assert list.size() == 3 : "list is " + list;
    assert list.contains(1) && list.contains(2) && list.contains(3);
  }
  /** {@inheritDoc} */
  @Override
  public Map<K, V> peekAll(
      @Nullable Collection<? extends K> keys, @Nullable Collection<GridCachePeekMode> modes)
      throws GridException {
    if (keys == null || keys.isEmpty()) return emptyMap();

    final Collection<K> skipped = new GridLeanSet<K>();

    final Map<K, V> map =
        !modes.contains(PARTITIONED_ONLY)
            ? peekAll0(keys, modes, ctx.tm().localTxx(), skipped)
            : new GridLeanMap<K, V>(0);

    if (map.size() != keys.size() && !modes.contains(NEAR_ONLY)) {
      map.putAll(
          dht.peekAll(
              F.view(
                  keys,
                  new P1<K>() {
                    @Override
                    public boolean apply(K k) {
                      return !map.containsKey(k) && !skipped.contains(k);
                    }
                  }),
              modes));
    }

    return map;
  }
  public Collection<PsiElement> getAdditionalElementsToDelete(
      @NotNull final PsiElement element,
      @NotNull final Collection<PsiElement> allElementsToDelete,
      final boolean askUser) {
    if (element instanceof PsiField) {
      PsiField field = (PsiField) element;
      final Project project = element.getProject();
      String propertyName =
          JavaCodeStyleManager.getInstance(project)
              .variableNameToPropertyName(field.getName(), VariableKind.FIELD);

      PsiClass aClass = field.getContainingClass();
      if (aClass != null) {
        boolean isStatic = field.hasModifierProperty(PsiModifier.STATIC);
        PsiMethod[] getters =
            GetterSetterPrototypeProvider.findGetters(aClass, propertyName, isStatic);
        if (getters != null) {
          final List<PsiMethod> validGetters = new ArrayList<>(1);
          for (PsiMethod getter : getters) {
            if (!allElementsToDelete.contains(getter) && (getter != null && getter.isPhysical())) {
              validGetters.add(getter);
            }
          }
          getters =
              validGetters.isEmpty()
                  ? null
                  : validGetters.toArray(new PsiMethod[validGetters.size()]);
        }

        PsiMethod setter = PropertyUtil.findPropertySetter(aClass, propertyName, isStatic, false);
        if (allElementsToDelete.contains(setter) || setter != null && !setter.isPhysical())
          setter = null;
        if (askUser && (getters != null || setter != null)) {
          final String message =
              RefactoringMessageUtil.getGetterSetterMessage(
                  field.getName(),
                  RefactoringBundle.message("delete.title"),
                  getters != null ? getters[0] : null,
                  setter);
          if (!ApplicationManager.getApplication().isUnitTestMode()
              && Messages.showYesNoDialog(
                      project,
                      message,
                      RefactoringBundle.message("safe.delete.title"),
                      Messages.getQuestionIcon())
                  != Messages.YES) {
            getters = null;
            setter = null;
          }
        }
        List<PsiElement> elements = new ArrayList<>();
        if (setter != null) elements.add(setter);
        if (getters != null) Collections.addAll(elements, getters);
        return elements;
      }
    }
    return null;
  }
  /**
   * First positive integer that is not present in started set.
   *
   * @param started Already started indices.
   * @return First positive integer that is not present in started set.
   */
  private int nextIndex(Collection<Integer> started) {
    assert started.contains(0);

    for (int i = 1; i < 10000; i++) {
      if (!started.contains(i)) return i;
    }

    throw new IllegalStateException();
  }
 /** values collection contains all values */
 public void testDescendingValues() {
   ConcurrentNavigableMap map = dmap5();
   Collection s = map.values();
   assertEquals(5, s.size());
   assertTrue(s.contains("A"));
   assertTrue(s.contains("B"));
   assertTrue(s.contains("C"));
   assertTrue(s.contains("D"));
   assertTrue(s.contains("E"));
 }
  @SuppressWarnings("squid:S1244")
  private static String selectBestEncoding(String acceptEncodingHeader) {
    // multiple encodings are accepted; determine best one

    Collection<String> bestEncodings = new HashSet<>(3);
    double bestQ = 0.0;
    Collection<String> unacceptableEncodings = new HashSet<>(3);
    boolean willAcceptAnything = false;

    for (String token : COMMA.split(acceptEncodingHeader)) {
      ContentEncodingQ contentEncodingQ = parseContentEncodingQ(token);
      String contentEncoding = contentEncodingQ.getContentEncoding();
      double q = contentEncodingQ.getQ();
      if (ANY_ENCODING.equals(contentEncoding)) {
        willAcceptAnything = q > 0.0;
      } else if (SUPPORTED_ENCODINGS.contains(contentEncoding)) {
        if (q > 0.0) {
          // This is a header quality comparison.
          // So it is safe to suppress warning squid:S1244
          if (q == bestQ) {
            bestEncodings.add(contentEncoding);
          } else if (q > bestQ) {
            bestQ = q;
            bestEncodings.clear();
            bestEncodings.add(contentEncoding);
          }
        } else {
          unacceptableEncodings.add(contentEncoding);
        }
      }
    }

    if (bestEncodings.isEmpty()) {
      // nothing was acceptable to us
      if (willAcceptAnything) {
        if (unacceptableEncodings.isEmpty()) {
          return SUPPORTED_ENCODINGS.get(0);
        } else {
          for (String encoding : SUPPORTED_ENCODINGS) {
            if (!unacceptableEncodings.contains(encoding)) {
              return encoding;
            }
          }
        }
      }
    } else {
      for (String encoding : SUPPORTED_ENCODINGS) {
        if (bestEncodings.contains(encoding)) {
          return encoding;
        }
      }
    }

    return NO_ENCODING;
  }
Esempio n. 16
0
 public boolean testContainsAddDiff() {
   description = "membership status is not affected by adding other";
   precondition = Boolean.TRUE;
   ;
   Object e = new Object();
   boolean before = c.contains(e);
   Object a = new Object();
   c.add(a);
   boolean after = c.contains(e);
   return before == after;
 }
  @SmallTest
  @MediumTest
  @LargeTest
  public void testCollectionContains() throws JSONException {
    JSONArray array = new JSONArray();
    array.put(5);

    Collection<Integer> collection = GraphObject.Factory.createList(array, Integer.class);
    assertTrue(collection.contains(5));
    assertFalse(collection.contains(6));
  }
Esempio n. 18
0
 public void process(String projectId, Date from, Date to) {
   reset();
   Collection<VcsCommitInfo> allCommits = getCommitsForProject(projectId, from, to);
   generateTestAndTrainSets(allCommits);
   System.out.println("Processing commits...");
   int total = allCommits.size();
   int counter = 0;
   long startTime = System.currentTimeMillis();
   for (VcsCommitInfo commitInfo : allCommits) {
     counter++;
     if (counter % 100 == 0) {
       System.out.println(
           counter
               + " / "
               + total
               + " | last 100 processed in "
               + (System.currentTimeMillis() - startTime)
               + " ms");
       startTime = System.currentTimeMillis();
     }
     for (String filename : commitInfo.getAffectedFiles()) {
       if (!commitAffections.containsKey(filename)) {
         commitAffections.put(filename, new ArrayList<VcsCommitInfo>());
       }
       commitAffections.get(filename).add(commitInfo);
     }
     if (VcsCommitInfoUtils.isRelatedToBugIssue(commitInfo)) {
       for (String filename : commitInfo.getAffectedFiles()) {
         if (!bugFixCommitAffections.containsKey(filename)) {
           bugFixCommitAffections.put(filename, new ArrayList<VcsCommitInfo>());
         }
         bugFixCommitAffections.get(filename).add(commitInfo);
       }
     }
     for (PredictionModel model : myModels) {
       if (trainSet.contains(commitInfo.getCommitId())) {
         // train the model
         model.update(commitInfo, true);
       }
       if (testSet.contains(commitInfo.getCommitId())) {
         // update the model without training and get prediction data
         Map<String, List<VcsCommitInfo>> topAppearanceMapForCurrentModel =
             appearancesInTop.get(model);
         for (String fileInTop : model.getPredictionData().keySet()) {
           if (!topAppearanceMapForCurrentModel.containsKey(fileInTop)) {
             topAppearanceMapForCurrentModel.put(fileInTop, new ArrayList<VcsCommitInfo>());
           }
           topAppearanceMapForCurrentModel.get(fileInTop).add(commitInfo);
         }
       }
     }
   }
 }
 public void putAny(String key, String value) {
   // guess the type
   if (BOOLEAN_SETTINGS.contains(key)) {
     putBoolean(key, "yes".equals(value));
   } else if (INT_SETTINGS.contains(key)) {
     putInt(key, Integer.parseInt(value));
   } else if (STRING_SETTINGS.contains(key)) {
     putString(key, value);
   } else {
     System.err.println("Unknown key: " + key);
   }
 }
 // Indicates if the classLoad should be overridden for the passed className.
 // Returns true in case the class should NOT be loaded by parent classLoader.
 protected boolean shouldOverrideLoadClass(String name) {
   if (shouldOverrideLoadClassForCollectionMembers) {
     // Override classLoad if the name is in collection
     return (classNames != null) && classNames.contains(name);
   } else {
     // Directly opposite: Override classLoad if the name is NOT in collection.
     // Forced to check for java. and javax. packages here, because even if the class
     // has been loaded by parent loader we would load it again
     // (see comment in loadClass)
     return !name.startsWith("java.")
         && !name.startsWith("javax.")
         && ((classNames == null) || !classNames.contains(name));
   }
 }
Esempio n. 21
0
  /**
   * Retain in this vector only the elements contained in the given collection.
   *
   * @param c the collection to filter by
   * @return true if this vector changed
   * @throws NullPointerException if c is null
   * @since 1.2
   */
  public synchronized boolean retainAll(Collection c) {
    if (c == null) throw new NullPointerException();

    int i;
    int j;
    for (i = 0; i < elementCount; i++) if (!c.contains(elementData[i])) break;
    if (i == elementCount) return false;

    modCount++;
    for (j = i++; i < elementCount; i++)
      if (c.contains(elementData[i])) elementData[j++] = elementData[i];
    elementCount -= i - j;
    return true;
  }
 @Nullable
 private static PyGenericType getGenericType(
     @NotNull PsiElement element, @NotNull Context context) {
   if (element instanceof PyCallExpression) {
     final PyCallExpression assignedCall = (PyCallExpression) element;
     final PyExpression callee = assignedCall.getCallee();
     if (callee != null) {
       final Collection<String> calleeQNames =
           resolveToQualifiedNames(callee, context.getTypeContext());
       if (calleeQNames.contains("typing.TypeVar")) {
         final PyExpression[] arguments = assignedCall.getArguments();
         if (arguments.length > 0) {
           final PyExpression firstArgument = arguments[0];
           if (firstArgument instanceof PyStringLiteralExpression) {
             final String name = ((PyStringLiteralExpression) firstArgument).getStringValue();
             if (name != null) {
               return new PyGenericType(name, getGenericTypeBound(arguments, context));
             }
           }
         }
       }
     }
   }
   return null;
 }
 @Nullable
 private static PyType getCallableType(@NotNull PsiElement resolved, @NotNull Context context) {
   if (resolved instanceof PySubscriptionExpression) {
     final PySubscriptionExpression subscriptionExpr = (PySubscriptionExpression) resolved;
     final PyExpression operand = subscriptionExpr.getOperand();
     final Collection<String> operandNames =
         resolveToQualifiedNames(operand, context.getTypeContext());
     if (operandNames.contains("typing.Callable")) {
       final PyExpression indexExpr = subscriptionExpr.getIndexExpression();
       if (indexExpr instanceof PyTupleExpression) {
         final PyTupleExpression tupleExpr = (PyTupleExpression) indexExpr;
         final PyExpression[] elements = tupleExpr.getElements();
         if (elements.length == 2) {
           final PyExpression parametersExpr = elements[0];
           final PyExpression returnTypeExpr = elements[1];
           if (parametersExpr instanceof PyListLiteralExpression) {
             final List<PyCallableParameter> parameters = new ArrayList<>();
             final PyListLiteralExpression listExpr = (PyListLiteralExpression) parametersExpr;
             for (PyExpression argExpr : listExpr.getElements()) {
               parameters.add(new PyCallableParameterImpl(null, getType(argExpr, context)));
             }
             final PyType returnType = getType(returnTypeExpr, context);
             return new PyCallableTypeImpl(parameters, returnType);
           }
           if (isEllipsis(parametersExpr)) {
             return new PyCallableTypeImpl(null, getType(returnTypeExpr, context));
           }
         }
       }
     }
   }
   return null;
 }
Esempio n. 24
0
 public boolean retainAll(Collection<?> c) {
   List<K> toRemove = new ArrayList<K>();
   for (K key : this) {
     if (!c.contains(key)) toRemove.add(key);
   }
   return removeAll(toRemove);
 }
Esempio n. 25
0
  /**
   * This method receives a normalized list of non-dominated solutions and return the inverted one.
   * This operation is needed for minimization problem
   *
   * @param solutionList The front to invert
   * @return The inverted front
   */
  public static <S extends Solution<?>> List<S> selectNRandomDifferentSolutions(
      int numberOfSolutionsToBeReturned, List<S> solutionList) {
    if (null == solutionList) {
      throw new JMetalException("The solution list is null");
    } else if (solutionList.size() == 0) {
      throw new JMetalException("The solution list is empty");
    } else if (solutionList.size() < numberOfSolutionsToBeReturned) {
      throw new JMetalException(
          "The solution list size ("
              + solutionList.size()
              + ") is less than "
              + "the number of requested solutions ("
              + numberOfSolutionsToBeReturned
              + ")");
    }

    JMetalRandom randomGenerator = JMetalRandom.getInstance();
    List<S> resultList = new ArrayList<>(numberOfSolutionsToBeReturned);

    if (solutionList.size() == 1) {
      resultList.add(solutionList.get(0));
    } else {
      Collection<Integer> positions = new HashSet<>(numberOfSolutionsToBeReturned);
      while (positions.size() < numberOfSolutionsToBeReturned) {
        int nextPosition = randomGenerator.nextInt(0, solutionList.size() - 1);
        if (!positions.contains(nextPosition)) {
          positions.add(nextPosition);
          resultList.add(solutionList.get(nextPosition));
        }
      }
    }

    return resultList;
  }
Esempio n. 26
0
  private static void checkForUnexpectedErrors() {
    AnalyzeExhaust exhaust =
        WholeProjectAnalyzerFacade.analyzeProjectWithCacheOnAFile((JetFile) getFile());
    Collection<Diagnostic> diagnostics = exhaust.getBindingContext().getDiagnostics();

    if (diagnostics.size() != 0) {
      String[] expectedErrorStrings =
          InTextDirectivesUtils.findListWithPrefix("// ERROR:", getFile().getText());

      System.out.println(getFile().getText());

      Collection<String> expectedErrors = new HashSet<String>(Arrays.asList(expectedErrorStrings));

      StringBuilder builder = new StringBuilder();
      boolean hasErrors = false;

      for (Diagnostic diagnostic : diagnostics) {
        if (diagnostic.getSeverity() == Severity.ERROR) {
          String errorText = IdeErrorMessages.RENDERER.render(diagnostic);
          if (!expectedErrors.contains(errorText)) {
            hasErrors = true;
            builder.append("// ERROR: ").append(errorText).append("\n");
          }
        }
      }

      Assert.assertFalse(
          "There should be no unexpected errors after applying fix (Use \"// ERROR:\" directive): \n"
              + builder.toString(),
          hasErrors);
    }
  }
Esempio n. 27
0
  /** Tests https://jira.jboss.org/jira/browse/JGRP-1079 for unicast messages */
  public void testOOBUnicastMessageLoss() throws Exception {
    MyReceiver receiver = new MySleepingReceiver("C2", 1000);
    b.setReceiver(receiver);

    a.getProtocolStack().getTransport().setOOBRejectionPolicy("discard");

    final int NUM = 10;
    final Address dest = b.getAddress();
    for (int i = 1; i <= NUM; i++) {
      Message msg = new Message(dest, null, i);
      msg.setFlag(Message.OOB);
      a.send(msg);
    }

    Collection<Integer> msgs = receiver.getMsgs();

    for (int i = 0; i < 20; i++) {
      if (msgs.size() == NUM) break;
      Util.sleep(1000);
      // sendStableMessages(c1,c2); // not needed for unicasts !
    }

    assert msgs.size() == NUM
        : "expected " + NUM + " messages but got " + msgs.size() + ", msgs=" + Util.print(msgs);
    for (int i = 1; i <= NUM; i++) {
      assert msgs.contains(i);
    }
  }
Esempio n. 28
0
  /** Tests https://jira.jboss.org/jira/browse/JGRP-1079 */
  public void testOOBMessageLoss() throws Exception {
    Util.close(b); // we only need 1 channel
    MyReceiver receiver = new MySleepingReceiver("C1", 1000);
    a.setReceiver(receiver);

    TP transport = a.getProtocolStack().getTransport();
    transport.setOOBRejectionPolicy("discard");

    final int NUM = 10;

    for (int i = 1; i <= NUM; i++) {
      Message msg = new Message(null, null, i);
      msg.setFlag(Message.OOB);
      a.send(msg);
    }
    STABLE stable = (STABLE) a.getProtocolStack().findProtocol(STABLE.class);
    if (stable != null) stable.runMessageGarbageCollection();
    Collection<Integer> msgs = receiver.getMsgs();

    for (int i = 0; i < 20; i++) {
      if (msgs.size() == NUM) break;
      Util.sleep(1000);
      sendStableMessages(a, b);
    }

    System.out.println("msgs = " + Util.print(msgs));

    assert msgs.size() == NUM
        : "expected " + NUM + " messages but got " + msgs.size() + ", msgs=" + Util.print(msgs);
    for (int i = 1; i <= NUM; i++) {
      assert msgs.contains(i);
    }
  }
Esempio n. 29
0
  private static Collection<? extends File> findFiles(
      Collection<String> extensions, File directory) {
    Set<File> result = new HashSet<File>();

    File[] children = directory.listFiles();
    if (children == null) {
      return result; // No permission?
    }

    for (File child : children) {
      if (child.isDirectory()) {
        result.addAll(UtilFindFiles.findFiles(extensions, child));
      } else {

        String extension = FileUtil.getFileExtension(child);

        if (extension != null) {
          if (extensions.contains(extension)) {
            result.add(child);
          }
        }
      }
    }

    return result;
  }
  /** {@inheritDoc} */
  @Override
  public V peek(K key, @Nullable Collection<GridCachePeekMode> modes) throws GridException {
    V val = null;

    if (!modes.contains(PARTITIONED_ONLY)) {
      try {
        val = peek0(true, key, modes, ctx.tm().txx());
      } catch (GridCacheFilterFailedException ignored) {
        if (log.isDebugEnabled()) log.debug("Filter validation failed for key: " + key);

        return null;
      }
    }

    return val == null && !modes.contains(NEAR_ONLY) ? dht.peek(key, modes) : val;
  }