Ejemplo n.º 1
0
 // check inclusion between states in the input FTA
 public boolean inclusionCheck(LinkedHashSet<String> q1, LinkedHashSet<String> q2) {
   Iterator iter, qiter1, qiter2;
   String x;
   LinkedHashSet<String> q;
   boolean includes = true;
   boolean b;
   iter = qd.iterator();
   while (iter.hasNext() && includes) {
     q = (LinkedHashSet<String>) iter.next();
     qiter1 = q1.iterator();
     while (qiter1.hasNext()) {
       x = (String) qiter1.next();
       if (q.contains(x)) {
         b = false;
         qiter2 = q2.iterator();
         while (qiter2.hasNext() && !b) {
           if (q.contains((String) qiter2.next())) {
             b = true;
           }
         }
         includes = includes && b;
       }
     }
   }
   return includes;
 }
Ejemplo n.º 2
0
  private static void runUDFS(final Graph g, Integer n, LinkedHashSet pre) {
    Queue q = new LinkedList();

    Node nd;
    Integer nodeRow;
    Integer nodeNumber;
    Edge edg;
    Node nd2;
    q.add(new Integer(n.intValue()));
    while (!q.isEmpty()) {
      nodeRow = new Integer(((Integer) q.poll()).intValue());
      if (!pre.contains(nodeRow)) {
        nd = g.getNode(nodeRow.intValue());
        pre.add(nodeRow);

        for (Iterator it = nd.edges(); it.hasNext(); ) {
          edg = (Edge) it.next();
          nd2 = edg.getTargetNode();
          nodeNumber = new Integer(nd2.getRow());
          if (!pre.contains(nodeNumber)) q.add(nodeNumber);
          nd2 = edg.getSourceNode();
          nodeNumber = new Integer(nd2.getRow());
          if (!pre.contains(nodeNumber)) q.add(nodeNumber);
        }
      }
    }
    nodeRow = null;
    nodeNumber = null;
    q = null;
    edg = null;
    nd2 = null;
  }
  /**
   * Performs a depth-first, post-order traversal over a DAG.
   *
   * @param initialNodes The nodes from which to perform the traversal. Not allowed to contain
   *     {@code null}.
   * @throws CycleException if a cycle is found while performing the traversal.
   */
  @SuppressWarnings("PMD.PrematureDeclaration")
  public void traverse(Iterable<? extends T> initialNodes)
      throws CycleException, IOException, InterruptedException {
    // This corresponds to the current chain of nodes being explored. Enforcing this invariant makes
    // this data structure useful for debugging.
    Deque<Explorable> toExplore = Lists.newLinkedList();
    for (T node : initialNodes) {
      toExplore.add(new Explorable(node));
    }

    Set<T> inProgress = Sets.newHashSet();
    LinkedHashSet<T> explored = Sets.newLinkedHashSet();

    while (!toExplore.isEmpty()) {
      Explorable explorable = toExplore.peek();
      T node = explorable.node;

      // This could happen if one of the initial nodes is a dependency of the other, for example.
      if (explored.contains(node)) {
        toExplore.removeFirst();
        continue;
      }

      inProgress.add(node);

      // Find children that need to be explored to add to the stack.
      int stackSize = toExplore.size();
      for (Iterator<T> iter = explorable.children; iter.hasNext(); ) {
        T child = iter.next();
        if (inProgress.contains(child)) {
          throw createCycleException(child, toExplore);
        } else if (!explored.contains(child)) {
          toExplore.addFirst(new Explorable(child));

          // Without this break statement:
          // (1) Children will be explored in reverse order instead of the specified order.
          // (2) CycleException may contain extra nodes.
          // Comment out the break statement and run the unit test to verify this for yourself.
          break;
        }
      }

      if (stackSize == toExplore.size()) {
        // Nothing was added to toExplore, so the current node can be popped off the stack and
        // marked as explored.
        toExplore.removeFirst();
        inProgress.remove(node);
        explored.add(node);

        // Now that the internal state of this traversal has been updated, notify the observer.
        onNodeExplored(node);
      }
    }

    Preconditions.checkState(inProgress.isEmpty(), "No more nodes should be in progress.");

    onTraversalComplete(Iterables.unmodifiableIterable(explored));
  }
