예제 #1
0
  @Override
  public void connectSensors() {
    super.connectSensors();
    connectServiceUpIsRunning();

    HostAndPort hostAndPort =
        BrooklynAccessUtils.getBrooklynAccessibleAddress(this, sensors().get(DOCKER_REGISTRY_PORT));
    sensors().set(Attributes.MAIN_URI, URI.create("https://" + hostAndPort + "/v2"));

    httpFeed =
        HttpFeed.builder()
            .entity(this)
            .period(Duration.seconds(3))
            .baseUri(getAttribute(Attributes.MAIN_URI))
            .poll(
                new HttpPollConfig<Boolean>(Attributes.SERVICE_UP)
                    .onSuccess(Functions.constant(true))
                    .onFailureOrException(Functions.constant(false)))
            .poll(
                new HttpPollConfig<List<String>>(DOCKER_REGISTRY_CATALOG)
                    .suburl("/_catalog")
                    .onSuccess(
                        Functionals.chain(
                            HttpValueFunctions.jsonContents(),
                            JsonFunctions.walk("repositories"),
                            JsonFunctions.forEach(JsonFunctions.cast(String.class))))
                    .onFailureOrException(Functions.constant(Collections.<String>emptyList())))
            .build();
  }
 public void testScanReverseKeysOnly() {
   persistence.mutate("A1", Functions.constant("A1".getBytes()));
   persistence.mutate("A2", Functions.constant("A2".getBytes()));
   persistence.mutate("A3", Functions.constant("A3".getBytes()));
   assertEquals(Lists.newArrayList("A3", "A2", "A1"), persistence.keyScanReverse("A", "B", 10));
   assertEquals(Lists.newArrayList("A3", "A2"), persistence.keyScanReverse("A", "B", 2));
   assertEquals(Lists.newArrayList("A2", "A1"), persistence.keyScanReverse("A", "A3", 5));
 }
 @Test
 public void testSubstituter() throws Exception {
   entity.setConfig(BrooklynConfigKeys.SUGGESTED_VERSION, "myversion");
   String baseurl = "version=${version},type=${type},simpletype=${simpletype}";
   Map<String, Object> subs = DownloadSubstituters.getBasicEntitySubstitutions(driver);
   DownloadTargets result =
       DownloadSubstituters.substituter(Functions.constant(baseurl), Functions.constant(subs))
           .apply(new BasicDownloadRequirement(driver));
   String expected =
       String.format(
           "version=%s,type=%s,simpletype=%s",
           "myversion", TestEntity.class.getName(), TestEntity.class.getSimpleName());
   assertEquals(result.getPrimaryLocations(), ImmutableList.of(expected));
 }
예제 #4
0
 @Override
 public String toString() {
   return function.getName()
       + "("
       + Joiner.on(", ").join(Iterables.transform(args, Functions.toStringFunction()))
       + ")";
 }
예제 #5
0
  /**
   * Internal ctor, called by {@link MixinConfig}
   *
   * @param parent
   * @param mixinName
   * @param runTransformers
   * @param plugin
   * @param suppressPlugin
   * @throws ClassNotFoundException
   */
  MixinInfo(
      MixinConfig parent,
      String mixinName,
      boolean runTransformers,
      IMixinConfigPlugin plugin,
      boolean suppressPlugin)
      throws ClassNotFoundException {
    this.parent = parent;
    this.name = mixinName;
    this.className = parent.getMixinPackage() + mixinName;
    this.plugin = plugin;
    this.phase = MixinEnvironment.getCurrentEnvironment().getPhase();

    // Read the class bytes and transform
    this.mixinBytes = this.loadMixinClass(this.className, runTransformers);

    ClassNode classNode = this.getClassNode(0);
    this.priority = this.readPriority(classNode);
    this.targetClasses = this.readTargetClasses(classNode, suppressPlugin);
    this.targetClassNames =
        Collections.unmodifiableList(
            Lists.transform(this.targetClasses, Functions.toStringFunction()));
    this.validationClassNode = classNode;
    this.classInfo = ClassInfo.fromClassNode(classNode);
  }
 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);
 }
