http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/d03f254b/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/entity/drivers/downloads/DownloadSubstituters.java ---------------------------------------------------------------------- diff --git a/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/entity/drivers/downloads/DownloadSubstituters.java b/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/entity/drivers/downloads/DownloadSubstituters.java deleted file mode 100644 index 64a081c..0000000 --- a/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/entity/drivers/downloads/DownloadSubstituters.java +++ /dev/null @@ -1,172 +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.core.entity.drivers.downloads; - -import static com.google.common.base.Preconditions.checkNotNull; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.OutputStreamWriter; -import java.io.Writer; -import java.util.Map; - -import org.apache.brooklyn.api.entity.Entity; -import org.apache.brooklyn.api.entity.drivers.EntityDriver; -import org.apache.brooklyn.api.entity.drivers.downloads.DownloadResolverManager.DownloadRequirement; -import org.apache.brooklyn.api.entity.drivers.downloads.DownloadResolverManager.DownloadTargets; -import org.apache.brooklyn.core.entity.BrooklynConfigKeys; -import org.apache.brooklyn.util.collections.MutableMap; -import org.apache.brooklyn.util.exceptions.Exceptions; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.google.common.base.Function; -import com.google.common.base.Objects; - -import freemarker.cache.StringTemplateLoader; -import freemarker.template.Configuration; -import freemarker.template.Template; -import freemarker.template.TemplateException; - -public class DownloadSubstituters { - - private static final Logger LOG = LoggerFactory.getLogger(DownloadSubstituters.class); - - static { - // TODO in Freemarker 2.4 SLF4J may be auto-selected and we can remove this; - // for now, we need it somewhere, else we get j.u.l logging; - // since this is the main place it is used, let's do it here - try { - LOG.debug("Configuring Freemarker logging for Brooklyn to use SLF4J"); - System.setProperty(freemarker.log.Logger.SYSTEM_PROPERTY_NAME_LOGGER_LIBRARY, freemarker.log.Logger.LIBRARY_NAME_SLF4J); - } catch (Exception e) { - LOG.warn("Error setting Freemarker logging: "+e, e); - } - } - - private DownloadSubstituters() {} - - /** - * Converts the basevalue by substituting things in the form ${key} for values specific - * to a given entity driver. The keys used are: - * <ul> - * <li>driver: the driver instance (e.g. can do freemarker.org stuff like ${driver.osTag} to call {@code driver.getOsTag()}) - * <li>entity: the entity instance - * <li>type: the fully qualified type name of the entity - * <li>simpletype: the unqualified type name of the entity - * <li>addon: the name of the add-on, or null if for the entity's main artifact - * <li>version: the version for this entity (or of the add-on), or not included if null - * </ul> - * - * Additional substitution keys (and values) can be defined using {@link DownloadRequirement#getProperties()}; these - * override the default substitutions listed above. - */ - public static String substitute(DownloadRequirement req, String basevalue) { - return substitute(basevalue, getBasicSubstitutions(req)); - } - - public static Map<String,Object> getBasicSubstitutions(DownloadRequirement req) { - EntityDriver driver = req.getEntityDriver(); - String addon = req.getAddonName(); - Map<String, ?> props = req.getProperties(); - - if (addon == null) { - return MutableMap.<String,Object>builder() - .putAll(getBasicEntitySubstitutions(driver)) - .putAll(props) - .build(); - } else { - return MutableMap.<String,Object>builder() - .putAll(getBasicAddonSubstitutions(driver, addon)) - .putAll(props) - .build(); - } - } - - public static Map<String,Object> getBasicEntitySubstitutions(EntityDriver driver) { - Entity entity = driver.getEntity(); - String type = entity.getEntityType().getName(); - String simpleType = type.substring(type.lastIndexOf(".")+1); - String version = entity.getConfig(BrooklynConfigKeys.SUGGESTED_VERSION); - - return MutableMap.<String,Object>builder() - .put("entity", entity) - .put("driver", driver) - .put("type", type) - .put("simpletype", simpleType) - .putIfNotNull("version", version) - .build(); - } - - public static Map<String,Object> getBasicAddonSubstitutions(EntityDriver driver, String addon) { - return MutableMap.<String,Object>builder() - .putAll(getBasicEntitySubstitutions(driver)) - .put("addon", addon) - .build(); - } - - public static String substitute(String basevalue, Map<String,?> substitutions) { - try { - Configuration cfg = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS); - StringTemplateLoader templateLoader = new StringTemplateLoader(); - templateLoader.putTemplate("config", basevalue); - cfg.setTemplateLoader(templateLoader); - Template template = cfg.getTemplate("config"); - - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - Writer out = new OutputStreamWriter(baos); - template.process(substitutions, out); - out.flush(); - - return new String(baos.toByteArray()); - } catch (IOException e) { - LOG.warn("Error processing template '"+basevalue+"'", e); - throw Exceptions.propagate(e); - } catch (TemplateException e) { - throw new IllegalArgumentException("Failed to process driver download '"+basevalue+"'", e); - } - } - - public static Function<DownloadRequirement, DownloadTargets> substituter(Function<? super DownloadRequirement, String> basevalueProducer, Function<? super DownloadRequirement, ? extends Map<String,?>> subsProducer) { - // FIXME Also need default subs (entity, driver, simpletype, etc) - return new Substituter(basevalueProducer, subsProducer); - } - - protected static class Substituter implements Function<DownloadRequirement, DownloadTargets> { - private final Function<? super DownloadRequirement, String> basevalueProducer; - private final Function<? super DownloadRequirement, ? extends Map<String,?>> subsProducer; - - Substituter(Function<? super DownloadRequirement, String> baseValueProducer, Function<? super DownloadRequirement, ? extends Map<String,?>> subsProducer) { - this.basevalueProducer = checkNotNull(baseValueProducer, "basevalueProducer"); - this.subsProducer = checkNotNull(subsProducer, "subsProducer"); - } - - @Override - public DownloadTargets apply(DownloadRequirement input) { - String basevalue = basevalueProducer.apply(input); - Map<String, ?> subs = subsProducer.apply(input); - String result = (basevalue != null) ? substitute(basevalue, subs) : null; - return (result != null) ? BasicDownloadTargets.builder().addPrimary(result).build() : BasicDownloadTargets.empty(); - } - - @Override public String toString() { - return Objects.toStringHelper(this).add("basevalue", basevalueProducer).add("subs", subsProducer).toString(); - } - } -}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/d03f254b/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/entity/drivers/downloads/FilenameProducers.java ---------------------------------------------------------------------- diff --git a/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/entity/drivers/downloads/FilenameProducers.java b/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/entity/drivers/downloads/FilenameProducers.java deleted file mode 100644 index 18240f1..0000000 --- a/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/entity/drivers/downloads/FilenameProducers.java +++ /dev/null @@ -1,64 +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.core.entity.drivers.downloads; - -import java.util.List; - -import javax.annotation.Nullable; - -import org.apache.brooklyn.api.entity.drivers.downloads.DownloadResolverManager.DownloadRequirement; -import org.apache.brooklyn.api.entity.drivers.downloads.DownloadResolverManager.DownloadTargets; -import org.apache.brooklyn.util.text.Strings; - -import com.google.common.base.Function; - -public class FilenameProducers { - - public static String inferFilename(String target) { - String result = target.substring(target.lastIndexOf("/")+1); - result = result.contains("?") ? result.substring(0, result.indexOf("?")) : result; - if (!result.contains(".")) - // require a full stop, else assume it isn't a filename - return null; - return result; - } - - public static Function<DownloadRequirement, String> fromFilenameProperty() { - return new Function<DownloadRequirement, String>() { - @Override public String apply(@Nullable DownloadRequirement req) { - Object filename = req.getProperties().get("filename"); - return (filename != null) ? filename.toString() : null; - } - }; - } - - public static Function<DownloadRequirement, String> firstPrimaryTargetOf(final Function<DownloadRequirement, DownloadTargets> producer) { - return new Function<DownloadRequirement, String>() { - @Override public String apply(@Nullable DownloadRequirement req) { - DownloadTargets targets = producer.apply(req); - List<String> primaryTargets = targets.getPrimaryLocations(); - for (String primaryTarget : primaryTargets) { - String result = inferFilename(primaryTarget); - if (!Strings.isBlank(result)) return result; - } - return null; - } - }; - } -} http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/d03f254b/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/entity/factory/AbstractConfigurableEntityFactory.java ---------------------------------------------------------------------- diff --git a/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/entity/factory/AbstractConfigurableEntityFactory.java b/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/entity/factory/AbstractConfigurableEntityFactory.java deleted file mode 100644 index 6b41e4b..0000000 --- a/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/entity/factory/AbstractConfigurableEntityFactory.java +++ /dev/null @@ -1,82 +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.core.entity.factory; - -import java.io.Serializable; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.Map; - -import org.apache.brooklyn.api.entity.Entity; -import org.apache.brooklyn.config.ConfigKey; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public abstract class AbstractConfigurableEntityFactory<T extends Entity> implements ConfigurableEntityFactory<T>, Serializable { - private static final Logger log = LoggerFactory.getLogger(AbstractConfigurableEntityFactory.class); - - protected final Map config = new LinkedHashMap(); - - public AbstractConfigurableEntityFactory(){ - this(new HashMap()); - } - - public AbstractConfigurableEntityFactory(Map flags) { - this.config.putAll(flags); - - } - public AbstractConfigurableEntityFactory<T> configure(Map flags) { - config.putAll(flags); - return this; - } - - public AbstractConfigurableEntityFactory<T> configure(ConfigKey key, Object value) { - config.put(key, value); - return this; - } - - public AbstractConfigurableEntityFactory<T> configure(ConfigKey.HasConfigKey key, Object value) { - return setConfig(key.getConfigKey(), value); - } - - public AbstractConfigurableEntityFactory<T> setConfig(ConfigKey key, Object value) { - return configure(key, value); - } - - public AbstractConfigurableEntityFactory<T> setConfig(ConfigKey.HasConfigKey key, Object value) { - return configure(key.getConfigKey(), value); - } - - public T newEntity(Entity parent){ - return newEntity(new HashMap(),parent); - } - - public T newEntity(Map flags, Entity parent) { - Map flags2 = new HashMap(); - flags2.putAll(config); - flags2.putAll(flags); - T result = newEntity2(flags2, parent); - // we rely increasingly on init, which factory doesn't call; really should remove factories! - log.warn("Deprecated legacy compatibility, using factory (init will not be invoked): "+result); - return result; - } - - public abstract T newEntity2(Map flags, Entity parent); -} - http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/d03f254b/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/entity/factory/ApplicationBuilder.java ---------------------------------------------------------------------- diff --git a/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/entity/factory/ApplicationBuilder.java b/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/entity/factory/ApplicationBuilder.java deleted file mode 100644 index 66f4795..0000000 --- a/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/entity/factory/ApplicationBuilder.java +++ /dev/null @@ -1,249 +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.core.entity.factory; - -import static com.google.common.base.Preconditions.checkNotNull; - -import java.util.Map; -import java.util.concurrent.atomic.AtomicBoolean; - -import org.apache.brooklyn.api.entity.Entity; -import org.apache.brooklyn.api.entity.EntitySpec; -import org.apache.brooklyn.api.mgmt.EntityManager; -import org.apache.brooklyn.api.mgmt.ManagementContext; -import org.apache.brooklyn.core.entity.Entities; -import org.apache.brooklyn.core.entity.StartableApplication; -import org.apache.brooklyn.entity.stock.BasicApplication; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.google.common.annotations.Beta; - -/** - * Experimental mechanism for defining/building applications. In future releases, this - * API will change. Its concepts will most likely be merged with a TOSCA implementation - * and with {@link EntitySpec}. - * - * For building an application. Users can sub-class and override doBuild(), putting the logic for - * creating and wiring together entities in there. - * - * The builder is mutable; a given instance should be used to build only a single application. - * Once {@link #manage()} has been called, the application will be built and no additional configuration - * should be performed through this builder. - * - * Example (simplified) code for sub-classing is: - * <pre> - * {@code - * app = new ApplicationBuilder() { - * //@Override - * public void doBuild() { - * MySqlNode db = addChild(EntitySpec.create(MySqlNode.class))); - * JBoss7Server as = addChild(EntitySpec.create(JBoss7Server.class) - * .configure(HTTP_PORT, "8080+") - * .configure(javaSysProp("brooklyn.example.db.url"), attributeWhenReady(db, MySqlNode.MYSQL_URL)); - * } - * }.manage(); - * } - * </pre> - * - * @author aled - * - * @deprecated since 0.9.0; use {@link EntitySpec} and {@link EntityManager#createEntity(EntitySpec)}, having - * added the children to the spec etc. - */ -@Deprecated -@Beta -public abstract class ApplicationBuilder { - - @SuppressWarnings("unused") - private static final Logger LOG = LoggerFactory.getLogger(ApplicationBuilder.class); - - @SuppressWarnings("unchecked") - @Beta - /** @deprecated since 0.7.0 the management context should normally be passed in; - * for TestApplication also see TestApplication.Factory.newManagedInstanceForTests() */ - @Deprecated - public static <T extends StartableApplication> T newManagedApp(Class<T> type) { - if (type.isInterface()) { - return (T) newManagedApp(EntitySpec.create(type)); - } else { - return (T) newManagedApp(EntitySpec.create(StartableApplication.class, type)); - } - } - - @SuppressWarnings("unchecked") - private static <T extends StartableApplication> T newManagedApp(EntitySpec<T> spec) { - return (T) new ApplicationBuilder(spec) { - @Override protected void doBuild() { - } - }.manage(); - } - - @SuppressWarnings("unchecked") - @Beta - public static <T extends StartableApplication> T newManagedApp(Class<T> type, ManagementContext managementContext) { - if (type.isInterface()) { - return (T) newManagedApp(EntitySpec.create(type), managementContext); - } else { - return (T) newManagedApp(EntitySpec.create(StartableApplication.class, type), managementContext); - } - } - - /** @deprecated class can be removed; users of this convenience method can now simply do mgmt.getEntityManager().createEntity(spec) */ - @SuppressWarnings("unchecked") - @Beta - public static <T extends StartableApplication> T newManagedApp(EntitySpec<T> spec, ManagementContext managementContext) { - return (T) new ApplicationBuilder(spec) { - @Override protected void doBuild() { - } - }.manage(managementContext); - } - - protected volatile boolean managed = false; - protected final AtomicBoolean inManage = new AtomicBoolean(false); - private EntitySpec<? extends StartableApplication> appSpec; - private ManagementContext managementContext; - private StartableApplication app; - - public ApplicationBuilder() { - this.appSpec = EntitySpec.create(BasicApplication.class); - } - - public ApplicationBuilder(EntitySpec<? extends StartableApplication> appSpec) { - this.appSpec = EntitySpec.create(appSpec); - } - - public final ApplicationBuilder appDisplayName(String val) { - checkPreManage(); - appSpec.displayName(val); - return this; - } - - protected final <T extends Entity> T createEntity(EntitySpec<T> spec) { - checkDuringManage(); - EntityManager entityManager = managementContext.getEntityManager(); - return entityManager.createEntity(spec); - } - - /** - * Adds the given entity as a child of the application being built. - * To be called during {@link #doBuild()}. - */ - protected final <T extends Entity> T addChild(T entity) { - checkDuringManage(); - return app.addChild(entity); - } - - /** - * Returns the type of the application being built. - */ - public final Class<? extends StartableApplication> getType() { - return appSpec.getType(); - } - - /** - * Configures the application instance. - */ - public final ApplicationBuilder configure(Map<?,?> config) { - checkPreManage(); - appSpec.configure(config); - return this; - } - - /** - * Adds the given entity as a child of the application being built. - */ - protected final <T extends Entity> T addChild(EntitySpec<T> spec) { - checkDuringManage(); - return addChild(createEntity(spec)); - } - - protected final <T extends Entity> T addChild(Map<?,?> config, Class<T> type) { - checkDuringManage(); - EntitySpec<T> spec = EntitySpec.create(type).configure(config); - return addChild(createEntity(spec)); - } - - protected final ManagementContext getManagementContext() { - return checkNotNull(managementContext, "must only be called after manage()"); - } - - protected final StartableApplication getApp() { - return checkNotNull(app, "must only be called after manage()"); - } - - /** - * For overriding, to create and wire together entities. - */ - protected abstract void doBuild(); - - /** - * Creates a new {@link ManagementContext}, and then builds and manages the application. - * - * @see #manage(ManagementContext) - */ - public final StartableApplication manage() { - return manage(Entities.newManagementContext()); - } - - /** - * Builds and manages the application, calling the user's {@link #doBuild()} method. - * - * @throws IllegalStateException If already managed, or if called during {@link #doBuild()}, or if - * multiple concurrent calls - */ - public final StartableApplication manage(ManagementContext managementContext) { - if (!inManage.compareAndSet(false, true)) { - throw new IllegalStateException("Concurrent and re-entrant calls to manage() forbidden on "+this); - } - try { - checkNotManaged(); - this.managementContext = managementContext; - this.app = managementContext.getEntityManager().createEntity(appSpec); - doBuild(); - // not needed with 0.9.0 (TODO - remove when confirmed) -// Entities.startManagement(app, managementContext); - managed = true; - return app; - } finally { - inManage.set(false); - } - } - - protected void checkPreManage() { - if (inManage.get()) { - throw new IllegalStateException("Builder being managed; cannot perform operation during call to manage(), or in doBuild()"); - } - if (managed) { - throw new IllegalStateException("Builder already managed; cannot perform operation after call to manage()"); - } - } - - protected void checkNotManaged() { - if (managed) { - throw new IllegalStateException("Builder already managed; cannot perform operation after call to manage()"); - } - } - - protected void checkDuringManage() { - if (!inManage.get() || app == null) { - throw new IllegalStateException("Operation only permitted during manage, e.g. called from doBuild() of "+this); - } - } -} http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/d03f254b/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/entity/factory/BasicConfigurableEntityFactory.java ---------------------------------------------------------------------- diff --git a/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/entity/factory/BasicConfigurableEntityFactory.java b/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/entity/factory/BasicConfigurableEntityFactory.java deleted file mode 100644 index 8f6e3f6..0000000 --- a/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/entity/factory/BasicConfigurableEntityFactory.java +++ /dev/null @@ -1,76 +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.core.entity.factory; - -import static com.google.common.base.Preconditions.checkNotNull; - -import java.io.IOException; -import java.io.ObjectInputStream; -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; -import java.util.HashMap; -import java.util.Map; - -import org.apache.brooklyn.api.entity.Entity; -import org.apache.brooklyn.core.mgmt.persist.DeserializingClassRenamesProvider; - -import com.google.common.base.Objects; -import com.google.common.base.Throwables; - -/** @deprecated since 0.7.0; use EntitySpec instead, as per {@link EntityFactory} javadoc */ -@Deprecated -public class BasicConfigurableEntityFactory<T extends Entity> extends AbstractConfigurableEntityFactory<T> { - private transient Class<? extends T> clazz; - private final String clazzName; - - public BasicConfigurableEntityFactory(Class<? extends T> clazz) { - this(new HashMap(), clazz); - } - - public BasicConfigurableEntityFactory(Map flags, Class<? extends T> clazz) { - super(flags); - this.clazz = checkNotNull(clazz, "clazz"); - this.clazzName = DeserializingClassRenamesProvider.findMappedName(clazz.getName()); - } - - public T newEntity2(Map flags, Entity parent) { - try { - Constructor<? extends T> constructor = clazz.getConstructor(Map.class, Entity.class); - return constructor.newInstance(flags, parent); - } catch (InstantiationException e) { - throw Throwables.propagate(e); - } catch (IllegalAccessException e) { - throw Throwables.propagate(e); - } catch (InvocationTargetException e) { - throw Throwables.propagate(e); - } catch (NoSuchMethodException e) { - throw Throwables.propagate(e); - } - } - - private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException { - s.defaultReadObject(); - clazz = (Class<T>) getClass().getClassLoader().loadClass(clazzName); - } - - @Override - public String toString() { - return Objects.toStringHelper(this).add("type", clazzName).toString(); - } -} http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/d03f254b/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/entity/factory/ClosureEntityFactory.java ---------------------------------------------------------------------- diff --git a/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/entity/factory/ClosureEntityFactory.java b/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/entity/factory/ClosureEntityFactory.java deleted file mode 100644 index df0cf26..0000000 --- a/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/entity/factory/ClosureEntityFactory.java +++ /dev/null @@ -1,53 +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.core.entity.factory; - -import groovy.lang.Closure; - -import java.util.HashMap; -import java.util.Map; - -import org.apache.brooklyn.api.entity.Entity; - -public class ClosureEntityFactory<T extends Entity> extends AbstractConfigurableEntityFactory<T> { - private final Closure<T> closure; - - public ClosureEntityFactory(Closure<T> closure){ - this(new HashMap(),closure); - } - - public ClosureEntityFactory(Map flags, Closure<T> closure) { - super(flags); - this.closure = closure; - } - - public T newEntity2(Map flags, Entity parent) { - if (closure.getMaximumNumberOfParameters()>1) - return closure.call(flags, parent); - else { - //leaving out the parent is discouraged - T entity = closure.call(flags); - if(parent!=null && entity.getParent()==null){ - entity.setParent(parent); - } - - return entity; - } - } -} \ No newline at end of file http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/d03f254b/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/entity/factory/ConfigurableEntityFactory.java ---------------------------------------------------------------------- diff --git a/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/entity/factory/ConfigurableEntityFactory.java b/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/entity/factory/ConfigurableEntityFactory.java deleted file mode 100644 index af5fba3..0000000 --- a/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/entity/factory/ConfigurableEntityFactory.java +++ /dev/null @@ -1,33 +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.core.entity.factory; - -import java.util.Map; - -import org.apache.brooklyn.api.entity.Entity; -import org.apache.brooklyn.config.ConfigKey; - -public interface ConfigurableEntityFactory<T extends Entity> extends EntityFactory<T> { - ConfigurableEntityFactory<T> configure(Map flags); - ConfigurableEntityFactory<T> configure(ConfigKey key, Object value); - ConfigurableEntityFactory<T> configure(ConfigKey.HasConfigKey key, Object value); - - ConfigurableEntityFactory<T> setConfig(ConfigKey key, Object value); - ConfigurableEntityFactory<T> setConfig(ConfigKey.HasConfigKey key, Object value); -} \ No newline at end of file http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/d03f254b/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/entity/factory/ConfigurableEntityFactoryFromEntityFactory.java ---------------------------------------------------------------------- diff --git a/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/entity/factory/ConfigurableEntityFactoryFromEntityFactory.java b/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/entity/factory/ConfigurableEntityFactoryFromEntityFactory.java deleted file mode 100644 index 1fc36c3..0000000 --- a/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/entity/factory/ConfigurableEntityFactoryFromEntityFactory.java +++ /dev/null @@ -1,45 +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.core.entity.factory; - -import static com.google.common.base.Preconditions.checkNotNull; - -import java.util.HashMap; -import java.util.Map; - -import org.apache.brooklyn.api.entity.Entity; - -public class ConfigurableEntityFactoryFromEntityFactory<T extends Entity> extends AbstractConfigurableEntityFactory<T> { - - private final EntityFactory<? extends T> factory; - - public ConfigurableEntityFactoryFromEntityFactory(EntityFactory<? extends T> entityFactory){ - this(new HashMap(),entityFactory); - } - - public ConfigurableEntityFactoryFromEntityFactory(Map flags, EntityFactory<? extends T> factory) { - super(flags); - this.factory = checkNotNull(factory, "factory"); - } - - @Override - public T newEntity2(Map flags, Entity parent) { - return factory.newEntity(flags, parent); - } -} \ No newline at end of file http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/d03f254b/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/entity/factory/EntityFactory.java ---------------------------------------------------------------------- diff --git a/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/entity/factory/EntityFactory.java b/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/entity/factory/EntityFactory.java deleted file mode 100644 index 2f4ede7..0000000 --- a/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/entity/factory/EntityFactory.java +++ /dev/null @@ -1,32 +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.core.entity.factory; - -import java.util.Map; - -import org.apache.brooklyn.api.entity.Entity; - -/** - * A Factory for creating entities. - * - * @deprecated since 0.7.0; use EntitySpec instead, as the factory does not put the entity through the initialization process */ -@Deprecated -public interface EntityFactory<T extends Entity> { - T newEntity(Map flags, Entity parent); -} http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/d03f254b/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/entity/factory/EntityFactoryForLocation.java ---------------------------------------------------------------------- diff --git a/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/entity/factory/EntityFactoryForLocation.java b/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/entity/factory/EntityFactoryForLocation.java deleted file mode 100644 index 79f72d7..0000000 --- a/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/entity/factory/EntityFactoryForLocation.java +++ /dev/null @@ -1,30 +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.core.entity.factory; - -import org.apache.brooklyn.api.entity.Entity; -import org.apache.brooklyn.api.location.Location; - -/** - * dispatch interface to allow an EntityFactory to indicate it might be able to discover - * other factories for specific locations (e.g. if the location implements a custom entity-aware interface) - */ -public interface EntityFactoryForLocation<T extends Entity> { - ConfigurableEntityFactory<T> newFactoryForLocation(Location l); -} http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/d03f254b/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/entity/internal/ConfigMapViewWithStringKeys.java ---------------------------------------------------------------------- diff --git a/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/entity/internal/ConfigMapViewWithStringKeys.java b/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/entity/internal/ConfigMapViewWithStringKeys.java deleted file mode 100644 index 7d91af4..0000000 --- a/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/entity/internal/ConfigMapViewWithStringKeys.java +++ /dev/null @@ -1,130 +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.core.entity.internal; - -import java.util.Collection; -import java.util.LinkedHashSet; -import java.util.Map; -import java.util.Set; - -import org.apache.brooklyn.config.ConfigKey; -import org.apache.brooklyn.core.config.BasicConfigKey; - -import com.google.common.annotations.Beta; -import com.google.common.collect.Sets; - -/** - * Internal class that presents a view over a ConfigMap, so it looks like a Map (with the - * keys being the config key names). - */ -@Beta -public class ConfigMapViewWithStringKeys implements Map<String,Object> { - - private org.apache.brooklyn.config.ConfigMap target; - - public ConfigMapViewWithStringKeys(org.apache.brooklyn.config.ConfigMap target) { - this.target = target; - } - - @Override - public int size() { - return target.getAllConfig().size(); - } - - @Override - public boolean isEmpty() { - return target.getAllConfig().isEmpty(); - } - - @Override - public boolean containsKey(Object key) { - return keySet().contains(key); - } - - @Override - public boolean containsValue(Object value) { - return values().contains(value); - } - - @Override - public Object get(Object key) { - return target.getConfig(new BasicConfigKey<Object>(Object.class, (String)key)); - } - - @Override - public Object put(String key, Object value) { - throw new UnsupportedOperationException("This view is read-only"); - } - - @Override - public Object remove(Object key) { - throw new UnsupportedOperationException("This view is read-only"); - } - - @Override - public void putAll(Map<? extends String, ? extends Object> m) { - throw new UnsupportedOperationException("This view is read-only"); - } - - @Override - public void clear() { - throw new UnsupportedOperationException("This view is read-only"); - } - - @Override - public Set<String> keySet() { - LinkedHashSet<String> result = Sets.newLinkedHashSet(); - Set<Map.Entry<ConfigKey<?>, Object>> set = target.getAllConfig().entrySet(); - for (final Map.Entry<ConfigKey<?>, Object> entry: set) { - result.add(entry.getKey().getName()); - } - return result; - } - - @Override - public Collection<Object> values() { - return target.getAllConfig().values(); - } - - @Override - public Set<Map.Entry<String, Object>> entrySet() { - LinkedHashSet<Map.Entry<String, Object>> result = Sets.newLinkedHashSet(); - Set<Map.Entry<ConfigKey<?>, Object>> set = target.getAllConfig().entrySet(); - for (final Map.Entry<ConfigKey<?>, Object> entry: set) { - result.add(new Map.Entry<String, Object>() { - @Override - public String getKey() { - return entry.getKey().getName(); - } - - @Override - public Object getValue() { - return entry.getValue(); - } - - @Override - public Object setValue(Object value) { - return entry.setValue(value); - } - }); - } - return result; - } - -} http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/d03f254b/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/entity/internal/EntityConfigMap.java ---------------------------------------------------------------------- diff --git a/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/entity/internal/EntityConfigMap.java b/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/entity/internal/EntityConfigMap.java deleted file mode 100644 index da209e1..0000000 --- a/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/entity/internal/EntityConfigMap.java +++ /dev/null @@ -1,319 +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.core.entity.internal; - -import static com.google.common.base.Preconditions.checkNotNull; -import static org.apache.brooklyn.util.groovy.GroovyJavaMethods.elvis; - -import java.util.Collection; -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Set; - -import org.apache.brooklyn.api.mgmt.ExecutionContext; -import org.apache.brooklyn.api.mgmt.Task; -import org.apache.brooklyn.config.ConfigInheritance; -import org.apache.brooklyn.config.ConfigKey; -import org.apache.brooklyn.core.config.Sanitizer; -import org.apache.brooklyn.core.config.StructuredConfigKey; -import org.apache.brooklyn.core.config.internal.AbstractConfigMapImpl; -import org.apache.brooklyn.core.entity.AbstractEntity; -import org.apache.brooklyn.util.collections.MutableMap; -import org.apache.brooklyn.util.core.config.ConfigBag; -import org.apache.brooklyn.util.core.flags.FlagUtils; -import org.apache.brooklyn.util.core.flags.SetFromFlag; -import org.apache.brooklyn.util.core.flags.TypeCoercions; -import org.apache.brooklyn.util.core.internal.ConfigKeySelfExtracting; -import org.apache.brooklyn.util.guava.Maybe; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.google.common.base.Predicate; -import com.google.common.collect.Maps; -import com.google.common.collect.Sets; - -public class EntityConfigMap extends AbstractConfigMapImpl { - - private static final Logger LOG = LoggerFactory.getLogger(EntityConfigMap.class); - - /** entity against which config resolution / task execution will occur */ - private final AbstractEntity entity; - - /** - * Map of configuration information that is defined at start-up time for the entity. These - * configuration parameters are shared and made accessible to the "children" of this - * entity. - */ - private final Map<ConfigKey<?>,Object> inheritedConfig = Collections.synchronizedMap(new LinkedHashMap<ConfigKey<?>, Object>()); - // TODO do we really want to have *both* bags and maps for these? danger that they get out of synch. - // have added some logic (Oct 2014) so that the same changes are applied to both, in most places at least; - // i (alex) think we should prefer ConfigBag (the input keys don't matter, it is more a question of retrieval keys), - // but first we need ConfigBag to support StructuredConfigKeys - private final ConfigBag localConfigBag; - private final ConfigBag inheritedConfigBag; - - public EntityConfigMap(AbstractEntity entity) { - // Not using ConcurrentMap, because want to (continue to) allow null values. - // Could use ConcurrentMapAcceptingNullVals (with the associated performance hit on entrySet() etc). - this(entity, Collections.synchronizedMap(Maps.<ConfigKey<?>, Object>newLinkedHashMap())); - } - - public EntityConfigMap(AbstractEntity entity, Map<ConfigKey<?>, Object> storage) { - this.entity = checkNotNull(entity, "entity must be specified"); - this.ownConfig = checkNotNull(storage, "storage map must be specified"); - - // TODO store ownUnused in backing-storage - this.localConfigBag = ConfigBag.newInstance(); - this.inheritedConfigBag = ConfigBag.newInstance(); - } - - @SuppressWarnings("unchecked") - public <T> T getConfig(ConfigKey<T> key, T defaultValue) { - // FIXME What about inherited task in config?! - // alex says: think that should work, no? - // FIXME What if someone calls getConfig on a task, before setting parent app? - // alex says: not supported (throw exception, or return the task) - - // In case this entity class has overridden the given key (e.g. to set default), then retrieve this entity's key - // TODO If ask for a config value that's not in our configKeys, should we really continue with rest of method and return key.getDefaultValue? - // e.g. SshBasedJavaAppSetup calls setAttribute(JMX_USER), which calls getConfig(JMX_USER) - // but that example doesn't have a default... - ConfigKey<T> ownKey = entity!=null ? (ConfigKey<T>)elvis(entity.getEntityType().getConfigKey(key.getName()), key) : key; - - ConfigInheritance inheritance = key.getInheritance(); - if (inheritance==null) inheritance = ownKey.getInheritance(); - if (inheritance==null) { - // TODO we could warn by introducing a temporary "ALWAYS_BUT_WARNING" instance - inheritance = getDefaultInheritance(); - } - - // TODO We're notifying of config-changed because currently persistence needs to know when the - // attributeWhenReady is complete (so it can persist the result). - // Long term, we'll just persist tasks properly so the call to onConfigChanged will go! - - // Don't use groovy truth: if the set value is e.g. 0, then would ignore set value and return default! - if (ownKey instanceof ConfigKeySelfExtracting) { - Object rawval = ownConfig.get(key); - T result = null; - boolean complete = false; - if (((ConfigKeySelfExtracting<T>)ownKey).isSet(ownConfig)) { - ExecutionContext exec = entity.getExecutionContext(); - result = ((ConfigKeySelfExtracting<T>)ownKey).extractValue(ownConfig, exec); - complete = true; - } else if (isInherited(ownKey, inheritance) && - ((ConfigKeySelfExtracting<T>)ownKey).isSet(inheritedConfig)) { - ExecutionContext exec = entity.getExecutionContext(); - result = ((ConfigKeySelfExtracting<T>)ownKey).extractValue(inheritedConfig, exec); - complete = true; - } else if (localConfigBag.containsKey(ownKey)) { - // TODO configBag.get doesn't handle tasks/attributeWhenReady - it only uses TypeCoercions - result = localConfigBag.get(ownKey); - complete = true; - } else if (isInherited(ownKey, inheritance) && - inheritedConfigBag.containsKey(ownKey)) { - result = inheritedConfigBag.get(ownKey); - complete = true; - } - - if (rawval instanceof Task) { - entity.getManagementSupport().getEntityChangeListener().onConfigChanged(key); - } - if (complete) { - return result; - } - } else { - LOG.warn("Config key {} of {} is not a ConfigKeySelfExtracting; cannot retrieve value; returning default", ownKey, this); - } - return TypeCoercions.coerce((defaultValue != null) ? defaultValue : ownKey.getDefaultValue(), key.getTypeToken()); - } - - private <T> boolean isInherited(ConfigKey<T> key) { - return isInherited(key, key.getInheritance()); - } - private <T> boolean isInherited(ConfigKey<T> key, ConfigInheritance inheritance) { - if (inheritance==null) inheritance = getDefaultInheritance(); - return inheritance.isInherited(key, entity.getParent(), entity); - } - private ConfigInheritance getDefaultInheritance() { - return ConfigInheritance.ALWAYS; - } - - @Override - public Maybe<Object> getConfigRaw(ConfigKey<?> key, boolean includeInherited) { - if (ownConfig.containsKey(key)) return Maybe.of(ownConfig.get(key)); - if (includeInherited && inheritedConfig.containsKey(key)) return Maybe.of(inheritedConfig.get(key)); - return Maybe.absent(); - } - - /** an immutable copy of the config visible at this entity, local and inherited (preferring local) */ - public Map<ConfigKey<?>,Object> getAllConfig() { - Map<ConfigKey<?>,Object> result = new LinkedHashMap<ConfigKey<?>,Object>(inheritedConfig.size()+ownConfig.size()); - result.putAll(inheritedConfig); - result.putAll(ownConfig); - return Collections.unmodifiableMap(result); - } - - /** an immutable copy of the config defined at this entity, ie not inherited */ - public Map<ConfigKey<?>,Object> getLocalConfig() { - Map<ConfigKey<?>,Object> result = new LinkedHashMap<ConfigKey<?>,Object>(ownConfig.size()); - result.putAll(ownConfig); - return Collections.unmodifiableMap(result); - } - - /** Creates an immutable copy of the config visible at this entity, local and inherited (preferring local), including those that did not match config keys */ - public ConfigBag getAllConfigBag() { - return ConfigBag.newInstanceCopying(localConfigBag) - .putAll(ownConfig) - .putIfAbsent(inheritedConfig) - .putIfAbsent(inheritedConfigBag) - .seal(); - } - - /** Creates an immutable copy of the config defined at this entity, ie not inherited, including those that did not match config keys */ - public ConfigBag getLocalConfigBag() { - return ConfigBag.newInstanceCopying(localConfigBag) - .putAll(ownConfig) - .seal(); - } - - @SuppressWarnings("unchecked") - public Object setConfig(ConfigKey<?> key, Object v) { - Object val = coerceConfigVal(key, v); - Object oldVal; - if (key instanceof StructuredConfigKey) { - oldVal = ((StructuredConfigKey)key).applyValueToMap(val, ownConfig); - // TODO ConfigBag does not handle structured config keys; quick fix is to remove (and should also remove any subkeys; - // as it stands if someone set string a.b.c in the config bag then removed structured key a.b, then got a.b.c they'd get a vale); - // long term fix is to support structured config keys in ConfigBag, at which point i think we could remove ownConfig altogether - localConfigBag.remove(key); - } else { - oldVal = ownConfig.put(key, val); - localConfigBag.put((ConfigKey<Object>)key, v); - } - entity.config().refreshInheritedConfigOfChildren(); - return oldVal; - } - - public void setLocalConfig(Map<ConfigKey<?>, ?> vals) { - ownConfig.clear(); - localConfigBag.clear(); - ownConfig.putAll(vals); - localConfigBag.putAll(vals); - } - - public void setInheritedConfig(Map<ConfigKey<?>, ?> valsO, ConfigBag configBagVals) { - Map<ConfigKey<?>, ?> vals = filterUninheritable(valsO); - - inheritedConfig.clear(); - inheritedConfig.putAll(vals); - - // The configBagVals contains all inherited, including strings that did not match a config key on the parent. - // They might match a config-key on this entity though, so need to check that: - // - if it matches one of our keys, set it in inheritedConfig - // - otherwise add it to our inheritedConfigBag - Set<String> valKeyNames = Sets.newLinkedHashSet(); - for (ConfigKey<?> key : vals.keySet()) { - valKeyNames.add(key.getName()); - } - Map<String,Object> valsUnmatched = MutableMap.<String,Object>builder() - .putAll(configBagVals.getAllConfig()) - .removeAll(valKeyNames) - .build(); - inheritedConfigBag.clear(); - Map<ConfigKey<?>, SetFromFlag> annotatedConfigKeys = FlagUtils.getAnnotatedConfigKeys(entity.getClass()); - Map<String, ConfigKey<?>> renamedConfigKeys = Maps.newLinkedHashMap(); - for (Map.Entry<ConfigKey<?>, SetFromFlag> entry: annotatedConfigKeys.entrySet()) { - String rename = entry.getValue().value(); - if (rename != null) { - renamedConfigKeys.put(rename, entry.getKey()); - } - } - for (Map.Entry<String,Object> entry : valsUnmatched.entrySet()) { - String name = entry.getKey(); - Object value = entry.getValue(); - ConfigKey<?> key = renamedConfigKeys.get(name); - if (key == null) key = entity.getEntityType().getConfigKey(name); - if (key != null) { - if (!isInherited(key)) { - // no-op - } else if (inheritedConfig.containsKey(key)) { - LOG.warn("Entity "+entity+" inherited duplicate config for key "+key+", via explicit config and string name "+name+"; using value of key"); - } else { - inheritedConfig.put(key, value); - } - } else { - // a config bag has discarded the keys, so we must assume default inheritance for things given that way - // unless we can infer a key; not a big deal, as we should have the key in inheritedConfig for everything - // which originated with a key ... but still, it would be nice to clean up the use of config bag! - inheritedConfigBag.putStringKey(name, value); - } - } - } - - private Map<ConfigKey<?>, ?> filterUninheritable(Map<ConfigKey<?>, ?> vals) { - Map<ConfigKey<?>, Object> result = Maps.newLinkedHashMap(); - for (Map.Entry<ConfigKey<?>, ?> entry : vals.entrySet()) { - if (isInherited(entry.getKey())) { - result.put(entry.getKey(), entry.getValue()); - } - } - return result; - } - - public void addToLocalBag(Map<String,?> vals) { - localConfigBag.putAll(vals); - // quick fix for problem that ownConfig can get out of synch - ownConfig.putAll(localConfigBag.getAllConfigAsConfigKeyMap()); - } - - public void removeFromLocalBag(String key) { - localConfigBag.remove(key); - ownConfig.remove(key); - } - - public void clearInheritedConfig() { - inheritedConfig.clear(); - inheritedConfigBag.clear(); - } - - @Override - public EntityConfigMap submap(Predicate<ConfigKey<?>> filter) { - EntityConfigMap m = new EntityConfigMap(entity, Maps.<ConfigKey<?>, Object>newLinkedHashMap()); - for (Map.Entry<ConfigKey<?>,Object> entry: inheritedConfig.entrySet()) - if (filter.apply(entry.getKey())) - m.inheritedConfig.put(entry.getKey(), entry.getValue()); - synchronized (ownConfig) { - for (Map.Entry<ConfigKey<?>,Object> entry: ownConfig.entrySet()) - if (filter.apply(entry.getKey())) - m.ownConfig.put(entry.getKey(), entry.getValue()); - } - return m; - } - - @Override - public String toString() { - Map<ConfigKey<?>, Object> sanitizeConfig; - synchronized (ownConfig) { - sanitizeConfig = Sanitizer.sanitize(ownConfig); - } - return super.toString()+"[own="+sanitizeConfig+"; inherited="+Sanitizer.sanitize(inheritedConfig)+"]"; - } - -} http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/d03f254b/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/entity/internal/EntityTransientCopyInternal.java ---------------------------------------------------------------------- diff --git a/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/entity/internal/EntityTransientCopyInternal.java b/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/entity/internal/EntityTransientCopyInternal.java deleted file mode 100644 index 09a8fdf..0000000 --- a/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/entity/internal/EntityTransientCopyInternal.java +++ /dev/null @@ -1,121 +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.core.entity.internal; - -import java.util.Collection; -import java.util.Map; - -import javax.annotation.Nullable; - -import org.apache.brooklyn.api.effector.Effector; -import org.apache.brooklyn.api.entity.Application; -import org.apache.brooklyn.api.entity.Entity; -import org.apache.brooklyn.api.entity.EntityType; -import org.apache.brooklyn.api.entity.Group; -import org.apache.brooklyn.api.location.Location; -import org.apache.brooklyn.api.mgmt.ExecutionContext; -import org.apache.brooklyn.api.mgmt.ManagementContext; -import org.apache.brooklyn.api.mgmt.rebind.RebindSupport; -import org.apache.brooklyn.api.mgmt.rebind.mementos.EntityMemento; -import org.apache.brooklyn.api.objs.BrooklynObject.TagSupport; -import org.apache.brooklyn.api.policy.Policy; -import org.apache.brooklyn.api.sensor.AttributeSensor; -import org.apache.brooklyn.api.sensor.Enricher; -import org.apache.brooklyn.config.ConfigKey; -import org.apache.brooklyn.config.ConfigKey.HasConfigKey; -import org.apache.brooklyn.core.entity.EntityInternal; -import org.apache.brooklyn.core.entity.EntityInternal.FeedSupport; -import org.apache.brooklyn.core.mgmt.internal.EntityManagementSupport; -import org.apache.brooklyn.core.objs.proxy.EntityProxyImpl; -import org.apache.brooklyn.util.core.config.ConfigBag; -import org.apache.brooklyn.util.guava.Maybe; - -import com.google.common.annotations.Beta; - -/** - * Selected methods from {@link EntityInternal} and parents which are permitted - * for entities being loaded in read-only mode, enforced by {@link EntityProxyImpl}. - * <p> - * Some of these methods do expose write capabilities, but such modifications are likely - * to be temporary, discarded on next rebind. Callers must take care with any such invocations. - * (The primary intent of this interface is to catch and prevent *most* such invocations!) - */ -@Beta -public interface EntityTransientCopyInternal { - - // TODO For feeds() and config(), need to ensure mutator methods on returned object are not invoked. - - // from Entity - - String getId(); - long getCreationTime(); - String getDisplayName(); - @Nullable String getIconUrl(); - EntityType getEntityType(); - Application getApplication(); - String getApplicationId(); - Entity getParent(); - Collection<Entity> getChildren(); - Collection<Policy> getPolicies(); - Collection<Enricher> getEnrichers(); - Collection<Group> getGroups(); - Collection<Location> getLocations(); - <T> T getAttribute(AttributeSensor<T> sensor); - <T> T getConfig(ConfigKey<T> key); - <T> T getConfig(HasConfigKey<T> key); - Maybe<Object> getConfigRaw(ConfigKey<?> key, boolean includeInherited); - Maybe<Object> getConfigRaw(HasConfigKey<?> key, boolean includeInherited); - TagSupport tags(); - String getCatalogItemId(); - - - // from entity local - - @Deprecated <T> T getConfig(ConfigKey<T> key, T defaultValue); - @Deprecated <T> T getConfig(HasConfigKey<T> key, T defaultValue); - - - // from EntityInternal: - - @Deprecated EntityConfigMap getConfigMap(); - @Deprecated Map<ConfigKey<?>,Object> getAllConfig(); - // for rebind mainly: - @Deprecated ConfigBag getAllConfigBag(); - @Deprecated ConfigBag getLocalConfigBag(); - @SuppressWarnings("rawtypes") - Map<AttributeSensor, Object> getAllAttributes(); - EntityManagementSupport getManagementSupport(); - ManagementContext getManagementContext(); - Effector<?> getEffector(String effectorName); - @Deprecated FeedSupport getFeedSupport(); - FeedSupport feeds(); - RebindSupport<EntityMemento> getRebindSupport(); - // for REST calls on read-only entities which want to resolve values - ExecutionContext getExecutionContext(); - void setCatalogItemId(String id); - - /** more methods, but which are only on selected entities */ - public interface SpecialEntityTransientCopyInternal { - // from Group - Collection<Entity> getMembers(); - boolean hasMember(Entity member); - Integer getCurrentSize(); - } - -} http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/d03f254b/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/entity/lifecycle/Lifecycle.java ---------------------------------------------------------------------- diff --git a/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/entity/lifecycle/Lifecycle.java b/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/entity/lifecycle/Lifecycle.java deleted file mode 100644 index 68b316e..0000000 --- a/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/entity/lifecycle/Lifecycle.java +++ /dev/null @@ -1,187 +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.core.entity.lifecycle; - -import java.io.Serializable; -import java.util.Date; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.apache.brooklyn.api.location.Location; -import org.apache.brooklyn.core.config.render.RendererHints; -import org.apache.brooklyn.core.entity.trait.Startable; -import org.apache.brooklyn.util.core.flags.TypeCoercions; -import org.apache.brooklyn.util.text.StringFunctions; - -import com.google.common.base.CaseFormat; -import com.google.common.base.Function; -import com.google.common.base.Objects; -import com.google.common.base.Preconditions; - -/** - * An enumeration representing the status of an {@link org.apache.brooklyn.api.entity.Entity}. - */ -public enum Lifecycle { - /** - * The entity has just been created. - * - * This stage encompasses the contruction. Once this stage is - * complete, the basic set of sensors will be available, apart from any that require the entity to be active or - * deployed to a {@link Location}. - */ - CREATED, - - /** - * The entity is starting. - * <p> - * This stage is typically entered when the {@link Startable#START} effector - * is called, to undertake the startup operations from the management plane. - * When this completes the entity will normally transition to - * {@link Lifecycle#RUNNING}. - */ - STARTING, - - /** - * The entity service is expected to be running. In healthy operation, {@link Attributes#SERVICE_UP} will be true, - * or will shortly be true if all service start actions have been completed and we are merely waiting for it to be running. - */ - RUNNING, - - /** - * The entity is stopping. - * - * This stage is activated when the - * {@link Startable#STOP} effector is called. The entity service is stopped. - * Sensors that provide data from the running entity may be cleared and subscriptions cancelled. - */ - STOPPING, - - /** - * The entity is not expected to be active. - * - * This stage is entered when an entity is stopped, or may be entered when an entity is - * fully created but not started. It may or may not be removed from the location(s) it was assigned, - * and it will typically not be providing new sensor data apart. - */ - STOPPED, - - /** - * The entity is destroyed. - * - * The entity will be unmanaged and removed from any groups and from its parent. - */ - DESTROYED, - - /** - * Entity error state. - * - * This stage is reachable from any other stage if an error occurs or an exception is thrown. - */ - ON_FIRE; - - /** - * The text representation of the {@link #name()}. - * - * This is formatted as lower case characters, with hyphens instead of spaces. - */ - public String value() { - return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_HYPHEN, name()); - } - - /** @see #value() */ - @Override - public String toString() { return value(); } - - /** - * Creates a {@link Lifecycle} from a text representation. - * - * This accepts the text representations output by the {@link #value()} method for each entry. - * - * @see #value() - */ - public static Lifecycle fromValue(String v) { - try { - return valueOf(CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_UNDERSCORE, v)); - } catch (IllegalArgumentException iae) { - return ON_FIRE; - } - } - - public static class Transition implements Serializable { - private static final long serialVersionUID = 603419184398753502L; - - final Lifecycle state; - final long timestampUtc; - - public Transition(Lifecycle state, Date timestamp) { - this.state = Preconditions.checkNotNull(state, "state"); - this.timestampUtc = Preconditions.checkNotNull(timestamp, "timestamp").getTime(); - } - - public Lifecycle getState() { - return state; - } - public Date getTimestamp() { - return new Date(timestampUtc); - } - - @Override - public int hashCode() { - return Objects.hashCode(state, timestampUtc); - } - - @Override - public boolean equals(Object obj) { - if (!(obj instanceof Transition)) return false; - if (!state.equals(((Transition)obj).getState())) return false; - if (timestampUtc != ((Transition)obj).timestampUtc) return false; - return true; - } - - @Override - public String toString() { - return state+" @ "+timestampUtc+" / "+new Date(timestampUtc); - } - } - - protected static class TransitionCoalesceFunction implements Function<String, Transition> { - private static final Pattern TRANSITION_PATTERN = Pattern.compile("^([\\w-]+)\\s+@\\s+(\\d+).*"); - - @Override - public Transition apply(final String input) { - if (input != null) { - Matcher m = TRANSITION_PATTERN.matcher(input); - if (m.matches()) { - Lifecycle state = Lifecycle.valueOf(m.group(1).toUpperCase().replace('-', '_')); - long time = Long.parseLong(m.group(2)); - return new Transition(state, new Date(time)); - } else { - throw new IllegalStateException("Serialized Lifecycle.Transition can't be parsed: " + input); - } - } else { - return null; - } - } - } - - static { - TypeCoercions.registerAdapter(String.class, Transition.class, new TransitionCoalesceFunction()); - RendererHints.register(Transition.class, RendererHints.displayValue(StringFunctions.toStringFunction())); - } -} http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/d03f254b/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/entity/lifecycle/PolicyDescriptor.java ---------------------------------------------------------------------- diff --git a/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/entity/lifecycle/PolicyDescriptor.java b/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/entity/lifecycle/PolicyDescriptor.java deleted file mode 100644 index ee063cb..0000000 --- a/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/entity/lifecycle/PolicyDescriptor.java +++ /dev/null @@ -1,68 +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.core.entity.lifecycle; - -import org.apache.brooklyn.api.policy.Policy; -import org.apache.brooklyn.core.entity.AbstractEntity; - -import com.google.common.base.Objects; - -/** Emitted as part of {@link AbstractEntity#POLICY_ADDED} and {@link AbstractEntity#POLICY_REMOVED} */ -public class PolicyDescriptor { - - private final String id; - private final String type; - private final String name; - - public PolicyDescriptor(Policy policy) { - this.id = policy.getId(); - this.type = policy.getPolicyType().getName(); - this.name = policy.getDisplayName(); - } - public String getId() { - return id; - } - - public String getPolicyType() { - return type; - } - - public String getName() { - return name; - } - - @Override - public boolean equals(Object other) { - if (!(other instanceof PolicyDescriptor)) { - return false; - } - PolicyDescriptor o = (PolicyDescriptor) other; - return Objects.equal(id, o.id) && Objects.equal(type, o.type) && Objects.equal(name, o.name); - } - - @Override - public int hashCode() { - return id.hashCode(); - } - - @Override - public String toString() { - return Objects.toStringHelper(this).add("id", id).add("type", type).add("name", name).omitNullValues().toString(); - } -}
