private PresentWhenExtensionAnnotationMatchesExtensionSet whenExtensionsAndAliasesInRegionInclude(
      String region, final Set<Extension> extensions, final Multimap<URI, URI> aliases) {
    final LoadingCache<String, Set<? extends Extension>> extensionsForRegion =
        CacheBuilder.newBuilder()
            .build(
                CacheLoader.from(
                    Functions.forMap(
                        ImmutableMap.<String, Set<? extends Extension>>of(
                            region, extensions, "differentregion", ImmutableSet.<Extension>of()))));

    PresentWhenExtensionAnnotationMatchesExtensionSet fn =
        Guice.createInjector(
                new AbstractModule() {
                  @Override
                  protected void configure() {
                    MapBinder<URI, URI> aliasBindings =
                        MapBinder.newMapBinder(
                                binder(), URI.class, URI.class, NamespaceAliases.class)
                            .permitDuplicates();
                    for (URI key : aliases.keySet()) {
                      for (URI value : aliases.get(key)) {
                        aliasBindings.addBinding(key).toInstance(value);
                      }
                    }
                  }

                  @Provides
                  LoadingCache<String, Set<? extends Extension>> getExtensions() {
                    return extensionsForRegion;
                  }
                })
            .getInstance(PresentWhenExtensionAnnotationMatchesExtensionSet.class);

    return fn;
  }
コード例 #2
0
 public TemplateBuilder createTemplateBuilder() {
   final Supplier<Set<? extends Image>> images =
       Suppliers.<Set<? extends Image>>ofInstance(
           ImmutableSet.of(
               new ImageBuilder()
                   .providerId("ebs-image-provider")
                   .name("image")
                   .id("us-east-1/bogus-image")
                   .location(jcloudsDomainLocation)
                   .userMetadata(ImmutableMap.of("rootDeviceType", RootDeviceType.EBS.value()))
                   .operatingSystem(
                       new OperatingSystem(
                           OsFamily.UBUNTU,
                           null,
                           "1.0",
                           VirtualizationType.PARAVIRTUAL.value(),
                           "ubuntu",
                           true))
                   .description("description")
                   .version("1.0")
                   .defaultCredentials(LoginCredentials.builder().user("root").build())
                   .status(Image.Status.AVAILABLE)
                   .build()));
   ImmutableMap<RegionAndName, Image> imageMap =
       (ImmutableMap<RegionAndName, Image>) ImagesToRegionAndIdMap.imagesToMap(images.get());
   Supplier<LoadingCache<RegionAndName, ? extends Image>> imageCache =
       Suppliers.<LoadingCache<RegionAndName, ? extends Image>>ofInstance(
           CacheBuilder.newBuilder()
               .<RegionAndName, Image>build(CacheLoader.from(Functions.forMap(imageMap))));
   JcloudsStubTemplateBuilder jcloudsStubTemplateBuilder = new JcloudsStubTemplateBuilder();
   return jcloudsStubTemplateBuilder.newTemplateBuilder(images, imageCache);
 }
コード例 #3
0
 @Override
 public ILearningCharmGroup[] getCharmGroups(Identified type) {
   if (MartialArtsUtilities.MARTIAL_ARTS.equals(type)) {
     return martialArtsGroups;
   }
   return Functions.forMap(nonMartialArtsGroupsByType, new ILearningCharmGroup[0]).apply(type);
 }