Ejemplo n.º 4
0
 private boolean isUnknownState(DfaValue val) {
   val = unwrap(val);
   if (val instanceof DfaVariableValue) {
     if (myUnknownVariables.contains(val)) return true;
     DfaVariableValue negatedValue = ((DfaVariableValue) val).getNegatedValue();
     if (negatedValue != null && myUnknownVariables.contains(negatedValue)) return true;
   }
   return false;
 }
Ejemplo n.º 5
0
  /** java.util.LinkedHashSet#contains(java.lang.Object) */
  public void test_containsLjava_lang_Object() {
    // Test for method boolean
    // java.util.LinkedHashSet.contains(java.lang.Object)
    assertTrue("Returned false for valid object", hs.contains(objArray[90]));
    assertTrue("Returned true for invalid Object", !hs.contains(new Object()));

    LinkedHashSet s = new LinkedHashSet();
    s.add(null);
    assertTrue("Cannot handle null", s.contains(null));
  }
Ejemplo n.º 6
0
 // check inclusion between states in the input FTA
 public boolean includes(String q1, String q2) {
   Iterator iter;
   LinkedHashSet<String> q;
   boolean includes = true;
   iter = qd.iterator();
   while (iter.hasNext() && includes) {
     q = (LinkedHashSet<String>) iter.next();
     includes = includes && (!q.contains(q1) || q.contains(q2));
   }
   return includes;
 }
Ejemplo n.º 7
0
  public void test_toArray$Ljava_lang_Object() {
    LinkedHashSet<Integer> lhs = new LinkedHashSet<Integer>();
    lhs.add(new Integer(1));
    lhs.add(new Integer(6));
    lhs.add(new Integer(7));
    lhs.add(new Integer(8));
    lhs.add(new Integer(9));
    lhs.add(new Integer(10));
    lhs.add(new Integer(11));
    lhs.add(new Integer(12));
    lhs.add(new Integer(13));

    Object[] o1 = new Object[lhs.size()];
    Object[] o2 = new Double[lhs.size()];
    lhs.toArray(o1);
    for (int i = 0; i < o1.length; i++) {
      assertTrue(lhs.contains(o1[i]));
    }

    try {
      lhs.toArray(null);
      fail("NullPointerException expected");
    } catch (NullPointerException e) {
      // expected
    }

    try {
      lhs.toArray(o2);
      fail("ArrayStoreException expected");
    } catch (ArrayStoreException e) {
      // expected
    }
  }
    // Find matching constructor, if this is an instance method, and populate
    // constructorDependencies
    private Optional<MethodHandle> getConstructor(
        Method method, Map<Set<TypeParameter>, Constructor<?>> constructors) {
      if (isStatic(method.getModifiers())) {
        return Optional.empty();
      }

      Constructor<?> constructor = constructors.get(typeParameters);
      requireNonNull(
          constructor,
          format(
              "%s is an instance method and requires a public constructor to be declared with %s type parameters",
              method.getName(), typeParameters));
      for (int i = 0; i < constructor.getParameterCount(); i++) {
        Annotation[] annotations = constructor.getParameterAnnotations()[i];
        checkArgument(
            containsMetaParameter(annotations), "Constructors may only have meta parameters");
        checkArgument(annotations.length == 1, "Meta parameters may only have a single annotation");
        Annotation annotation = annotations[0];
        if (annotation instanceof TypeParameter) {
          checkArgument(
              typeParameters.contains(annotation),
              "Injected type parameters must be declared with @TypeParameter annotation on the constructor");
        }
        constructorDependencies.add(parseDependency(annotation));
      }
      try {
        return Optional.of(lookup().unreflectConstructor(constructor));
      } catch (IllegalAccessException e) {
        throw new PrestoException(FUNCTION_IMPLEMENTATION_ERROR, e);
      }
    }
  /*
   * Overridden to provide filtering for root & children items.
   *
   * (non-Javadoc)
   *
   * @see com.vaadin.data.util.IndexedContainer#updateContainerFiltering()
   */
  @Override
  protected boolean doFilterContainer(boolean hasFilters) {
    if (!hasFilters) {
      // All filters removed
      filteredRoots = null;
      filteredChildren = null;
      filteredParent = null;

      return super.doFilterContainer(hasFilters);
    }

    // Reset data structures
    filteredRoots = new LinkedList<>();
    filteredChildren = new HashMap<>();
    filteredParent = new HashMap<>();

    if (includeParentsWhenFiltering) {
      // Filter so that parents for items that match the filter are also
      // included
      HashSet<Object> includedItems = new HashSet<>();
      for (Object rootId : roots) {
        if (filterIncludingParents(rootId, includedItems)) {
          filteredRoots.add(rootId);
          addFilteredChildrenRecursively(rootId, includedItems);
        }
      }
      // includedItemIds now contains all the item ids that should be
      // included. Filter IndexedContainer based on this
      filterOverride = includedItems;
      super.doFilterContainer(hasFilters);
      filterOverride = null;

      return true;
    } else {
      // Filter by including all items that pass the filter and make items
      // with no parent new root items

      // Filter IndexedContainer first so getItemIds return the items that
      // match
      super.doFilterContainer(hasFilters);

      LinkedHashSet<Object> filteredItemIds = new LinkedHashSet<>(getItemIds());

      for (Object itemId : filteredItemIds) {
        Object itemParent = parent.get(itemId);
        if (itemParent == null || !filteredItemIds.contains(itemParent)) {
          // Parent is not included or this was a root, in both cases
          // this should be a filtered root
          filteredRoots.add(itemId);
        } else {
          // Parent is included. Add this to the children list (create
          // it first if necessary)
          addFilteredChild(itemParent, itemId);
        }
      }

      return true;
    }
  }
