Java Code Examples for org.apache.brooklyn.api.entity.Entity#getParent()

The following examples show how to use org.apache.brooklyn.api.entity.Entity#getParent() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ApplicationResource.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
public List<EntityDetail> fetch(String entityIds, String extraSensorsS) {
    List<String> extraSensorNames = JavaStringEscapes.unwrapOptionallyQuotedJavaStringList(extraSensorsS);
    List<AttributeSensor<?>> extraSensors = extraSensorNames.stream().map((s) -> Sensors.newSensor(Object.class, s)).collect(Collectors.toList());
    
    List<EntityDetail> entitySummaries = Lists.newArrayList();
    for (Entity application : mgmt().getApplications()) {
        entitySummaries.add(addSensorsByName((EntityDetail)fromEntity(application, false, -1, null, null), application, extraSensors));
    }

    if (Strings.isNonBlank(entityIds)) {
        List<String> extraEntities = JavaStringEscapes.unwrapOptionallyQuotedJavaStringList(entityIds);
        for (String entityId: extraEntities) {
            Entity entity = mgmt().getEntityManager().getEntity(entityId.trim());
            while (entity != null && entity.getParent() != null) {
                if (Entitlements.isEntitled(mgmt().getEntitlementManager(), Entitlements.SEE_ENTITY, entity)) {
                    entitySummaries.add(addSensorsByName((EntityDetail)fromEntity(entity, false, -1, null, null), entity, extraSensors));
                }
                entity = entity.getParent();
            }
        }
    }
    return entitySummaries;
}
 
Example 2
Source File: EntityManagementSupport.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
public void attemptLegacyAutodeployment(String effectorName) {
    synchronized (this) {
        if (managementContext != null) {
            log.warn("Autodeployment suggested but not required for " + entity + "." + effectorName);
            return;
        }
        if (entity instanceof Application) {
            log.warn("Autodeployment with new management context triggered for " + entity + "." + effectorName + " -- will not be supported in future. Explicit manage call required.");
            if (initialManagementContext != null) {
                initialManagementContext.getEntityManager().manage(entity);
            } else {
                Entities.startManagement(entity);
            }
            return;
        }
    }
    if ("start".equals(effectorName)) {
        Entity e=entity;
        if (e.getParent()!=null && ((EntityInternal)e.getParent()).getManagementSupport().isDeployed()) { 
            log.warn("Autodeployment in parent's management context triggered for "+entity+"."+effectorName+" -- will not be supported in future. Explicit manage call required.");
            ((EntityInternal)e.getParent()).getManagementContext().getEntityManager().manage(entity);
            return;
        }
    }
    log.warn("Autodeployment not available for "+entity+"."+effectorName);
}
 
Example 3
Source File: Entities.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
/**
 * Brings this entity under management only if its ancestor is managed.
 * <p>
 * Returns true if successful, otherwise returns false in the expectation that the ancestor
 * will become managed, or throws exception if it has no parent or a non-application root.
 *
 * @throws IllegalStateException if {@literal e} is an {@link Application}.
 * @see #startManagement(Entity)
 * 
 * @deprecated since 0.9.0; entities are automatically managed when created via {@link Entity#addChild(EntitySpec)},
 *             or with {@link EntityManager#createEntity(EntitySpec)} (it is strongly encouraged to include the parent
 *             if using the latter for anything but a top-level app).
 */
@Deprecated
public static boolean manage(Entity e) {
    if (Entities.isManaged(e)) {
        return true; // no-op
    }
    
    log.warn("Deprecated use of Entities.manage(Entity), for unmanaged entity "+e);
    Entity o = e.getParent();
    Entity eum = e; // Highest unmanaged ancestor
    if (o==null) throw new IllegalArgumentException("Can't manage "+e+" because it is an orphan");
    while (o.getParent()!=null) {
        if (!isManaged(o)) eum = o;
        o = o.getParent();
    }
    if (isManaged(o)) {
        ((EntityInternal)o).getManagementContext().getEntityManager().manage(eum);
        return true;
    }
    if (!(o instanceof Application)) {
        throw new IllegalStateException("Can't manage "+e+" because it is not rooted at an application");
    }
    return false;
}
 
