Esempio n. 1
0
  @Override
  public void doFilter(
      ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
      throws IOException, ServletException {
    HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
    String path = httpRequest.getServletPath();
    HasRolePrincipal principal = getPrincipal(httpRequest);
    PrincipalRequestWrapper requestWrapper = new PrincipalRequestWrapper(httpRequest, principal);

    if (securityResources.containsKey(path)) {
      if (principal.isNull()) {
        httpRequest.getRequestDispatcher("/login").forward(requestWrapper, servletResponse);
        return;
      }

      Set<String> roles = securityResources.get(path);
      if (Sets.intersection(roles, principal.getRoles()).isEmpty()) {
        ((HttpServletResponse) servletResponse).setStatus(HttpServletResponse.SC_FORBIDDEN);
        servletResponse.setCharacterEncoding("UTF-8");
        requestWrapper.getRequestDispatcher("/403.jsp").include(requestWrapper, servletResponse);
        return;
      }
    }

    filterChain.doFilter(requestWrapper, servletResponse);
  }
Esempio n. 2
0
 /**
  * Returns a list of saved queries
  *
  * @param criteria a multivalued map that has the filter criteria
  * @param start Displacement from the start of the search result
  * @param count Count of number of records required
  * @return list of saved queries
  * @throws LensException
  */
 public ListResponse getList(MultivaluedMap<String, String> criteria, long start, long count)
     throws LensException {
   final StringBuilder selectQueryBuilder =
       new StringBuilder("select * from " + SAVED_QUERY_TABLE_NAME);
   final Set<String> availableFilterKeys = FILTER_KEYS.keySet();
   final Sets.SetView<String> intersection =
       Sets.intersection(availableFilterKeys, criteria.keySet());
   if (intersection.size() > 0) {
     final StringBuilder whereClauseBuilder = new StringBuilder(" where ");
     final List<String> predicates = Lists.newArrayList();
     for (String colName : intersection) {
       predicates.add(
           FILTER_KEYS.get(colName).resolveFilterExpression(colName, criteria.getFirst(colName)));
     }
     Joiner.on(" and ").skipNulls().appendTo(whereClauseBuilder, predicates);
     selectQueryBuilder.append(whereClauseBuilder.toString());
   }
   final String listCountQuery =
       "select count(*) as "
           + VALUE_ALIAS
           + " from ("
           + selectQueryBuilder.toString()
           + ") tmp_table";
   selectQueryBuilder.append(" limit ").append(start).append(", ").append(count);
   final String listQuery = selectQueryBuilder.toString();
   try {
     return new ListResponse(
         start,
         runner.query(listCountQuery, new SingleValuedResultHandler()),
         runner.query(listQuery, new SavedQueryResultSetHandler()));
   } catch (SQLException e) {
     throw new LensException("List query failed!", e);
   }
 }
  @Override
  public Expression visitUnion(UnionNode node, Void context) {
    Expression firstUnderlyingPredicate = node.getSources().get(0).accept(this, context);
    // Rewrite in terms of output symbols
    Expression firstOutputPredicate =
        ExpressionTreeRewriter.rewriteWith(
            new ExpressionSymbolInliner(node.outputSymbolMap(0)), firstUnderlyingPredicate);

    Set<Expression> conjuncts = ImmutableSet.copyOf(extractConjuncts(firstOutputPredicate));

    // Find the intersection of all predicates
    for (int i = 1; i < node.getSources().size(); i++) {
      Expression underlyingPredicate = node.getSources().get(i).accept(this, context);
      // Rewrite in terms of output symbols
      Expression outputPredicate =
          ExpressionTreeRewriter.rewriteWith(
              new ExpressionSymbolInliner(node.outputSymbolMap(i)), underlyingPredicate);

      // TODO: use a more precise way to determine overlapping conjuncts (e.g. commutative
      // predicates)
      conjuncts =
          Sets.intersection(conjuncts, ImmutableSet.copyOf(extractConjuncts(outputPredicate)));
    }

    return combineConjuncts(conjuncts);
  }
    /**
     * @return Pair of dep-file rule key and the members of possibleDepFileSourcePaths that actually
     *     appeared in the dep file
     * @throws IOException
     */
    public Optional<Pair<RuleKey, ImmutableSet<SourcePath>>> build(
        Optional<ImmutableSet<SourcePath>> possibleDepFileSourcePaths) throws IOException {
      ImmutableSet<SourcePath> inputs = builder.getInputsSoFar();

      ImmutableSet<SourcePath> depFileInputs = inputs;

      if (possibleDepFileSourcePaths.isPresent()) {
        // possibleDepFileSourcePaths is an ImmutableSortedSet which implements contains() via
        // binary search rather than via hashing. Thus taking the intersection/difference
        // is O(n*log(n)). Here, we make a hash-based copy of the set, so that intersection
        // will be reduced to O(N).
        ImmutableSet<SourcePath> possibleDepFileSourcePathsUnsorted =
            ImmutableSet.copyOf(possibleDepFileSourcePaths.get());
        Sets.SetView<SourcePath> nonDepFileInputs =
            Sets.difference(inputs, possibleDepFileSourcePathsUnsorted);

        builder.addToRuleKey(nonDepFileInputs);

        depFileInputs =
            ImmutableSet.copyOf(Sets.intersection(inputs, possibleDepFileSourcePathsUnsorted));
      }

      Optional<RuleKey> ruleKey = builder.build();
      if (ruleKey.isPresent()) {
        return Optional.of(new Pair<>(ruleKey.get(), depFileInputs));
      } else {
        return Optional.empty();
      }
    }
Esempio n. 5
0
  private static void mergeConfigMaps(
      final Map<String, String> source, final HashMap<String, String> destination) {
    checkNotNull(source, "source");
    checkNotNull(destination, "destination");

    if (source.isEmpty()) {
      return;
    }

    final Sets.SetView<String> sharedKeys =
        Sets.intersection(source.keySet(), destination.keySet());
    final Sets.SetView<String> newKeys = Sets.difference(source.keySet(), destination.keySet());

    // skip empty values in the source map
    // if they are already in the destination in order to
    // prevent overwrites of populated keys with empty ones
    sharedKeys
        .stream()
        .filter(key -> !source.get(key).trim().isEmpty() && !key.startsWith("#"))
        .forEach(key -> destination.put(key, source.get(key)));

    // Add new keys regardless of whether or not they're empty
    newKeys
        .stream()
        .filter(key -> !key.startsWith("#"))
        .forEach(key -> destination.put(key, source.get(key).trim()));
  }
  private void updateGeneratedViews(
      AbstractBuild<?, ?> build, BuildListener listener, Set<GeneratedView> freshViews)
      throws IOException {
    Set<GeneratedView> generatedViews =
        extractGeneratedObjects(build.getProject(), GeneratedViewsAction.class);
    Set<GeneratedView> added = Sets.difference(freshViews, generatedViews);
    Set<GeneratedView> existing = Sets.intersection(generatedViews, freshViews);
    Set<GeneratedView> removed = Sets.difference(generatedViews, freshViews);

    logItems(listener, "Adding views", added);
    logItems(listener, "Existing views", existing);
    logItems(listener, "Removing views", removed);

    // Delete views
    if (removedViewAction == RemovedViewAction.DELETE) {
      for (GeneratedView removedView : removed) {
        String viewName = removedView.getName();
        ItemGroup parent = getLookupStrategy().getParent(build.getProject(), viewName);
        if (parent instanceof ViewGroup) {
          View view = ((ViewGroup) parent).getView(FilenameUtils.getName(viewName));
          if (view != null) {
            ((ViewGroup) parent).deleteView(view);
          }
        } else if (parent == null) {
          LOGGER.log(Level.FINE, "Parent ViewGroup seems to have been already deleted");
        } else {
          LOGGER.log(Level.WARNING, format("Could not delete view within %s", parent.getClass()));
        }
      }
    }
  }
  @Test
  public void whenCalculatingSetIntersection_thenCorrect() {
    final Set<Character> first = ImmutableSet.of('a', 'b', 'c');
    final Set<Character> second = ImmutableSet.of('b', 'c', 'd');

    final Set<Character> intersection = Sets.intersection(first, second);
    assertThat(intersection, containsInAnyOrder('b', 'c'));
  }
  private List<Class<? extends Job>> getJobClasses(Class annotation) {
    Set<Class<? extends Job>> jobs =
        (Set<Class<? extends Job>>) reflections.getSubTypesOf(Job.class);
    Set<Class<?>> annotatedClasses = reflections.getTypesAnnotatedWith(annotation);

    return Sets.intersection(new HashSet<Class<? extends Job>>(jobs), annotatedClasses)
        .immutableCopy()
        .asList();
  }
Esempio n. 9
0
  @Override
  public Iterable<T> getIntersectingElements(long start, long end) {
    Iterable<T> matchStarts =
        Iterables.concat(fStartTimesIndex.asMap().headMap(end, true).values());
    Iterable<T> matchEnds = Iterables.concat(fEndTimesIndex.asMap().tailMap(start, true).values());

    return checkNotNull(
        Sets.intersection(Sets.newHashSet(matchStarts), Sets.newHashSet(matchEnds)));
  }
 @Override
 public void checkFreeSeats(EventTimetable eventTimetable, Set<Integer> seats) {
   for (Map<EventTimetable, Set<Integer>> eventsToPlaces : bookingStorage.values()) {
     Set<Integer> bookedPlaces = eventsToPlaces.get(eventTimetable);
     if (!Sets.intersection(seats, bookedPlaces).isEmpty()) {
       throw new RuntimeException("Seats are busy");
     }
   }
 }
Esempio n. 11
0
  /**
   * Modifies the {@code scope} of a library dependency to {@code "PROVIDED"}, where appropriate.
   *
   * <p>If an {@code android_binary()} rule uses the {@code no_dx} argument, then the jars in the
   * libraries that should not be dex'ed must be included with {@code scope="PROVIDED"} in IntelliJ.
   *
   * <p>The problem is that if a library is included by two android_binary rules that each need it
   * in a different way (i.e., for one it should be {@code scope="COMPILE"} and another it should be
   * {@code scope="PROVIDED"}), then it must be tagged as {@code scope="PROVIDED"} in all dependent
   * modules and then added as {@code scope="COMPILE"} in the .iml file that corresponds to the
   * android_binary that <em>does not</em> list the library in its {@code no_dx} list.
   */
  @VisibleForTesting
  static void markNoDxJarsAsProvided(
      List<Module> modules, Set<String> noDxJars, DependencyGraph dependencyGraph) {
    Map<String, String> intelliJLibraryNameToJarPath = Maps.newHashMap();
    for (String jarPath : noDxJars) {
      String libraryName = getIntellijNameForBinaryJar(jarPath);
      intelliJLibraryNameToJarPath.put(libraryName, jarPath);
    }

    for (Module module : modules) {
      // For an android_binary() rule, create a set of paths to JAR files (or directories) that
      // must be dex'ed. If a JAR file that is in the no_dx list for some android_binary rule, but
      // is in this set for this android_binary rule, then it should be scope="COMPILE" rather than
      // scope="PROVIDED".
      Set<String> classpathEntriesToDex;
      if (module.srcRule instanceof AndroidBinaryRule) {
        AndroidBinaryRule androidBinaryRule = (AndroidBinaryRule) module.srcRule;
        AndroidDexTransitiveDependencies dexTransitiveDependencies =
            androidBinaryRule.findDexTransitiveDependencies(dependencyGraph);
        classpathEntriesToDex =
            Sets.newHashSet(
                Sets.intersection(noDxJars, dexTransitiveDependencies.classpathEntriesToDex));
      } else {
        classpathEntriesToDex = ImmutableSet.of();
      }

      // Inspect all of the library dependencies. If the corresponding JAR file is in the set of
      // noDxJars, then either change its scope to "COMPILE" or "PROVIDED", as appropriate.
      for (DependentModule dependentModule : module.dependencies) {
        if (!dependentModule.isLibrary()) {
          continue;
        }

        // This is the IntelliJ name for the library that corresponds to the PrebuiltJarRule.
        String libraryName = dependentModule.getLibraryName();

        String jarPath = intelliJLibraryNameToJarPath.get(libraryName);
        if (jarPath != null) {
          if (classpathEntriesToDex.contains(jarPath)) {
            dependentModule.scope = null;
            classpathEntriesToDex.remove(jarPath);
          } else {
            dependentModule.scope = "PROVIDED";
          }
        }
      }

      // Make sure that every classpath entry that is also in noDxJars is added with scope="COMPILE"
      // if it has not already been added to the module.
      for (String entry : classpathEntriesToDex) {
        String libraryName = getIntellijNameForBinaryJar(entry);
        DependentModule dependency = DependentModule.newLibrary(null, libraryName);
        module.dependencies.add(dependency);
      }
    }
  }
Esempio n. 12
0
    public OwnersReport updatedWith(OwnersReport other) {
      SetMultimap<TargetNode<?>, Path> updatedOwners = TreeMultimap.create(owners);
      updatedOwners.putAll(other.owners);

      return new OwnersReport(
          updatedOwners,
          Sets.intersection(inputsWithNoOwners, other.inputsWithNoOwners),
          Sets.union(nonExistentInputs, other.nonExistentInputs),
          Sets.union(nonFileInputs, other.nonFileInputs));
    }
Esempio n. 13
0
 public ClaimSet build() {
   Map<String, String> claimsMap = claims.build();
   checkState(
       Sets.intersection(claimsMap.keySet(), requiredClaims).size() == requiredClaims.size(),
       "not all required claims were present");
   if (expirationTime == 0) {
     expirationTime = emissionTime + 3600;
   }
   return new ClaimSet(claimsMap, emissionTime, expirationTime);
 }
Esempio n. 14
0
 /**
  * If {@code node1} is equal to {@code node2}, a {@code Set} instance is returned, calculating the
  * set of self-loop edges. Otherwise, this method returns the intersection of these two sets,
  * using {@code Sets.intersection}:
  *
  * <ol>
  *   <li>{@code node1}'s incident edges.
  *   <li>{@code node2}'s incident edges.
  * </ol>
  *
  * The first argument passed to {@code Sets.intersection} is the smaller of the two sets.
  *
  * @see Sets#intersection
  */
 @Override
 public Set<E> edgesConnecting(Object node1, Object node2) {
   checkNotNull(node1, "node1");
   checkNotNull(node2, "node2");
   Set<E> incidentEdgesN1 = incidentEdges(node1);
   if (node1.equals(node2)) {
     Set<E> returnSet = Sets.newLinkedHashSet();
     for (E edge : incidentEdgesN1) {
       // An edge is a self-loop iff it has exactly one incident node.
       if (edgeToIncidentNodes.get(edge).size() == 1) {
         returnSet.add(edge);
       }
     }
     return Collections.unmodifiableSet(returnSet);
   }
   Set<E> incidentEdgesN2 = incidentEdges(node2);
   return incidentEdgesN1.size() <= incidentEdgesN2.size()
       ? Sets.intersection(incidentEdgesN1, incidentEdgesN2).immutableCopy()
       : Sets.intersection(incidentEdgesN2, incidentEdgesN1).immutableCopy();
 }
Esempio n. 15
0
 static SkylarkClassObject concat(SkylarkClassObject lval, SkylarkClassObject rval, Location loc)
     throws EvalException {
   SetView<String> commonFields = Sets.intersection(lval.values.keySet(), rval.values.keySet());
   if (!commonFields.isEmpty()) {
     throw new EvalException(
         loc,
         "Cannot concat structs with common field(s): " + Joiner.on(",").join(commonFields));
   }
   return new SkylarkClassObject(
       ImmutableMap.<String, Object>builder().putAll(lval.values).putAll(rval.values).build(),
       loc);
 }
Esempio n. 16
0
  private void updateGeneratedConfigFiles(
      AbstractBuild<?, ?> build,
      BuildListener listener,
      Set<GeneratedConfigFile> freshConfigFiles) {
    Set<GeneratedConfigFile> generatedConfigFiles =
        extractGeneratedObjects(build.getProject(), GeneratedConfigFilesAction.class);
    Set<GeneratedConfigFile> added = Sets.difference(freshConfigFiles, generatedConfigFiles);
    Set<GeneratedConfigFile> existing = Sets.intersection(generatedConfigFiles, freshConfigFiles);
    Set<GeneratedConfigFile> removed = Sets.difference(generatedConfigFiles, freshConfigFiles);

    logItems(listener, "Adding config files", added);
    logItems(listener, "Existing config files", existing);
    logItems(listener, "Removing config files", removed);
  }
Esempio n. 17
0
  private void runCallables(Set<Target> unfinished) {
    Set<PipelineCallable<?>> oldCallables = activePipelineCallables;
    activePipelineCallables = Sets.newHashSet();
    List<PipelineCallable<?>> callablesToRun = Lists.newArrayList();
    List<PipelineCallable<?>> failedCallables = Lists.newArrayList();
    for (PipelineCallable<?> pipelineCallable : oldCallables) {
      if (Sets.intersection(allPipelineCallables.get(pipelineCallable), unfinished).isEmpty()) {
        if (pipelineCallable.runSingleThreaded()) {
          try {
            if (pipelineCallable.call() != PipelineCallable.Status.SUCCESS) {
              failedCallables.add(pipelineCallable);
            }
          } catch (Throwable t) {
            pipelineCallable.setMessage(t.getLocalizedMessage());
            failedCallables.add(pipelineCallable);
          }
        } else {
          callablesToRun.add(pipelineCallable);
        }
      } else {
        // Still need to run this one
        activePipelineCallables.add(pipelineCallable);
      }
    }

    ListeningExecutorService es = MoreExecutors.listeningDecorator(Executors.newCachedThreadPool());
    try {
      List<Future<PipelineCallable.Status>> res = es.invokeAll(callablesToRun);
      for (int i = 0; i < res.size(); i++) {
        if (res.get(i).get() != PipelineCallable.Status.SUCCESS) {
          failedCallables.add((PipelineCallable) callablesToRun.get(i));
        }
      }
    } catch (Throwable t) {
      t.printStackTrace();
      failedCallables.addAll((List) callablesToRun);
    } finally {
      es.shutdownNow();
    }

    if (!failedCallables.isEmpty()) {
      LOG.error("{} callable failure(s) occurred:", failedCallables.size());
      for (PipelineCallable<?> c : failedCallables) {
        LOG.error("{} : {}", c.getName(), c.getMessage());
      }
      status.set(Status.FAILED);
      set(PipelineResult.EMPTY);
      doneSignal.countDown();
    }
  }
Esempio n. 18
0
  @Override
  public Iterable<T> getIntersectingElements(long position) {
    /*
     * The intervals intersecting 't' are those whose 1) start time is
     * *lower* than 't' AND 2) end time is *higher* than 't'.
     */
    Iterable<T> matchStarts =
        Iterables.concat(fStartTimesIndex.asMap().headMap(position, true).values());
    Iterable<T> matchEnds =
        Iterables.concat(fEndTimesIndex.asMap().tailMap(position, true).values());

    return checkNotNull(
        Sets.intersection(Sets.newHashSet(matchStarts), Sets.newHashSet(matchEnds)));
  }
Esempio n. 19
0
  private <A extends Arg> BuildRule getFlavoredBinaryRule(
      TargetGraph targetGraph,
      final BuildRuleParams params,
      final BuildRuleResolver resolver,
      A args) {
    // Cxx targets must have one Platform Flavor set otherwise nothing gets compiled.
    ImmutableSet<Flavor> flavors =
        params
            .getBuildTarget()
            .withoutFlavors(ImmutableSet.of(ReactNativeFlavors.DO_NOT_BUNDLE))
            .getFlavors();
    if (!cxxPlatformFlavorDomain.containsAnyOf(flavors)) {
      flavors =
          new ImmutableSet.Builder<Flavor>()
              .addAll(flavors)
              .add(defaultCxxPlatform.getFlavor())
              .build();
    }

    final TargetNode<?> binaryTargetNode = Preconditions.checkNotNull(targetGraph.get(args.binary));
    // If the binary target of the AppleBundle is an AppleLibrary then the build flavor
    // must be specified.
    if (binaryTargetNode.getDescription() instanceof AppleLibraryDescription
        && (Sets.intersection(
                    SUPPORTED_LIBRARY_FLAVORS, binaryTargetNode.getBuildTarget().getFlavors())
                .size()
            != 1)) {
      throw new HumanReadableException(
          "AppleExtension bundle [%s] must have exactly one of these flavors: [%s].",
          binaryTargetNode.getBuildTarget().toString(),
          Joiner.on(", ").join(SUPPORTED_LIBRARY_FLAVORS));
    }

    BuildRuleParams binaryRuleParams =
        new BuildRuleParams(
            args.binary,
            Suppliers.ofInstance(
                BuildRules.toBuildRulesFor(
                    params.getBuildTarget(), resolver, binaryTargetNode.getDeclaredDeps())),
            Suppliers.ofInstance(
                BuildRules.toBuildRulesFor(
                    params.getBuildTarget(), resolver, binaryTargetNode.getExtraDeps())),
            params.getProjectFilesystem(),
            params.getCellRoots(),
            params.getRuleKeyBuilderFactory());

    return CxxDescriptionEnhancer.requireBuildRule(
        targetGraph, binaryRuleParams, resolver, flavors.toArray(new Flavor[0]));
  }
Esempio n. 20
0
  private void updateGeneratedUserContents(
      AbstractBuild<?, ?> build,
      BuildListener listener,
      Set<GeneratedUserContent> freshUserContents) {
    Set<GeneratedUserContent> generatedUserContents =
        extractGeneratedObjects(build.getProject(), GeneratedUserContentsAction.class);
    Set<GeneratedUserContent> added = Sets.difference(freshUserContents, generatedUserContents);
    Set<GeneratedUserContent> existing =
        Sets.intersection(generatedUserContents, freshUserContents);
    Set<GeneratedUserContent> removed = Sets.difference(generatedUserContents, freshUserContents);

    logItems(listener, "Adding user content", added);
    logItems(listener, "Existing user content", existing);
    logItems(listener, "Removing user content", removed);
  }
Esempio n. 21
0
  /**
   * Returns the count of squares reachable by the first player
   *
   * @param grid
   * @param startingLoc
   * @return
   */
  public static boolean getConnectedSquareCount(GridChar grid, int startingLoc) {

    // int oldCount = (1+getConnectedSquareCountOld(grid,startingLoc) );

    // The boolean means it is player 1, the connected square co
    Set<Pair<Integer, Boolean>> visitedNodes = Sets.newHashSet();

    LinkedList<Pair<Integer, Boolean>> toVisit = new LinkedList<>();
    toVisit.add(new ImmutablePair<>(startingLoc, true));

    while (!toVisit.isEmpty()) {

      Pair<Integer, Boolean> loc = toVisit.poll();

      if (visitedNodes.contains(loc)) continue;

      visitedNodes.add(loc);

      for (Direction dir : Direction.values()) {
        Integer childIdx = grid.getIndex(loc.getLeft(), dir);
        if (childIdx == null) continue;

        char sq = grid.getEntry(childIdx);

        if (sq == '#' || sq == 'K' || sq == 'T') continue;

        toVisit.add(new ImmutablePair<>(childIdx, !loc.getRight()));
      }
    }

    Set<Integer> fpPoints = Sets.newHashSet();
    Set<Integer> spPoints = Sets.newHashSet();
    for (Pair<Integer, Boolean> p : visitedNodes) {
      if (p.getRight()) fpPoints.add(p.getLeft());
      else spPoints.add(p.getLeft());
    }

    Set<Integer> shared = Sets.intersection(fpPoints, spPoints);
    Set<Integer> union = Sets.union(fpPoints, spPoints);

    if (!shared.isEmpty()) {
      return (union.size() + 1) % 2 == 0;
    } else {
      // log.debug("size {} size {}", fpPoints.size(), spPoints.size());
      return spPoints.size() < fpPoints.size();
    }
    // return (countFP + countSP + 1) % 2 == 0;
  }
  @Test(description = "convert a map model")
  public void mapModelTest() {
    final Model model =
        new ModelImpl()
            .description("a map model")
            .additionalProperties(new RefProperty("#/definitions/Children"));
    final DefaultCodegen codegen = new TypeScriptFetchClientCodegen();
    final CodegenModel cm = codegen.fromModel("sample", model);

    Assert.assertEquals(cm.name, "sample");
    Assert.assertEquals(cm.classname, "Sample");
    Assert.assertEquals(cm.description, "a map model");
    Assert.assertEquals(cm.vars.size(), 0);
    Assert.assertEquals(cm.imports.size(), 1);
    Assert.assertEquals(Sets.intersection(cm.imports, Sets.newHashSet("Children")).size(), 1);
  }
Esempio n. 23
0
 private FMLControlledNamespacedRegistry<?> findRegistry(Class<?> type) {
   BiMap<Class<?>, String> typeReg = registryTypes.inverse();
   String name = typeReg.get(type);
   if (name == null) {
     Set<Class<?>> parents = Sets.newHashSet();
     findSuperTypes(type, parents);
     SetView<Class<?>> foundType = Sets.intersection(parents, registryTypes.values());
     if (foundType.isEmpty()) {
       FMLLog.severe("Unable to find registry for type %s", type.getName());
       throw new IllegalArgumentException(
           "Attempt to register an object without an associated registry");
     }
     Class<?> regtype = Iterables.getOnlyElement(foundType);
     name = typeReg.get(regtype);
   }
   return genericRegistries.get(name);
 }
Esempio n. 24
0
  private static String getSortAndFunctionDeclarations(
      Definition definition, Set<Variable> variables) {
    Set<Sort> sorts = new HashSet<>();
    List<Production> functions = new ArrayList<>();
    for (Production production : definition.context().productions) {
      String smtlib = production.getAttribute(Attribute.SMTLIB_KEY);
      if (smtlib != null && !SMTLIB_BUILTIN_FUNCTIONS.contains(smtlib) && !smtlib.startsWith("(")) {
        functions.add(production);
        sorts.add(Sort.of(production.getSort()));
        for (int i = 0; i < production.getArity(); ++i) {
          sorts.add(Sort.of(production.getChildSort(i)));
        }
      }
    }
    for (Variable variable : variables) {
      sorts.add(variable.sort());
    }

    if (!Sets.intersection(sorts, RESERVED_Z3_SORTS).isEmpty()) {
      throw new UnsupportedOperationException("do not use sorts " + RESERVED_Z3_SORTS);
    }

    StringBuilder sb = new StringBuilder();

    for (Sort sort : Sets.difference(sorts, SMTLIB_BUILTIN_SORTS)) {
      sb.append("(declare-sort ");
      sb.append(sort);
      sb.append(")\n");
    }

    for (Production production : functions) {
      sb.append("(declare-fun ");
      sb.append(production.getAttribute(Attribute.SMTLIB_KEY));
      sb.append(" (");
      List<String> childrenSorts = new ArrayList<>();
      for (int i = 0; i < production.getArity(); ++i) {
        childrenSorts.add(getSortName(production.getChildNode(i)));
      }
      Joiner.on(" ").appendTo(sb, childrenSorts);
      sb.append(") ");
      sb.append(getSortName(production));
      sb.append(")\n");
    }

    return sb.toString();
  }
  /**
   * Returns the first match of <code>reference</code> in <code>candidates</code>. This
   * implementation will consider two Resources to be "matches" if their roots have IDs, and these
   * IDs are the same.
   *
   * @param reference The reference resource.
   * @param candidates The list of potential candidates that may match <code>reference</code>.
   * @return The first match of <code>reference</code> in <code>candidates</code>. <code>null</code>
   *     if none.
   * @deprecated use {@link RootIDMatchingStrategy#findMatches(Resource, Iterable)} instead.
   */
  @Deprecated
  protected Resource findMatch(Resource reference, Iterable<Resource> candidates) {
    final Set<String> referenceIDs = getResourceIdentifiers(reference);
    if (referenceIDs.isEmpty()) {
      return null;
    }

    Resource match = null;
    final Iterator<Resource> candidateIterator = candidates.iterator();
    while (candidateIterator.hasNext() && match == null) {
      final Resource candidate = candidateIterator.next();
      final Set<String> candidateIDs = getResourceIdentifiers(candidate);
      if (!candidateIDs.isEmpty() && !Sets.intersection(candidateIDs, referenceIDs).isEmpty()) {
        match = candidate;
      }
    }
    return match;
  }
 static void validateRegions(
     Map<String, Collection<String>> regionsToAdd,
     Map<String, Collection<String>> supportedRegions) {
   MapDifference<String, Collection<String>> comparison =
       Maps.difference(regionsToAdd, supportedRegions);
   checkArgument(
       comparison.entriesOnlyOnLeft().isEmpty(),
       "unsupported regions: %s",
       comparison.entriesOnlyOnLeft().keySet());
   for (Entry<String, Collection<String>> entry : regionsToAdd.entrySet()) {
     ImmutableSet<String> toAdd = ImmutableSet.copyOf(entry.getValue());
     SetView<String> intersection =
         Sets.intersection(toAdd, ImmutableSet.copyOf(supportedRegions.get(entry.getKey())));
     SetView<String> unsupported = Sets.difference(toAdd, intersection);
     checkArgument(
         unsupported.isEmpty(), "unsupported territories in %s:", entry.getKey(), unsupported);
   }
 }
  /**
   * @param gcBefore
   * @return
   */
  private List<SSTableReader> getNextBackgroundSSTables(final int gcBefore) {
    if (!isEnabled() || cfs.getSSTables().isEmpty()) return Collections.emptyList();

    Set<SSTableReader> uncompacting = Sets.intersection(sstables, cfs.getUncompactingSSTables());

    // Find fully expired SSTables. Those will be included no matter what.
    Set<SSTableReader> expired =
        CompactionController.getFullyExpiredSSTables(
            cfs, uncompacting, cfs.getOverlappingSSTables(uncompacting), gcBefore);
    Set<SSTableReader> candidates = Sets.newHashSet(filterSuspectSSTables(uncompacting));

    List<SSTableReader> compactionCandidates =
        new ArrayList<>(getNextNonExpiredSSTables(Sets.difference(candidates, expired), gcBefore));
    if (!expired.isEmpty()) {
      logger.debug("Including expired sstables: {}", expired);
      compactionCandidates.addAll(expired);
    }
    return compactionCandidates;
  }
    @Override
    public void run() {
      while (provider.isRunning()) {
        ResponseList<Post> postResponseList;
        try {
          postResponseList = client.getFeed(id);

          Set<Post> update = Sets.newHashSet(postResponseList);
          Set<Post> repeats = Sets.intersection(priorPollResult, Sets.newHashSet(update));
          Set<Post> entrySet = Sets.difference(update, repeats);
          LOGGER.debug(
              this.id
                  + " response: "
                  + update.size()
                  + " previous: "
                  + repeats.size()
                  + " new: "
                  + entrySet.size());
          for (Post item : entrySet) {
            String json = DataObjectFactory.getRawJSON(item);
            org.apache.streams.facebook.Post post =
                mapper.readValue(json, org.apache.streams.facebook.Post.class);
            try {
              lock.readLock().lock();
              ComponentUtils.offerUntilSuccess(new StreamsDatum(post), providerQueue);
              countersCurrent.incrementAttempt();
            } finally {
              lock.readLock().unlock();
            }
          }
          priorPollResult = update;
        } catch (Exception e) {
          e.printStackTrace();
        } finally {
          try {
            Thread.sleep(configuration.getPollIntervalMillis());
          } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
          }
        }
      }
    }