Ejemplo n.º 10
0
 /** java.util.LinkedHashSet#clear() */
 public void test_clear() {
   // Test for method void java.util.LinkedHashSet.clear()
   Set orgSet = (Set) hs.clone();
   hs.clear();
   Iterator i = orgSet.iterator();
   assertEquals("Returned non-zero size after clear", 0, hs.size());
   while (i.hasNext()) assertTrue("Failed to clear set", !hs.contains(i.next()));
 }
Ejemplo n.º 11
0
 void setVariableState(DfaVariableValue dfaVar, DfaVariableState state) {
   assert !myUnknownVariables.contains(dfaVar);
   if (state.equals(myDefaultVariableStates.get(dfaVar))) {
     myVariableStates.remove(dfaVar);
   } else {
     myVariableStates.put(dfaVar, state);
   }
   myCachedHash = null;
 }
Ejemplo n.º 12
0
 /** java.util.LinkedHashSet#add(java.lang.Object) */
 public void test_addLjava_lang_Object() {
   // Test for method boolean java.util.LinkedHashSet.add(java.lang.Object)
   int size = hs.size();
   hs.add(new Integer(8));
   assertTrue("Added element already contained by set", hs.size() == size);
   hs.add(new Integer(-9));
   assertTrue("Failed to increment set size after add", hs.size() == size + 1);
   assertTrue("Failed to add element to set", hs.contains(new Integer(-9)));
 }