Example 4
Source File: ApplicationLoggingTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
private String getIndent() {
    String indent = "";
    Entity e = this;
    while (e.getParent() != null) {
        indent += "  ";
        e = e.getParent();
    }
    return indent;
}
 
Example 5
Source File: CassandraNodeSshDriver.java    From brooklyn-library with Apache License 2.0 5 votes vote down vote up
/** returns cassandra-related ancestors (datacenter, fabric), with datacenter first and fabric last */
protected List<Entity> getCassandraAncestors() {
    List<Entity> result = new ArrayList<Entity>();
    Entity ancestor = getEntity().getParent();
    while (ancestor!=null) {
        if (ancestor instanceof CassandraDatacenter || ancestor instanceof CassandraFabric)
            result.add(ancestor);
        ancestor = ancestor.getParent();
    }
    return result;
}
 
Example 6
Source File: Locations.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/** if no locations are supplied, returns locations on the entity, or in the ancestors, until it finds a non-empty set,
 * or ultimately the empty set if no locations are anywhere */ 
public static Collection<? extends Location> getLocationsCheckingAncestors(Collection<? extends Location> locations, Entity entity) {
    // look in ancestors if location not set here
    Entity ancestor = entity;
    while ((locations==null || locations.isEmpty()) && ancestor!=null) {
        locations = ancestor.getLocations();
        ancestor = ancestor.getParent();
    }
    return locations;
}
 
Example 7
Source File: LocalEntityManager.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/**
 * activates management when effector invoked, warning unless context is acceptable
 * (currently only acceptable context is "start")
 */
void manageIfNecessary(Entity entity, Object context) {
    if (!isRunning()) {
        return; // TODO Still a race for terminate being called, and then isManaged below returning false
    } else if (((EntityInternal)entity).getManagementSupport().wasDeployed()) {
        return;
    } else if (isManaged(entity)) {
        return;
    } else if (isPreManaged(entity)) {
        return;
    } else if (Boolean.TRUE.equals(((EntityInternal)entity).getManagementSupport().isReadOnly())) {
        return;
    } else {
        Entity rootUnmanaged = entity;
        while (true) {
            Entity candidateUnmanagedParent = rootUnmanaged.getParent();
            if (candidateUnmanagedParent == null || isManaged(candidateUnmanagedParent) || isPreManaged(candidateUnmanagedParent))
                break;
            rootUnmanaged = candidateUnmanagedParent;
        }
        if (context == Startable.START.getName())
            log.info("Activating local management for {} on start", rootUnmanaged);
        else
            log.warn("Activating local management for {} due to effector invocation on {}: {}", new Object[]{rootUnmanaged, entity, context});
        manage(rootUnmanaged);
    }
}
 
Example 8
Source File: Entities.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
public static Set<Location> getAllInheritedLocations(Entity entity) {
    Set<Location> result = MutableSet.of();
    while (entity!=null) {
        result.addAll(entity.getLocations());
        entity = entity.getParent();
    }
    return result;
}
 
Example 9
Source File: Entities.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
public static Entity catalogItemScopeRoot(Entity entity) {
    Entity root = entity;
    while (root.getParent() != null &&
            root != root.getParent() &&
            Objects.equal(root.getParent().getCatalogItemId(), root.getCatalogItemId())) {
        root = root.getParent();
    }
    return root;
}
 
Example 10
Source File: Entities.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/** Returns the entity's parent, its parent's parent, and so on. */
public static Iterable<Entity> ancestorsWithoutSelf(Entity root) {
    Set<Entity> result = Sets.newLinkedHashSet();
    Entity parent = (root != null) ? root.getParent() : null;
    while (parent != null) {
        result.add(parent);
        parent = parent.getParent();
    }
    return result;
}
 
