http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/main/java/brooklyn/util/javalang/Boxing.java ---------------------------------------------------------------------- diff --git a/utils/common/src/main/java/brooklyn/util/javalang/Boxing.java b/utils/common/src/main/java/brooklyn/util/javalang/Boxing.java deleted file mode 100644 index 72f5138..0000000 --- a/utils/common/src/main/java/brooklyn/util/javalang/Boxing.java +++ /dev/null @@ -1,102 +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.lang.reflect.Array; - -import brooklyn.util.guava.Maybe; - -import com.google.common.collect.ImmutableBiMap; - -public class Boxing { - - public static boolean unboxSafely(Boolean ref, boolean valueIfNull) { - if (ref==null) return valueIfNull; - return ref.booleanValue(); - } - - public static final ImmutableBiMap<Class<?>, Class<?>> PRIMITIVE_TO_BOXED = - ImmutableBiMap.<Class<?>, Class<?>>builder() - .put(Integer.TYPE, Integer.class) - .put(Long.TYPE, Long.class) - .put(Double.TYPE, Double.class) - .put(Float.TYPE, Float.class) - .put(Boolean.TYPE, Boolean.class) - .put(Character.TYPE, Character.class) - .put(Byte.TYPE, Byte.class) - .put(Short.TYPE, Short.class) - .put(Void.TYPE, Void.class) - .build(); - - /** Returns the unboxed type for the given primitive type name, if available; - * e.g. {@link Integer#TYPE} for <code>int</code> (distinct from <code>Integer.class</code>), - * or null if not a primitive. - * */ - public static Maybe<Class<?>> getPrimitiveType(String typeName) { - if (typeName!=null) { - for (Class<?> t: PRIMITIVE_TO_BOXED.keySet()) { - if (typeName.equals(t.getName())) return Maybe.<Class<?>>of(t); - } - } - return Maybe.absent("Not a primitive: "+typeName); - } - - public static Class<?> boxedType(Class<?> type) { - if (PRIMITIVE_TO_BOXED.containsKey(type)) - return PRIMITIVE_TO_BOXED.get(type); - return type; - } - - /** sets the given element in an array to the indicated value; - * if the type is a primitive type, the appropriate primitive method is used - * <p> - * this is needed because arrays do not deal with autoboxing */ - public static void setInArray(Object target, int index, Object value, Class<?> type) { - if (PRIMITIVE_TO_BOXED.containsKey(type)) { - if (type.equals(Integer.TYPE)) - Array.setInt(target, index, (Integer)value); - else if (type.equals(Long.TYPE)) - Array.setLong(target, index, (Long)value); - else if (type.equals(Double.TYPE)) - Array.setDouble(target, index, (Double)value); - else if (type.equals(Float.TYPE)) - Array.setFloat(target, index, (Float)value); - else if (type.equals(Boolean.TYPE)) - Array.setBoolean(target, index, (Boolean)value); - else if (type.equals(Character.TYPE)) - Array.setChar(target, index, (Character)value); - else if (type.equals(Byte.TYPE)) - Array.setByte(target, index, (Byte)value); - else if (type.equals(Short.TYPE)) - Array.setShort(target, index, (Short)value); - - else if (type.equals(Void.TYPE)) - Array.set(target, index, (Void)value); - - else - // should not happen! - throw new IllegalStateException("Unsupported primitive: "+type); - - return; - } - - Array.set(target, index, value); - } - -}
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/main/java/brooklyn/util/javalang/Enums.java ---------------------------------------------------------------------- diff --git a/utils/common/src/main/java/brooklyn/util/javalang/Enums.java b/utils/common/src/main/java/brooklyn/util/javalang/Enums.java deleted file mode 100644 index f79fb6e..0000000 --- a/utils/common/src/main/java/brooklyn/util/javalang/Enums.java +++ /dev/null @@ -1,170 +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.Arrays; -import java.util.Set; - -import brooklyn.util.collections.MutableSet; -import brooklyn.util.exceptions.Exceptions; -import brooklyn.util.guava.Maybe; -import brooklyn.util.text.StringFunctions; -import brooklyn.util.text.Strings; - -import com.google.common.base.CaseFormat; -import com.google.common.base.Function; -import com.google.common.collect.Iterables; - -public class Enums { - - /** returns a function which given an enum, returns its <code>name()</code> function - * @deprecated since 0.7.0 use {@link #nameFunction()} to avoid inner class */ - @Deprecated - public static Function<Enum<?>,String> enumValueNameFunction() { - return new Function<Enum<?>,String>() { - @Override - public String apply(Enum<?> input) { - return input.name(); - } - }; - } - - private static final class EnumToNameFunction implements Function<Enum<?>, String> { - @Override - public String apply(Enum<?> input) { - return input.name(); - } - } - - /** returns a function which given an enum, returns its <code>name()</code> function */ - public static Function<Enum<?>,String> nameFunction() { - return new EnumToNameFunction(); - } - - private static final class EnumFromStringFunction<T extends Enum<?>> implements Function<String,T> { - private final Class<T> type; - public EnumFromStringFunction(Class<T> type) { this.type = type; } - @Override - public T apply(String input) { - return valueOfIgnoreCase(type, input).orNull(); - } - } - - /** returns a function which given a string, produces an enum of the given type or null */ - public static <T extends Enum<?>> Function<String,T> fromStringFunction(Class<T> type) { - return new EnumFromStringFunction<T>(type); - } - - @SuppressWarnings("unchecked") - private static <T extends Enum<?>> T[] values(Class<T> type) { - try { - return (T[]) type.getMethod("values").invoke(null); - } catch (Exception e) { - throw Exceptions.propagate(e); - } - } - - /** as {@link #checkAllEnumeratedIgnoreCase(String, Enum[], String...)} using the same default strategy - * that {@link #valueOfIgnoreCase(Class, String)} applies */ - public static void checkAllEnumeratedIgnoreCase(Class<? extends Enum<?>> type, String ...explicitValues) { - checkAllEnumeratedIgnoreCase(JavaClassNames.simpleClassName(type), values(type), explicitValues); - } - /** checks that all accepted enum values are represented by the given set of explicit values */ - public static void checkAllEnumeratedIgnoreCase(String contextMessage, Enum<?>[] enumValues, String ...explicitValues) { - MutableSet<String> explicitValuesSet = MutableSet.copyOf(Iterables.transform(Arrays.asList(explicitValues), StringFunctions.toLowerCase())); - - Set<Enum<?>> missingEnums = MutableSet.of(); - for (Enum<?> e: enumValues) { - if (explicitValuesSet.remove(e.name().toLowerCase())) continue; - if (explicitValuesSet.remove(e.toString().toLowerCase())) continue; - - if (explicitValuesSet.remove(CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, e.name()).toLowerCase())) continue; - if (explicitValuesSet.remove(CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, e.toString()).toLowerCase())) continue; - - if (explicitValuesSet.remove(CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, e.toString()).toLowerCase())) continue; - if (explicitValuesSet.remove(CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, e.name()).toLowerCase())) continue; - - missingEnums.add(e); - } - - if (!missingEnums.isEmpty() || !explicitValuesSet.isEmpty()) { - throw new IllegalStateException("Not all options for "+contextMessage+" are enumerated; " - + "leftover enums = "+missingEnums+"; " - + "leftover values = "+explicitValuesSet); - } - } - - /** as {@link #valueOfIgnoreCase(String, Enum[], String)} for all values of the given enum and using the enum type as the message */ - public static <T extends Enum<?>> Maybe<T> valueOfIgnoreCase(Class<T> type, String givenValue) { - return valueOfIgnoreCase(JavaClassNames.simpleClassName(type), values(type), givenValue); - } - - /** attempts to match the givenValue against the given enum values, first looking for exact matches (against name and toString), - * then matching ignoring case, - * then matching with {@link CaseFormat#UPPER_UNDERSCORE} converted to {@link CaseFormat#LOWER_CAMEL}, - * then matching with {@link CaseFormat#LOWER_CAMEL} converted to {@link CaseFormat#UPPER_UNDERSCORE} - * (including case insensitive matches for the final two) - **/ - public static <T extends Enum<?>> Maybe<T> valueOfIgnoreCase(String contextMessage, T[] enumValues, String givenValue) { - if (givenValue==null) - return Maybe.absent(new IllegalStateException("Value for "+contextMessage+" must not be null")); - if (Strings.isBlank(givenValue)) - return Maybe.absent(new IllegalStateException("Value for "+contextMessage+" must not be blank")); - - for (T v: enumValues) - if (v.name().equals(givenValue)) - return Maybe.of(v); - for (T v: enumValues) - if (v.toString().equals(givenValue)) - return Maybe.of(v); - for (T v: enumValues) - if (v.name().equalsIgnoreCase(givenValue)) return - Maybe.of(v); - for (T v: enumValues) - if (v.toString().equalsIgnoreCase(givenValue)) - return Maybe.of(v); - for (T v: enumValues) - if (CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, v.name()).equals(givenValue)) - return Maybe.of(v); - for (T v: enumValues) - if (CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, v.toString()).equals(givenValue)) - return Maybe.of(v); - for (T v: enumValues) - if (CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, v.name()).equalsIgnoreCase(givenValue)) - return Maybe.of(v); - for (T v: enumValues) - if (CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, v.toString()).equalsIgnoreCase(givenValue)) - return Maybe.of(v); - for (T v: enumValues) - if (CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, v.toString()).equalsIgnoreCase(givenValue)) - return Maybe.of(v); - for (T v: enumValues) - if (CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, v.name()).equals(givenValue)) - return Maybe.of(v); - for (T v: enumValues) - if (CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, v.toString()).equals(givenValue)) - return Maybe.of(v); - for (T v: enumValues) - if (CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, v.name()).equalsIgnoreCase(givenValue)) - return Maybe.of(v); - - return Maybe.absent(new IllegalStateException("Invalid value "+givenValue+" for "+contextMessage)); - } - -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/main/java/brooklyn/util/javalang/Equals.java ---------------------------------------------------------------------- diff --git a/utils/common/src/main/java/brooklyn/util/javalang/Equals.java b/utils/common/src/main/java/brooklyn/util/javalang/Equals.java deleted file mode 100644 index 621d1dd..0000000 --- a/utils/common/src/main/java/brooklyn/util/javalang/Equals.java +++ /dev/null @@ -1,94 +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.lang.reflect.Field; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import brooklyn.util.exceptions.Exceptions; - -import com.google.common.annotations.Beta; -import com.google.common.base.Objects; - - -public class Equals { - - private static final Logger log = LoggerFactory.getLogger(Equals.class); - - /** Tests whether the objects given are either all null or all equal to the first argument */ - public static boolean objects(Object o1, Object o2, Object... oo) { - if (!Objects.equal(o1, o2)) return false; - for (Object o: oo) - if (!Objects.equal(o1, o)) return false; - return true; - } - - /** Tests whether the two objects given are either all null or all approximately equal - * (tolerance of 0.001 for floating point, but subject to change) */ - // relatively high tolerance mainly due to enrichers such as Tomcat windowed average, in hot standby; - // could make smaller - @Beta - public static boolean approximately(Object o1, Object o2) { - if (o1 instanceof Number) { - if (o2 instanceof Number) { - return Math.abs( ((Number)o2).doubleValue()-((Number)o1).doubleValue() ) < 0.001; - } - } - return Objects.equal(o1, o2); - } - - /** As {@link #approximately(Object, Object)} but testing all the arguments given. */ - @Beta - public static boolean approximately(Object o1, Object o2, Object o3, Object... oo) { - if (!approximately(o1, o2)) return false; - if (!approximately(o1, o3)) return false; - for (Object o: oo) - if (!approximately(o1, o)) return false; - return true; - } - - /** Useful for debugging EqualsBuilder.reflectionEquals */ - public static void dumpReflectiveEquals(Object o1, Object o2) { - log.info("Comparing: "+o1+" "+o2); - Class<?> clazz = o1.getClass(); - while (!(clazz.equals(Object.class))) { - log.info(" fields in: "+clazz); - for (Field f: clazz.getDeclaredFields()) { - f.setAccessible(true); - try { - log.info( " "+(Objects.equal(f.get(o1), f.get(o2)) ? "==" : "!=" ) + - " "+ f.getName()+ " "+ f.get(o1) +" "+ f.get(o2) + - " ("+ classOf(f.get(o1)) +" "+ classOf(f.get(o2)+")") ); - } catch (Exception e) { - Exceptions.propagateIfFatal(e); - log.info( " <error> "+e); - } - } - clazz = clazz.getSuperclass(); - } - } - - private static String classOf(Object o) { - if (o==null) return null; - return o.getClass().toString(); - } - -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/main/java/brooklyn/util/javalang/JavaClassNames.java ---------------------------------------------------------------------- diff --git a/utils/common/src/main/java/brooklyn/util/javalang/JavaClassNames.java b/utils/common/src/main/java/brooklyn/util/javalang/JavaClassNames.java deleted file mode 100644 index 1de2c46..0000000 --- a/utils/common/src/main/java/brooklyn/util/javalang/JavaClassNames.java +++ /dev/null @@ -1,162 +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 brooklyn.util.net.Urls; -import brooklyn.util.text.Strings; - -import com.google.common.base.Preconditions; -import com.google.common.reflect.TypeToken; - -public class JavaClassNames { - - private static final StackTraceSimplifier STACK_TRACE_SIMPLIFIER_EXCLUDING_UTIL_JAVALANG = - StackTraceSimplifier.newInstance(StackTraceSimplifier.class.getPackage().getName()+"."); - - /** returns the Class of anything which isn't a class; if input is class it is pass-through */ - public static Class<?> type(Object x) { - if (x==null) return null; - if (x instanceof Class) return (Class<?>)x; - if (x instanceof TypeToken) return ((TypeToken<?>)x).getRawType(); - return x.getClass(); - } - - /** like type, but removes any array modifiers */ - public static Class<?> componentType(Object x) { - Class<?> c = type(x); - if (c==null) return null; - while (c.isArray()) { - c = c.getComponentType(); - } - return c; - } - - /** returns a simplified name of the class, just the simple name if it seems useful, else the full name */ - public static String simpleClassName(Class<?> t) { - int arrayCount = 0; - while (t.isArray()) { - arrayCount++; - t = t.getComponentType(); - } - Class<?> ct = componentType(t); - - String result = ct.getSimpleName(); - if (Strings.isBlank(result) || result.length()<=4) { - if (ct.isPrimitive()) { - // TODO unbox - } else { - result = ct.getName(); - } - } - return result+Strings.repeat("[]", arrayCount); - } - - /** as {@link #simpleClassName(Class)} but taking the type of the object if it is not already a class - * or a type-token; callers should usually do the getClass themselves, unless they aren't sure whether - * it is already a Class-type object */ - public static String simpleClassName(Object x) { - if (x==null) return null; - return simpleClassName(type(x)); - } - - /** as {@link #simpleClassName(Class)} but taking a string rep'n of the class name, - * and doing best effort to simplify it (without instantiating) */ - public static String simplifyClassName(String className) { - if (className==null) return null; - int lastDot = className.lastIndexOf('.'); - if (lastDot < className.length()-5) - return className.substring(lastDot+1); - return className; - } - - /** as {@link #simpleClassName(Object)} but making the result clean for use on filesystems and as java identifiers */ - public static String cleanSimpleClassName(Object x) { - return Strings.makeValidFilename(simpleClassName(x)); - } - - /** as {@link #simpleClassName(Object)} but making the result clean for use on filesystems and as java identifiers */ - public static String cleanSimpleClassName(Class<?> x) { - return Strings.makeValidFilename(simpleClassName(x)); - } - - public static String packageName(Object x) { - return componentType(x).getPackage().getName(); - } - - /** returns e.g. "/com/acme/" for an object in package com.acme */ - public static String packagePath(Object x) { - return Urls.mergePaths("/", componentType(x).getPackage().getName().replace('.', '/'), "/"); - } - - /** returns path relative to the package of x, unless path is absolute. - * useful to mimic Class.getResource(path) behaviour, cf Class.resolveName where the first argument below is the class. */ - public static String resolveName(Object context, String path) { - Preconditions.checkNotNull(path, "path must not be null"); - if (path.startsWith("/") || Urls.isUrlWithProtocol(path)) return path; - Preconditions.checkNotNull(context, "context must not be null when path is relative"); - return packagePath(context)+path; - } - - /** returns a "classpath:" URL given a context object and a file to be found in that directory or a sub-directory - * (ignoring the context object if the given path is absolute, i.e. starting with "/" or "protocol:") - * e.g. "classpath://com/acme/foo.txt" given a context object com.acme.SomeClass and "foo.txt" */ - public static String resolveClasspathUrl(Object context, String path) { - if (Urls.isUrlWithProtocol(path)) return path; - // additional / comes from resolve name - return "classpath:/"+resolveName(context, path); - } - - /** returns a cleaned stack trace; caller is usually at the top */ - public static StackTraceElement[] currentStackTraceCleaned() { - return STACK_TRACE_SIMPLIFIER_EXCLUDING_UTIL_JAVALANG.clean( - Thread.currentThread().getStackTrace()); - } - - /** returns top of cleaned stack trace; usually the caller's location */ - public static StackTraceElement currentStackElement() { - return STACK_TRACE_SIMPLIFIER_EXCLUDING_UTIL_JAVALANG.nthUseful(0, - Thread.currentThread().getStackTrace()); - } - - /** returns element in cleaned stack trace; usually the caller's location is at the top, - * and caller of that is up one, etc */ - public static StackTraceElement callerStackElement(int depth) { - return STACK_TRACE_SIMPLIFIER_EXCLUDING_UTIL_JAVALANG.nthUseful(depth, - Thread.currentThread().getStackTrace()); - } - - /** returns nice class name and method for the given element */ - public static String niceClassAndMethod(StackTraceElement st) { - return simplifyClassName(st.getClassName())+"."+st.getMethodName(); - } - - /** returns nice class name and method for the caller, going up the stack (filtered to remove invocation etc), - * with 0 typically being the context where this method is called, 1 being its caller, etc */ - public static String callerNiceClassAndMethod(int depth) { - return niceClassAndMethod(callerStackElement(depth)); - } - - /** convenience for {@link #callerNiceClassAndMethod(int)} with depth 0 - * <p> - * useful for tests and other debug-facing log messages! */ - public static String niceClassAndMethod() { - return callerNiceClassAndMethod(0); - } - -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/main/java/brooklyn/util/javalang/LoadedClassLoader.java ---------------------------------------------------------------------- diff --git a/utils/common/src/main/java/brooklyn/util/javalang/LoadedClassLoader.java b/utils/common/src/main/java/brooklyn/util/javalang/LoadedClassLoader.java deleted file mode 100644 index cef27ab..0000000 --- a/utils/common/src/main/java/brooklyn/util/javalang/LoadedClassLoader.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 brooklyn.util.javalang; - -import java.util.LinkedHashMap; -import java.util.Map; - -/** a classloader which allows you to register classes and resources which this loader will return when needed, - * (essentially a registry rather than a classloader, but useful if you need to make new classes available in - * an old context) */ -public class LoadedClassLoader extends ClassLoader { - - Map<String, Class<?>> loadedClasses = new LinkedHashMap<String, Class<?>>(); - - protected synchronized Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { - Class<?> result = loadedClasses.get(name); - if (result==null) throw new ClassNotFoundException(""+name+" not known here"); - if (resolve) resolveClass(result); - return result; - } - - public void addClass(Class<?> clazz) { - loadedClasses.put(clazz.getName(), clazz); - } - - // TODO could also add resources - -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/main/java/brooklyn/util/javalang/MemoryUsageTracker.java ---------------------------------------------------------------------- diff --git a/utils/common/src/main/java/brooklyn/util/javalang/MemoryUsageTracker.java b/utils/common/src/main/java/brooklyn/util/javalang/MemoryUsageTracker.java deleted file mode 100644 index e8bb896..0000000 --- a/utils/common/src/main/java/brooklyn/util/javalang/MemoryUsageTracker.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.javalang; - -import java.lang.ref.SoftReference; -import java.lang.ref.WeakReference; -import java.util.concurrent.atomic.AtomicLong; - -import com.google.common.cache.Cache; -import com.google.common.cache.CacheBuilder; -import com.google.common.cache.RemovalListener; -import com.google.common.cache.RemovalNotification; - -/** - * Tracks the amount of memory consumed by the given objects in use. - * <p> - * {@link WeakReference}s are used internally, so that shortly after a {@link #track(Object, long)}ed object is GC'd, - * the {@link #getBytesUsed()} value decrements appropriately. - */ -public class MemoryUsageTracker { - - /** - * Shared instance for use for tracking memory used by {@link SoftReference}. - * <p> - * Callers should only use this field to {@link #track(Object, long)} objects which have (or will soon have) - * given up their strong references, so that only soft or weak references remain. - * Provided size estimates are accurate, {@link #getBytesUsed()} will report - * the amount of used memory which is reclaimable by collecting soft references. - * <p> - * This is particularly handy for tracking {@link SoftReference}s, because otherwise you can quickly get to a state - * where {@link Runtime#freeMemory()} looks very low. - **/ - public static final MemoryUsageTracker SOFT_REFERENCES = new MemoryUsageTracker(); - - AtomicLong bytesUsed = new AtomicLong(0); - - Cache<Object, Long> memoryTrackedReferences = CacheBuilder.newBuilder() - .weakKeys() - .removalListener(new RemovalListener<Object,Long>() { - @Override - public void onRemoval(RemovalNotification<Object, Long> notification) { - bytesUsed.addAndGet(-notification.getValue()); - } - }).build(); - - public void track(Object instance, long bytesUsedByInstance) { - bytesUsed.addAndGet(bytesUsedByInstance); - memoryTrackedReferences.put(instance, bytesUsedByInstance); - } - - public long getBytesUsed() { - memoryTrackedReferences.cleanUp(); - return bytesUsed.get(); - } - -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/main/java/brooklyn/util/javalang/Reflections.java ---------------------------------------------------------------------- diff --git a/utils/common/src/main/java/brooklyn/util/javalang/Reflections.java b/utils/common/src/main/java/brooklyn/util/javalang/Reflections.java deleted file mode 100644 index 7db91d4..0000000 --- a/utils/common/src/main/java/brooklyn/util/javalang/Reflections.java +++ /dev/null @@ -1,789 +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 static com.google.common.base.Preconditions.checkNotNull; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.lang.reflect.Array; -import java.lang.reflect.Constructor; -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.net.URL; -import java.util.Arrays; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashSet; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Set; -import java.util.Stack; - -import javax.annotation.Nullable; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import brooklyn.util.collections.MutableList; -import brooklyn.util.exceptions.Exceptions; - -import com.google.common.base.Optional; -import com.google.common.base.Preconditions; -import com.google.common.base.Predicate; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Iterables; -import com.google.common.collect.Sets; - -/** - * Reflection utilities ("borrowed" from cloudsoft monterey). - * - * @author aled - */ -public class Reflections { - - private static final Logger LOG = LoggerFactory.getLogger(Reflections.class); - - public static class ReflectionNotFoundException extends RuntimeException { - private static final long serialVersionUID = 9032835250796708037L; - public ReflectionNotFoundException(String message, Throwable cause) { - super(message, cause); - } - public ReflectionNotFoundException(String message) { - super(message); - } - } - - public static class ReflectionAccessException extends RuntimeException { - private static final long serialVersionUID = 6569605861192432009L; - - public ReflectionAccessException(String message, Throwable cause) { - super(message, cause); - } - } - - private final ClassLoader classLoader; - - public Reflections(ClassLoader classLoader) { - this.classLoader = checkNotNull(classLoader); - } - - public Object loadInstance(String classname, Object...argValues) throws ReflectionNotFoundException, ReflectionAccessException { - Class<?> clazz = loadClass(classname); - Optional<?> v = null; - try { - v = invokeConstructorWithArgs(clazz, argValues); - if (v.isPresent()) return v.get(); - } catch (Exception e) { - throw new IllegalStateException("Error invoking constructor for "+clazz+Arrays.toString(argValues) + ": " + Exceptions.collapseText(e)); - } - throw new IllegalStateException("No suitable constructor for "+clazz+Arrays.toString(argValues)); - } - public Object loadInstance(String classname, Class<?>[] argTypes, Object[] argValues) throws ReflectionNotFoundException, ReflectionAccessException { - Class<?> clazz = loadClass(classname); - Constructor<?> constructor = loadConstructor(clazz, argTypes); - return loadInstance(constructor, argValues); - } - - public Object loadInstance(String classname) throws ReflectionNotFoundException, ReflectionAccessException { - Class<?> clazz = loadClass(classname); - try { - return clazz.newInstance(); - } catch (InstantiationException e) { - throw new ReflectionAccessException("Failed to create instance of class '" + classname + "' using class loader " + classLoader + ": " + Exceptions.collapseText(e), e); - } catch (IllegalAccessException e) { - throw new ReflectionAccessException("Failed to create instance of class '" + classname + "' using class loader " + classLoader + ": " + Exceptions.collapseText(e), e); - } - } - - /** instantiates the given class from its binary name */ - public Class<?> loadClass(String classname) throws ReflectionNotFoundException { - try { - return classLoader.loadClass(classname); - } catch (ClassNotFoundException e) { - throw new ReflectionNotFoundException("Failed to load class '" + classname + "' using class loader " + classLoader + ": " + Exceptions.collapseText(e), e); - } catch (NoClassDefFoundError e) { - throw new ReflectionNotFoundException("Failed to load class '" + classname + "' using class loader " + classLoader + ": " + Exceptions.collapseText(e), e); - } catch (UnsupportedClassVersionError e) { - throw new ReflectionNotFoundException("Failed to load class '" + classname + "' using class loader " + classLoader + ": " + Exceptions.collapseText(e), e); - } - } - - @SuppressWarnings("unchecked") - public <T> Class<? extends T> loadClass(String classname, Class<T> superType) throws ReflectionNotFoundException { - return (Class<? extends T>) loadClass(classname); - } - - /** given a nested part, e.g. Inner$VeryInner, this will recurse through clazz.Inner, looking for VeryInner, - * then looking in each supertype (interface) of clazz for Inner.VeryInner; - * <p> - * so it will find Clazz.Inner.VeryInner wherever in the hierarchy it is defined - * <p> - * (as opposed to ClassLoader which requires Inner.VeryInner to be _declared_ in clazz, not in any supertype - * <p> - * returns null if not found - */ - public static Class<?> loadInnerClassPossiblyInheritted(Class<?> clazz, String nestedPart) throws ReflectionNotFoundException { - Set<String> visited = new HashSet<String>(); - Class<?> result = loadInnerClassPossiblyInheritted(visited, clazz, nestedPart); - if (result!=null) return result; - throw new ReflectionNotFoundException("Inner class " + nestedPart + " could not be found in " + clazz + " or any of its super-types"); - } - - /** as 2-arg, but maintains set of visited elements, and returns null if not found */ - private static Class<?> loadInnerClassPossiblyInheritted(Set<String> visited, Class<?> clazz, String nestedPart) throws ReflectionNotFoundException { - if (clazz==null) return null; - if (nestedPart==null || nestedPart.length()==0) return clazz; - - int i1 = nestedPart.indexOf('$'); - int i2 = nestedPart.indexOf('.'); - int idx = (i2 > -1 && (i2 < i1 || i1==-1) ? i2 : i1); - String thisClassToFind = nestedPart; - String nextClassesToFind = ""; - if (idx>=0) { - thisClassToFind = nestedPart.substring(0, idx); - nextClassesToFind = nestedPart.substring(idx+1); - } - - if (!visited.add(clazz.getCanonicalName()+"!"+nestedPart)) { - //already visited - return null; - } - - Class<?>[] members = clazz.getClasses(); - for (int i = 0; i < members.length; i++) { - if (members[i].getSimpleName().equals(thisClassToFind)) { - Class<?> clazzI = loadInnerClassPossiblyInheritted(visited, members[i], nextClassesToFind); - if (clazzI!=null) return clazzI; - } - } - - //look in supertype first (not sure if necessary) - Class<?> result = loadInnerClassPossiblyInheritted(visited, clazz.getSuperclass(), nestedPart); - if (result!=null) return result; - - for (Class<?> iface : clazz.getInterfaces()) { - result = loadInnerClassPossiblyInheritted(visited, iface, nestedPart); - if (result!=null) return result; - } - return null; - } - - /** does not look through ancestors of outer class */ - public Class<?> loadInnerClassNotInheritted(String outerClassname, String innerClassname) throws ReflectionNotFoundException { - return loadClass(outerClassname + "$" + innerClassname); - } - - /** does not look through ancestors of outer class - * <p> - * uses the classloader set in this class, not in the clazz supplied */ - public Class<?> loadInnerClassNotInheritted(Class<?> outerClazz, String innerClassname) throws ReflectionNotFoundException { - return loadClass(outerClazz.getName() + "$" + innerClassname); - } - - public Constructor<?> loadConstructor(Class<?> clazz, Class<?>[] argTypes) throws ReflectionAccessException { - try { - return clazz.getConstructor(argTypes); - } catch (SecurityException e) { - throw new ReflectionAccessException("Failed to load constructor of class '" + clazz + " with argument types " + Arrays.asList(argTypes) + ": " + Exceptions.collapseText(e), e); - } catch (NoSuchMethodException e) { - throw new ReflectionAccessException("Failed to load constructor of class '" + clazz + " with argument types " + Arrays.asList(argTypes) + ": " + Exceptions.collapseText(e), e); - } - } - - /** Invokes a suitable constructor, supporting varargs and primitives */ - public static <T> Optional<T> invokeConstructorWithArgs(ClassLoader classLoader, String className, Object...argsArray) { - Reflections reflections = new Reflections(classLoader); - @SuppressWarnings("unchecked") - Class<T> clazz = (Class<T>) reflections.loadClass(className); - return invokeConstructorWithArgs(reflections, clazz, argsArray, false); - } - - /** Invokes a suitable constructor, supporting varargs and primitives */ - public static <T> Optional<T> invokeConstructorWithArgs(ClassLoader classLoader, Class<T> clazz, Object[] argsArray, boolean setAccessible) { - Reflections reflections = new Reflections(classLoader); - return invokeConstructorWithArgs(reflections, clazz, argsArray, setAccessible); - } - - /** Invokes a suitable constructor, supporting varargs and primitives */ - public static <T> Optional<T> invokeConstructorWithArgs(Class<T> clazz, Object...argsArray) { - return invokeConstructorWithArgs(clazz, argsArray, false); - } - - /** Invokes a suitable constructor, supporting varargs and primitives */ - public static <T> Optional<T> invokeConstructorWithArgs(Class<T> clazz, Object[] argsArray, boolean setAccessible) { - Reflections reflections = new Reflections(clazz.getClassLoader()); - return invokeConstructorWithArgs(reflections, clazz, argsArray, setAccessible); - } - - /** Invokes a suitable constructor, supporting varargs and primitives, additionally supporting setAccessible */ - @SuppressWarnings("unchecked") - public static <T> Optional<T> invokeConstructorWithArgs(Reflections reflections, Class<T> clazz, Object[] argsArray, boolean setAccessible) { - for (Constructor<?> constructor : clazz.getConstructors()) { - Class<?>[] parameterTypes = constructor.getParameterTypes(); - if (constructor.isVarArgs()) { - if (typesMatchUpTo(argsArray, parameterTypes, parameterTypes.length-1)) { - Class<?> varargType = parameterTypes[parameterTypes.length-1].getComponentType(); - boolean varargsMatch = true; - for (int i=parameterTypes.length-1; i<argsArray.length; i++) { - if (!Boxing.boxedType(varargType).isInstance(argsArray[i]) || - (varargType.isPrimitive() && argsArray[i]==null)) { - varargsMatch = false; - break; - } - } - if (varargsMatch) { - Object varargs = Array.newInstance(varargType, argsArray.length+1 - parameterTypes.length); - for (int i=parameterTypes.length-1; i<argsArray.length; i++) { - Boxing.setInArray(varargs, i+1-parameterTypes.length, argsArray[i], varargType); - } - Object[] newArgsArray = new Object[parameterTypes.length]; - System.arraycopy(argsArray, 0, newArgsArray, 0, parameterTypes.length-1); - newArgsArray[parameterTypes.length-1] = varargs; - if (setAccessible) constructor.setAccessible(true); - return (Optional<T>) Optional.of(reflections.loadInstance(constructor, newArgsArray)); - } - } - } - if (typesMatch(argsArray, parameterTypes)) { - if (setAccessible) constructor.setAccessible(true); - return (Optional<T>) Optional.of(reflections.loadInstance(constructor, argsArray)); - } - } - return Optional.absent(); - } - - - /** returns a single constructor in a given class, or throws an exception */ - public Constructor<?> loadSingleConstructor(Class<?> clazz) { - Constructor<?>[] constructors = clazz.getConstructors(); - if (constructors.length == 1) { - return constructors[0]; - } - throw new IllegalArgumentException("Class " + clazz + " has more than one constructor"); - } - - public <T> T loadInstance(Constructor<T> constructor, Object...argValues) throws IllegalArgumentException, ReflectionAccessException { - try { - try { - return constructor.newInstance(argValues); - } catch (IllegalArgumentException e) { - try { - LOG.warn("Failure passing provided arguments ("+getIllegalArgumentsErrorMessage(constructor, argValues)+"; "+e+"); attempting to reconstitute"); - argValues = (Object[]) updateFromNewClassLoader(argValues); - return constructor.newInstance(argValues); - } catch (Throwable e2) { - LOG.warn("Reconstitution attempt failed (will rethrow original excaption): "+e2, e2); - throw e; - } - } - } catch (IllegalArgumentException e) { - throw new IllegalArgumentException(getIllegalArgumentsErrorMessage(constructor, argValues)+": " + Exceptions.collapseText(e), e); - } catch (InstantiationException e) { - throw new ReflectionAccessException("Failed to create instance of " + constructor.getDeclaringClass() + ": " + Exceptions.collapseText(e), e); - } catch (IllegalAccessException e) { - throw new ReflectionAccessException("Failed to create instance of " + constructor.getDeclaringClass() + ": " + Exceptions.collapseText(e), e); - } catch (InvocationTargetException e) { - throw new ReflectionAccessException("Failed to create instance of " + constructor.getDeclaringClass() + ": " + Exceptions.collapseText(e), e); - } - } - - public Method loadMethod(Class<?> clazz, String methodName, Class<?>[] argTypes) throws ReflectionNotFoundException, ReflectionAccessException { - try { - return clazz.getMethod(methodName, argTypes); - } catch (NoClassDefFoundError e) { - throw new ReflectionNotFoundException("Failed to invoke method " + methodName + " on class " + clazz + " with argument types " + Arrays.asList(argTypes) + ", using class loader " + clazz.getClassLoader() + ": " + Exceptions.collapseText(e), e); - } catch (NoSuchMethodException e) { - throw new ReflectionNotFoundException("Failed to invoke method " + methodName + " on class " + clazz + " with argument types " + Arrays.asList(argTypes) + ": " + Exceptions.collapseText(e), e); - } catch (SecurityException e) { - throw new ReflectionAccessException("Failed to invoke method " + methodName + " on class " + clazz + " with argument types " + Arrays.asList(argTypes) + ": " + Exceptions.collapseText(e), e); - } - } - - /** returns the first method matching the given name */ - public Method loadMethod(Class<?> clazz, String methodName) throws ReflectionNotFoundException, ReflectionAccessException { - try { - Method[] allmethods = clazz.getMethods(); - for (int i = 0; i < allmethods.length; i++) { - if (allmethods[i].getName().equals(methodName)) { - return allmethods[i]; - } - } - throw new ReflectionNotFoundException("Cannot find method " + methodName + " on class " + clazz); - - } catch (SecurityException e) { - throw new ReflectionAccessException("Failed to invoke method '" + methodName + " on class " + clazz + ": " + Exceptions.collapseText(e), e); - } - } - - /** - * - * @throws ReflectionAccessException If invocation failed due to illegal access or the invoked method failed - * @throws IllegalArgumentException If the arguments were invalid - */ - public Object invokeMethod(Method method, Object obj, Object... argValues) throws ReflectionAccessException { - try { - return method.invoke(obj, argValues); - } catch (IllegalArgumentException e) { - throw new IllegalArgumentException(getIllegalArgumentsErrorMessage(method, argValues), e); - } catch (IllegalAccessException e) { - throw new ReflectionAccessException("Failed to invoke method '" + method.toGenericString() + " on class " + method.getDeclaringClass() + " with argument values " + Arrays.asList(argValues) + ": " + Exceptions.collapseText(e), e); - } catch (InvocationTargetException e) { - throw new ReflectionAccessException("Failed to invoke method '" + method.toGenericString() + " on class " + method.getDeclaringClass() + " with argument values " + Arrays.asList(argValues) + ": " + Exceptions.collapseText(e), e); - } - } - - public Object invokeStaticMethod(Method method, Object... argValues) throws IllegalArgumentException, ReflectionAccessException { - try { - return method.invoke(null, argValues); - } catch (IllegalArgumentException e) { - throw new IllegalArgumentException(getIllegalArgumentsErrorMessage(method, argValues), e); - } catch (IllegalAccessException e) { - throw new ReflectionAccessException("Failed to invoke method '" + method.toGenericString() + " on class " + method.getDeclaringClass() + " with argument values " + Arrays.asList(argValues) + ": " + Exceptions.collapseText(e), e); - } catch (InvocationTargetException e) { - throw new ReflectionAccessException("Failed to invoke method '" + method.toGenericString() + " on class " + method.getDeclaringClass() + " with argument values " + Arrays.asList(argValues) + ": " + Exceptions.collapseText(e), e); - } - } - - public Object loadStaticField(Class<?> clazz, String fieldname) throws ReflectionAccessException { - return loadStaticFields(clazz, new String[] {fieldname}, null)[0]; - } - - public Object[] loadStaticFields(Class<?> clazz, String[] fieldnamesArray, Object[] defaults) throws ReflectionAccessException { - Object[] result = new Object[fieldnamesArray.length]; - if (defaults!=null) { - for (int i = 0; i < defaults.length; i++) { - result[i] = defaults[i]; - } - } - - List<String> fieldnames = Arrays.asList(fieldnamesArray); - Field[] classFields = clazz.getDeclaredFields(); - - for (int i = 0; i < classFields.length; i++) { - Field field = classFields[i]; - int index = fieldnames.indexOf(field.getName()); - if (index >= 0) { - try { - result[index] = field.get(null); - } catch (IllegalArgumentException e) { - throw new ReflectionAccessException("Failed to load field '" + field.getName() + " from class " + clazz + ": " + Exceptions.collapseText(e), e); - } catch (IllegalAccessException e) { - throw new ReflectionAccessException("Failed to load field '" + field.getName() + " from class " + clazz + ": " + Exceptions.collapseText(e), e); - } - } - } - return result; - } - - private static String getIllegalArgumentsErrorMessage(Method method, Object[] argValues) { - return method.toGenericString() + " not applicable for the parameters of type " + argumentTypesToString(argValues); - } - - private static String getIllegalArgumentsErrorMessage(Constructor<?> constructor, Object[] argValues) { - return constructor.toGenericString() + " not applicable for the parameters of type " + argumentTypesToString(argValues); - } - - private static String argumentTypesToString(Object[] argValues) { - StringBuffer msg = new StringBuffer("("); - for (int i = 0; i < argValues.length; i++) { - if (i != 0) msg.append(", "); - msg.append(argValues[i] != null ? argValues[i].getClass().getName() : "null"); - } - msg.append(")"); - return msg.toString(); - } - - /** copies all fields from the source to target; very little compile-time safety checking, so use with care - * @throws IllegalAccessException - * @throws IllegalArgumentException */ - public static <T> void copyFields(T source, T target) throws IllegalArgumentException, IllegalAccessException { - Class<? extends Object> clazz = source.getClass(); - while (clazz!=null) { - Field[] fields = clazz.getDeclaredFields(); - for (Field f : fields) { - f.setAccessible(true); - Object vs = f.get(source); - Object vt = f.get(target); - if ((vs==null && vt!=null) || (vs!=null && !vs.equals(vt))) { - f.set(target, vs); - } - } - clazz = clazz.getSuperclass(); - } - } - - /** - * Loads class given its canonical name format (e.g. com.acme.Foo.Inner), - * using iterative strategy (trying com.acme.Foo$Inner, then com.acme$Foo$Inner, etc). - * @throws ReflectionNotFoundException - */ - public Class<?> loadClassFromCanonicalName(String canonicalName) throws ClassNotFoundException, ReflectionNotFoundException { - ClassNotFoundException err = null; - String name = canonicalName; - do { - try { - return classLoader.loadClass(name); - } catch (ClassNotFoundException e) { - if (err == null) err = e; - int lastIndexOf = name.lastIndexOf("."); - if (lastIndexOf >= 0) { - name = name.substring(0, lastIndexOf) + "$" + name.substring(lastIndexOf+1); - } - } - } while (name.contains(".")); - throw err; - } - - /** finds the resource in the classloader, if it exists; inserts or replaces leading slash as necessary - * (i believe it should _not_ have one, but there is some inconsistency) - * - * Will return null if no resource is found. - */ - @Nullable - public URL getResource(String r) { - URL u = null; - u = classLoader.getResource(r); - if (u!=null) return u; - - if (r.startsWith("/")) r = r.substring(1); - else r = "/"+r; - return classLoader.getResource(r); - } - - /** - * Serialize the given object, then reload using the current class loader; - * this removes linkages to instances with classes loaded by an older class loader. - * <p> - * (like a poor man's clone) - * <p> - * aka "reconstitute(Object)" - */ - public final Object updateFromNewClassLoader(Object data) throws IOException, ClassNotFoundException { - ByteArrayOutputStream bytes = new ByteArrayOutputStream(); - new ObjectOutputStream(bytes).writeObject(data); - Object reconstituted = new ObjectInputStream(new ByteArrayInputStream(bytes.toByteArray())).readObject(); - if (LOG.isDebugEnabled()) LOG.debug("Reconstituted data: " + reconstituted + ", class loader: " + classLoader); - return reconstituted; - } - - public ClassLoader getClassLoader() { - return classLoader; - } - - @SuppressWarnings("unchecked") - public static <T> Class<? super T> findSuperType(T impl, String typeName) { - Set<Class<?>> toinspect = new LinkedHashSet<Class<?>>(); - Set<Class<?>> inspected = new HashSet<Class<?>>(); - toinspect.add(impl.getClass()); - - while (toinspect.size() > 0) { - Class<?> clazz = toinspect.iterator().next(); // get and remove the first element - if (clazz.getName().equals(typeName)) { - return (Class<? super T>) clazz; - } - inspected.add(clazz); - List<Class<?>> toAdd = Arrays.asList(clazz.getInterfaces()); - toinspect.addAll( toAdd ); - if (clazz.getSuperclass() != null) toinspect.add(clazz.getSuperclass()); - toinspect.removeAll(inspected); - } - - return null; - } - - /** whereas Class.getInterfaces() only returns interfaces directly implemented by a class, - * this walks the inheritance hierarchy to include interfaces implemented by superclass/ancestors; - * (note it does not include superinterfaces) - */ - public static Set<Class<?>> getInterfacesIncludingClassAncestors(Class<?> clazz) { - Set<Class<?>> result = new LinkedHashSet<Class<?>>(); - while (clazz!=null) { - for (Class<?> iface: clazz.getInterfaces()) - result.add(iface); - clazz = clazz.getSuperclass(); - } - return result; - } - - public static Method findMethod(Class<?> clazz, String name, Class<?>... parameterTypes) throws NoSuchMethodException { - if (clazz == null || name == null) { - throw new NullPointerException("Must not be null: clazz="+clazz+"; name="+name); - } - Class<?> clazzToInspect = clazz; - NoSuchMethodException toThrowIfFails = null; - - while (clazzToInspect != null) { - try { - return clazzToInspect.getDeclaredMethod(name, parameterTypes); - } catch (NoSuchMethodException e) { - if (toThrowIfFails == null) toThrowIfFails = e; - clazzToInspect = clazzToInspect.getSuperclass(); - } - } - throw toThrowIfFails; - } - - public static Field findField(Class<?> clazz, String name) throws NoSuchFieldException { - if (clazz == null || name == null) { - throw new NullPointerException("Must not be null: clazz="+clazz+"; name="+name); - } - Class<?> clazzToInspect = clazz; - NoSuchFieldException toThrowIfFails = null; - - while (clazzToInspect != null) { - try { - return clazzToInspect.getDeclaredField(name); - } catch (NoSuchFieldException e) { - if (toThrowIfFails == null) toThrowIfFails = e; - clazzToInspect = clazzToInspect.getSuperclass(); - } - } - throw toThrowIfFails; - } - - public static List<Field> findPublicFieldsOrderedBySuper(Class<?> clazz) { - checkNotNull(clazz, "clazz"); - MutableList.Builder<Field> result = MutableList.<Field>builder(); - Stack<Class<?>> tovisit = new Stack<Class<?>>(); - Set<Class<?>> visited = Sets.newLinkedHashSet(); - tovisit.push(clazz); - - while (!tovisit.isEmpty()) { - Class<?> nextclazz = tovisit.pop(); - if (!visited.add(nextclazz)) { - continue; // already visited - } - if (nextclazz.getSuperclass() != null) tovisit.add(nextclazz.getSuperclass()); - tovisit.addAll(Arrays.asList(nextclazz.getInterfaces())); - - result.addAll(Iterables.filter(Arrays.asList(nextclazz.getDeclaredFields()), new Predicate<Field>() { - @Override public boolean apply(Field input) { - return Modifier.isPublic(input.getModifiers()); - }})); - - } - - List<Field> resultList = result.build(); - Collections.sort(resultList, new Comparator<Field>() { - @Override public int compare(Field f1, Field f2) { - Field fsubbest = inferSubbestField(f1, f2); - return (fsubbest == null) ? 0 : (fsubbest == f1 ? 1 : -1); - }}); - - return resultList; - } - - // TODO I've seen strange behaviour where class.getMethods() does not include methods from interfaces. - // Also the ordering guarantees here are useful... - public static List<Method> findPublicMethodsOrderedBySuper(Class<?> clazz) { - checkNotNull(clazz, "clazz"); - MutableList.Builder<Method> result = MutableList.<Method>builder(); - Stack<Class<?>> tovisit = new Stack<Class<?>>(); - Set<Class<?>> visited = Sets.newLinkedHashSet(); - tovisit.push(clazz); - - while (!tovisit.isEmpty()) { - Class<?> nextclazz = tovisit.pop(); - if (!visited.add(nextclazz)) { - continue; // already visited - } - if (nextclazz.getSuperclass() != null) tovisit.add(nextclazz.getSuperclass()); - tovisit.addAll(Arrays.asList(nextclazz.getInterfaces())); - - result.addAll(Iterables.filter(Arrays.asList(nextclazz.getDeclaredMethods()), new Predicate<Method>() { - @Override public boolean apply(Method input) { - return Modifier.isPublic(input.getModifiers()); - }})); - - } - - List<Method> resultList = result.build(); - Collections.sort(resultList, new Comparator<Method>() { - @Override public int compare(Method m1, Method m2) { - Method msubbest = inferSubbestMethod(m1, m2); - return (msubbest == null) ? 0 : (msubbest == m1 ? 1 : -1); - }}); - - return resultList; - } - - /** - * Gets the field that is in the sub-class; or null if one field does not come from a sub-class of the other field's class - */ - public static Field inferSubbestField(Field f1, Field f2) { - Class<?> c1 = f1.getDeclaringClass(); - Class<?> c2 = f2.getDeclaringClass(); - boolean isSuper1 = c1.isAssignableFrom(c2); - boolean isSuper2 = c2.isAssignableFrom(c1); - return (isSuper1) ? (isSuper2 ? null : f2) : (isSuper2 ? f1 : null); - } - - /** - * Gets the method that is in the sub-class; or null if one method does not come from a sub-class of the other method's class - */ - public static Method inferSubbestMethod(Method m1, Method m2) { - Class<?> c1 = m1.getDeclaringClass(); - Class<?> c2 = m2.getDeclaringClass(); - boolean isSuper1 = c1.isAssignableFrom(c2); - boolean isSuper2 = c2.isAssignableFrom(c1); - return (isSuper1) ? (isSuper2 ? null : m2) : (isSuper2 ? m1 : null); - } - - /** - * Gets the class that is in the sub-class; or null if neither is a sub-class of the other. - */ - public static Class<?> inferSubbest(Class<?> c1, Class<?> c2) { - boolean isSuper1 = c1.isAssignableFrom(c2); - boolean isSuper2 = c2.isAssignableFrom(c1); - return (isSuper1) ? (isSuper2 ? null : c2) : (isSuper2 ? c1 : null); - } - - /** convenience for casting the given candidate to the given type (without any coercion, and allowing candidate to be null) */ - @SuppressWarnings("unchecked") - public static <T> T cast(Object candidate, Class<? extends T> type) { - if (candidate==null) return null; - if (!type.isAssignableFrom(candidate.getClass())) - throw new IllegalArgumentException("Requires a "+type+", but had a "+candidate.getClass()+" ("+candidate+")"); - return (T)candidate; - } - - /** invokes the given method on the given clazz or instance, doing reasonably good matching on args etc - * @throws InvocationTargetException - * @throws IllegalAccessException - * @throws IllegalArgumentException */ - public static Optional<Object> invokeMethodWithArgs(Object clazzOrInstance, String method, List<Object> args) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException { - return invokeMethodWithArgs(clazzOrInstance, method, args, false); - } - public static Optional<Object> invokeMethodWithArgs(Object clazzOrInstance, String method, List<Object> args, boolean setAccessible) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException { - Preconditions.checkNotNull(clazzOrInstance, "clazz or instance"); - Preconditions.checkNotNull(method, "method"); - Preconditions.checkNotNull(args, "args to "+method); - - Class<?> clazz; - Object instance; - if (clazzOrInstance instanceof Class) { - clazz = (Class<?>)clazzOrInstance; - instance = null; - } else { - clazz = clazzOrInstance.getClass(); - instance = clazzOrInstance; - } - - Object[] argsArray = args.toArray(); - - for (Method m: clazz.getMethods()) { - if (method.equals(m.getName())) { - Class<?>[] parameterTypes = m.getParameterTypes(); - if (m.isVarArgs()) { - if (typesMatchUpTo(argsArray, parameterTypes, parameterTypes.length-1)) { - Class<?> varargType = parameterTypes[parameterTypes.length-1].getComponentType(); - boolean varargsMatch = true; - for (int i=parameterTypes.length-1; i<argsArray.length; i++) { - if (!Boxing.boxedType(varargType).isInstance(argsArray[i]) || - (varargType.isPrimitive() && argsArray[i]==null)) { - varargsMatch = false; - break; - } - } - if (varargsMatch) { - Object varargs = Array.newInstance(varargType, argsArray.length+1 - parameterTypes.length); - for (int i=parameterTypes.length-1; i<argsArray.length; i++) { - Boxing.setInArray(varargs, i+1-parameterTypes.length, argsArray[i], varargType); - } - Object[] newArgsArray = new Object[parameterTypes.length]; - System.arraycopy(argsArray, 0, newArgsArray, 0, parameterTypes.length-1); - newArgsArray[parameterTypes.length-1] = varargs; - if (setAccessible) m.setAccessible(true); - return Optional.of(m.invoke(instance, newArgsArray)); - } - } - } - if (typesMatch(argsArray, parameterTypes)) { - if (setAccessible) m.setAccessible(true); - return Optional.of(m.invoke(instance, argsArray)); - } - } - } - - return Optional.absent(); - } - - /** true iff all args match the corresponding types */ - public static boolean typesMatch(Object[] argsArray, Class<?>[] parameterTypes) { - if (argsArray.length != parameterTypes.length) - return false; - return typesMatchUpTo(argsArray, parameterTypes, argsArray.length); - } - - /** true iff the initial N args match the corresponding types */ - public static boolean typesMatchUpTo(Object[] argsArray, Class<?>[] parameterTypes, int lengthRequired) { - if (argsArray.length < lengthRequired || parameterTypes.length < lengthRequired) - return false; - for (int i=0; i<lengthRequired; i++) { - if (argsArray[i]==null) continue; - if (Boxing.boxedType(parameterTypes[i]).isInstance(argsArray[i])) continue; - return false; - } - return true; - } - - /** - * Gets all the interfaces implemented by the given type, including its parent classes. - * - * @param type the class to look up - * @return an immutable list of the interface classes - */ - public static List<Class<?>> getAllInterfaces(@Nullable Class<?> type) { - Set<Class<?>> found = Sets.newLinkedHashSet(); - findAllInterfaces(type, found); - return ImmutableList.copyOf(found); - } - - /** Recurse through the class hierarchies of the type and its interfaces. */ - private static void findAllInterfaces(@Nullable Class<?> type, Set<Class<?>> found) { - if (type == null) return; - for (Class<?> i : type.getInterfaces()) { - if (found.add(i)) { // not seen before - findAllInterfaces(i, found); - } - } - findAllInterfaces(type.getSuperclass(), found); - } - - public static boolean hasNoArgConstructor(Class<?> clazz) { - try { - clazz.getConstructor(new Class[0]); - return true; - } catch (NoSuchMethodException e) { - return false; - } - } - - public static boolean hasNoNonObjectFields(Class<? extends Object> clazz) { - if (Object.class.equals(clazz)) return true; - if (clazz.getDeclaredFields().length>0) return false; - return hasNoNonObjectFields(clazz.getSuperclass()); - } -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/main/java/brooklyn/util/javalang/Serializers.java ---------------------------------------------------------------------- diff --git a/utils/common/src/main/java/brooklyn/util/javalang/Serializers.java b/utils/common/src/main/java/brooklyn/util/javalang/Serializers.java deleted file mode 100644 index b16229f..0000000 --- a/utils/common/src/main/java/brooklyn/util/javalang/Serializers.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package brooklyn.util.javalang; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.io.ObjectStreamClass; -import java.io.OutputStream; - -import brooklyn.util.stream.Streams; - -public class Serializers { - - public interface ObjectReplacer { - public static final ObjectReplacer NOOP = new ObjectReplacer() { - @Override public Object replace(Object toserialize) { - return toserialize; - } - @Override public Object resolve(Object todeserialize) { - return todeserialize; - } - }; - - public Object replace(Object toserialize); - public Object resolve(Object todeserialize); - } - - public static <T> T reconstitute(T object) throws IOException, ClassNotFoundException { - return reconstitute(object, ObjectReplacer.NOOP); - } - - public static <T> T reconstitute(T object, ObjectReplacer replacer) throws IOException, ClassNotFoundException { - if (object == null) return null; - return reconstitute(object, object.getClass().getClassLoader(), replacer); - } - - public static <T> T reconstitute(T object, ClassLoader classLoader) throws IOException, ClassNotFoundException { - return reconstitute(object, classLoader, ObjectReplacer.NOOP); - } - - @SuppressWarnings("unchecked") - public static <T> T reconstitute(T object, ClassLoader classLoader, final ObjectReplacer replacer) throws IOException, ClassNotFoundException { - if (object == null) return null; - - class ReconstitutingObjectOutputStream extends ObjectOutputStream { - public ReconstitutingObjectOutputStream(OutputStream outputStream) throws IOException { - super(outputStream); - enableReplaceObject(true); - } - @Override - protected Object replaceObject(Object obj) throws IOException { - return replacer.replace(obj); - } - }; - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - ObjectOutputStream oos = new ReconstitutingObjectOutputStream(baos); - oos.writeObject(object); - oos.close(); - - class ReconstitutingObjectInputStream extends ClassLoaderObjectInputStream { - public ReconstitutingObjectInputStream(InputStream inputStream, ClassLoader classLoader) throws IOException { - super(inputStream, classLoader); - super.enableResolveObject(true); - } - @Override protected Object resolveObject(Object obj) throws IOException { - return replacer.resolve(obj); - } - }; - ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); - ReconstitutingObjectInputStream ois = new ReconstitutingObjectInputStream(bais, classLoader); - try { - return (T) ois.readObject(); - } finally { - Streams.closeQuietly(ois); - } - } - - /** - * Follows pattern in org.apache.commons.io.input.ClassLoaderObjectInputStream - */ - public static class ClassLoaderObjectInputStream extends ObjectInputStream { - - private final ClassLoader classLoader; - - public ClassLoaderObjectInputStream(InputStream inputStream, ClassLoader classLoader) throws IOException { - super(inputStream); - this.classLoader = classLoader; - } - - @Override - protected Class<?> resolveClass(ObjectStreamClass objectStreamClass) throws IOException, ClassNotFoundException { - Class<?> clazz = Class.forName(objectStreamClass.getName(), false, classLoader); - - if (clazz != null) { - return clazz; - } else { - return super.resolveClass(objectStreamClass); - } - } - } -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/main/java/brooklyn/util/javalang/StackTraceSimplifier.java ---------------------------------------------------------------------- diff --git a/utils/common/src/main/java/brooklyn/util/javalang/StackTraceSimplifier.java b/utils/common/src/main/java/brooklyn/util/javalang/StackTraceSimplifier.java deleted file mode 100644 index 283cb98..0000000 --- a/utils/common/src/main/java/brooklyn/util/javalang/StackTraceSimplifier.java +++ /dev/null @@ -1,203 +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.PrintWriter; -import java.io.StringWriter; -import java.util.Arrays; -import java.util.Collection; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import brooklyn.util.text.Strings; - -import com.google.common.annotations.Beta; -import com.google.common.collect.ImmutableSet; - -/** - * Utility class for cleaning up stacktraces. - */ -public class StackTraceSimplifier { - - private static final Logger log = LoggerFactory.getLogger(StackTraceSimplifier.class); - - /** comma-separated prefixes (not regexes) */ - public static final String DEFAULT_BLACKLIST_SYSTEM_PROPERTY_NAME = "brooklyn.util.javalang.StackTraceSimplifier.blacklist"; - - /** @deprecated since 0.6.0 use {@link #DEFAULT_BLACKLIST_SYSTEM_PROPERTY_NAME} */ @Deprecated - public static final String LEGACY_DEFAULT_BLACKLIST_SYSTEM_PROPERTY_NAME = "groovy.sanitized.stacktraces"; - - private static final Collection<String> DEFAULT_BLACKLIST; - - static { - ImmutableSet.Builder<String> blacklist = ImmutableSet.builder(); - blacklist.addAll(Arrays.asList( - System.getProperty(DEFAULT_BLACKLIST_SYSTEM_PROPERTY_NAME, - "java.," + - "javax.," + - "sun.," + - "groovy.," + - "org.codehaus.groovy.," + - "gjdk.groovy.," - ).split("(\\s|,)+"))); - - String legacyDefaults = System.getProperty(LEGACY_DEFAULT_BLACKLIST_SYSTEM_PROPERTY_NAME); - if (Strings.isNonBlank(legacyDefaults)) { - log.warn("Detected ude of legacy system property "+LEGACY_DEFAULT_BLACKLIST_SYSTEM_PROPERTY_NAME); - blacklist.addAll(Arrays.asList(legacyDefaults.split("(\\s|,)+"))); - } - - DEFAULT_BLACKLIST = blacklist.build(); - } - - private static final StackTraceSimplifier DEFAULT_INSTACE = newInstance(); - - private final Collection<String> blacklist; - - protected StackTraceSimplifier() { - this(true); - } - - protected StackTraceSimplifier(boolean includeDefaultBlacklist, String ...packages) { - ImmutableSet.Builder<String> blacklistB = ImmutableSet.builder(); - if (includeDefaultBlacklist) - blacklistB.addAll(DEFAULT_BLACKLIST); - blacklistB.add(packages); - blacklist = blacklistB.build(); - } - - public static StackTraceSimplifier newInstance() { - return new StackTraceSimplifier(); - } - - public static StackTraceSimplifier newInstance(String ...additionalBlacklistPackagePrefixes) { - return new StackTraceSimplifier(true, additionalBlacklistPackagePrefixes); - } - - public static StackTraceSimplifier newInstanceExcludingOnly(String ...blacklistPackagePrefixes) { - return new StackTraceSimplifier(false, blacklistPackagePrefixes); - } - - /** @return whether the given element is useful, that is, not in the blacklist */ - public boolean isUseful(StackTraceElement el) { - for (String s: blacklist){ - if (el.getClassName().startsWith(s)) return false;; - // gets underscores in some contexts ? - if (el.getClassName().replace('_', '.').startsWith(s)) return false; - } - - return true; - } - - /** @return new list containing just the {@link #isUseful(StackTraceElement)} stack trace elements */ - public List<StackTraceElement> clean(Iterable<StackTraceElement> st) { - List<StackTraceElement> result = new LinkedList<StackTraceElement>(); - for (StackTraceElement element: st){ - if (isUseful(element)){ - result.add(element); - } - } - - return result; - } - - /** @return new array containing just the {@link #isUseful(StackTraceElement)} stack trace elements */ - public StackTraceElement[] clean(StackTraceElement[] st) { - List<StackTraceElement> result = clean(Arrays.asList(st)); - return result.toArray(new StackTraceElement[result.size()]); - } - - /** @return first {@link #isUseful(StackTraceElement)} stack trace elements, or null */ - public StackTraceElement firstUseful(StackTraceElement[] st) { - return nthUseful(0, st); - } - - /** @return (n+1)th {@link #isUseful(StackTraceElement)} stack trace elements (ie 0 is {@link #firstUseful(StackTraceElement[])}), or null */ - public StackTraceElement nthUseful(int n, StackTraceElement[] st) { - for (StackTraceElement element: st){ - if (isUseful(element)) { - if (n==0) - return element; - n--; - } - } - return null; - } - - /** {@link #clean(StackTraceElement[])} the given throwable instance, returning the same instance for convenience */ - public <T extends Throwable> T cleaned(T t) { - t.setStackTrace(clean(t.getStackTrace())); - return t; - } - - // ---- statics - - /** static convenience for {@link #isUseful(StackTraceElement)} */ - public static boolean isStackTraceElementUseful(StackTraceElement el) { - return DEFAULT_INSTACE.isUseful(el); - } - - /** static convenience for {@link #clean(Iterable)} */ - public static List<StackTraceElement> cleanStackTrace(Iterable<StackTraceElement> st) { - return DEFAULT_INSTACE.clean(st); - } - - /** static convenience for {@link #clean(StackTraceElement[])} */ - public static StackTraceElement[] cleanStackTrace(StackTraceElement[] st) { - return DEFAULT_INSTACE.clean(st); - } - - /** static convenience for {@link #cleaned(Throwable)} */ - public static <T extends Throwable> T cleanedStackTrace(T t) { - return DEFAULT_INSTACE.cleaned(t); - } - - public static String toString(Throwable t) { - StringWriter sw = new StringWriter(); - PrintWriter pw = new PrintWriter(sw); - t.printStackTrace(pw); - return sw.getBuffer().toString(); - } - - /** returns the number of times the calling method occurs elsewhere in the stack trace; - * 0 if no recursion, 1 if it has cycled three times, etc. */ - @Beta // useful to track down things like https://github.com/apache/incubator-brooklyn/pull/489 - public static int getRecursiveCallCount() { - StackTraceElement[] t = cleanStackTrace(new Throwable().getStackTrace()); - Iterator<StackTraceElement> ti = Arrays.asList(t).iterator(); - ti.next(); - if (!ti.hasNext()) return 0; - // t0 is the caller - StackTraceElement t0 = ti.next(); - String l0 = t0.getClassName()+"."+t0.getMethodName()+"("+t0.getFileName()+")"; - int count = 0; - while (ti.hasNext()) { - StackTraceElement ta = ti.next(); - String li = ta.getClassName()+"."+ta.getMethodName()+"("+ta.getFileName()+")"; - // if we have something in a different method, then something back in the method - // from which the recursive check came, then return true - if (li.equals(l0)) count++; - } - return count; - } -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/main/java/brooklyn/util/javalang/Threads.java ---------------------------------------------------------------------- diff --git a/utils/common/src/main/java/brooklyn/util/javalang/Threads.java b/utils/common/src/main/java/brooklyn/util/javalang/Threads.java deleted file mode 100644 index b3af17b..0000000 --- a/utils/common/src/main/java/brooklyn/util/javalang/Threads.java +++ /dev/null @@ -1,62 +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 org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import brooklyn.util.exceptions.Exceptions; - -public class Threads { - - private static final Logger log = LoggerFactory.getLogger(Threads.class); - - public static Thread addShutdownHook(final Runnable task) { - Thread t = new Thread("shutdownHookThread") { - public void run() { - try { - task.run(); - } catch (Exception e) { - log.error("Failed to execute shutdownhook", e); - } - } - }; - Runtime.getRuntime().addShutdownHook(t); - return t; - } - - public static boolean removeShutdownHook(Thread hook) { - try { - return Runtime.getRuntime().removeShutdownHook(hook); - } catch (IllegalStateException e) { - // probably shutdown in progress - String text = Exceptions.collapseText(e); - if (text.contains("Shutdown in progress")) { - if (log.isTraceEnabled()) { - log.trace("Could not remove shutdown hook "+hook+": "+text); - } - } else { - log.warn("Could not remove shutdown hook "+hook+": "+text); - log.debug("Shutdown hook removal details: "+e, e); - } - return false; - } - } - -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/main/java/brooklyn/util/logging/LoggingSetup.java ---------------------------------------------------------------------- diff --git a/utils/common/src/main/java/brooklyn/util/logging/LoggingSetup.java b/utils/common/src/main/java/brooklyn/util/logging/LoggingSetup.java deleted file mode 100644 index ba89426..0000000 --- a/utils/common/src/main/java/brooklyn/util/logging/LoggingSetup.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.logging; - -import org.slf4j.bridge.SLF4JBridgeHandler; - -public class LoggingSetup { - - /** bridge java.util.logging messages to slf4j - * <p> - * without this, we get ugly java.util.logging messages on the console and _not_ in the file; - * with this, the excludes rules (which route the common j.u.l categories to the file _only_) - * will apply to j.u.l loggers - * <p> - * typically this is invoked in a static block on a class (in tests and in BrooklynWebServer) - * or could be done on app startup */ - public static void installJavaUtilLoggingBridge() { - SLF4JBridgeHandler.removeHandlersForRootLogger(); - SLF4JBridgeHandler.install(); - } - - -}