コード例 #4
0
      @Override
      public Map<Symbol, Symbol> visitProject(ProjectNode node, Set<Symbol> lookupSymbols) {
        // Map from output Symbols to source Symbols
        Map<Symbol, Symbol> directSymbolTranslationOutputMap =
            Maps.transformValues(
                Maps.filterValues(node.getAssignments(), SymbolReference.class::isInstance),
                Symbol::from);
        Map<Symbol, Symbol> outputToSourceMap =
            lookupSymbols
                .stream()
                .filter(directSymbolTranslationOutputMap.keySet()::contains)
                .collect(toImmutableMap(identity(), directSymbolTranslationOutputMap::get));

        checkState(
            !outputToSourceMap.isEmpty(),
            "No lookup symbols were able to pass through the projection");

        // Map from source Symbols to underlying index source Symbols
        Map<Symbol, Symbol> sourceToIndexMap =
            node.getSource().accept(this, ImmutableSet.copyOf(outputToSourceMap.values()));

        // Generate the Map the connects lookup symbols to underlying index source symbols
        Map<Symbol, Symbol> outputToIndexMap =
            Maps.transformValues(
                Maps.filterValues(outputToSourceMap, in(sourceToIndexMap.keySet())),
                Functions.forMap(sourceToIndexMap));
        return ImmutableMap.copyOf(outputToIndexMap);
      }
コード例 #5
0
  private synchronized void removeLeastRecentlyUsedCommand() {
    Ordering<String> ordering =
        Ordering.from(lastUsedComparator).onResultOf(Functions.forMap(this.hayStack));
    ImmutableSortedMap<String, CommandEntry> orderedHay =
        ImmutableSortedMap.copyOf(this.hayStack, ordering);
    String oldestKey = orderedHay.keySet().last();

    hayStack.remove(oldestKey);
  }
コード例 #6
0
 private Iterable<IncludeScannable> getLipoScannables(NestedSet<Artifact> realMandatoryInputs) {
   return lipoScannableMap == null
       ? ImmutableList.<IncludeScannable>of()
       : Iterables.filter(
           Iterables.transform(
               Iterables.filter(
                   FileType.filter(
                       realMandatoryInputs,
                       CppFileTypes.C_SOURCE,
                       CppFileTypes.CPP_SOURCE,
                       CppFileTypes.ASSEMBLER_WITH_C_PREPROCESSOR),
                   Predicates.not(Predicates.equalTo(getSourceFile()))),
               Functions.forMap(lipoScannableMap, null)),
           Predicates.notNull());
 }
コード例 #7
0
 public List<String> getSortedPeopleList(String firstName, String lastName) {
   // TODO: Talk to solrDao that would give a list of people salary pair. Then sort them on a logic
   People linkedInPeople = linkedInDao.getPerson(firstName, lastName);
   Map<String, BigDecimal> personSalaryMap = new HashMap<String, BigDecimal>();
   for (Person person : linkedInPeople.getPersonList()) {
     String key =
         person.getFirstName() + "_" + person.getLastName() + "_" + person.getCurrentStatus();
     personSalaryMap.put(key, getSalary(person));
   }
   Map<String, String> mockPeopleList = new HashMap<String, String>();
   List<String> sortedPeople =
       Ordering.natural()
           .onResultOf(Functions.forMap(personSalaryMap))
           .immutableSortedCopy(personSalaryMap.keySet());
   return sortedPeople;
 }
コード例 #8
0
  @Override
  public synchronized ArrayList<String> find(String needle) {

    Ordering<String> ordering =
        Ordering.from(comparator).onResultOf(Functions.forMap(this.hayStack));
    ImmutableSortedMap<String, CommandEntry> orderedHay =
        ImmutableSortedMap.copyOf(this.hayStack, ordering);

    ArrayList<String> needles = new ArrayList<>();
    for (String straw : orderedHay.keySet()) {
      if (straw.contains(needle)) {
        needles.add(straw);
      }
    }
    return needles;
  }
コード例 #9
0
 @Override
 protected CacheLoader<String, Optional<String>> bucketToRegion(
     @Region Supplier<Set<String>> regionSupplier, final S3Client client) {
   return CacheLoader.<String, Optional<String>>from(
       Functions.forMap(
           ImmutableMap.<String, Optional<String>>builder()
               .put("bucket", Optional.<String>absent())
               .put("destinationbucket", Optional.<String>absent())
               .put("bucket-us-standard", Optional.of("us-standard"))
               .put("bucket-us-west-1", Optional.of("us-west-1"))
               .put("bucket-us-west-2", Optional.of("us-west-2"))
               .put("bucket-eu-west-1", Optional.of("eu-west-1"))
               .put("bucket-sa-east-1", Optional.of("sa-east-1"))
               .put("bucket-ap-southeast-1", Optional.of("ap-southeast-1"))
               .put("bucket-ap-northeast-1", Optional.of("ap-northeast-1"))
               .build()));
 }
