http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/main/java/brooklyn/util/exceptions/PropagatedRuntimeException.java ---------------------------------------------------------------------- diff --git a/utils/common/src/main/java/brooklyn/util/exceptions/PropagatedRuntimeException.java b/utils/common/src/main/java/brooklyn/util/exceptions/PropagatedRuntimeException.java deleted file mode 100644 index 07f4ca7..0000000 --- a/utils/common/src/main/java/brooklyn/util/exceptions/PropagatedRuntimeException.java +++ /dev/null @@ -1,70 +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 brooklyn.util.exceptions; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** Indicates a runtime exception which has been propagated via {@link Exceptions#propagate} */ -public class PropagatedRuntimeException extends RuntimeException { - - private static final long serialVersionUID = 3959054308510077172L; - private static final Logger LOG = LoggerFactory.getLogger(PropagatedRuntimeException.class); - - private final boolean causeEmbeddedInMessage; - - /** Callers should typically *not* attempt to summarise the cause in the message here; use toString() to get extended information */ - public PropagatedRuntimeException(String message, Throwable cause) { - super(message, cause); - warnIfWrapping(cause); - causeEmbeddedInMessage = message.endsWith(Exceptions.collapseText(getCause())); - } - - public PropagatedRuntimeException(String message, Throwable cause, boolean causeEmbeddedInMessage) { - super(message, cause); - warnIfWrapping(cause); - this.causeEmbeddedInMessage = causeEmbeddedInMessage; - } - - public PropagatedRuntimeException(Throwable cause) { - super("" /* do not use default message as that destroys the toString */, cause); - warnIfWrapping(cause); - causeEmbeddedInMessage = false; - } - - private void warnIfWrapping(Throwable cause) { - if (LOG.isTraceEnabled() && cause instanceof PropagatedRuntimeException) { - LOG.trace("Wrapping a PropagatedRuntimeException in another PropagatedRuntimeException. Call chain:", new Exception()); - } - } - - @Override - public String toString() { - if (causeEmbeddedInMessage) { - return super.toString(); - } else { - return Exceptions.appendSeparator(super.toString(), Exceptions.collapseText(getCause())); - } - } - - public boolean isCauseEmbeddedInMessage() { - return causeEmbeddedInMessage; - } - -}
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/main/java/brooklyn/util/exceptions/ReferenceWithError.java ---------------------------------------------------------------------- diff --git a/utils/common/src/main/java/brooklyn/util/exceptions/ReferenceWithError.java b/utils/common/src/main/java/brooklyn/util/exceptions/ReferenceWithError.java deleted file mode 100644 index bd52b3f..0000000 --- a/utils/common/src/main/java/brooklyn/util/exceptions/ReferenceWithError.java +++ /dev/null @@ -1,101 +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 brooklyn.util.exceptions; - -import javax.annotation.Nullable; - -import com.google.common.annotations.Beta; -import com.google.common.base.Supplier; - -/** A reference to an object which can carry an object alongside it. */ -@Beta -public class ReferenceWithError<T> implements Supplier<T> { - - private final T object; - private final Throwable error; - private final boolean maskError; - - /** returns a reference which includes an error, and where attempts to get the content cause the error to throw */ - public static <T> ReferenceWithError<T> newInstanceThrowingError(T object, Throwable error) { - return new ReferenceWithError<T>(object, error, false); - } - - /** returns a reference which includes an error, but attempts to get the content do not cause the error to throw */ - public static <T> ReferenceWithError<T> newInstanceMaskingError(T object, Throwable error) { - return new ReferenceWithError<T>(object, error, true); - } - - /** returns a reference which includes an error, but attempts to get the content do not cause the error to throw */ - public static <T> ReferenceWithError<T> newInstanceWithoutError(T object) { - return new ReferenceWithError<T>(object, null, false); - } - - protected ReferenceWithError(@Nullable T object, @Nullable Throwable error, boolean maskError) { - this.object = object; - this.error = error; - this.maskError = maskError; - } - - /** whether this will mask any error on an attempt to {@link #get()}; - * if false (if created with {@link #newInstanceThrowingError(Object, Throwable)}) a call to {@link #get()} will throw if there is an error; - * true if created with {@link #newInstanceMaskingError(Object, Throwable)} and {@link #get()} will not throw */ - public boolean masksErrorIfPresent() { - return maskError; - } - - /** returns the underlying value, throwing if there is an error which is not masked (ie {@link #throwsErrorOnAccess()} is set) */ - public T get() { - if (masksErrorIfPresent()) { - return getWithoutError(); - } - return getWithError(); - } - - /** returns the object, ignoring any error (even non-masked) */ - public T getWithoutError() { - return object; - } - - /** throws error, even if there is one (even if masked), else returns the object */ - public T getWithError() { - checkNoError(); - return object; - } - - /** throws if there is an error (even if masked) */ - public void checkNoError() { - if (hasError()) - Exceptions.propagate(error); - } - - /** returns the error (not throwing) */ - public Throwable getError() { - return error; - } - - /** true if there is an error (whether masked or not) */ - public boolean hasError() { - return error!=null; - } - - @Override - public String toString() { - return getClass().getSimpleName()+"["+object+(error!=null?"/"+(maskError?"masking:":"throwing:")+error:"")+"]"; - } -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/main/java/brooklyn/util/exceptions/RuntimeInterruptedException.java ---------------------------------------------------------------------- diff --git a/utils/common/src/main/java/brooklyn/util/exceptions/RuntimeInterruptedException.java b/utils/common/src/main/java/brooklyn/util/exceptions/RuntimeInterruptedException.java deleted file mode 100644 index d9dae6b..0000000 --- a/utils/common/src/main/java/brooklyn/util/exceptions/RuntimeInterruptedException.java +++ /dev/null @@ -1,50 +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 brooklyn.util.exceptions; - -/** - * A {@link RuntimeException} that is thrown when a Thread is interrupted. - * <p> - * This exception is useful if a Thread needs to be interrupted, but the {@link InterruptedException} can't be thrown - * because it is checked. - * <p> - * When the {@link RuntimeInterruptedException} is created, it will automatically set the interrupt status on the calling - * thread. - * - * @author Peter Veentjer. - */ -public class RuntimeInterruptedException extends RuntimeException { - - private static final long serialVersionUID = 915050245927866175L; - - public RuntimeInterruptedException(InterruptedException cause) { - super(cause); - Thread.currentThread().interrupt(); - } - - public RuntimeInterruptedException(String msg, InterruptedException cause) { - super(msg, cause); - Thread.currentThread().interrupt(); - } - - @Override - public InterruptedException getCause() { - return (InterruptedException) super.getCause(); - } -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/main/java/brooklyn/util/exceptions/RuntimeTimeoutException.java ---------------------------------------------------------------------- diff --git a/utils/common/src/main/java/brooklyn/util/exceptions/RuntimeTimeoutException.java b/utils/common/src/main/java/brooklyn/util/exceptions/RuntimeTimeoutException.java deleted file mode 100644 index 865ae73..0000000 --- a/utils/common/src/main/java/brooklyn/util/exceptions/RuntimeTimeoutException.java +++ /dev/null @@ -1,36 +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 brooklyn.util.exceptions; - -public class RuntimeTimeoutException extends IllegalStateException { - - private static final long serialVersionUID = -3359163414517503809L; - - public RuntimeTimeoutException() { - super("timeout"); - } - - public RuntimeTimeoutException(String message) { - super(message); - } - - public RuntimeTimeoutException(String message, Throwable cause) { - super(message, cause); - } -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/main/java/brooklyn/util/exceptions/UserFacingException.java ---------------------------------------------------------------------- diff --git a/utils/common/src/main/java/brooklyn/util/exceptions/UserFacingException.java b/utils/common/src/main/java/brooklyn/util/exceptions/UserFacingException.java deleted file mode 100644 index b7237ac..0000000 --- a/utils/common/src/main/java/brooklyn/util/exceptions/UserFacingException.java +++ /dev/null @@ -1,39 +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 brooklyn.util.exceptions; - -/** marker interface, to show that an exception is suitable for pretty-printing to an end-user, - * without including a stack trace */ -public class UserFacingException extends RuntimeException { - - private static final long serialVersionUID = 2216885527195571323L; - - public UserFacingException(String message) { - super(message); - } - - public UserFacingException(Throwable cause) { - super(cause.getMessage(), cause); - } - - public UserFacingException(String message, Throwable cause) { - super(message, cause); - } - -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/main/java/brooklyn/util/git/GithubUrls.java ---------------------------------------------------------------------- diff --git a/utils/common/src/main/java/brooklyn/util/git/GithubUrls.java b/utils/common/src/main/java/brooklyn/util/git/GithubUrls.java deleted file mode 100644 index d38b66d..0000000 --- a/utils/common/src/main/java/brooklyn/util/git/GithubUrls.java +++ /dev/null @@ -1,42 +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 brooklyn.util.git; - -import brooklyn.util.net.Urls; - -public class GithubUrls { - - public static String BASE_URL = "https://github.com/"; - - /** returns URL for the root of the given repo */ - public static String root(String owner, String repo) { - return Urls.mergePaths(BASE_URL, owner, repo); - } - - /** returns URL for downloading a .tar.gz version of a tag of a repository */ - public static String tgz(String owner, String repo, String tag) { - return Urls.mergePaths(root(owner, repo), "archive", tag+".tar.gz"); - } - - /** returns URL for downloading a .zip version of a tag of a repository */ - public static String zip(String owner, String repo, String tag) { - return Urls.mergePaths(root(owner, repo), "archive", tag+".zip"); - } - -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/main/java/brooklyn/util/guava/Functionals.java ---------------------------------------------------------------------- diff --git a/utils/common/src/main/java/brooklyn/util/guava/Functionals.java b/utils/common/src/main/java/brooklyn/util/guava/Functionals.java deleted file mode 100644 index 08e41b1..0000000 --- a/utils/common/src/main/java/brooklyn/util/guava/Functionals.java +++ /dev/null @@ -1,151 +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 brooklyn.util.guava; - -import java.util.concurrent.Callable; - -import brooklyn.util.guava.IfFunctions.IfFunctionBuilderApplyingFirst; - -import com.google.common.base.Function; -import com.google.common.base.Functions; -import com.google.common.base.Predicate; -import com.google.common.base.Supplier; -import com.google.common.base.Suppliers; - -public class Functionals { - - /** applies f1 to the input, then the result of that is passed to f2 (note opposite semantics to {@link Functions#compose(Function, Function)} */ - public static <A,B,C> Function<A,C> chain(final Function<A,? extends B> f1, final Function<B,C> f2) { - return Functions.compose(f2, f1); - } - - /** applies f1 to the input, then f2 to that result, then f3 to that result */ - public static <A,B,C,D> Function<A,D> chain(final Function<A,? extends B> f1, final Function<B,? extends C> f2, final Function<C,D> f3) { - return chain(f1, chain(f2, f3)); - } - - /** applies f1 to the input, then f2 to that result, then f3 to that result, then f4 to that result */ - public static <A,B,C,D,E> Function<A,E> chain(final Function<A,? extends B> f1, final Function<B,? extends C> f2, final Function<C,? extends D> f3, final Function<D,E> f4) { - return chain(f1, chain(f2, chain(f3, f4))); - } - - /** @see IfFunctions */ - public static <I> IfFunctionBuilderApplyingFirst<I> ifEquals(I test) { - return IfFunctions.ifEquals(test); - } - - /** @see IfFunctions */ - public static <I> IfFunctionBuilderApplyingFirst<I> ifNotEquals(I test) { - return IfFunctions.ifNotEquals(test); - } - - /** @see IfFunctions */ - public static <I> IfFunctionBuilderApplyingFirst<I> ifPredicate(Predicate<I> test) { - return IfFunctions.ifPredicate(test); - } - - /** like guava equivalent but parametrises the input generic type, and allows tostring to be customised */ - public static final class ConstantFunction<I, O> implements Function<I, O> { - private final O constant; - private Object toStringDescription; - - public ConstantFunction(O constant) { - this(constant, null); - } - public ConstantFunction(O constant, Object toStringDescription) { - this.constant = constant; - this.toStringDescription = toStringDescription; - } - - @Override - public O apply(I input) { - return constant; - } - - @Override - public String toString() { - return toStringDescription==null ? "constant("+constant+")" : toStringDescription.toString(); - } - } - - /** like guava {@link Functions#forSupplier(Supplier)} but parametrises the input generic type */ - public static <I,O> Function<I,O> function(final Supplier<O> supplier) { - class SupplierAsFunction implements Function<I,O> { - @Override public O apply(I input) { - return supplier.get(); - } - @Override public String toString() { - return "function("+supplier+")"; - } - } - return new SupplierAsFunction(); - } - - public static <I> Function<I,Void> function(final Runnable runnable) { - class RunnableAsFunction implements Function<I,Void> { - @Override public Void apply(I input) { - runnable.run(); - return null; - } - } - return new RunnableAsFunction(); - } - - public static Runnable runnable(final Supplier<?> supplier) { - class SupplierAsRunnable implements Runnable { - @Override - public void run() { - supplier.get(); - } - } - return new SupplierAsRunnable(); - } - - public static <T> Callable<T> callable(final Supplier<T> supplier) { - class SupplierAsCallable implements Callable<T> { - @Override - public T call() { - return supplier.get(); - } - @Override - public String toString() { - return "callable("+supplier+")"; - } - } - return new SupplierAsCallable(); - } - public static <T,U> Callable<U> callable(Function<T,U> f, T x) { - return callable(Suppliers.compose(f, Suppliers.ofInstance(x))); - } - - public static <T> Predicate<T> predicate(final Function<T,Boolean> f) { - class FunctionAsPredicate implements Predicate<T> { - @Override - public boolean apply(T input) { - return f.apply(input); - } - @Override - public String toString() { - return "predicate("+f+")"; - } - } - return new FunctionAsPredicate(); - } - -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/main/java/brooklyn/util/guava/IfFunctions.java ---------------------------------------------------------------------- diff --git a/utils/common/src/main/java/brooklyn/util/guava/IfFunctions.java b/utils/common/src/main/java/brooklyn/util/guava/IfFunctions.java deleted file mode 100644 index ceea8c3..0000000 --- a/utils/common/src/main/java/brooklyn/util/guava/IfFunctions.java +++ /dev/null @@ -1,158 +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 brooklyn.util.guava; - -import java.util.LinkedHashMap; -import java.util.Map; - -import com.google.common.annotations.Beta; -import com.google.common.base.Function; -import com.google.common.base.Functions; -import com.google.common.base.Predicate; -import com.google.common.base.Predicates; -import com.google.common.base.Supplier; - -/** Utilities for building {@link Function} instances which return specific values - * (or {@link Supplier} or {@link Function} instances) when certain predicates are satisfied, - * tested in order and returning the first matching, - * with support for an "else" default value if none are satisfied (null by default). */ -public class IfFunctions { - - public static <I,O> IfFunctionBuilder<I,O> newInstance(Class<I> testType, Class<O> returnType) { - return new IfFunctionBuilder<I,O>(); - } - - public static <I> IfFunctionBuilderApplyingFirst<I> ifPredicate(Predicate<? super I> test) { - return new IfFunctionBuilderApplyingFirst<I>(test); - } - public static <I> IfFunctionBuilderApplyingFirst<I> ifEquals(I test) { - return ifPredicate(Predicates.equalTo(test)); - } - public static <I> IfFunctionBuilderApplyingFirst<I> ifNotEquals(I test) { - return ifPredicate(Predicates.not(Predicates.equalTo(test))); - } - - @Beta - public static class IfFunction<I,O> implements Function<I,O> { - protected final Map<Predicate<? super I>,Function<? super I,? extends O>> tests = new LinkedHashMap<Predicate<? super I>,Function<? super I,? extends O>>(); - protected Function<? super I,? extends O> defaultFunction = null; - - protected IfFunction(IfFunction<I,O> input) { - this.tests.putAll(input.tests); - this.defaultFunction = input.defaultFunction; - } - - protected IfFunction() { - } - - @Override - public O apply(I input) { - for (Map.Entry<Predicate<? super I>,Function<? super I,? extends O>> test: tests.entrySet()) { - if (test.getKey().apply(input)) - return test.getValue().apply(input); - } - return defaultFunction==null ? null : defaultFunction.apply(input); - } - - @Override - public String toString() { - return "if["+tests+"]"+(defaultFunction!=null ? "-else["+defaultFunction+"]" : ""); - } - } - - @Beta - public static class IfFunctionBuilder<I,O> extends IfFunction<I,O> { - protected IfFunctionBuilder() { super(); } - protected IfFunctionBuilder(IfFunction<I,O> input) { super(input); } - - public IfFunction<I,O> build() { - return new IfFunction<I,O>(this); - } - - public IfFunctionBuilderApplying<I,O> ifPredicate(Predicate<I> test) { - return new IfFunctionBuilderApplying<I,O>(this, (Predicate<I>)test); - } - public IfFunctionBuilderApplying<I,O> ifEquals(I test) { - return ifPredicate(Predicates.equalTo(test)); - } - public IfFunctionBuilderApplying<I,O> ifNotEquals(I test) { - return ifPredicate(Predicates.not(Predicates.equalTo(test))); - } - - public IfFunctionBuilder<I,O> defaultValue(O defaultValue) { - return defaultApply(new Functionals.ConstantFunction<I,O>(defaultValue, defaultValue)); - } - @SuppressWarnings("unchecked") - public IfFunctionBuilder<I,O> defaultGet(Supplier<? extends O> defaultSupplier) { - return defaultApply((Function<I,O>)Functions.forSupplier(defaultSupplier)); - } - public IfFunctionBuilder<I,O> defaultApply(Function<? super I,? extends O> defaultFunction) { - IfFunctionBuilder<I, O> result = new IfFunctionBuilder<I,O>(this); - result.defaultFunction = defaultFunction; - return result; - } - } - - @Beta - public static class IfFunctionBuilderApplying<I,O> { - private IfFunction<I, O> input; - private Predicate<? super I> test; - - private IfFunctionBuilderApplying(IfFunction<I,O> input, Predicate<? super I> test) { - this.input = input; - this.test = test; - } - - public IfFunctionBuilder<I,O> value(O value) { - return apply(new Functionals.ConstantFunction<I,O>(value, value)); - } - @SuppressWarnings("unchecked") - public IfFunctionBuilder<I,O> get(Supplier<? extends O> supplier) { - return apply((Function<I,O>)Functions.forSupplier(supplier)); - } - public IfFunctionBuilder<I,O> apply(Function<? super I,? extends O> function) { - IfFunctionBuilder<I, O> result = new IfFunctionBuilder<I,O>(input); - result.tests.put(test, function); - return result; - } - } - - @Beta - public static class IfFunctionBuilderApplyingFirst<I> { - private Predicate<? super I> test; - - private IfFunctionBuilderApplyingFirst(Predicate<? super I> test) { - this.test = test; - } - - public <O> IfFunctionBuilder<I,O> value(O value) { - return apply(new Functionals.ConstantFunction<I,O>(value, value)); - } - @SuppressWarnings("unchecked") - public <O> IfFunctionBuilder<I,O> get(Supplier<? extends O> supplier) { - return apply((Function<I,O>)Functions.forSupplier(supplier)); - } - public <O> IfFunctionBuilder<I,O> apply(Function<? super I,? extends O> function) { - IfFunctionBuilder<I, O> result = new IfFunctionBuilder<I,O>(); - result.tests.put(test, function); - return result; - } - } - -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/main/java/brooklyn/util/guava/IllegalStateExceptionSupplier.java ---------------------------------------------------------------------- diff --git a/utils/common/src/main/java/brooklyn/util/guava/IllegalStateExceptionSupplier.java b/utils/common/src/main/java/brooklyn/util/guava/IllegalStateExceptionSupplier.java deleted file mode 100644 index b75bca2..0000000 --- a/utils/common/src/main/java/brooklyn/util/guava/IllegalStateExceptionSupplier.java +++ /dev/null @@ -1,43 +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 brooklyn.util.guava; - -import com.google.common.base.Supplier; - -public class IllegalStateExceptionSupplier implements Supplier<RuntimeException> { - - public static final IllegalStateExceptionSupplier EMPTY_EXCEPTION = new IllegalStateExceptionSupplier(); - - protected final String message; - protected final Throwable cause; - - public IllegalStateExceptionSupplier() { this(null, null); } - public IllegalStateExceptionSupplier(String message) { this(message, null); } - public IllegalStateExceptionSupplier(Throwable cause) { this(cause!=null ? cause.getMessage() : null, cause); } - public IllegalStateExceptionSupplier(String message, Throwable cause) { - this.message = message; - this.cause = cause; - } - - @Override - public RuntimeException get() { - return new IllegalStateException(message, cause); - } - -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/main/java/brooklyn/util/guava/KeyTransformingLoadingCache.java ---------------------------------------------------------------------- diff --git a/utils/common/src/main/java/brooklyn/util/guava/KeyTransformingLoadingCache.java b/utils/common/src/main/java/brooklyn/util/guava/KeyTransformingLoadingCache.java deleted file mode 100644 index 73ab2f5..0000000 --- a/utils/common/src/main/java/brooklyn/util/guava/KeyTransformingLoadingCache.java +++ /dev/null @@ -1,152 +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 brooklyn.util.guava; - -import java.util.concurrent.Callable; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.ExecutionException; - -import com.google.common.base.Function; -import com.google.common.cache.AbstractLoadingCache; -import com.google.common.cache.CacheStats; -import com.google.common.cache.LoadingCache; -import com.google.common.collect.ImmutableMap; - -/** - * A cache that transforms its keys before deferring to a delegate {@link LoadingCache}. - */ -// Concise names welcome. -public class KeyTransformingLoadingCache<A, B, V> extends AbstractLoadingCache<A, V> { - - private final LoadingCache<B, V> delegate; - private final Function<A, B> keyTransformer; - - public KeyTransformingLoadingCache(LoadingCache<B, V> delegate, Function<A, B> keyTransformer) { - this.delegate = delegate; - this.keyTransformer = keyTransformer; - } - - public static <A, B, V> KeyTransformingLoadingCache<A, B, V> from(LoadingCache<B, V> delegate, Function<A, B> keyTransformer) { - return new KeyTransformingLoadingCache<A, B, V>(delegate, keyTransformer); - } - - protected Function<A, B> keyTransformer() { - return keyTransformer; - } - - protected LoadingCache<B, V> delegate() { - return delegate; - } - - @Override - public V getIfPresent(Object key) { - try { - @SuppressWarnings("unchecked") - A cast = (A) key; - return delegate().getIfPresent(keyTransformer().apply(cast)); - } catch (ClassCastException e) { - return null; - } - } - - @Override - public V get(A key, Callable<? extends V> valueLoader) throws ExecutionException { - return delegate().get(keyTransformer().apply(key), valueLoader); - } - - /** - * Undefined because we can't prohibit a surjective {@link #keyTransformer()}. - * @throws UnsupportedOperationException - */ - @Override - public ImmutableMap<A, V> getAllPresent(Iterable<?> keys) { - throw new UnsupportedOperationException("getAllPresent in "+getClass().getName() + " undefined"); - } - - @Override - public void put(A key, V value) { - delegate().put(keyTransformer().apply(key), value); - } - - @Override - public void invalidate(Object key) { - try { - @SuppressWarnings("unchecked") - A cast = (A) key; - delegate().invalidate(keyTransformer().apply(cast)); - } catch (ClassCastException e) { - // Ignore - } - } - - @Override - public void invalidateAll() { - delegate().invalidateAll(); - } - - @Override - public long size() { - return delegate().size(); - } - - @Override - public CacheStats stats() { - return delegate().stats(); - } - - @Override - public V get(A key) throws ExecutionException { - return delegate().get(keyTransformer().apply(key)); - } - - @Override - public void refresh(A key) { - delegate().refresh(keyTransformer().apply(key)); - } - - /** - * Undefined because input values are not tracked. - * @throws UnsupportedOperationException - */ - @Override - public ConcurrentMap<A, V> asMap() { - throw new UnsupportedOperationException("asMap in " + getClass().getName() + " undefined"); - } - - @Override - public void cleanUp() { - delegate().cleanUp(); - } - - // Users can avoid middle type parameter. - public static class KeyTransformingSameTypeLoadingCache<A, V> extends KeyTransformingLoadingCache<A, A, V> { - public KeyTransformingSameTypeLoadingCache(LoadingCache<A, V> delegate, Function<A, A> keyTransformer) { - super(delegate, keyTransformer); - } - - // IDE note: This was named `from` to be consistent with KeyTransformingLoadingCache but Intellij 13 - // claims a name clash with the superclass `from`: - // java: name clash: <A,V>from(LoadingCache<A,V>, Function<A,A>) in KeyTransformingSameTypeLoadingCache - // and <A,B,V>from(LoadingCache<B,V>, Function<A,B>) in KeyTransformingLoadingCache have the same erasure, - // yet neither hides the other - public static <A, V> KeyTransformingSameTypeLoadingCache<A, V> with(LoadingCache<A, V> delegate, Function<A, A> keyTransformer) { - return new KeyTransformingSameTypeLoadingCache<A, V>(delegate, keyTransformer); - } - } -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/main/java/brooklyn/util/guava/Maybe.java ---------------------------------------------------------------------- diff --git a/utils/common/src/main/java/brooklyn/util/guava/Maybe.java b/utils/common/src/main/java/brooklyn/util/guava/Maybe.java deleted file mode 100644 index 1c0fcda..0000000 --- a/utils/common/src/main/java/brooklyn/util/guava/Maybe.java +++ /dev/null @@ -1,296 +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 brooklyn.util.guava; - -import static com.google.common.base.Preconditions.checkNotNull; - -import java.io.Serializable; -import java.lang.ref.SoftReference; -import java.util.Collections; -import java.util.Iterator; -import java.util.Set; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; - -import brooklyn.util.javalang.JavaClassNames; - -import com.google.common.annotations.Beta; -import com.google.common.base.Function; -import com.google.common.base.Objects; -import com.google.common.base.Optional; -import com.google.common.base.Preconditions; -import com.google.common.base.Supplier; -import com.google.common.collect.AbstractIterator; -import com.google.common.collect.ImmutableSet; - -/** Like Guava Optional but permitting null and permitting errors to be thrown. */ -public abstract class Maybe<T> implements Serializable, Supplier<T> { - - private static final long serialVersionUID = -6372099069863179019L; - - public static <T> Maybe<T> absent() { - return new Absent<T>(); - } - - /** Creates an absent whose get throws an {@link IllegalStateException} with the indicated message. - * Both stack traces (the cause and the callers) are provided, which can be quite handy. */ - public static <T> Maybe<T> absent(final String message) { - return absent(new IllegalStateExceptionSupplier(message)); - } - - /** Creates an absent whose get throws an {@link IllegalStateException} with the indicated cause. - * Both stack traces (the cause and the callers) are provided, which can be quite handy. */ - public static <T> Maybe<T> absent(final Throwable cause) { - return absent(new IllegalStateExceptionSupplier(cause)); - } - - /** Creates an absent whose get throws an {@link IllegalStateException} with the indicated message and underlying cause. - * Both stack traces (the cause and the callers) are provided, which can be quite handy. */ - public static <T> Maybe<T> absent(final String message, final Throwable cause) { - return absent(new IllegalStateExceptionSupplier(message, cause)); - } - - /** Creates an absent whose get throws an {@link RuntimeException} generated on demand from the given supplier */ - public static <T> Maybe<T> absent(final Supplier<? extends RuntimeException> exceptionSupplier) { - return new Absent<T>(Preconditions.checkNotNull(exceptionSupplier)); - } - - public static <T> Maybe<T> of(@Nullable T value) { - return new Present<T>(value); - } - - /** creates an instance wrapping a {@link SoftReference}, so it might go absent later on */ - public static <T> Maybe<T> soft(T value) { - return softThen(value, null); - } - /** creates an instance wrapping a {@link SoftReference}, using the second item given if lost */ - public static <T> Maybe<T> softThen(T value, Maybe<T> ifEmpty) { - if (value==null) return of((T)null); - return new SoftlyPresent<T>(value).usingAfterExpiry(ifEmpty); - } - - /** like {@link Optional#fromNullable(Object)}, returns absent if the argument is null */ - public static <T> Maybe<T> fromNullable(@Nullable T value) { - if (value==null) return absent(); - return new Present<T>(value); - } - - public static <T> Maybe<T> of(final Optional<T> value) { - if (value.isPresent()) return new AbstractPresent<T>() { - private static final long serialVersionUID = -5735268814211401356L; - @Override - public T get() { - return value.get(); - } - }; - return absent(); - } - - public static <T> Maybe<T> of(final Supplier<T> value) { - return new AbstractPresent<T>() { - private static final long serialVersionUID = -5735268814211401356L; - @Override - public T get() { - return value.get(); - } - }; - } - - /** returns a Maybe containing the next element in the iterator, or absent if none */ - public static <T> Maybe<T> next(Iterator<T> iterator) { - return iterator.hasNext() ? Maybe.of(iterator.next()) : Maybe.<T>absent(); - } - - public abstract boolean isPresent(); - public abstract T get(); - - public boolean isAbsent() { - return !isPresent(); - } - public boolean isAbsentOrNull() { - return !isPresentAndNonNull(); - } - public boolean isPresentAndNonNull() { - return isPresent() && get()!=null; - } - - public T or(T nextValue) { - if (isPresent()) return get(); - return nextValue; - } - - public Maybe<T> or(Maybe<T> nextValue) { - if (isPresent()) return this; - return nextValue; - } - - public T or(Supplier<T> nextValue) { - if (isPresent()) return get(); - return nextValue.get(); - } - - public T orNull() { - if (isPresent()) return get(); - return null; - } - - public Set<T> asSet() { - if (isPresent()) return ImmutableSet.of(get()); - return Collections.emptySet(); - } - - public <V> Maybe<V> transform(final Function<? super T, V> f) { - if (isPresent()) return new AbstractPresent<V>() { - private static final long serialVersionUID = 325089324325L; - public V get() { - return f.apply(Maybe.this.get()); - } - }; - return absent(); - } - - /** - * Returns the value of each present instance from the supplied {@code maybes}, in order, - * skipping over occurrences of {@link Maybe#absent()}. Iterators are unmodifiable and are - * evaluated lazily. - * - * @see Optional#presentInstances(Iterable) - */ - @Beta - public static <T> Iterable<T> presentInstances(final Iterable<? extends Maybe<? extends T>> maybes) { - checkNotNull(maybes); - return new Iterable<T>() { - @Override - public Iterator<T> iterator() { - return new AbstractIterator<T>() { - private final Iterator<? extends Maybe<? extends T>> iterator = checkNotNull(maybes.iterator()); - - @Override - protected T computeNext() { - while (iterator.hasNext()) { - Maybe<? extends T> maybe = iterator.next(); - if (maybe.isPresent()) { return maybe.get(); } - } - return endOfData(); - } - }; - } - }; - } - - public static class Absent<T> extends Maybe<T> { - private static final long serialVersionUID = -757170462010887057L; - private final Supplier<? extends RuntimeException> exception; - public Absent() { - this(IllegalStateExceptionSupplier.EMPTY_EXCEPTION); - } - public Absent(Supplier<? extends RuntimeException> exception) { - this.exception = exception; - } - @Override - public boolean isPresent() { - return false; - } - @Override - public T get() { - throw getException(); - } - public RuntimeException getException() { - return exception.get(); - } - } - - public static abstract class AbstractPresent<T> extends Maybe<T> { - private static final long serialVersionUID = -2266743425340870492L; - protected AbstractPresent() { - } - @Override - public boolean isPresent() { - return true; - } - } - - public static class Present<T> extends AbstractPresent<T> { - private static final long serialVersionUID = 436799990500336015L; - private final T value; - protected Present(T value) { - this.value = value; - } - @Override - public T get() { - return value; - } - } - - public static class SoftlyPresent<T> extends Maybe<T> { - private static final long serialVersionUID = 436799990500336015L; - private final SoftReference<T> value; - private Maybe<T> defaultValue; - protected SoftlyPresent(@Nonnull T value) { - this.value = new SoftReference<T>(value); - } - @Override - public T get() { - T result = value.get(); - if (result!=null) return result; - if (defaultValue==null) throw new IllegalStateException("Softly present item has been GC'd"); - return defaultValue.get(); - } - @Override - public T orNull() { - T result = value.get(); - if (result!=null) return result; - if (defaultValue==null) return null; - return defaultValue.orNull(); - } - @Override - public boolean isPresent() { - return value.get()!=null || (defaultValue!=null && defaultValue.isPresent()); - } - public Maybe<T> solidify() { - return Maybe.fromNullable(value.get()); - } - SoftlyPresent<T> usingAfterExpiry(Maybe<T> defaultValue) { - this.defaultValue = defaultValue; - return this; - } - } - - @Override - public String toString() { - return JavaClassNames.simpleClassName(this)+"["+(isPresent()?"value="+get():"")+"]"; - } - - @Override - public int hashCode() { - if (!isPresent()) return Objects.hashCode(31, isPresent()); - return Objects.hashCode(31, get()); - } - - @Override - public boolean equals(Object obj) { - if (!(obj instanceof Maybe)) return false; - Maybe<?> other = (Maybe<?>)obj; - if (!isPresent()) - return !other.isPresent(); - return Objects.equal(get(), other.get()); - } - -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/main/java/brooklyn/util/guava/MaybeFunctions.java ---------------------------------------------------------------------- diff --git a/utils/common/src/main/java/brooklyn/util/guava/MaybeFunctions.java b/utils/common/src/main/java/brooklyn/util/guava/MaybeFunctions.java deleted file mode 100644 index 2955785..0000000 --- a/utils/common/src/main/java/brooklyn/util/guava/MaybeFunctions.java +++ /dev/null @@ -1,52 +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 brooklyn.util.guava; - -import com.google.common.base.Function; - -public class MaybeFunctions { - - public static <T> Function<T, Maybe<T>> wrap() { - return new Function<T, Maybe<T>>() { - @Override - public Maybe<T> apply(T input) { - return Maybe.fromNullable(input); - } - }; - } - - public static <T> Function<Maybe<T>, T> get() { - return new Function<Maybe<T>, T>() { - @Override - public T apply(Maybe<T> input) { - return input.get(); - } - }; - } - - public static <T> Function<Maybe<T>, T> or(final T value) { - return new Function<Maybe<T>, T>() { - @Override - public T apply(Maybe<T> input) { - return input.or(value); - } - }; - } - -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/main/java/brooklyn/util/guava/SerializablePredicate.java ---------------------------------------------------------------------- diff --git a/utils/common/src/main/java/brooklyn/util/guava/SerializablePredicate.java b/utils/common/src/main/java/brooklyn/util/guava/SerializablePredicate.java deleted file mode 100644 index e090320..0000000 --- a/utils/common/src/main/java/brooklyn/util/guava/SerializablePredicate.java +++ /dev/null @@ -1,26 +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 brooklyn.util.guava; - -import java.io.Serializable; - -import com.google.common.base.Predicate; - -public interface SerializablePredicate<T> extends Predicate<T>, Serializable { -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/main/java/brooklyn/util/guava/TypeTokens.java ---------------------------------------------------------------------- diff --git a/utils/common/src/main/java/brooklyn/util/guava/TypeTokens.java b/utils/common/src/main/java/brooklyn/util/guava/TypeTokens.java deleted file mode 100644 index ca69a97..0000000 --- a/utils/common/src/main/java/brooklyn/util/guava/TypeTokens.java +++ /dev/null @@ -1,72 +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 brooklyn.util.guava; - -import javax.annotation.Nullable; - -import com.google.common.reflect.TypeToken; - -public class TypeTokens { - - /** returns raw type, if it's raw, else null; - * used e.g. to set only one of the raw type or the type token, - * for instance to make serialized output nicer */ - @Nullable - public static <T> Class<? super T> getRawTypeIfRaw(@Nullable TypeToken<T> type) { - if (type==null || !type.equals(TypeToken.of(type.getRawType()))) { - return null; - } else { - return type.getRawType(); - } - } - - /** returns null if it's raw, else the type token */ - @Nullable - public static <T> TypeToken<T> getTypeTokenIfNotRaw(@Nullable TypeToken<T> type) { - if (type==null || type.equals(TypeToken.of(type.getRawType()))) { - return null; - } else { - return type; - } - } - - /** given either a token or a raw type, returns the raw type */ - public static <T> Class<? super T> getRawType(TypeToken<T> token, Class<? super T> raw) { - if (raw!=null) return raw; - if (token!=null) return token.getRawType(); - throw new IllegalStateException("Both indicators of type are null"); - } - - - /** given either a token or a raw type, returns the token */ - @SuppressWarnings("unchecked") - public static <T> TypeToken<T> getTypeToken(TypeToken<T> token, Class<? super T> raw) { - if (token!=null) return token; - if (raw!=null) return TypeToken.of((Class<T>)raw); - throw new IllegalStateException("Both indicators of type are null"); - } - - /** gets the Class<T> object from a token; normal methods return Class<? super T> which may technically be correct - * with generics but this sloppily but handily gives you Class<T> which is usually what you have anyway */ - @SuppressWarnings({ "rawtypes", "unchecked" }) - public static <T> Class<T> getRawRawType(TypeToken<T> token) { - return (Class)token.getRawType(); - } - -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/main/java/brooklyn/util/internal/BasicDelegatingSystemProperty.java ---------------------------------------------------------------------- diff --git a/utils/common/src/main/java/brooklyn/util/internal/BasicDelegatingSystemProperty.java b/utils/common/src/main/java/brooklyn/util/internal/BasicDelegatingSystemProperty.java deleted file mode 100644 index a1c766b..0000000 --- a/utils/common/src/main/java/brooklyn/util/internal/BasicDelegatingSystemProperty.java +++ /dev/null @@ -1,36 +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 brooklyn.util.internal; - -public class BasicDelegatingSystemProperty { - protected final StringSystemProperty delegate; - - public BasicDelegatingSystemProperty(String name) { - delegate = new StringSystemProperty(name); - } - public String getPropertyName() { - return delegate.getPropertyName(); - } - public boolean isAvailable() { - return delegate.isAvailable(); - } - public String toString() { - return delegate.toString(); - } -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/main/java/brooklyn/util/internal/BooleanSystemProperty.java ---------------------------------------------------------------------- diff --git a/utils/common/src/main/java/brooklyn/util/internal/BooleanSystemProperty.java b/utils/common/src/main/java/brooklyn/util/internal/BooleanSystemProperty.java deleted file mode 100644 index 66b119d..0000000 --- a/utils/common/src/main/java/brooklyn/util/internal/BooleanSystemProperty.java +++ /dev/null @@ -1,29 +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 brooklyn.util.internal; - -public class BooleanSystemProperty extends BasicDelegatingSystemProperty { - public BooleanSystemProperty(String name) { - super(name); - } - public boolean isEnabled() { - // actually access system property! - return Boolean.getBoolean(getPropertyName()); - } -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/main/java/brooklyn/util/internal/BrooklynSystemProperties.java ---------------------------------------------------------------------- diff --git a/utils/common/src/main/java/brooklyn/util/internal/BrooklynSystemProperties.java b/utils/common/src/main/java/brooklyn/util/internal/BrooklynSystemProperties.java deleted file mode 100644 index 9737d48..0000000 --- a/utils/common/src/main/java/brooklyn/util/internal/BrooklynSystemProperties.java +++ /dev/null @@ -1,39 +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 brooklyn.util.internal; - -/** - * Convenience for retrieving well-defined system properties, including checking if they have been set etc. - */ -public class BrooklynSystemProperties { - - // TODO should these become ConfigKeys ? - - public static BooleanSystemProperty DEBUG = new BooleanSystemProperty("brooklyn.debug"); - public static BooleanSystemProperty EXPERIMENTAL = new BooleanSystemProperty("brooklyn.experimental"); - - /** controls how long jsch delays between commands it issues */ - // -Dbrooklyn.jsch.exec.delay=100 - public static IntegerSystemProperty JSCH_EXEC_DELAY = new IntegerSystemProperty("brooklyn.jsch.exec.delay"); - - /** allows specifying a particular geo lookup service (to lookup IP addresses), as the class FQN to use */ - // -Dbrooklyn.location.geo.HostGeoLookup=brooklyn.location.geo.UtraceHostGeoLookup - public static StringSystemProperty HOST_GEO_LOOKUP_IMPL = new StringSystemProperty("brooklyn.location.geo.HostGeoLookup"); - -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/main/java/brooklyn/util/internal/DoubleSystemProperty.java ---------------------------------------------------------------------- diff --git a/utils/common/src/main/java/brooklyn/util/internal/DoubleSystemProperty.java b/utils/common/src/main/java/brooklyn/util/internal/DoubleSystemProperty.java deleted file mode 100644 index 6003148..0000000 --- a/utils/common/src/main/java/brooklyn/util/internal/DoubleSystemProperty.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 brooklyn.util.internal; - -public class DoubleSystemProperty extends BasicDelegatingSystemProperty { - public DoubleSystemProperty(String name) { - super(name); - } - public double getValue() { - return Double.parseDouble(delegate.getValue()); - } -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/main/java/brooklyn/util/internal/IntegerSystemProperty.java ---------------------------------------------------------------------- diff --git a/utils/common/src/main/java/brooklyn/util/internal/IntegerSystemProperty.java b/utils/common/src/main/java/brooklyn/util/internal/IntegerSystemProperty.java deleted file mode 100644 index 9150725..0000000 --- a/utils/common/src/main/java/brooklyn/util/internal/IntegerSystemProperty.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 brooklyn.util.internal; - -public class IntegerSystemProperty extends BasicDelegatingSystemProperty { - public IntegerSystemProperty(String name) { - super(name); - } - public int getValue() { - return Integer.parseInt(delegate.getValue()); - } -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/main/java/brooklyn/util/internal/StringSystemProperty.java ---------------------------------------------------------------------- diff --git a/utils/common/src/main/java/brooklyn/util/internal/StringSystemProperty.java b/utils/common/src/main/java/brooklyn/util/internal/StringSystemProperty.java deleted file mode 100644 index b635202..0000000 --- a/utils/common/src/main/java/brooklyn/util/internal/StringSystemProperty.java +++ /dev/null @@ -1,50 +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 brooklyn.util.internal; - -public class StringSystemProperty { - - // TODO replace usages of this and related items with ConfigKeys - - public StringSystemProperty(String name) { - this.propertyName = name; - } - - private final String propertyName; - - public String getPropertyName() { - return propertyName; - } - - public boolean isAvailable() { - String property = System.getProperty(getPropertyName()); - return property!=null; - } - public boolean isNonEmpty() { - String property = System.getProperty(getPropertyName()); - return property!=null && !property.equals(""); - } - public String getValue() { - return System.getProperty(getPropertyName()); - } - @Override - public String toString() { - return getPropertyName()+(isAvailable()?"="+getValue():"(unset)"); - } -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/main/java/brooklyn/util/io/FileUtil.java ---------------------------------------------------------------------- diff --git a/utils/common/src/main/java/brooklyn/util/io/FileUtil.java b/utils/common/src/main/java/brooklyn/util/io/FileUtil.java deleted file mode 100644 index 66e7fc1..0000000 --- a/utils/common/src/main/java/brooklyn/util/io/FileUtil.java +++ /dev/null @@ -1,202 +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 brooklyn.util.io; - -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.List; -import java.util.regex.Pattern; - -import org.apache.commons.io.FileUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import brooklyn.util.exceptions.Exceptions; -import brooklyn.util.guava.Maybe; -import brooklyn.util.os.Os; -import brooklyn.util.stream.StreamGobbler; -import brooklyn.util.stream.Streams; - -import com.google.common.annotations.Beta; -import com.google.common.collect.ImmutableList; - -public class FileUtil { - - private static final Logger LOG = LoggerFactory.getLogger(FileUtil.class); - - private static boolean loggedSetFilePermissionsWarning = false; - - // When we move to java 7, we can use Files.setPosixFilePermissions - public static void setFilePermissionsTo700(File file) throws IOException { - file.createNewFile(); - boolean setRead = file.setReadable(false, false) & file.setReadable(true, true); - boolean setWrite = file.setWritable(false, false) & file.setWritable(true, true); - boolean setExec = file.setExecutable(false, false) & file.setExecutable(true, true); - - if (setRead && setWrite && setExec) { - if (LOG.isTraceEnabled()) LOG.trace("Set permissions to 700 for file {}", file.getAbsolutePath()); - } else { - if (loggedSetFilePermissionsWarning) { - if (LOG.isTraceEnabled()) LOG.trace("Failed to set permissions to 700 for file {}: setRead={}, setWrite={}, setExecutable={}", - new Object[] {file.getAbsolutePath(), setRead, setWrite, setExec}); - } else { - if (Os.isMicrosoftWindows()) { - if (LOG.isDebugEnabled()) LOG.debug("Failed to set permissions to 700 for file {}; expected behaviour on Windows; setRead={}, setWrite={}, setExecutable={}; subsequent failures (on any file) will be logged at trace", - new Object[] {file.getAbsolutePath(), setRead, setWrite, setExec}); - } else { - LOG.warn("Failed to set permissions to 700 for file {}: setRead={}, setWrite={}, setExecutable={}; subsequent failures (on any file) will be logged at trace", - new Object[] {file.getAbsolutePath(), setRead, setWrite, setExec}); - } - loggedSetFilePermissionsWarning = true; - } - } - } - - // When we move to java 7, we can use Files.setPosixFilePermissions - public static void setFilePermissionsTo600(File file) throws IOException { - file.createNewFile(); - file.setExecutable(false, false); - file.setReadable(false, false); - file.setWritable(false, false); - file.setReadable(true, true); - file.setWritable(true, true); - - boolean setRead = file.setReadable(false, false) & file.setReadable(true, true); - boolean setWrite = file.setWritable(false, false) & file.setWritable(true, true); - boolean setExec = file.setExecutable(false, false); - - if (setRead && setWrite && setExec) { - if (LOG.isTraceEnabled()) LOG.trace("Set permissions to 600 for file {}", file.getAbsolutePath()); - } else { - if (loggedSetFilePermissionsWarning) { - if (LOG.isTraceEnabled()) LOG.trace("Failed to set permissions to 600 for file {}: setRead={}, setWrite={}, setExecutable={}", - new Object[] {file.getAbsolutePath(), setRead, setWrite, setExec}); - } else { - if (Os.isMicrosoftWindows()) { - if (LOG.isDebugEnabled()) LOG.debug("Failed to set permissions to 600 for file {}; expected behaviour on Windows; setRead={}, setWrite={}, setExecutable={}; subsequent failures (on any file) will be logged at trace", - new Object[] {file.getAbsolutePath(), setRead, setWrite, setExec}); - } else { - LOG.warn("Failed to set permissions to 600 for file {}: setRead={}, setWrite={}, setExecutable={}; subsequent failures (on any file) will be logged at trace", - new Object[] {file.getAbsolutePath(), setRead, setWrite, setExec}); - } - loggedSetFilePermissionsWarning = true; - } - } - } - - public static void moveDir(File srcDir, File destDir) throws IOException, InterruptedException { - if (!Os.isMicrosoftWindows()) { - String cmd = "mv '"+srcDir.getAbsolutePath()+"' '"+destDir.getAbsolutePath()+"'"; - Process proc = Runtime.getRuntime().exec(cmd); - proc.waitFor(); - if (proc.exitValue() == 0) return; - } - - FileUtils.moveDirectory(srcDir, destDir); - } - - public static void copyDir(File srcDir, File destDir) throws IOException, InterruptedException { - if (!Os.isMicrosoftWindows()) { - String cmd = "cp -R '"+srcDir.getAbsolutePath()+"' '"+destDir.getAbsolutePath()+"'"; - Process proc = Runtime.getRuntime().exec(cmd); - proc.waitFor(); - if (proc.exitValue() == 0) return; - } - - FileUtils.copyDirectory(srcDir, destDir); - } - - /** - * This utility will be deleted when we move to Java 7 - * - * @return The file permission (in a form like "-rwxr--r--"), or null if the permissions could not be determined. - */ - @Beta - public static Maybe<String> getFilePermissions(File file) { - if (!file.exists()) return Maybe.absent("File "+file+" does not exist"); - - if (Os.isMicrosoftWindows()) { - return Maybe.absent("Cannot determine permissions on windows"); - } else { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - ByteArrayOutputStream err = new ByteArrayOutputStream(); - int exitcode = exec(ImmutableList.of("ls", "-ld", file.getAbsolutePath()), out, err); - if (exitcode != 0) { - if (LOG.isDebugEnabled()) LOG.debug("Could not determine permissions of file "+file+"; exit code "+exitcode+"; stderr "+new String(err.toByteArray())); - return Maybe.absent("Could not determine permission of file "+file+"; exit code "+exitcode); - } - String stdout = new String(out.toByteArray()); - return (stdout.trim().isEmpty() ? Maybe.<String>absent("empty output") : Maybe.of(stdout.split("\\s")[0])); - } - } - - // guava's Files.copy(InputStreamSupplier, File) is deprecated, and will be deleted in guava 18.0 - @Beta - public static void copyTo(InputStream in, File dest) { - FileOutputStream out = null; - try { - out = new FileOutputStream(dest); - Streams.copy(in, out); - } catch (FileNotFoundException e) { - throw Exceptions.propagate(e); - } finally { - Streams.closeQuietly(out); - } - } - - private static int exec(List<String> cmds, OutputStream out, OutputStream err) { - StreamGobbler errgobbler = null; - StreamGobbler outgobbler = null; - - ProcessBuilder pb = new ProcessBuilder(cmds); - - try { - Process p = pb.start(); - - if (out != null) { - InputStream outstream = p.getInputStream(); - outgobbler = new StreamGobbler(outstream, out, (Logger) null); - outgobbler.start(); - } - if (err != null) { - InputStream errstream = p.getErrorStream(); - errgobbler = new StreamGobbler(errstream, err, (Logger) null); - errgobbler.start(); - } - - int result = p.waitFor(); - - if (outgobbler != null) outgobbler.blockUntilFinished(); - if (errgobbler != null) errgobbler.blockUntilFinished(); - - return result; - } catch (Exception e) { - throw Exceptions.propagate(e); - } finally { - Streams.closeQuietly(outgobbler); - Streams.closeQuietly(errgobbler); - } - } - -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/main/java/brooklyn/util/javalang/AggregateClassLoader.java ---------------------------------------------------------------------- diff --git a/utils/common/src/main/java/brooklyn/util/javalang/AggregateClassLoader.java b/utils/common/src/main/java/brooklyn/util/javalang/AggregateClassLoader.java deleted file mode 100644 index db0254b..0000000 --- a/utils/common/src/main/java/brooklyn/util/javalang/AggregateClassLoader.java +++ /dev/null @@ -1,173 +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 brooklyn.util.javalang; - -import java.io.IOException; -import java.net.URL; -import java.util.Collection; -import java.util.Collections; -import java.util.Enumeration; -import java.util.Iterator; -import java.util.List; -import java.util.Set; -import java.util.concurrent.CopyOnWriteArrayList; - -import com.google.common.collect.Sets; - -/** looks for classes and resources in the classloaders added here - * <p> - * similar to XStream's CompositeClassLoader, but also supporting resources, - * exposing more info, a few conveniences, and a nice toString */ -public class AggregateClassLoader extends ClassLoader { - - // thread safe -- and all access in this class is also synchronized, - // so that reset is guaranteed not to interfere with an add(0, cl) - private final CopyOnWriteArrayList<ClassLoader> classLoaders = new CopyOnWriteArrayList<ClassLoader>(); - - private AggregateClassLoader() { - //Don't pass load requests to the app classloader, - //always relay to the classLoaders list. - super(null); - } - - /** creates default instance, with classloaders of Object and AggregateClassLoader */ - public static AggregateClassLoader newInstanceWithDefaultLoaders() { - AggregateClassLoader cl = new AggregateClassLoader(); - cl.addFirst(AggregateClassLoader.class.getClassLoader()); // whichever classloader loaded this jar. - cl.addFirst(Object.class.getClassLoader()); // bootstrap loader. - return cl; - } - /** creates default instance, with no classloaders (assuming this instance will itself be nested, - * or defaults will be added by caller) */ - public static AggregateClassLoader newInstanceWithNoLoaders() { - return new AggregateClassLoader(); - } - - /** Add a loader to the first position in the search path. */ - public void addFirst(ClassLoader classLoader) { - if (classLoader != null) { - synchronized (classLoaders) { - classLoaders.add(0, classLoader); - } - } - } - /** Add a loader to the last position in the search path. */ - public void addLast(ClassLoader classLoader) { - if (classLoader != null) { - synchronized (classLoaders) { - classLoaders.add(classLoader); - } - } - } - /** Add a loader to the specific position in the search path. - * (It is callers responsibility to ensure that position is valid.) */ - public void add(int index, ClassLoader classLoader) { - if (classLoader != null) { - synchronized (classLoaders) { - classLoaders.add(index, classLoader); - } - } - } - - /** Resets the classloader shown here to be the given set */ - public void reset(Collection<? extends ClassLoader> newClassLoaders) { - synchronized (classLoaders) { - // synchronize: - // * to prevent concurrent invocations - // * so add(0, cl) doesn't interfere - // * and for good measure we add before removing so that iterator always contains everything - // although since iterator access is synchronized that shouldn't be necessary - int count = classLoaders.size(); - classLoaders.addAll(newClassLoaders); - for (int i=0; i<count; i++) { - classLoaders.remove(0); - } - } - } - - /** True if nothing is in the list here */ - public boolean isEmpty() { - return classLoaders.isEmpty(); - } - - /** Returns the _live_ (and modifiable) list of classloaders; dangerous and discouraged. - * @deprecated since 0.7.0 */ - @Deprecated - public List<ClassLoader> getList() { - return classLoaders; - } - - public Iterator<ClassLoader> iterator() { - synchronized (classLoaders) { - // CopyOnWriteList iterator is immutable view of snapshot - return classLoaders.iterator(); - } - } - - @Override - protected Class<?> findClass(String name) throws ClassNotFoundException { - for (ClassLoader classLoader: classLoaders) { - try { - return classLoader.loadClass(name); - } catch (ClassNotFoundException notFound) { - /* ignore (nice if there were a better way than throwing... */ - } - } - // last resort. see comment in XStream CompositeClassLoader - ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); - if (contextClassLoader != null) - return contextClassLoader.loadClass(name); - throw new ClassNotFoundException(name); - } - - @Override - public String toString() { - return "AggregateClassLoader"+classLoaders; - } - - @Override - public URL getResource(String name) { - URL result = null; - Iterator<ClassLoader> cli = iterator(); - while (cli.hasNext()) { - ClassLoader classLoader=cli.next(); - result = classLoader.getResource(name); - if (result!=null) return result; - } - // last resort. see comment in XStream CompositeClassLoader - ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); - if (contextClassLoader != null) - return contextClassLoader.getResource(name); - return null; - } - - @Override - public Enumeration<URL> getResources(String name) throws IOException { - Set<URL> resources = Sets.newLinkedHashSet(); - Iterator<ClassLoader> cli = iterator(); - while (cli.hasNext()) { - ClassLoader classLoader=cli.next(); - resources.addAll(Collections.list(classLoader.getResources(name))); - } - return Collections.enumeration(resources); - } - - // TODO lesser used items, such as getPackage, findLibrary - -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/main/java/brooklyn/util/javalang/AtomicReferences.java ---------------------------------------------------------------------- diff --git a/utils/common/src/main/java/brooklyn/util/javalang/AtomicReferences.java b/utils/common/src/main/java/brooklyn/util/javalang/AtomicReferences.java deleted file mode 100644 index baac3a8..0000000 --- a/utils/common/src/main/java/brooklyn/util/javalang/AtomicReferences.java +++ /dev/null @@ -1,48 +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 brooklyn.util.javalang; - -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicReference; - -import com.google.common.base.Objects; -import com.google.common.base.Preconditions; -import com.google.common.base.Supplier; - -public class AtomicReferences { - - /** sets the atomic reference to the given value, and returns whether there is any change */ - public static boolean setIfDifferent(AtomicBoolean ref, boolean value) { - return ref.getAndSet(value) != value; - } - - /** sets the atomic reference to the given value, and returns whether there is any change */ - public static <T> boolean setIfDifferent(AtomicReference<T> ref, T value) { - return !Objects.equal(ref.getAndSet(value), value); - } - - /** returns the given atomic as a Supplier */ - public static <T> Supplier<T> supplier(final AtomicReference<T> ref) { - Preconditions.checkNotNull(ref); - return new Supplier<T>() { - @Override public T get() { return ref.get(); } - @Override public String toString() { return "AtomicRefSupplier"; } - }; - } -}