예제 #7
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);
      }
예제 #8
0
  private Function<String, String> createFunction(boolean isForObfuscation) {
    if (!rawMap.isPresent()) {
      return Functions.identity();
    }

    ImmutableMap.Builder<String, String> builder = ImmutableMap.builder();
    for (Map.Entry<String, String> entry : rawMap.get().entrySet()) {
      String original = entry.getKey().replace('.', '/');
      String obfuscated = entry.getValue().replace('.', '/');
      builder.put(
          isForObfuscation ? original : obfuscated, isForObfuscation ? obfuscated : original);
    }
    final Map<String, String> map = builder.build();

    return new Function<String, String>() {
      @Override
      public String apply(String input) {
        String mapped = map.get(input);
        if (mapped != null) {
          return mapped;
        } else {
          return input;
        }
      }
    };
  }
 @Override
 public void pause(final IJobUpdateKey key, AuditData auditData) throws UpdateStateException {
   requireNonNull(key);
   LOG.info("Attempting to pause update " + key);
   unscopedChangeUpdateStatus(
       key, Functions.compose(createAuditedEvent(auditData), GET_PAUSE_STATE));
 }
예제 #10
0
  @Test
  public void testIgnorePaths() throws IOException {
    ProjectFilesystem filesystem = EasyMock.createMock(ProjectFilesystem.class);
    EasyMock.expect(filesystem.getPathRelativizer())
        .andReturn(Functions.<String>identity())
        .times(2);
    BuildTargetParser parser = EasyMock.createMock(BuildTargetParser.class);
    EasyMock.replay(filesystem, parser);

    Reader reader =
        new StringReader(
            Joiner.on('\n').join("[project]", "ignore = .git, foo, bar/, baz//, a/b/c"));
    BuckConfig config = BuckConfig.createFromReader(reader, filesystem, parser, Platform.detect());

    ImmutableSet<String> ignorePaths = config.getIgnorePaths();
    assertEquals(
        "Should ignore paths, sans trailing slashes",
        ignorePaths,
        ImmutableSet.of(
            BuckConstant.BUCK_OUTPUT_DIRECTORY,
            ".idea",
            System.getProperty(BuckConfig.BUCK_BUCKD_DIR_KEY, ".buckd"),
            config.getCacheDir(),
            ".git",
            "foo",
            "bar",
            "baz",
            "a/b/c"));

    EasyMock.verify(filesystem, parser);
  }
  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;
  }
 @Override
 public Iterator<Tree> childrenIterator() {
   return Iterators.concat(
       Iterators.singletonIterator(openCurlyBrace),
       properties.elementsAndSeparators(Functions.<Tree>identity()),
       Iterators.singletonIterator(closeCurlyBrace));
 }
예제 #13
0
 @Override
 public ILearningCharmGroup[] getCharmGroups(Identified type) {
   if (MartialArtsUtilities.MARTIAL_ARTS.equals(type)) {
     return martialArtsGroups;
   }
   return Functions.forMap(nonMartialArtsGroupsByType, new ILearningCharmGroup[0]).apply(type);
 }