コード例 #10
0
ファイル: PlanFragment.java プロジェクト: JasonGitHub/presto
  @JsonCreator
  public PlanFragment(
      @JsonProperty("id") PlanFragmentId id,
      @JsonProperty("root") PlanNode root,
      @JsonProperty("symbols") Map<Symbol, Type> symbols,
      @JsonProperty("distribution") PlanDistribution distribution,
      @JsonProperty("partitionedSource") PlanNodeId partitionedSource,
      @JsonProperty("outputPartitioning") OutputPartitioning outputPartitioning) {
    this.id = checkNotNull(id, "id is null");
    this.root = checkNotNull(root, "root is null");
    this.symbols = checkNotNull(symbols, "symbols is null");
    this.distribution = checkNotNull(distribution, "distribution is null");
    this.partitionedSource = partitionedSource;

    tupleInfos =
        IterableTransformer.on(root.getOutputSymbols())
            .transform(Functions.forMap(symbols))
            .transform(Type.toRaw())
            .transform(
                new Function<TupleInfo.Type, TupleInfo>() {
                  @Override
                  public TupleInfo apply(TupleInfo.Type input) {
                    return new TupleInfo(input);
                  }
                })
            .list();

    ImmutableList.Builder<PlanNode> sources = ImmutableList.builder();
    findSources(root, sources, partitionedSource);
    this.sources = sources.build();

    ImmutableSet.Builder<PlanNodeId> sourceIds = ImmutableSet.builder();
    for (PlanNode source : this.sources) {
      sourceIds.add(source.getId());
    }
    if (partitionedSource != null) {
      sourceIds.add(partitionedSource);
    }
    this.sourceIds = sourceIds.build();

    this.outputPartitioning = checkNotNull(outputPartitioning, "outputPartitioning is null");
  }
コード例 #11
0
ファイル: Section.java プロジェクト: axiak/LUScheduling
 Set<Course> getPrerequisites() {
   return ImmutableSet.copyOf(
       Lists.transform(serial.getPrereqCourseIdList(), Functions.forMap(program.courses)));
 }
コード例 #12
0
 public void setFormValidationSupplierMap(
     final Map<String, Supplier<ValidationProvider>> formValidationSupplierMap) {
   this.setFormValidationSupplierFunction(
       Functions.<String, Supplier<ValidationProvider>>forMap(formValidationSupplierMap, null));
 }
コード例 #13
0
 @Override
 public Function<JetDeclaration, JetScope> getDeclaringScopes() {
   return Functions.forMap(declaringScopes);
 }
