http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/49d99d4e/gemfire-core/src/main/java/com/gemstone/gemfire/internal/tools/gfsh/app/util/SimplePrintUtil.java ---------------------------------------------------------------------- diff --git a/gemfire-core/src/main/java/com/gemstone/gemfire/internal/tools/gfsh/app/util/SimplePrintUtil.java b/gemfire-core/src/main/java/com/gemstone/gemfire/internal/tools/gfsh/app/util/SimplePrintUtil.java deleted file mode 100644 index f126ae0..0000000 --- a/gemfire-core/src/main/java/com/gemstone/gemfire/internal/tools/gfsh/app/util/SimplePrintUtil.java +++ /dev/null @@ -1,1366 +0,0 @@ -package com.gemstone.gemfire.internal.tools.gfsh.app.util; - -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Date; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import com.gemstone.gemfire.cache.Region; -import com.gemstone.gemfire.cache.query.SelectResults; -import com.gemstone.gemfire.cache.query.Struct; -import com.gemstone.gemfire.cache.query.types.CollectionType; -import com.gemstone.gemfire.cache.query.types.ObjectType; -import com.gemstone.gemfire.cache.query.types.StructType; -import com.gemstone.gemfire.internal.tools.gfsh.app.cache.data.Mappable; -import com.gemstone.gemfire.internal.tools.gfsh.app.misc.util.StringUtil; - -public class SimplePrintUtil -{ - private static boolean printType = false; - private static int collectionEntryPrintCount = 5; - - public static boolean isPrintType() - { - return printType; - } - - public static void setPrintType(boolean printType) - { - SimplePrintUtil.printType = printType; - } - - public static int getCollectionEntryPrintCount() - { - return collectionEntryPrintCount; - } - - public static void setCollectionEntryPrintCount(int collectionEntryPrintCount) - { - SimplePrintUtil.collectionEntryPrintCount = collectionEntryPrintCount; - } - - /** - * Prints the region entries. It prints both keys and values formatted. - * @param region - * @param startIndex - * @param startRowNum - * @param rowCount - * @param keyList - * @return Returns the number of rows printed. - * @throws Exception - */ - public static int printEntries(Region region, Iterator regionIterator, int startIndex, int startRowNum, int rowCount, List keyList) throws Exception - { - - if (region == null || regionIterator == null) { - System.out.println("Error: Region is null"); - return 0; - } - - int endIndex = startIndex + rowCount; // exclusive - if (endIndex >= region.size()) { - endIndex = region.size(); - } - - if (startIndex == endIndex) { - return 0; - } - - HashSet keyNameSet = new HashSet(); - HashSet valueNameSet = new HashSet(); - Object key = null; - Object value = null; - int index = startIndex; - - // Print keys and values - int row = startRowNum; - index = startIndex; - for (Iterator itr = regionIterator; index < endIndex && itr.hasNext(); index++) { - Region.Entry entry = (Region.Entry) itr.next(); - key = entry.getKey(); - value = entry.getValue(); - keyNameSet.add(key.getClass().getName()); - if (value != null) { - valueNameSet.add(value.getClass().getName()); - } - printObject(row, "Key", key, true); - printObject(row, "Value", value, false); - System.out.println(); - row++; - } - - System.out.println(); - System.out.println(" Fetch size: " + rowCount); - System.out.println(" Returned: " + (row-1) + "/" + region.size()); - for (Object keyName : keyNameSet) { - System.out.println(" Key Class: " + keyName); - } - for (Object valueName : valueNameSet) { - System.out.println("Value Class: " + valueName); - - } - return endIndex - startIndex; - } - - public static int printEntries(Region region, Map keyMap, List keyList) throws Exception - { - if (region == null) { - System.out.println("Error: Region is null"); - return 0; - } - - HashSet keyNameSet = new HashSet(); - HashSet valueNameSet = new HashSet(); - ArrayList indexList = new ArrayList(keyMap.keySet()); - Collections.sort(indexList); - Object key = null; - Object value = null; - - // Print keys and values - int row = 1; - int rowCount = keyMap.size(); - for (Iterator iterator = indexList.iterator(); iterator.hasNext();) { - Object index = iterator.next(); - key = keyMap.get(index); - value = region.get(key); - keyNameSet.add(key.getClass().getName()); - if (value != null) { - valueNameSet.add(value.getClass().getName()); - } - printObject(row, "Key", key, true); - printObject(row, "Value", value, false); - System.out.println(); - row++; - } - - System.out.println(); - for (Object keyName : keyNameSet) { - System.out.println(" Key Class: " + keyName); - } - for (Object valueName : valueNameSet) { - System.out.println("Value Class: " + valueName); - } - return rowCount; - } - - public static int printEntries(Region region, Set keySet, List keyList) throws Exception - { - if (region == null) { - System.out.println("Error: Region is null"); - return 0; - } - - if (keySet.size() == 0) { - return 0; - } - - // Print keys and values - HashSet keyNameSet = new HashSet(); - HashSet valueNameSet = new HashSet(); - int row = 1; - Object key = null; - Object value = null; - for (Iterator iterator = keySet.iterator(); iterator.hasNext();) { - key = iterator.next(); - value = region.get(key); - if (keyList != null) { - keyList.add(key); - } - keyNameSet.add(key.getClass().getName()); - if (value != null) { - valueNameSet.add(value.getClass().getName()); - } - printObject(row, "Key", key, true); - printObject(row, "Value", value, false); - row++; - } - System.out.println(); - for (Object keyName : keyNameSet) { - System.out.println(" Key Class: " + keyName); - } - for (Object valueName : valueNameSet) { - System.out.println("Value Class: " + valueName); - } - return row - 1; - } - - public static int printEntries(Map map, int startIndex, int startRowNum, int rowCount, int actualSize, List keyList) throws Exception - { - if (map == null) { - System.out.println("Error: map is null"); - return 0; - } - - HashSet keyNameSet = new HashSet(); - HashSet valueNameSet = new HashSet(); - Object key = null; - Object value = null; - Set entrySet = map.entrySet(); - int count = 0; - int row = startRowNum; - int lastRow = startRowNum + rowCount - 1; - for (Iterator itr = entrySet.iterator(); count < rowCount && itr.hasNext(); count++) { - Map.Entry entry = (Map.Entry) itr.next(); - key = entry.getKey(); - value = entry.getValue(); - keyNameSet.add(key.getClass().getName()); - if (value != null) { - valueNameSet.add(value.getClass().getName()); - } - printObject(row, "Key", key, true, 2); - printObject(row, "Value", value, false, 2); - System.out.println(); - row++; - } - System.out.println(); - System.out.println(" Fetch size: " + rowCount); - System.out.println(" Returned: " + (row-1) + "/" + actualSize); - for (Object keyName : keyNameSet) { - System.out.println(" Key Class: " + keyName); - } - for (Object valueName : valueNameSet) { - System.out.println("Value Class: " + valueName); - } - return count; - } - - public static int printEntries(Map map, int rowCount, List keyList, - boolean displaySummary, boolean showValues) throws Exception - { - return printEntries(map, rowCount, keyList, "Key", "Value", displaySummary, showValues); - } - - public static int printEntries(Map map, int rowCount, List keyList, - String keyColumnName, String valueColumnName, - boolean displaySummary, boolean showValues) throws Exception - { - if (map == null) { - System.out.println("Error: Region is null"); - return 0; - } - - if (map.size() == 0) { - return 0; - } - - // Print keys and values - int row = 1; - Object key = null; - Object value = null; - int count = 0; - HashSet keyNameSet = new HashSet(); - HashSet valueNameSet = new HashSet(); - Set nameSet = map.entrySet(); - for (Iterator itr = nameSet.iterator(); count < rowCount && itr.hasNext(); count++) { - - Map.Entry entry = (Map.Entry) itr.next(); - key = entry.getKey(); - value = entry.getValue(); - if (keyList != null) { - keyList.add(key); - } - keyNameSet.add(key.getClass().getName()); - if (value != null) { - valueNameSet.add(value.getClass().getName()); - } - printObject(row, keyColumnName, key, true, 2); - if (showValues) { - printObject(row, valueColumnName, value, false, 2); - } - System.out.println(); - row++; - } - if (displaySummary) { - System.out.println(); - System.out.println("Displayed (fetched): " + (row - 1)); - System.out.println(" Actual Size: " + map.size()); - for (Object keyName : keyNameSet) { - System.out.println(" " + keyColumnName + " Class: " + keyName); - } - for (Object valueName : valueNameSet) { - System.out.println(" " + valueColumnName + " Class: " + valueName); - - } - } - return row - 1; - } - - public static int printSet(Set set, int rowCount, List keyList, - String keyColumnName, - boolean displaySummary) throws Exception - { - if (set == null) { - return 0; - } - - if (set.size() == 0) { - return 0; - } - - // Print keys and values - int row = 1; - Object key = null; - int count = 0; - HashSet keyNameSet = new HashSet(); -// HashSet valueNameSet = new HashSet(); //FindBugs - unused - Set nameSet = set; - for (Iterator itr = nameSet.iterator(); count < rowCount && itr.hasNext(); count++) { - key = itr.next(); - if (keyList != null) { - keyList.add(key); - } - keyNameSet.add(key.getClass().getName()); - printObject(row, keyColumnName, key, true, 2); - System.out.println(); - row++; - } - if (displaySummary) { - System.out.println(); - System.out.println("Displayed (fetched): " + (row - 1)); - System.out.println(" Actual Size: " + set.size()); - for (Object keyName : keyNameSet) { - System.out.println(" " + keyColumnName + " Class: " + keyName); - } - } - return row - 1; - } - -//FindBugs - private method never called -// private static void computeMaxLengths(List keyList, List valueList, Object key, Object value) -// { -// computeMaxLengths(keyList, key, true); -// computeMaxLengths(valueList, value, false); -// } - - private static void printTopHeaders(List list, Object obj, - boolean printLastColumnSpaces, String primitiveHeader) - { - Object object = obj; - if (object == null) { - object = "null"; - } - - if (object instanceof String || object.getClass().isPrimitive() || - object.getClass() == Boolean.class || - object.getClass() == Byte.class || - object.getClass() == Character.class || - object.getClass() == Short.class || - object.getClass() == Integer.class || - object.getClass() == Long.class || - object.getClass() == Float.class || - object.getClass() == Double.class || - object.getClass().isArray() || - object instanceof Date) - { - - int maxLen = (Integer) list.get(0); - if (maxLen < primitiveHeader.length()) { - maxLen = primitiveHeader.length(); - } - if (printLastColumnSpaces) { - System.out.print(StringUtil.getRightPaddedString(primitiveHeader, maxLen, ' ')); - } else { - System.out.print(primitiveHeader); - } - - } else { - - Class cls = object.getClass(); - Method methods[] = cls.getMethods(); - Method method; - Class retType; - String name; - Object value; - int listIndex = 0; - for (int i = 0; i < methods.length; i++) { - method = methods[i]; - name = method.getName(); - if (name.length() <= 3 || name.startsWith("get") == false || name.equals("getClass")) { - continue; - } - retType = method.getReturnType(); - if (retType == Void.TYPE) { - continue; - } - try { - value = method.invoke(object, (Object[])null); - value = getPrintableValue(value); - int maxLen = (Integer) list.get(listIndex); - String header = name.substring(3); - if (listIndex == list.size() - 1) { - if (printLastColumnSpaces) { - System.out.print(StringUtil.getRightPaddedString(header, maxLen, ' ')); - } else { - System.out.print(header); - } - } else { - System.out.print(StringUtil.getRightPaddedString(header, maxLen, ' ')); - System.out.print(" "); - } - - listIndex++; - } catch (Exception ex) { - } - } - } - } - - private static void printBottomHeaders(List list, Object obj, boolean printLastColumnSpaces, - String primitiveHeader) - { - Object object = obj; - if (object == null) { - object = "null"; - } - - if (object instanceof String || object.getClass().isPrimitive() || - object.getClass() == Boolean.class || - object.getClass() == Byte.class || - object.getClass() == Character.class || - object.getClass() == Short.class || - object.getClass() == Integer.class || - object.getClass() == Long.class || - object.getClass() == Float.class || - object.getClass() == Double.class || - object.getClass().isArray() || - object instanceof Date) - { - - int maxLen = (Integer) list.get(0); - if (maxLen < primitiveHeader.length()) { - maxLen = primitiveHeader.length(); - } - if (printLastColumnSpaces) { - System.out.print(StringUtil.getRightPaddedString(StringUtil.getRightPaddedString("", primitiveHeader - .length(), '-'), maxLen, ' ')); - } else { - System.out.print(StringUtil.getRightPaddedString("", primitiveHeader.length(), '-')); - } - - } else { - - Class cls = object.getClass(); - Method methods[] = cls.getMethods(); - Method method; - Class retType; - String name; - Object value; - int listIndex = 0; - listIndex = 0; - for (int i = 0; i < methods.length; i++) { - method = methods[i]; - name = method.getName(); - if (name.length() <= 3 || name.startsWith("get") == false || name.equals("getClass")) { - continue; - } - retType = method.getReturnType(); - if (retType == Void.TYPE) { - continue; - } - try { - value = method.invoke(object, (Object[])null); - value = getPrintableValue(value); - int maxLen = (Integer) list.get(listIndex); - String header = name.substring(3); - - if (listIndex == list.size() - 1) { - if (printLastColumnSpaces) { - System.out.print(StringUtil.getRightPaddedString(StringUtil.getRightPaddedString("", header - .length(), '-'), maxLen, ' ')); - } else { - System.out.print(StringUtil.getRightPaddedString("", header.length(), '-')); - } - } else { - System.out.print(StringUtil.getRightPaddedString(StringUtil.getRightPaddedString("", header - .length(), '-'), maxLen, ' ')); - System.out.print(" "); - } - listIndex++; - } catch (Exception ex) { - } - } - } - } - -// FindBugs - private method never called -// private static void printHeaders(List keyList, List valueList, Object key, Object value, int rowMaxLen) -// throws Exception -// { -// System.out.print(StringUtil.getRightPaddedString("Row", rowMaxLen, ' ')); -// System.out.print(" "); -// printTopHeaders(keyList, key, true, "Key"); -// System.out.print(" | "); -// printTopHeaders(valueList, value, false, "Value"); -// System.out.println(); -// -// if (rowMaxLen < 3) { -// rowMaxLen = 3; -// } -// System.out.print(StringUtil.getRightPaddedString("", rowMaxLen, '-')); -// System.out.print(" "); -// printBottomHeaders(keyList, key, true, "Key"); -// System.out.print(" | "); -// printBottomHeaders(valueList, value, false, "Value"); -// System.out.println(); -// } - - /** - * Prints the SelectResults contents up to the specified rowCount. - * @param sr - * @param startRowNum - * @param rowCount - * @return The number of rows printed - */ - public static int printSelectResults(SelectResults sr, int startIndex, int startRowNum, int rowCount) - { - if (sr == null) { - System.out.println("Error: SelectResults is null"); - return 0; - } - - int endIndex = startIndex + rowCount; // exclusive - if (endIndex >= sr.size()) { - endIndex = sr.size(); - } - - if (startIndex >= endIndex) { - return 0; - } - - CollectionType type = sr.getCollectionType(); - ObjectType elementType = type.getElementType(); - int row = 1; - if (rowCount == -1) { - rowCount = sr.size(); - } - - HashSet elementNameSet = new HashSet(); - Object element = null; - boolean isStructType = false; - StructType structType = null; - Struct struct = null; - List srList = sr.asList(); - - row = startRowNum; - for (int i = startIndex; i < endIndex; i++) { - element = srList.get(i); - - if (elementType.isStructType()) { - - structType = (StructType) elementType; - struct = (Struct) element; - printStruct(row, structType, struct, 0); - System.out.println(); - - } else { - System.out.println(row + ". " + getPrintableType(element)); - printObject(null, element, 1); - System.out.println(); - } - row++; - } - System.out.println(); - for (Object elementClassName : elementNameSet) { - System.out.println("Class: " + elementClassName); - } - return endIndex - startIndex; - } - - private static int printSelectResults_iterator(SelectResults sr, int startRowNum, int rowCount) - { - if (sr == null) { - System.out.println("SelectResults is null"); - return 0; - } - - CollectionType type = sr.getCollectionType(); - ObjectType elementType = type.getElementType(); - int row = 1; - if (rowCount == -1) { - rowCount = sr.size(); - } - - HashSet elementNameSet = new HashSet(); - ArrayList maxLenList = new ArrayList(); - Object element = null; - boolean isStructType = false; - StructType structType = null; - Struct struct = null; - for (Iterator iter = sr.iterator(); iter.hasNext() && row <= rowCount;) { - element = iter.next(); - if (elementType.isStructType()) { - structType = (StructType) elementType; - struct = (Struct) element; - computeMaxLengths(maxLenList, structType, struct); - isStructType = true; - } else { - computeMaxLengths(maxLenList, element, false); - elementNameSet.add(element.getClass().getName()); - } - row++; - } - - if (element == null && struct == null) { - return 0; - } - - int rowMax = String.valueOf(startRowNum + rowCount - 1).length(); - if (rowMax < 3) { - rowMax = 3; - } - if (isStructType) { - printHeaders(maxLenList, structType, struct, rowMax); - } else { - printHeaders(maxLenList, element, rowMax); - } - - row = startRowNum; - int lastRow = startRowNum + rowCount - 1; - for (Iterator iter = sr.iterator(); iter.hasNext() && row <= lastRow;) { - element = iter.next(); - - if (elementType.isStructType()) { - - structType = (StructType) elementType; - struct = (Struct) element; - System.out.print(StringUtil.getRightPaddedString(row + "", rowMax, ' ')); - System.out.print(" "); - System.out.println(); - - } else { - - System.out.print(StringUtil.getRightPaddedString(row + "", rowMax, ' ')); - System.out.print(" "); - printObject(maxLenList, element, false); - System.out.println(); - } - row++; - } - System.out.println(); - for (Object elementClassName : elementNameSet) { - System.out.println("Class: " + elementClassName); - } - return row - 1; - } - - private static void computeMaxLengths(List list, StructType structType, Struct struct) - { - ObjectType[] fieldTypes = structType.getFieldTypes(); - String[] fieldNames = structType.getFieldNames(); - Object[] fieldValues = struct.getFieldValues(); - - int listIndex = 0; - for (int i = 0; i < fieldTypes.length; i++) { - ObjectType fieldType = fieldTypes[i]; - String fieldName = fieldNames[i]; - Object fieldValue = fieldValues[i]; - - Integer len; - if (listIndex >= list.size()) { - len = fieldName.length(); - list.add(len); - } else { - len = (Integer) list.get(listIndex); - } - if (fieldValue == null) { - if (len.intValue() < 4) { - len = 4; - } - } else { - int valueLen = fieldValue.toString().length(); - if (len.intValue() < valueLen) { - len = valueLen; - } - } - list.set(listIndex, len); - listIndex++; - } - } - - private static void computeMaxLengths(List list, Object obj, boolean isKey) - { - Object object = obj; - if (object == null) { - object = "null"; - } - - if (object instanceof String || object.getClass().isPrimitive() || - object.getClass() == Boolean.class || - object.getClass() == Byte.class || - object.getClass() == Character.class || - object.getClass() == Short.class || - object.getClass() == Integer.class || - object.getClass() == Long.class || - object.getClass() == Float.class || - object.getClass() == Double.class || - object.getClass().isArray() || - object instanceof Date) - { - if (list.size() > 0) { - int len = (Integer) list.get(0); - if (len < object.toString().length()) { - list.set(0, object.toString().length()); - } - } else { - if (isKey) { - if (object.toString().length() < 3) { // Key - list.add(3); - } else { - list.add(object.toString().length()); - } - } else { - if (object.toString().length() < 5) { // Value - list.add(5); - } else { - list.add(object.toString().length()); - } - } - } - - } else { - - Class cls = object.getClass(); - Method methods[] = cls.getMethods(); - Method method; - Class retType; - String name; - Object value; - int listIndex = 0; - for (int i = 0; i < methods.length; i++) { - method = methods[i]; - name = method.getName(); - if (name.length() <= 3 || name.startsWith("get") == false || name.equals("getClass")) { - continue; - } - retType = method.getReturnType(); - if (retType == Void.TYPE) { - continue; - } - try { - value = method.invoke(object, (Object[])null); - value = getPrintableValue(value); - Integer len; - if (listIndex >= list.size()) { - len = name.length() - 3; - list.add(len); - } else { - len = (Integer) list.get(listIndex); - } - if (value == null) { - if (len.intValue() < 4) { - len = 4; - } - } else { - int valueLen = value.toString().length(); - if (len.intValue() < valueLen) { - len = valueLen; - } - } - list.set(listIndex, len); - listIndex++; - } catch (Exception ex) { - } - } - } - } - - private static void printHeaders(List list, StructType structType, Struct struct, int rowMaxLen) - { - System.out.print(StringUtil.getRightPaddedString("Row", rowMaxLen, ' ')); - System.out.print(" "); - - ObjectType[] fieldTypes = structType.getFieldTypes(); - String[] fieldNames = structType.getFieldNames(); - Object[] fieldValues = struct.getFieldValues(); - - int listIndex = 0; - for (int i = 0; i < fieldTypes.length; i++) { - ObjectType fieldType = fieldTypes[i]; - String fieldName = fieldNames[i]; - Object fieldValue = fieldValues[i]; - fieldValue = getPrintableValue(fieldValue); - int maxLen = (Integer) list.get(listIndex); - String header = fieldName; - System.out.print(StringUtil.getRightPaddedString(header, maxLen, ' ')); - System.out.print(" "); - listIndex++; - } - System.out.println(); - System.out.print(StringUtil.getRightPaddedString("", rowMaxLen, '-')); - System.out.print(" "); - listIndex = 0; - for (int i = 0; i < fieldTypes.length; i++) { - ObjectType fieldType = fieldTypes[i]; - String fieldName = fieldNames[i]; - Object fieldValue = fieldValues[i]; - fieldValue = getPrintableValue(fieldValue); - int maxLen = (Integer) list.get(listIndex); - String header = fieldName; - System.out.print(StringUtil.getRightPaddedString(StringUtil.getRightPaddedString("", header.length(), '-'), - maxLen, ' ')); - System.out.print(" "); - listIndex++; - } - System.out.println(); - } - - private static void printHeaders(List list, Object object, int rowMaxLen) - { - System.out.print(StringUtil.getRightPaddedString("Row", rowMaxLen, ' ')); - System.out.print(" "); - printTopHeaders(list, object, false, "Value"); - System.out.println(); - - System.out.print(StringUtil.getRightPaddedString("", rowMaxLen, '-')); - System.out.print(" "); - printBottomHeaders(list, object, false, "Value"); - System.out.println(); - } - - private static String getPrintableType(Object object) - { - if (isPrintType()) { - if (object == null) { - return " (N/A)"; - } - return " (" + object.getClass().getSimpleName() + ")"; - } else { - return ""; - } - } - - private static void printStruct(int row, StructType structType, Struct struct, int level) - { - String spaces = getSpaces(level); - String spaces2 = getSpaces(level+1); - - ObjectType[] fieldTypes = structType.getFieldTypes(); - String[] fieldNames = structType.getFieldNames(); - Object[] fieldValues = struct.getFieldValues(); - - int listIndex = 0; - System.out.println(spaces + row + "."); - for (int i = 0; i < fieldTypes.length; i++) { - ObjectType fieldType = fieldTypes[i]; - String fieldName = fieldNames[i]; - Object fieldValue = fieldValues[i]; - printObject(fieldName, fieldValue, level+1); - } - } - - private static void printObject(int row, String header, Object object, boolean printRow) - { - printObject(row, header, object, printRow, 1); - } - - private static void printObject(int row, String header, Object object, boolean printRow, int level) - { - if (printRow) { - System.out.print(row + ". "); - } else { - String rowStr = Integer.toString(row); - String spaces = ""; - for (int i = 0; i < rowStr.length(); i++) { - spaces += " "; - } - System.out.print(spaces + " "); - } - if (header == null) { - System.out.print(getPrintableType(object)); - } else { - System.out.print(header + getPrintableType(object)); - } - System.out.println(); - printObject(null, object, level); - } - - private static void printObject(String name, Object obj, int level) - { - String spaces = getSpaces(level); - - Object object = obj; - if (object == null) { - object = "null"; - } - - if (object instanceof String || object.getClass().isPrimitive() || - object.getClass() == Boolean.class || - object.getClass() == Byte.class || - object.getClass() == Character.class || - object.getClass() == Short.class || - object.getClass() == Integer.class || - object.getClass() == Long.class || - object.getClass() == Float.class || - object.getClass() == Double.class || - object.getClass().isArray() || - object instanceof Date) - { - printValue(name, object, level); - - } else if (object instanceof Map) { - printMap(name, (Map)object, level); - - } else if (object instanceof Collection) { - printCollection(name, (Collection)object, level); - - } else if (object instanceof Mappable) { - printMappable(name, (Mappable)object, level); - -// } else if (object instanceof Struct) { -// printStruct(name, (Struct)object, level); - - } else { - Class cls = object.getClass(); - Method methods[] = cls.getMethods(); - Method method; - Class retType; - Object value; - int listIndex = 0; - ArrayList<String> methodList = new ArrayList(); - HashMap<String, Method> methodMap = new HashMap(); - for (int i = 0; i < methods.length; i++) { - method = methods[i]; - name = method.getName(); - if (name.length() <= 3 || name.startsWith("get") == false || name.equals("getClass")) { - continue; - } - retType = method.getReturnType(); - if (retType == Void.TYPE) { - continue; - } - String propertyName = name.substring(3); - methodMap.put(propertyName, method); - methodList.add(propertyName); - } - Collections.sort(methodList); - for (String propertyName : methodList) { - try { - method = methodMap.get(propertyName); - value = method.invoke(object, (Object[])null); - printObject(propertyName, value, level); - } catch (Exception ex) { - } - } - } - } - - public static void printList(List resultList) - { - ArrayList maxLenList = new ArrayList(); - Object nonNullObject = null; - for (int i = 0; i < resultList.size(); i++) { - Object object = resultList.get(i); - if (object != null) { - nonNullObject = object; - } - computeMaxLengths(maxLenList, object, true); // TODO: true? - } - if (nonNullObject == null) { - return; - } - - int rowMax = String.valueOf(resultList.size()).length(); - if (rowMax < 3) { - rowMax = 3; - } - printHeaders(maxLenList, nonNullObject, rowMax); - for (int i = 0; i < resultList.size(); i++) { - Object object = resultList.get(i); - System.out.print(StringUtil.getRightPaddedString((i + 1) + "", rowMax, ' ')); - System.out.print(" "); - printObject(maxLenList, object, false); - System.out.println(); - } - } - - public static int printList(List list, int startIndex, int startRowNum, int rowCount, int actualSize, List keyList) throws Exception - { - if (list == null) { - System.out.println("Error: map is null"); - return 0; - } - - HashSet objectNameSet = new HashSet(); -// HashSet valueNameSet = new HashSet(); //FindBugs - unused - Object object = null; - - int count = 0; - int row = startRowNum; - int lastRow = startRowNum + rowCount - 1; - for (Iterator itr = list.iterator(); count < rowCount && itr.hasNext(); count++) { - object = itr.next(); - objectNameSet.add(object.getClass().getName()); - printObject(row, "Object", object, true, 2); - System.out.println(); - row++; - } - System.out.println(); - System.out.println(" Fetch size: " + rowCount); - System.out.println(" Returned: " + (row-1) + "/" + actualSize); - for (Object keyName : objectNameSet) { - System.out.println(" Class: " + keyName); - } - return count; - } - - private static void computeMappableMaxLengths(List list, Mappable mappable) - { - String name; - Object value; - int listIndex = 0; - ArrayList<String> keyList = new ArrayList(mappable.getKeys()); - Collections.sort(keyList); - for (int i = 0; i < keyList.size(); i++) { - name = keyList.get(i); - value = mappable.getValue(name); - value = getPrintableValue(value); - Integer len; - if (listIndex >= list.size()) { - len = name.length(); - list.add(len); - } else { - len = (Integer) list.get(listIndex); - } - if (value == null) { - if (len.intValue() < 4) { - len = 4; - } - } else { - int valueLen = value.toString().length(); - if (len.intValue() < valueLen) { - len = valueLen; - } - } - list.set(listIndex, len); - listIndex++; - } - } - - private static void printMappableHeaders(List list, Mappable mappable, int rowMaxLen) - { - System.out.print(StringUtil.getRightPaddedString("Row", rowMaxLen, ' ')); - System.out.print(" "); - printMappableTopHeaders(list, mappable, false); - System.out.println(); - if (rowMaxLen < 3) { - rowMaxLen = 3; - } - System.out.print(StringUtil.getRightPaddedString("", rowMaxLen, '-')); - System.out.print(" "); - printMappableBottomHeaders(list, mappable, false); - System.out.println(); - } - - private static void printMappableTopHeaders(List list, Mappable mappable, - boolean printLastColumnSpaces) - { - int listIndex = 0; - ArrayList<String> keyList = new ArrayList(mappable.getKeys()); - Collections.sort(keyList); - for (int i = 0; i < keyList.size(); i++) { - String header = keyList.get(i); - int maxLen = (Integer) list.get(listIndex); - if (listIndex == list.size() - 1) { - if (printLastColumnSpaces) { - System.out.print(StringUtil.getRightPaddedString(header, maxLen, ' ')); - } else { - System.out.print(header); - } - } else { - System.out.print(StringUtil.getRightPaddedString(header, maxLen, ' ')); - System.out.print(" "); - } - - listIndex++; - } - } - - private static void printMappableBottomHeaders(List list, Mappable mappable, boolean printLastColumnSpaces) - { - int listIndex = 0; - ArrayList<String> keyList = new ArrayList(mappable.getKeys()); - Collections.sort(keyList); - for (int i = 0; i < keyList.size(); i++) { - String header = keyList.get(i); - int maxLen = (Integer) list.get(listIndex); - if (listIndex == list.size() - 1) { - if (printLastColumnSpaces) { - System.out.print(StringUtil.getRightPaddedString(StringUtil.getRightPaddedString("", header - .length(), '-'), maxLen, ' ')); - } else { - System.out.print(StringUtil.getRightPaddedString("", header.length(), '-')); - } - } else { - System.out.print(StringUtil.getRightPaddedString(StringUtil.getRightPaddedString("", header - .length(), '-'), maxLen, ' ')); - System.out.print(" "); - } - listIndex++; - } - } - - private static void printMappable(String name, Mappable mappable, int level) - { - String spaces = getSpaces(level); - int listIndex = 0; - ArrayList<String> keyList = new ArrayList(mappable.getKeys()); - Collections.sort(keyList); - for (int i = 0; i < keyList.size(); i++) { - String n = keyList.get(i); - Object value = mappable.getValue(n); - printObject(n, value, level); - } - } - - public static void printMappableList(List<Mappable> resultList) - { - for (int i = 0; i < resultList.size(); i++) { - Mappable mappable = resultList.get(i); - printObject(i+1, null, mappable, true); - System.out.println(); - } - } - - private static Object getPrintableValue(Object value) - { - if (value instanceof Byte) { - value = ((Byte) value).toString(); - } else if (value instanceof byte[]) { - value = "[B " + ((byte[])value).length; - } else if (value instanceof boolean[]) { - value = "[Z " + ((boolean[])value).length; - } else if (value instanceof short[]) { - value = "[S " + ((short[])value).length; - } else if (value instanceof int[]) { - value = "[I " + ((int[])value).length; - } else if (value instanceof long[]) { - value = "[J " + ((long[])value).length; - } else if (value instanceof float[]) { - value = "[F " + ((float[])value).length; - } else if (value instanceof double[]) { - value = "[D " + ((double[])value).length; - } -// if (value instanceof Map) { -// StringBuffer buffer = printMap(null, (Map)value, new StringBuffer("\n"), 2); -// value = buffer.toString(); -// } - return value; - } - - private static void printValue(Object name, Object value, int level) - { - String spaces = getSpaces(level); - Object printableValue = value; - if (value instanceof Byte) { - printableValue = ((Byte) value).toString(); - } else if (value instanceof byte[]) { - printableValue = "[B " + ((byte[])value).length; - } else if (value instanceof boolean[]) { - printableValue = "[Z " + ((boolean[])value).length; - } else if (value instanceof short[]) { - printableValue = "[S " + ((short[])value).length; - } else if (value instanceof int[]) { - printableValue = "[I " + ((int[])value).length; - } else if (value instanceof long[]) { - printableValue = "[J " + ((long[])value).length; - } else if (value instanceof float[]) { - printableValue = "[F " + ((float[])value).length; - } else if (value instanceof double[]) { - printableValue = "[D " + ((double[])value).length; - } - if (value instanceof Map) { - printMap(name, (Map)value, level); - } else { - if (name == null) { - System.out.println(spaces + printableValue + getPrintableType(value)); - } else { - if (name.toString().startsWith("[")) { - System.out.println(spaces + name + " " + printableValue + getPrintableType(value)); - } else { - System.out.println(spaces + name + " = " + printableValue + getPrintableType(value)); - } - } - } - } - - private static void printMap(Object name, Map map, int level) - { - String spaces = getSpaces(level); - String spaces2 = getSpaces(level+1); - - if (name == null) { - System.out.println(spaces + "size: " + map.size() + getPrintableType(map)); - } else { - System.out.println(spaces + name + " - size: " + map.size() + getPrintableType(map)); - } - - Set<Map.Entry> entrySet = map.entrySet(); - int count = 0; - for (Map.Entry entry : entrySet) { - Object key = entry.getKey(); - Object value = entry.getValue(); - if (key instanceof Map) { - printMap(null, (Map)key, level+1); - } else { - if (isPrintType()) { - if (value == null) { - System.out.println(spaces2 + key + " (" + key.getClass().getSimpleName() + ", N/A"); - } else { - System.out.println(spaces2 + key + " (" + key.getClass().getSimpleName() + ", " + value.getClass().getSimpleName() + ")"); - } - } else { - System.out.println(spaces2 + key); - } - printObject(key.toString(), value, level+2); - } - count++; - if (count >= getCollectionEntryPrintCount()) { - break; - } - } - if (count < entrySet.size()) { - System.out.println(spaces2 + "<" + (entrySet.size() - count) + " more ...>"); - } - } - - private static void printCollection(Object name, Collection col, int level) - { - String spaces = getSpaces(level); - String spaces2 = getSpaces(level+1); - -// if (name == null) { -// if (isPrintType()) { -// System.out.println(spaces + getPrintableType(map)); -// } -// } else { -// System.out.println(spaces + name + getPrintableType(map)); -// } - - if (name == null) { - System.out.println(spaces + "size: " + col.size() + getPrintableType(col)); - } else { - System.out.println(spaces + name + " - size: " + col.size() + getPrintableType(col)); - } - - - int count = 0; - for (Object value : col) { - if (col instanceof Map) { - printMap(null, (Map)value, level+1); - } else if (value instanceof Collection) { - printCollection(null, (Collection)value, level+1); - } else { - printObject("[" + count + "]", value, level+1); - } - count++; - if (count >= getCollectionEntryPrintCount()) { - break; - } - } - if (count < col.size()) { - System.out.println(spaces2 + "<" + (col.size() - count) + " more ...>"); - } - } - - private static String getSpaces(int level) - { - String spaces = ""; - for (int i = 0; i < level; i++) { - spaces += " "; - } - return spaces; - } - - private static void printObject(List list, Object obj, boolean printLastColumnSpaces) - { - Object object = obj; - if (object == null) { - object = "null"; - } - - if (object instanceof String || object.getClass().isPrimitive() || - object.getClass() == Boolean.class || - object.getClass() == Byte.class || - object.getClass() == Character.class || - object.getClass() == Short.class || - object.getClass() == Integer.class || - object.getClass() == Long.class || - object.getClass() == Float.class || - object.getClass() == Double.class || - object.getClass().isArray() || - object instanceof Date) - { - object = getPrintableValue(object); - if (list.size() > 0) { - int maxLen = (Integer) list.get(0); - if (printLastColumnSpaces) { - System.out.print(StringUtil.getRightPaddedString(object.toString(), maxLen, ' ')); - } else { - System.out.print(object.toString()); - } - } else { - System.out.print(object.toString()); - } - - } else { - - Class cls = object.getClass(); - Method methods[] = cls.getMethods(); - Method method; - Class retType; - String name; - Object value; - int listIndex = 0; - for (int i = 0; i < methods.length; i++) { - method = methods[i]; - name = method.getName(); - if (name.length() <= 3 || name.startsWith("get") == false || name.equals("getClass")) { - continue; - } - retType = method.getReturnType(); - if (retType == Void.TYPE) { - continue; - } - try { - value = method.invoke(object, (Object[])null); - value = getPrintableValue(value); - - int maxLen = (Integer) list.get(listIndex); - if (listIndex == list.size() - 1) { - if (value == null) { - if (printLastColumnSpaces) { - System.out.print(StringUtil.getRightPaddedString("null", maxLen, ' ')); - } else { - System.out.print("null"); - } - } else { - if (printLastColumnSpaces) { - System.out.print(StringUtil.getRightPaddedString(value.toString(), maxLen, ' ')); - } else { - System.out.print(value.toString()); - } - } - - } else { - if (value == null) { - System.out.print(StringUtil.getRightPaddedString("null", maxLen, ' ')); - } else { - System.out.print(StringUtil.getRightPaddedString(value.toString(), maxLen, ' ')); - } - System.out.print(" "); - } - - listIndex++; - } catch (Exception ex) { - } - } - } - } -}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/49d99d4e/gemfire-core/src/main/java/com/gemstone/gemfire/internal/tools/gfsh/command/AbstractCommandTask.java ---------------------------------------------------------------------- diff --git a/gemfire-core/src/main/java/com/gemstone/gemfire/internal/tools/gfsh/command/AbstractCommandTask.java b/gemfire-core/src/main/java/com/gemstone/gemfire/internal/tools/gfsh/command/AbstractCommandTask.java deleted file mode 100644 index 6b31b3c..0000000 --- a/gemfire-core/src/main/java/com/gemstone/gemfire/internal/tools/gfsh/command/AbstractCommandTask.java +++ /dev/null @@ -1,136 +0,0 @@ -package com.gemstone.gemfire.internal.tools.gfsh.command; - -import java.io.DataInput; -import java.io.DataOutput; -import java.io.IOException; - -import com.gemstone.gemfire.DataSerializer; -import com.gemstone.gemfire.cache.AttributesFactory; -import com.gemstone.gemfire.cache.Cache; -import com.gemstone.gemfire.cache.CacheException; -import com.gemstone.gemfire.cache.CacheFactory; -import com.gemstone.gemfire.cache.DataPolicy; -import com.gemstone.gemfire.cache.EntryEvent; -import com.gemstone.gemfire.cache.ExpirationAction; -import com.gemstone.gemfire.cache.ExpirationAttributes; -import com.gemstone.gemfire.cache.Region; -import com.gemstone.gemfire.cache.Scope; -import com.gemstone.gemfire.cache.util.CacheListenerAdapter; -import com.gemstone.gemfire.internal.tools.gfsh.util.RegionUtil; - -/** - * AbstractCommandTask provides sendResults() for sending CommandResult - * objects asynchronously. - * @author dpark - * - */ -public abstract class AbstractCommandTask implements CommandTask -{ - private static final long serialVersionUID = 1L; - - private static final String KEY_RESULTS_DEFAULT = "results"; - - private static final String REGION_NAME_ASYNC = "async"; - - // The default of 2 minute idle time allowed - private static int ASYNC_REGION_TIMEOUT = Integer.getInteger("AbstractCommandTask.ASYNC_REGION_TIMEOUT", 120); - - Region commandRegion; - - private String resultSetRegionFullPath; - - protected Region getCommandRegion() - { - return commandRegion; - } - - public void setCommandRegion(Region commandRegion) { - this.commandRegion = commandRegion; - } - - /** - * Sets the region in which the results to be sent. This is - * invoked by CommandServerManager. Do not invoke it directly. - * @param resultSetRegionFullPath - */ - /*protected*/public void setResultSetRegionPath(String resultSetRegionFullPath) - { - this.resultSetRegionFullPath = resultSetRegionFullPath; - } - - /** - * Returns the region used to keep track of asynchronous regions. - * The command client is allowed to supply an optional inbox region - * with which it may receive results. The server removes these inbox - * regions if they have idle for more that ASYNC_REGION_TIMEOUT. - * @return the region used to keep track of asynchronous regions - */ - private Region getAsyncRegion() - { - Region asyncRegion = getCommandRegion().getSubregion(REGION_NAME_ASYNC); - if (asyncRegion == null) { - AttributesFactory factory = new AttributesFactory(); - factory.setStatisticsEnabled(true); - factory.setScope(Scope.LOCAL); - factory.setDataPolicy(DataPolicy.NORMAL); - factory.setEntryIdleTimeout(new ExpirationAttributes(ASYNC_REGION_TIMEOUT, ExpirationAction.LOCAL_DESTROY)); - factory.addCacheListener(new CacheListenerAdapter() { - public void afterDestroy(EntryEvent event) - { - String regionPath = (String)event.getKey(); - getCommandRegion().getSubregion(regionPath).destroyRegion(); - } - }); - try { - asyncRegion = getCommandRegion().createSubregion(REGION_NAME_ASYNC, factory.create()); - } catch (Exception ex) { - // in case another thread created it - asyncRegion = getCommandRegion().getSubregion(REGION_NAME_ASYNC); - } - } - return asyncRegion; - } - - /** - * Sends the specified results to the client's private inbox region. - * The inbox region is a sub-region of the command region. Invoke - * this method if the results are too large to send synchronously. - * The client must supply a listener using - * CommandClient.addCommandResultsListener() in order to receive - * the results. - * @param results The results to send to the client. - */ - protected void sendResults(CommandResults results) - { - try { - Region resultSetRegion = RegionUtil.getRegion(resultSetRegionFullPath, Scope.LOCAL, DataPolicy.EMPTY, null); - resultSetRegion.put(KEY_RESULTS_DEFAULT, results); - Region asyncRegion = getAsyncRegion(); - asyncRegion.put(resultSetRegion.getName(), true); - } catch (CacheException ex) { - Cache cache = CacheFactory.getAnyInstance(); - cache.getLogger().error(ex); - } - } - - public void fromData(DataInput input) throws IOException, ClassNotFoundException - { - resultSetRegionFullPath = DataSerializer.readString(input); - } - - public void toData(DataOutput output) throws IOException - { - DataSerializer.writeString(resultSetRegionFullPath, output); - } - - - /** - * Runs this task. A client executes CommandTak by calling - * CommandClient.execute(CommandTask task). - * @param userData The userData optionally provided by the cache server. The - * cache server may pass any user data to the command task. - * @return Returns the task results. - */ - public abstract CommandResults runTask(Object userData); - -} http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/49d99d4e/gemfire-core/src/main/java/com/gemstone/gemfire/internal/tools/gfsh/command/CommandResults.java ---------------------------------------------------------------------- diff --git a/gemfire-core/src/main/java/com/gemstone/gemfire/internal/tools/gfsh/command/CommandResults.java b/gemfire-core/src/main/java/com/gemstone/gemfire/internal/tools/gfsh/command/CommandResults.java deleted file mode 100644 index 1406580..0000000 --- a/gemfire-core/src/main/java/com/gemstone/gemfire/internal/tools/gfsh/command/CommandResults.java +++ /dev/null @@ -1,119 +0,0 @@ -package com.gemstone.gemfire.internal.tools.gfsh.command; - -import java.io.DataInput; -import java.io.DataOutput; -import java.io.IOException; - -import com.gemstone.gemfire.DataSerializable; -import com.gemstone.gemfire.DataSerializer; - -/** - * CommandResults contains the results obtained from executing a CommandTask. It - * may also contain error code and/or exception generated by the server. - * - * @author dpark - * - */ -public class CommandResults implements DataSerializable { - private static final long serialVersionUID = 1L; - - public static final byte CODE_NORMAL = 0; - public static final byte CODE_ERROR = -1; - - private Object key; - private Object dataObject; - private byte code = CODE_NORMAL; - private String codeMessage; - // Will need to make it simpler for supporting catching native clients - // exception - private String exception; - - /** - * Creates a new CommandResults. CommandResults.setDataObject() to set the - * data object that contains the task results. - */ - public CommandResults() { - } - - /** - * Creates a new CommandResults object with the data object contains - * results. - * - * @param dataObject - * The data object that contains the task results. - */ - public CommandResults(Object dataObject) { - this.dataObject = dataObject; - } - - /** - * Returns the results set by CommandTask. - */ - public Object getDataObject() { - return dataObject; - } - - /** - * Returns the code set by the CommandTask. It is typically used for sending - * error code. The default value is 0. - * - * @return code - *///FIXME: java docs @return - public byte getCode() { - return code; - } - - public void setCode(byte code) { - this.code = code; - } - - /** - * Returns the message associated with the code. The default value is null. - */ - public String getCodeMessage() { - return codeMessage; - } - - public void setCodeMessage(String codeMessage) { - this.codeMessage = codeMessage; - } - - public void setKey(Object key) { - this.key = key; - } - - public Object getKey() { - return key; - } - - /** - * Returns the server exception if any. - */ - public Throwable getException() { - return new Throwable(exception); - } - - public void setException(Throwable exception) { - this.exception = exception.getMessage(); - } - - public void setDataObject(Object dataObject) { - this.dataObject = dataObject; - } - - public void toData(DataOutput out) throws IOException { - out.writeByte(code); - DataSerializer.writeObject(codeMessage, out); - DataSerializer.writeObject(dataObject, out); - DataSerializer.writeObject(exception, out); - } - - public void fromData(DataInput in) throws IOException, - ClassNotFoundException { - code = in.readByte(); - codeMessage = (String)DataSerializer.readObject(in); - dataObject = DataSerializer.readObject(in); - exception = (String)DataSerializer.readObject(in); - } - -} http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/49d99d4e/gemfire-core/src/main/java/com/gemstone/gemfire/internal/tools/gfsh/command/CommandTask.java ---------------------------------------------------------------------- diff --git a/gemfire-core/src/main/java/com/gemstone/gemfire/internal/tools/gfsh/command/CommandTask.java b/gemfire-core/src/main/java/com/gemstone/gemfire/internal/tools/gfsh/command/CommandTask.java deleted file mode 100644 index c942faf..0000000 --- a/gemfire-core/src/main/java/com/gemstone/gemfire/internal/tools/gfsh/command/CommandTask.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.gemstone.gemfire.internal.tools.gfsh.command; - -import com.gemstone.gemfire.DataSerializable; - -/** - * CommandTask is an interface that must be implemented for executing - * command task. The server invokes CommandTask.runTask() and returns - * its results to the client. - * @author dpark - * - */ -public interface CommandTask extends DataSerializable -{ - /** - * Runs this task. A client executes CommandTak by calling - * CommandClient.execute(CommandTask task). - * @param userData The userData optionally provided by the cache server. The - * cache server may pass any user data to the command task. - * @return Returns the task results. - */ - public CommandResults runTask(Object userData); - -} http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/49d99d4e/gemfire-core/src/main/java/com/gemstone/gemfire/internal/tools/gfsh/util/RegionUtil.java ---------------------------------------------------------------------- diff --git a/gemfire-core/src/main/java/com/gemstone/gemfire/internal/tools/gfsh/util/RegionUtil.java b/gemfire-core/src/main/java/com/gemstone/gemfire/internal/tools/gfsh/util/RegionUtil.java deleted file mode 100644 index 5dd89d9..0000000 --- a/gemfire-core/src/main/java/com/gemstone/gemfire/internal/tools/gfsh/util/RegionUtil.java +++ /dev/null @@ -1,829 +0,0 @@ -package com.gemstone.gemfire.internal.tools.gfsh.util; - -import java.io.File; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; -import java.util.Properties; -import java.util.Set; -import java.util.StringTokenizer; - -import com.gemstone.gemfire.admin.AdminDistributedSystem; -import com.gemstone.gemfire.admin.AdminDistributedSystemFactory; -import com.gemstone.gemfire.admin.AdminException; -import com.gemstone.gemfire.admin.CacheVm; -import com.gemstone.gemfire.admin.DistributedSystemConfig; -import com.gemstone.gemfire.admin.SystemMember; -import com.gemstone.gemfire.admin.SystemMemberCache; -import com.gemstone.gemfire.admin.SystemMemberRegion; -import com.gemstone.gemfire.admin.internal.AdminDistributedSystemImpl; -import com.gemstone.gemfire.cache.AttributesFactory; -import com.gemstone.gemfire.cache.Cache; -import com.gemstone.gemfire.cache.CacheClosedException; -import com.gemstone.gemfire.cache.CacheException; -import com.gemstone.gemfire.cache.CacheFactory; -import com.gemstone.gemfire.cache.CacheListener; -import com.gemstone.gemfire.cache.DataPolicy; -import com.gemstone.gemfire.cache.EntryNotFoundException; -import com.gemstone.gemfire.cache.EvictionAttributes; -import com.gemstone.gemfire.cache.MirrorType; -import com.gemstone.gemfire.cache.Region; -import com.gemstone.gemfire.cache.RegionAttributes; -import com.gemstone.gemfire.cache.Scope; -import com.gemstone.gemfire.cache.client.Pool; -import com.gemstone.gemfire.cache.util.BridgeClient; -import com.gemstone.gemfire.cache.util.BridgeLoader; -import com.gemstone.gemfire.cache.util.BridgeWriter; -import com.gemstone.gemfire.distributed.DistributedSystem; - - -/** - * <p>Copyright: Copyright (c) 2005</p> - * <p>Company: GemStone Systems, Inc.</p> - * @author Dae Song Park - * @version 1.0 - */ -public class RegionUtil -{ - /** - * Creates a subregion of the specified parentRegion. - * @param parentRegion The parent region. If null, it creates a top-level - * region. - * @param regionName The subregion name - * @param scope The scope - * @param dataPolicy The data policy - * @param listener The cache listener - * @throws OrderManagerException Thrown if it is unable to create the region. - */ - public static Region createRegion(Region parentRegion, String regionName, Scope scope, - DataPolicy dataPolicy, CacheListener listener) - throws CacheException - { - return createRegion(parentRegion, regionName, scope, dataPolicy, listener, null, null); - } - - public static Region createRegion(Region parentRegion, String regionName, Scope scope, - DataPolicy dataPolicy, CacheListener listener, - File[] persistenceDirs, EvictionAttributes evictionAttributes) - throws CacheException - { - return createRegion(parentRegion, regionName, scope, dataPolicy, listener, persistenceDirs, evictionAttributes, null); - } - - public static Region createRegion(Region parentRegion, String regionName, Scope scope, - DataPolicy dataPolicy, CacheListener listener, - File[] persistenceDirs, EvictionAttributes evictionAttributes, String endpoints) - throws CacheException - { - Region region = parentRegion.getSubregion(regionName); - if (region != null) { - return region; - } - AttributesFactory factory = new AttributesFactory(); - - factory.setScope(scope); - factory.setDataPolicy(dataPolicy); - if (listener != null) { - factory.addCacheListener(listener); - } - - if (persistenceDirs != null) { - factory.setDiskDirs(persistenceDirs); - } - - factory.setEvictionAttributes(evictionAttributes); - - if (endpoints != null) { - BridgeWriter bridgeWriter = new BridgeWriter(); - Properties prop = new Properties(); - prop.setProperty("endpoints", endpoints); - prop.setProperty("establishCallbackConnection", "true"); - bridgeWriter.init(prop); - factory.setCacheWriter(bridgeWriter); - - BridgeLoader bridgeLoader = new BridgeLoader(); - prop = new Properties(); - prop.setProperty("endpoints", endpoints); - bridgeLoader.init(prop); - factory.setCacheLoader(bridgeLoader); - } - - RegionAttributes attr = factory.create(); - - return parentRegion.createSubregion(regionName, attr); - } - - public static Region createVMRegion(Cache cache, String regionName, Scope scope, - DataPolicy dataPolicy, CacheListener listener) - throws CacheException - { - AttributesFactory factory = new AttributesFactory(); - - factory.setScope(scope); - factory.setDataPolicy(dataPolicy); - if (listener != null) { - factory.addCacheListener(listener); - } - - RegionAttributes attr = factory.create(); - - return cache.createRegion(regionName, attr); - } - - /** - * Returns the parent region of the specified path. - * @param regionPath The region path. - * @return the parent region of the specified path. - */ - public static Region getParentRegion(String regionPath) - { - if (regionPath == null) { - return null; - } - - Cache cache = CacheFactory.getAnyInstance(); - String split[]; - if (regionPath.startsWith("/")) { - split = regionPath.substring(1).split("/"); - } else { - split = regionPath.split("/"); - } - if (split.length == 0) { - return null; - } - Region region = cache.getRegion(split[0]); - if (region != null) { - int i; - for (i = 1; i < split.length; i++) { - Region subregion = region.getSubregion(split[i]); - if (subregion == null) { - break; - } - region = subregion; - } - if (i != split.length - 1) { - region = null; - } - } - return region; - } - - /** - * Returns the last region - * @param regionPath - * @return the last region - */ - public static Region getLastRegionInPath(String regionPath) - { - if (regionPath == null) { - return null; - } - - Cache cache = CacheFactory.getAnyInstance(); - String split[] = regionPath.split("/"); - if (split.length == 0) { - return null; - } - - Region region = cache.getRegion(split[0]); - if (region != null) { - for (int i = 1; i < split.length; i++) { - Region subregion = region.getSubregion(split[i]); - if (subregion == null) { - break; - } - region = subregion; - } - } - return region; - } - - /** - * Returns the specified region. It creates one if it does not exist. - * @param regionPath - * @param scope - * @param mirrorType - * @param endpoints - * @return Returns the specified region. It creates one if it does not exist. - * @deprecated Use #getRegion(String regionPath, Scope scope, DataPolicy dataPolicy, String endpoints) instead - */ - public static Region getRegion(String regionPath, Scope scope, MirrorType mirrorType, String endpoints) - { - DataPolicy dataPolicy; - if (mirrorType == MirrorType.KEYS || mirrorType == MirrorType.KEYS_VALUES) { - dataPolicy = DataPolicy.REPLICATE; - } else if (mirrorType == MirrorType.NONE) { - dataPolicy = DataPolicy.NORMAL; - } else { - dataPolicy = DataPolicy.DEFAULT; - } - return getRegion(regionPath, scope, dataPolicy, endpoints); - } - - // nk94960 - public static Region getRegion(String regionPath, Scope scope, DataPolicy dataPolicy, String endpoints) - throws CacheException - { - return getRegion(regionPath, scope, dataPolicy, endpoints, false, null); - } - - //nk94960 - public static Region getRegion(String regionPath, Scope scope, DataPolicy dataPolicy, String endpoints, boolean enableBridgeConflation) - throws CacheException - { - return getRegion(regionPath, scope, dataPolicy, endpoints, enableBridgeConflation, null); - - } - - /** - * Returns the region specified. It creates a new region if it does not - * exist. - * - * The following system properties are used to create BridgeLoader and - * BridgeWriter for the region if endpoints is specified (i.e., if enpoints - * is not null.) - * <p> - * <li>readTimeout (optional: default 10000)</li> - * <li>allowableServerTimeouts (optional: default 7 timeouts)</li> - * <li>allowableServerTimeoutPeriod (optional: default: 10000 milliseconds)</li> - * <li>retryAttempts (optional: default 5)</li> - * <li>retryInterval (optional: default 10000)</li> - * <li>LBPolicy (optional: default "Sticky")</li> - * <li>connectionsPerServer (optional: default 2)</li> - * <li>socketBufferSize (optional: default 32768)</li> - * <p> - * - * @param regionPath - * @param scope - * @param dataPolicy - * @param endpoints - * @param enableBridgeConflation - * @return the region specified - * @throws CacheException - */ - public static Region getRegion(String regionPath, Scope scope, DataPolicy dataPolicy, String endpoints, boolean enableBridgeConflation, String diskDir) //nk94960 - throws CacheException - { - Cache cache = null; - Region region = null; - - try { - cache = CacheFactory.getAnyInstance(); - region = cache.getRegion(regionPath); - - if (region != null) { - return region; - } - } catch (CacheClosedException ex) { - Properties props = new Properties(); - DistributedSystem system = DistributedSystem.connect(props); - cache = CacheFactory.create(system); - } - - // Parse region path - StringTokenizer st = new StringTokenizer(regionPath, "/"); - String regionName; - int index = 0; - int count = st.countTokens(); - AttributesFactory factory = new AttributesFactory(); - factory.setDataPolicy(DataPolicy.NORMAL); - - while (st.hasMoreTokens()) { - regionName = st.nextToken(); - index++; - - if (index == count) { - factory.setDataPolicy(dataPolicy); - - if (endpoints != null) { - String establishCallbackConnection = System.getProperty("establishCallbackConnection", "true"); - Long readTimeout = Long.getLong("readTimeout", 10000); - Integer allowableServerTimeouts = Integer.getInteger("allowableServerTimeouts", 7); - Long allowableServerTimeoutPeriod = Long.getLong("allowableServerTimeoutPeriod ", 10000); - Integer retryAttempts = Integer.getInteger("retryAttempts", 5); - Long retryInterval = Long.getLong("retryInterval", 10000); - String lbPolicy = System.getProperty("LBPolicy", "Sticky"); - Integer connectionsPerServer = Integer.getInteger("connectionsPerServer", 2); - Integer socketBufferSize = Integer.getInteger("socketBufferSize ", 32768); - BridgeClient bridgeClient = new BridgeClient(); - Properties prop = new Properties(); - prop.setProperty("endpoints", endpoints); - prop.setProperty("establishCallbackConnection", establishCallbackConnection); - prop.setProperty("readTimeout", readTimeout.toString()); - prop.setProperty("allowableServerTimeouts", allowableServerTimeouts.toString()); - prop.setProperty("allowableServerTimeoutPeriod ", allowableServerTimeoutPeriod.toString()); - prop.setProperty("retryAttempts", retryAttempts.toString()); - prop.setProperty("retryInterval", retryInterval.toString()); - prop.setProperty("LBPolicy", lbPolicy); - prop.setProperty("connectionsPerServer", connectionsPerServer.toString()); - prop.setProperty("socketBufferSize", socketBufferSize.toString()); - bridgeClient.init(prop); - factory.setCacheLoader(bridgeClient); - } else { - factory.setEnableBridgeConflation(enableBridgeConflation); - factory.setEnableAsyncConflation(enableBridgeConflation); - } - } - - if (index == 1) { - region = cache.getRegion(regionName); - - if (region == null) { - factory.setScope(scope); - //nk94960 - if(diskDir != null){ - File[] dirs = new File[1]; - dirs[0] = new File(diskDir); - - factory.setDiskDirs(dirs); - } - region = cache.createRegion(regionName, factory.create()); - } - } else { - Region subregion = region.getSubregion(regionName); - if (subregion == null) { - factory.setScope(scope); - //nk94960 - if(diskDir != null){ - File[] dirs = new File[1]; - dirs[0] = new File(diskDir); - - factory.setDiskDirs(dirs); - } - subregion = region.createSubregion(regionName, factory.create()); - } - - region = subregion; - } - } - - return region; - } - - public static Region getRegion(String regionPath, DataPolicy dataPolicy) - throws CacheException - { - return getRegion(regionPath, Scope.DISTRIBUTED_NO_ACK, dataPolicy, null); - } - - public static Region getRegion(String regionPath) throws CacheException - { - return getRegion(regionPath, Scope.DISTRIBUTED_NO_ACK, DataPolicy.NORMAL, null); - } - - public static Region getRegion(String regionPath, Scope scope, DataPolicy dataPolicy, Pool pool, - boolean enableBridgeConflation) throws CacheException - { - Cache cache = null; - Region region = null; - - try { - cache = CacheFactory.getAnyInstance(); - region = cache.getRegion(regionPath); - - if (region != null) { - return region; - } - } catch (CacheClosedException ex) { - Properties props = new Properties(); - DistributedSystem system = DistributedSystem.connect(props); - cache = CacheFactory.create(system); - } - - // Parse region path - StringTokenizer st = new StringTokenizer(regionPath, "/"); - String regionName; - int index = 0; - int count = st.countTokens(); - AttributesFactory factory = new AttributesFactory(); - factory.setDataPolicy(DataPolicy.NORMAL); - - while (st.hasMoreTokens()) { - regionName = st.nextToken(); - index++; - - if (index == count) { - factory.setDataPolicy(dataPolicy); - factory.setPoolName(pool.getName()); - } - - if (index == 1) { - region = cache.getRegion(regionName); - - if (region == null) { - factory.setScope(scope); - region = cache.createRegion(regionName, factory.create()); - } - } else { - Region subregion = region.getSubregion(regionName); - if (subregion == null) { - factory.setScope(scope); - subregion = region.createSubregion(regionName, factory.create()); - } - - region = subregion; - } - } - - return region; - } - - /** - * Returns a sorted list of all region full paths found in the specified - * distributed system. - * @param ds The distributed system to search. - * @return Returns a sorted list of all region paths defined in the - * distributed system. - */ - public static List getAllRegionPathListInDistributedSystem(DistributedSystem ds, boolean recursive) - { - List list = new ArrayList(); - try { - // members - AdminDistributedSystem adminSystem = getAdminDistributedSystemConnected(ds); - SystemMember[] members = adminSystem.getSystemMemberApplications(); - for (int i = 0; i < members.length; i++) { - SystemMemberCache cache = members[i].getCache(); - - if (cache != null) { - list = getRegionPaths(cache, list, recursive); - } - } - - // cache servers - CacheVm[] vms = adminSystem.getCacheVms(); - for (int i = 0; i < vms.length; i++) { - SystemMemberCache cache = vms[i].getCache(); - if (cache != null) { - list = getRegionPaths(cache, list, recursive); - } - } - } catch (Exception e) { - e.printStackTrace(); - } - - Collections.sort(list); - return list; - } - - /** - * Returns a sorted String array of all region full paths found in the specified - * distributed system. - * @param ds The distributed system to search. - * @return Returns a String array of all region paths defined in the - * distributed system. - */ - public static String[] getAllRegionPathsInDistributedSystem(DistributedSystem ds, boolean recursive) - { - List list = getAllRegionPathListInDistributedSystem(ds, recursive); - return (String[])list.toArray(new String[0]); - } - - public static List getRegionPathList(SystemMemberCache cache, boolean recursive) - throws Exception - { - return getRegionPaths(cache, new ArrayList(), recursive); - } - - public static String[] getRegionPaths(SystemMemberCache cache, boolean recursive) - throws Exception - { - List list = getRegionPathList(cache, recursive); - return (String[])list.toArray(new String[0]); - } - - private static List getRegionPaths(SystemMemberCache cache, List list, boolean recursive) - throws Exception - { - // get a list of all root regions - Set regions = cache.getRootRegionNames(); - Iterator itor = regions.iterator(); - - while (itor.hasNext()) { - String regionPath = "/" + itor.next().toString(); - - SystemMemberRegion systemMemberRegion = cache.getRegion(regionPath); - if (list.contains(regionPath) == false) { - list.add(regionPath); - } - if (recursive && systemMemberRegion.getSubregionCount() > 0) { - getRegionPaths(systemMemberRegion, cache, list); - } - } - return list; - } - - private static List getRegionPaths(SystemMemberRegion systemMemberRegion, SystemMemberCache cache, List list, boolean recursive) throws Exception - { - // get a list of all root regions - Set regionNames = systemMemberRegion.getSubregionNames(); - list.addAll(regionNames); - - Iterator itor = regionNames.iterator(); - while (itor.hasNext()) { - String regionPath = (String)itor.next(); - if (list.contains(regionPath) == false) { - list.add(regionPath); - } - SystemMemberRegion subregion = cache.getRegion(regionPath); - if (recursive && subregion != null && subregion.getSubregionCount() > 0) { - list = getRegionPaths(subregion, cache, list, recursive); - } - } - return list; - } - - private static List getRegionPaths(SystemMemberRegion systemMemberRegion, SystemMemberCache cache, List list) - throws Exception - { - // get a list of all subregions - Set subregions = systemMemberRegion.getSubregionFullPaths(); - Iterator itor = subregions.iterator(); - - while (itor.hasNext()) { - String regionPath = itor.next().toString(); - if (list.contains(regionPath) == false) { - list.add(regionPath); - } - - SystemMemberRegion subregion = cache.getRegion(regionPath); - - if (subregion != null && subregion.getSubregionCount() > 0) { - getRegionPaths(subregion, cache, list); - } - } - return list; - } - - public static List getAllRegionPathList(Cache cache) - { - return getAllRegionPathList(cache, true); - } - - /** - * Returns a sorted list of all region full paths found in the specified - * cache. - * @param cache The cache to search. - * @return Returns a sorted list of all region paths defined in the - * distributed system. - */ - public static List getAllRegionPathList(Cache cache, boolean recursive) - { - ArrayList list = new ArrayList(); - if (cache == null) { - return list; - } - - // get a list of all root regions - Set regions = cache.rootRegions(); - Iterator itor = regions.iterator(); - - while (itor.hasNext()) { - String regionPath = ((Region)itor.next()).getFullPath(); - - Region region = cache.getRegion(regionPath); - list.add(regionPath); - Set subregionSet = region.subregions(true); - if (recursive) { - for (Iterator subIter = subregionSet.iterator(); subIter.hasNext(); ){ - list.add(((Region)subIter.next()).getFullPath()); - } - } - } - Collections.sort(list); - return list; - } - - public static String[] getAllRegionPaths(Cache cache) - { - return getAllRegionPaths(cache, true); - } - - /** - * Returns a sorted String array of all region full paths found in the specified - * cache. - * @param cache The cache to search. - * @return Returns a sorted String array of all region paths defined in the - * distributed system. - */ - public static String[] getAllRegionPaths(Cache cache, boolean recursive) - { - List list = getAllRegionPathList(cache, recursive); - return (String[])list.toArray(new String[0]); - } - - public static List getAllRegionPathList(Region region, boolean recursive) - { - List list = new ArrayList(); - if (region == null) { - return list; - } - - Set subregionSet = region.subregions(true); - if (recursive) { - for (Iterator subIter = subregionSet.iterator(); subIter.hasNext(); ){ - list.add(((Region)subIter.next()).getFullPath()); - } - } - - Collections.sort(list); - return list; - } - - public static String[] getAllRegionPaths(Region region, boolean recursive) - { - List list = getAllRegionPathList(region, recursive); - return (String[])list.toArray(new String[0]); - } - - public static List getAllRegionPathListInDistributedSystem(Region region, boolean recursive) - { - DistributedSystem ds = region.getCache().getDistributedSystem(); - String regionPath = region.getFullPath(); - List list = new ArrayList(); - try { - AdminDistributedSystem adminSystem = getAdminDistributedSystemConnected(ds); - SystemMember[] members = adminSystem.getSystemMemberApplications(); - - for (int i = 0; i < members.length; i++) { - SystemMemberCache cache = members[i].getCache(); - - if (cache != null) { - SystemMemberRegion sregion = cache.getRegion(regionPath); - list = getRegionPaths(sregion, cache, list, recursive); - } - } - } catch (Exception e) { - e.printStackTrace(); - } - - Collections.sort(list); - return list; - } - - /* - * Returns a sorted String array of all region full paths found in the specified - * distributed system. - * @param ds The distributed system to search. - * @return Returns a String array of all region paths defined in the - * distributed system. - *///FIXME: Java Docs needs serious fixing. - public static String[] getAllRegionPathsInDistributedSystem(Region region, boolean recursive) - { - List list = getAllRegionPathListInDistributedSystem(region, recursive); - return (String[])list.toArray(new String[0]); - } - - public static AdminDistributedSystem getAdminDistributedSystemConnected(DistributedSystem ds) throws AdminException - { - AdminDistributedSystem adminSystem = AdminDistributedSystemImpl.getConnectedInstance(); - if (adminSystem == null) { - DistributedSystemConfig config = AdminDistributedSystemFactory.defineDistributedSystem(ds, null); - adminSystem = AdminDistributedSystemFactory.getDistributedSystem(config); - } - - try { - if (adminSystem.isConnected() == false) { - adminSystem.connect(); - } - } catch (Exception ex) { - // ignore - } - return adminSystem; - } - - - /** - * Creates the entire regions found in the distributed system. - * @param ds - * @param scope - */ - public static void createAllRegionsInDistributedSystem(DistributedSystem ds, Scope scope) - { - try { - AdminDistributedSystem adminSystem = getAdminDistributedSystemConnected(ds); - SystemMember[] members = adminSystem.getSystemMemberApplications(); - - for (int i = 0; i < members.length; i++) { - SystemMemberCache cache = members[i].getCache(); - - if (cache != null) { - createCache(cache, scope); - } - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - public static void createAllRegionsInCacheServers(DistributedSystem ds, Scope scope) - { - try { - AdminDistributedSystem adminSystem = getAdminDistributedSystemConnected(ds); - CacheVm[] cacheVms = adminSystem.getCacheVms(); - - for (int i = 0; i < cacheVms.length; i++) { - SystemMemberCache cache = cacheVms[i].getCache(); - - if (cache != null) { - createCache(cache, scope); - } - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - private static void createCache(SystemMemberCache cache, Scope scope) - throws Exception - { - // get a list of all root regions - Set regions = cache.getRootRegionNames(); - Iterator itor = regions.iterator(); - Scope regionScope; - - while (itor.hasNext()) { - String regionName = itor.next().toString(); - - SystemMemberRegion systemMemberRegion = cache.getRegion(regionName); - - if (scope == null) { - regionScope = systemMemberRegion.getScope(); - } else { - regionScope = scope; - } - - Region region = getRegion(systemMemberRegion.getFullPath(), regionScope, DataPolicy.NORMAL, null); - - if (systemMemberRegion.getSubregionCount() > 0) { - createRegion(region, systemMemberRegion, cache, scope); - } - } - } - - private static void createRegion(Region region, SystemMemberRegion systemMemberRegion, - SystemMemberCache cache, Scope scope) - throws Exception - { - // get a list of all subregions - Set subregions = systemMemberRegion.getSubregionFullPaths(); - Iterator itor = subregions.iterator(); - - while (itor.hasNext()) { - String regionName = itor.next().toString(); - - SystemMemberRegion subregion = cache.getRegion(regionName); - region = getRegion(systemMemberRegion.getFullPath(), scope, DataPolicy.NORMAL, null); - - if (subregion.getSubregionCount() > 0) { - createRegion(region, subregion, cache, scope); - } - } - } - - /** - * Locally clears the specified region. - * @param region The region to be cleared. - * @throws CacheException Thrown if it encounters a cache error. - */ - public final static void clearLocalRegion(Region region) throws CacheException - { - if (region == null) { - return; - } - for (Iterator iterator = region.keySet().iterator(); iterator.hasNext();) { - try { - region.localDestroy(iterator.next()); - } catch (EntryNotFoundException ex) { - // ignore all exceptions, especially, EntryNotFoundException - } - } - } - - /** - * Clears the distributed region. - * @param region The region to be cleared. - * @throws CacheException - */ - public final static void clearRegion(Region region) throws CacheException - { - if (region == null) { - return; - } - - region.clear(); - } - - public static Region<?,?> getLocalRegion(String regionPath){ - Region<?,?> region = null; - try{ - Cache cache = CacheFactory.getAnyInstance(); - region = cache.getRegion(regionPath); - }catch(CacheClosedException cce){ - region = null; - } - return region; - } - -} http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/49d99d4e/gemfire-core/src/test/java/com/gemstone/gemfire/internal/cache/ClientServerGetAllDUnitTest.java ---------------------------------------------------------------------- diff --git a/gemfire-core/src/test/java/com/gemstone/gemfire/internal/cache/ClientServerGetAllDUnitTest.java b/gemfire-core/src/test/java/com/gemstone/gemfire/internal/cache/ClientServerGetAllDUnitTest.java index 5215c90..5a9cd77 100755 --- a/gemfire-core/src/test/java/com/gemstone/gemfire/internal/cache/ClientServerGetAllDUnitTest.java +++ b/gemfire-core/src/test/java/com/gemstone/gemfire/internal/cache/ClientServerGetAllDUnitTest.java @@ -13,7 +13,6 @@ import com.gemstone.gemfire.internal.AvailablePort; import com.gemstone.gemfire.internal.AvailablePortHelper; import com.gemstone.gemfire.internal.cache.PartitionedRegion; import com.gemstone.gemfire.internal.offheap.SimpleMemoryAllocatorImpl; -import com.gemstone.gemfire.internal.tools.gfsh.app.commands.key; import com.gemstone.gemfire.cache30.BridgeTestCase; import com.gemstone.gemfire.cache30.CacheSerializableRunnable; import com.gemstone.gemfire.cache.client.*;