예제 #14
0
 public Builder setRuleKeys(Iterable<RuleKey> ruleKeys) {
   // Make sure we expand any lazy evaluation Iterators so Json serialization works correctly.
   List<String> keysAsStrings =
       FluentIterable.from(ruleKeys).transform(Functions.toStringFunction()).toList();
   data.put("rule_keys", keysAsStrings);
   return this;
 }
 public Loader<Cursor> build(Context context) {
   return new ComposedCursorLoader<Cursor>(
       context,
       query.getQueryData(),
       ImmutableList.copyOf(notificationUris),
       Functions.<Cursor>identity());
 }
  @Override
  public Iterable<Cursor> makeCursors(Filter filter, Interval interval, QueryGranularity gran) {
    Interval actualInterval = interval;
    if (!actualInterval.overlaps(index.dataInterval)) {
      return ImmutableList.of();
    }

    if (actualInterval.getStart().isBefore(index.dataInterval.getStart())) {
      actualInterval = actualInterval.withStart(index.dataInterval.getStart());
    }
    if (actualInterval.getEnd().isAfter(index.dataInterval.getEnd())) {
      actualInterval = actualInterval.withEnd(index.dataInterval.getEnd());
    }

    final Iterable<Cursor> iterable;
    if (filter == null) {
      iterable = new NoFilterCursorIterable(index, actualInterval, gran);
    } else {
      Offset offset = new ConciseOffset(filter.goConcise(new MMappedInvertedIndexSelector(index)));

      iterable = new CursorIterable(index, actualInterval, gran, offset);
    }

    return FunctionalIterable.create(iterable).keep(Functions.<Cursor>identity());
  }
 @SuppressWarnings({"unchecked", "rawtypes"})
 private void validate() {
   checkNotNull(source, "Entity source");
   checkNotNull(sensor, "Sensor");
   if (readiness == null) readiness = GroovyJavaMethods.truthPredicate();
   if (postProcess == null) postProcess = (Function) Functions.identity();
 }
 public static Function<HttpToolResponse, Boolean> responseCodeEquals(final int... expected) {
   List<Integer> expectedList = Lists.newArrayList();
   for (int e : expected) {
     expectedList.add((Integer) e);
   }
   return Functionals.chain(
       HttpValueFunctions.responseCode(), Functions.forPredicate(Predicates.in(expectedList)));
 }
예제 #19
0
  /** @return the framework search paths with any embedded macros expanded. */
  static ImmutableSet<Path> getFrameworkSearchPaths(
      Optional<ImmutableSortedSet<FrameworkPath>> frameworks,
      CxxPlatform cxxPlatform,
      SourcePathResolver resolver) {

    ImmutableSet<Path> searchPaths =
        FluentIterable.from(frameworks.get())
            .transform(
                FrameworkPath.getUnexpandedSearchPathFunction(
                    resolver.getPathFunction(), Functions.<Path>identity()))
            .toSet();

    return FluentIterable.from(Optional.of(searchPaths).or(ImmutableSet.<Path>of()))
        .transform(Functions.toStringFunction())
        .transform(CxxFlags.getTranslateMacrosFn(cxxPlatform))
        .transform(MorePaths.TO_PATH)
        .toSet();
  }
  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);
  }
예제 #21
0
 private static Optional<Tool> getOptionalTool(
     String tool,
     ImmutableList<Path> toolSearchPaths,
     ExecutableFinder executableFinder,
     String version) {
   return getOptionalToolPath(tool, toolSearchPaths, executableFinder)
       .transform(VersionedTool.fromPath(tool, version))
       .transform(Functions.<Tool>identity());
 }
예제 #22
0
  @Override
  public void apply(final EntityLocal entity) {
    super.apply(entity);

    if (LOG.isDebugEnabled()) {
      LOG.debug("Adding SSH sensor {} to {}", name, entity);
    }

    Supplier<Map<String, String>> envSupplier =
        new Supplier<Map<String, String>>() {
          @Override
          public Map<String, String> get() {
            return MutableMap.copyOf(
                Strings.toStringMap(entity.getConfig(SoftwareProcess.SHELL_ENVIRONMENT), ""));
          }
        };

    Supplier<String> commandSupplier =
        new Supplier<String>() {
          @Override
          public String get() {
            return makeCommandExecutingInDirectory(command, executionDir, entity);
          }
        };

    SshPollConfig<T> pollConfig =
        new SshPollConfig<T>(sensor)
            .period(period)
            .env(envSupplier)
            .command(commandSupplier)
            .checkSuccess(SshValueFunctions.exitStatusEquals(0))
            .onFailureOrException(Functions.constant((T) null))
            .onSuccess(
                Functions.compose(
                    new Function<String, T>() {
                      @Override
                      public T apply(String input) {
                        return TypeCoercions.coerce(input, getType(type));
                      }
                    },
                    SshValueFunctions.stdout()));

    SshFeed.builder().entity(entity).onlyIfServiceUp().poll(pollConfig).build();
  }
 public void testDefensiveCopy() {
   byte[] input = "B".getBytes();
   persistence.mutate("A", Functions.constant(input));
   input[0]++;
   if (supportsDefensiveCopy) {
     assertTrue(Arrays.equals(persistence.get("A"), "B".getBytes()));
   } else {
     assertTrue(Arrays.equals(persistence.get("A"), input));
   }
 }