コード例 #14
0
ファイル: PajekNetIOTest.java プロジェクト: RomaKoks/jung
  public void testMixedSaveLoadSave() throws IOException {
    Graph<Number, Number> graph1 = new SparseMultigraph<Number, Number>();
    for (int i = 0; i < 5; i++) {
      graph1.addVertex(i);
    }
    int j = 0;

    List<Number> id = new ArrayList<Number>(graph1.getVertices());
    GreekLabels<Number> gl = new GreekLabels<Number>(id);
    Number[] edges = {0, 1, 2, 3, 4, 5};

    graph1.addEdge(j++, 0, 1, EdgeType.DIRECTED);
    graph1.addEdge(j++, 0, 2, EdgeType.DIRECTED);
    graph1.addEdge(j++, 1, 2, EdgeType.DIRECTED);
    graph1.addEdge(j++, 1, 3);
    graph1.addEdge(j++, 1, 4);
    graph1.addEdge(j++, 4, 3);

    Map<Number, Number> nr = new HashMap<Number, Number>();
    for (int i = 0; i < edges.length; i++) {
      nr.put(edges[i], new Float(Math.random()));
    }

    assertEquals(graph1.getEdgeCount(), 6);

    //        System.err.println(" mixed graph1 = "+graph1);
    //        for(Number edge : graph1.getEdges()) {
    //        	System.err.println("edge "+edge+" is directed? "+graph1.getEdgeType(edge));
    //        }
    //        for(Number v : graph1.getVertices()) {
    //        	System.err.println(v+" outedges are "+graph1.getOutEdges(v));
    //        	System.err.println(v+" inedges are "+graph1.getInEdges(v));
    //        	System.err.println(v+" incidentedges are "+graph1.getIncidentEdges(v));
    //        }

    String testFilename = "mtest.net";
    String testFilename2 = testFilename + "2";

    // assign arbitrary locations to each vertex
    Map<Number, Point2D> locations = new HashMap<Number, Point2D>();
    for (Number v : graph1.getVertices()) {
      locations.put(v, new Point2D.Double(v.intValue() * v.intValue(), 1 << v.intValue()));
    }
    Function<Number, Point2D> vld = Functions.forMap(locations);

    PajekNetWriter<Number, Number> pnw = new PajekNetWriter<Number, Number>();
    pnw.save(graph1, testFilename, gl, Functions.forMap(nr), vld);

    Graph<Number, Number> graph2 = pnr.load(testFilename, graphFactory);
    Function<Number, String> pl = pnr.getVertexLabeller();
    List<Number> id2 = new ArrayList<Number>(graph2.getVertices());
    Function<Number, Point2D> vld2 = pnr.getVertexLocationTransformer();

    assertEquals(graph1.getVertexCount(), graph2.getVertexCount());
    assertEquals(graph1.getEdgeCount(), graph2.getEdgeCount());

    // test vertex labels and locations
    for (int i = 0; i < graph1.getVertexCount(); i++) {
      Number v1 = id.get(i);
      Number v2 = id2.get(i);
      assertEquals(gl.apply(v1), pl.apply(v2));
      assertEquals(vld.apply(v1), vld2.apply(v2));
    }

    // test edge weights
    Function<Number, Number> nr2 = pnr.getEdgeWeightTransformer();
    for (Number e2 : graph2.getEdges()) {
      Pair<Number> endpoints = graph2.getEndpoints(e2);
      Number v1_2 = endpoints.getFirst();
      Number v2_2 = endpoints.getSecond();
      Number v1_1 = id.get(id2.indexOf(v1_2));
      Number v2_1 = id.get(id2.indexOf(v2_2));
      Number e1 = graph1.findEdge(v1_1, v2_1);
      assertNotNull(e1);
      assertEquals(nr.get(e1).floatValue(), nr2.apply(e2).floatValue(), 0.0001);
    }

    pnw.save(graph2, testFilename2, pl, nr2, vld2);

    compareIndexedGraphs(graph1, graph2);

    pnr.setVertexLabeller(null);
    Graph<Number, Number> graph3 = pnr.load(testFilename2, graphFactory);

    compareIndexedGraphs(graph2, graph3);

    File file1 = new File(testFilename);
    File file2 = new File(testFilename2);

    Assert.assertTrue(file1.length() == file2.length());
    file1.delete();
    file2.delete();
  }