Example 11
Source File: Entities.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/**
 * Returns true if the given descendant includes the given ancestor in its chain.
 * Does <i>NOT</i> count a node as its ancestor.
 */
public static boolean isAncestor(Entity descendant, Entity potentialAncestor) {
    Entity ancestor = descendant.getParent();
    while (ancestor != null) {
        if (ancestor.equals(potentialAncestor)) return true;
        ancestor = ancestor.getParent();
    }
    return false;
}
 
Example 12
Source File: BasicExecutionContext.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
private String idStack(Entity target) {
    Deque<String> ids = new ArrayDeque<>();
    Entity e = target;
    ids.push(e.getId());
    while (e.getParent() != null) {
        e = e.getParent();
        ids.push(e.getId());
    }
    return ids.toString().replace(" ", "");
}
 
Example 13
Source File: DynamicFabricImpl.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
protected Entity addCluster(Location location) {
    String locationName = elvis(location.getDisplayName(), location.getDisplayName(), null);
    Map creation = Maps.newLinkedHashMap();
    creation.putAll(getCustomChildFlags());
    if (groovyTruth(getDisplayNamePrefix()) || groovyTruth(getDisplayNameSuffix())) {
        String displayName = "" + elvis(getDisplayNamePrefix(), "") + elvis(locationName, "unnamed") + elvis(getDisplayNameSuffix(),"");
        creation.put("displayName", displayName);
    }
    logger.info("Creating entity in fabric {} at {}{}", new Object[] {this, location, 
            (creation!=null && !creation.isEmpty() ? ", properties "+creation : "") });

    Entity entity = createCluster(location, creation);
    
    if (locationName != null) {
        if (entity.getDisplayName()==null)
            entity.setDisplayName(entity.getEntityType().getSimpleName() +" ("+locationName+")");
        else if (!entity.getDisplayName().contains(locationName)) 
            entity.setDisplayName(entity.getDisplayName() +" ("+locationName+")");
    }
    if (entity.getParent()==null) entity.setParent(this);
    
    // Continue to call manage(), because some uses of NodeFactory (in tests) still instantiate the
    // entity via its constructor
    Entities.manage(entity);
    
    addMember(entity);
    
    return entity;
}
 
Example 14
Source File: ApplicationResource.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public List<EntitySummary> details(String entityIds, boolean includeAllApps, String extraSensorsGlobsS, String extraConfigGlobsS, int depth) {
    List<String> extraSensorGlobs = JavaStringEscapes.unwrapOptionallyQuotedJavaStringList(extraSensorsGlobsS);
    List<String> extraConfigGlobs = JavaStringEscapes.unwrapOptionallyQuotedJavaStringList(extraConfigGlobsS);

    Map<String, EntitySummary> entitySummaries = MutableMap.of();

    if (includeAllApps) {
        for (Entity application : mgmt().getApplications()) {
            if (Entitlements.isEntitled(mgmt().getEntitlementManager(), Entitlements.SEE_ENTITY, application)) {
                entitySummaries.put(application.getId(), fromEntity(application, true, depth, extraSensorGlobs, extraConfigGlobs));
            }
        }
    }

    if (Strings.isNonBlank(entityIds)) {
        List<String> extraEntities = JavaStringEscapes.unwrapOptionallyQuotedJavaStringList(entityIds);
        for (String entityId: extraEntities) {
            Entity entity = mgmt().getEntityManager().getEntity(entityId.trim());
            while (entity != null && !entitySummaries.containsKey(entity.getId())) {
                if (Entitlements.isEntitled(mgmt().getEntitlementManager(), Entitlements.SEE_ENTITY, entity)) {
                    entitySummaries.put(entity.getId(), fromEntity(entity, true, depth, extraSensorGlobs, extraConfigGlobs));
                }
                entity = entity.getParent();
            }
        }
    }
    return MutableList.copyOf(entitySummaries.values());
}
 