Ejemplo n.º 13
0
  /**
   * Returns an array containing all installed providers that satisfy the specified* selection
   * criteria, or null if no such providers have been installed. The returned providers are ordered
   * according to their <a href= "#insertProviderAt(java.security.Provider, int)">preference
   * order</a>.
   *
   * <p>The selection criteria are represented by a map. Each map entry represents a selection
   * criterion. A provider is selected iff it satisfies all selection criteria. The key for any
   * entry in such a map must be in one of the following two formats:
   *
   * <ul>
   *   <li><i>&lt;crypto_service>.&lt;algorithm_or_type></i>
   *       <p>The cryptographic service name must not contain any dots.
   *       <p>The value associated with the key must be an empty string.
   *       <p>A provider satisfies this selection criterion iff the provider implements the
   *       specified algorithm or type for the specified cryptographic service.
   *   <li><i>&lt;crypto_service>.&lt;algorithm_or_type> &lt;attribute_name></i>
   *       <p>The cryptographic service name must not contain any dots. There must be one or more
   *       space charaters between the <i>&lt;algorithm_or_type></i> and the
   *       <i>&lt;attribute_name></i>.
   *       <p>The value associated with the key must be a non-empty string. A provider satisfies
   *       this selection criterion iff the provider implements the specified algorithm or type for
   *       the specified cryptographic service and its implementation meets the constraint expressed
   *       by the specified attribute name/value pair.
   * </ul>
   *
   * <p>See Appendix A in the <a href= "../../../guide/security/CryptoSpec.html#AppA"> Java
   * Cryptogaphy Architecture API Specification &amp; Reference </a> for information about standard
   * cryptographic service names, standard algorithm names and standard attribute names.
   *
   * @param filter the criteria for selecting providers. The filter is case-insensitive.
   * @return all the installed providers that satisfy the selection criteria, or null if no such
   *     providers have been installed.
   * @throws InvalidParameterException if the filter is not in the required format
   * @throws NullPointerException if filter is null
   * @see #getProviders(java.lang.String)
   */
  public static Provider[] getProviders(Map<String, String> filter) {
    // Get all installed providers first.
    // Then only return those providers who satisfy the selection criteria.
    Provider[] allProviders = Security.getProviders();
    Set keySet = filter.keySet();
    LinkedHashSet candidates = new LinkedHashSet(5);

    // Returns all installed providers
    // if the selection criteria is null.
    if ((keySet == null) || (allProviders == null)) {
      return allProviders;
    }

    boolean firstSearch = true;

    // For each selection criterion, remove providers
    // which don't satisfy the criterion from the candidate set.
    for (Iterator ite = keySet.iterator(); ite.hasNext(); ) {
      String key = (String) ite.next();
      String value = (String) filter.get(key);

      LinkedHashSet newCandidates = getAllQualifyingCandidates(key, value, allProviders);
      if (firstSearch) {
        candidates = newCandidates;
        firstSearch = false;
      }

      if ((newCandidates != null) && !newCandidates.isEmpty()) {
        // For each provider in the candidates set, if it
        // isn't in the newCandidate set, we should remove
        // it from the candidate set.
        for (Iterator cansIte = candidates.iterator(); cansIte.hasNext(); ) {
          Provider prov = (Provider) cansIte.next();
          if (!newCandidates.contains(prov)) {
            cansIte.remove();
          }
        }
      } else {
        candidates = null;
        break;
      }
    }

    if ((candidates == null) || (candidates.isEmpty())) return null;

    Object[] candidatesArray = candidates.toArray();
    Provider[] result = new Provider[candidatesArray.length];

    for (int i = 0; i < result.length; i++) {
      result[i] = (Provider) candidatesArray[i];
    }

    return result;
  }
 private void parseArguments(Method method) {
   ImmutableSet<String> typeParameterNames =
       typeParameters.stream().map(TypeParameter::value).collect(toImmutableSet());
   for (int i = 0; i < method.getParameterCount(); i++) {
     Annotation[] annotations = method.getParameterAnnotations()[i];
     Class<?> parameterType = method.getParameterTypes()[i];
     // Skip injected parameters
     if (parameterType == ConnectorSession.class) {
       continue;
     }
     if (containsMetaParameter(annotations)) {
       checkArgument(
           annotations.length == 1, "Meta parameters may only have a single annotation");
       checkArgument(argumentTypes.isEmpty(), "Meta parameter must come before parameters");
       Annotation annotation = annotations[0];
       if (annotation instanceof TypeParameter) {
         checkArgument(
             typeParameters.contains(annotation),
             "Injected type parameters must be declared with @TypeParameter annotation on the method");
       }
       dependencies.add(parseDependency(annotation));
     } else {
       SqlType type = null;
       boolean nullableArgument = false;
       for (Annotation annotation : annotations) {
         if (annotation instanceof SqlType) {
           type = (SqlType) annotation;
         }
         if (annotation instanceof Nullable) {
           nullableArgument = true;
         }
       }
       requireNonNull(type, format("@SqlType annotation missing for argument to %s", method));
       if (typeParameterNames.contains(type.value())
           && !(parameterType == Object.class && nullableArgument)) {
         // Infer specialization on this type parameter. We don't do this for @Nullable Object
         // because it could match a type like BIGINT
         Class<?> specialization = specializedTypeParameters.get(type.value());
         Class<?> nativeParameterType = Primitives.unwrap(parameterType);
         checkArgument(
             specialization == null || specialization.equals(nativeParameterType),
             "%s has conflicting specializations %s and %s",
             type.value(),
             specialization,
             nativeParameterType);
         specializedTypeParameters.put(type.value(), nativeParameterType);
       }
       argumentNativeContainerTypes.add(parameterType);
       argumentTypes.add(type.value());
       nullableArguments.add(nullableArgument);
     }
   }
 }
