public static EffectorSummary effectorSummary(
     final Entity entity, Effector<?> effector, UriBuilder ub) {
   URI applicationUri =
       serviceUriBuilder(ub, ApplicationApi.class, "get").build(entity.getApplicationId());
   URI entityUri =
       serviceUriBuilder(ub, EntityApi.class, "get")
           .build(entity.getApplicationId(), entity.getId());
   URI selfUri =
       serviceUriBuilder(ub, EffectorApi.class, "invoke")
           .build(entity.getApplicationId(), entity.getId(), effector.getName());
   return new EffectorSummary(
       effector.getName(),
       effector.getReturnTypeName(),
       ImmutableSet.copyOf(
           Iterables.transform(
               effector.getParameters(),
               new Function<ParameterType<?>, EffectorSummary.ParameterSummary<?>>() {
                 @Override
                 public EffectorSummary.ParameterSummary<?> apply(
                     @Nullable ParameterType<?> parameterType) {
                   return parameterSummary(entity, parameterType);
                 }
               })),
       effector.getDescription(),
       ImmutableMap.of(
           "self", selfUri,
           "entity", entityUri,
           "application", applicationUri));
 }
  /*TODO RENAME Method. It could be represent that the service is bound and the service
  operation is called*/
  private void manageService(Entity rawEntity) {

    CloudFoundryService cloudFoundryService;
    if (rawEntity instanceof CloudFoundryService) {

      cloudFoundryService = (CloudFoundryService) rawEntity;

      String serviceName = cloudFoundryService.getConfig(CloudFoundryService.SERVICE_INSTANCE_NAME);

      if (!Strings.isEmpty(serviceName)) {

        Entities.waitForServiceUp(
            cloudFoundryService, cloudFoundryService.getConfig(BrooklynConfigKeys.START_TIMEOUT));

        bindingServiceToEntity(serviceName);
        setCredentialsOnService(cloudFoundryService);
        cloudFoundryService.operation(getEntity());
      } else {
        log.error(
            "Trying to get service instance name from {}, but getting null", cloudFoundryService);
      }
    } else {
      log.error(
          "The service entity {} is not available from the application {}",
          new Object[] {rawEntity, getEntity()});

      throw new NoSuchElementException(
          "No entity matching id "
              + rawEntity.getId()
              + " in Management Context "
              + getEntity().getManagementContext()
              + " during entity service binding "
              + getEntity().getId());
    }
  }
  @Test
  public void testAddChild() throws Exception {
    try {
      // to test in GUI:
      // services: [ { type: org.apache.brooklyn.entity.stock.BasicEntity }]
      Response response =
          client()
              .path(entityEndpoint + "/children")
              .query("timeout", "10s")
              .post(
                  javax.ws.rs.client.Entity.entity(
                      "services: [ { type: " + TestEntity.class.getName() + " }]",
                      "application/yaml"));

      HttpAsserts.assertHealthyStatusCode(response.getStatus());
      Assert.assertEquals(entity.getChildren().size(), 1);
      Entity child = Iterables.getOnlyElement(entity.getChildren());
      Assert.assertTrue(Entities.isManaged(child));

      TaskSummary task = response.readEntity(TaskSummary.class);
      Assert.assertEquals(task.getResult(), MutableList.of(child.getId()));

    } finally {
      // restore it for other tests
      Collection<Entity> children = entity.getChildren();
      if (!children.isEmpty()) Entities.unmanage(Iterables.getOnlyElement(children));
    }
  }
 public static Map<String, Object> getSensorMap(String sensor, Iterable<Entity> descs) {
   if (Iterables.isEmpty(descs)) return Collections.emptyMap();
   Map<String, Object> result = MutableMap.of();
   Iterator<Entity> di = descs.iterator();
   Sensor<?> s = null;
   while (di.hasNext()) {
     Entity potentialSource = di.next();
     s = potentialSource.getEntityType().getSensor(sensor);
     if (s != null) break;
   }
   if (s == null) s = Sensors.newSensor(Object.class, sensor);
   if (!(s instanceof AttributeSensor<?>)) {
     log.warn("Cannot retrieve non-attribute sensor " + s + " for entities; returning empty map");
     return result;
   }
   for (Entity e : descs) {
     Object v = null;
     try {
       v = e.getAttribute((AttributeSensor<?>) s);
     } catch (Exception exc) {
       Exceptions.propagateIfFatal(exc);
       log.warn("Error retrieving sensor " + s + " for " + e + " (ignoring): " + exc);
     }
     if (v != null) result.put(e.getId(), v);
   }
   return result;
 }
  /**
   * Walks the contents of a ManagementContext, to create a corresponding memento.
   *
   * @deprecated since 0.7.0; will be moved to test code; generate each entity/location memento
   *     separately
   */
  @Deprecated
  public static BrooklynMemento newBrooklynMemento(ManagementContext managementContext) {
    BrooklynMementoImpl.Builder builder = BrooklynMementoImpl.builder();

    for (Application app : managementContext.getApplications()) {
      builder.applicationIds.add(app.getId());
    }
    for (Entity entity : managementContext.getEntityManager().getEntities()) {
      builder.entities.put(
          entity.getId(), ((EntityInternal) entity).getRebindSupport().getMemento());

      for (Location location : entity.getLocations()) {
        if (!builder.locations.containsKey(location.getId())) {
          for (Location locationInHierarchy : TreeUtils.findLocationsInHierarchy(location)) {
            if (!builder.locations.containsKey(locationInHierarchy.getId())) {
              builder.locations.put(
                  locationInHierarchy.getId(),
                  ((LocationInternal) locationInHierarchy).getRebindSupport().getMemento());
            }
          }
        }
      }
    }
    for (LocationMemento memento : builder.locations.values()) {
      if (memento.getParent() == null) {
        builder.topLevelLocationIds.add(memento.getId());
      }
    }

    BrooklynMemento result = builder.build();
    MementoValidators.validateMemento(result);
    return result;
  }
 private ArrayNode entitiesIdAsArray(Iterable<? extends Entity> entities) {
   ArrayNode node = mapper().createArrayNode();
   for (Entity entity : entities) {
     if (Entitlements.isEntitled(
         mgmt().getEntitlementManager(), Entitlements.SEE_ENTITY, entity)) {
       node.add(entity.getId());
     }
   }
   return node;
 }
 private ArrayNode entitiesIdAndNameAsArray(Collection<? extends Entity> entities) {
   ArrayNode node = mapper().createArrayNode();
   for (Entity entity : entities) {
     if (Entitlements.isEntitled(
         mgmt().getEntitlementManager(), Entitlements.SEE_ENTITY, entity)) {
       ObjectNode holder = mapper().createObjectNode();
       holder.put("id", entity.getId());
       holder.put("name", entity.getDisplayName());
       node.add(holder);
     }
   }
   return node;
 }
  @Override
  public JsonNode fetch(String entityIds) {
    Map<String, JsonNode> jsonEntitiesById = MutableMap.of();
    for (Application application : mgmt().getApplications())
      jsonEntitiesById.put(application.getId(), fromEntity(application));
    if (entityIds != null) {
      for (String entityId : entityIds.split(",")) {
        Entity entity = mgmt().getEntityManager().getEntity(entityId.trim());
        while (entity != null && entity.getParent() != null) {
          if (Entitlements.isEntitled(
              mgmt().getEntitlementManager(), Entitlements.SEE_ENTITY, entity)) {
            jsonEntitiesById.put(entity.getId(), fromEntity(entity));
          }
          entity = entity.getParent();
        }
      }
    }

    ArrayNode result = mapper().createArrayNode();
    for (JsonNode n : jsonEntitiesById.values()) result.add(n);
    return result;
  }
  private ObjectNode entityBase(Entity entity) {
    ObjectNode aRoot = mapper().createObjectNode();
    aRoot.put("name", entity.getDisplayName());
    aRoot.put("id", entity.getId());
    aRoot.put("type", entity.getEntityType().getName());

    Boolean serviceUp = entity.getAttribute(Attributes.SERVICE_UP);
    if (serviceUp != null) aRoot.put("serviceUp", serviceUp);

    Lifecycle serviceState = entity.getAttribute(Attributes.SERVICE_STATE_ACTUAL);
    if (serviceState != null) aRoot.put("serviceState", serviceState.toString());

    String iconUrl = entity.getIconUrl();
    if (iconUrl != null) {
      if (brooklyn().isUrlServerSideAndSafe(iconUrl))
        // route to server if it is a server-side url
        iconUrl = EntityTransformer.entityUri(entity) + "/icon";
      aRoot.put("iconUrl", iconUrl);
    }

    return aRoot;
  }