Esempio n. 29
0
 @SuppressWarnings("unchecked")
 private <T> FMLControlledNamespacedRegistry<T> createGenericRegistry(
     String registryName, Class<T> type, int minId, int maxId) {
   Set<Class<?>> parents = Sets.newHashSet();
   findSuperTypes(type, parents);
   SetView<Class<?>> overlappedTypes = Sets.intersection(parents, registryTypes.values());
   if (!overlappedTypes.isEmpty()) {
     Class<?> foundType = overlappedTypes.iterator().next();
     FMLLog.severe(
         "Found existing registry of type %1s named %2s, you cannot create a new registry (%3s) with type %4s, as %4s has a parent of that type",
         foundType, registryTypes.inverse().get(foundType), registryName, type);
     throw new IllegalArgumentException(
         "Duplicate registry parent type found - you can only have one registry for a particular super type");
   }
   FMLControlledNamespacedRegistry<?> fmlControlledNamespacedRegistry =
       new FMLControlledNamespacedRegistry<T>(null, maxId, minId, type);
   genericRegistries.put(registryName, fmlControlledNamespacedRegistry);
   registryTypes.put(registryName, type);
   return (FMLControlledNamespacedRegistry<T>) fmlControlledNamespacedRegistry;
 }
  /**
   * Returns the first two matches of <code>reference</code> in <code>candidates</code>. This
   * implementation will consider two Resources to be "matches" if their roots have IDs, and these
   * IDs intersect.
   *
   * <p>Subclasses may return more than two elements if considered useful.
   *
   * @param reference The reference resource.
   * @param candidates The list of potential candidates that may match <code>reference</code>.
   * @return The first two matches of <code>reference</code> in <code>candidates</code>. Empty list
   *     if none.
   * @since 3.3
   */
  protected List<Resource> findMatches(Resource reference, Iterable<Resource> candidates) {
    final Set<String> referenceIDs = getResourceIdentifiers(reference);
    if (referenceIDs.isEmpty()) {
      return Lists.newArrayList();
    }

    final List<Resource> matches = new ArrayList<Resource>(2);
    final Iterator<Resource> candidateIterator = candidates.iterator();

    // optimize for size 2 since we do not need more at the moment
    while (candidateIterator.hasNext() && matches.size() < 2) {
      final Resource candidate = candidateIterator.next();
      final Set<String> candidateIDs = getResourceIdentifiers(candidate);
      if (!candidateIDs.isEmpty() && !Sets.intersection(candidateIDs, referenceIDs).isEmpty()) {
        matches.add(candidate);
      }
    }

    return matches;
  }