Example 15
Source File: EntityConfigMap.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
@Override
protected Entity getParentOfContainer(Entity container) {
    if (container==null) return null;
    return container.getParent();
}
 
Example 16
Source File: EntityFunctions.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
@Override public Entity apply(Entity input) {
    return input==null ? null : input.getParent();
}
 
Example 17
Source File: LocalEntityManager.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
/**
 * Should ensure that the entity is now managed somewhere, and known about in all the lists.
 * Returns true if the entity has now become managed; false if it was already managed (anything else throws exception)
 */
private synchronized boolean manageNonRecursive(Entity e, ManagementTransitionMode mode) {
    Entity old = entitiesById.get(e.getId());
    
    if (old!=null && mode.wasNotLoaded()) {
        if (old == deproxyIfNecessary(e)) {
            log.warn("{} redundant call to start management of entity {}; ignoring", this, e);
        } else {
            throw new IdAlreadyExistsException("call to manage entity "+e+" ("+mode+") but "
                    + "different entity "+old+" already known under that id '"+e.getId()+"' at "+this);
        }
        return false;
    }

    BrooklynLogging.log(log, BrooklynLogging.levelDebugOrTraceIfReadOnly(e),
            "{} starting management of entity {}", this, e);
    Entity realE = toRealEntity(e);
    
    Entity oldProxy = entityProxiesById.get(e.getId());
    Entity proxyE;
    if (oldProxy!=null) {
        if (mode.wasNotLoaded()) {
            throw new IdAlreadyExistsException("call to manage entity "+e+" from unloaded "
                    + "state ("+mode+") but already had proxy "+oldProxy+" already known "
                    + "under that id '"+e.getId()+"' at "+this);
        }
        // make the old proxy point at this new delegate
        // (some other tricks done in the call below)
        ((EntityProxyImpl)(Proxy.getInvocationHandler(oldProxy))).resetDelegate(oldProxy, oldProxy, realE);
        proxyE = oldProxy;
    } else {
        proxyE = toProxyEntityIfAvailable(e);
    }
    entityProxiesById.put(e.getId(), proxyE);
    entityTypes.put(e.getId(), realE.getClass().getName());
    entitiesById.put(e.getId(), realE);
    
    preManagedEntitiesById.remove(e.getId());
    if ((e instanceof Application) && (e.getParent()==null)) {
        applications.add((Application)proxyE);
        applicationIds.add(e.getId());
    }
    if (!entities.contains(proxyE)) 
        entities.add(proxyE);
    
    if (old!=null && old!=e) {
        // passing the transition info will ensure the right shutdown steps invoked for old instance
        unmanage(old, mode, true);
    }
    
    return true;
}
 
Example 18
Source File: ApplicationResource.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
/** depth 0 means no detail even at root; negative means infinite; positive means include details for that many levels 
 * (ie 1 means this entity but no details of descendants) */