Ejemplo n.º 15
0
  // This may not catch 100% of packets, but should get most of them, a small number may end up
  // being compressed by main thread
  @SuppressWarnings("unchecked")
  public void manageChunkQueue(boolean flag1) {
    List<ChunkCoordIntPair> playerChunkQueue = player.chunkCoordIntPairQueue;

    try {
      if (!playerChunkQueue.isEmpty()) {
        chunkUpdateQueue.addAll(playerChunkQueue);
        playerChunkQueue.clear();
      }
    } catch (ConcurrentModificationException e) {
      // seems to be called from a separate thread during teleports (rogue plugins?)
    }

    int chunkCompressionThreadSize = ChunkCompressionThread.getPlayerQueueSize(this.player);
    if (!chunkUpdateQueue.isEmpty()
        && (lowPriorityCount()
                + chunkCompressionThreadSize
                + MapChunkThread.getQueueLength(this.player))
            < 4) {
      ChunkCoordIntPair playerChunk = getPlayerChunk();
      Iterator<ChunkCoordIntPair> i = chunkUpdateQueue.iterator();
      ChunkCoordIntPair first = i.next();
      while (first != null && !activeChunks.contains(first)) {
        i.remove();
        if (i.hasNext()) {
          first = i.next();
        } else {
          first = null;
        }
      }
      if (first != null) {
        if (updateCounter.get() > 0) {
          int cx = playerChunk.x;
          int cz = playerChunk.z;
          boolean chunkFound = false;
          for (int c = 0; c < spiralx.length; c++) {
            ChunkCoordIntPair testChunk = new ChunkCoordIntPair(spiralx[c] + cx, spiralz[c] + cz);
            if (chunkUpdateQueue.contains(testChunk)) {
              first = testChunk;
              chunkFound = true;
              break;
            }
          }
          if (!chunkFound) {
            updateCounter.decrementAndGet();
          }
        }
        chunkUpdateQueue.remove(first);
        MapChunkThread.sendPacketMapChunk(first, this.player, this.player.world);
        sendChunkTiles(first.x, first.z, player);
      }
    }
  }
Ejemplo n.º 16
0
  /** java.util.LinkedHashSet#remove(java.lang.Object) */
  public void test_removeLjava_lang_Object() {
    // Test for method boolean
    // java.util.LinkedHashSet.remove(java.lang.Object)
    int size = hs.size();
    hs.remove(new Integer(98));
    assertTrue("Failed to remove element", !hs.contains(new Integer(98)));
    assertTrue("Failed to decrement set size", hs.size() == size - 1);

    LinkedHashSet s = new LinkedHashSet();
    s.add(null);
    assertTrue("Cannot handle null", s.remove(null));
  }
Ejemplo n.º 17
0
  private static void runDDFS(final Graph g, Integer n, LinkedHashSet nodeSet, boolean isPreOrder) {
    boolean done = false;

    Node nd;
    Node nd2;
    Integer nodeRow;
    Integer nodeNumber;

    Stack nodeStack = new Stack();

    nodeStack.add(new Integer(n.intValue()));
    while (!nodeStack.isEmpty()) {
      nodeRow = (Integer) nodeStack.peek();
      nd = g.getNode(nodeRow.intValue());
      if (!nodeSet.contains(nodeRow)) {
        if (isPreOrder) nodeSet.add(nodeRow);
        nodeSet.add(nodeRow);
      }
      done = true;
      for (Iterator it = nd.outNeighbors(); it.hasNext(); ) {
        nd2 = ((Node) it.next());
        nodeNumber = new Integer(nd2.getRow());
        if (!nodeSet.contains(nodeNumber)) {
          nodeStack.add(nodeNumber);
          done = false;
          break;
        }
      }
      if (done) {
        if (!isPreOrder) nodeSet.add(nodeRow);
        nodeStack.pop();
      }
    }
    nodeStack = null;
    nd = null;
    nd2 = null;
    nodeRow = null;
    nodeNumber = null;
  }