예제 #24
0
 public static Map<String, Key> getKeyInstances(final EvaluationConstraint constraint) {
   return Maps.transformValues(
       Maps.filterValues(
           KEY_MAP,
           CollectionUtils.propertyContainsPredicate(
               constraint,
               Functions.compose(
                   PolicyKeyToEvaluationConstraints.INSTANCE, KeyClassToPolicyKey.INSTANCE))),
       KeyClassToKeyInstance.INSTANCE);
 }
  /**
   * Set the strategy used to locate the {@link SAMLMetadataContext} associated with a given {@link
   * ProfileRequestContext}. Also sets the strategy to find the {@link SAMLMetadataContext} from the
   * {@link AttributeFilterContext}; SAMLMetadataContext
   *
   * @param strategy strategy used to locate the {@link AuthenticationContext} associated with a
   *     given {@link ProfileRequestContext}
   */
  public void setMetadataContextLookupStrategy(
      @Nonnull final Function<ProfileRequestContext, SAMLMetadataContext> strategy) {
    ComponentSupport.ifInitializedThrowUnmodifiabledComponentException(this);

    metadataContextLookupStrategy =
        Constraint.isNotNull(strategy, "MetadataContext lookup strategy cannot be null");
    metadataFromFilterLookupStrategy =
        Functions.compose(
            metadataContextLookupStrategy,
            new RootContextLookup<AttributeFilterContext, ProfileRequestContext>());
  }
예제 #26
0
 private Map<String, Integer> nullMeasures() {
   Set<String> metrics =
       ImmutableSet.of(
           "tests",
           "test_failures",
           "test_errors",
           "skipped_tests",
           "test_success_density",
           "test_execution_time");
   return Maps.asMap(metrics, Functions.<Integer>constant(null));
 }
  @Test
  public void jsonRepresentationContainsAllRuleKeysWithTransform() throws IOException {
    Iterable<RuleKey> ruleKeysInATransform =
        Iterables.transform(TEST_RULE_KEYS, Functions.<RuleKey>identity());

    HttpArtifactCacheEvent.Finished finishedEvent =
        createBuilder().setRuleKeys(ruleKeysInATransform).build();
    configureEvent(finishedEvent);
    String json = JSON_CONVERTER.writeValueAsString(finishedEvent);
    assertTrue(json.contains(TEST_RULE_KEYS_JSON));
  }
예제 #28
0
  public SqlTask createInitialTask() {
    TaskId taskId = new TaskId("query", "stage", "task" + nextTaskId.incrementAndGet());
    URI location = URI.create("fake://task/" + taskId);

    return new SqlTask(
        taskId,
        location,
        sqlTaskExecutionFactory,
        taskNotificationExecutor,
        Functions.<SqlTask>identity(),
        new DataSize(32, MEGABYTE));
  }
예제 #29
0
  @Override
  public void addOptionsToAlgorithmParameters(
      DropdownMutator mutator, List<String> numericColumnNames) {
    List<String> options = Lists.newArrayList(numericColumnNames);

    options.add(getColumnNameParameterDisablingToken());
    mutator.add(getColumnNameParameterId(), options, getColumnNameParameterDisablingToken());

    mutator.add(
        getScalingParameterId(),
        Collections2.transform(EnumSet.allOf(Scaling.class), Functions.toStringFunction()));
  }
예제 #30
0
  @TypeMapper
  public enum ServiceIdToServiceStatus implements Function<ServiceId, ServiceStatusType> {
    INSTANCE;
    private final Function<ServiceId, ServiceStatusType> transform =
        Functions.compose(
            ServiceConfigurationToStatus.INSTANCE, ServiceIdToServiceConfiguration.INSTANCE);

    @Override
    public ServiceStatusType apply(ServiceId input) {
      return transform.apply(input);
    }
  }