Esempio n. 10
0
 public static final Predicate<Entity> sameCluster(Entity entity) {
   Preconditions.checkNotNull(entity, "entity");
   return new SameClusterPredicate(entity.getId());
 }
  /** @deprecated since 0.7.0; use {@link #newBasicMemento(BrooklynObject)} instead */
  @Deprecated
  public static BasicEntityMemento.Builder newEntityMementoBuilder(Entity entityRaw) {
    EntityInternal entity = (EntityInternal) entityRaw;
    BasicEntityMemento.Builder builder = BasicEntityMemento.builder();
    populateBrooklynObjectMementoBuilder(entity, builder);

    EntityDynamicType definedType = BrooklynTypes.getDefinedEntityType(entity.getClass());

    // TODO the dynamic attributeKeys and configKeys are computed in the BasicEntityMemento
    // whereas effectors are computed here -- should be consistent!
    // (probably best to compute attrKeys and configKeys here)
    builder.effectors.addAll(entity.getEntityType().getEffectors());
    builder.effectors.removeAll(definedType.getEffectors().values());

    builder.isTopLevelApp = (entity instanceof Application && entity.getParent() == null);

    Map<ConfigKey<?>, Object> localConfig = entity.getConfigMap().getLocalConfig();
    for (Map.Entry<ConfigKey<?>, Object> entry : localConfig.entrySet()) {
      ConfigKey<?> key = checkNotNull(entry.getKey(), localConfig);
      Object value = configValueToPersistable(entry.getValue());
      builder.config.put(key, value);
    }

    Map<String, Object> localConfigUnmatched =
        MutableMap.copyOf(entity.getConfigMap().getLocalConfigBag().getAllConfig());
    for (ConfigKey<?> key : localConfig.keySet()) {
      localConfigUnmatched.remove(key.getName());
    }
    for (Map.Entry<String, Object> entry : localConfigUnmatched.entrySet()) {
      String key = checkNotNull(entry.getKey(), localConfig);
      Object value = entry.getValue();
      // TODO Not transforming; that code is deleted in another pending PR anyway!
      builder.configUnmatched.put(key, value);
    }

    @SuppressWarnings("rawtypes")
    Map<AttributeSensor, Object> allAttributes = entity.getAllAttributes();
    for (@SuppressWarnings("rawtypes")
    Map.Entry<AttributeSensor, Object> entry : allAttributes.entrySet()) {
      AttributeSensor<?> key = checkNotNull(entry.getKey(), allAttributes);
      if (key.getPersistenceMode() != SensorPersistenceMode.NONE) {
        Object value = entry.getValue();
        builder.attributes.put((AttributeSensor<?>) key, value);
      }
    }

    for (Location location : entity.getLocations()) {
      builder.locations.add(location.getId());
    }

    for (Entity child : entity.getChildren()) {
      builder.children.add(child.getId());
    }

    for (Policy policy : entity.getPolicies()) {
      builder.policies.add(policy.getId());
    }

    for (Enricher enricher : entity.getEnrichers()) {
      builder.enrichers.add(enricher.getId());
    }

    for (Feed feed : entity.feeds().getFeeds()) {
      builder.feeds.add(feed.getId());
    }

    Entity parentEntity = entity.getParent();
    builder.parent = (parentEntity != null) ? parentEntity.getId() : null;

    if (entity instanceof Group) {
      for (Entity member : ((Group) entity).getMembers()) {
        builder.members.add(member.getId());
      }
    }

    return builder;
  }
Esempio n. 12
0
 public static final Predicate<Entity> sameInfrastructure(Entity entity) {
   Preconditions.checkNotNull(entity, "entity");
   return new SameInfrastructurePredicate(entity.getId());
 }