Ejemplo n.º 18
0
  public ArrayList<String> IPTrack(
      String ipaddr, boolean IPdisp, boolean recursive, boolean override) {
    ArrayList<String> output = new ArrayList<String>();

    PreparedStatement ps = null;
    ResultSet rs = null;
    try {
      ps =
          conn.prepareStatement(
              "SELECT `accountname` "
                  + "FROM `"
                  + table
                  + "` "
                  + "WHERE `ip` = ? "
                  + "ORDER BY `time` DESC");
      ps.setString(1, ipaddr);
      rs = ps.executeQuery();

      LinkedHashSet<String> names = new LinkedHashSet<String>();
      while (rs.next()) {
        if ((!plugin.untraceable.contains(rs.getString("accountname"))) || (override))
          names.add(rs.getString("accountname") + ((IPdisp) ? " (" + ipaddr + ")" : ""));
      }
      if (recursive) { // OH GOD OH GOD OH GOD
        LinkedHashSet<String> names_spent = new LinkedHashSet<String>();
        java.util.Iterator<String> names_itr = names.iterator();
        while (names_itr.hasNext()) {

          String thisName = names_itr.next();
          if (names_spent.contains(thisName)) continue;

          names_spent.add(thisName);
          if (names.addAll(
              PlayerTrack(
                  ((thisName.indexOf(" ") != -1)
                      ? thisName.substring(0, thisName.indexOf(" "))
                      : thisName),
                  IPdisp,
                  false,
                  override,
                  false,
                  false))) names_itr = names.iterator();
        }
      }
      output.addAll(names);
    } catch (SQLException ex) {
      PlayerTracker.log.log(Level.SEVERE, "[P-Tracker] Couldn't execute MySQL statement: ", ex);
    }

    return output;
  }
Ejemplo n.º 19
0
  public void addProcedures(final Iterable<ProcedureInfo> procedures) {
    // check for duplicates and existings
    final HashSet<ProcedureInfo> newProcs = new HashSet<ProcedureInfo>();
    for (final ProcedureInfo procedure : procedures) {
      assert (newProcs.contains(procedure) == false);
      assert (m_procedures.contains(procedure) == false);
      newProcs.add(procedure);
    }

    // add the procs
    for (final ProcedureInfo procedure : procedures) {
      m_procedures.add(procedure);
    }
  }
Ejemplo n.º 20
0
  /**
   * Adds a given CustomGraphicLayer, <EM>in draw order</EM>, to this DNodeView in a thread-safe
   * way. Each CustomGraphicLayer will be drawn in the order is was added. So, if you care about
   * draw order (as for overlapping graphics), make sure you add them in the order you desire. Note
   * that since CustomGraphicLayers may be added by multiple apps, your additions may be interleaved
   * with others.
   *
   * <p>A CustomGraphicLayer can only be associated with a DNodeView once. If you wish to have a
   * custom graphic, with the same paint and shape information, occur in multiple places in the draw
   * order, simply create a new CustomGraphicLayer and add it.
   *
   * @since Cytoscape 2.6
   * @throws IllegalArgumentException if shape or paint are null.
   * @return true if the CustomGraphicLayer was added to this DNodeView. false if this DNodeView
   *     already contained this CustomGraphicLayer.
   * @see org.cytoscape.view.presentation.customgraphics.CustomGraphicLayer
   */
  public boolean addCustomGraphic(final CustomGraphicLayer cg) {
    boolean retVal = false;
    synchronized (CG_LOCK) {
      // Lazy instantiation
      if (orderedCustomGraphicLayers == null) {
        orderedCustomGraphicLayers = new LinkedHashSet<CustomGraphicLayer>();
        graphicsPositions = new HashMap<CustomGraphicLayer, ObjectPosition>();
      }

      if (orderedCustomGraphicLayers.contains(cg)) retVal = false;
      else retVal = orderedCustomGraphicLayers.add(cg);
    }
    ensureContentChanged();
    return retVal;
  }