private EntitySummary fromEntity(Entity entity, boolean includeTags, int detailDepth, List<String> extraSensorGlobs, List<String> extraConfigGlobs) {
    if (detailDepth==0) {
        return new EntitySummary(
            entity.getId(), 
            entity.getDisplayName(),
            entity.getEntityType().getName(),
            entity.getCatalogItemId(),
            MutableMap.of("self", EntityTransformer.entityUri(entity, ui.getBaseUriBuilder())) );
    }

    Boolean serviceUp = entity.getAttribute(Attributes.SERVICE_UP);

    Lifecycle serviceState = entity.getAttribute(Attributes.SERVICE_STATE_ACTUAL);

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

    List<EntitySummary> children = Lists.newArrayList();
    if (!entity.getChildren().isEmpty()) {
        for (Entity child : entity.getChildren()) {
            if (Entitlements.isEntitled(mgmt().getEntitlementManager(), Entitlements.SEE_ENTITY, child)) {
                children.add(fromEntity(child, includeTags, detailDepth-1, extraSensorGlobs, extraConfigGlobs));
            }
        }
    }

    String parentId = null;
    if (entity.getParent()!= null) {
        parentId = entity.getParent().getId();
    }

    List<String> groupIds = Lists.newArrayList();
    if (!entity.groups().isEmpty()) {
        groupIds.addAll(entitiesIdAsArray(entity.groups()));
    }

    List<Map<String, String>> members = Lists.newArrayList();
    if (entity instanceof Group) {
        // use attribute instead of method in case it is read-only
        Collection<Entity> memberEntities = entity.getAttribute(AbstractGroup.GROUP_MEMBERS);
        if (memberEntities != null && !memberEntities.isEmpty())
            members.addAll(entitiesIdAndNameAsList(memberEntities));
    }

    EntityDetail result = new EntityDetail(
            entity.getApplicationId(),
            entity.getId(),
            parentId,
            entity.getDisplayName(),
            entity.getEntityType().getName(),
            serviceUp,
            serviceState,
            iconUrl,
            entity.getCatalogItemId(),
            children,
            groupIds,
            members,
            MutableMap.of("self", EntityTransformer.entityUri(entity, ui.getBaseUriBuilder())) );
    
    if (includeTags) {
        result.setExtraField("tags", resolving(MutableList.copyOf(entity.tags().getTags())).preferJson(true).resolve() );
    }
    result.setExtraField("creationTimeUtc", entity.getCreationTime());
    addSensorsByGlobs(result, entity, extraSensorGlobs);
    addConfigByGlobs(result, entity, extraConfigGlobs);
    
    return result;
}
 
Example 19
Source File: EntityTransformer.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
public static EntitySummary entitySummary(Entity entity, UriBuilder ub) {
        URI applicationUri = serviceUriBuilder(ub, ApplicationApi.class, "get").build(entity.getApplicationId());
        URI entityUri = serviceUriBuilder(ub, EntityApi.class, "get").build(entity.getApplicationId(), entity.getId());
        ImmutableMap.Builder<String, URI> lb = ImmutableMap.<String, URI>builder()
                .put("self", entityUri);
        if (entity.getParent()!=null) {
            URI parentUri = serviceUriBuilder(ub, EntityApi.class, "get").build(entity.getApplicationId(), entity.getParent().getId());
            lb.put("parent", parentUri);
        }

//        UriBuilder urib = serviceUriBuilder(ub, EntityApi.class, "getChildren").build(entity.getApplicationId(), entity.getId());
        // TODO: change all these as well :S
        lb.put("application", applicationUri)
                .put("children", URI.create(entityUri + "/children"))
                .put("config", URI.create(entityUri + "/config"))
                .put("sensors", URI.create(entityUri + "/sensors"))
                .put("effectors", URI.create(entityUri + "/effectors"))
                .put("adjuncts", URI.create(entityUri + "/adjuncts"))
                .put("policies", URI.create(entityUri + "/policies"))
                .put("activities", URI.create(entityUri + "/activities"))
                .put("locations", URI.create(entityUri + "/locations"))
                .put("tags", URI.create(entityUri + "/tags"))
                .put("expunge", URI.create(entityUri + "/expunge"))
                .put("rename", URI.create(entityUri + "/name"))
                .put("spec", URI.create(entityUri + "/spec"))
            ;

        if (RegisteredTypes.getIconUrl(entity)!=null)
            lb.put("iconUrl", URI.create(entityUri + "/icon"));

        if (entity.getCatalogItemId() != null) {
            String versionedId = entity.getCatalogItemId();
            URI catalogUri;
            String symbolicName = CatalogUtils.getSymbolicNameFromVersionedId(versionedId);
            String version = CatalogUtils.getVersionFromVersionedId(versionedId);
            catalogUri = serviceUriBuilder(ub, CatalogApi.class, "getEntity").build(symbolicName, version);
            lb.put("catalog", catalogUri);
        }

        String type = entity.getEntityType().getName();
        return new EntitySummary(entity.getId(), entity.getDisplayName(), type, entity.getCatalogItemId(), lb.build());
    }