コード例 #15
0
  private List<Element> elementsForGroup(
      String lastModified, LakeviewContentGroup contentGroup, Set<String> seenItems) {
    DateTime brandPublicationDate = null;
    DateTime brandEndDate = null;
    int addedSeasons = 0;

    List<Element> elements = Lists.newLinkedList();

    if (contentGroup.isFlattened()) {
      for (Episode episode : contentGroup.episodes()) {
        DateTime publicationDate = orginalPublicationDate(episode);
        if (publicationDate != null) {
          Element episodeElem =
              createEpisodeElem(episode, contentGroup.brand(), null, publicationDate, lastModified);
          String itemId = itemId(episodeElem);
          if (!seenItems.contains(itemId)) {
            elements.add(episodeElem);
            brandPublicationDate =
                publicationDate.isBefore(brandPublicationDate)
                    ? publicationDate
                    : brandPublicationDate;
            brandEndDate = latestOf(publicationDate, brandEndDate);
            seenItems.add(itemId);
          } else {
            log.warn("Not including duplicate of " + itemId);
          }
        }
      }
    } else {
      Map<String, Episode> episodeSeriesIndex =
          Maps.uniqueIndex(contentGroup.episodes(), Identified.TO_URI);

      Function<ChildRef, Episode> childRefToEpisode =
          Functions.compose(Functions.forMap(episodeSeriesIndex, null), ChildRef.TO_URI);
      for (Series series : contentGroup.series()) {
        DateTime seriesPublicationDate = null;

        int addedEpisodes = 0;
        for (Episode episode : sortedSeriesEpisodes(series.getChildRefs(), childRefToEpisode)) {
          DateTime publicationDate = orginalPublicationDate(episode);
          if (publicationDate != null) {
            Element epElem =
                createEpisodeElem(
                    episode, contentGroup.brand(), series, publicationDate, lastModified);
            String itemId = itemId(epElem);
            if (!seenItems.contains(itemId)) {
              elements.add(epElem);
              addedEpisodes++;
              seenItems.add(itemId);
              seriesPublicationDate = earliestOf(publicationDate, seriesPublicationDate);
              brandEndDate = latestOf(publicationDate, brandEndDate);
            } else {
              log.warn("Not including duplicate of " + itemId);
            }
          }
        }

        if (seriesPublicationDate != null) {
          addedSeasons++;
          elements.add(
              elements.size() - addedEpisodes,
              createSeriesElem(series, contentGroup.brand(), seriesPublicationDate, lastModified));
          brandPublicationDate =
              seriesPublicationDate.isBefore(brandPublicationDate)
                  ? seriesPublicationDate
                  : brandPublicationDate;
        }
      }
    }

    Element brandElem = null;
    if (brandPublicationDate != null) {
      brandElem =
          createBrandElem(
              contentGroup.brand(),
              brandPublicationDate,
              brandEndDate,
              lastModified,
              contentGroup,
              addedSeasons);
      if (brandElem != null) {
        elements.add(0, brandElem);
      }
    }

    return brandElem != null ? elements : ImmutableList.<Element>of();
  }
コード例 #16
0
ファイル: Section.java プロジェクト: axiak/LUScheduling
 Set<Resource> getRequiredResources() {
   return ImmutableSet.copyOf(
       Lists.transform(serial.getRequiredResourceList(), Functions.forMap(program.resources)));
 }
コード例 #17
0
ファイル: Section.java プロジェクト: axiak/LUScheduling
 // Does not cache!
 Set<Teacher> getTeachers() {
   return ImmutableSet.copyOf(
       Lists.transform(serial.getTeacherIdList(), Functions.forMap(program.teachers)));
 }
コード例 #18
0
/** @since 2.3 */
public final class AnnotationRuleParser implements ServerComponent {

  private static final Logger LOG = LoggerFactory.getLogger(AnnotationRuleParser.class);

  public List<Rule> parse(String repositoryKey, Collection<Class> annotatedClasses) {
    List<Rule> rules = Lists.newArrayList();
    for (Class annotatedClass : annotatedClasses) {
      rules.add(create(repositoryKey, annotatedClass));
    }
    return rules;
  }

  private Rule create(String repositoryKey, Class annotatedClass) {
    org.sonar.check.Rule ruleAnnotation =
        AnnotationUtils.getAnnotation(annotatedClass, org.sonar.check.Rule.class);
    if (ruleAnnotation != null) {
      return toRule(repositoryKey, annotatedClass, ruleAnnotation);
    }
    LOG.warn(
        "The class "
            + annotatedClass.getCanonicalName()
            + " should be annotated with "
            + Rule.class);
    return null;
  }