Ejemplo n.º 21
0
  /** java.util.LinkedHashSet#LinkedHashSet(java.util.Collection) */
  public void test_ConstructorLjava_util_Collection() {
    // Test for method java.util.LinkedHashSet(java.util.Collection)
    LinkedHashSet hs2 = new LinkedHashSet(Arrays.asList(objArray));
    for (int counter = 0; counter < objArray.length; counter++)
      assertTrue("LinkedHashSet does not contain correct elements", hs.contains(objArray[counter]));
    assertTrue(
        "LinkedHashSet created from collection incorrect size", hs2.size() == objArray.length);

    try {
      new LinkedHashSet(null);
      fail("NullPointerException expected");
    } catch (NullPointerException e) {
      // expected
    }
  }
  private boolean isGenericCollection(ClassDescriptor operandClass) {
    String dottedClassName = operandClass.getDottedClassName();

    if (baseGenericTypes.contains(dottedClassName)) return true;

    String found = null;
    for (String c : baseGenericTypes) {
      if (Subtypes2.instanceOf(operandClass, c)) {
        found = c;
        break;
      }
    }
    if (found == null) return false;
    if (dottedClassName.startsWith("java.util.")
        || dottedClassName.startsWith("com.google.common.collect.")) return true;
    try {
      XClass xclass = Global.getAnalysisCache().getClassAnalysis(XClass.class, operandClass);

      String sig = xclass.getSourceSignature();
      if (sig == null) return false;

      String typeParameter = null;
      List<String> split = GenericUtilities.split(sig, true);
      if (sig.charAt(0) == '<') {
        int end = sig.indexOf(':');
        if (end > 0) typeParameter = sig.substring(1, end);
      }
      if (DEBUG) System.out.println(dottedClassName + " " + typeParameter + " " + split);
      for (String s : split) {
        int i = s.indexOf('<');
        if (i < 0) continue;
        if (s.charAt(0) != 'L') throw new IllegalStateException("unexpected non signature: " + s);
        ClassDescriptor c = DescriptorFactory.createClassDescriptor(s.substring(1, i));
        String superTypeParameter = s.substring(i + 1);
        if (isGenericCollection(c)
            && (typeParameter == null || superTypeParameter.startsWith("T" + typeParameter))) {
          if (DEBUG) System.out.println(operandClass + " is a subtype of " + s);
          return true;
        }
      }
      if (DEBUG) System.out.println("Not a subtype");

    } catch (CheckedAnalysisException e1) {
      AnalysisContext.logError(
          "Error checking for weird generic parameterization of " + operandClass, e1);
    }
    return false;
  }
Ejemplo n.º 23
0
 private static LinkedHashSet<String> extractMails(List<URL> urls) {
   LinkedHashSet<String> mails = new LinkedHashSet<String>();
   Pattern p =
       Pattern.compile(
           "[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})",
           Pattern.DOTALL);
   Iterator<URL> iterator = urls.iterator();
   while (iterator.hasNext()) {
     Matcher m = p.matcher(fetchContent(iterator.next()));
     if (m.find() && !mails.contains(m.group(0))) {
       mails.add(m.group(0));
       System.out.println(m.group(0));
     }
   }
   return mails;
 }
Ejemplo n.º 24
0
  /**
   * Add a schema based on a URL.
   *
   * @param schemaURL Schema file URL
   */
  public void addSchema(String schemaURL) {
    try {
      schemaURL = URLDecoder.decode(schemaURL, "UTF-8");
    } catch (final UnsupportedEncodingException e) {
      e.printStackTrace();
      System.exit(-1);
    }
    assert (m_schemas.contains(schemaURL) == false);
    final File schemaFile = new File(schemaURL);
    assert (schemaFile != null);
    assert (schemaFile.isDirectory() == false);
    // this check below fails in some valid cases (like when the file is in a jar)
    // assert schemaFile.canRead()
    //    : "can't read file: " + schemaPath;

    m_schemas.add(schemaURL);
  }
 private static void ensureItemAdded(
     List<LookupElement> items,
     LinkedHashSet<LookupElement> model,
     Iterator<LookupElement> byRelevance,
     @Nullable final LookupElement item) {
   if (item != null && ContainerUtil.indexOfIdentity(items, item) >= 0 && !model.contains(item)) {
     addSomeItems(
         model,
         byRelevance,
         new Condition<LookupElement>() {
           @Override
           public boolean value(LookupElement lastAdded) {
             return lastAdded == item;
           }
         });
   }
 }
