http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/d03f254b/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/mgmt/EntityManagementUtils.java ---------------------------------------------------------------------- diff --git a/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/mgmt/EntityManagementUtils.java b/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/mgmt/EntityManagementUtils.java deleted file mode 100644 index 2f37e7c..0000000 --- a/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/mgmt/EntityManagementUtils.java +++ /dev/null @@ -1,332 +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.mgmt; - -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.Callable; - -import javax.annotation.Nullable; - -import org.apache.brooklyn.api.catalog.CatalogItem; -import org.apache.brooklyn.api.entity.Application; -import org.apache.brooklyn.api.entity.Entity; -import org.apache.brooklyn.api.entity.EntitySpec; -import org.apache.brooklyn.api.internal.AbstractBrooklynObjectSpec; -import org.apache.brooklyn.api.mgmt.ManagementContext; -import org.apache.brooklyn.api.mgmt.Task; -import org.apache.brooklyn.config.ConfigKey; -import org.apache.brooklyn.core.catalog.internal.BasicBrooklynCatalog; -import org.apache.brooklyn.core.config.ConfigKeys; -import org.apache.brooklyn.core.effector.Effectors; -import org.apache.brooklyn.core.entity.Entities; -import org.apache.brooklyn.core.entity.EntityFunctions; -import org.apache.brooklyn.core.entity.trait.Startable; -import org.apache.brooklyn.core.typereg.RegisteredTypeLoadingContexts; -import org.apache.brooklyn.entity.stock.BasicApplication; -import org.apache.brooklyn.util.collections.MutableList; -import org.apache.brooklyn.util.collections.MutableMap; -import org.apache.brooklyn.util.core.task.TaskBuilder; -import org.apache.brooklyn.util.core.task.Tasks; -import org.apache.brooklyn.util.text.Strings; -import org.apache.brooklyn.util.time.Duration; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.google.common.base.Predicates; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Iterables; -import com.google.common.collect.Maps; -import com.google.common.util.concurrent.Runnables; - -/** Utility methods for working with entities and applications */ -public class EntityManagementUtils { - - private static final Logger log = LoggerFactory.getLogger(EntityManagementUtils.class); - - /** - * A marker config value which indicates that an {@link Application} entity was created automatically, - * needed because a plan might give multiple top-level entities or a non-Application top-level entity, - * in a context where Brooklyn requires an {@link Application} at the root. - * <p> - * Typically when such a wrapper app wraps another {@link Application} - * (or where we are looking for a single {@link Entity}, or a list to add, and they are so wrapped) - * it will be unwrapped. - * See {@link #newWrapperApp()} and {@link #unwrapApplication(EntitySpec)}. - */ - public static final ConfigKey<Boolean> WRAPPER_APP_MARKER = ConfigKeys.newBooleanConfigKey("brooklyn.wrapper_app"); - - /** creates an application from the given app spec, managed by the given management context */ - public static <T extends Application> T createUnstarted(ManagementContext mgmt, EntitySpec<T> spec) { - T app = mgmt.getEntityManager().createEntity(spec); - return app; - } - - /** as {@link #createUnstarted(ManagementContext, EntitySpec)} but for a string plan (e.g. camp yaml) */ - public static Application createUnstarted(ManagementContext mgmt, String plan) { - EntitySpec<? extends Application> spec = createEntitySpecForApplication(mgmt, plan); - return createUnstarted(mgmt, spec); - } - - @SuppressWarnings("unchecked") - public static EntitySpec<? extends Application> createEntitySpecForApplication(ManagementContext mgmt, final String plan) { - return mgmt.getTypeRegistry().createSpecFromPlan(null, plan, RegisteredTypeLoadingContexts.spec(Application.class), EntitySpec.class); - } - - @Deprecated /** @deprecated since 0.9.0; use {@link BrooklynTypeRegistry#createSpec(RegisteredType, org.apache.brooklyn.api.typereg.RegisteredTypeConstraint, Class)} */ - // not used in Brooklyn - public static <T,SpecT extends AbstractBrooklynObjectSpec<? extends T, SpecT>> SpecT createCatalogSpec(ManagementContext mgmt, CatalogItem<T, SpecT> item) { - return createCatalogSpec(mgmt, item, ImmutableSet.<String>of()); - } - - @Deprecated /** @deprecated since 0.9.0; use {@link BrooklynTypeRegistry#createSpec(RegisteredType, org.apache.brooklyn.api.typereg.RegisteredTypeConstraint, Class)} */ - // not used in Brooklyn - public static <T,SpecT extends AbstractBrooklynObjectSpec<? extends T, SpecT>> SpecT createCatalogSpec(ManagementContext mgmt, final CatalogItem<T, SpecT> item, final Set<String> encounteredTypes) { - return BasicBrooklynCatalog.internalCreateSpecLegacy(mgmt, item, encounteredTypes, true); - } - - /** container for operation which creates something and which wants to return both - * the items created and any pending create/start task */ - public static class CreationResult<T,U> { - private final T thing; - @Nullable private final Task<U> task; - public CreationResult(T thing, Task<U> task) { - super(); - this.thing = thing; - this.task = task; - } - - protected static <T,U> CreationResult<T,U> of(T thing, @Nullable Task<U> task) { - return new CreationResult<T,U>(thing, task); - } - - /** returns the thing/things created */ - @Nullable public T get() { return thing; } - /** associated task, ie the one doing the creation/starting */ - public Task<U> task() { return task; } - public CreationResult<T,U> blockUntilComplete(Duration timeout) { if (task!=null) task.blockUntilEnded(timeout); return this; } - public CreationResult<T,U> blockUntilComplete() { if (task!=null) task.blockUntilEnded(); return this; } - } - - public static <T extends Application> CreationResult<T,Void> createStarting(ManagementContext mgmt, EntitySpec<T> appSpec) { - return start(createUnstarted(mgmt, appSpec)); - } - - public static CreationResult<? extends Application,Void> createStarting(ManagementContext mgmt, String appSpec) { - return start(createUnstarted(mgmt, appSpec)); - } - - public static <T extends Application> CreationResult<T,Void> start(T app) { - Task<Void> task = Entities.invokeEffector(app, app, Startable.START, - // locations already set in the entities themselves; - // TODO make it so that this arg does not have to be supplied to START ! - MutableMap.of("locations", MutableList.of())); - return CreationResult.of(app, task); - } - - public static CreationResult<List<Entity>, List<String>> addChildren(final Entity parent, String yaml, Boolean start) { - if (Boolean.FALSE.equals(start)) - return CreationResult.of(addChildrenUnstarted(parent, yaml), null); - return addChildrenStarting(parent, yaml); - } - - /** adds entities from the given yaml, under the given parent; but does not start them */ - public static List<Entity> addChildrenUnstarted(final Entity parent, String yaml) { - log.debug("Creating child of "+parent+" from yaml:\n{}", yaml); - - ManagementContext mgmt = parent.getApplication().getManagementContext(); - - EntitySpec<? extends Application> specA = createEntitySpecForApplication(mgmt, yaml); - - // see whether we can promote children - List<EntitySpec<?>> specs = MutableList.of(); - if (!canUnwrapEntity(specA)) { - // if not promoting, set a nice name if needed - if (Strings.isEmpty(specA.getDisplayName())) { - int size = specA.getChildren().size(); - String childrenCountString = size+" "+(size!=1 ? "children" : "child"); - specA.displayName("Dynamically added "+childrenCountString); - } - } - - specs.add(unwrapEntity(specA)); - - final List<Entity> children = MutableList.of(); - for (EntitySpec<?> spec: specs) { - Entity child = (Entity)parent.addChild(spec); - children.add(child); - } - - return children; - } - - public static CreationResult<List<Entity>,List<String>> addChildrenStarting(final Entity parent, String yaml) { - final List<Entity> children = addChildrenUnstarted(parent, yaml); - String childrenCountString; - - int size = children.size(); - childrenCountString = size+" "+(size!=1 ? "children" : "child"); - - TaskBuilder<List<String>> taskM = Tasks.<List<String>>builder().displayName("add children") - .dynamic(true) - .tag(BrooklynTaskTags.NON_TRANSIENT_TASK_TAG) - .body(new Callable<List<String>>() { - @Override public List<String> call() throws Exception { - return ImmutableList.copyOf(Iterables.transform(children, EntityFunctions.id())); - }}) - .description("Add and start "+childrenCountString); - - TaskBuilder<?> taskS = Tasks.builder().parallel(true).displayName("add (parallel)").description("Start each new entity"); - - // autostart if requested - for (Entity child: children) { - if (child instanceof Startable) { - taskS.add(Effectors.invocation(child, Startable.START, ImmutableMap.of("locations", ImmutableList.of()))); - } else { - // include a task, just to give feedback in the GUI - taskS.add(Tasks.builder().displayName("create").description("Skipping start (not a Startable Entity)") - .body(Runnables.doNothing()) - .tag(BrooklynTaskTags.tagForTargetEntity(child)) - .build()); - } - } - taskM.add(taskS.build()); - Task<List<String>> task = Entities.submit(parent, taskM.build()); - - return CreationResult.of(children, task); - } - - /** Unwraps a single {@link Entity} if appropriate. See {@link #WRAPPER_APP_MARKER}. - * Also see {@link #canUnwrapEntity(EntitySpec)} to test whether it will unwrap. */ - public static EntitySpec<? extends Entity> unwrapEntity(EntitySpec<? extends Entity> wrapperApplication) { - if (!canUnwrapEntity(wrapperApplication)) { - return wrapperApplication; - } - EntitySpec<?> wrappedEntity = Iterables.getOnlyElement(wrapperApplication.getChildren()); - @SuppressWarnings("unchecked") - EntitySpec<? extends Application> wrapperApplicationTyped = (EntitySpec<? extends Application>) wrapperApplication; - EntityManagementUtils.mergeWrapperParentSpecToChildEntity(wrapperApplicationTyped, wrappedEntity); - return wrappedEntity; - } - - /** Unwraps a wrapped {@link Application} if appropriate. - * This is like {@link #canUnwrapEntity(EntitySpec)} with an additional check that the wrapped child is an {@link Application}. - * See {@link #WRAPPER_APP_MARKER} for an overview. - * Also see {@link #canUnwrapApplication(EntitySpec)} to test whether it will unwrap. */ - public static EntitySpec<? extends Application> unwrapApplication(EntitySpec<? extends Application> wrapperApplication) { - if (!canUnwrapApplication(wrapperApplication)) { - return wrapperApplication; - } - @SuppressWarnings("unchecked") - EntitySpec<? extends Application> wrappedApplication = (EntitySpec<? extends Application>) unwrapEntity(wrapperApplication); - return wrappedApplication; - } - - /** Modifies the child so it includes the inessential setup of its parent, - * for use when unwrapping specific children, but a name or other item may have been set on the parent. - * See {@link #WRAPPER_APP_MARKER}. */ - private static void mergeWrapperParentSpecToChildEntity(EntitySpec<? extends Application> wrapperParent, EntitySpec<?> wrappedChild) { - if (Strings.isNonEmpty(wrapperParent.getDisplayName())) { - wrappedChild.displayName(wrapperParent.getDisplayName()); - } - - wrappedChild.locations(wrapperParent.getLocations()); - - if (!wrapperParent.getParameters().isEmpty()) - wrappedChild.parametersReplace(wrapperParent.getParameters()); - - // prefer the wrapper ID (change in 2016-01); see notes on the catalogItemIdIfNotNull method - wrappedChild.catalogItemIdIfNotNull(wrapperParent.getCatalogItemId()); - - // NB: this clobber's child config wherever they conflict; might prefer to deeply merge maps etc - // (or maybe even prevent the merge in these cases; - // not sure there is a compelling reason to have config on a pure-wrapper parent) - Map<ConfigKey<?>, Object> configWithoutWrapperMarker = Maps.filterKeys(wrapperParent.getConfig(), Predicates.not(Predicates.<ConfigKey<?>>equalTo(EntityManagementUtils.WRAPPER_APP_MARKER))); - wrappedChild.configure(configWithoutWrapperMarker); - wrappedChild.configure(wrapperParent.getFlags()); - - // copying tags to all entities may be something the caller wants to control, - // e.g. if we're adding multiple, the caller might not want to copy the parent - // (the BrooklynTags.YAML_SPEC tag will include the parents source including siblings), - // but OTOH they might because otherwise the parent's tags might get lost. - // also if we are unwrapping multiple registry references we will get the YAML_SPEC for each; - // putting the parent's tags first however causes the preferred (outer) one to be retrieved first. - wrappedChild.tagsReplace(MutableList.copyOf(wrapperParent.getTags()).appendAll(wrappedChild.getTags())); - } - - public static EntitySpec<? extends Application> newWrapperApp() { - return EntitySpec.create(BasicApplication.class).configure(WRAPPER_APP_MARKER, true); - } - - /** As {@link #canUnwrapEntity(EntitySpec)} - * but additionally requiring that the wrapped item is an {@link Application}, - * for use when the context requires an {@link Application} ie a root of a spec. - * @see #WRAPPER_APP_MARKER */ - public static boolean canUnwrapApplication(EntitySpec<? extends Application> wrapperApplication) { - if (!canUnwrapEntity(wrapperApplication)) return false; - - EntitySpec<?> childSpec = Iterables.getOnlyElement(wrapperApplication.getChildren()); - return (childSpec.getType()!=null && Application.class.isAssignableFrom(childSpec.getType())); - } - /** @deprecated since 0.9.0 use {@link #canUnwrapApplication(EntitySpec)} */ @Deprecated - public static boolean canPromoteWrappedApplication(EntitySpec<? extends Application> app) { - return canUnwrapApplication(app); - } - - /** Returns true if the spec is for a wrapper app with no important settings, wrapping a single child entity. - * for use when adding from a plan specifying multiple entities but there is nothing significant at the application level, - * and the context would like to flatten it to remove the wrapper yielding just a single entity. - * (but note the result is not necessarily an {@link Application}; - * see {@link #canUnwrapApplication(EntitySpec)} if that is required). - * <p> - * Note callers will normally use one of {@link #unwrapEntity(EntitySpec)} or {@link #unwrapApplication(EntitySpec)}. - * - * @see #WRAPPER_APP_MARKER for an overview */ - public static boolean canUnwrapEntity(EntitySpec<? extends Entity> spec) { - return isWrapperApp(spec) && hasSingleChild(spec) && - // these "brooklyn.*" items on the app rather than the child absolutely prevent unwrapping - // as their semantics could well be different whether they are on the parent or the child - spec.getEnrichers().isEmpty() && - spec.getEnricherSpecs().isEmpty() && - spec.getInitializers().isEmpty() && - spec.getPolicies().isEmpty() && - spec.getPolicySpecs().isEmpty() && - // these items prevent merge only if they are defined at both levels - (spec.getLocations().isEmpty() || Iterables.getOnlyElement(spec.getChildren()).getLocations().isEmpty()) - // TODO what should we do with parameters? currently clobbers due to EntitySpec.parameters(...) behaviour. -// && (spec.getParameters().isEmpty() || Iterables.getOnlyElement(spec.getChildren()).getParameters().isEmpty()) - ; - } - /** @deprecated since 0.9.0 use {@link #canUnwrapEntity(EntitySpec)} */ @Deprecated - public static boolean canPromoteChildrenInWrappedApplication(EntitySpec<? extends Application> spec) { - return canUnwrapEntity(spec); - } - - public static boolean isWrapperApp(EntitySpec<?> spec) { - return Boolean.TRUE.equals(spec.getConfig().get(EntityManagementUtils.WRAPPER_APP_MARKER)); - } - - private static boolean hasSingleChild(EntitySpec<?> spec) { - return spec.getChildren().size() == 1; - } - -}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/d03f254b/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/mgmt/HasBrooklynManagementContext.java ---------------------------------------------------------------------- diff --git a/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/mgmt/HasBrooklynManagementContext.java b/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/mgmt/HasBrooklynManagementContext.java deleted file mode 100644 index 2048c9e..0000000 --- a/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/mgmt/HasBrooklynManagementContext.java +++ /dev/null @@ -1,31 +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.mgmt; - -import org.apache.brooklyn.api.mgmt.ManagementContext; - -/** - * Provides a generic way to obtain a {@link ManagementContext}, which things can implement. - * The intent is to reduce coupling between components by only referring to this interface. - */ -public interface HasBrooklynManagementContext { - - public ManagementContext getBrooklynManagementContext(); - -} http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/d03f254b/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/mgmt/ManagementContextInjectable.java ---------------------------------------------------------------------- diff --git a/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/mgmt/ManagementContextInjectable.java b/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/mgmt/ManagementContextInjectable.java deleted file mode 100644 index 8d0a6a5..0000000 --- a/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/mgmt/ManagementContextInjectable.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.mgmt; - -import org.apache.brooklyn.api.mgmt.ManagementContext; - -/** - * Provides a way for the {@link ManagementContext} to be injected directly. - */ -public interface ManagementContextInjectable { - - /** - * Sets the {@link ManagementContext} reference. - */ - public void setManagementContext(ManagementContext managementContext); - -} http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/d03f254b/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/mgmt/classloading/AbstractBrooklynClassLoadingContext.java ---------------------------------------------------------------------- diff --git a/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/mgmt/classloading/AbstractBrooklynClassLoadingContext.java b/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/mgmt/classloading/AbstractBrooklynClassLoadingContext.java deleted file mode 100644 index 8003948..0000000 --- a/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/mgmt/classloading/AbstractBrooklynClassLoadingContext.java +++ /dev/null @@ -1,83 +0,0 @@ -package org.apache.brooklyn.core.mgmt.classloading; - -import javax.annotation.Nullable; - -import org.apache.brooklyn.api.mgmt.ManagementContext; -import org.apache.brooklyn.api.mgmt.classloading.BrooklynClassLoadingContext; -import org.apache.brooklyn.util.guava.Maybe; - -import com.google.common.base.Objects; - -/* - * 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. - */ -@SuppressWarnings("deprecation") -public abstract class AbstractBrooklynClassLoadingContext implements BrooklynClassLoadingContext, - org.apache.brooklyn.core.mgmt.classloading.BrooklynClassLoadingContext { - - protected final ManagementContext mgmt; - - public AbstractBrooklynClassLoadingContext(ManagementContext mgmt) { - this.mgmt = mgmt; - } - - @Override - public ManagementContext getManagementContext() { - return mgmt; - } - - @Override - public Class<?> loadClass(String className) { - return tryLoadClass(className).get(); - } - - @Override - // this is the only one left for subclasses - public abstract Maybe<Class<?>> tryLoadClass(String className); - - @Override - public <T> Class<? extends T> loadClass(String className, @Nullable Class<T> supertype) { - return tryLoadClass(className, supertype).get(); - } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - @Override - public <T> Maybe<Class<? extends T>> tryLoadClass(String className, @Nullable Class<T> supertype) { - Maybe<Class<?>> result = tryLoadClass(className); - if (result.isAbsent()) return (Maybe)result; - Class<?> clazz = result.get(); - if (supertype==null || supertype.isAssignableFrom(clazz)) return (Maybe)result; - throw new ClassCastException(className+" is not an instance of "+supertype); - } - - @Override - public abstract String toString(); - - @Override - public int hashCode() { - return Objects.hashCode(mgmt); - } - - @Override - public boolean equals(Object obj) { - if (!(obj instanceof BrooklynClassLoadingContext)) return false; - if (!Objects.equal(mgmt, ((BrooklynClassLoadingContext)obj).getManagementContext())) return false; - return true; - } - -} http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/d03f254b/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/mgmt/classloading/BrooklynClassLoadingContext.java ---------------------------------------------------------------------- diff --git a/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/mgmt/classloading/BrooklynClassLoadingContext.java b/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/mgmt/classloading/BrooklynClassLoadingContext.java deleted file mode 100644 index b6a5e50..0000000 --- a/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/mgmt/classloading/BrooklynClassLoadingContext.java +++ /dev/null @@ -1,28 +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.mgmt.classloading; - - -/** - * @deprecated since 0.9.0; moved to API package; use the super-interface - * {@link org.apache.brooklyn.api.mgmt.classloading.BrooklynClassLoadingContext} - */ -@Deprecated -public interface BrooklynClassLoadingContext extends org.apache.brooklyn.api.mgmt.classloading.BrooklynClassLoadingContext { -} http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/d03f254b/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/mgmt/classloading/BrooklynClassLoadingContextSequential.java ---------------------------------------------------------------------- diff --git a/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/mgmt/classloading/BrooklynClassLoadingContextSequential.java b/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/mgmt/classloading/BrooklynClassLoadingContextSequential.java deleted file mode 100644 index 530039a..0000000 --- a/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/mgmt/classloading/BrooklynClassLoadingContextSequential.java +++ /dev/null @@ -1,135 +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.mgmt.classloading; - -import java.net.URL; -import java.util.List; -import java.util.Set; - -import org.apache.brooklyn.api.mgmt.ManagementContext; -import org.apache.brooklyn.api.mgmt.classloading.BrooklynClassLoadingContext; -import org.apache.brooklyn.util.collections.MutableList; -import org.apache.brooklyn.util.collections.MutableSet; -import org.apache.brooklyn.util.exceptions.Exceptions; -import org.apache.brooklyn.util.guava.Maybe; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.google.common.base.Objects; -import com.google.common.collect.Iterables; -import com.google.common.collect.Lists; - -public final class BrooklynClassLoadingContextSequential extends AbstractBrooklynClassLoadingContext { - - private static final Logger log = LoggerFactory.getLogger(BrooklynClassLoadingContextSequential.class); - - private final List<BrooklynClassLoadingContext> primaries = MutableList.<BrooklynClassLoadingContext>of(); - // secondaries used to put java classloader last - private final Set<BrooklynClassLoadingContext> secondaries = MutableSet.<BrooklynClassLoadingContext>of(); - - public BrooklynClassLoadingContextSequential(ManagementContext mgmt, BrooklynClassLoadingContext ...targets) { - super(mgmt); - for (BrooklynClassLoadingContext target: targets) - add(target); - } - - public void add(BrooklynClassLoadingContext target) { - if (target instanceof BrooklynClassLoadingContextSequential) { - for (BrooklynClassLoadingContext targetN: ((BrooklynClassLoadingContextSequential)target).primaries ) - add(targetN); - for (BrooklynClassLoadingContext targetN: ((BrooklynClassLoadingContextSequential)target).secondaries ) - addSecondary(targetN); - } else { - this.primaries.add( target ); - } - } - - public void addSecondary(BrooklynClassLoadingContext target) { - if (!(target instanceof JavaBrooklynClassLoadingContext)) { - // support for legacy catalog classloader only - log.warn("Only Java classloaders should be secondary"); - } - this.secondaries.add( target ); - } - - public Maybe<Class<?>> tryLoadClass(String className) { - List<Throwable> errors = MutableList.of(); - for (BrooklynClassLoadingContext target: primaries) { - Maybe<Class<?>> clazz = target.tryLoadClass(className); - if (clazz.isPresent()) - return clazz; - errors.add( ((Maybe.Absent<?>)clazz).getException() ); - } - boolean noPrimaryErrors = errors.isEmpty(); - for (BrooklynClassLoadingContext target: secondaries) { - Maybe<Class<?>> clazz = target.tryLoadClass(className); - if (clazz.isPresent()) - return clazz; - if (noPrimaryErrors) - errors.add( ((Maybe.Absent<?>)clazz).getException() ); - } - - return Maybe.absent(Exceptions.create("Unable to load "+className+" from "+primaries, errors)); - } - - @Override - public URL getResource(String resourceInThatDir) { - for (BrooklynClassLoadingContext target: primaries) { - URL result = target.getResource(resourceInThatDir); - if (result!=null) return result; - } - for (BrooklynClassLoadingContext target: secondaries) { - URL result = target.getResource(resourceInThatDir); - if (result!=null) return result; - } - return null; - } - - @Override - public Iterable<URL> getResources(String name) { - List<Iterable<URL>> resources = Lists.newArrayList(); - for (BrooklynClassLoadingContext target : primaries) { - resources.add(target.getResources(name)); - } - for (BrooklynClassLoadingContext target : secondaries) { - resources.add(target.getResources(name)); - } - return Iterables.concat(resources); - } - - @Override - public String toString() { - return "classload:"+primaries+";"+secondaries; - } - - @Override - public int hashCode() { - return Objects.hashCode(super.hashCode(), primaries, secondaries); - } - - @Override - public boolean equals(Object obj) { - if (!super.equals(obj)) return false; - if (!(obj instanceof BrooklynClassLoadingContextSequential)) return false; - if (!Objects.equal(primaries, ((BrooklynClassLoadingContextSequential)obj).primaries)) return false; - if (!Objects.equal(secondaries, ((BrooklynClassLoadingContextSequential)obj).secondaries)) return false; - return true; - } - -} http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/d03f254b/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/mgmt/classloading/ClassLoaderFromBrooklynClassLoadingContext.java ---------------------------------------------------------------------- diff --git a/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/mgmt/classloading/ClassLoaderFromBrooklynClassLoadingContext.java b/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/mgmt/classloading/ClassLoaderFromBrooklynClassLoadingContext.java deleted file mode 100644 index f36e2ac..0000000 --- a/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/mgmt/classloading/ClassLoaderFromBrooklynClassLoadingContext.java +++ /dev/null @@ -1,66 +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.mgmt.classloading; - -import java.net.URL; - -import org.apache.brooklyn.api.mgmt.classloading.BrooklynClassLoadingContext; - -public class ClassLoaderFromBrooklynClassLoadingContext extends ClassLoader { - - /** Constructs a {@link ClassLoader} which delegates to the given {@link BrooklynClassLoadingContext} */ - public static ClassLoader of(BrooklynClassLoadingContext clc) { - return new ClassLoaderFromBrooklynClassLoadingContext(clc); - } - - protected final BrooklynClassLoadingContext clc; - - protected ClassLoaderFromBrooklynClassLoadingContext(BrooklynClassLoadingContext clc) { - this.clc = clc; - } - - @Override - public Class<?> findClass(String className) throws ClassNotFoundException { - Class<?> result = clc.loadClass(className); - if (result!=null) return result; - - // last resort. see comment in XStream CompositeClassLoader - ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); - if (contextClassLoader != null) { - result = contextClassLoader.loadClass(className); - if (result!=null) return result; - } - return null; - } - - @Override - protected URL findResource(String name) { - URL result = clc.getResource(name); - if (result!=null) return result; - - // last resort. see comment in XStream CompositeClassLoader - ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); - if (contextClassLoader != null) { - result = contextClassLoader.getResource(name); - if (result!=null) 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/mgmt/classloading/JavaBrooklynClassLoadingContext.java ---------------------------------------------------------------------- diff --git a/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/mgmt/classloading/JavaBrooklynClassLoadingContext.java b/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/mgmt/classloading/JavaBrooklynClassLoadingContext.java deleted file mode 100644 index 064ba03..0000000 --- a/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/mgmt/classloading/JavaBrooklynClassLoadingContext.java +++ /dev/null @@ -1,133 +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.mgmt.classloading; - -import static com.google.common.base.Preconditions.checkNotNull; -import static com.google.common.base.Preconditions.checkState; - -import java.io.IOException; -import java.net.URL; -import java.util.Collections; -import java.util.Enumeration; - -import org.apache.brooklyn.api.mgmt.ManagementContext; -import org.apache.brooklyn.core.entity.AbstractEntity; -import org.apache.brooklyn.core.mgmt.persist.DeserializingClassRenamesProvider; -import org.apache.brooklyn.util.exceptions.Exceptions; -import org.apache.brooklyn.util.guava.Maybe; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.google.common.base.Objects; - -public class JavaBrooklynClassLoadingContext extends AbstractBrooklynClassLoadingContext { - - private static final Logger LOG = LoggerFactory.getLogger(JavaBrooklynClassLoadingContext.class); - - // on deserialization this loader is replaced with the catalog's root loader; - // may cause problems for non-osgi catalog items, but that's a reasonable trade-off, - // should this be serialized (e.g. in SpecialFlagsTransformer) in such a case! - private final transient ClassLoader loader; - - /** - * @deprecated since 0.7.0 only for legacy catalog items which provide a non-osgi loader; see {@link #newDefault(ManagementContext)} - */ @Deprecated - public static JavaBrooklynClassLoadingContext create(ClassLoader loader) { - return new JavaBrooklynClassLoadingContext(null, checkNotNull(loader, "loader")); - } - - /** - * At least one of mgmt or loader must not be null. - * @deprecated since 0.7.0 only for legacy catalog items which provide a non-osgi loader; see {@link #newDefault(ManagementContext)} - */ @Deprecated - public static JavaBrooklynClassLoadingContext create(ManagementContext mgmt, ClassLoader loader) { - checkState(mgmt != null || loader != null, "mgmt and loader must not both be null"); - return new JavaBrooklynClassLoadingContext(mgmt, loader); - } - - public static JavaBrooklynClassLoadingContext create(ManagementContext mgmt) { - return new JavaBrooklynClassLoadingContext(checkNotNull(mgmt, "mgmt"), null); - } - - @Deprecated /** @deprecated since 0.7.0 use {@link #create(ManagementContext)} */ - public static JavaBrooklynClassLoadingContext newDefault(ManagementContext mgmt) { - return new JavaBrooklynClassLoadingContext(checkNotNull(mgmt, "mgmt"), null); - } - - @Deprecated /** @deprecated since 0.7.0 will become private; use one of the static methods to instantiate */ - public JavaBrooklynClassLoadingContext(ManagementContext mgmt, ClassLoader loader) { - super(mgmt); - this.loader = loader; - } - - private ClassLoader getClassLoader() { - if (loader != null) return loader; - if (mgmt!=null) return mgmt.getCatalogClassLoader(); - return JavaBrooklynClassLoadingContext.class.getClassLoader(); - } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - public Maybe<Class<?>> tryLoadClass(String className) { - try { - className = DeserializingClassRenamesProvider.findMappedName(className); - return (Maybe) Maybe.of(getClassLoader().loadClass(className)); - } catch (NoClassDefFoundError e) { - String msg = "Invalid linkage in (transitive dependencies of) class "+className+": "+e.toString(); - LOG.debug(msg); - return Maybe.absent(msg, e); - } catch (Exception e) { - Exceptions.propagateIfFatal(e); - return Maybe.absent("Invalid class: "+className, e); - } - } - - @Override - public String toString() { - return "java:"+getClassLoader(); - } - - @Override - public int hashCode() { - return Objects.hashCode(super.hashCode(), getClassLoader()); - } - - @Override - public boolean equals(Object obj) { - if (!super.equals(obj)) return false; - if (!(obj instanceof JavaBrooklynClassLoadingContext)) return false; - if (!Objects.equal(getClassLoader(), ((JavaBrooklynClassLoadingContext)obj).getClassLoader())) return false; - return true; - } - - @Override - public URL getResource(String name) { - return getClassLoader().getResource(name); - } - - @Override - public Iterable<URL> getResources(String name) { - Enumeration<URL> resources; - try { - resources = getClassLoader().getResources(name); - } catch (IOException e) { - throw Exceptions.propagate(e); - } - return Collections.list(resources); - } -} http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/d03f254b/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/mgmt/classloading/OsgiBrooklynClassLoadingContext.java ---------------------------------------------------------------------- diff --git a/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/mgmt/classloading/OsgiBrooklynClassLoadingContext.java b/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/mgmt/classloading/OsgiBrooklynClassLoadingContext.java deleted file mode 100644 index 524f7b5..0000000 --- a/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/mgmt/classloading/OsgiBrooklynClassLoadingContext.java +++ /dev/null @@ -1,144 +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.mgmt.classloading; - -import java.net.URL; -import java.util.Collection; -import java.util.Collections; - -import org.apache.brooklyn.api.mgmt.ManagementContext; -import org.apache.brooklyn.api.typereg.OsgiBundleWithUrl; -import org.apache.brooklyn.api.typereg.RegisteredType; -import org.apache.brooklyn.core.mgmt.entitlement.Entitlements; -import org.apache.brooklyn.core.mgmt.ha.OsgiManager; -import org.apache.brooklyn.core.mgmt.internal.ManagementContextInternal; -import org.apache.brooklyn.util.guava.Maybe; - -import com.google.common.base.Objects; - -public class OsgiBrooklynClassLoadingContext extends AbstractBrooklynClassLoadingContext { - - private final String catalogItemId; - private boolean hasBundles = false; - private transient Collection<? extends OsgiBundleWithUrl> _bundles; - - public OsgiBrooklynClassLoadingContext(ManagementContext mgmt, String catalogItemId, Collection<? extends OsgiBundleWithUrl> bundles) { - super(mgmt); - this._bundles = bundles; - this.hasBundles = bundles!=null && !bundles.isEmpty(); - this.catalogItemId = catalogItemId; - } - - public Collection<? extends OsgiBundleWithUrl> getBundles() { - if (_bundles!=null || !hasBundles) return _bundles; - RegisteredType item = mgmt.getTypeRegistry().get(catalogItemId); - if (item==null) { - throw new IllegalStateException("Catalog item not found for "+catalogItemId+"; cannot create loading context"); - } - _bundles = item.getLibraries(); - return _bundles; - } - - @Override - @SuppressWarnings({ "unchecked", "rawtypes" }) - public Maybe<Class<?>> tryLoadClass(String className) { - Maybe<Class<Object>> clazz = null; - Maybe<OsgiManager> osgi = null; - if (mgmt!=null) { - osgi = ((ManagementContextInternal)mgmt).getOsgiManager(); - if (osgi.isPresent() && getBundles()!=null && !getBundles().isEmpty()) { - if (!Entitlements.isEntitled(mgmt.getEntitlementManager(), Entitlements.SEE_CATALOG_ITEM, catalogItemId)) - return Maybe.absent("Not entitled to use this catalog entry"); - - clazz = osgi.get().tryResolveClass(className, getBundles()); - if (clazz.isPresent()) - return (Maybe)clazz; - } - } - - if (clazz!=null) { - // if OSGi bundles were defined and failed, then use its error message - return (Maybe)clazz; - } - // else determine best message - if (mgmt==null) return Maybe.absent("No mgmt context available for loading "+className); - if (osgi!=null && osgi.isAbsent()) return Maybe.absent("OSGi not available on mgmt for loading "+className); - if (!hasBundles) - return Maybe.absent("No bundles available for loading "+className); - return Maybe.absent("Inconsistent state ("+mgmt+"/"+osgi+"/"+getBundles()+" loading "+className); - } - - @Override - public String toString() { - return "OSGi:"+catalogItemId+"["+getBundles()+"]"; - } - - @Override - public int hashCode() { - return Objects.hashCode(super.hashCode(), getBundles(), catalogItemId); - } - - @Override - public boolean equals(Object obj) { - if (!super.equals(obj)) return false; - if (!(obj instanceof OsgiBrooklynClassLoadingContext)) return false; - - OsgiBrooklynClassLoadingContext other = (OsgiBrooklynClassLoadingContext)obj; - if (!catalogItemId.equals(other.catalogItemId)) return false; - if (!Objects.equal(getBundles(), other.getBundles())) return false; - return true; - } - - @Override - public URL getResource(String name) { - if (mgmt != null && isEntitledToSeeCatalogItem()) { - Maybe<OsgiManager> osgi = ((ManagementContextInternal) mgmt).getOsgiManager(); - if (osgi.isPresent() && hasBundles) { - return osgi.get().getResource(name, getBundles()); - } - } - return null; - } - - @Override - public Iterable<URL> getResources(String name) { - if (mgmt != null && isEntitledToSeeCatalogItem()) { - Maybe<OsgiManager> osgi = ((ManagementContextInternal) mgmt).getOsgiManager(); - if (osgi.isPresent() && hasBundles) { - return osgi.get().getResources(name, getBundles()); - } - } - return Collections.emptyList(); - } - - public String getCatalogItemId() { - return catalogItemId; - } - - /** - * @return true if the current entitlement context may {@link Entitlements#SEE_CATALOG_ITEM see} - * {@link #getCatalogItemId}. - */ - private boolean isEntitledToSeeCatalogItem() { - return Entitlements.isEntitled(mgmt.getEntitlementManager(), - Entitlements.SEE_CATALOG_ITEM, - catalogItemId); - } - -} http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/d03f254b/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/mgmt/entitlement/BasicEntitlementClassDefinition.java ---------------------------------------------------------------------- diff --git a/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/mgmt/entitlement/BasicEntitlementClassDefinition.java b/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/mgmt/entitlement/BasicEntitlementClassDefinition.java deleted file mode 100644 index ed93fc7..0000000 --- a/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/mgmt/entitlement/BasicEntitlementClassDefinition.java +++ /dev/null @@ -1,56 +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.mgmt.entitlement; - -import org.apache.brooklyn.api.mgmt.entitlement.EntitlementClass; - -import com.google.common.base.Objects; -import com.google.common.reflect.TypeToken; - - -public class BasicEntitlementClassDefinition<T> implements EntitlementClass<T> { - - private final String identifier; - private final TypeToken<T> argumentType; - - public BasicEntitlementClassDefinition(String identifier, TypeToken<T> argumentType) { - this.identifier = identifier; - this.argumentType = argumentType; - } - - public BasicEntitlementClassDefinition(String identifier, Class<T> argumentType) { - this.identifier = identifier; - this.argumentType = TypeToken.of(argumentType); - } - - @Override - public String entitlementClassIdentifier() { - return identifier; - } - - @Override - public TypeToken<T> entitlementClassArgumentType() { - return argumentType; - } - - @Override - public String toString() { - return Objects.toStringHelper(this).add("identitifier", identifier).add("argumentType", argumentType).toString(); - } -} http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/d03f254b/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/mgmt/entitlement/EntitlementManagerAdapter.java ---------------------------------------------------------------------- diff --git a/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/mgmt/entitlement/EntitlementManagerAdapter.java b/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/mgmt/entitlement/EntitlementManagerAdapter.java deleted file mode 100644 index b722a00..0000000 --- a/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/mgmt/entitlement/EntitlementManagerAdapter.java +++ /dev/null @@ -1,133 +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.mgmt.entitlement; - -import org.apache.brooklyn.api.entity.Entity; -import org.apache.brooklyn.api.mgmt.entitlement.EntitlementClass; -import org.apache.brooklyn.api.mgmt.entitlement.EntitlementContext; -import org.apache.brooklyn.api.mgmt.entitlement.EntitlementManager; -import org.apache.brooklyn.core.mgmt.entitlement.Entitlements.EntitlementClassesHandler; -import org.apache.brooklyn.core.mgmt.entitlement.Entitlements.EntityAndItem; -import org.apache.brooklyn.core.mgmt.entitlement.Entitlements.StringAndArgument; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.google.common.annotations.Beta; - -/** - * provides an easy entry point to supplying entitlements, by providing the dispatch and defining the additional methods - * which have to be supplied. - * <p> - * note that this class may change as versions change, deliberately breaking backwards compatibility - * to ensure all permissions are used. - * <p> - * @since 0.7.0 */ -@Beta -public abstract class EntitlementManagerAdapter implements EntitlementManager { - - private static final Logger log = LoggerFactory.getLogger(EntitlementManagerAdapter.class); - - protected class Handler implements EntitlementClassesHandler<Boolean> { - final EntitlementContext context; - protected Handler(EntitlementContext context) { - this.context = context; - } - - @Override - public Boolean handleSeeCatalogItem(String catalogItemId) { - return isEntitledToSeeCatalogItem(context, catalogItemId); - } - @Override - public Boolean handleAddCatalogItem(Object catalogItemBeingAdded) { - return isEntitledToAddCatalogItem(context, catalogItemBeingAdded); - } - @Override - public Boolean handleModifyCatalogItem(StringAndArgument catalogItemIdAndModification) { - return isEntitledToModifyCatalogItem(context, catalogItemIdAndModification==null ? null : catalogItemIdAndModification.getString(), - catalogItemIdAndModification==null ? null : catalogItemIdAndModification.getArgument()); - } - - @Override - public Boolean handleSeeEntity(Entity entity) { - return isEntitledToSeeEntity(context, entity); - } - @Override - public Boolean handleSeeSensor(EntityAndItem<String> sensorInfo) { - return isEntitledToSeeSensor(context, sensorInfo.getEntity(), sensorInfo.getItem()); - } - @Override - public Boolean handleInvokeEffector(EntityAndItem<StringAndArgument> effectorInfo) { - StringAndArgument item = effectorInfo.getItem(); - return isEntitledToInvokeEffector(context, effectorInfo.getEntity(), item==null ? null : item.getString(), item==null ? null : item.getArgument()); - } - @Override - public Boolean handleModifyEntity(Entity entity) { - return isEntitledToModifyEntity(context, entity); - } - - @Override - public Boolean handleDeployApplication(Object app) { - return isEntitledToDeployApplication(context, app); - } - - @Override - public Boolean handleSeeAllServerInfo() { - return isEntitledToSeeAllServerInfo(context); - } - - @Override - public Boolean handleSeeServerStatus() { - return isEntitledToSeeServerStatus(context); - } - - @Override - public Boolean handleRoot() { - return isEntitledToRoot(context); - } - } - - @Override - public <T> boolean isEntitled(EntitlementContext context, EntitlementClass<T> entitlementClass, T entitlementClassArgument) { - if (log.isTraceEnabled()) { - log.trace("Checking entitlement of "+context+" to "+entitlementClass+" "+entitlementClassArgument); - } - - if (isEntitledToRoot( context )) return true; - - Handler handler = new Handler(context); - return Entitlements.EntitlementClassesEnum.of(entitlementClass).handle( - handler, entitlementClassArgument); - } - - protected abstract boolean isEntitledToSeeCatalogItem(EntitlementContext context, String catalogItemId); - /** passes item to be added, either yaml, or possibly null if any addition allowed (eg when resetting) */ - protected abstract boolean isEntitledToAddCatalogItem(EntitlementContext context, Object catalogItemBeingAdded); - /** passes item being modified, as ID and description of modification, both possibly null if any modification is allowed (eg when resetting) */ - protected abstract boolean isEntitledToModifyCatalogItem(EntitlementContext context, String catalogItemId, Object catalogItemModification); - protected abstract boolean isEntitledToSeeSensor(EntitlementContext context, Entity entity, String sensorName); - protected abstract boolean isEntitledToSeeEntity(EntitlementContext context, Entity entity); - /** arguments might be null, a map, or a list, depending how/where invoked */ - protected abstract boolean isEntitledToInvokeEffector(EntitlementContext context, Entity entity, String effectorName, Object arguments); - protected abstract boolean isEntitledToModifyEntity(EntitlementContext context, Entity entity); - protected abstract boolean isEntitledToDeployApplication(EntitlementContext context, Object app); - protected abstract boolean isEntitledToSeeAllServerInfo(EntitlementContext context); - protected abstract boolean isEntitledToSeeServerStatus(EntitlementContext context); - protected abstract boolean isEntitledToRoot(EntitlementContext context); - -} http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/d03f254b/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/mgmt/entitlement/EntitlementPredicates.java ---------------------------------------------------------------------- diff --git a/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/mgmt/entitlement/EntitlementPredicates.java b/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/mgmt/entitlement/EntitlementPredicates.java deleted file mode 100644 index 3d2e981..0000000 --- a/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/mgmt/entitlement/EntitlementPredicates.java +++ /dev/null @@ -1,61 +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.mgmt.entitlement; - -import static com.google.common.base.Preconditions.checkNotNull; - -import javax.annotation.Nullable; - -import org.apache.brooklyn.api.mgmt.entitlement.EntitlementClass; -import org.apache.brooklyn.api.mgmt.entitlement.EntitlementManager; - -import com.google.common.base.Predicate; - -public class EntitlementPredicates { - - /** @deprecated since 0.9.0 kept only to allow conversion of anonymous inner classes */ - @SuppressWarnings("unused") @Deprecated - private static <T> Predicate<T> isEntitledOld(final EntitlementManager entitlementManager, final EntitlementClass<T> entitlementClass) { - // TODO PERSISTENCE WORKAROUND - return new Predicate<T>() { - @Override - public boolean apply(@Nullable T t) { - return Entitlements.isEntitled(entitlementManager, entitlementClass, t); - } - }; - } - - public static <T> Predicate<T> isEntitled(final EntitlementManager entitlementManager, final EntitlementClass<T> entitlementClass) { - return new IsEntitled<>(checkNotNull(entitlementManager, "entitlementManager"), checkNotNull(entitlementClass, "entitlementClass")); - } - - protected static class IsEntitled<T> implements Predicate<T> { - private final EntitlementManager entitlementManager; - private final EntitlementClass<T> entitlementClass; - - protected IsEntitled(final EntitlementManager entitlementManager, final EntitlementClass<T> entitlementClass) { - this.entitlementManager = checkNotNull(entitlementManager, "entitlementManager"); - this.entitlementClass = checkNotNull(entitlementClass, "entitlementClass"); - } - @Override - public boolean apply(@Nullable T t) { - return Entitlements.isEntitled(entitlementManager, entitlementClass, t); - } - } -} http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/d03f254b/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/mgmt/entitlement/Entitlements.java ---------------------------------------------------------------------- diff --git a/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/mgmt/entitlement/Entitlements.java b/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/mgmt/entitlement/Entitlements.java deleted file mode 100644 index 6c281fc..0000000 --- a/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/mgmt/entitlement/Entitlements.java +++ /dev/null @@ -1,418 +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.mgmt.entitlement; - -import java.util.Arrays; -import java.util.List; - -import javax.annotation.Nullable; - -import org.apache.brooklyn.api.entity.Entity; -import org.apache.brooklyn.api.mgmt.ManagementContext; -import org.apache.brooklyn.api.mgmt.Task; -import org.apache.brooklyn.api.mgmt.entitlement.EntitlementClass; -import org.apache.brooklyn.api.mgmt.entitlement.EntitlementContext; -import org.apache.brooklyn.api.mgmt.entitlement.EntitlementManager; -import org.apache.brooklyn.config.ConfigKey; -import org.apache.brooklyn.core.config.ConfigKeys; -import org.apache.brooklyn.core.config.Sanitizer; -import org.apache.brooklyn.core.internal.BrooklynProperties; -import org.apache.brooklyn.core.mgmt.BrooklynTaskTags; -import org.apache.brooklyn.core.mgmt.internal.ManagementContextInternal; -import org.apache.brooklyn.core.mgmt.persist.DeserializingClassRenamesProvider; -import org.apache.brooklyn.util.core.task.Tasks; -import org.apache.brooklyn.util.exceptions.Exceptions; -import org.apache.brooklyn.util.javalang.Reflections; -import org.apache.brooklyn.util.text.Strings; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.google.common.annotations.Beta; -import com.google.common.base.Joiner; -import com.google.common.base.Objects; -import com.google.common.base.Optional; -import com.google.common.base.Predicate; -import com.google.common.base.Predicates; -import com.google.common.collect.ImmutableList; -import com.google.common.reflect.TypeToken; - -/** @since 0.7.0 */ -@Beta -public class Entitlements { - - private static final Logger log = LoggerFactory.getLogger(Entitlements.class); - - // ------------------- individual permissions - - public static EntitlementClass<String> SEE_CATALOG_ITEM = new BasicEntitlementClassDefinition<String>("catalog.see", String.class); - public static EntitlementClass<Object> ADD_CATALOG_ITEM = new BasicEntitlementClassDefinition<Object>("catalog.add", Object.class); - public static EntitlementClass<StringAndArgument> MODIFY_CATALOG_ITEM = new BasicEntitlementClassDefinition<StringAndArgument>("catalog.modify", StringAndArgument.class); - - public static EntitlementClass<Entity> SEE_ENTITY = new BasicEntitlementClassDefinition<Entity>("entity.see", Entity.class); - public static EntitlementClass<EntityAndItem<String>> SEE_SENSOR = new BasicEntitlementClassDefinition<EntityAndItem<String>>("sensor.see", EntityAndItem. typeToken(String.class)); - // string is effector name; argument may be a map or a list, depending how the args were supplied - public static EntitlementClass<EntityAndItem<StringAndArgument>> INVOKE_EFFECTOR = new BasicEntitlementClassDefinition<EntityAndItem<StringAndArgument>>("effector.invoke", EntityAndItem.typeToken(StringAndArgument.class)); - public static EntitlementClass<Entity> MODIFY_ENTITY = new BasicEntitlementClassDefinition<Entity>("entity.modify", Entity.class); - - /** the permission to deploy an application, where parameter is some representation of the app to be deployed (spec instance or yaml plan) */ - public static EntitlementClass<Object> DEPLOY_APPLICATION = new BasicEntitlementClassDefinition<Object>("app.deploy", Object.class); - - /** catch-all for catalog, locations, scripting, usage, etc - exporting persistence, shutting down, etc; - * this is significantly more powerful than {@link #SERVER_STATUS}. - * NB: this may be refactored and deprecated in future */ - public static EntitlementClass<Void> SEE_ALL_SERVER_INFO = new BasicEntitlementClassDefinition<Void>("server.info.all.see", Void.class); - - /** permission to see general server status info: basically HA status; not nearly as much as {@link #SEE_ALL_SERVER_INFO} */ - public static EntitlementClass<Void> SERVER_STATUS = new BasicEntitlementClassDefinition<Void>("server.status", Void.class); - - /** permission to run untrusted code or embedded scripts at the server; - * secondary check required for any operation which could potentially grant root-level access */ - public static EntitlementClass<Void> ROOT = new BasicEntitlementClassDefinition<Void>("root", Void.class); - - @SuppressWarnings("unchecked") - public static enum EntitlementClassesEnum { - ENTITLEMENT_SEE_CATALOG_ITEM(SEE_CATALOG_ITEM) { public <T> T handle(EntitlementClassesHandler<T> handler, Object argument) { return handler.handleSeeCatalogItem((String)argument); } }, - ENTITLEMENT_ADD_CATALOG_ITEM(ADD_CATALOG_ITEM) { public <T> T handle(EntitlementClassesHandler<T> handler, Object argument) { return handler.handleAddCatalogItem(argument); } }, - ENTITLEMENT_MODIFY_CATALOG_ITEM(MODIFY_CATALOG_ITEM) { public <T> T handle(EntitlementClassesHandler<T> handler, Object argument) { return handler.handleModifyCatalogItem((StringAndArgument)argument); } }, - - ENTITLEMENT_SEE_ENTITY(SEE_ENTITY) { public <T> T handle(EntitlementClassesHandler<T> handler, Object argument) { return handler.handleSeeEntity((Entity)argument); } }, - ENTITLEMENT_SEE_SENSOR(SEE_SENSOR) { public <T> T handle(EntitlementClassesHandler<T> handler, Object argument) { return handler.handleSeeSensor((EntityAndItem<String>)argument); } }, - ENTITLEMENT_INVOKE_EFFECTOR(INVOKE_EFFECTOR) { public <T> T handle(EntitlementClassesHandler<T> handler, Object argument) { return handler.handleInvokeEffector((EntityAndItem<StringAndArgument>)argument); } }, - ENTITLEMENT_MODIFY_ENTITY(MODIFY_ENTITY) { public <T> T handle(EntitlementClassesHandler<T> handler, Object argument) { return handler.handleModifyEntity((Entity)argument); } }, - - ENTITLEMENT_DEPLOY_APPLICATION(DEPLOY_APPLICATION) { public <T> T handle(EntitlementClassesHandler<T> handler, Object argument) { return handler.handleDeployApplication(argument); } }, - - ENTITLEMENT_SEE_ALL_SERVER_INFO(SEE_ALL_SERVER_INFO) { public <T> T handle(EntitlementClassesHandler<T> handler, Object argument) { return handler.handleSeeAllServerInfo(); } }, - ENTITLEMENT_SERVER_STATUS(SERVER_STATUS) { public <T> T handle(EntitlementClassesHandler<T> handler, Object argument) { return handler.handleSeeServerStatus(); } }, - ENTITLEMENT_ROOT(ROOT) { public <T> T handle(EntitlementClassesHandler<T> handler, Object argument) { return handler.handleRoot(); } }, - ; - - private EntitlementClass<?> entitlementClass; - - private EntitlementClassesEnum(EntitlementClass<?> specificClass) { - this.entitlementClass = specificClass; - } - public EntitlementClass<?> getEntitlementClass() { - return entitlementClass; - } - - public abstract <T> T handle(EntitlementClassesHandler<T> handler, Object argument); - - public static EntitlementClassesEnum of(EntitlementClass<?> entitlementClass) { - for (EntitlementClassesEnum x: values()) { - if (entitlementClass.equals(x.getEntitlementClass())) return x; - } - return null; - } - } - - public interface EntitlementClassesHandler<T> { - public T handleSeeCatalogItem(String catalogItemId); - public T handleSeeServerStatus(); - public T handleAddCatalogItem(Object catalogItemBeingAdded); - public T handleModifyCatalogItem(StringAndArgument catalogItemIdAndModification); - public T handleSeeEntity(Entity entity); - public T handleSeeSensor(EntityAndItem<String> sensorInfo); - public T handleInvokeEffector(EntityAndItem<StringAndArgument> effectorInfo); - public T handleModifyEntity(Entity entity); - public T handleDeployApplication(Object app); - public T handleSeeAllServerInfo(); - public T handleRoot(); - } - - protected static class Pair<T1,T2> { - protected final T1 p1; - protected final T2 p2; - protected Pair(T1 p1, T2 p2) { this.p1 = p1; this.p2 = p2; } - } - public static class EntityAndItem<T> extends Pair<Entity,T> { - public static <TT> TypeToken<EntityAndItem<TT>> typeToken(Class<TT> type) { - return new TypeToken<Entitlements.EntityAndItem<TT>>() { - private static final long serialVersionUID = -738154831809025407L; - }; - } - public EntityAndItem(Entity entity, T item) { super (entity, item); } - public Entity getEntity() { return p1; } - public T getItem() { return p2; } - public static <T> EntityAndItem<T> of(Entity entity, T item) { - return new EntityAndItem<T>(entity, item); - } - } - - public static class StringAndArgument extends Pair<String,Object> { - public StringAndArgument(String string, Object argument) { super(string, argument); } - public String getString() { return p1; } - public Object getArgument() { return p2; } - public static StringAndArgument of(String string, Object argument) { - return new StringAndArgument(string, argument); - } - } - - /** - * These lifecycle operations are currently treated as effectors. This may change in the future. - * @since 0.7.0 */ - @Beta - public static class LifecycleEffectors { - public static final String DELETE = "delete"; - } - - // ------------- permission sets ------------- - - /** always ALLOW access to everything */ - public static EntitlementManager root() { - return new EntitlementManager() { - @Override - public <T> boolean isEntitled(EntitlementContext context, EntitlementClass<T> permission, T typeArgument) { - return true; - } - @Override - public String toString() { - return "Entitlements.root"; - } - }; - } - - /** always DENY access to anything which requires entitlements */ - public static EntitlementManager minimal() { - return new EntitlementManager() { - @Override - public <T> boolean isEntitled(EntitlementContext context, EntitlementClass<T> permission, T typeArgument) { - return false; - } - @Override - public String toString() { - return "Entitlements.minimal"; - } - }; - } - - public static class FineGrainedEntitlements { - - private static final Joiner COMMA_JOINER = Joiner.on(','); - - public static EntitlementManager anyOf(final EntitlementManager... checkers) { - return anyOf(Arrays.asList(checkers)); - } - - public static EntitlementManager anyOf(final Iterable<? extends EntitlementManager> checkers) { - return new EntitlementManager() { - @Override - public <T> boolean isEntitled(EntitlementContext context, EntitlementClass<T> permission, T typeArgument) { - for (EntitlementManager checker: checkers) - if (checker.isEntitled(context, permission, typeArgument)) - return true; - return false; - } - @Override - public String toString() { - return "Entitlements.anyOf(" + COMMA_JOINER.join(checkers) + ")"; - } - }; - } - - public static EntitlementManager allOf(final EntitlementManager... checkers) { - return allOf(Arrays.asList(checkers)); - } - - public static EntitlementManager allOf(final Iterable<? extends EntitlementManager> checkers) { - return new EntitlementManager() { - @Override - public <T> boolean isEntitled(EntitlementContext context, EntitlementClass<T> permission, T typeArgument) { - for (EntitlementManager checker: checkers) - if (checker.isEntitled(context, permission, typeArgument)) - return true; - return false; - } - @Override - public String toString() { - return "Entitlements.allOf(" + COMMA_JOINER.join(checkers) + ")"; - } - }; - } - - public static <U> EntitlementManager allowing(EntitlementClass<U> permission, Predicate<U> test) { - return new SinglePermissionEntitlementChecker<U>(permission, test); - } - - public static <U> EntitlementManager allowing(EntitlementClass<U> permission) { - return new SinglePermissionEntitlementChecker<U>(permission, Predicates.<U>alwaysTrue()); - } - - public static class SinglePermissionEntitlementChecker<U> implements EntitlementManager { - final EntitlementClass<U> permission; - final Predicate<U> test; - - protected SinglePermissionEntitlementChecker(EntitlementClass<U> permission, Predicate<U> test) { - this.permission = permission; - this.test = test; - } - - @SuppressWarnings("unchecked") - @Override - public <T> boolean isEntitled(EntitlementContext context, EntitlementClass<T> permission, T typeArgument) { - if (!Objects.equal(this.permission, permission)) return false; - return test.apply((U)typeArgument); - } - @Override - public String toString() { - return "Entitlements.allowing(" + permission + " -> " + test + ")"; - } - } - public static EntitlementManager seeNonSecretSensors() { - return allowing(SEE_SENSOR, new Predicate<EntityAndItem<String>>() { - @Override - public boolean apply(EntityAndItem<String> input) { - if (input == null) return false; - return !Sanitizer.IS_SECRET_PREDICATE.apply(input.getItem()); - } - @Override - public String toString() { - return "Predicates.nonSecret"; - } - }); - } - - } - - /** allow read-only */ - public static EntitlementManager readOnly() { - return FineGrainedEntitlements.anyOf( - FineGrainedEntitlements.allowing(SEE_ENTITY), - FineGrainedEntitlements.seeNonSecretSensors() - ); - } - - /** allow healthcheck */ - public static EntitlementManager serverStatusOnly() { - return FineGrainedEntitlements.allowing(SERVER_STATUS); - } - - // ------------- lookup conveniences ------------- - - private static class PerThreadEntitlementContextHolder { - public static final ThreadLocal<EntitlementContext> perThreadEntitlementsContextHolder = new ThreadLocal<EntitlementContext>(); - } - - /** - * Finds the currently applicable {@link EntitlementContext} by examining the current thread - * then by investigating the current task, its submitter, etc. */ - // NOTE: entitlements are propagated to tasks whenever they are created, as tags - // (see BrooklynTaskTags.tagForEntitlement and BasicExecutionContext.submitInternal). - // It might be cheaper to only do this lookup, not to propagate as tags, and to ensure - // all entitlement operations are wrapped in a task at source; but currently we do not - // do that so we need at least to set entitlement on the outermost task. - // Setting it on tasks submitted by a task is not strictly necessary (i.e. in BasicExecutionContext) - // but seems cheap enough, and means checking entitlements is fast, if we choose to do that more often. - public static EntitlementContext getEntitlementContext() { - EntitlementContext context; - context = PerThreadEntitlementContextHolder.perThreadEntitlementsContextHolder.get(); - if (context!=null) return context; - - Task<?> task = Tasks.current(); - while (task!=null) { - context = BrooklynTaskTags.getEntitlement(task); - if (context!=null) return context; - task = task.getSubmittedByTask(); - } - - // no entitlements set -- assume entitlements not used, or system internal - return null; - } - - public static void setEntitlementContext(EntitlementContext context) { - EntitlementContext oldContext = PerThreadEntitlementContextHolder.perThreadEntitlementsContextHolder.get(); - if (oldContext!=null && context!=null) { - log.warn("Changing entitlement context from "+oldContext+" to "+context+"; context should have been reset or extended, not replaced"); - log.debug("Trace for entitlement context duplicate overwrite", new Throwable("Trace for entitlement context overwrite")); - } - PerThreadEntitlementContextHolder.perThreadEntitlementsContextHolder.set(context); - } - - public static void clearEntitlementContext() { - PerThreadEntitlementContextHolder.perThreadEntitlementsContextHolder.set(null); - } - - public static <T> boolean isEntitled(EntitlementManager checker, EntitlementClass<T> permission, T typeArgument) { - return checker.isEntitled(getEntitlementContext(), permission, typeArgument); - } - - /** throws {@link NotEntitledException} if entitlement not available for current {@link #getEntitlementContext()} */ - public static <T> void checkEntitled(EntitlementManager checker, EntitlementClass<T> permission, T typeArgument) { - if (!isEntitled(checker, permission, typeArgument)) { - throw new NotEntitledException(getEntitlementContext(), permission, typeArgument); - } - } - /** throws {@link NotEntitledException} if entitlement not available for current {@link #getEntitlementContext()} - * @since 0.7.0 - * @deprecated since 0.7.0, use {@link #checkEntitled(EntitlementManager, EntitlementClass, Object)}; - * kept briefly because there is some downstream usage*/ - public static <T> void requireEntitled(EntitlementManager checker, EntitlementClass<T> permission, T typeArgument) { - checkEntitled(checker, permission, typeArgument); - } - - // ----------------- initialization ---------------- - - public final static String ENTITLEMENTS_CONFIG_PREFIX = "brooklyn.entitlements"; - - public static ConfigKey<String> GLOBAL_ENTITLEMENT_MANAGER = ConfigKeys.newStringConfigKey(ENTITLEMENTS_CONFIG_PREFIX+".global", - "Class for entitlements in effect globally; " - + "short names 'minimal', 'readonly', or 'root' are permitted here, with the default 'root' giving full access to all declared users; " - + "or supply the name of an "+EntitlementManager.class+" class to instantiate, taking a 1-arg BrooklynProperties constructor or a 0-arg constructor", - "root"); - - public static EntitlementManager newManager(ManagementContext mgmt, BrooklynProperties brooklynProperties) { - return newGlobalManager(mgmt, brooklynProperties); - } - private static EntitlementManager newGlobalManager(ManagementContext mgmt, BrooklynProperties brooklynProperties) { - return load(mgmt, brooklynProperties, brooklynProperties.getConfig(GLOBAL_ENTITLEMENT_MANAGER)); - } - - public static EntitlementManager load(@Nullable ManagementContext mgmt, BrooklynProperties brooklynProperties, String type) { - if ("root".equalsIgnoreCase(type)) return root(); - if ("readonly".equalsIgnoreCase(type) || "read_only".equalsIgnoreCase(type)) return readOnly(); - if ("minimal".equalsIgnoreCase(type)) return minimal(); - if (Strings.isNonBlank(type)) { - try { - ClassLoader cl = mgmt==null ? null : ((ManagementContextInternal)mgmt).getCatalogClassLoader(); - if (cl==null) cl = Entitlements.class.getClassLoader(); - Class<?> clazz = cl.loadClass(DeserializingClassRenamesProvider.findMappedName(type)); - return (EntitlementManager) instantiate(clazz, ImmutableList.of( - new Object[] {mgmt, brooklynProperties}, - new Object[] {mgmt}, - new Object[] {brooklynProperties}, - new Object[0])); - } catch (Exception e) { - throw Exceptions.propagate(e); - } - } - throw new IllegalStateException("Invalid entitlement manager specified: '"+type+"'"); - } - - private static Object instantiate(Class<?> clazz, List<Object[]> constructorArgOptions) { - try { - for (Object[] constructorArgOption : constructorArgOptions) { - Optional<?> result = Reflections.invokeConstructorWithArgs(clazz, constructorArgOption); - if (result.isPresent()) return result.get(); - } - } catch (Exception e) { - throw Exceptions.propagate(e); - } - throw new IllegalStateException("No matching constructor to instantiate "+clazz); - } -} http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/d03f254b/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/mgmt/entitlement/NotEntitledException.java ---------------------------------------------------------------------- diff --git a/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/mgmt/entitlement/NotEntitledException.java b/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/mgmt/entitlement/NotEntitledException.java deleted file mode 100644 index 76ae278..0000000 --- a/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/mgmt/entitlement/NotEntitledException.java +++ /dev/null @@ -1,44 +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.mgmt.entitlement; - -import org.apache.brooklyn.api.mgmt.entitlement.EntitlementClass; -import org.apache.brooklyn.api.mgmt.entitlement.EntitlementContext; - - -public class NotEntitledException extends RuntimeException { - - private static final long serialVersionUID = -4001882260980589181L; - - EntitlementContext entitlementContext; - EntitlementClass<?> permission; - Object typeArgument; - - public <T> NotEntitledException(EntitlementContext entitlementContext, EntitlementClass<T> permission, T typeArgument) { - this.entitlementContext = entitlementContext; - this.permission = permission; - this.typeArgument = typeArgument; - } - - @Override - public String toString() { - return super.toString()+"["+entitlementContext+":"+permission+(typeArgument!=null ? "("+typeArgument+")" : "")+"]"; - } - -}
