You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@brooklyn.apache.org by he...@apache.org on 2016/02/01 18:51:20 UTC
[38/51] [abbrv] [partial] brooklyn-server git commit: move subdir
from incubator up a level as it is promoted to its own repo (first
non-incubator commit!)
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/d03f254b/brooklyn-server/camp/camp-brooklyn/src/main/java/org/apache/brooklyn/camp/brooklyn/spi/creation/BrooklynAssemblyTemplateInstantiator.java
----------------------------------------------------------------------
diff --git a/brooklyn-server/camp/camp-brooklyn/src/main/java/org/apache/brooklyn/camp/brooklyn/spi/creation/BrooklynAssemblyTemplateInstantiator.java b/brooklyn-server/camp/camp-brooklyn/src/main/java/org/apache/brooklyn/camp/brooklyn/spi/creation/BrooklynAssemblyTemplateInstantiator.java
deleted file mode 100644
index 931c2e7..0000000
--- a/brooklyn-server/camp/camp-brooklyn/src/main/java/org/apache/brooklyn/camp/brooklyn/spi/creation/BrooklynAssemblyTemplateInstantiator.java
+++ /dev/null
@@ -1,124 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.camp.brooklyn.spi.creation;
-
-import java.util.List;
-import java.util.Set;
-
-import org.apache.brooklyn.api.entity.Application;
-import org.apache.brooklyn.api.entity.EntitySpec;
-import org.apache.brooklyn.api.mgmt.ManagementContext;
-import org.apache.brooklyn.api.mgmt.classloading.BrooklynClassLoadingContext;
-import org.apache.brooklyn.camp.CampPlatform;
-import org.apache.brooklyn.camp.brooklyn.api.AssemblyTemplateSpecInstantiator;
-import org.apache.brooklyn.camp.spi.Assembly;
-import org.apache.brooklyn.camp.spi.AssemblyTemplate;
-import org.apache.brooklyn.camp.spi.PlatformComponentTemplate;
-import org.apache.brooklyn.camp.spi.collection.ResolvableLink;
-import org.apache.brooklyn.core.mgmt.EntityManagementUtils;
-import org.apache.brooklyn.core.mgmt.EntityManagementUtils.CreationResult;
-import org.apache.brooklyn.core.mgmt.HasBrooklynManagementContext;
-import org.apache.brooklyn.core.mgmt.classloading.JavaBrooklynClassLoadingContext;
-import org.apache.brooklyn.util.collections.MutableSet;
-import org.apache.brooklyn.util.core.flags.TypeCoercions;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.common.collect.Lists;
-
-public class BrooklynAssemblyTemplateInstantiator implements AssemblyTemplateSpecInstantiator {
-
- private static final Logger log = LoggerFactory.getLogger(BrooklynAssemblyTemplateInstantiator.class);
-
- public static final String NEVER_UNWRAP_APPS_PROPERTY = "wrappedApp";
-
- @Override
- public Assembly instantiate(AssemblyTemplate template, CampPlatform platform) {
- Application app = create(template, platform);
- CreationResult<Application, Void> start = EntityManagementUtils.start(app);
- log.debug("CAMP created "+app+"; starting in "+start.task());
- return platform.assemblies().get(app.getApplicationId());
- }
-
- private Application create(AssemblyTemplate template, CampPlatform platform) {
- ManagementContext mgmt = getManagementContext(platform);
- BrooklynClassLoadingContext loader = JavaBrooklynClassLoadingContext.create(mgmt);
- EntitySpec<? extends Application> spec = createApplicationSpec(template, platform, loader, MutableSet.<String>of());
- Application instance = mgmt.getEntityManager().createEntity(spec);
- log.info("CAMP created '{}'", instance);
- return instance;
- }
-
- @Override
- public List<EntitySpec<?>> createServiceSpecs(
- AssemblyTemplate template,
- CampPlatform platform, BrooklynClassLoadingContext itemLoader,
- Set<String> encounteredRegisteredTypeIds) {
- return buildTemplateServicesAsSpecs(itemLoader, template, platform, encounteredRegisteredTypeIds);
- }
-
- @Override
- public EntitySpec<? extends Application> createApplicationSpec(
- AssemblyTemplate template,
- CampPlatform platform,
- BrooklynClassLoadingContext loader,
- Set<String> encounteredTypeSymbolicNames) {
- log.debug("CAMP creating application instance for {} ({})", template.getId(), template);
-
- // AssemblyTemplates created via PDP, _specifying_ then entities to put in
-
- EntitySpec<? extends Application> app = CampInternalUtils.createWrapperApp(template, loader);
- app.configure(EntityManagementUtils.WRAPPER_APP_MARKER, Boolean.TRUE);
-
- // first build the children into an empty shell app
- List<EntitySpec<?>> childSpecs = createServiceSpecs(template, platform, loader, encounteredTypeSymbolicNames);
- for (EntitySpec<?> childSpec : childSpecs) {
- // children get parsed and unwrapped irrespective of the NEVER_UNWRAP_APPS setting;
- // we could support a NEVER_UNWRAP_NESTED_ENTITIES item but i don't know if there's a use case
- app.child(EntityManagementUtils.unwrapEntity(childSpec));
- }
-
- if (allowedToUnwrap(template, app)) {
- app = EntityManagementUtils.unwrapApplication(app);
- }
-
- return app;
- }
-
- private boolean allowedToUnwrap(AssemblyTemplate template, EntitySpec<? extends Application> app) {
- return !(Boolean.TRUE.equals(TypeCoercions.coerce(template.getCustomAttributes().get(NEVER_UNWRAP_APPS_PROPERTY), Boolean.class)));
- }
-
- private List<EntitySpec<?>> buildTemplateServicesAsSpecs(BrooklynClassLoadingContext loader, AssemblyTemplate template, CampPlatform platform, Set<String> encounteredRegisteredTypeIds) {
- List<EntitySpec<?>> result = Lists.newArrayList();
-
- for (ResolvableLink<PlatformComponentTemplate> ctl: template.getPlatformComponentTemplates().links()) {
- PlatformComponentTemplate appChildComponentTemplate = ctl.resolve();
- BrooklynComponentTemplateResolver entityResolver = BrooklynComponentTemplateResolver.Factory.newInstance(loader, appChildComponentTemplate);
- EntitySpec<?> spec = entityResolver.resolveSpec(encounteredRegisteredTypeIds);
- result.add(spec);
- }
- return result;
- }
-
- private static ManagementContext getManagementContext(CampPlatform platform) {
- return ((HasBrooklynManagementContext)platform).getBrooklynManagementContext();
- }
-
-}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/d03f254b/brooklyn-server/camp/camp-brooklyn/src/main/java/org/apache/brooklyn/camp/brooklyn/spi/creation/BrooklynComponentTemplateResolver.java
----------------------------------------------------------------------
diff --git a/brooklyn-server/camp/camp-brooklyn/src/main/java/org/apache/brooklyn/camp/brooklyn/spi/creation/BrooklynComponentTemplateResolver.java b/brooklyn-server/camp/camp-brooklyn/src/main/java/org/apache/brooklyn/camp/brooklyn/spi/creation/BrooklynComponentTemplateResolver.java
deleted file mode 100644
index fdc2559..0000000
--- a/brooklyn-server/camp/camp-brooklyn/src/main/java/org/apache/brooklyn/camp/brooklyn/spi/creation/BrooklynComponentTemplateResolver.java
+++ /dev/null
@@ -1,387 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.camp.brooklyn.spi.creation;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.LinkedHashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.ServiceLoader;
-import java.util.Set;
-import java.util.concurrent.atomic.AtomicBoolean;
-
-import javax.annotation.Nullable;
-
-import org.apache.brooklyn.api.entity.Entity;
-import org.apache.brooklyn.api.entity.EntitySpec;
-import org.apache.brooklyn.api.location.Location;
-import org.apache.brooklyn.api.mgmt.ManagementContext;
-import org.apache.brooklyn.api.mgmt.classloading.BrooklynClassLoadingContext;
-import org.apache.brooklyn.api.typereg.RegisteredType;
-import org.apache.brooklyn.camp.brooklyn.BrooklynCampConstants;
-import org.apache.brooklyn.camp.brooklyn.BrooklynCampReservedKeys;
-import org.apache.brooklyn.camp.brooklyn.spi.creation.service.CampServiceSpecResolver;
-import org.apache.brooklyn.camp.brooklyn.spi.creation.service.ServiceTypeResolver;
-import org.apache.brooklyn.camp.brooklyn.spi.creation.service.ServiceTypeResolverAdaptor;
-import org.apache.brooklyn.camp.spi.AbstractResource;
-import org.apache.brooklyn.camp.spi.ApplicationComponentTemplate;
-import org.apache.brooklyn.camp.spi.AssemblyTemplate;
-import org.apache.brooklyn.camp.spi.PlatformComponentTemplate;
-import org.apache.brooklyn.config.ConfigKey;
-import org.apache.brooklyn.core.catalog.internal.CatalogUtils;
-import org.apache.brooklyn.core.config.ConfigKeys;
-import org.apache.brooklyn.core.mgmt.BrooklynTags;
-import org.apache.brooklyn.core.mgmt.BrooklynTaskTags;
-import org.apache.brooklyn.core.mgmt.EntityManagementUtils;
-import org.apache.brooklyn.core.mgmt.ManagementContextInjectable;
-import org.apache.brooklyn.core.mgmt.classloading.JavaBrooklynClassLoadingContext;
-import org.apache.brooklyn.core.resolve.entity.EntitySpecResolver;
-import org.apache.brooklyn.util.collections.MutableList;
-import org.apache.brooklyn.util.collections.MutableSet;
-import org.apache.brooklyn.util.core.config.ConfigBag;
-import org.apache.brooklyn.util.core.flags.FlagUtils;
-import org.apache.brooklyn.util.core.flags.FlagUtils.FlagConfigKeyAndValueRecord;
-import org.apache.brooklyn.util.core.task.Tasks;
-import org.apache.brooklyn.util.guava.Maybe;
-import org.apache.brooklyn.util.net.Urls;
-import org.apache.brooklyn.util.text.Strings;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.common.base.Function;
-import com.google.common.collect.Iterables;
-import com.google.common.collect.Maps;
-
-/**
- * This generates instances of a template resolver that use a {@link ServiceTypeResolver}
- * to parse the {@code serviceType} line in the template.
- */
-@SuppressWarnings("deprecation") // Because of ServiceTypeResolver
-public class BrooklynComponentTemplateResolver {
-
- private static final Logger log = LoggerFactory.getLogger(BrooklynComponentTemplateResolver.class);
-
- private final BrooklynClassLoadingContext loader;
- private final ManagementContext mgmt;
- private final ConfigBag attrs;
- private final Maybe<AbstractResource> template;
- private final BrooklynYamlTypeInstantiator.Factory yamlLoader;
- private final String type;
- private final AtomicBoolean alreadyBuilt = new AtomicBoolean(false);
- private final EntitySpecResolver serviceSpecResolver;
-
- private BrooklynComponentTemplateResolver(BrooklynClassLoadingContext loader, ConfigBag attrs, AbstractResource optionalTemplate, String type) {
- this.loader = loader;
- this.mgmt = loader.getManagementContext();
- this.attrs = ConfigBag.newInstanceCopying(attrs);
- this.template = Maybe.fromNullable(optionalTemplate);
- this.yamlLoader = new BrooklynYamlTypeInstantiator.Factory(loader, this);
- this.type = type;
- this.serviceSpecResolver = new CampServiceSpecResolver(mgmt, getServiceTypeResolverOverrides());
- }
-
- // Deprecated because want to keep as much of the state private as possible
- // Can't remove them because used by ServiceTypeResolver implementations
- /** @deprecated since 0.9.0 */
- @Deprecated public ManagementContext getManagementContext() { return mgmt; }
- @Deprecated public ConfigBag getAttrs() { return attrs; }
- @Deprecated public BrooklynYamlTypeInstantiator.Factory getYamlLoader() { return yamlLoader; }
- @Deprecated public String getDeclaredType() { return type; }
-
- public static class Factory {
-
- public static BrooklynComponentTemplateResolver newInstance(BrooklynClassLoadingContext context, Map<String, ?> childAttrs) {
- return newInstance(context, ConfigBag.newInstance(childAttrs), null);
- }
-
- public static BrooklynComponentTemplateResolver newInstance(BrooklynClassLoadingContext context, AbstractResource template) {
- return newInstance(context, ConfigBag.newInstance(template.getCustomAttributes()), template);
- }
-
- public static BrooklynComponentTemplateResolver newInstance(BrooklynClassLoadingContext context, String serviceType) {
- return newInstance(context, ConfigBag.newInstance().configureStringKey("serviceType", serviceType), null);
- }
-
- private static BrooklynComponentTemplateResolver newInstance(BrooklynClassLoadingContext context, ConfigBag attrs, AbstractResource optionalTemplate) {
- String type = getDeclaredType(null, optionalTemplate, attrs);
- return new BrooklynComponentTemplateResolver(context, attrs, optionalTemplate, type);
- }
-
- private static String getDeclaredType(String knownServiceType, AbstractResource optionalTemplate, @Nullable ConfigBag attrs) {
- String type = knownServiceType;
- if (type==null && optionalTemplate!=null) {
- type = optionalTemplate.getType();
- if (type.equals(AssemblyTemplate.CAMP_TYPE) || type.equals(PlatformComponentTemplate.CAMP_TYPE) || type.equals(ApplicationComponentTemplate.CAMP_TYPE))
- // ignore these values for the type; only subclasses are interesting
- type = null;
- }
- if (type==null) type = extractServiceTypeAttribute(attrs);
- return type;
- }
-
- private static String extractServiceTypeAttribute(@Nullable ConfigBag attrs) {
- return BrooklynYamlTypeInstantiator.InstantiatorFromKey.extractTypeName("service", attrs).orNull();
- }
- }
-
- public boolean canResolve() {
- return serviceSpecResolver.accepts(type, loader);
- }
-
- public <T extends Entity> EntitySpec<T> resolveSpec(Set<String> encounteredRegisteredTypeSymbolicNames) {
- if (alreadyBuilt.getAndSet(true))
- throw new IllegalStateException("Spec can only be used once: "+this);
-
- EntitySpec<?> spec = serviceSpecResolver.resolve(type, loader, encounteredRegisteredTypeSymbolicNames);
-
- if (spec == null) {
- // Try to provide some troubleshooting details
- final String msgDetails;
- RegisteredType item = mgmt.getTypeRegistry().get(Strings.removeFromStart(type, "catalog:"));
- String proto = Urls.getProtocol(type);
- if (item != null && encounteredRegisteredTypeSymbolicNames.contains(item.getSymbolicName())) {
- msgDetails = "Cycle between catalog items detected, starting from " + type +
- ". Other catalog items being resolved up the stack are " + encounteredRegisteredTypeSymbolicNames +
- ". Tried loading it as a Java class instead but failed.";
- } else if (proto != null) {
- msgDetails = "The reference " + type + " looks like a URL (running the CAMP Brooklyn assembly-template instantiator) but the protocol " +
- proto + " isn't white listed (" + BrooklynCampConstants.YAML_URL_PROTOCOL_WHITELIST + "). " +
- "It's also neither a catalog item nor a java type.";
- } else {
- msgDetails = "No resolver knew how to handle it. Using resolvers: " + serviceSpecResolver;
- }
- throw new IllegalStateException("Unable to create spec for type " + type + ". " + msgDetails);
- }
- spec = EntityManagementUtils.unwrapEntity(spec);
-
- populateSpec(spec, encounteredRegisteredTypeSymbolicNames);
-
- @SuppressWarnings("unchecked")
- EntitySpec<T> typedSpec = (EntitySpec<T>) spec;
- return typedSpec;
- }
-
- private List<EntitySpecResolver> getServiceTypeResolverOverrides() {
- List<EntitySpecResolver> overrides = new ArrayList<>();
- ServiceLoader<ServiceTypeResolver> loader = ServiceLoader.load(ServiceTypeResolver.class, mgmt.getCatalogClassLoader());
- for (ServiceTypeResolver resolver : loader) {
- overrides.add(new ServiceTypeResolverAdaptor(this, resolver));
- }
- return overrides;
- }
-
- @SuppressWarnings("unchecked")
- private <T extends Entity> void populateSpec(EntitySpec<T> spec, Set<String> encounteredRegisteredTypeIds) {
- String name, source=null, templateId=null, planId=null;
- if (template.isPresent()) {
- name = template.get().getName();
- templateId = template.get().getId();
- source = template.get().getSourceCode();
- } else {
- name = (String)attrs.getStringKey("name");
- }
- planId = (String)attrs.getStringKey("id");
- if (planId==null)
- planId = (String) attrs.getStringKey(BrooklynCampConstants.PLAN_ID_FLAG);
-
- Object childrenObj = attrs.getStringKey(BrooklynCampReservedKeys.BROOKLYN_CHILDREN);
- if (childrenObj != null) {
- Iterable<Map<String,?>> children = (Iterable<Map<String,?>>)childrenObj;
- for (Map<String,?> childAttrs : children) {
- BrooklynComponentTemplateResolver entityResolver = BrooklynComponentTemplateResolver.Factory.newInstance(loader, childAttrs);
- // encounteredRegisteredTypeIds must contain the items currently being loaded (the dependency chain),
- // but not parent items in this type already resolved.
- EntitySpec<? extends Entity> childSpec = entityResolver.resolveSpec(encounteredRegisteredTypeIds);
- spec.child(EntityManagementUtils.unwrapEntity(childSpec));
- }
- }
-
- if (source!=null) {
- spec.tag(BrooklynTags.newYamlSpecTag(source));
- }
-
- if (!Strings.isBlank(name))
- spec.displayName(name);
- if (templateId != null)
- spec.configure(BrooklynCampConstants.TEMPLATE_ID, templateId);
- if (planId != null)
- spec.configure(BrooklynCampConstants.PLAN_ID, planId);
-
- List<Location> locations = new BrooklynYamlLocationResolver(mgmt).resolveLocations(attrs.getAllConfig(), true);
- if (locations != null) {
- // override locations defined in the type if locations are specified here
- // empty list can be used by caller to clear, so they are inherited
- spec.clearLocations();
- spec.locations(locations);
- }
-
- decorateSpec(spec, encounteredRegisteredTypeIds);
- }
-
- private <T extends Entity> void decorateSpec(EntitySpec<T> spec, Set<String> encounteredRegisteredTypeIds) {
- new BrooklynEntityDecorationResolver.PolicySpecResolver(yamlLoader).decorate(spec, attrs);
- new BrooklynEntityDecorationResolver.EnricherSpecResolver(yamlLoader).decorate(spec, attrs);
- new BrooklynEntityDecorationResolver.InitializerResolver(yamlLoader).decorate(spec, attrs);
- new BrooklynEntityDecorationResolver.SpecParameterResolver(yamlLoader).decorate(spec, attrs);
-
- configureEntityConfig(spec, encounteredRegisteredTypeIds);
- }
-
- @SuppressWarnings({ "unchecked", "rawtypes" })
- private void configureEntityConfig(EntitySpec<?> spec, Set<String> encounteredRegisteredTypeIds) {
- // first take *recognised* flags and config keys from the top-level, and put them in the bag (of brooklyn.config)
- // attrs will contain only brooklyn.xxx properties when coming from BrooklynEntityMatcher.
- // Any top-level flags will go into "brooklyn.flags". When resolving a spec from $brooklyn:entitySpec
- // top level flags remain in place. Have to support both cases.
-
- ConfigBag bag = ConfigBag.newInstance((Map<Object, Object>) attrs.getStringKey(BrooklynCampReservedKeys.BROOKLYN_CONFIG));
- ConfigBag bagFlags = ConfigBag.newInstanceCopying(attrs);
- if (attrs.containsKey(BrooklynCampReservedKeys.BROOKLYN_FLAGS)) {
- bagFlags.putAll((Map<String, Object>) attrs.getStringKey(BrooklynCampReservedKeys.BROOKLYN_FLAGS));
- }
-
- Collection<FlagConfigKeyAndValueRecord> topLevelApparentConfig = findAllFlagsAndConfigKeys(spec, bagFlags);
- for (FlagConfigKeyAndValueRecord r: topLevelApparentConfig) {
- if (r.getConfigKeyMaybeValue().isPresent())
- bag.putIfAbsent((ConfigKey)r.getConfigKey(), r.getConfigKeyMaybeValue().get());
- if (r.getFlagMaybeValue().isPresent())
- bag.putAsStringKeyIfAbsent(r.getFlagName(), r.getFlagMaybeValue().get());
- }
-
- // now set configuration for all the items in the bag
- Collection<FlagConfigKeyAndValueRecord> records = findAllFlagsAndConfigKeys(spec, bag);
- Set<String> keyNamesUsed = new LinkedHashSet<String>();
- for (FlagConfigKeyAndValueRecord r: records) {
- if (r.getFlagMaybeValue().isPresent()) {
- Object transformed = new SpecialFlagsTransformer(loader, encounteredRegisteredTypeIds).apply(r.getFlagMaybeValue().get());
- spec.configure(r.getFlagName(), transformed);
- keyNamesUsed.add(r.getFlagName());
- }
- if (r.getConfigKeyMaybeValue().isPresent()) {
- Object transformed = new SpecialFlagsTransformer(loader, encounteredRegisteredTypeIds).apply(r.getConfigKeyMaybeValue().get());
- spec.configure((ConfigKey<Object>)r.getConfigKey(), transformed);
- keyNamesUsed.add(r.getConfigKey().getName());
- }
- }
-
- // set unused keys as anonymous config keys -
- // they aren't flags or known config keys, so must be passed as config keys in order for
- // EntitySpec to know what to do with them (as they are passed to the spec as flags)
- for (String key: MutableSet.copyOf(bag.getUnusedConfig().keySet())) {
- // we don't let a flag with the same name as a config key override the config key
- // (that's why we check whether it is used)
- if (!keyNamesUsed.contains(key)) {
- Object transformed = new SpecialFlagsTransformer(loader, encounteredRegisteredTypeIds).apply(bag.getStringKey(key));
- spec.configure(ConfigKeys.newConfigKey(Object.class, key.toString()), transformed);
- }
- }
- }
-
- /**
- * Searches for config keys in the type, additional interfaces and the implementation (if specified)
- */
- private Collection<FlagConfigKeyAndValueRecord> findAllFlagsAndConfigKeys(EntitySpec<?> spec, ConfigBag bagFlags) {
- Set<FlagConfigKeyAndValueRecord> allKeys = MutableSet.of();
- allKeys.addAll(FlagUtils.findAllFlagsAndConfigKeys(null, spec.getType(), bagFlags));
- if (spec.getImplementation() != null) {
- allKeys.addAll(FlagUtils.findAllFlagsAndConfigKeys(null, spec.getImplementation(), bagFlags));
- }
- for (Class<?> iface : spec.getAdditionalInterfaces()) {
- allKeys.addAll(FlagUtils.findAllFlagsAndConfigKeys(null, iface, bagFlags));
- }
- allKeys.addAll(FlagUtils.findAllParameterConfigKeys(spec.getParameters(), bagFlags));
- return allKeys;
- }
-
- private static class SpecialFlagsTransformer implements Function<Object, Object> {
- protected final ManagementContext mgmt;
- /* TODO find a way to make do without loader here?
- * it is not very nice having to serialize it; but serialization of BLCL is now relatively clean.
- *
- * it is only used to instantiate classes, and now most types should be registered;
- * the notable exception is when one entity in a bundle is creating another in the same bundle,
- * it wants to use his bundle CLC to do that. but we can set up some unique reference to the entity
- * which can be used to find it from mgmt, rather than pass the loader.
- */
- private BrooklynClassLoadingContext loader = null;
- private Set<String> encounteredRegisteredTypeIds;
-
- public SpecialFlagsTransformer(BrooklynClassLoadingContext loader, Set<String> encounteredRegisteredTypeIds) {
- this.loader = loader;
- mgmt = loader.getManagementContext();
- this.encounteredRegisteredTypeIds = encounteredRegisteredTypeIds;
- }
- @Override
- public Object apply(Object input) {
- if (input instanceof Map)
- return transformSpecialFlags((Map<?, ?>)input);
- else if (input instanceof Set<?>)
- return MutableSet.copyOf(transformSpecialFlags((Iterable<?>)input));
- else if (input instanceof List<?>)
- return MutableList.copyOf(transformSpecialFlags((Iterable<?>)input));
- else if (input instanceof Iterable<?>)
- return transformSpecialFlags((Iterable<?>)input);
- else
- return transformSpecialFlags((Object)input);
- }
-
- protected Map<?, ?> transformSpecialFlags(Map<?, ?> flag) {
- return Maps.transformValues(flag, this);
- }
-
- protected Iterable<?> transformSpecialFlags(Iterable<?> flag) {
- return Iterables.transform(flag, this);
- }
-
- protected BrooklynClassLoadingContext getLoader() {
- if (loader!=null) return loader;
- // TODO currently loader will non-null unless someone has messed with the rebind files,
- // but we'd like to get rid of it; ideally we'd have a reference to the entity.
- // for now, this is a slightly naff way to do it, if we have to set loader=null as a workaround
- Entity entity = BrooklynTaskTags.getTargetOrContextEntity(Tasks.current());
- if (entity!=null) return CatalogUtils.getClassLoadingContext(entity);
- return JavaBrooklynClassLoadingContext.create(mgmt);
- }
-
- /**
- * Makes additional transformations to the given flag with the extra knowledge of the flag's management context.
- * @return The modified flag, or the flag unchanged.
- */
- protected Object transformSpecialFlags(Object flag) {
- if (flag instanceof EntitySpecConfiguration) {
- EntitySpecConfiguration specConfig = (EntitySpecConfiguration) flag;
- // TODO: This should called from BrooklynAssemblyTemplateInstantiator.configureEntityConfig
- // And have transformSpecialFlags(Object flag, ManagementContext mgmt) drill into the Object flag if it's a map or iterable?
- @SuppressWarnings("unchecked")
- Map<String, Object> resolvedConfig = (Map<String, Object>)transformSpecialFlags(specConfig.getSpecConfiguration());
- specConfig.setSpecConfiguration(resolvedConfig);
- EntitySpec<?> entitySpec = Factory.newInstance(getLoader(), specConfig.getSpecConfiguration()).resolveSpec(encounteredRegisteredTypeIds);
-
- return EntityManagementUtils.unwrapEntity(entitySpec);
- }
- if (flag instanceof ManagementContextInjectable) {
- log.debug("Injecting Brooklyn management context info object: {}", flag);
- ((ManagementContextInjectable) flag).setManagementContext(loader.getManagementContext());
- }
-
- return flag;
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/d03f254b/brooklyn-server/camp/camp-brooklyn/src/main/java/org/apache/brooklyn/camp/brooklyn/spi/creation/BrooklynEntityDecorationResolver.java
----------------------------------------------------------------------
diff --git a/brooklyn-server/camp/camp-brooklyn/src/main/java/org/apache/brooklyn/camp/brooklyn/spi/creation/BrooklynEntityDecorationResolver.java b/brooklyn-server/camp/camp-brooklyn/src/main/java/org/apache/brooklyn/camp/brooklyn/spi/creation/BrooklynEntityDecorationResolver.java
deleted file mode 100644
index 4913cb1..0000000
--- a/brooklyn-server/camp/camp-brooklyn/src/main/java/org/apache/brooklyn/camp/brooklyn/spi/creation/BrooklynEntityDecorationResolver.java
+++ /dev/null
@@ -1,216 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.camp.brooklyn.spi.creation;
-
-import java.util.List;
-import java.util.Map;
-
-import org.apache.brooklyn.api.entity.EntityInitializer;
-import org.apache.brooklyn.api.entity.EntitySpec;
-import org.apache.brooklyn.api.mgmt.ManagementContext;
-import org.apache.brooklyn.api.objs.SpecParameter;
-import org.apache.brooklyn.api.policy.Policy;
-import org.apache.brooklyn.api.policy.PolicySpec;
-import org.apache.brooklyn.api.sensor.Enricher;
-import org.apache.brooklyn.api.sensor.EnricherSpec;
-import org.apache.brooklyn.api.typereg.RegisteredType;
-import org.apache.brooklyn.camp.brooklyn.BrooklynCampReservedKeys;
-import org.apache.brooklyn.camp.brooklyn.spi.creation.BrooklynYamlTypeInstantiator.InstantiatorFromKey;
-import org.apache.brooklyn.core.objs.BasicSpecParameter;
-import org.apache.brooklyn.core.typereg.RegisteredTypeLoadingContexts;
-import org.apache.brooklyn.core.typereg.RegisteredTypes;
-import org.apache.brooklyn.util.collections.MutableList;
-import org.apache.brooklyn.util.core.config.ConfigBag;
-import org.apache.brooklyn.util.guava.Maybe;
-
-import com.google.common.annotations.Beta;
-import com.google.common.collect.ImmutableList;
-
-/**
- * Pattern for resolving "decorations" on service specs / entity specs, such as policies, enrichers, etc.
- * @since 0.7.0
- */
-@Beta
-public abstract class BrooklynEntityDecorationResolver<DT> {
-
- public final BrooklynYamlTypeInstantiator.Factory instantiator;
-
- protected BrooklynEntityDecorationResolver(BrooklynYamlTypeInstantiator.Factory instantiator) {
- this.instantiator = instantiator;
- }
-
- public abstract void decorate(EntitySpec<?> entitySpec, ConfigBag attrs);
-
- protected List<? extends DT> buildListOfTheseDecorationsFromEntityAttributes(ConfigBag attrs) {
- Object value = getDecorationAttributeJsonValue(attrs);
- if (value==null) return MutableList.of();
- if (value instanceof Iterable) {
- return buildListOfTheseDecorationsFromIterable((Iterable<?>)value);
- } else {
- // in future may support types other than iterables here,
- // e.g. a map short form where the key is the type
- throw new IllegalArgumentException(getDecorationKind()+" body should be iterable, not " + value.getClass());
- }
- }
-
- protected Map<?,?> checkIsMap(Object decorationJson) {
- if (!(decorationJson instanceof Map))
- throw new IllegalArgumentException(getDecorationKind()+" value must be a Map, not " +
- (decorationJson==null ? null : decorationJson.getClass()) );
- return (Map<?,?>) decorationJson;
- }
-
- protected List<DT> buildListOfTheseDecorationsFromIterable(Iterable<?> value) {
- List<DT> decorations = MutableList.of();
- for (Object decorationJson: value)
- addDecorationFromJsonMap(checkIsMap(decorationJson), decorations);
- return decorations;
- }
-
- protected abstract String getDecorationKind();
- protected abstract Object getDecorationAttributeJsonValue(ConfigBag attrs);
-
- /** creates and adds decorations from the given json to the given collection;
- * default impl requires a map and calls {@link #addDecorationFromJsonMap(Map, List)} */
- protected void addDecorationFromJson(Object decorationJson, List<DT> decorations) {
- addDecorationFromJsonMap(checkIsMap(decorationJson), decorations);
- }
- protected abstract void addDecorationFromJsonMap(Map<?,?> decorationJson, List<DT> decorations);
-
-
- public static class PolicySpecResolver extends BrooklynEntityDecorationResolver<PolicySpec<?>> {
-
- public PolicySpecResolver(BrooklynYamlTypeInstantiator.Factory loader) { super(loader); }
- @Override protected String getDecorationKind() { return "Policy"; }
-
- @Override
- public void decorate(EntitySpec<?> entitySpec, ConfigBag attrs) {
- entitySpec.policySpecs(buildListOfTheseDecorationsFromEntityAttributes(attrs));
- }
-
- @Override
- protected Object getDecorationAttributeJsonValue(ConfigBag attrs) {
- return attrs.getStringKey(BrooklynCampReservedKeys.BROOKLYN_POLICIES);
- }
-
- @Override
- protected void addDecorationFromJsonMap(Map<?, ?> decorationJson, List<PolicySpec<?>> decorations) {
- InstantiatorFromKey decoLoader = instantiator.from(decorationJson).prefix("policy");
-
- String policyType = decoLoader.getTypeName().get();
- ManagementContext mgmt = instantiator.loader.getManagementContext();
-
- Maybe<RegisteredType> item = RegisteredTypes.tryValidate(mgmt.getTypeRegistry().get(policyType), RegisteredTypeLoadingContexts.spec(Policy.class));
- PolicySpec<?> spec;
- if (!item.isNull()) {
- // throw error if absent for any reason other than null
- spec = mgmt.getTypeRegistry().createSpec(item.get(), null, PolicySpec.class);
- } else {
- Class<? extends Policy> type = decoLoader.getType(Policy.class);
- spec = PolicySpec.create(type)
- .parameters(BasicSpecParameter.fromClass(mgmt, type));
- }
- spec.configure( decoLoader.getConfigMap() );
- decorations.add(spec);
- }
- }
-
- public static class EnricherSpecResolver extends BrooklynEntityDecorationResolver<EnricherSpec<?>> {
-
- public EnricherSpecResolver(BrooklynYamlTypeInstantiator.Factory loader) { super(loader); }
- @Override protected String getDecorationKind() { return "Enricher"; }
-
- @Override
- public void decorate(EntitySpec<?> entitySpec, ConfigBag attrs) {
- entitySpec.enricherSpecs(buildListOfTheseDecorationsFromEntityAttributes(attrs));
- }
-
- @Override
- protected Object getDecorationAttributeJsonValue(ConfigBag attrs) {
- return attrs.getStringKey(BrooklynCampReservedKeys.BROOKLYN_ENRICHERS);
- }
-
- @Override
- protected void addDecorationFromJsonMap(Map<?, ?> decorationJson, List<EnricherSpec<?>> decorations) {
- InstantiatorFromKey decoLoader = instantiator.from(decorationJson).prefix("enricher");
- Class<? extends Enricher> type = decoLoader.getType(Enricher.class);
- decorations.add(EnricherSpec.create(type)
- .configure(decoLoader.getConfigMap())
- .parameters(BasicSpecParameter.fromClass(instantiator.loader.getManagementContext(), type)));
- }
- }
-
- public static class InitializerResolver extends BrooklynEntityDecorationResolver<EntityInitializer> {
-
- public InitializerResolver(BrooklynYamlTypeInstantiator.Factory loader) { super(loader); }
- @Override protected String getDecorationKind() { return "Entity initializer"; }
-
- @Override
- public void decorate(EntitySpec<?> entitySpec, ConfigBag attrs) {
- entitySpec.addInitializers(buildListOfTheseDecorationsFromEntityAttributes(attrs));
- }
-
- @Override
- protected Object getDecorationAttributeJsonValue(ConfigBag attrs) {
- return attrs.getStringKey(BrooklynCampReservedKeys.BROOKLYN_INITIALIZERS);
- }
-
- @Override
- protected void addDecorationFromJsonMap(Map<?, ?> decorationJson, List<EntityInitializer> decorations) {
- decorations.add(instantiator.from(decorationJson).prefix("initializer").newInstance(EntityInitializer.class));
- }
- }
-
- // Not much value from extending from BrooklynEntityDecorationResolver, but let's not break the convention
- public static class SpecParameterResolver extends BrooklynEntityDecorationResolver<SpecParameter<?>> {
-
- protected SpecParameterResolver(BrooklynYamlTypeInstantiator.Factory instantiator) { super(instantiator); }
- @Override protected String getDecorationKind() { return "Spec Parameter initializer"; }
-
- @Override
- public void decorate(EntitySpec<?> entitySpec, ConfigBag attrs) {
- List<? extends SpecParameter<?>> explicitParams = buildListOfTheseDecorationsFromEntityAttributes(attrs);
- // TODO see discussion at EntitySpec.parameters;
- // maybe we should instead inherit always, or
- // inherit except where it is set as config and then add the new explicit ones
- if (!explicitParams.isEmpty()) {
- entitySpec.parameters(explicitParams);
- }
- if (entitySpec.getParameters().isEmpty()) {
- entitySpec.parameters(BasicSpecParameter.fromSpec(instantiator.loader.getManagementContext(), entitySpec));
- }
- }
-
- @Override
- protected List<SpecParameter<?>> buildListOfTheseDecorationsFromIterable(Iterable<?> value) {
- return BasicSpecParameter.fromConfigList(ImmutableList.copyOf(value), instantiator.loader);
- }
-
- @Override
- protected Object getDecorationAttributeJsonValue(ConfigBag attrs) {
- return attrs.getStringKey(BrooklynCampReservedKeys.BROOKLYN_PARAMETERS);
- }
-
- @Override
- protected void addDecorationFromJsonMap(Map<?, ?> decorationJson, List<SpecParameter<?>> decorations) {
- throw new IllegalStateException("Not called");
- }
- }
-
-}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/d03f254b/brooklyn-server/camp/camp-brooklyn/src/main/java/org/apache/brooklyn/camp/brooklyn/spi/creation/BrooklynEntityMatcher.java
----------------------------------------------------------------------
diff --git a/brooklyn-server/camp/camp-brooklyn/src/main/java/org/apache/brooklyn/camp/brooklyn/spi/creation/BrooklynEntityMatcher.java b/brooklyn-server/camp/camp-brooklyn/src/main/java/org/apache/brooklyn/camp/brooklyn/spi/creation/BrooklynEntityMatcher.java
deleted file mode 100644
index 91a490a..0000000
--- a/brooklyn-server/camp/camp-brooklyn/src/main/java/org/apache/brooklyn/camp/brooklyn/spi/creation/BrooklynEntityMatcher.java
+++ /dev/null
@@ -1,180 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.camp.brooklyn.spi.creation;
-
-import java.util.List;
-import java.util.Map;
-
-import org.apache.brooklyn.api.mgmt.ManagementContext;
-import org.apache.brooklyn.api.mgmt.classloading.BrooklynClassLoadingContext;
-import org.apache.brooklyn.camp.brooklyn.BrooklynCampReservedKeys;
-import org.apache.brooklyn.camp.spi.PlatformComponentTemplate;
-import org.apache.brooklyn.camp.spi.PlatformComponentTemplate.Builder;
-import org.apache.brooklyn.camp.spi.pdp.AssemblyTemplateConstructor;
-import org.apache.brooklyn.camp.spi.pdp.Service;
-import org.apache.brooklyn.camp.spi.resolve.PdpMatcher;
-import org.apache.brooklyn.core.catalog.internal.BasicBrooklynCatalog;
-import org.apache.brooklyn.core.mgmt.classloading.JavaBrooklynClassLoadingContext;
-import org.apache.brooklyn.util.collections.MutableMap;
-import org.apache.brooklyn.util.text.Strings;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.common.collect.Lists;
-import com.google.common.collect.Maps;
-
-public class BrooklynEntityMatcher implements PdpMatcher {
-
- private static final Logger log = LoggerFactory.getLogger(BrooklynEntityMatcher.class);
-
- protected final ManagementContext mgmt;
-
- public BrooklynEntityMatcher(ManagementContext bmc) {
- this.mgmt = bmc;
- }
-
- @Override
- public boolean accepts(Object deploymentPlanItem) {
- return lookupType(deploymentPlanItem) != null;
- }
-
- /** returns the type of the given plan item,
- * typically whether a Service can be matched to a Brooklyn entity,
- * or null if not supported */
- protected String lookupType(Object deploymentPlanItem) {
- if (deploymentPlanItem instanceof Service) {
- Service service = (Service)deploymentPlanItem;
-
- String serviceType = service.getServiceType();
- if (serviceType==null) throw new NullPointerException("Service must declare a type ("+service+")");
- BrooklynClassLoadingContext loader = BasicBrooklynCatalog.BrooklynLoaderTracker.getLoader();
- if (loader == null) loader = JavaBrooklynClassLoadingContext.create(mgmt);
- if (BrooklynComponentTemplateResolver.Factory.newInstance(loader, serviceType).canResolve())
- return serviceType;
- }
- return null;
- }
-
- @Override
- public boolean apply(Object deploymentPlanItem, AssemblyTemplateConstructor atc) {
- if (!(deploymentPlanItem instanceof Service)) return false;
-
- String type = lookupType(deploymentPlanItem);
- if (type==null) return false;
-
- log.debug("Item "+deploymentPlanItem+" being instantiated with "+type);
-
- Object old = atc.getInstantiator();
- if (old!=null && !old.equals(BrooklynAssemblyTemplateInstantiator.class)) {
- log.warn("Can't mix Brooklyn entities with non-Brooklyn entities (at present): "+old);
- return false;
- }
-
- // TODO should we build up a new type, BrooklynEntityComponentTemplate here
- // complete w EntitySpec -- ie merge w BrooklynComponentTemplateResolver ?
-
- Builder<? extends PlatformComponentTemplate> builder = PlatformComponentTemplate.builder();
- builder.type( type.indexOf(':')==-1 ? "brooklyn:"+type : type );
-
- // currently instantiator must be brooklyn at the ATC level
- // optionally would be nice to support multiple/mixed instantiators,
- // ie at the component level, perhaps with the first one responsible for building the app
- atc.instantiator(BrooklynAssemblyTemplateInstantiator.class);
-
- String name = ((Service)deploymentPlanItem).getName();
- if (!Strings.isBlank(name)) builder.name(name);
-
- // configuration
- Map<String, Object> attrs = MutableMap.copyOf( ((Service)deploymentPlanItem).getCustomAttributes() );
-
- if (attrs.containsKey("id"))
- builder.customAttribute("planId", attrs.remove("id"));
-
- Object location = attrs.remove("location");
- if (location!=null)
- builder.customAttribute("location", location);
- Object locations = attrs.remove("locations");
- if (locations!=null)
- builder.customAttribute("locations", locations);
-
- MutableMap<Object, Object> brooklynFlags = MutableMap.of();
- Object origBrooklynFlags = attrs.remove(BrooklynCampReservedKeys.BROOKLYN_FLAGS);
- if (origBrooklynFlags!=null) {
- if (!(origBrooklynFlags instanceof Map))
- throw new IllegalArgumentException("brooklyn.flags must be a map of brooklyn flags");
- brooklynFlags.putAll((Map<?,?>)origBrooklynFlags);
- }
-
- addCustomMapAttributeIfNonNull(builder, attrs, BrooklynCampReservedKeys.BROOKLYN_CONFIG);
- addCustomListAttributeIfNonNull(builder, attrs, BrooklynCampReservedKeys.BROOKLYN_POLICIES);
- addCustomListAttributeIfNonNull(builder, attrs, BrooklynCampReservedKeys.BROOKLYN_ENRICHERS);
- addCustomListAttributeIfNonNull(builder, attrs, BrooklynCampReservedKeys.BROOKLYN_INITIALIZERS);
- addCustomListAttributeIfNonNull(builder, attrs, BrooklynCampReservedKeys.BROOKLYN_CHILDREN);
- addCustomListAttributeIfNonNull(builder, attrs, BrooklynCampReservedKeys.BROOKLYN_PARAMETERS);
- addCustomMapAttributeIfNonNull(builder, attrs, BrooklynCampReservedKeys.BROOKLYN_CATALOG);
-
- brooklynFlags.putAll(attrs);
- if (!brooklynFlags.isEmpty()) {
- builder.customAttribute(BrooklynCampReservedKeys.BROOKLYN_FLAGS, brooklynFlags);
- }
-
- atc.add(builder.build());
-
- return true;
- }
-
- /**
- * Looks for the given key in the map of attributes and adds it to the given builder
- * as a custom attribute with type List.
- * @throws java.lang.IllegalArgumentException if map[key] is not an instance of List
- */
- private void addCustomListAttributeIfNonNull(Builder<? extends PlatformComponentTemplate> builder, Map<?,?> attrs, String key) {
- Object items = attrs.remove(key);
- if (items != null) {
- if (items instanceof List) {
- List<?> itemList = (List<?>) items;
- if (!itemList.isEmpty()) {
- builder.customAttribute(key, Lists.newArrayList(itemList));
- }
- } else {
- throw new IllegalArgumentException(key + " must be a list, is: " + items.getClass().getName());
- }
- }
- }
-
- /**
- * Looks for the given key in the map of attributes and adds it to the given builder
- * as a custom attribute with type Map.
- * @throws java.lang.IllegalArgumentException if map[key] is not an instance of Map
- */
- private void addCustomMapAttributeIfNonNull(Builder<? extends PlatformComponentTemplate> builder, Map<?,?> attrs, String key) {
- Object items = attrs.remove(key);
- if (items != null) {
- if (items instanceof Map) {
- Map<?, ?> itemMap = (Map<?, ?>) items;
- if (!itemMap.isEmpty()) {
- builder.customAttribute(key, Maps.newHashMap(itemMap));
- }
- } else {
- throw new IllegalArgumentException(key + " must be a map, is: " + items.getClass().getName());
- }
- }
- }
-
-}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/d03f254b/brooklyn-server/camp/camp-brooklyn/src/main/java/org/apache/brooklyn/camp/brooklyn/spi/creation/BrooklynYamlLocationResolver.java
----------------------------------------------------------------------
diff --git a/brooklyn-server/camp/camp-brooklyn/src/main/java/org/apache/brooklyn/camp/brooklyn/spi/creation/BrooklynYamlLocationResolver.java b/brooklyn-server/camp/camp-brooklyn/src/main/java/org/apache/brooklyn/camp/brooklyn/spi/creation/BrooklynYamlLocationResolver.java
deleted file mode 100644
index 2f8dd99..0000000
--- a/brooklyn-server/camp/camp-brooklyn/src/main/java/org/apache/brooklyn/camp/brooklyn/spi/creation/BrooklynYamlLocationResolver.java
+++ /dev/null
@@ -1,142 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.camp.brooklyn.spi.creation;
-
-import java.util.Arrays;
-import java.util.List;
-import java.util.Map;
-
-import org.apache.brooklyn.api.location.Location;
-import org.apache.brooklyn.api.location.LocationDefinition;
-import org.apache.brooklyn.api.mgmt.ManagementContext;
-import org.apache.brooklyn.util.collections.MutableList;
-import org.apache.brooklyn.util.collections.MutableMap;
-import org.apache.brooklyn.util.exceptions.Exceptions;
-import org.apache.brooklyn.util.guava.Maybe;
-import org.apache.brooklyn.util.guava.Maybe.Absent;
-import org.apache.brooklyn.util.text.Strings;
-
-import com.google.common.collect.Iterables;
-
-public class BrooklynYamlLocationResolver {
-
- protected final ManagementContext mgmt;
-
- public BrooklynYamlLocationResolver(ManagementContext bmc) {
- this.mgmt = bmc;
- }
-
- /** returns list of locations, if any were supplied, or null if none indicated */
- @SuppressWarnings("unchecked")
- public List<Location> resolveLocations(Map<? super String,?> attrs, boolean removeUsedAttributes) {
- Object location = attrs.get("location");
- Object locations = attrs.get("locations");
-
- if (location==null && locations==null)
- return null;
-
- Location locationFromString = null;
- List<Location> locationsFromList = null;
-
- if (location!=null) {
- if (location instanceof String) {
- locationFromString = resolveLocationFromString((String)location);
- } else if (location instanceof Map) {
- locationFromString = resolveLocationFromMap((Map<?,?>)location);
- } else {
- throw new IllegalStateException("Illegal parameter for 'location'; must be a string or map (but got "+location+")");
- }
- }
-
- if (locations!=null) {
- if (!(locations instanceof Iterable))
- throw new IllegalStateException("Illegal parameter for 'locations'; must be an iterable (but got "+locations+")");
- locationsFromList = resolveLocations( (Iterable<Object>)locations );
- }
-
- if (locationFromString!=null && locationsFromList!=null) {
- if (locationsFromList.size() != 1)
- throw new IllegalStateException("Conflicting 'location' and 'locations' ("+location+" and "+locations+"); "
- + "if both are supplied the list must have exactly one element being the same");
- if (!locationFromString.equals( Iterables.getOnlyElement(locationsFromList) ))
- throw new IllegalStateException("Conflicting 'location' and 'locations' ("+location+" and "+locations+"); "
- + "different location specified in each");
- } else if (locationFromString!=null) {
- locationsFromList = Arrays.asList(locationFromString);
- }
-
- return locationsFromList;
- }
-
- public List<Location> resolveLocations(Iterable<Object> locations) {
- List<Location> result = MutableList.of();
- for (Object l: locations) {
- Location ll = resolveLocation(l);
- if (ll!=null) result.add(ll);
- }
- return result;
- }
-
- public Location resolveLocation(Object location) {
- if (location instanceof String) {
- return resolveLocationFromString((String)location);
- } else if (location instanceof Map) {
- return resolveLocationFromMap((Map<?,?>)location);
- }
- // could support e.g. location definition
- throw new IllegalStateException("Illegal parameter for 'location' ("+location+"); must be a string or map");
- }
-
- /** resolves the location from the given spec string, either "Named Location", or "named:Named Location" format;
- * returns null if input is blank (or null); otherwise guaranteed to resolve or throw error */
- public Location resolveLocationFromString(String location) {
- if (Strings.isBlank(location)) return null;
- return resolveLocation(location, MutableMap.of());
- }
-
- public Location resolveLocationFromMap(Map<?,?> location) {
- if (location.size() > 1) {
- throw new IllegalStateException("Illegal parameter for 'location'; expected a single entry in map ("+location+")");
- }
- Object key = Iterables.getOnlyElement(location.keySet());
- Object value = location.get(key);
-
- if (!(key instanceof String)) {
- throw new IllegalStateException("Illegal parameter for 'location'; expected String key ("+location+")");
- }
- if (!(value instanceof Map)) {
- throw new IllegalStateException("Illegal parameter for 'location'; expected config map ("+location+")");
- }
- return resolveLocation((String)key, (Map<?,?>)value);
- }
-
- protected Location resolveLocation(String spec, Map<?,?> flags) {
- LocationDefinition ldef = mgmt.getLocationRegistry().getDefinedLocationByName((String)spec);
- if (ldef!=null)
- // found it as a named location
- return mgmt.getLocationRegistry().resolve(ldef, null, flags).get();
-
- Maybe<Location> l = mgmt.getLocationRegistry().resolve(spec, null, flags);
- if (l.isPresent()) return l.get();
-
- RuntimeException exception = ((Absent<?>)l).getException();
- throw new IllegalStateException("Illegal parameter for 'location' ("+spec+"); not resolvable: "+
- Exceptions.collapseText( exception ), exception);
- }
-}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/d03f254b/brooklyn-server/camp/camp-brooklyn/src/main/java/org/apache/brooklyn/camp/brooklyn/spi/creation/BrooklynYamlTypeInstantiator.java
----------------------------------------------------------------------
diff --git a/brooklyn-server/camp/camp-brooklyn/src/main/java/org/apache/brooklyn/camp/brooklyn/spi/creation/BrooklynYamlTypeInstantiator.java b/brooklyn-server/camp/camp-brooklyn/src/main/java/org/apache/brooklyn/camp/brooklyn/spi/creation/BrooklynYamlTypeInstantiator.java
deleted file mode 100644
index 01bfaa2..0000000
--- a/brooklyn-server/camp/camp-brooklyn/src/main/java/org/apache/brooklyn/camp/brooklyn/spi/creation/BrooklynYamlTypeInstantiator.java
+++ /dev/null
@@ -1,209 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.camp.brooklyn.spi.creation;
-
-import java.util.Map;
-
-import javax.annotation.Nonnull;
-import javax.annotation.Nullable;
-
-import org.apache.brooklyn.api.mgmt.classloading.BrooklynClassLoadingContext;
-import org.apache.brooklyn.camp.brooklyn.BrooklynCampReservedKeys;
-import org.apache.brooklyn.util.collections.MutableMap;
-import org.apache.brooklyn.util.core.config.ConfigBag;
-import org.apache.brooklyn.util.exceptions.Exceptions;
-import org.apache.brooklyn.util.guava.Maybe;
-import org.apache.brooklyn.util.javalang.Reflections;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.common.annotations.Beta;
-import com.google.common.base.Optional;
-import com.google.common.base.Preconditions;
-
-/** Assists in loading types referenced from YAML;
- * mainly as a way to share logic used in very different contexts. */
-public abstract class BrooklynYamlTypeInstantiator {
-
- private static final Logger log = LoggerFactory.getLogger(BrooklynYamlTypeInstantiator.class);
-
- protected final Factory factory;
-
- @Beta
- public static class Factory {
- final BrooklynClassLoadingContext loader;
- final Object contextForLogging;
-
- public Factory(BrooklynClassLoadingContext loader, Object contextForLogging) {
- this.loader = loader;
- this.contextForLogging = contextForLogging;
- }
-
- public InstantiatorFromKey from(Map<?,?> data) {
- return new InstantiatorFromKey(this, ConfigBag.newInstance(data));
- }
-
- public InstantiatorFromKey from(ConfigBag data) {
- return new InstantiatorFromKey(this, data);
- }
-
- public InstantiatorFromName type(String typeName) {
- return new InstantiatorFromName(this, typeName);
- }
-
- }
-
- public static class InstantiatorFromKey extends BrooklynYamlTypeInstantiator {
- protected final ConfigBag data;
- protected String typeKeyPrefix = null;
-
- /** Nullable only permitted for instances which do not do loading, e.g. LoaderFromKey#lookup */
- protected InstantiatorFromKey(@Nullable Factory factory, ConfigBag data) {
- super(factory);
- this.data = data;
- }
-
- public static Maybe<String> extractTypeName(String prefix, ConfigBag data) {
- if (data==null) return Maybe.absent();
- return new InstantiatorFromKey(null, data).prefix(prefix).getTypeName();
- }
-
- public InstantiatorFromKey prefix(String prefix) {
- typeKeyPrefix = prefix;
- return this;
- }
-
- @Override
- public Maybe<String> getTypeName() {
- Maybe<Object> result = data.getStringKeyMaybe(getPreferredKeyName());
- if (result.isAbsent() && typeKeyPrefix!=null) {
- // try alternatives if a prefix was specified
- result = data.getStringKeyMaybe(typeKeyPrefix+"Type");
- if (result.isAbsent()) result = data.getStringKeyMaybe("type");
- }
-
- if (result.isAbsent() || result.get()==null)
- return Maybe.absent("Missing key '"+getPreferredKeyName()+"'");
-
- if (result.get() instanceof String) return Maybe.of((String)result.get());
-
- throw new IllegalArgumentException("Invalid value "+result.get().getClass()+" for "+getPreferredKeyName()+"; "
- + "expected String, got "+result.get());
- }
-
- protected String getPreferredKeyName() {
- if (typeKeyPrefix!=null) return typeKeyPrefix+"_type";
- return "type";
- }
-
- /** as {@link #newInstance(Class)} but inferring the type */
- public Object newInstance() {
- return newInstance(null);
- }
-
- /** creates a new instance of the type referred to by this description,
- * as a subtype of the type supplied here,
- * inferring a Map from <code>brooklyn.config</code> key.
- * TODO in future also picking up recognized flags and config keys (those declared on the type).
- * <p>
- * constructs the object using:
- * <li> a constructor on the class taking a Map
- * <li> a no-arg constructor, only if the inferred map is empty
- **/
- public <T> T newInstance(@Nullable Class<T> supertype) {
- Class<? extends T> type = getType(supertype);
- Map<String, ?> cfg = getConfigMap();
- Optional<? extends T> result = Reflections.invokeConstructorWithArgs(type, cfg);
- if (result.isPresent())
- return result.get();
-
- ConfigBag cfgBag = ConfigBag.newInstance(cfg);
- result = Reflections.invokeConstructorWithArgs(type, cfgBag);
- if (result.isPresent())
- return result.get();
-
- if (cfg.isEmpty()) {
- result = Reflections.invokeConstructorWithArgs(type);
- if (result.isPresent())
- return result.get();
- }
-
- throw new IllegalStateException("No known mechanism for constructing type "+type+" in "+factory.contextForLogging);
- }
-
- /** finds the map of config for the type specified;
- * currently only gets <code>brooklyn.config</code>, returning empty map if none,
- * but TODO in future should support recognized flags and config keys (those declared on the type),
- * incorporating code in {@link BrooklynEntityMatcher}.
- */
- @SuppressWarnings("unchecked")
- @Nonnull
- public Map<String,?> getConfigMap() {
- MutableMap<String,Object> result = MutableMap.of();
- Object bc = data.getStringKey(BrooklynCampReservedKeys.BROOKLYN_CONFIG);
- if (bc!=null) {
- if (bc instanceof Map)
- result.putAll((Map<? extends String, ?>) bc);
- else
- throw new IllegalArgumentException("brooklyn.config key in "+factory.contextForLogging+" should be a map, not "+bc.getClass()+" ("+bc+")");
- }
- return result;
- }
-
- }
-
- public static class InstantiatorFromName extends BrooklynYamlTypeInstantiator {
- protected final String typeName;
- protected InstantiatorFromName(Factory factory, String typeName) {
- super(factory);
- this.typeName = typeName;
- }
-
- @Override
- public Maybe<String> getTypeName() {
- return Maybe.fromNullable(typeName);
- }
- }
-
- protected BrooklynYamlTypeInstantiator(Factory factory) {
- this.factory = factory;
- }
-
- public abstract Maybe<String> getTypeName();
-
- public BrooklynClassLoadingContext getClassLoadingContext() {
- Preconditions.checkNotNull(factory, "No factory set; cannot use this instance for type loading");
- return factory.loader;
- }
-
- public Class<?> getType() {
- return getType(Object.class);
- }
-
- public <T> Class<? extends T> getType(@Nonnull Class<T> type) {
- try {
- return getClassLoadingContext().loadClass(getTypeName().get(), type);
- } catch (Exception e) {
- Exceptions.propagateIfFatal(e);
- log.debug("Unable to resolve " + type + " " + getTypeName().get() + " (rethrowing) in spec " + factory.contextForLogging);
- throw Exceptions.propagate(e);
- }
- }
-
-}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/d03f254b/brooklyn-server/camp/camp-brooklyn/src/main/java/org/apache/brooklyn/camp/brooklyn/spi/creation/CampCatalogUtils.java
----------------------------------------------------------------------
diff --git a/brooklyn-server/camp/camp-brooklyn/src/main/java/org/apache/brooklyn/camp/brooklyn/spi/creation/CampCatalogUtils.java b/brooklyn-server/camp/camp-brooklyn/src/main/java/org/apache/brooklyn/camp/brooklyn/spi/creation/CampCatalogUtils.java
deleted file mode 100644
index 706d6f2..0000000
--- a/brooklyn-server/camp/camp-brooklyn/src/main/java/org/apache/brooklyn/camp/brooklyn/spi/creation/CampCatalogUtils.java
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.camp.brooklyn.spi.creation;
-
-import java.util.Set;
-
-import org.apache.brooklyn.api.catalog.CatalogItem;
-import org.apache.brooklyn.api.internal.AbstractBrooklynObjectSpec;
-import org.apache.brooklyn.api.mgmt.ManagementContext;
-import org.apache.brooklyn.camp.CampPlatform;
-import org.apache.brooklyn.core.typereg.RegisteredTypes;
-
-@Deprecated /** @deprecated since 0.9.0 use RegisteredType and CampResolver */
-public class CampCatalogUtils {
-
- public static AbstractBrooklynObjectSpec<?, ?> createSpec(ManagementContext mgmt, CatalogItem<?, ?> item, Set<String> parentEncounteredTypes) {
- return CampResolver.createSpecFromFull(mgmt, RegisteredTypes.of(item), item.getCatalogItemJavaType(), parentEncounteredTypes, null);
- }
-
- public static CampPlatform getCampPlatform(ManagementContext mgmt) {
- return CampInternalUtils.getCampPlatform(mgmt);
- }
-
-}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/d03f254b/brooklyn-server/camp/camp-brooklyn/src/main/java/org/apache/brooklyn/camp/brooklyn/spi/creation/CampInternalUtils.java
----------------------------------------------------------------------
diff --git a/brooklyn-server/camp/camp-brooklyn/src/main/java/org/apache/brooklyn/camp/brooklyn/spi/creation/CampInternalUtils.java b/brooklyn-server/camp/camp-brooklyn/src/main/java/org/apache/brooklyn/camp/brooklyn/spi/creation/CampInternalUtils.java
deleted file mode 100644
index 9096168..0000000
--- a/brooklyn-server/camp/camp-brooklyn/src/main/java/org/apache/brooklyn/camp/brooklyn/spi/creation/CampInternalUtils.java
+++ /dev/null
@@ -1,247 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.camp.brooklyn.spi.creation;
-
-import static com.google.common.base.Preconditions.checkNotNull;
-
-import java.io.StringReader;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Set;
-
-import org.apache.brooklyn.api.entity.Application;
-import org.apache.brooklyn.api.entity.EntitySpec;
-import org.apache.brooklyn.api.internal.AbstractBrooklynObjectSpec;
-import org.apache.brooklyn.api.location.Location;
-import org.apache.brooklyn.api.location.LocationSpec;
-import org.apache.brooklyn.api.mgmt.ManagementContext;
-import org.apache.brooklyn.api.mgmt.classloading.BrooklynClassLoadingContext;
-import org.apache.brooklyn.api.objs.SpecParameter;
-import org.apache.brooklyn.api.policy.Policy;
-import org.apache.brooklyn.api.policy.PolicySpec;
-import org.apache.brooklyn.api.typereg.RegisteredType;
-import org.apache.brooklyn.camp.CampPlatform;
-import org.apache.brooklyn.camp.brooklyn.BrooklynCampConstants;
-import org.apache.brooklyn.camp.brooklyn.BrooklynCampReservedKeys;
-import org.apache.brooklyn.camp.spi.AssemblyTemplate;
-import org.apache.brooklyn.camp.spi.AssemblyTemplate.Builder;
-import org.apache.brooklyn.camp.spi.instantiate.AssemblyTemplateInstantiator;
-import org.apache.brooklyn.camp.spi.pdp.DeploymentPlan;
-import org.apache.brooklyn.core.catalog.internal.BasicBrooklynCatalog;
-import org.apache.brooklyn.core.catalog.internal.BasicBrooklynCatalog.BrooklynLoaderTracker;
-import org.apache.brooklyn.core.objs.BasicSpecParameter;
-import org.apache.brooklyn.core.objs.BrooklynObjectInternal.ConfigurationSupportInternal;
-import org.apache.brooklyn.entity.stock.BasicApplicationImpl;
-import org.apache.brooklyn.util.exceptions.Exceptions;
-import org.apache.brooklyn.util.guava.Maybe;
-import org.apache.brooklyn.util.stream.Streams;
-import org.apache.brooklyn.util.yaml.Yamls;
-
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.ImmutableSet;
-import com.google.common.collect.Iterables;
-
-/** package-private; as {@link RegisteredType} becomes standard hopefully we can remove this */
-class CampInternalUtils {
-
- static EntitySpec<? extends Application> createWrapperApp(AssemblyTemplate template, BrooklynClassLoadingContext loader) {
- BrooklynComponentTemplateResolver resolver = BrooklynComponentTemplateResolver.Factory.newInstance(
- loader, buildWrapperAppTemplate(template));
- EntitySpec<Application> wrapperSpec = resolver.resolveSpec(ImmutableSet.<String>of());
- resetSpecIfTemplateHasNoExplicitParameters(template, wrapperSpec);
- // caller always sets WRAPPER_APP config; should we do it here?
- return wrapperSpec;
- }
-
- static void resetSpecIfTemplateHasNoExplicitParameters(AssemblyTemplate template, EntitySpec<? extends Application> wrapperSpec) {
- if (!template.getCustomAttributes().containsKey(BrooklynCampReservedKeys.BROOKLYN_PARAMETERS)) {
- // Clear out default parameters (coming from the wrapper app's class) so they don't overwrite the entity's params on unwrap.
- wrapperSpec.parameters(ImmutableList.<SpecParameter<?>>of());
- }
- }
-
- private static AssemblyTemplate buildWrapperAppTemplate(AssemblyTemplate template) {
- Builder<? extends AssemblyTemplate> builder = AssemblyTemplate.builder();
- builder.type("brooklyn:" + BasicApplicationImpl.class.getName());
- builder.id(template.getId());
- builder.name(template.getName());
- builder.sourceCode(template.getSourceCode());
- for (Entry<String, Object> entry : template.getCustomAttributes().entrySet()) {
- builder.customAttribute(entry.getKey(), entry.getValue());
- }
- builder.instantiator(template.getInstantiator());
- AssemblyTemplate wrapTemplate = builder.build();
- return wrapTemplate;
- }
-
- static AssemblyTemplateInstantiator getInstantiator(AssemblyTemplate at) {
- try {
- return at.getInstantiator().newInstance();
- } catch (Exception e) {
- throw Exceptions.propagate(e);
- }
- }
-
- static AssemblyTemplate registerDeploymentPlan(String plan, BrooklynClassLoadingContext loader, CampPlatform camp) {
- BrooklynLoaderTracker.setLoader(loader);
- try {
- return camp.pdp().registerDeploymentPlan(new StringReader(plan));
- } finally {
- BrooklynLoaderTracker.unsetLoader(loader);
- }
- }
-
- static PolicySpec<?> createPolicySpec(String yamlPlan, BrooklynClassLoadingContext loader, Set<String> encounteredCatalogTypes) {
- DeploymentPlan plan = makePlanFromYaml(loader.getManagementContext(), yamlPlan);
-
- //Would ideally re-use the PolicySpecResolver
- //but it is CAMP specific and there is no easy way to get hold of it.
- Object policies = checkNotNull(plan.getCustomAttributes().get(BasicBrooklynCatalog.POLICIES_KEY), "policy config");
- if (!(policies instanceof Iterable<?>)) {
- throw new IllegalStateException("The value of " + BasicBrooklynCatalog.POLICIES_KEY + " must be an Iterable.");
- }
-
- Object policy = Iterables.getOnlyElement((Iterable<?>)policies);
-
- return createPolicySpec(loader, policy, encounteredCatalogTypes);
- }
-
- @SuppressWarnings("unchecked")
- static PolicySpec<?> createPolicySpec(BrooklynClassLoadingContext loader, Object policy, Set<String> encounteredCatalogTypes) {
- Map<String, Object> itemMap;
- if (policy instanceof String) {
- itemMap = ImmutableMap.<String, Object>of("type", policy);
- } else if (policy instanceof Map) {
- itemMap = (Map<String, Object>) policy;
- } else {
- throw new IllegalStateException("Policy expected to be string or map. Unsupported object type " + policy.getClass().getName() + " (" + policy.toString() + ")");
- }
-
- String versionedId = (String) checkNotNull(Yamls.getMultinameAttribute(itemMap, "policy_type", "policyType", "type"), "policy type");
- PolicySpec<? extends Policy> spec = resolvePolicySpec(versionedId, loader, encounteredCatalogTypes);
- Map<String, Object> brooklynConfig = (Map<String, Object>) itemMap.get(BrooklynCampReservedKeys.BROOKLYN_CONFIG);
- if (brooklynConfig != null) {
- spec.configure(brooklynConfig);
- }
- List<?> parameters = (List<?>) itemMap.get(BrooklynCampReservedKeys.BROOKLYN_PARAMETERS);
- initParameters(parameters, spec, loader);
- return spec;
- }
-
- static LocationSpec<?> createLocationSpec(String yamlPlan, BrooklynClassLoadingContext loader, Set<String> encounteredTypes) {
- DeploymentPlan plan = makePlanFromYaml(loader.getManagementContext(), yamlPlan);
- Object locations = checkNotNull(plan.getCustomAttributes().get(BasicBrooklynCatalog.LOCATIONS_KEY), "location config");
- if (!(locations instanceof Iterable<?>)) {
- throw new IllegalStateException("The value of " + BasicBrooklynCatalog.LOCATIONS_KEY + " must be an Iterable.");
- }
-
- Object location = Iterables.getOnlyElement((Iterable<?>)locations);
- return createLocationSpec(loader, location);
- }
-
- @SuppressWarnings("unchecked")
- private static LocationSpec<?> createLocationSpec(BrooklynClassLoadingContext loader, Object location) {
- Map<String, Object> itemMap;
- if (location instanceof String) {
- itemMap = ImmutableMap.<String, Object>of("type", location);
- } else if (location instanceof Map) {
- itemMap = (Map<String, Object>) location;
- } else {
- throw new IllegalStateException("Location expected to be string or map. Unsupported object type " + location.getClass().getName() + " (" + location.toString() + ")");
- }
-
- String type = (String) checkNotNull(Yamls.getMultinameAttribute(itemMap, "location_type", "locationType", "type"), "location type");
- Map<String, Object> brooklynConfig = (Map<String, Object>) itemMap.get("brooklyn.config");
- LocationSpec<?> locationSpec = resolveLocationSpec(type, brooklynConfig, loader);
- List<?> explicitParams = (List<?>) itemMap.get(BrooklynCampReservedKeys.BROOKLYN_PARAMETERS);
- initParameters(explicitParams, locationSpec, loader);
- return locationSpec;
- }
-
- private static void initParameters(List<?> explicitParams, AbstractBrooklynObjectSpec<?, ?> spec, BrooklynClassLoadingContext loader) {
- if (explicitParams != null) {
- spec.parameters(BasicSpecParameter.fromConfigList(explicitParams, loader));
- } else {
- spec.parameters(BasicSpecParameter.fromSpec(loader.getManagementContext(), spec));
- }
- }
-
- public static DeploymentPlan makePlanFromYaml(ManagementContext mgmt, String yaml) {
- CampPlatform camp = getCampPlatform(mgmt);
- return camp.pdp().parseDeploymentPlan(Streams.newReaderWithContents(yaml));
- }
-
- public static CampPlatform getCampPlatform(ManagementContext mgmt) {
- CampPlatform result = mgmt.getConfig().getConfig(BrooklynCampConstants.CAMP_PLATFORM);
- if (result!=null) {
- return result;
- } else {
- throw new IllegalStateException("No CAMP Platform is registered with this Brooklyn management context.");
- }
- }
-
- @SuppressWarnings("unchecked")
- private static PolicySpec<? extends Policy> resolvePolicySpec(
- String versionedId,
- BrooklynClassLoadingContext loader,
- Set<String> encounteredCatalogTypes) {
-
- PolicySpec<? extends Policy> spec;
- RegisteredType item = loader.getManagementContext().getTypeRegistry().get(versionedId);
- if (item != null && !encounteredCatalogTypes.contains(item.getSymbolicName())) {
- return loader.getManagementContext().getTypeRegistry().createSpec(item, null, PolicySpec.class);
- } else {
- // TODO-type-registry pass the loader in to the above, and allow it to load with the loader
- spec = PolicySpec.create(loader.loadClass(versionedId, Policy.class));
- }
- return spec;
- }
-
- private static LocationSpec<?> resolveLocationSpec(
- String type,
- Map<String, Object> brooklynConfig,
- BrooklynClassLoadingContext loader) {
- Maybe<Class<? extends Location>> javaClass = loader.tryLoadClass(type, Location.class);
- if (javaClass.isPresent()) {
- LocationSpec<?> spec = LocationSpec.create(javaClass.get());
- if (brooklynConfig != null) {
- spec.configure(brooklynConfig);
- }
- return spec;
- } else {
- Maybe<Location> loc = loader.getManagementContext().getLocationRegistry().resolve(type, false, brooklynConfig);
- if (loc.isPresent()) {
- // TODO extensions?
- Map<String, Object> locConfig = ((ConfigurationSupportInternal)loc.get().config()).getBag().getAllConfig();
- Class<? extends Location> locType = loc.get().getClass();
- Set<Object> locTags = loc.get().tags().getTags();
- String locDisplayName = loc.get().getDisplayName();
- return LocationSpec.create(locType)
- .configure(locConfig)
- .displayName(locDisplayName)
- .tags(locTags);
- } else {
- throw new IllegalStateException("No class or resolver found for location type "+type);
- }
- }
- }
-
-}