Ejemplo n.º 26
0
  public void test_toArray() {
    LinkedHashSet<Integer> lhs = new LinkedHashSet<Integer>();
    lhs.add(new Integer(1));
    lhs.add(new Integer(6));
    lhs.add(new Integer(7));
    lhs.add(new Integer(8));
    lhs.add(new Integer(9));
    lhs.add(new Integer(10));
    lhs.add(new Integer(11));
    lhs.add(new Integer(12));
    lhs.add(new Integer(13));

    Object[] o = lhs.toArray();
    for (int i = 0; i < o.length; i++) {
      assertTrue(lhs.contains(o[i]));
    }
    assertEquals(lhs.size(), o.length);
  }
Ejemplo n.º 27
0
 @NotNull
 @Override
 public List<Instruction> getReversedInstructions() {
   LinkedHashSet<Instruction> traversedInstructions = Sets.newLinkedHashSet();
   PseudocodeTraverserKt.traverseFollowingInstructions(
       sinkInstruction, traversedInstructions, BACKWARD, null);
   if (traversedInstructions.size() < instructions.size()) {
     List<Instruction> simplyReversedInstructions = Lists.newArrayList(instructions);
     Collections.reverse(simplyReversedInstructions);
     for (Instruction instruction : simplyReversedInstructions) {
       if (!traversedInstructions.contains(instruction)) {
         PseudocodeTraverserKt.traverseFollowingInstructions(
             instruction, traversedInstructions, BACKWARD, null);
       }
     }
   }
   return Lists.newArrayList(traversedInstructions);
 }
Ejemplo n.º 28
0
  private static String resolveVariableReplacement(
      String value, Props props, LinkedHashSet<String> visitedVariables) {
    StringBuffer buffer = new StringBuffer();
    int startIndex = 0;

    Matcher matcher = VARIABLE_REPLACEMENT_PATTERN.matcher(value);
    while (matcher.find(startIndex)) {
      if (startIndex < matcher.start()) {
        // Copy everything up front to the buffer
        buffer.append(value.substring(startIndex, matcher.start()));
      }

      String subVariable = matcher.group(1);
      // Detected a cycle
      if (visitedVariables.contains(subVariable)) {
        throw new IllegalArgumentException(
            String.format(
                "Circular variable substitution found: [%s] -> [%s]",
                StringUtils.join(visitedVariables, "->"), subVariable));
      } else {
        // Add substitute variable and recurse.
        String replacement = props.get(subVariable);
        visitedVariables.add(subVariable);

        if (replacement == null) {
          throw new UndefinedPropertyException(
              String.format(
                  "Could not find variable substitution for variable(s) [%s]",
                  StringUtils.join(visitedVariables, "->")));
        }

        buffer.append(resolveVariableReplacement(replacement, props, visitedVariables));
        visitedVariables.remove(subVariable);
      }

      startIndex = matcher.end();
    }

    if (startIndex < value.length()) {
      buffer.append(value.substring(startIndex));
    }

    return buffer.toString();
  }
Ejemplo n.º 29
0
  /** java.util.LinkedHashSet#iterator() */
  public void test_iterator() {
    // Test for method java.util.Iterator java.util.LinkedHashSet.iterator()
    Iterator i = hs.iterator();
    int x = 0;
    int j;
    for (j = 0; i.hasNext(); j++) {
      Object oo = i.next();
      if (oo != null) {
        Integer ii = (Integer) oo;
        assertTrue("Incorrect element found", ii.intValue() == j);
      } else {
        assertTrue("Cannot find null", hs.contains(oo));
      }
      ++x;
    }
    assertTrue("Returned iteration of incorrect size", hs.size() == x);

    LinkedHashSet s = new LinkedHashSet();
    s.add(null);
    assertNull("Cannot handle null", s.iterator().next());
  }
  private static LinkedHashSet<String> readSnpOrderFile(String file1) {
    LinkedHashSet<String> snpOrdering = new LinkedHashSet<String>();
    try {
      java.io.BufferedReader in =
          new java.io.BufferedReader(new java.io.FileReader(new File(file1)));
      String str;
      int i = 0;
      while ((str = in.readLine()) != null) {
        if (!snpOrdering.contains((str))) {
          snpOrdering.add(str);
        } else {
          System.out.println("\tDuplicate entry: " + str);
        }
      }

      in.close();

    } catch (IOException e) {
      System.out.println(e.getMessage());
      System.exit(-1);
    }
    return (snpOrdering);
  }