  private Rule toRule(String repositoryKey, Class clazz, org.sonar.check.Rule ruleAnnotation) {
    String ruleKey = StringUtils.defaultIfEmpty(ruleAnnotation.key(), clazz.getCanonicalName());
    String ruleName = StringUtils.defaultIfEmpty(ruleAnnotation.name(), null);
    String description = StringUtils.defaultIfEmpty(ruleAnnotation.description(), null);
    Rule rule = Rule.create(repositoryKey, ruleKey, ruleName);
    rule.setDescription(description);
    rule.setSeverity(RulePriority.fromCheckPriority(ruleAnnotation.priority()));
    rule.setCardinality(ruleAnnotation.cardinality());
    rule.setStatus(ruleAnnotation.status().name());

    List<Field> fields = FieldUtils2.getFields(clazz, true);
    for (Field field : fields) {
      addRuleProperty(rule, field);
    }
    return rule;
  }

  private void addRuleProperty(Rule rule, Field field) {
    org.sonar.check.RuleProperty propertyAnnotation =
        field.getAnnotation(org.sonar.check.RuleProperty.class);
    if (propertyAnnotation != null) {
      String fieldKey = StringUtils.defaultIfEmpty(propertyAnnotation.key(), field.getName());
      RuleParam param = rule.createParameter(fieldKey);
      param.setDescription(propertyAnnotation.description());
      param.setDefaultValue(propertyAnnotation.defaultValue());
      if (!StringUtils.isBlank(propertyAnnotation.type())) {
        try {
          param.setType(PropertyType.valueOf(propertyAnnotation.type().trim()).name());
        } catch (IllegalArgumentException e) {
          throw new SonarException("Invalid property type [" + propertyAnnotation.type() + "]", e);
        }
      } else {
        param.setType(guessType(field.getType()).name());
      }
    }
  }

  private static final Function<Class<?>, PropertyType> TYPE_FOR_CLASS =
      Functions.forMap(
          ImmutableMap.<Class<?>, PropertyType>builder()
              .put(Integer.class, PropertyType.INTEGER)
              .put(int.class, PropertyType.INTEGER)
              .put(Float.class, PropertyType.FLOAT)
              .put(float.class, PropertyType.FLOAT)
              .put(Boolean.class, PropertyType.BOOLEAN)
              .put(boolean.class, PropertyType.BOOLEAN)
              .build(),
          PropertyType.STRING);

  @VisibleForTesting
  static PropertyType guessType(Class<?> type) {
    return TYPE_FOR_CLASS.apply(type);
  }
}
コード例 #19
0
 private boolean isBackgroundValueLessThanMinimumValueForCircle(
     final IGenericTraitCollection traitCollection, CircleType type) {
   return Functions.forMap(typesByMinimumValue, 0).apply(type)
       > getBackgroundValue(traitCollection);
 }
コード例 #20
0
 private List<OUTCOME_TYPE> getTopOutcomes(Map<OUTCOME_TYPE, Double> scoredOutcomes) {
   // get just the outcomes that fit within the stack
   Ordering<OUTCOME_TYPE> ordering =
       Ordering.natural().onResultOf(Functions.forMap(scoredOutcomes));
   return ordering.greatestOf(scoredOutcomes.keySet(), this.stackSize);
 }
コード例 #21
0
ファイル: SeqMisc.java プロジェクト: jonross/seq4j
 /**
  * Wraps {@link Functions#forMap(Map, Object)}; returns a function that looks up its argument in a
  * map, using the given default value if the map does not contain that key.
  */
 public static <K, V> Function<K, V> lookup(Map<K, ? extends V> map, V defaultValue) {
   return Functions.forMap(map, defaultValue);
 }
コード例 #22
0
ファイル: SeqMisc.java プロジェクト: jonross/seq4j
 /**
  * Wraps {@link Functions#forMap(Map)}; returns a function that looks up its argument in a map.
  */
 public static <K, V> Function<K, V> lookup(Map<K, V> map) {
   return Functions.forMap(map);
 }