target
stringlengths 20
113k
| src_fm
stringlengths 11
86.3k
| src_fm_fc
stringlengths 21
86.4k
| src_fm_fc_co
stringlengths 30
86.4k
| src_fm_fc_ms
stringlengths 42
86.8k
| src_fm_fc_ms_ff
stringlengths 43
86.8k
|
---|---|---|---|---|---|
@Test public void testMakeKey_KeyKindIdKey() { assertEquals( Key.newBuilder() .addPath(GRANDPARENT.getPath(0)) .addPath(Key.PathElement.newBuilder().setKind("Parent").setId(23L)) .addPath(CHILD.getPath(0)) .build(), makeKey(GRANDPARENT, "Parent", 23, CHILD).build()); } | public static Key.Builder makeKey(Object... elements) { Key.Builder key = Key.newBuilder(); PartitionId partitionId = null; for (int pathIndex = 0; pathIndex < elements.length; pathIndex += 2) { PathElement.Builder pathElement = PathElement.newBuilder(); Object element = elements[pathIndex]; if (element instanceof Key) { Key subKey = (Key) element; if (partitionId == null) { partitionId = subKey.getPartitionId(); } else if (!partitionId.equals(subKey.getPartitionId())) { throw new IllegalArgumentException("Partition IDs did not match, found: " + partitionId + " and " + subKey.getPartitionId()); } key.addAllPath(((Key) element).getPathList()); pathIndex--; } else { String kind; try { kind = (String) element; } catch (ClassCastException e) { throw new IllegalArgumentException("Expected string or Key, got: " + element.getClass()); } pathElement.setKind(kind); if (pathIndex + 1 < elements.length) { Object value = elements[pathIndex + 1]; if (value instanceof String) { pathElement.setName((String) value); } else if (value instanceof Long) { pathElement.setId((Long) value); } else if (value instanceof Integer) { pathElement.setId((Integer) value); } else if (value instanceof Short) { pathElement.setId((Short) value); } else { throw new IllegalArgumentException( "Expected string or integer, got: " + value.getClass()); } } key.addPath(pathElement); } } if (partitionId != null && !partitionId.equals(PartitionId.getDefaultInstance())) { key.setPartitionId(partitionId); } return key; } | DatastoreHelper { public static Key.Builder makeKey(Object... elements) { Key.Builder key = Key.newBuilder(); PartitionId partitionId = null; for (int pathIndex = 0; pathIndex < elements.length; pathIndex += 2) { PathElement.Builder pathElement = PathElement.newBuilder(); Object element = elements[pathIndex]; if (element instanceof Key) { Key subKey = (Key) element; if (partitionId == null) { partitionId = subKey.getPartitionId(); } else if (!partitionId.equals(subKey.getPartitionId())) { throw new IllegalArgumentException("Partition IDs did not match, found: " + partitionId + " and " + subKey.getPartitionId()); } key.addAllPath(((Key) element).getPathList()); pathIndex--; } else { String kind; try { kind = (String) element; } catch (ClassCastException e) { throw new IllegalArgumentException("Expected string or Key, got: " + element.getClass()); } pathElement.setKind(kind); if (pathIndex + 1 < elements.length) { Object value = elements[pathIndex + 1]; if (value instanceof String) { pathElement.setName((String) value); } else if (value instanceof Long) { pathElement.setId((Long) value); } else if (value instanceof Integer) { pathElement.setId((Integer) value); } else if (value instanceof Short) { pathElement.setId((Short) value); } else { throw new IllegalArgumentException( "Expected string or integer, got: " + value.getClass()); } } key.addPath(pathElement); } } if (partitionId != null && !partitionId.equals(PartitionId.getDefaultInstance())) { key.setPartitionId(partitionId); } return key; } } | DatastoreHelper { public static Key.Builder makeKey(Object... elements) { Key.Builder key = Key.newBuilder(); PartitionId partitionId = null; for (int pathIndex = 0; pathIndex < elements.length; pathIndex += 2) { PathElement.Builder pathElement = PathElement.newBuilder(); Object element = elements[pathIndex]; if (element instanceof Key) { Key subKey = (Key) element; if (partitionId == null) { partitionId = subKey.getPartitionId(); } else if (!partitionId.equals(subKey.getPartitionId())) { throw new IllegalArgumentException("Partition IDs did not match, found: " + partitionId + " and " + subKey.getPartitionId()); } key.addAllPath(((Key) element).getPathList()); pathIndex--; } else { String kind; try { kind = (String) element; } catch (ClassCastException e) { throw new IllegalArgumentException("Expected string or Key, got: " + element.getClass()); } pathElement.setKind(kind); if (pathIndex + 1 < elements.length) { Object value = elements[pathIndex + 1]; if (value instanceof String) { pathElement.setName((String) value); } else if (value instanceof Long) { pathElement.setId((Long) value); } else if (value instanceof Integer) { pathElement.setId((Integer) value); } else if (value instanceof Short) { pathElement.setId((Short) value); } else { throw new IllegalArgumentException( "Expected string or integer, got: " + value.getClass()); } } key.addPath(pathElement); } } if (partitionId != null && !partitionId.equals(PartitionId.getDefaultInstance())) { key.setPartitionId(partitionId); } return key; } private DatastoreHelper(); } | DatastoreHelper { public static Key.Builder makeKey(Object... elements) { Key.Builder key = Key.newBuilder(); PartitionId partitionId = null; for (int pathIndex = 0; pathIndex < elements.length; pathIndex += 2) { PathElement.Builder pathElement = PathElement.newBuilder(); Object element = elements[pathIndex]; if (element instanceof Key) { Key subKey = (Key) element; if (partitionId == null) { partitionId = subKey.getPartitionId(); } else if (!partitionId.equals(subKey.getPartitionId())) { throw new IllegalArgumentException("Partition IDs did not match, found: " + partitionId + " and " + subKey.getPartitionId()); } key.addAllPath(((Key) element).getPathList()); pathIndex--; } else { String kind; try { kind = (String) element; } catch (ClassCastException e) { throw new IllegalArgumentException("Expected string or Key, got: " + element.getClass()); } pathElement.setKind(kind); if (pathIndex + 1 < elements.length) { Object value = elements[pathIndex + 1]; if (value instanceof String) { pathElement.setName((String) value); } else if (value instanceof Long) { pathElement.setId((Long) value); } else if (value instanceof Integer) { pathElement.setId((Integer) value); } else if (value instanceof Short) { pathElement.setId((Short) value); } else { throw new IllegalArgumentException( "Expected string or integer, got: " + value.getClass()); } } key.addPath(pathElement); } } if (partitionId != null && !partitionId.equals(PartitionId.getDefaultInstance())) { key.setPartitionId(partitionId); } return key; } private DatastoreHelper(); static Credential getServiceAccountCredential(String serviceAccountId,
String privateKeyFile); static Credential getServiceAccountCredential(String serviceAccountId,
String privateKeyFile, Collection<String> serviceAccountScopes); static Credential getServiceAccountCredential(String serviceAccountId,
PrivateKey privateKey, Collection<String> serviceAccountScopes); static DatastoreOptions.Builder getOptionsFromEnv(); @Nullable static String getProjectIdFromComputeEngine(); static Datastore getDatastoreFromEnv(); static QuerySplitter getQuerySplitter(); static Comparator<Key> getKeyComparator(); static PropertyOrder.Builder makeOrder(String property,
PropertyOrder.Direction direction); static Filter.Builder makeAncestorFilter(Key ancestor); static Filter.Builder makeFilter(String property, PropertyFilter.Operator operator,
Value value); static Filter.Builder makeFilter(String property, PropertyFilter.Operator operator,
Value.Builder value); static Filter.Builder makeAndFilter(Filter... subfilters); static Filter.Builder makeAndFilter(Iterable<Filter> subfilters); static PropertyReference.Builder makePropertyReference(String propertyName); static Value.Builder makeValue(Iterable<Value> values); static Value.Builder makeValue(Value value1, Value value2, Value... rest); static Value.Builder makeValue(Value.Builder value1, Value.Builder value2,
Value.Builder... rest); static Value.Builder makeValue(Key key); static Value.Builder makeValue(Key.Builder key); static Value.Builder makeValue(long key); static Value.Builder makeValue(double value); static Value.Builder makeValue(boolean value); static Value.Builder makeValue(String value); static Value.Builder makeValue(Entity entity); static Value.Builder makeValue(Entity.Builder entity); static Value.Builder makeValue(ByteString blob); static Value.Builder makeValue(Date date); static Value.Builder makeValue(LatLng value); static Value.Builder makeValue(LatLng.Builder value); static Key.Builder makeKey(Object... elements); static double getDouble(Value value); static Key getKey(Value value); static ByteString getByteString(Value value); static Entity getEntity(Value value); static String getString(Value value); static boolean getBoolean(Value value); static long getLong(Value value); static long getTimestamp(Value value); static List<Value> getList(Value value); static Date toDate(Value value); static Mutation.Builder makeInsert(Entity entity); static Mutation.Builder makeUpdate(Entity entity); static Mutation.Builder makeUpsert(Entity entity); static Mutation.Builder makeDelete(Key key); } | DatastoreHelper { public static Key.Builder makeKey(Object... elements) { Key.Builder key = Key.newBuilder(); PartitionId partitionId = null; for (int pathIndex = 0; pathIndex < elements.length; pathIndex += 2) { PathElement.Builder pathElement = PathElement.newBuilder(); Object element = elements[pathIndex]; if (element instanceof Key) { Key subKey = (Key) element; if (partitionId == null) { partitionId = subKey.getPartitionId(); } else if (!partitionId.equals(subKey.getPartitionId())) { throw new IllegalArgumentException("Partition IDs did not match, found: " + partitionId + " and " + subKey.getPartitionId()); } key.addAllPath(((Key) element).getPathList()); pathIndex--; } else { String kind; try { kind = (String) element; } catch (ClassCastException e) { throw new IllegalArgumentException("Expected string or Key, got: " + element.getClass()); } pathElement.setKind(kind); if (pathIndex + 1 < elements.length) { Object value = elements[pathIndex + 1]; if (value instanceof String) { pathElement.setName((String) value); } else if (value instanceof Long) { pathElement.setId((Long) value); } else if (value instanceof Integer) { pathElement.setId((Integer) value); } else if (value instanceof Short) { pathElement.setId((Short) value); } else { throw new IllegalArgumentException( "Expected string or integer, got: " + value.getClass()); } } key.addPath(pathElement); } } if (partitionId != null && !partitionId.equals(PartitionId.getDefaultInstance())) { key.setPartitionId(partitionId); } return key; } private DatastoreHelper(); static Credential getServiceAccountCredential(String serviceAccountId,
String privateKeyFile); static Credential getServiceAccountCredential(String serviceAccountId,
String privateKeyFile, Collection<String> serviceAccountScopes); static Credential getServiceAccountCredential(String serviceAccountId,
PrivateKey privateKey, Collection<String> serviceAccountScopes); static DatastoreOptions.Builder getOptionsFromEnv(); @Nullable static String getProjectIdFromComputeEngine(); static Datastore getDatastoreFromEnv(); static QuerySplitter getQuerySplitter(); static Comparator<Key> getKeyComparator(); static PropertyOrder.Builder makeOrder(String property,
PropertyOrder.Direction direction); static Filter.Builder makeAncestorFilter(Key ancestor); static Filter.Builder makeFilter(String property, PropertyFilter.Operator operator,
Value value); static Filter.Builder makeFilter(String property, PropertyFilter.Operator operator,
Value.Builder value); static Filter.Builder makeAndFilter(Filter... subfilters); static Filter.Builder makeAndFilter(Iterable<Filter> subfilters); static PropertyReference.Builder makePropertyReference(String propertyName); static Value.Builder makeValue(Iterable<Value> values); static Value.Builder makeValue(Value value1, Value value2, Value... rest); static Value.Builder makeValue(Value.Builder value1, Value.Builder value2,
Value.Builder... rest); static Value.Builder makeValue(Key key); static Value.Builder makeValue(Key.Builder key); static Value.Builder makeValue(long key); static Value.Builder makeValue(double value); static Value.Builder makeValue(boolean value); static Value.Builder makeValue(String value); static Value.Builder makeValue(Entity entity); static Value.Builder makeValue(Entity.Builder entity); static Value.Builder makeValue(ByteString blob); static Value.Builder makeValue(Date date); static Value.Builder makeValue(LatLng value); static Value.Builder makeValue(LatLng.Builder value); static Key.Builder makeKey(Object... elements); static double getDouble(Value value); static Key getKey(Value value); static ByteString getByteString(Value value); static Entity getEntity(Value value); static String getString(Value value); static boolean getBoolean(Value value); static long getLong(Value value); static long getTimestamp(Value value); static List<Value> getList(Value value); static Date toDate(Value value); static Mutation.Builder makeInsert(Entity entity); static Mutation.Builder makeUpdate(Entity entity); static Mutation.Builder makeUpsert(Entity entity); static Mutation.Builder makeDelete(Key key); static final String SCATTER_PROPERTY_NAME; static final String KEY_PROPERTY_NAME; static final String PROJECT_ID_ENV_VAR; static final String LOCAL_HOST_ENV_VAR; static final String SERVICE_ACCOUNT_ENV_VAR; static final String PRIVATE_KEY_FILE_ENV_VAR; } |
@Test public void testMakeKey_Key() { assertEquals( Key.newBuilder() .addPath(CHILD.getPath(0)) .build(), makeKey(CHILD).build()); } | public static Key.Builder makeKey(Object... elements) { Key.Builder key = Key.newBuilder(); PartitionId partitionId = null; for (int pathIndex = 0; pathIndex < elements.length; pathIndex += 2) { PathElement.Builder pathElement = PathElement.newBuilder(); Object element = elements[pathIndex]; if (element instanceof Key) { Key subKey = (Key) element; if (partitionId == null) { partitionId = subKey.getPartitionId(); } else if (!partitionId.equals(subKey.getPartitionId())) { throw new IllegalArgumentException("Partition IDs did not match, found: " + partitionId + " and " + subKey.getPartitionId()); } key.addAllPath(((Key) element).getPathList()); pathIndex--; } else { String kind; try { kind = (String) element; } catch (ClassCastException e) { throw new IllegalArgumentException("Expected string or Key, got: " + element.getClass()); } pathElement.setKind(kind); if (pathIndex + 1 < elements.length) { Object value = elements[pathIndex + 1]; if (value instanceof String) { pathElement.setName((String) value); } else if (value instanceof Long) { pathElement.setId((Long) value); } else if (value instanceof Integer) { pathElement.setId((Integer) value); } else if (value instanceof Short) { pathElement.setId((Short) value); } else { throw new IllegalArgumentException( "Expected string or integer, got: " + value.getClass()); } } key.addPath(pathElement); } } if (partitionId != null && !partitionId.equals(PartitionId.getDefaultInstance())) { key.setPartitionId(partitionId); } return key; } | DatastoreHelper { public static Key.Builder makeKey(Object... elements) { Key.Builder key = Key.newBuilder(); PartitionId partitionId = null; for (int pathIndex = 0; pathIndex < elements.length; pathIndex += 2) { PathElement.Builder pathElement = PathElement.newBuilder(); Object element = elements[pathIndex]; if (element instanceof Key) { Key subKey = (Key) element; if (partitionId == null) { partitionId = subKey.getPartitionId(); } else if (!partitionId.equals(subKey.getPartitionId())) { throw new IllegalArgumentException("Partition IDs did not match, found: " + partitionId + " and " + subKey.getPartitionId()); } key.addAllPath(((Key) element).getPathList()); pathIndex--; } else { String kind; try { kind = (String) element; } catch (ClassCastException e) { throw new IllegalArgumentException("Expected string or Key, got: " + element.getClass()); } pathElement.setKind(kind); if (pathIndex + 1 < elements.length) { Object value = elements[pathIndex + 1]; if (value instanceof String) { pathElement.setName((String) value); } else if (value instanceof Long) { pathElement.setId((Long) value); } else if (value instanceof Integer) { pathElement.setId((Integer) value); } else if (value instanceof Short) { pathElement.setId((Short) value); } else { throw new IllegalArgumentException( "Expected string or integer, got: " + value.getClass()); } } key.addPath(pathElement); } } if (partitionId != null && !partitionId.equals(PartitionId.getDefaultInstance())) { key.setPartitionId(partitionId); } return key; } } | DatastoreHelper { public static Key.Builder makeKey(Object... elements) { Key.Builder key = Key.newBuilder(); PartitionId partitionId = null; for (int pathIndex = 0; pathIndex < elements.length; pathIndex += 2) { PathElement.Builder pathElement = PathElement.newBuilder(); Object element = elements[pathIndex]; if (element instanceof Key) { Key subKey = (Key) element; if (partitionId == null) { partitionId = subKey.getPartitionId(); } else if (!partitionId.equals(subKey.getPartitionId())) { throw new IllegalArgumentException("Partition IDs did not match, found: " + partitionId + " and " + subKey.getPartitionId()); } key.addAllPath(((Key) element).getPathList()); pathIndex--; } else { String kind; try { kind = (String) element; } catch (ClassCastException e) { throw new IllegalArgumentException("Expected string or Key, got: " + element.getClass()); } pathElement.setKind(kind); if (pathIndex + 1 < elements.length) { Object value = elements[pathIndex + 1]; if (value instanceof String) { pathElement.setName((String) value); } else if (value instanceof Long) { pathElement.setId((Long) value); } else if (value instanceof Integer) { pathElement.setId((Integer) value); } else if (value instanceof Short) { pathElement.setId((Short) value); } else { throw new IllegalArgumentException( "Expected string or integer, got: " + value.getClass()); } } key.addPath(pathElement); } } if (partitionId != null && !partitionId.equals(PartitionId.getDefaultInstance())) { key.setPartitionId(partitionId); } return key; } private DatastoreHelper(); } | DatastoreHelper { public static Key.Builder makeKey(Object... elements) { Key.Builder key = Key.newBuilder(); PartitionId partitionId = null; for (int pathIndex = 0; pathIndex < elements.length; pathIndex += 2) { PathElement.Builder pathElement = PathElement.newBuilder(); Object element = elements[pathIndex]; if (element instanceof Key) { Key subKey = (Key) element; if (partitionId == null) { partitionId = subKey.getPartitionId(); } else if (!partitionId.equals(subKey.getPartitionId())) { throw new IllegalArgumentException("Partition IDs did not match, found: " + partitionId + " and " + subKey.getPartitionId()); } key.addAllPath(((Key) element).getPathList()); pathIndex--; } else { String kind; try { kind = (String) element; } catch (ClassCastException e) { throw new IllegalArgumentException("Expected string or Key, got: " + element.getClass()); } pathElement.setKind(kind); if (pathIndex + 1 < elements.length) { Object value = elements[pathIndex + 1]; if (value instanceof String) { pathElement.setName((String) value); } else if (value instanceof Long) { pathElement.setId((Long) value); } else if (value instanceof Integer) { pathElement.setId((Integer) value); } else if (value instanceof Short) { pathElement.setId((Short) value); } else { throw new IllegalArgumentException( "Expected string or integer, got: " + value.getClass()); } } key.addPath(pathElement); } } if (partitionId != null && !partitionId.equals(PartitionId.getDefaultInstance())) { key.setPartitionId(partitionId); } return key; } private DatastoreHelper(); static Credential getServiceAccountCredential(String serviceAccountId,
String privateKeyFile); static Credential getServiceAccountCredential(String serviceAccountId,
String privateKeyFile, Collection<String> serviceAccountScopes); static Credential getServiceAccountCredential(String serviceAccountId,
PrivateKey privateKey, Collection<String> serviceAccountScopes); static DatastoreOptions.Builder getOptionsFromEnv(); @Nullable static String getProjectIdFromComputeEngine(); static Datastore getDatastoreFromEnv(); static QuerySplitter getQuerySplitter(); static Comparator<Key> getKeyComparator(); static PropertyOrder.Builder makeOrder(String property,
PropertyOrder.Direction direction); static Filter.Builder makeAncestorFilter(Key ancestor); static Filter.Builder makeFilter(String property, PropertyFilter.Operator operator,
Value value); static Filter.Builder makeFilter(String property, PropertyFilter.Operator operator,
Value.Builder value); static Filter.Builder makeAndFilter(Filter... subfilters); static Filter.Builder makeAndFilter(Iterable<Filter> subfilters); static PropertyReference.Builder makePropertyReference(String propertyName); static Value.Builder makeValue(Iterable<Value> values); static Value.Builder makeValue(Value value1, Value value2, Value... rest); static Value.Builder makeValue(Value.Builder value1, Value.Builder value2,
Value.Builder... rest); static Value.Builder makeValue(Key key); static Value.Builder makeValue(Key.Builder key); static Value.Builder makeValue(long key); static Value.Builder makeValue(double value); static Value.Builder makeValue(boolean value); static Value.Builder makeValue(String value); static Value.Builder makeValue(Entity entity); static Value.Builder makeValue(Entity.Builder entity); static Value.Builder makeValue(ByteString blob); static Value.Builder makeValue(Date date); static Value.Builder makeValue(LatLng value); static Value.Builder makeValue(LatLng.Builder value); static Key.Builder makeKey(Object... elements); static double getDouble(Value value); static Key getKey(Value value); static ByteString getByteString(Value value); static Entity getEntity(Value value); static String getString(Value value); static boolean getBoolean(Value value); static long getLong(Value value); static long getTimestamp(Value value); static List<Value> getList(Value value); static Date toDate(Value value); static Mutation.Builder makeInsert(Entity entity); static Mutation.Builder makeUpdate(Entity entity); static Mutation.Builder makeUpsert(Entity entity); static Mutation.Builder makeDelete(Key key); } | DatastoreHelper { public static Key.Builder makeKey(Object... elements) { Key.Builder key = Key.newBuilder(); PartitionId partitionId = null; for (int pathIndex = 0; pathIndex < elements.length; pathIndex += 2) { PathElement.Builder pathElement = PathElement.newBuilder(); Object element = elements[pathIndex]; if (element instanceof Key) { Key subKey = (Key) element; if (partitionId == null) { partitionId = subKey.getPartitionId(); } else if (!partitionId.equals(subKey.getPartitionId())) { throw new IllegalArgumentException("Partition IDs did not match, found: " + partitionId + " and " + subKey.getPartitionId()); } key.addAllPath(((Key) element).getPathList()); pathIndex--; } else { String kind; try { kind = (String) element; } catch (ClassCastException e) { throw new IllegalArgumentException("Expected string or Key, got: " + element.getClass()); } pathElement.setKind(kind); if (pathIndex + 1 < elements.length) { Object value = elements[pathIndex + 1]; if (value instanceof String) { pathElement.setName((String) value); } else if (value instanceof Long) { pathElement.setId((Long) value); } else if (value instanceof Integer) { pathElement.setId((Integer) value); } else if (value instanceof Short) { pathElement.setId((Short) value); } else { throw new IllegalArgumentException( "Expected string or integer, got: " + value.getClass()); } } key.addPath(pathElement); } } if (partitionId != null && !partitionId.equals(PartitionId.getDefaultInstance())) { key.setPartitionId(partitionId); } return key; } private DatastoreHelper(); static Credential getServiceAccountCredential(String serviceAccountId,
String privateKeyFile); static Credential getServiceAccountCredential(String serviceAccountId,
String privateKeyFile, Collection<String> serviceAccountScopes); static Credential getServiceAccountCredential(String serviceAccountId,
PrivateKey privateKey, Collection<String> serviceAccountScopes); static DatastoreOptions.Builder getOptionsFromEnv(); @Nullable static String getProjectIdFromComputeEngine(); static Datastore getDatastoreFromEnv(); static QuerySplitter getQuerySplitter(); static Comparator<Key> getKeyComparator(); static PropertyOrder.Builder makeOrder(String property,
PropertyOrder.Direction direction); static Filter.Builder makeAncestorFilter(Key ancestor); static Filter.Builder makeFilter(String property, PropertyFilter.Operator operator,
Value value); static Filter.Builder makeFilter(String property, PropertyFilter.Operator operator,
Value.Builder value); static Filter.Builder makeAndFilter(Filter... subfilters); static Filter.Builder makeAndFilter(Iterable<Filter> subfilters); static PropertyReference.Builder makePropertyReference(String propertyName); static Value.Builder makeValue(Iterable<Value> values); static Value.Builder makeValue(Value value1, Value value2, Value... rest); static Value.Builder makeValue(Value.Builder value1, Value.Builder value2,
Value.Builder... rest); static Value.Builder makeValue(Key key); static Value.Builder makeValue(Key.Builder key); static Value.Builder makeValue(long key); static Value.Builder makeValue(double value); static Value.Builder makeValue(boolean value); static Value.Builder makeValue(String value); static Value.Builder makeValue(Entity entity); static Value.Builder makeValue(Entity.Builder entity); static Value.Builder makeValue(ByteString blob); static Value.Builder makeValue(Date date); static Value.Builder makeValue(LatLng value); static Value.Builder makeValue(LatLng.Builder value); static Key.Builder makeKey(Object... elements); static double getDouble(Value value); static Key getKey(Value value); static ByteString getByteString(Value value); static Entity getEntity(Value value); static String getString(Value value); static boolean getBoolean(Value value); static long getLong(Value value); static long getTimestamp(Value value); static List<Value> getList(Value value); static Date toDate(Value value); static Mutation.Builder makeInsert(Entity entity); static Mutation.Builder makeUpdate(Entity entity); static Mutation.Builder makeUpsert(Entity entity); static Mutation.Builder makeDelete(Key key); static final String SCATTER_PROPERTY_NAME; static final String KEY_PROPERTY_NAME; static final String PROJECT_ID_ENV_VAR; static final String LOCAL_HOST_ENV_VAR; static final String SERVICE_ACCOUNT_ENV_VAR; static final String PRIVATE_KEY_FILE_ENV_VAR; } |
@Test public void testMakeKey_KeyKey() { assertEquals( Key.newBuilder() .addPath(PARENT.getPath(0)) .addPath(CHILD.getPath(0)) .build(), makeKey(PARENT, CHILD).build()); } | public static Key.Builder makeKey(Object... elements) { Key.Builder key = Key.newBuilder(); PartitionId partitionId = null; for (int pathIndex = 0; pathIndex < elements.length; pathIndex += 2) { PathElement.Builder pathElement = PathElement.newBuilder(); Object element = elements[pathIndex]; if (element instanceof Key) { Key subKey = (Key) element; if (partitionId == null) { partitionId = subKey.getPartitionId(); } else if (!partitionId.equals(subKey.getPartitionId())) { throw new IllegalArgumentException("Partition IDs did not match, found: " + partitionId + " and " + subKey.getPartitionId()); } key.addAllPath(((Key) element).getPathList()); pathIndex--; } else { String kind; try { kind = (String) element; } catch (ClassCastException e) { throw new IllegalArgumentException("Expected string or Key, got: " + element.getClass()); } pathElement.setKind(kind); if (pathIndex + 1 < elements.length) { Object value = elements[pathIndex + 1]; if (value instanceof String) { pathElement.setName((String) value); } else if (value instanceof Long) { pathElement.setId((Long) value); } else if (value instanceof Integer) { pathElement.setId((Integer) value); } else if (value instanceof Short) { pathElement.setId((Short) value); } else { throw new IllegalArgumentException( "Expected string or integer, got: " + value.getClass()); } } key.addPath(pathElement); } } if (partitionId != null && !partitionId.equals(PartitionId.getDefaultInstance())) { key.setPartitionId(partitionId); } return key; } | DatastoreHelper { public static Key.Builder makeKey(Object... elements) { Key.Builder key = Key.newBuilder(); PartitionId partitionId = null; for (int pathIndex = 0; pathIndex < elements.length; pathIndex += 2) { PathElement.Builder pathElement = PathElement.newBuilder(); Object element = elements[pathIndex]; if (element instanceof Key) { Key subKey = (Key) element; if (partitionId == null) { partitionId = subKey.getPartitionId(); } else if (!partitionId.equals(subKey.getPartitionId())) { throw new IllegalArgumentException("Partition IDs did not match, found: " + partitionId + " and " + subKey.getPartitionId()); } key.addAllPath(((Key) element).getPathList()); pathIndex--; } else { String kind; try { kind = (String) element; } catch (ClassCastException e) { throw new IllegalArgumentException("Expected string or Key, got: " + element.getClass()); } pathElement.setKind(kind); if (pathIndex + 1 < elements.length) { Object value = elements[pathIndex + 1]; if (value instanceof String) { pathElement.setName((String) value); } else if (value instanceof Long) { pathElement.setId((Long) value); } else if (value instanceof Integer) { pathElement.setId((Integer) value); } else if (value instanceof Short) { pathElement.setId((Short) value); } else { throw new IllegalArgumentException( "Expected string or integer, got: " + value.getClass()); } } key.addPath(pathElement); } } if (partitionId != null && !partitionId.equals(PartitionId.getDefaultInstance())) { key.setPartitionId(partitionId); } return key; } } | DatastoreHelper { public static Key.Builder makeKey(Object... elements) { Key.Builder key = Key.newBuilder(); PartitionId partitionId = null; for (int pathIndex = 0; pathIndex < elements.length; pathIndex += 2) { PathElement.Builder pathElement = PathElement.newBuilder(); Object element = elements[pathIndex]; if (element instanceof Key) { Key subKey = (Key) element; if (partitionId == null) { partitionId = subKey.getPartitionId(); } else if (!partitionId.equals(subKey.getPartitionId())) { throw new IllegalArgumentException("Partition IDs did not match, found: " + partitionId + " and " + subKey.getPartitionId()); } key.addAllPath(((Key) element).getPathList()); pathIndex--; } else { String kind; try { kind = (String) element; } catch (ClassCastException e) { throw new IllegalArgumentException("Expected string or Key, got: " + element.getClass()); } pathElement.setKind(kind); if (pathIndex + 1 < elements.length) { Object value = elements[pathIndex + 1]; if (value instanceof String) { pathElement.setName((String) value); } else if (value instanceof Long) { pathElement.setId((Long) value); } else if (value instanceof Integer) { pathElement.setId((Integer) value); } else if (value instanceof Short) { pathElement.setId((Short) value); } else { throw new IllegalArgumentException( "Expected string or integer, got: " + value.getClass()); } } key.addPath(pathElement); } } if (partitionId != null && !partitionId.equals(PartitionId.getDefaultInstance())) { key.setPartitionId(partitionId); } return key; } private DatastoreHelper(); } | DatastoreHelper { public static Key.Builder makeKey(Object... elements) { Key.Builder key = Key.newBuilder(); PartitionId partitionId = null; for (int pathIndex = 0; pathIndex < elements.length; pathIndex += 2) { PathElement.Builder pathElement = PathElement.newBuilder(); Object element = elements[pathIndex]; if (element instanceof Key) { Key subKey = (Key) element; if (partitionId == null) { partitionId = subKey.getPartitionId(); } else if (!partitionId.equals(subKey.getPartitionId())) { throw new IllegalArgumentException("Partition IDs did not match, found: " + partitionId + " and " + subKey.getPartitionId()); } key.addAllPath(((Key) element).getPathList()); pathIndex--; } else { String kind; try { kind = (String) element; } catch (ClassCastException e) { throw new IllegalArgumentException("Expected string or Key, got: " + element.getClass()); } pathElement.setKind(kind); if (pathIndex + 1 < elements.length) { Object value = elements[pathIndex + 1]; if (value instanceof String) { pathElement.setName((String) value); } else if (value instanceof Long) { pathElement.setId((Long) value); } else if (value instanceof Integer) { pathElement.setId((Integer) value); } else if (value instanceof Short) { pathElement.setId((Short) value); } else { throw new IllegalArgumentException( "Expected string or integer, got: " + value.getClass()); } } key.addPath(pathElement); } } if (partitionId != null && !partitionId.equals(PartitionId.getDefaultInstance())) { key.setPartitionId(partitionId); } return key; } private DatastoreHelper(); static Credential getServiceAccountCredential(String serviceAccountId,
String privateKeyFile); static Credential getServiceAccountCredential(String serviceAccountId,
String privateKeyFile, Collection<String> serviceAccountScopes); static Credential getServiceAccountCredential(String serviceAccountId,
PrivateKey privateKey, Collection<String> serviceAccountScopes); static DatastoreOptions.Builder getOptionsFromEnv(); @Nullable static String getProjectIdFromComputeEngine(); static Datastore getDatastoreFromEnv(); static QuerySplitter getQuerySplitter(); static Comparator<Key> getKeyComparator(); static PropertyOrder.Builder makeOrder(String property,
PropertyOrder.Direction direction); static Filter.Builder makeAncestorFilter(Key ancestor); static Filter.Builder makeFilter(String property, PropertyFilter.Operator operator,
Value value); static Filter.Builder makeFilter(String property, PropertyFilter.Operator operator,
Value.Builder value); static Filter.Builder makeAndFilter(Filter... subfilters); static Filter.Builder makeAndFilter(Iterable<Filter> subfilters); static PropertyReference.Builder makePropertyReference(String propertyName); static Value.Builder makeValue(Iterable<Value> values); static Value.Builder makeValue(Value value1, Value value2, Value... rest); static Value.Builder makeValue(Value.Builder value1, Value.Builder value2,
Value.Builder... rest); static Value.Builder makeValue(Key key); static Value.Builder makeValue(Key.Builder key); static Value.Builder makeValue(long key); static Value.Builder makeValue(double value); static Value.Builder makeValue(boolean value); static Value.Builder makeValue(String value); static Value.Builder makeValue(Entity entity); static Value.Builder makeValue(Entity.Builder entity); static Value.Builder makeValue(ByteString blob); static Value.Builder makeValue(Date date); static Value.Builder makeValue(LatLng value); static Value.Builder makeValue(LatLng.Builder value); static Key.Builder makeKey(Object... elements); static double getDouble(Value value); static Key getKey(Value value); static ByteString getByteString(Value value); static Entity getEntity(Value value); static String getString(Value value); static boolean getBoolean(Value value); static long getLong(Value value); static long getTimestamp(Value value); static List<Value> getList(Value value); static Date toDate(Value value); static Mutation.Builder makeInsert(Entity entity); static Mutation.Builder makeUpdate(Entity entity); static Mutation.Builder makeUpsert(Entity entity); static Mutation.Builder makeDelete(Key key); } | DatastoreHelper { public static Key.Builder makeKey(Object... elements) { Key.Builder key = Key.newBuilder(); PartitionId partitionId = null; for (int pathIndex = 0; pathIndex < elements.length; pathIndex += 2) { PathElement.Builder pathElement = PathElement.newBuilder(); Object element = elements[pathIndex]; if (element instanceof Key) { Key subKey = (Key) element; if (partitionId == null) { partitionId = subKey.getPartitionId(); } else if (!partitionId.equals(subKey.getPartitionId())) { throw new IllegalArgumentException("Partition IDs did not match, found: " + partitionId + " and " + subKey.getPartitionId()); } key.addAllPath(((Key) element).getPathList()); pathIndex--; } else { String kind; try { kind = (String) element; } catch (ClassCastException e) { throw new IllegalArgumentException("Expected string or Key, got: " + element.getClass()); } pathElement.setKind(kind); if (pathIndex + 1 < elements.length) { Object value = elements[pathIndex + 1]; if (value instanceof String) { pathElement.setName((String) value); } else if (value instanceof Long) { pathElement.setId((Long) value); } else if (value instanceof Integer) { pathElement.setId((Integer) value); } else if (value instanceof Short) { pathElement.setId((Short) value); } else { throw new IllegalArgumentException( "Expected string or integer, got: " + value.getClass()); } } key.addPath(pathElement); } } if (partitionId != null && !partitionId.equals(PartitionId.getDefaultInstance())) { key.setPartitionId(partitionId); } return key; } private DatastoreHelper(); static Credential getServiceAccountCredential(String serviceAccountId,
String privateKeyFile); static Credential getServiceAccountCredential(String serviceAccountId,
String privateKeyFile, Collection<String> serviceAccountScopes); static Credential getServiceAccountCredential(String serviceAccountId,
PrivateKey privateKey, Collection<String> serviceAccountScopes); static DatastoreOptions.Builder getOptionsFromEnv(); @Nullable static String getProjectIdFromComputeEngine(); static Datastore getDatastoreFromEnv(); static QuerySplitter getQuerySplitter(); static Comparator<Key> getKeyComparator(); static PropertyOrder.Builder makeOrder(String property,
PropertyOrder.Direction direction); static Filter.Builder makeAncestorFilter(Key ancestor); static Filter.Builder makeFilter(String property, PropertyFilter.Operator operator,
Value value); static Filter.Builder makeFilter(String property, PropertyFilter.Operator operator,
Value.Builder value); static Filter.Builder makeAndFilter(Filter... subfilters); static Filter.Builder makeAndFilter(Iterable<Filter> subfilters); static PropertyReference.Builder makePropertyReference(String propertyName); static Value.Builder makeValue(Iterable<Value> values); static Value.Builder makeValue(Value value1, Value value2, Value... rest); static Value.Builder makeValue(Value.Builder value1, Value.Builder value2,
Value.Builder... rest); static Value.Builder makeValue(Key key); static Value.Builder makeValue(Key.Builder key); static Value.Builder makeValue(long key); static Value.Builder makeValue(double value); static Value.Builder makeValue(boolean value); static Value.Builder makeValue(String value); static Value.Builder makeValue(Entity entity); static Value.Builder makeValue(Entity.Builder entity); static Value.Builder makeValue(ByteString blob); static Value.Builder makeValue(Date date); static Value.Builder makeValue(LatLng value); static Value.Builder makeValue(LatLng.Builder value); static Key.Builder makeKey(Object... elements); static double getDouble(Value value); static Key getKey(Value value); static ByteString getByteString(Value value); static Entity getEntity(Value value); static String getString(Value value); static boolean getBoolean(Value value); static long getLong(Value value); static long getTimestamp(Value value); static List<Value> getList(Value value); static Date toDate(Value value); static Mutation.Builder makeInsert(Entity entity); static Mutation.Builder makeUpdate(Entity entity); static Mutation.Builder makeUpsert(Entity entity); static Mutation.Builder makeDelete(Key key); static final String SCATTER_PROPERTY_NAME; static final String KEY_PROPERTY_NAME; static final String PROJECT_ID_ENV_VAR; static final String LOCAL_HOST_ENV_VAR; static final String SERVICE_ACCOUNT_ENV_VAR; static final String PRIVATE_KEY_FILE_ENV_VAR; } |
@Test public void testMakeKey_KeyKeyKey() { assertEquals( Key.newBuilder() .addPath(GRANDPARENT.getPath(0)) .addPath(PARENT.getPath(0)) .addPath(CHILD.getPath(0)) .build(), makeKey(GRANDPARENT, PARENT, CHILD).build()); } | public static Key.Builder makeKey(Object... elements) { Key.Builder key = Key.newBuilder(); PartitionId partitionId = null; for (int pathIndex = 0; pathIndex < elements.length; pathIndex += 2) { PathElement.Builder pathElement = PathElement.newBuilder(); Object element = elements[pathIndex]; if (element instanceof Key) { Key subKey = (Key) element; if (partitionId == null) { partitionId = subKey.getPartitionId(); } else if (!partitionId.equals(subKey.getPartitionId())) { throw new IllegalArgumentException("Partition IDs did not match, found: " + partitionId + " and " + subKey.getPartitionId()); } key.addAllPath(((Key) element).getPathList()); pathIndex--; } else { String kind; try { kind = (String) element; } catch (ClassCastException e) { throw new IllegalArgumentException("Expected string or Key, got: " + element.getClass()); } pathElement.setKind(kind); if (pathIndex + 1 < elements.length) { Object value = elements[pathIndex + 1]; if (value instanceof String) { pathElement.setName((String) value); } else if (value instanceof Long) { pathElement.setId((Long) value); } else if (value instanceof Integer) { pathElement.setId((Integer) value); } else if (value instanceof Short) { pathElement.setId((Short) value); } else { throw new IllegalArgumentException( "Expected string or integer, got: " + value.getClass()); } } key.addPath(pathElement); } } if (partitionId != null && !partitionId.equals(PartitionId.getDefaultInstance())) { key.setPartitionId(partitionId); } return key; } | DatastoreHelper { public static Key.Builder makeKey(Object... elements) { Key.Builder key = Key.newBuilder(); PartitionId partitionId = null; for (int pathIndex = 0; pathIndex < elements.length; pathIndex += 2) { PathElement.Builder pathElement = PathElement.newBuilder(); Object element = elements[pathIndex]; if (element instanceof Key) { Key subKey = (Key) element; if (partitionId == null) { partitionId = subKey.getPartitionId(); } else if (!partitionId.equals(subKey.getPartitionId())) { throw new IllegalArgumentException("Partition IDs did not match, found: " + partitionId + " and " + subKey.getPartitionId()); } key.addAllPath(((Key) element).getPathList()); pathIndex--; } else { String kind; try { kind = (String) element; } catch (ClassCastException e) { throw new IllegalArgumentException("Expected string or Key, got: " + element.getClass()); } pathElement.setKind(kind); if (pathIndex + 1 < elements.length) { Object value = elements[pathIndex + 1]; if (value instanceof String) { pathElement.setName((String) value); } else if (value instanceof Long) { pathElement.setId((Long) value); } else if (value instanceof Integer) { pathElement.setId((Integer) value); } else if (value instanceof Short) { pathElement.setId((Short) value); } else { throw new IllegalArgumentException( "Expected string or integer, got: " + value.getClass()); } } key.addPath(pathElement); } } if (partitionId != null && !partitionId.equals(PartitionId.getDefaultInstance())) { key.setPartitionId(partitionId); } return key; } } | DatastoreHelper { public static Key.Builder makeKey(Object... elements) { Key.Builder key = Key.newBuilder(); PartitionId partitionId = null; for (int pathIndex = 0; pathIndex < elements.length; pathIndex += 2) { PathElement.Builder pathElement = PathElement.newBuilder(); Object element = elements[pathIndex]; if (element instanceof Key) { Key subKey = (Key) element; if (partitionId == null) { partitionId = subKey.getPartitionId(); } else if (!partitionId.equals(subKey.getPartitionId())) { throw new IllegalArgumentException("Partition IDs did not match, found: " + partitionId + " and " + subKey.getPartitionId()); } key.addAllPath(((Key) element).getPathList()); pathIndex--; } else { String kind; try { kind = (String) element; } catch (ClassCastException e) { throw new IllegalArgumentException("Expected string or Key, got: " + element.getClass()); } pathElement.setKind(kind); if (pathIndex + 1 < elements.length) { Object value = elements[pathIndex + 1]; if (value instanceof String) { pathElement.setName((String) value); } else if (value instanceof Long) { pathElement.setId((Long) value); } else if (value instanceof Integer) { pathElement.setId((Integer) value); } else if (value instanceof Short) { pathElement.setId((Short) value); } else { throw new IllegalArgumentException( "Expected string or integer, got: " + value.getClass()); } } key.addPath(pathElement); } } if (partitionId != null && !partitionId.equals(PartitionId.getDefaultInstance())) { key.setPartitionId(partitionId); } return key; } private DatastoreHelper(); } | DatastoreHelper { public static Key.Builder makeKey(Object... elements) { Key.Builder key = Key.newBuilder(); PartitionId partitionId = null; for (int pathIndex = 0; pathIndex < elements.length; pathIndex += 2) { PathElement.Builder pathElement = PathElement.newBuilder(); Object element = elements[pathIndex]; if (element instanceof Key) { Key subKey = (Key) element; if (partitionId == null) { partitionId = subKey.getPartitionId(); } else if (!partitionId.equals(subKey.getPartitionId())) { throw new IllegalArgumentException("Partition IDs did not match, found: " + partitionId + " and " + subKey.getPartitionId()); } key.addAllPath(((Key) element).getPathList()); pathIndex--; } else { String kind; try { kind = (String) element; } catch (ClassCastException e) { throw new IllegalArgumentException("Expected string or Key, got: " + element.getClass()); } pathElement.setKind(kind); if (pathIndex + 1 < elements.length) { Object value = elements[pathIndex + 1]; if (value instanceof String) { pathElement.setName((String) value); } else if (value instanceof Long) { pathElement.setId((Long) value); } else if (value instanceof Integer) { pathElement.setId((Integer) value); } else if (value instanceof Short) { pathElement.setId((Short) value); } else { throw new IllegalArgumentException( "Expected string or integer, got: " + value.getClass()); } } key.addPath(pathElement); } } if (partitionId != null && !partitionId.equals(PartitionId.getDefaultInstance())) { key.setPartitionId(partitionId); } return key; } private DatastoreHelper(); static Credential getServiceAccountCredential(String serviceAccountId,
String privateKeyFile); static Credential getServiceAccountCredential(String serviceAccountId,
String privateKeyFile, Collection<String> serviceAccountScopes); static Credential getServiceAccountCredential(String serviceAccountId,
PrivateKey privateKey, Collection<String> serviceAccountScopes); static DatastoreOptions.Builder getOptionsFromEnv(); @Nullable static String getProjectIdFromComputeEngine(); static Datastore getDatastoreFromEnv(); static QuerySplitter getQuerySplitter(); static Comparator<Key> getKeyComparator(); static PropertyOrder.Builder makeOrder(String property,
PropertyOrder.Direction direction); static Filter.Builder makeAncestorFilter(Key ancestor); static Filter.Builder makeFilter(String property, PropertyFilter.Operator operator,
Value value); static Filter.Builder makeFilter(String property, PropertyFilter.Operator operator,
Value.Builder value); static Filter.Builder makeAndFilter(Filter... subfilters); static Filter.Builder makeAndFilter(Iterable<Filter> subfilters); static PropertyReference.Builder makePropertyReference(String propertyName); static Value.Builder makeValue(Iterable<Value> values); static Value.Builder makeValue(Value value1, Value value2, Value... rest); static Value.Builder makeValue(Value.Builder value1, Value.Builder value2,
Value.Builder... rest); static Value.Builder makeValue(Key key); static Value.Builder makeValue(Key.Builder key); static Value.Builder makeValue(long key); static Value.Builder makeValue(double value); static Value.Builder makeValue(boolean value); static Value.Builder makeValue(String value); static Value.Builder makeValue(Entity entity); static Value.Builder makeValue(Entity.Builder entity); static Value.Builder makeValue(ByteString blob); static Value.Builder makeValue(Date date); static Value.Builder makeValue(LatLng value); static Value.Builder makeValue(LatLng.Builder value); static Key.Builder makeKey(Object... elements); static double getDouble(Value value); static Key getKey(Value value); static ByteString getByteString(Value value); static Entity getEntity(Value value); static String getString(Value value); static boolean getBoolean(Value value); static long getLong(Value value); static long getTimestamp(Value value); static List<Value> getList(Value value); static Date toDate(Value value); static Mutation.Builder makeInsert(Entity entity); static Mutation.Builder makeUpdate(Entity entity); static Mutation.Builder makeUpsert(Entity entity); static Mutation.Builder makeDelete(Key key); } | DatastoreHelper { public static Key.Builder makeKey(Object... elements) { Key.Builder key = Key.newBuilder(); PartitionId partitionId = null; for (int pathIndex = 0; pathIndex < elements.length; pathIndex += 2) { PathElement.Builder pathElement = PathElement.newBuilder(); Object element = elements[pathIndex]; if (element instanceof Key) { Key subKey = (Key) element; if (partitionId == null) { partitionId = subKey.getPartitionId(); } else if (!partitionId.equals(subKey.getPartitionId())) { throw new IllegalArgumentException("Partition IDs did not match, found: " + partitionId + " and " + subKey.getPartitionId()); } key.addAllPath(((Key) element).getPathList()); pathIndex--; } else { String kind; try { kind = (String) element; } catch (ClassCastException e) { throw new IllegalArgumentException("Expected string or Key, got: " + element.getClass()); } pathElement.setKind(kind); if (pathIndex + 1 < elements.length) { Object value = elements[pathIndex + 1]; if (value instanceof String) { pathElement.setName((String) value); } else if (value instanceof Long) { pathElement.setId((Long) value); } else if (value instanceof Integer) { pathElement.setId((Integer) value); } else if (value instanceof Short) { pathElement.setId((Short) value); } else { throw new IllegalArgumentException( "Expected string or integer, got: " + value.getClass()); } } key.addPath(pathElement); } } if (partitionId != null && !partitionId.equals(PartitionId.getDefaultInstance())) { key.setPartitionId(partitionId); } return key; } private DatastoreHelper(); static Credential getServiceAccountCredential(String serviceAccountId,
String privateKeyFile); static Credential getServiceAccountCredential(String serviceAccountId,
String privateKeyFile, Collection<String> serviceAccountScopes); static Credential getServiceAccountCredential(String serviceAccountId,
PrivateKey privateKey, Collection<String> serviceAccountScopes); static DatastoreOptions.Builder getOptionsFromEnv(); @Nullable static String getProjectIdFromComputeEngine(); static Datastore getDatastoreFromEnv(); static QuerySplitter getQuerySplitter(); static Comparator<Key> getKeyComparator(); static PropertyOrder.Builder makeOrder(String property,
PropertyOrder.Direction direction); static Filter.Builder makeAncestorFilter(Key ancestor); static Filter.Builder makeFilter(String property, PropertyFilter.Operator operator,
Value value); static Filter.Builder makeFilter(String property, PropertyFilter.Operator operator,
Value.Builder value); static Filter.Builder makeAndFilter(Filter... subfilters); static Filter.Builder makeAndFilter(Iterable<Filter> subfilters); static PropertyReference.Builder makePropertyReference(String propertyName); static Value.Builder makeValue(Iterable<Value> values); static Value.Builder makeValue(Value value1, Value value2, Value... rest); static Value.Builder makeValue(Value.Builder value1, Value.Builder value2,
Value.Builder... rest); static Value.Builder makeValue(Key key); static Value.Builder makeValue(Key.Builder key); static Value.Builder makeValue(long key); static Value.Builder makeValue(double value); static Value.Builder makeValue(boolean value); static Value.Builder makeValue(String value); static Value.Builder makeValue(Entity entity); static Value.Builder makeValue(Entity.Builder entity); static Value.Builder makeValue(ByteString blob); static Value.Builder makeValue(Date date); static Value.Builder makeValue(LatLng value); static Value.Builder makeValue(LatLng.Builder value); static Key.Builder makeKey(Object... elements); static double getDouble(Value value); static Key getKey(Value value); static ByteString getByteString(Value value); static Entity getEntity(Value value); static String getString(Value value); static boolean getBoolean(Value value); static long getLong(Value value); static long getTimestamp(Value value); static List<Value> getList(Value value); static Date toDate(Value value); static Mutation.Builder makeInsert(Entity entity); static Mutation.Builder makeUpdate(Entity entity); static Mutation.Builder makeUpsert(Entity entity); static Mutation.Builder makeDelete(Key key); static final String SCATTER_PROPERTY_NAME; static final String KEY_PROPERTY_NAME; static final String PROJECT_ID_ENV_VAR; static final String LOCAL_HOST_ENV_VAR; static final String SERVICE_ACCOUNT_ENV_VAR; static final String PRIVATE_KEY_FILE_ENV_VAR; } |
@Test public void testMakeKey_KeyMultiLevelKey() { assertEquals( Key.newBuilder() .addPath(GRANDPARENT.getPath(0)) .addPath(PARENT.getPath(0)) .addPath(CHILD.getPath(0)) .build(), makeKey(GRANDPARENT, makeKey(PARENT, CHILD).build()).build()); } | public static Key.Builder makeKey(Object... elements) { Key.Builder key = Key.newBuilder(); PartitionId partitionId = null; for (int pathIndex = 0; pathIndex < elements.length; pathIndex += 2) { PathElement.Builder pathElement = PathElement.newBuilder(); Object element = elements[pathIndex]; if (element instanceof Key) { Key subKey = (Key) element; if (partitionId == null) { partitionId = subKey.getPartitionId(); } else if (!partitionId.equals(subKey.getPartitionId())) { throw new IllegalArgumentException("Partition IDs did not match, found: " + partitionId + " and " + subKey.getPartitionId()); } key.addAllPath(((Key) element).getPathList()); pathIndex--; } else { String kind; try { kind = (String) element; } catch (ClassCastException e) { throw new IllegalArgumentException("Expected string or Key, got: " + element.getClass()); } pathElement.setKind(kind); if (pathIndex + 1 < elements.length) { Object value = elements[pathIndex + 1]; if (value instanceof String) { pathElement.setName((String) value); } else if (value instanceof Long) { pathElement.setId((Long) value); } else if (value instanceof Integer) { pathElement.setId((Integer) value); } else if (value instanceof Short) { pathElement.setId((Short) value); } else { throw new IllegalArgumentException( "Expected string or integer, got: " + value.getClass()); } } key.addPath(pathElement); } } if (partitionId != null && !partitionId.equals(PartitionId.getDefaultInstance())) { key.setPartitionId(partitionId); } return key; } | DatastoreHelper { public static Key.Builder makeKey(Object... elements) { Key.Builder key = Key.newBuilder(); PartitionId partitionId = null; for (int pathIndex = 0; pathIndex < elements.length; pathIndex += 2) { PathElement.Builder pathElement = PathElement.newBuilder(); Object element = elements[pathIndex]; if (element instanceof Key) { Key subKey = (Key) element; if (partitionId == null) { partitionId = subKey.getPartitionId(); } else if (!partitionId.equals(subKey.getPartitionId())) { throw new IllegalArgumentException("Partition IDs did not match, found: " + partitionId + " and " + subKey.getPartitionId()); } key.addAllPath(((Key) element).getPathList()); pathIndex--; } else { String kind; try { kind = (String) element; } catch (ClassCastException e) { throw new IllegalArgumentException("Expected string or Key, got: " + element.getClass()); } pathElement.setKind(kind); if (pathIndex + 1 < elements.length) { Object value = elements[pathIndex + 1]; if (value instanceof String) { pathElement.setName((String) value); } else if (value instanceof Long) { pathElement.setId((Long) value); } else if (value instanceof Integer) { pathElement.setId((Integer) value); } else if (value instanceof Short) { pathElement.setId((Short) value); } else { throw new IllegalArgumentException( "Expected string or integer, got: " + value.getClass()); } } key.addPath(pathElement); } } if (partitionId != null && !partitionId.equals(PartitionId.getDefaultInstance())) { key.setPartitionId(partitionId); } return key; } } | DatastoreHelper { public static Key.Builder makeKey(Object... elements) { Key.Builder key = Key.newBuilder(); PartitionId partitionId = null; for (int pathIndex = 0; pathIndex < elements.length; pathIndex += 2) { PathElement.Builder pathElement = PathElement.newBuilder(); Object element = elements[pathIndex]; if (element instanceof Key) { Key subKey = (Key) element; if (partitionId == null) { partitionId = subKey.getPartitionId(); } else if (!partitionId.equals(subKey.getPartitionId())) { throw new IllegalArgumentException("Partition IDs did not match, found: " + partitionId + " and " + subKey.getPartitionId()); } key.addAllPath(((Key) element).getPathList()); pathIndex--; } else { String kind; try { kind = (String) element; } catch (ClassCastException e) { throw new IllegalArgumentException("Expected string or Key, got: " + element.getClass()); } pathElement.setKind(kind); if (pathIndex + 1 < elements.length) { Object value = elements[pathIndex + 1]; if (value instanceof String) { pathElement.setName((String) value); } else if (value instanceof Long) { pathElement.setId((Long) value); } else if (value instanceof Integer) { pathElement.setId((Integer) value); } else if (value instanceof Short) { pathElement.setId((Short) value); } else { throw new IllegalArgumentException( "Expected string or integer, got: " + value.getClass()); } } key.addPath(pathElement); } } if (partitionId != null && !partitionId.equals(PartitionId.getDefaultInstance())) { key.setPartitionId(partitionId); } return key; } private DatastoreHelper(); } | DatastoreHelper { public static Key.Builder makeKey(Object... elements) { Key.Builder key = Key.newBuilder(); PartitionId partitionId = null; for (int pathIndex = 0; pathIndex < elements.length; pathIndex += 2) { PathElement.Builder pathElement = PathElement.newBuilder(); Object element = elements[pathIndex]; if (element instanceof Key) { Key subKey = (Key) element; if (partitionId == null) { partitionId = subKey.getPartitionId(); } else if (!partitionId.equals(subKey.getPartitionId())) { throw new IllegalArgumentException("Partition IDs did not match, found: " + partitionId + " and " + subKey.getPartitionId()); } key.addAllPath(((Key) element).getPathList()); pathIndex--; } else { String kind; try { kind = (String) element; } catch (ClassCastException e) { throw new IllegalArgumentException("Expected string or Key, got: " + element.getClass()); } pathElement.setKind(kind); if (pathIndex + 1 < elements.length) { Object value = elements[pathIndex + 1]; if (value instanceof String) { pathElement.setName((String) value); } else if (value instanceof Long) { pathElement.setId((Long) value); } else if (value instanceof Integer) { pathElement.setId((Integer) value); } else if (value instanceof Short) { pathElement.setId((Short) value); } else { throw new IllegalArgumentException( "Expected string or integer, got: " + value.getClass()); } } key.addPath(pathElement); } } if (partitionId != null && !partitionId.equals(PartitionId.getDefaultInstance())) { key.setPartitionId(partitionId); } return key; } private DatastoreHelper(); static Credential getServiceAccountCredential(String serviceAccountId,
String privateKeyFile); static Credential getServiceAccountCredential(String serviceAccountId,
String privateKeyFile, Collection<String> serviceAccountScopes); static Credential getServiceAccountCredential(String serviceAccountId,
PrivateKey privateKey, Collection<String> serviceAccountScopes); static DatastoreOptions.Builder getOptionsFromEnv(); @Nullable static String getProjectIdFromComputeEngine(); static Datastore getDatastoreFromEnv(); static QuerySplitter getQuerySplitter(); static Comparator<Key> getKeyComparator(); static PropertyOrder.Builder makeOrder(String property,
PropertyOrder.Direction direction); static Filter.Builder makeAncestorFilter(Key ancestor); static Filter.Builder makeFilter(String property, PropertyFilter.Operator operator,
Value value); static Filter.Builder makeFilter(String property, PropertyFilter.Operator operator,
Value.Builder value); static Filter.Builder makeAndFilter(Filter... subfilters); static Filter.Builder makeAndFilter(Iterable<Filter> subfilters); static PropertyReference.Builder makePropertyReference(String propertyName); static Value.Builder makeValue(Iterable<Value> values); static Value.Builder makeValue(Value value1, Value value2, Value... rest); static Value.Builder makeValue(Value.Builder value1, Value.Builder value2,
Value.Builder... rest); static Value.Builder makeValue(Key key); static Value.Builder makeValue(Key.Builder key); static Value.Builder makeValue(long key); static Value.Builder makeValue(double value); static Value.Builder makeValue(boolean value); static Value.Builder makeValue(String value); static Value.Builder makeValue(Entity entity); static Value.Builder makeValue(Entity.Builder entity); static Value.Builder makeValue(ByteString blob); static Value.Builder makeValue(Date date); static Value.Builder makeValue(LatLng value); static Value.Builder makeValue(LatLng.Builder value); static Key.Builder makeKey(Object... elements); static double getDouble(Value value); static Key getKey(Value value); static ByteString getByteString(Value value); static Entity getEntity(Value value); static String getString(Value value); static boolean getBoolean(Value value); static long getLong(Value value); static long getTimestamp(Value value); static List<Value> getList(Value value); static Date toDate(Value value); static Mutation.Builder makeInsert(Entity entity); static Mutation.Builder makeUpdate(Entity entity); static Mutation.Builder makeUpsert(Entity entity); static Mutation.Builder makeDelete(Key key); } | DatastoreHelper { public static Key.Builder makeKey(Object... elements) { Key.Builder key = Key.newBuilder(); PartitionId partitionId = null; for (int pathIndex = 0; pathIndex < elements.length; pathIndex += 2) { PathElement.Builder pathElement = PathElement.newBuilder(); Object element = elements[pathIndex]; if (element instanceof Key) { Key subKey = (Key) element; if (partitionId == null) { partitionId = subKey.getPartitionId(); } else if (!partitionId.equals(subKey.getPartitionId())) { throw new IllegalArgumentException("Partition IDs did not match, found: " + partitionId + " and " + subKey.getPartitionId()); } key.addAllPath(((Key) element).getPathList()); pathIndex--; } else { String kind; try { kind = (String) element; } catch (ClassCastException e) { throw new IllegalArgumentException("Expected string or Key, got: " + element.getClass()); } pathElement.setKind(kind); if (pathIndex + 1 < elements.length) { Object value = elements[pathIndex + 1]; if (value instanceof String) { pathElement.setName((String) value); } else if (value instanceof Long) { pathElement.setId((Long) value); } else if (value instanceof Integer) { pathElement.setId((Integer) value); } else if (value instanceof Short) { pathElement.setId((Short) value); } else { throw new IllegalArgumentException( "Expected string or integer, got: " + value.getClass()); } } key.addPath(pathElement); } } if (partitionId != null && !partitionId.equals(PartitionId.getDefaultInstance())) { key.setPartitionId(partitionId); } return key; } private DatastoreHelper(); static Credential getServiceAccountCredential(String serviceAccountId,
String privateKeyFile); static Credential getServiceAccountCredential(String serviceAccountId,
String privateKeyFile, Collection<String> serviceAccountScopes); static Credential getServiceAccountCredential(String serviceAccountId,
PrivateKey privateKey, Collection<String> serviceAccountScopes); static DatastoreOptions.Builder getOptionsFromEnv(); @Nullable static String getProjectIdFromComputeEngine(); static Datastore getDatastoreFromEnv(); static QuerySplitter getQuerySplitter(); static Comparator<Key> getKeyComparator(); static PropertyOrder.Builder makeOrder(String property,
PropertyOrder.Direction direction); static Filter.Builder makeAncestorFilter(Key ancestor); static Filter.Builder makeFilter(String property, PropertyFilter.Operator operator,
Value value); static Filter.Builder makeFilter(String property, PropertyFilter.Operator operator,
Value.Builder value); static Filter.Builder makeAndFilter(Filter... subfilters); static Filter.Builder makeAndFilter(Iterable<Filter> subfilters); static PropertyReference.Builder makePropertyReference(String propertyName); static Value.Builder makeValue(Iterable<Value> values); static Value.Builder makeValue(Value value1, Value value2, Value... rest); static Value.Builder makeValue(Value.Builder value1, Value.Builder value2,
Value.Builder... rest); static Value.Builder makeValue(Key key); static Value.Builder makeValue(Key.Builder key); static Value.Builder makeValue(long key); static Value.Builder makeValue(double value); static Value.Builder makeValue(boolean value); static Value.Builder makeValue(String value); static Value.Builder makeValue(Entity entity); static Value.Builder makeValue(Entity.Builder entity); static Value.Builder makeValue(ByteString blob); static Value.Builder makeValue(Date date); static Value.Builder makeValue(LatLng value); static Value.Builder makeValue(LatLng.Builder value); static Key.Builder makeKey(Object... elements); static double getDouble(Value value); static Key getKey(Value value); static ByteString getByteString(Value value); static Entity getEntity(Value value); static String getString(Value value); static boolean getBoolean(Value value); static long getLong(Value value); static long getTimestamp(Value value); static List<Value> getList(Value value); static Date toDate(Value value); static Mutation.Builder makeInsert(Entity entity); static Mutation.Builder makeUpdate(Entity entity); static Mutation.Builder makeUpsert(Entity entity); static Mutation.Builder makeDelete(Key key); static final String SCATTER_PROPERTY_NAME; static final String KEY_PROPERTY_NAME; static final String PROJECT_ID_ENV_VAR; static final String LOCAL_HOST_ENV_VAR; static final String SERVICE_ACCOUNT_ENV_VAR; static final String PRIVATE_KEY_FILE_ENV_VAR; } |
@Test public void testMakeKey_MultiLevelKeyKey() { assertEquals( Key.newBuilder() .addPath(GRANDPARENT.getPath(0)) .addPath(PARENT.getPath(0)) .addPath(CHILD.getPath(0)) .build(), makeKey(makeKey(GRANDPARENT, PARENT).build(), CHILD).build()); } | public static Key.Builder makeKey(Object... elements) { Key.Builder key = Key.newBuilder(); PartitionId partitionId = null; for (int pathIndex = 0; pathIndex < elements.length; pathIndex += 2) { PathElement.Builder pathElement = PathElement.newBuilder(); Object element = elements[pathIndex]; if (element instanceof Key) { Key subKey = (Key) element; if (partitionId == null) { partitionId = subKey.getPartitionId(); } else if (!partitionId.equals(subKey.getPartitionId())) { throw new IllegalArgumentException("Partition IDs did not match, found: " + partitionId + " and " + subKey.getPartitionId()); } key.addAllPath(((Key) element).getPathList()); pathIndex--; } else { String kind; try { kind = (String) element; } catch (ClassCastException e) { throw new IllegalArgumentException("Expected string or Key, got: " + element.getClass()); } pathElement.setKind(kind); if (pathIndex + 1 < elements.length) { Object value = elements[pathIndex + 1]; if (value instanceof String) { pathElement.setName((String) value); } else if (value instanceof Long) { pathElement.setId((Long) value); } else if (value instanceof Integer) { pathElement.setId((Integer) value); } else if (value instanceof Short) { pathElement.setId((Short) value); } else { throw new IllegalArgumentException( "Expected string or integer, got: " + value.getClass()); } } key.addPath(pathElement); } } if (partitionId != null && !partitionId.equals(PartitionId.getDefaultInstance())) { key.setPartitionId(partitionId); } return key; } | DatastoreHelper { public static Key.Builder makeKey(Object... elements) { Key.Builder key = Key.newBuilder(); PartitionId partitionId = null; for (int pathIndex = 0; pathIndex < elements.length; pathIndex += 2) { PathElement.Builder pathElement = PathElement.newBuilder(); Object element = elements[pathIndex]; if (element instanceof Key) { Key subKey = (Key) element; if (partitionId == null) { partitionId = subKey.getPartitionId(); } else if (!partitionId.equals(subKey.getPartitionId())) { throw new IllegalArgumentException("Partition IDs did not match, found: " + partitionId + " and " + subKey.getPartitionId()); } key.addAllPath(((Key) element).getPathList()); pathIndex--; } else { String kind; try { kind = (String) element; } catch (ClassCastException e) { throw new IllegalArgumentException("Expected string or Key, got: " + element.getClass()); } pathElement.setKind(kind); if (pathIndex + 1 < elements.length) { Object value = elements[pathIndex + 1]; if (value instanceof String) { pathElement.setName((String) value); } else if (value instanceof Long) { pathElement.setId((Long) value); } else if (value instanceof Integer) { pathElement.setId((Integer) value); } else if (value instanceof Short) { pathElement.setId((Short) value); } else { throw new IllegalArgumentException( "Expected string or integer, got: " + value.getClass()); } } key.addPath(pathElement); } } if (partitionId != null && !partitionId.equals(PartitionId.getDefaultInstance())) { key.setPartitionId(partitionId); } return key; } } | DatastoreHelper { public static Key.Builder makeKey(Object... elements) { Key.Builder key = Key.newBuilder(); PartitionId partitionId = null; for (int pathIndex = 0; pathIndex < elements.length; pathIndex += 2) { PathElement.Builder pathElement = PathElement.newBuilder(); Object element = elements[pathIndex]; if (element instanceof Key) { Key subKey = (Key) element; if (partitionId == null) { partitionId = subKey.getPartitionId(); } else if (!partitionId.equals(subKey.getPartitionId())) { throw new IllegalArgumentException("Partition IDs did not match, found: " + partitionId + " and " + subKey.getPartitionId()); } key.addAllPath(((Key) element).getPathList()); pathIndex--; } else { String kind; try { kind = (String) element; } catch (ClassCastException e) { throw new IllegalArgumentException("Expected string or Key, got: " + element.getClass()); } pathElement.setKind(kind); if (pathIndex + 1 < elements.length) { Object value = elements[pathIndex + 1]; if (value instanceof String) { pathElement.setName((String) value); } else if (value instanceof Long) { pathElement.setId((Long) value); } else if (value instanceof Integer) { pathElement.setId((Integer) value); } else if (value instanceof Short) { pathElement.setId((Short) value); } else { throw new IllegalArgumentException( "Expected string or integer, got: " + value.getClass()); } } key.addPath(pathElement); } } if (partitionId != null && !partitionId.equals(PartitionId.getDefaultInstance())) { key.setPartitionId(partitionId); } return key; } private DatastoreHelper(); } | DatastoreHelper { public static Key.Builder makeKey(Object... elements) { Key.Builder key = Key.newBuilder(); PartitionId partitionId = null; for (int pathIndex = 0; pathIndex < elements.length; pathIndex += 2) { PathElement.Builder pathElement = PathElement.newBuilder(); Object element = elements[pathIndex]; if (element instanceof Key) { Key subKey = (Key) element; if (partitionId == null) { partitionId = subKey.getPartitionId(); } else if (!partitionId.equals(subKey.getPartitionId())) { throw new IllegalArgumentException("Partition IDs did not match, found: " + partitionId + " and " + subKey.getPartitionId()); } key.addAllPath(((Key) element).getPathList()); pathIndex--; } else { String kind; try { kind = (String) element; } catch (ClassCastException e) { throw new IllegalArgumentException("Expected string or Key, got: " + element.getClass()); } pathElement.setKind(kind); if (pathIndex + 1 < elements.length) { Object value = elements[pathIndex + 1]; if (value instanceof String) { pathElement.setName((String) value); } else if (value instanceof Long) { pathElement.setId((Long) value); } else if (value instanceof Integer) { pathElement.setId((Integer) value); } else if (value instanceof Short) { pathElement.setId((Short) value); } else { throw new IllegalArgumentException( "Expected string or integer, got: " + value.getClass()); } } key.addPath(pathElement); } } if (partitionId != null && !partitionId.equals(PartitionId.getDefaultInstance())) { key.setPartitionId(partitionId); } return key; } private DatastoreHelper(); static Credential getServiceAccountCredential(String serviceAccountId,
String privateKeyFile); static Credential getServiceAccountCredential(String serviceAccountId,
String privateKeyFile, Collection<String> serviceAccountScopes); static Credential getServiceAccountCredential(String serviceAccountId,
PrivateKey privateKey, Collection<String> serviceAccountScopes); static DatastoreOptions.Builder getOptionsFromEnv(); @Nullable static String getProjectIdFromComputeEngine(); static Datastore getDatastoreFromEnv(); static QuerySplitter getQuerySplitter(); static Comparator<Key> getKeyComparator(); static PropertyOrder.Builder makeOrder(String property,
PropertyOrder.Direction direction); static Filter.Builder makeAncestorFilter(Key ancestor); static Filter.Builder makeFilter(String property, PropertyFilter.Operator operator,
Value value); static Filter.Builder makeFilter(String property, PropertyFilter.Operator operator,
Value.Builder value); static Filter.Builder makeAndFilter(Filter... subfilters); static Filter.Builder makeAndFilter(Iterable<Filter> subfilters); static PropertyReference.Builder makePropertyReference(String propertyName); static Value.Builder makeValue(Iterable<Value> values); static Value.Builder makeValue(Value value1, Value value2, Value... rest); static Value.Builder makeValue(Value.Builder value1, Value.Builder value2,
Value.Builder... rest); static Value.Builder makeValue(Key key); static Value.Builder makeValue(Key.Builder key); static Value.Builder makeValue(long key); static Value.Builder makeValue(double value); static Value.Builder makeValue(boolean value); static Value.Builder makeValue(String value); static Value.Builder makeValue(Entity entity); static Value.Builder makeValue(Entity.Builder entity); static Value.Builder makeValue(ByteString blob); static Value.Builder makeValue(Date date); static Value.Builder makeValue(LatLng value); static Value.Builder makeValue(LatLng.Builder value); static Key.Builder makeKey(Object... elements); static double getDouble(Value value); static Key getKey(Value value); static ByteString getByteString(Value value); static Entity getEntity(Value value); static String getString(Value value); static boolean getBoolean(Value value); static long getLong(Value value); static long getTimestamp(Value value); static List<Value> getList(Value value); static Date toDate(Value value); static Mutation.Builder makeInsert(Entity entity); static Mutation.Builder makeUpdate(Entity entity); static Mutation.Builder makeUpsert(Entity entity); static Mutation.Builder makeDelete(Key key); } | DatastoreHelper { public static Key.Builder makeKey(Object... elements) { Key.Builder key = Key.newBuilder(); PartitionId partitionId = null; for (int pathIndex = 0; pathIndex < elements.length; pathIndex += 2) { PathElement.Builder pathElement = PathElement.newBuilder(); Object element = elements[pathIndex]; if (element instanceof Key) { Key subKey = (Key) element; if (partitionId == null) { partitionId = subKey.getPartitionId(); } else if (!partitionId.equals(subKey.getPartitionId())) { throw new IllegalArgumentException("Partition IDs did not match, found: " + partitionId + " and " + subKey.getPartitionId()); } key.addAllPath(((Key) element).getPathList()); pathIndex--; } else { String kind; try { kind = (String) element; } catch (ClassCastException e) { throw new IllegalArgumentException("Expected string or Key, got: " + element.getClass()); } pathElement.setKind(kind); if (pathIndex + 1 < elements.length) { Object value = elements[pathIndex + 1]; if (value instanceof String) { pathElement.setName((String) value); } else if (value instanceof Long) { pathElement.setId((Long) value); } else if (value instanceof Integer) { pathElement.setId((Integer) value); } else if (value instanceof Short) { pathElement.setId((Short) value); } else { throw new IllegalArgumentException( "Expected string or integer, got: " + value.getClass()); } } key.addPath(pathElement); } } if (partitionId != null && !partitionId.equals(PartitionId.getDefaultInstance())) { key.setPartitionId(partitionId); } return key; } private DatastoreHelper(); static Credential getServiceAccountCredential(String serviceAccountId,
String privateKeyFile); static Credential getServiceAccountCredential(String serviceAccountId,
String privateKeyFile, Collection<String> serviceAccountScopes); static Credential getServiceAccountCredential(String serviceAccountId,
PrivateKey privateKey, Collection<String> serviceAccountScopes); static DatastoreOptions.Builder getOptionsFromEnv(); @Nullable static String getProjectIdFromComputeEngine(); static Datastore getDatastoreFromEnv(); static QuerySplitter getQuerySplitter(); static Comparator<Key> getKeyComparator(); static PropertyOrder.Builder makeOrder(String property,
PropertyOrder.Direction direction); static Filter.Builder makeAncestorFilter(Key ancestor); static Filter.Builder makeFilter(String property, PropertyFilter.Operator operator,
Value value); static Filter.Builder makeFilter(String property, PropertyFilter.Operator operator,
Value.Builder value); static Filter.Builder makeAndFilter(Filter... subfilters); static Filter.Builder makeAndFilter(Iterable<Filter> subfilters); static PropertyReference.Builder makePropertyReference(String propertyName); static Value.Builder makeValue(Iterable<Value> values); static Value.Builder makeValue(Value value1, Value value2, Value... rest); static Value.Builder makeValue(Value.Builder value1, Value.Builder value2,
Value.Builder... rest); static Value.Builder makeValue(Key key); static Value.Builder makeValue(Key.Builder key); static Value.Builder makeValue(long key); static Value.Builder makeValue(double value); static Value.Builder makeValue(boolean value); static Value.Builder makeValue(String value); static Value.Builder makeValue(Entity entity); static Value.Builder makeValue(Entity.Builder entity); static Value.Builder makeValue(ByteString blob); static Value.Builder makeValue(Date date); static Value.Builder makeValue(LatLng value); static Value.Builder makeValue(LatLng.Builder value); static Key.Builder makeKey(Object... elements); static double getDouble(Value value); static Key getKey(Value value); static ByteString getByteString(Value value); static Entity getEntity(Value value); static String getString(Value value); static boolean getBoolean(Value value); static long getLong(Value value); static long getTimestamp(Value value); static List<Value> getList(Value value); static Date toDate(Value value); static Mutation.Builder makeInsert(Entity entity); static Mutation.Builder makeUpdate(Entity entity); static Mutation.Builder makeUpsert(Entity entity); static Mutation.Builder makeDelete(Key key); static final String SCATTER_PROPERTY_NAME; static final String KEY_PROPERTY_NAME; static final String PROJECT_ID_ENV_VAR; static final String LOCAL_HOST_ENV_VAR; static final String SERVICE_ACCOUNT_ENV_VAR; static final String PRIVATE_KEY_FILE_ENV_VAR; } |
@Test public void testMakeKey_MultiLevelKey() { assertEquals( Key.newBuilder() .addPath(GRANDPARENT.getPath(0)) .addPath(PARENT.getPath(0)) .addPath(CHILD.getPath(0)) .build(), makeKey(makeKey(GRANDPARENT, PARENT, CHILD).build()).build()); } | public static Key.Builder makeKey(Object... elements) { Key.Builder key = Key.newBuilder(); PartitionId partitionId = null; for (int pathIndex = 0; pathIndex < elements.length; pathIndex += 2) { PathElement.Builder pathElement = PathElement.newBuilder(); Object element = elements[pathIndex]; if (element instanceof Key) { Key subKey = (Key) element; if (partitionId == null) { partitionId = subKey.getPartitionId(); } else if (!partitionId.equals(subKey.getPartitionId())) { throw new IllegalArgumentException("Partition IDs did not match, found: " + partitionId + " and " + subKey.getPartitionId()); } key.addAllPath(((Key) element).getPathList()); pathIndex--; } else { String kind; try { kind = (String) element; } catch (ClassCastException e) { throw new IllegalArgumentException("Expected string or Key, got: " + element.getClass()); } pathElement.setKind(kind); if (pathIndex + 1 < elements.length) { Object value = elements[pathIndex + 1]; if (value instanceof String) { pathElement.setName((String) value); } else if (value instanceof Long) { pathElement.setId((Long) value); } else if (value instanceof Integer) { pathElement.setId((Integer) value); } else if (value instanceof Short) { pathElement.setId((Short) value); } else { throw new IllegalArgumentException( "Expected string or integer, got: " + value.getClass()); } } key.addPath(pathElement); } } if (partitionId != null && !partitionId.equals(PartitionId.getDefaultInstance())) { key.setPartitionId(partitionId); } return key; } | DatastoreHelper { public static Key.Builder makeKey(Object... elements) { Key.Builder key = Key.newBuilder(); PartitionId partitionId = null; for (int pathIndex = 0; pathIndex < elements.length; pathIndex += 2) { PathElement.Builder pathElement = PathElement.newBuilder(); Object element = elements[pathIndex]; if (element instanceof Key) { Key subKey = (Key) element; if (partitionId == null) { partitionId = subKey.getPartitionId(); } else if (!partitionId.equals(subKey.getPartitionId())) { throw new IllegalArgumentException("Partition IDs did not match, found: " + partitionId + " and " + subKey.getPartitionId()); } key.addAllPath(((Key) element).getPathList()); pathIndex--; } else { String kind; try { kind = (String) element; } catch (ClassCastException e) { throw new IllegalArgumentException("Expected string or Key, got: " + element.getClass()); } pathElement.setKind(kind); if (pathIndex + 1 < elements.length) { Object value = elements[pathIndex + 1]; if (value instanceof String) { pathElement.setName((String) value); } else if (value instanceof Long) { pathElement.setId((Long) value); } else if (value instanceof Integer) { pathElement.setId((Integer) value); } else if (value instanceof Short) { pathElement.setId((Short) value); } else { throw new IllegalArgumentException( "Expected string or integer, got: " + value.getClass()); } } key.addPath(pathElement); } } if (partitionId != null && !partitionId.equals(PartitionId.getDefaultInstance())) { key.setPartitionId(partitionId); } return key; } } | DatastoreHelper { public static Key.Builder makeKey(Object... elements) { Key.Builder key = Key.newBuilder(); PartitionId partitionId = null; for (int pathIndex = 0; pathIndex < elements.length; pathIndex += 2) { PathElement.Builder pathElement = PathElement.newBuilder(); Object element = elements[pathIndex]; if (element instanceof Key) { Key subKey = (Key) element; if (partitionId == null) { partitionId = subKey.getPartitionId(); } else if (!partitionId.equals(subKey.getPartitionId())) { throw new IllegalArgumentException("Partition IDs did not match, found: " + partitionId + " and " + subKey.getPartitionId()); } key.addAllPath(((Key) element).getPathList()); pathIndex--; } else { String kind; try { kind = (String) element; } catch (ClassCastException e) { throw new IllegalArgumentException("Expected string or Key, got: " + element.getClass()); } pathElement.setKind(kind); if (pathIndex + 1 < elements.length) { Object value = elements[pathIndex + 1]; if (value instanceof String) { pathElement.setName((String) value); } else if (value instanceof Long) { pathElement.setId((Long) value); } else if (value instanceof Integer) { pathElement.setId((Integer) value); } else if (value instanceof Short) { pathElement.setId((Short) value); } else { throw new IllegalArgumentException( "Expected string or integer, got: " + value.getClass()); } } key.addPath(pathElement); } } if (partitionId != null && !partitionId.equals(PartitionId.getDefaultInstance())) { key.setPartitionId(partitionId); } return key; } private DatastoreHelper(); } | DatastoreHelper { public static Key.Builder makeKey(Object... elements) { Key.Builder key = Key.newBuilder(); PartitionId partitionId = null; for (int pathIndex = 0; pathIndex < elements.length; pathIndex += 2) { PathElement.Builder pathElement = PathElement.newBuilder(); Object element = elements[pathIndex]; if (element instanceof Key) { Key subKey = (Key) element; if (partitionId == null) { partitionId = subKey.getPartitionId(); } else if (!partitionId.equals(subKey.getPartitionId())) { throw new IllegalArgumentException("Partition IDs did not match, found: " + partitionId + " and " + subKey.getPartitionId()); } key.addAllPath(((Key) element).getPathList()); pathIndex--; } else { String kind; try { kind = (String) element; } catch (ClassCastException e) { throw new IllegalArgumentException("Expected string or Key, got: " + element.getClass()); } pathElement.setKind(kind); if (pathIndex + 1 < elements.length) { Object value = elements[pathIndex + 1]; if (value instanceof String) { pathElement.setName((String) value); } else if (value instanceof Long) { pathElement.setId((Long) value); } else if (value instanceof Integer) { pathElement.setId((Integer) value); } else if (value instanceof Short) { pathElement.setId((Short) value); } else { throw new IllegalArgumentException( "Expected string or integer, got: " + value.getClass()); } } key.addPath(pathElement); } } if (partitionId != null && !partitionId.equals(PartitionId.getDefaultInstance())) { key.setPartitionId(partitionId); } return key; } private DatastoreHelper(); static Credential getServiceAccountCredential(String serviceAccountId,
String privateKeyFile); static Credential getServiceAccountCredential(String serviceAccountId,
String privateKeyFile, Collection<String> serviceAccountScopes); static Credential getServiceAccountCredential(String serviceAccountId,
PrivateKey privateKey, Collection<String> serviceAccountScopes); static DatastoreOptions.Builder getOptionsFromEnv(); @Nullable static String getProjectIdFromComputeEngine(); static Datastore getDatastoreFromEnv(); static QuerySplitter getQuerySplitter(); static Comparator<Key> getKeyComparator(); static PropertyOrder.Builder makeOrder(String property,
PropertyOrder.Direction direction); static Filter.Builder makeAncestorFilter(Key ancestor); static Filter.Builder makeFilter(String property, PropertyFilter.Operator operator,
Value value); static Filter.Builder makeFilter(String property, PropertyFilter.Operator operator,
Value.Builder value); static Filter.Builder makeAndFilter(Filter... subfilters); static Filter.Builder makeAndFilter(Iterable<Filter> subfilters); static PropertyReference.Builder makePropertyReference(String propertyName); static Value.Builder makeValue(Iterable<Value> values); static Value.Builder makeValue(Value value1, Value value2, Value... rest); static Value.Builder makeValue(Value.Builder value1, Value.Builder value2,
Value.Builder... rest); static Value.Builder makeValue(Key key); static Value.Builder makeValue(Key.Builder key); static Value.Builder makeValue(long key); static Value.Builder makeValue(double value); static Value.Builder makeValue(boolean value); static Value.Builder makeValue(String value); static Value.Builder makeValue(Entity entity); static Value.Builder makeValue(Entity.Builder entity); static Value.Builder makeValue(ByteString blob); static Value.Builder makeValue(Date date); static Value.Builder makeValue(LatLng value); static Value.Builder makeValue(LatLng.Builder value); static Key.Builder makeKey(Object... elements); static double getDouble(Value value); static Key getKey(Value value); static ByteString getByteString(Value value); static Entity getEntity(Value value); static String getString(Value value); static boolean getBoolean(Value value); static long getLong(Value value); static long getTimestamp(Value value); static List<Value> getList(Value value); static Date toDate(Value value); static Mutation.Builder makeInsert(Entity entity); static Mutation.Builder makeUpdate(Entity entity); static Mutation.Builder makeUpsert(Entity entity); static Mutation.Builder makeDelete(Key key); } | DatastoreHelper { public static Key.Builder makeKey(Object... elements) { Key.Builder key = Key.newBuilder(); PartitionId partitionId = null; for (int pathIndex = 0; pathIndex < elements.length; pathIndex += 2) { PathElement.Builder pathElement = PathElement.newBuilder(); Object element = elements[pathIndex]; if (element instanceof Key) { Key subKey = (Key) element; if (partitionId == null) { partitionId = subKey.getPartitionId(); } else if (!partitionId.equals(subKey.getPartitionId())) { throw new IllegalArgumentException("Partition IDs did not match, found: " + partitionId + " and " + subKey.getPartitionId()); } key.addAllPath(((Key) element).getPathList()); pathIndex--; } else { String kind; try { kind = (String) element; } catch (ClassCastException e) { throw new IllegalArgumentException("Expected string or Key, got: " + element.getClass()); } pathElement.setKind(kind); if (pathIndex + 1 < elements.length) { Object value = elements[pathIndex + 1]; if (value instanceof String) { pathElement.setName((String) value); } else if (value instanceof Long) { pathElement.setId((Long) value); } else if (value instanceof Integer) { pathElement.setId((Integer) value); } else if (value instanceof Short) { pathElement.setId((Short) value); } else { throw new IllegalArgumentException( "Expected string or integer, got: " + value.getClass()); } } key.addPath(pathElement); } } if (partitionId != null && !partitionId.equals(PartitionId.getDefaultInstance())) { key.setPartitionId(partitionId); } return key; } private DatastoreHelper(); static Credential getServiceAccountCredential(String serviceAccountId,
String privateKeyFile); static Credential getServiceAccountCredential(String serviceAccountId,
String privateKeyFile, Collection<String> serviceAccountScopes); static Credential getServiceAccountCredential(String serviceAccountId,
PrivateKey privateKey, Collection<String> serviceAccountScopes); static DatastoreOptions.Builder getOptionsFromEnv(); @Nullable static String getProjectIdFromComputeEngine(); static Datastore getDatastoreFromEnv(); static QuerySplitter getQuerySplitter(); static Comparator<Key> getKeyComparator(); static PropertyOrder.Builder makeOrder(String property,
PropertyOrder.Direction direction); static Filter.Builder makeAncestorFilter(Key ancestor); static Filter.Builder makeFilter(String property, PropertyFilter.Operator operator,
Value value); static Filter.Builder makeFilter(String property, PropertyFilter.Operator operator,
Value.Builder value); static Filter.Builder makeAndFilter(Filter... subfilters); static Filter.Builder makeAndFilter(Iterable<Filter> subfilters); static PropertyReference.Builder makePropertyReference(String propertyName); static Value.Builder makeValue(Iterable<Value> values); static Value.Builder makeValue(Value value1, Value value2, Value... rest); static Value.Builder makeValue(Value.Builder value1, Value.Builder value2,
Value.Builder... rest); static Value.Builder makeValue(Key key); static Value.Builder makeValue(Key.Builder key); static Value.Builder makeValue(long key); static Value.Builder makeValue(double value); static Value.Builder makeValue(boolean value); static Value.Builder makeValue(String value); static Value.Builder makeValue(Entity entity); static Value.Builder makeValue(Entity.Builder entity); static Value.Builder makeValue(ByteString blob); static Value.Builder makeValue(Date date); static Value.Builder makeValue(LatLng value); static Value.Builder makeValue(LatLng.Builder value); static Key.Builder makeKey(Object... elements); static double getDouble(Value value); static Key getKey(Value value); static ByteString getByteString(Value value); static Entity getEntity(Value value); static String getString(Value value); static boolean getBoolean(Value value); static long getLong(Value value); static long getTimestamp(Value value); static List<Value> getList(Value value); static Date toDate(Value value); static Mutation.Builder makeInsert(Entity entity); static Mutation.Builder makeUpdate(Entity entity); static Mutation.Builder makeUpsert(Entity entity); static Mutation.Builder makeDelete(Key key); static final String SCATTER_PROPERTY_NAME; static final String KEY_PROPERTY_NAME; static final String PROJECT_ID_ENV_VAR; static final String LOCAL_HOST_ENV_VAR; static final String SERVICE_ACCOUNT_ENV_VAR; static final String PRIVATE_KEY_FILE_ENV_VAR; } |
@Test public void testMakeKey_PartitionId() { PartitionId partitionId = PartitionId.newBuilder() .setNamespaceId("namespace-id") .build(); Key parent = PARENT.toBuilder() .setPartitionId(partitionId) .build(); assertEquals( Key.newBuilder() .setPartitionId(partitionId) .addPath(PARENT.getPath(0)) .addPath(Key.PathElement.newBuilder().setKind("Child")) .build(), makeKey(parent, "Child").build()); } | public static Key.Builder makeKey(Object... elements) { Key.Builder key = Key.newBuilder(); PartitionId partitionId = null; for (int pathIndex = 0; pathIndex < elements.length; pathIndex += 2) { PathElement.Builder pathElement = PathElement.newBuilder(); Object element = elements[pathIndex]; if (element instanceof Key) { Key subKey = (Key) element; if (partitionId == null) { partitionId = subKey.getPartitionId(); } else if (!partitionId.equals(subKey.getPartitionId())) { throw new IllegalArgumentException("Partition IDs did not match, found: " + partitionId + " and " + subKey.getPartitionId()); } key.addAllPath(((Key) element).getPathList()); pathIndex--; } else { String kind; try { kind = (String) element; } catch (ClassCastException e) { throw new IllegalArgumentException("Expected string or Key, got: " + element.getClass()); } pathElement.setKind(kind); if (pathIndex + 1 < elements.length) { Object value = elements[pathIndex + 1]; if (value instanceof String) { pathElement.setName((String) value); } else if (value instanceof Long) { pathElement.setId((Long) value); } else if (value instanceof Integer) { pathElement.setId((Integer) value); } else if (value instanceof Short) { pathElement.setId((Short) value); } else { throw new IllegalArgumentException( "Expected string or integer, got: " + value.getClass()); } } key.addPath(pathElement); } } if (partitionId != null && !partitionId.equals(PartitionId.getDefaultInstance())) { key.setPartitionId(partitionId); } return key; } | DatastoreHelper { public static Key.Builder makeKey(Object... elements) { Key.Builder key = Key.newBuilder(); PartitionId partitionId = null; for (int pathIndex = 0; pathIndex < elements.length; pathIndex += 2) { PathElement.Builder pathElement = PathElement.newBuilder(); Object element = elements[pathIndex]; if (element instanceof Key) { Key subKey = (Key) element; if (partitionId == null) { partitionId = subKey.getPartitionId(); } else if (!partitionId.equals(subKey.getPartitionId())) { throw new IllegalArgumentException("Partition IDs did not match, found: " + partitionId + " and " + subKey.getPartitionId()); } key.addAllPath(((Key) element).getPathList()); pathIndex--; } else { String kind; try { kind = (String) element; } catch (ClassCastException e) { throw new IllegalArgumentException("Expected string or Key, got: " + element.getClass()); } pathElement.setKind(kind); if (pathIndex + 1 < elements.length) { Object value = elements[pathIndex + 1]; if (value instanceof String) { pathElement.setName((String) value); } else if (value instanceof Long) { pathElement.setId((Long) value); } else if (value instanceof Integer) { pathElement.setId((Integer) value); } else if (value instanceof Short) { pathElement.setId((Short) value); } else { throw new IllegalArgumentException( "Expected string or integer, got: " + value.getClass()); } } key.addPath(pathElement); } } if (partitionId != null && !partitionId.equals(PartitionId.getDefaultInstance())) { key.setPartitionId(partitionId); } return key; } } | DatastoreHelper { public static Key.Builder makeKey(Object... elements) { Key.Builder key = Key.newBuilder(); PartitionId partitionId = null; for (int pathIndex = 0; pathIndex < elements.length; pathIndex += 2) { PathElement.Builder pathElement = PathElement.newBuilder(); Object element = elements[pathIndex]; if (element instanceof Key) { Key subKey = (Key) element; if (partitionId == null) { partitionId = subKey.getPartitionId(); } else if (!partitionId.equals(subKey.getPartitionId())) { throw new IllegalArgumentException("Partition IDs did not match, found: " + partitionId + " and " + subKey.getPartitionId()); } key.addAllPath(((Key) element).getPathList()); pathIndex--; } else { String kind; try { kind = (String) element; } catch (ClassCastException e) { throw new IllegalArgumentException("Expected string or Key, got: " + element.getClass()); } pathElement.setKind(kind); if (pathIndex + 1 < elements.length) { Object value = elements[pathIndex + 1]; if (value instanceof String) { pathElement.setName((String) value); } else if (value instanceof Long) { pathElement.setId((Long) value); } else if (value instanceof Integer) { pathElement.setId((Integer) value); } else if (value instanceof Short) { pathElement.setId((Short) value); } else { throw new IllegalArgumentException( "Expected string or integer, got: " + value.getClass()); } } key.addPath(pathElement); } } if (partitionId != null && !partitionId.equals(PartitionId.getDefaultInstance())) { key.setPartitionId(partitionId); } return key; } private DatastoreHelper(); } | DatastoreHelper { public static Key.Builder makeKey(Object... elements) { Key.Builder key = Key.newBuilder(); PartitionId partitionId = null; for (int pathIndex = 0; pathIndex < elements.length; pathIndex += 2) { PathElement.Builder pathElement = PathElement.newBuilder(); Object element = elements[pathIndex]; if (element instanceof Key) { Key subKey = (Key) element; if (partitionId == null) { partitionId = subKey.getPartitionId(); } else if (!partitionId.equals(subKey.getPartitionId())) { throw new IllegalArgumentException("Partition IDs did not match, found: " + partitionId + " and " + subKey.getPartitionId()); } key.addAllPath(((Key) element).getPathList()); pathIndex--; } else { String kind; try { kind = (String) element; } catch (ClassCastException e) { throw new IllegalArgumentException("Expected string or Key, got: " + element.getClass()); } pathElement.setKind(kind); if (pathIndex + 1 < elements.length) { Object value = elements[pathIndex + 1]; if (value instanceof String) { pathElement.setName((String) value); } else if (value instanceof Long) { pathElement.setId((Long) value); } else if (value instanceof Integer) { pathElement.setId((Integer) value); } else if (value instanceof Short) { pathElement.setId((Short) value); } else { throw new IllegalArgumentException( "Expected string or integer, got: " + value.getClass()); } } key.addPath(pathElement); } } if (partitionId != null && !partitionId.equals(PartitionId.getDefaultInstance())) { key.setPartitionId(partitionId); } return key; } private DatastoreHelper(); static Credential getServiceAccountCredential(String serviceAccountId,
String privateKeyFile); static Credential getServiceAccountCredential(String serviceAccountId,
String privateKeyFile, Collection<String> serviceAccountScopes); static Credential getServiceAccountCredential(String serviceAccountId,
PrivateKey privateKey, Collection<String> serviceAccountScopes); static DatastoreOptions.Builder getOptionsFromEnv(); @Nullable static String getProjectIdFromComputeEngine(); static Datastore getDatastoreFromEnv(); static QuerySplitter getQuerySplitter(); static Comparator<Key> getKeyComparator(); static PropertyOrder.Builder makeOrder(String property,
PropertyOrder.Direction direction); static Filter.Builder makeAncestorFilter(Key ancestor); static Filter.Builder makeFilter(String property, PropertyFilter.Operator operator,
Value value); static Filter.Builder makeFilter(String property, PropertyFilter.Operator operator,
Value.Builder value); static Filter.Builder makeAndFilter(Filter... subfilters); static Filter.Builder makeAndFilter(Iterable<Filter> subfilters); static PropertyReference.Builder makePropertyReference(String propertyName); static Value.Builder makeValue(Iterable<Value> values); static Value.Builder makeValue(Value value1, Value value2, Value... rest); static Value.Builder makeValue(Value.Builder value1, Value.Builder value2,
Value.Builder... rest); static Value.Builder makeValue(Key key); static Value.Builder makeValue(Key.Builder key); static Value.Builder makeValue(long key); static Value.Builder makeValue(double value); static Value.Builder makeValue(boolean value); static Value.Builder makeValue(String value); static Value.Builder makeValue(Entity entity); static Value.Builder makeValue(Entity.Builder entity); static Value.Builder makeValue(ByteString blob); static Value.Builder makeValue(Date date); static Value.Builder makeValue(LatLng value); static Value.Builder makeValue(LatLng.Builder value); static Key.Builder makeKey(Object... elements); static double getDouble(Value value); static Key getKey(Value value); static ByteString getByteString(Value value); static Entity getEntity(Value value); static String getString(Value value); static boolean getBoolean(Value value); static long getLong(Value value); static long getTimestamp(Value value); static List<Value> getList(Value value); static Date toDate(Value value); static Mutation.Builder makeInsert(Entity entity); static Mutation.Builder makeUpdate(Entity entity); static Mutation.Builder makeUpsert(Entity entity); static Mutation.Builder makeDelete(Key key); } | DatastoreHelper { public static Key.Builder makeKey(Object... elements) { Key.Builder key = Key.newBuilder(); PartitionId partitionId = null; for (int pathIndex = 0; pathIndex < elements.length; pathIndex += 2) { PathElement.Builder pathElement = PathElement.newBuilder(); Object element = elements[pathIndex]; if (element instanceof Key) { Key subKey = (Key) element; if (partitionId == null) { partitionId = subKey.getPartitionId(); } else if (!partitionId.equals(subKey.getPartitionId())) { throw new IllegalArgumentException("Partition IDs did not match, found: " + partitionId + " and " + subKey.getPartitionId()); } key.addAllPath(((Key) element).getPathList()); pathIndex--; } else { String kind; try { kind = (String) element; } catch (ClassCastException e) { throw new IllegalArgumentException("Expected string or Key, got: " + element.getClass()); } pathElement.setKind(kind); if (pathIndex + 1 < elements.length) { Object value = elements[pathIndex + 1]; if (value instanceof String) { pathElement.setName((String) value); } else if (value instanceof Long) { pathElement.setId((Long) value); } else if (value instanceof Integer) { pathElement.setId((Integer) value); } else if (value instanceof Short) { pathElement.setId((Short) value); } else { throw new IllegalArgumentException( "Expected string or integer, got: " + value.getClass()); } } key.addPath(pathElement); } } if (partitionId != null && !partitionId.equals(PartitionId.getDefaultInstance())) { key.setPartitionId(partitionId); } return key; } private DatastoreHelper(); static Credential getServiceAccountCredential(String serviceAccountId,
String privateKeyFile); static Credential getServiceAccountCredential(String serviceAccountId,
String privateKeyFile, Collection<String> serviceAccountScopes); static Credential getServiceAccountCredential(String serviceAccountId,
PrivateKey privateKey, Collection<String> serviceAccountScopes); static DatastoreOptions.Builder getOptionsFromEnv(); @Nullable static String getProjectIdFromComputeEngine(); static Datastore getDatastoreFromEnv(); static QuerySplitter getQuerySplitter(); static Comparator<Key> getKeyComparator(); static PropertyOrder.Builder makeOrder(String property,
PropertyOrder.Direction direction); static Filter.Builder makeAncestorFilter(Key ancestor); static Filter.Builder makeFilter(String property, PropertyFilter.Operator operator,
Value value); static Filter.Builder makeFilter(String property, PropertyFilter.Operator operator,
Value.Builder value); static Filter.Builder makeAndFilter(Filter... subfilters); static Filter.Builder makeAndFilter(Iterable<Filter> subfilters); static PropertyReference.Builder makePropertyReference(String propertyName); static Value.Builder makeValue(Iterable<Value> values); static Value.Builder makeValue(Value value1, Value value2, Value... rest); static Value.Builder makeValue(Value.Builder value1, Value.Builder value2,
Value.Builder... rest); static Value.Builder makeValue(Key key); static Value.Builder makeValue(Key.Builder key); static Value.Builder makeValue(long key); static Value.Builder makeValue(double value); static Value.Builder makeValue(boolean value); static Value.Builder makeValue(String value); static Value.Builder makeValue(Entity entity); static Value.Builder makeValue(Entity.Builder entity); static Value.Builder makeValue(ByteString blob); static Value.Builder makeValue(Date date); static Value.Builder makeValue(LatLng value); static Value.Builder makeValue(LatLng.Builder value); static Key.Builder makeKey(Object... elements); static double getDouble(Value value); static Key getKey(Value value); static ByteString getByteString(Value value); static Entity getEntity(Value value); static String getString(Value value); static boolean getBoolean(Value value); static long getLong(Value value); static long getTimestamp(Value value); static List<Value> getList(Value value); static Date toDate(Value value); static Mutation.Builder makeInsert(Entity entity); static Mutation.Builder makeUpdate(Entity entity); static Mutation.Builder makeUpsert(Entity entity); static Mutation.Builder makeDelete(Key key); static final String SCATTER_PROPERTY_NAME; static final String KEY_PROPERTY_NAME; static final String PROJECT_ID_ENV_VAR; static final String LOCAL_HOST_ENV_VAR; static final String SERVICE_ACCOUNT_ENV_VAR; static final String PRIVATE_KEY_FILE_ENV_VAR; } |
@Test public void testMakeKey_NonMatchingPartitionId2() { PartitionId partitionId1 = PartitionId.newBuilder() .setNamespaceId("namespace-id") .build(); PartitionId partitionId2 = PartitionId.newBuilder() .setNamespaceId("another-namespace-id") .build(); try { makeKey( PARENT.toBuilder().setPartitionId(partitionId1).build(), CHILD.toBuilder().setPartitionId(partitionId2).build()); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } } | public static Key.Builder makeKey(Object... elements) { Key.Builder key = Key.newBuilder(); PartitionId partitionId = null; for (int pathIndex = 0; pathIndex < elements.length; pathIndex += 2) { PathElement.Builder pathElement = PathElement.newBuilder(); Object element = elements[pathIndex]; if (element instanceof Key) { Key subKey = (Key) element; if (partitionId == null) { partitionId = subKey.getPartitionId(); } else if (!partitionId.equals(subKey.getPartitionId())) { throw new IllegalArgumentException("Partition IDs did not match, found: " + partitionId + " and " + subKey.getPartitionId()); } key.addAllPath(((Key) element).getPathList()); pathIndex--; } else { String kind; try { kind = (String) element; } catch (ClassCastException e) { throw new IllegalArgumentException("Expected string or Key, got: " + element.getClass()); } pathElement.setKind(kind); if (pathIndex + 1 < elements.length) { Object value = elements[pathIndex + 1]; if (value instanceof String) { pathElement.setName((String) value); } else if (value instanceof Long) { pathElement.setId((Long) value); } else if (value instanceof Integer) { pathElement.setId((Integer) value); } else if (value instanceof Short) { pathElement.setId((Short) value); } else { throw new IllegalArgumentException( "Expected string or integer, got: " + value.getClass()); } } key.addPath(pathElement); } } if (partitionId != null && !partitionId.equals(PartitionId.getDefaultInstance())) { key.setPartitionId(partitionId); } return key; } | DatastoreHelper { public static Key.Builder makeKey(Object... elements) { Key.Builder key = Key.newBuilder(); PartitionId partitionId = null; for (int pathIndex = 0; pathIndex < elements.length; pathIndex += 2) { PathElement.Builder pathElement = PathElement.newBuilder(); Object element = elements[pathIndex]; if (element instanceof Key) { Key subKey = (Key) element; if (partitionId == null) { partitionId = subKey.getPartitionId(); } else if (!partitionId.equals(subKey.getPartitionId())) { throw new IllegalArgumentException("Partition IDs did not match, found: " + partitionId + " and " + subKey.getPartitionId()); } key.addAllPath(((Key) element).getPathList()); pathIndex--; } else { String kind; try { kind = (String) element; } catch (ClassCastException e) { throw new IllegalArgumentException("Expected string or Key, got: " + element.getClass()); } pathElement.setKind(kind); if (pathIndex + 1 < elements.length) { Object value = elements[pathIndex + 1]; if (value instanceof String) { pathElement.setName((String) value); } else if (value instanceof Long) { pathElement.setId((Long) value); } else if (value instanceof Integer) { pathElement.setId((Integer) value); } else if (value instanceof Short) { pathElement.setId((Short) value); } else { throw new IllegalArgumentException( "Expected string or integer, got: " + value.getClass()); } } key.addPath(pathElement); } } if (partitionId != null && !partitionId.equals(PartitionId.getDefaultInstance())) { key.setPartitionId(partitionId); } return key; } } | DatastoreHelper { public static Key.Builder makeKey(Object... elements) { Key.Builder key = Key.newBuilder(); PartitionId partitionId = null; for (int pathIndex = 0; pathIndex < elements.length; pathIndex += 2) { PathElement.Builder pathElement = PathElement.newBuilder(); Object element = elements[pathIndex]; if (element instanceof Key) { Key subKey = (Key) element; if (partitionId == null) { partitionId = subKey.getPartitionId(); } else if (!partitionId.equals(subKey.getPartitionId())) { throw new IllegalArgumentException("Partition IDs did not match, found: " + partitionId + " and " + subKey.getPartitionId()); } key.addAllPath(((Key) element).getPathList()); pathIndex--; } else { String kind; try { kind = (String) element; } catch (ClassCastException e) { throw new IllegalArgumentException("Expected string or Key, got: " + element.getClass()); } pathElement.setKind(kind); if (pathIndex + 1 < elements.length) { Object value = elements[pathIndex + 1]; if (value instanceof String) { pathElement.setName((String) value); } else if (value instanceof Long) { pathElement.setId((Long) value); } else if (value instanceof Integer) { pathElement.setId((Integer) value); } else if (value instanceof Short) { pathElement.setId((Short) value); } else { throw new IllegalArgumentException( "Expected string or integer, got: " + value.getClass()); } } key.addPath(pathElement); } } if (partitionId != null && !partitionId.equals(PartitionId.getDefaultInstance())) { key.setPartitionId(partitionId); } return key; } private DatastoreHelper(); } | DatastoreHelper { public static Key.Builder makeKey(Object... elements) { Key.Builder key = Key.newBuilder(); PartitionId partitionId = null; for (int pathIndex = 0; pathIndex < elements.length; pathIndex += 2) { PathElement.Builder pathElement = PathElement.newBuilder(); Object element = elements[pathIndex]; if (element instanceof Key) { Key subKey = (Key) element; if (partitionId == null) { partitionId = subKey.getPartitionId(); } else if (!partitionId.equals(subKey.getPartitionId())) { throw new IllegalArgumentException("Partition IDs did not match, found: " + partitionId + " and " + subKey.getPartitionId()); } key.addAllPath(((Key) element).getPathList()); pathIndex--; } else { String kind; try { kind = (String) element; } catch (ClassCastException e) { throw new IllegalArgumentException("Expected string or Key, got: " + element.getClass()); } pathElement.setKind(kind); if (pathIndex + 1 < elements.length) { Object value = elements[pathIndex + 1]; if (value instanceof String) { pathElement.setName((String) value); } else if (value instanceof Long) { pathElement.setId((Long) value); } else if (value instanceof Integer) { pathElement.setId((Integer) value); } else if (value instanceof Short) { pathElement.setId((Short) value); } else { throw new IllegalArgumentException( "Expected string or integer, got: " + value.getClass()); } } key.addPath(pathElement); } } if (partitionId != null && !partitionId.equals(PartitionId.getDefaultInstance())) { key.setPartitionId(partitionId); } return key; } private DatastoreHelper(); static Credential getServiceAccountCredential(String serviceAccountId,
String privateKeyFile); static Credential getServiceAccountCredential(String serviceAccountId,
String privateKeyFile, Collection<String> serviceAccountScopes); static Credential getServiceAccountCredential(String serviceAccountId,
PrivateKey privateKey, Collection<String> serviceAccountScopes); static DatastoreOptions.Builder getOptionsFromEnv(); @Nullable static String getProjectIdFromComputeEngine(); static Datastore getDatastoreFromEnv(); static QuerySplitter getQuerySplitter(); static Comparator<Key> getKeyComparator(); static PropertyOrder.Builder makeOrder(String property,
PropertyOrder.Direction direction); static Filter.Builder makeAncestorFilter(Key ancestor); static Filter.Builder makeFilter(String property, PropertyFilter.Operator operator,
Value value); static Filter.Builder makeFilter(String property, PropertyFilter.Operator operator,
Value.Builder value); static Filter.Builder makeAndFilter(Filter... subfilters); static Filter.Builder makeAndFilter(Iterable<Filter> subfilters); static PropertyReference.Builder makePropertyReference(String propertyName); static Value.Builder makeValue(Iterable<Value> values); static Value.Builder makeValue(Value value1, Value value2, Value... rest); static Value.Builder makeValue(Value.Builder value1, Value.Builder value2,
Value.Builder... rest); static Value.Builder makeValue(Key key); static Value.Builder makeValue(Key.Builder key); static Value.Builder makeValue(long key); static Value.Builder makeValue(double value); static Value.Builder makeValue(boolean value); static Value.Builder makeValue(String value); static Value.Builder makeValue(Entity entity); static Value.Builder makeValue(Entity.Builder entity); static Value.Builder makeValue(ByteString blob); static Value.Builder makeValue(Date date); static Value.Builder makeValue(LatLng value); static Value.Builder makeValue(LatLng.Builder value); static Key.Builder makeKey(Object... elements); static double getDouble(Value value); static Key getKey(Value value); static ByteString getByteString(Value value); static Entity getEntity(Value value); static String getString(Value value); static boolean getBoolean(Value value); static long getLong(Value value); static long getTimestamp(Value value); static List<Value> getList(Value value); static Date toDate(Value value); static Mutation.Builder makeInsert(Entity entity); static Mutation.Builder makeUpdate(Entity entity); static Mutation.Builder makeUpsert(Entity entity); static Mutation.Builder makeDelete(Key key); } | DatastoreHelper { public static Key.Builder makeKey(Object... elements) { Key.Builder key = Key.newBuilder(); PartitionId partitionId = null; for (int pathIndex = 0; pathIndex < elements.length; pathIndex += 2) { PathElement.Builder pathElement = PathElement.newBuilder(); Object element = elements[pathIndex]; if (element instanceof Key) { Key subKey = (Key) element; if (partitionId == null) { partitionId = subKey.getPartitionId(); } else if (!partitionId.equals(subKey.getPartitionId())) { throw new IllegalArgumentException("Partition IDs did not match, found: " + partitionId + " and " + subKey.getPartitionId()); } key.addAllPath(((Key) element).getPathList()); pathIndex--; } else { String kind; try { kind = (String) element; } catch (ClassCastException e) { throw new IllegalArgumentException("Expected string or Key, got: " + element.getClass()); } pathElement.setKind(kind); if (pathIndex + 1 < elements.length) { Object value = elements[pathIndex + 1]; if (value instanceof String) { pathElement.setName((String) value); } else if (value instanceof Long) { pathElement.setId((Long) value); } else if (value instanceof Integer) { pathElement.setId((Integer) value); } else if (value instanceof Short) { pathElement.setId((Short) value); } else { throw new IllegalArgumentException( "Expected string or integer, got: " + value.getClass()); } } key.addPath(pathElement); } } if (partitionId != null && !partitionId.equals(PartitionId.getDefaultInstance())) { key.setPartitionId(partitionId); } return key; } private DatastoreHelper(); static Credential getServiceAccountCredential(String serviceAccountId,
String privateKeyFile); static Credential getServiceAccountCredential(String serviceAccountId,
String privateKeyFile, Collection<String> serviceAccountScopes); static Credential getServiceAccountCredential(String serviceAccountId,
PrivateKey privateKey, Collection<String> serviceAccountScopes); static DatastoreOptions.Builder getOptionsFromEnv(); @Nullable static String getProjectIdFromComputeEngine(); static Datastore getDatastoreFromEnv(); static QuerySplitter getQuerySplitter(); static Comparator<Key> getKeyComparator(); static PropertyOrder.Builder makeOrder(String property,
PropertyOrder.Direction direction); static Filter.Builder makeAncestorFilter(Key ancestor); static Filter.Builder makeFilter(String property, PropertyFilter.Operator operator,
Value value); static Filter.Builder makeFilter(String property, PropertyFilter.Operator operator,
Value.Builder value); static Filter.Builder makeAndFilter(Filter... subfilters); static Filter.Builder makeAndFilter(Iterable<Filter> subfilters); static PropertyReference.Builder makePropertyReference(String propertyName); static Value.Builder makeValue(Iterable<Value> values); static Value.Builder makeValue(Value value1, Value value2, Value... rest); static Value.Builder makeValue(Value.Builder value1, Value.Builder value2,
Value.Builder... rest); static Value.Builder makeValue(Key key); static Value.Builder makeValue(Key.Builder key); static Value.Builder makeValue(long key); static Value.Builder makeValue(double value); static Value.Builder makeValue(boolean value); static Value.Builder makeValue(String value); static Value.Builder makeValue(Entity entity); static Value.Builder makeValue(Entity.Builder entity); static Value.Builder makeValue(ByteString blob); static Value.Builder makeValue(Date date); static Value.Builder makeValue(LatLng value); static Value.Builder makeValue(LatLng.Builder value); static Key.Builder makeKey(Object... elements); static double getDouble(Value value); static Key getKey(Value value); static ByteString getByteString(Value value); static Entity getEntity(Value value); static String getString(Value value); static boolean getBoolean(Value value); static long getLong(Value value); static long getTimestamp(Value value); static List<Value> getList(Value value); static Date toDate(Value value); static Mutation.Builder makeInsert(Entity entity); static Mutation.Builder makeUpdate(Entity entity); static Mutation.Builder makeUpsert(Entity entity); static Mutation.Builder makeDelete(Key key); static final String SCATTER_PROPERTY_NAME; static final String KEY_PROPERTY_NAME; static final String PROJECT_ID_ENV_VAR; static final String LOCAL_HOST_ENV_VAR; static final String SERVICE_ACCOUNT_ENV_VAR; static final String PRIVATE_KEY_FILE_ENV_VAR; } |
@Test public void makeClient_WithCredentialTransport() { NetHttpTransport credTransport = new NetHttpTransport(); NetHttpTransport transport = new NetHttpTransport(); GoogleCredential credential = new GoogleCredential.Builder() .setTransport(credTransport) .build(); DatastoreOptions options = new DatastoreOptions.Builder() .projectId(PROJECT_ID) .credential(credential) .transport(transport) .build(); HttpRequestFactory f = factory.makeClient(options); assertNotSame(credTransport, f.getTransport()); assertEquals(transport, f.getTransport()); } | public HttpRequestFactory makeClient(DatastoreOptions options) { Credential credential = options.getCredential(); HttpTransport transport = options.getTransport(); if (transport == null) { transport = credential == null ? new NetHttpTransport() : credential.getTransport(); transport = transport == null ? new NetHttpTransport() : transport; } return transport.createRequestFactory(credential); } | DatastoreFactory { public HttpRequestFactory makeClient(DatastoreOptions options) { Credential credential = options.getCredential(); HttpTransport transport = options.getTransport(); if (transport == null) { transport = credential == null ? new NetHttpTransport() : credential.getTransport(); transport = transport == null ? new NetHttpTransport() : transport; } return transport.createRequestFactory(credential); } } | DatastoreFactory { public HttpRequestFactory makeClient(DatastoreOptions options) { Credential credential = options.getCredential(); HttpTransport transport = options.getTransport(); if (transport == null) { transport = credential == null ? new NetHttpTransport() : credential.getTransport(); transport = transport == null ? new NetHttpTransport() : transport; } return transport.createRequestFactory(credential); } } | DatastoreFactory { public HttpRequestFactory makeClient(DatastoreOptions options) { Credential credential = options.getCredential(); HttpTransport transport = options.getTransport(); if (transport == null) { transport = credential == null ? new NetHttpTransport() : credential.getTransport(); transport = transport == null ? new NetHttpTransport() : transport; } return transport.createRequestFactory(credential); } static DatastoreFactory get(); Datastore create(DatastoreOptions options); HttpRequestFactory makeClient(DatastoreOptions options); static void logMethodCalls(); } | DatastoreFactory { public HttpRequestFactory makeClient(DatastoreOptions options) { Credential credential = options.getCredential(); HttpTransport transport = options.getTransport(); if (transport == null) { transport = credential == null ? new NetHttpTransport() : credential.getTransport(); transport = transport == null ? new NetHttpTransport() : transport; } return transport.createRequestFactory(credential); } static DatastoreFactory get(); Datastore create(DatastoreOptions options); HttpRequestFactory makeClient(DatastoreOptions options); static void logMethodCalls(); static final String VERSION; static final String DEFAULT_HOST; } |
@Test public void testException() { Status statusProto = Status.newBuilder() .setCode(Code.UNAUTHENTICATED_VALUE) .setMessage("The request does not have valid authentication credentials.") .build(); DatastoreException exception = RemoteRpc.makeException("url", METHOD_NAME, new ByteArrayInputStream(statusProto.toByteArray()), "application/x-protobuf", Charsets.UTF_8, new RuntimeException(), 401); assertEquals(Code.UNAUTHENTICATED, exception.getCode()); assertEquals("The request does not have valid authentication credentials.", exception.getMessage()); assertEquals(METHOD_NAME, exception.getMethodName()); } | public static DatastoreException makeException(String url, String methodName, Code code, String message, Throwable cause) { logger.fine("remote datastore call " + methodName + " against " + url + " failed: " + message); return new DatastoreException(methodName, code, message, cause); } | RemoteRpc { public static DatastoreException makeException(String url, String methodName, Code code, String message, Throwable cause) { logger.fine("remote datastore call " + methodName + " against " + url + " failed: " + message); return new DatastoreException(methodName, code, message, cause); } } | RemoteRpc { public static DatastoreException makeException(String url, String methodName, Code code, String message, Throwable cause) { logger.fine("remote datastore call " + methodName + " against " + url + " failed: " + message); return new DatastoreException(methodName, code, message, cause); } RemoteRpc(HttpRequestFactory client, HttpRequestInitializer initializer, String url); } | RemoteRpc { public static DatastoreException makeException(String url, String methodName, Code code, String message, Throwable cause) { logger.fine("remote datastore call " + methodName + " against " + url + " failed: " + message); return new DatastoreException(methodName, code, message, cause); } RemoteRpc(HttpRequestFactory client, HttpRequestInitializer initializer, String url); InputStream call(String methodName, MessageLite request); String getUrl(); static DatastoreException makeException(String url, String methodName, Code code,
String message, Throwable cause); } | RemoteRpc { public static DatastoreException makeException(String url, String methodName, Code code, String message, Throwable cause) { logger.fine("remote datastore call " + methodName + " against " + url + " failed: " + message); return new DatastoreException(methodName, code, message, cause); } RemoteRpc(HttpRequestFactory client, HttpRequestInitializer initializer, String url); InputStream call(String methodName, MessageLite request); String getUrl(); static DatastoreException makeException(String url, String methodName, Code code,
String message, Throwable cause); } |
@Test public void testInvalidProtoException() { DatastoreException exception = RemoteRpc.makeException("url", METHOD_NAME, new ByteArrayInputStream("<invalid proto>".getBytes()), "application/x-protobuf", Charsets.UTF_8, new RuntimeException(), 401); assertEquals(Code.INTERNAL, exception.getCode()); assertEquals("Unable to parse Status protocol buffer: HTTP status code was 401.", exception.getMessage()); assertEquals(METHOD_NAME, exception.getMethodName()); } | public static DatastoreException makeException(String url, String methodName, Code code, String message, Throwable cause) { logger.fine("remote datastore call " + methodName + " against " + url + " failed: " + message); return new DatastoreException(methodName, code, message, cause); } | RemoteRpc { public static DatastoreException makeException(String url, String methodName, Code code, String message, Throwable cause) { logger.fine("remote datastore call " + methodName + " against " + url + " failed: " + message); return new DatastoreException(methodName, code, message, cause); } } | RemoteRpc { public static DatastoreException makeException(String url, String methodName, Code code, String message, Throwable cause) { logger.fine("remote datastore call " + methodName + " against " + url + " failed: " + message); return new DatastoreException(methodName, code, message, cause); } RemoteRpc(HttpRequestFactory client, HttpRequestInitializer initializer, String url); } | RemoteRpc { public static DatastoreException makeException(String url, String methodName, Code code, String message, Throwable cause) { logger.fine("remote datastore call " + methodName + " against " + url + " failed: " + message); return new DatastoreException(methodName, code, message, cause); } RemoteRpc(HttpRequestFactory client, HttpRequestInitializer initializer, String url); InputStream call(String methodName, MessageLite request); String getUrl(); static DatastoreException makeException(String url, String methodName, Code code,
String message, Throwable cause); } | RemoteRpc { public static DatastoreException makeException(String url, String methodName, Code code, String message, Throwable cause) { logger.fine("remote datastore call " + methodName + " against " + url + " failed: " + message); return new DatastoreException(methodName, code, message, cause); } RemoteRpc(HttpRequestFactory client, HttpRequestInitializer initializer, String url); InputStream call(String methodName, MessageLite request); String getUrl(); static DatastoreException makeException(String url, String methodName, Code code,
String message, Throwable cause); } |
@Test public void testEmptyProtoException() { Status statusProto = Status.newBuilder().build(); DatastoreException exception = RemoteRpc.makeException( "url", METHOD_NAME, new ByteArrayInputStream(statusProto.toByteArray()), "application/x-protobuf", Charsets.UTF_8, new RuntimeException(), 404); assertEquals(Code.INTERNAL, exception.getCode()); assertEquals( "Unexpected OK error code with HTTP status code of 404. Message: .", exception.getMessage()); assertEquals(METHOD_NAME, exception.getMethodName()); } | public static DatastoreException makeException(String url, String methodName, Code code, String message, Throwable cause) { logger.fine("remote datastore call " + methodName + " against " + url + " failed: " + message); return new DatastoreException(methodName, code, message, cause); } | RemoteRpc { public static DatastoreException makeException(String url, String methodName, Code code, String message, Throwable cause) { logger.fine("remote datastore call " + methodName + " against " + url + " failed: " + message); return new DatastoreException(methodName, code, message, cause); } } | RemoteRpc { public static DatastoreException makeException(String url, String methodName, Code code, String message, Throwable cause) { logger.fine("remote datastore call " + methodName + " against " + url + " failed: " + message); return new DatastoreException(methodName, code, message, cause); } RemoteRpc(HttpRequestFactory client, HttpRequestInitializer initializer, String url); } | RemoteRpc { public static DatastoreException makeException(String url, String methodName, Code code, String message, Throwable cause) { logger.fine("remote datastore call " + methodName + " against " + url + " failed: " + message); return new DatastoreException(methodName, code, message, cause); } RemoteRpc(HttpRequestFactory client, HttpRequestInitializer initializer, String url); InputStream call(String methodName, MessageLite request); String getUrl(); static DatastoreException makeException(String url, String methodName, Code code,
String message, Throwable cause); } | RemoteRpc { public static DatastoreException makeException(String url, String methodName, Code code, String message, Throwable cause) { logger.fine("remote datastore call " + methodName + " against " + url + " failed: " + message); return new DatastoreException(methodName, code, message, cause); } RemoteRpc(HttpRequestFactory client, HttpRequestInitializer initializer, String url); InputStream call(String methodName, MessageLite request); String getUrl(); static DatastoreException makeException(String url, String methodName, Code code,
String message, Throwable cause); } |
@Test public void testEmptyProtoExceptionUnauthenticated() { Status statusProto = Status.newBuilder().build(); DatastoreException exception = RemoteRpc.makeException( "url", METHOD_NAME, new ByteArrayInputStream(statusProto.toByteArray()), "application/x-protobuf", Charsets.UTF_8, new RuntimeException(), 401); assertEquals(Code.UNAUTHENTICATED, exception.getCode()); assertEquals("Unauthenticated.", exception.getMessage()); assertEquals(METHOD_NAME, exception.getMethodName()); } | public static DatastoreException makeException(String url, String methodName, Code code, String message, Throwable cause) { logger.fine("remote datastore call " + methodName + " against " + url + " failed: " + message); return new DatastoreException(methodName, code, message, cause); } | RemoteRpc { public static DatastoreException makeException(String url, String methodName, Code code, String message, Throwable cause) { logger.fine("remote datastore call " + methodName + " against " + url + " failed: " + message); return new DatastoreException(methodName, code, message, cause); } } | RemoteRpc { public static DatastoreException makeException(String url, String methodName, Code code, String message, Throwable cause) { logger.fine("remote datastore call " + methodName + " against " + url + " failed: " + message); return new DatastoreException(methodName, code, message, cause); } RemoteRpc(HttpRequestFactory client, HttpRequestInitializer initializer, String url); } | RemoteRpc { public static DatastoreException makeException(String url, String methodName, Code code, String message, Throwable cause) { logger.fine("remote datastore call " + methodName + " against " + url + " failed: " + message); return new DatastoreException(methodName, code, message, cause); } RemoteRpc(HttpRequestFactory client, HttpRequestInitializer initializer, String url); InputStream call(String methodName, MessageLite request); String getUrl(); static DatastoreException makeException(String url, String methodName, Code code,
String message, Throwable cause); } | RemoteRpc { public static DatastoreException makeException(String url, String methodName, Code code, String message, Throwable cause) { logger.fine("remote datastore call " + methodName + " against " + url + " failed: " + message); return new DatastoreException(methodName, code, message, cause); } RemoteRpc(HttpRequestFactory client, HttpRequestInitializer initializer, String url); InputStream call(String methodName, MessageLite request); String getUrl(); static DatastoreException makeException(String url, String methodName, Code code,
String message, Throwable cause); } |
@Test public void testPlainTextException() { DatastoreException exception = RemoteRpc.makeException("url", METHOD_NAME, new ByteArrayInputStream("Text Error".getBytes()), "text/plain", Charsets.UTF_8, new RuntimeException(), 401); assertEquals(Code.INTERNAL, exception.getCode()); assertEquals( "Non-protobuf error: Text Error. HTTP status code was 401.", exception.getMessage()); assertEquals(METHOD_NAME, exception.getMethodName()); } | public static DatastoreException makeException(String url, String methodName, Code code, String message, Throwable cause) { logger.fine("remote datastore call " + methodName + " against " + url + " failed: " + message); return new DatastoreException(methodName, code, message, cause); } | RemoteRpc { public static DatastoreException makeException(String url, String methodName, Code code, String message, Throwable cause) { logger.fine("remote datastore call " + methodName + " against " + url + " failed: " + message); return new DatastoreException(methodName, code, message, cause); } } | RemoteRpc { public static DatastoreException makeException(String url, String methodName, Code code, String message, Throwable cause) { logger.fine("remote datastore call " + methodName + " against " + url + " failed: " + message); return new DatastoreException(methodName, code, message, cause); } RemoteRpc(HttpRequestFactory client, HttpRequestInitializer initializer, String url); } | RemoteRpc { public static DatastoreException makeException(String url, String methodName, Code code, String message, Throwable cause) { logger.fine("remote datastore call " + methodName + " against " + url + " failed: " + message); return new DatastoreException(methodName, code, message, cause); } RemoteRpc(HttpRequestFactory client, HttpRequestInitializer initializer, String url); InputStream call(String methodName, MessageLite request); String getUrl(); static DatastoreException makeException(String url, String methodName, Code code,
String message, Throwable cause); } | RemoteRpc { public static DatastoreException makeException(String url, String methodName, Code code, String message, Throwable cause) { logger.fine("remote datastore call " + methodName + " against " + url + " failed: " + message); return new DatastoreException(methodName, code, message, cause); } RemoteRpc(HttpRequestFactory client, HttpRequestInitializer initializer, String url); InputStream call(String methodName, MessageLite request); String getUrl(); static DatastoreException makeException(String url, String methodName, Code code,
String message, Throwable cause); } |
@Test public void testGzip() throws IOException, DatastoreException { BeginTransactionResponse response = newBeginTransactionResponse(); InjectedTestValues injectedTestValues = new InjectedTestValues(gzip(response), new byte[1], true); RemoteRpc rpc = newRemoteRpc(injectedTestValues); InputStream is = rpc.call("beginTransaction", BeginTransactionResponse.getDefaultInstance()); BeginTransactionResponse parsedResponse = BeginTransactionResponse.parseFrom(is); is.close(); assertEquals(response, parsedResponse); assertEquals(-1, injectedTestValues.inputStream.read()); } | public InputStream call(String methodName, MessageLite request) throws DatastoreException { logger.fine("remote datastore call " + methodName); long startTime = System.currentTimeMillis(); try { HttpResponse httpResponse; try { rpcCount.incrementAndGet(); ProtoHttpContent payload = new ProtoHttpContent(request); HttpRequest httpRequest = client.buildPostRequest(resolveURL(methodName), payload); httpRequest.getHeaders().put(API_FORMAT_VERSION_HEADER, API_FORMAT_VERSION); httpRequest.setThrowExceptionOnExecuteError(false); httpRequest.setReadTimeout(65 * 1000); if (initializer != null) { initializer.initialize(httpRequest); } httpResponse = httpRequest.execute(); if (!httpResponse.isSuccessStatusCode()) { try (InputStream content = httpResponse.getContent()) { throw makeException(url, methodName, content, httpResponse.getContentType(), httpResponse.getContentCharset(), null, httpResponse.getStatusCode()); } } return httpResponse.getContent(); } catch (SocketTimeoutException e) { throw makeException(url, methodName, Code.DEADLINE_EXCEEDED, "Deadline exceeded", e); } catch (IOException e) { throw makeException(url, methodName, Code.UNAVAILABLE, "I/O error", e); } } finally { long elapsedTime = System.currentTimeMillis() - startTime; logger.fine("remote datastore call " + methodName + " took " + elapsedTime + " ms"); } } | RemoteRpc { public InputStream call(String methodName, MessageLite request) throws DatastoreException { logger.fine("remote datastore call " + methodName); long startTime = System.currentTimeMillis(); try { HttpResponse httpResponse; try { rpcCount.incrementAndGet(); ProtoHttpContent payload = new ProtoHttpContent(request); HttpRequest httpRequest = client.buildPostRequest(resolveURL(methodName), payload); httpRequest.getHeaders().put(API_FORMAT_VERSION_HEADER, API_FORMAT_VERSION); httpRequest.setThrowExceptionOnExecuteError(false); httpRequest.setReadTimeout(65 * 1000); if (initializer != null) { initializer.initialize(httpRequest); } httpResponse = httpRequest.execute(); if (!httpResponse.isSuccessStatusCode()) { try (InputStream content = httpResponse.getContent()) { throw makeException(url, methodName, content, httpResponse.getContentType(), httpResponse.getContentCharset(), null, httpResponse.getStatusCode()); } } return httpResponse.getContent(); } catch (SocketTimeoutException e) { throw makeException(url, methodName, Code.DEADLINE_EXCEEDED, "Deadline exceeded", e); } catch (IOException e) { throw makeException(url, methodName, Code.UNAVAILABLE, "I/O error", e); } } finally { long elapsedTime = System.currentTimeMillis() - startTime; logger.fine("remote datastore call " + methodName + " took " + elapsedTime + " ms"); } } } | RemoteRpc { public InputStream call(String methodName, MessageLite request) throws DatastoreException { logger.fine("remote datastore call " + methodName); long startTime = System.currentTimeMillis(); try { HttpResponse httpResponse; try { rpcCount.incrementAndGet(); ProtoHttpContent payload = new ProtoHttpContent(request); HttpRequest httpRequest = client.buildPostRequest(resolveURL(methodName), payload); httpRequest.getHeaders().put(API_FORMAT_VERSION_HEADER, API_FORMAT_VERSION); httpRequest.setThrowExceptionOnExecuteError(false); httpRequest.setReadTimeout(65 * 1000); if (initializer != null) { initializer.initialize(httpRequest); } httpResponse = httpRequest.execute(); if (!httpResponse.isSuccessStatusCode()) { try (InputStream content = httpResponse.getContent()) { throw makeException(url, methodName, content, httpResponse.getContentType(), httpResponse.getContentCharset(), null, httpResponse.getStatusCode()); } } return httpResponse.getContent(); } catch (SocketTimeoutException e) { throw makeException(url, methodName, Code.DEADLINE_EXCEEDED, "Deadline exceeded", e); } catch (IOException e) { throw makeException(url, methodName, Code.UNAVAILABLE, "I/O error", e); } } finally { long elapsedTime = System.currentTimeMillis() - startTime; logger.fine("remote datastore call " + methodName + " took " + elapsedTime + " ms"); } } RemoteRpc(HttpRequestFactory client, HttpRequestInitializer initializer, String url); } | RemoteRpc { public InputStream call(String methodName, MessageLite request) throws DatastoreException { logger.fine("remote datastore call " + methodName); long startTime = System.currentTimeMillis(); try { HttpResponse httpResponse; try { rpcCount.incrementAndGet(); ProtoHttpContent payload = new ProtoHttpContent(request); HttpRequest httpRequest = client.buildPostRequest(resolveURL(methodName), payload); httpRequest.getHeaders().put(API_FORMAT_VERSION_HEADER, API_FORMAT_VERSION); httpRequest.setThrowExceptionOnExecuteError(false); httpRequest.setReadTimeout(65 * 1000); if (initializer != null) { initializer.initialize(httpRequest); } httpResponse = httpRequest.execute(); if (!httpResponse.isSuccessStatusCode()) { try (InputStream content = httpResponse.getContent()) { throw makeException(url, methodName, content, httpResponse.getContentType(), httpResponse.getContentCharset(), null, httpResponse.getStatusCode()); } } return httpResponse.getContent(); } catch (SocketTimeoutException e) { throw makeException(url, methodName, Code.DEADLINE_EXCEEDED, "Deadline exceeded", e); } catch (IOException e) { throw makeException(url, methodName, Code.UNAVAILABLE, "I/O error", e); } } finally { long elapsedTime = System.currentTimeMillis() - startTime; logger.fine("remote datastore call " + methodName + " took " + elapsedTime + " ms"); } } RemoteRpc(HttpRequestFactory client, HttpRequestInitializer initializer, String url); InputStream call(String methodName, MessageLite request); String getUrl(); static DatastoreException makeException(String url, String methodName, Code code,
String message, Throwable cause); } | RemoteRpc { public InputStream call(String methodName, MessageLite request) throws DatastoreException { logger.fine("remote datastore call " + methodName); long startTime = System.currentTimeMillis(); try { HttpResponse httpResponse; try { rpcCount.incrementAndGet(); ProtoHttpContent payload = new ProtoHttpContent(request); HttpRequest httpRequest = client.buildPostRequest(resolveURL(methodName), payload); httpRequest.getHeaders().put(API_FORMAT_VERSION_HEADER, API_FORMAT_VERSION); httpRequest.setThrowExceptionOnExecuteError(false); httpRequest.setReadTimeout(65 * 1000); if (initializer != null) { initializer.initialize(httpRequest); } httpResponse = httpRequest.execute(); if (!httpResponse.isSuccessStatusCode()) { try (InputStream content = httpResponse.getContent()) { throw makeException(url, methodName, content, httpResponse.getContentType(), httpResponse.getContentCharset(), null, httpResponse.getStatusCode()); } } return httpResponse.getContent(); } catch (SocketTimeoutException e) { throw makeException(url, methodName, Code.DEADLINE_EXCEEDED, "Deadline exceeded", e); } catch (IOException e) { throw makeException(url, methodName, Code.UNAVAILABLE, "I/O error", e); } } finally { long elapsedTime = System.currentTimeMillis() - startTime; logger.fine("remote datastore call " + methodName + " took " + elapsedTime + " ms"); } } RemoteRpc(HttpRequestFactory client, HttpRequestInitializer initializer, String url); InputStream call(String methodName, MessageLite request); String getUrl(); static DatastoreException makeException(String url, String methodName, Code code,
String message, Throwable cause); } |
@Test public void testMustacheTagPattern() { String text = "{{foo }} and {{#bar}}...{{/bar}}"; Pattern tagPattern = Patterns .newMustacheTagPattern(MustacheEngineBuilder.newBuilder() .build().getConfiguration()); Matcher matcher = tagPattern.matcher(text); StringBuffer result = new StringBuffer(); int occurences = 0; while (matcher.find()) { System.out.println(matcher.group(0)); matcher.appendReplacement(result, "FOUND"); occurences++; } matcher.appendTail(result); assertEquals(3, occurences); assertEquals("FOUND and FOUND...FOUND", result.toString()); } | public static Pattern newMustacheTagPattern(Configuration configuration) { StringBuilder regex = new StringBuilder(); regex.append(Pattern.quote(configuration .getStringPropertyValue(EngineConfigurationKey.START_DELIMITER))); regex.append(".*?"); regex.append(Pattern.quote(configuration .getStringPropertyValue(EngineConfigurationKey.END_DELIMITER))); return Pattern.compile(regex.toString()); } | Patterns { public static Pattern newMustacheTagPattern(Configuration configuration) { StringBuilder regex = new StringBuilder(); regex.append(Pattern.quote(configuration .getStringPropertyValue(EngineConfigurationKey.START_DELIMITER))); regex.append(".*?"); regex.append(Pattern.quote(configuration .getStringPropertyValue(EngineConfigurationKey.END_DELIMITER))); return Pattern.compile(regex.toString()); } } | Patterns { public static Pattern newMustacheTagPattern(Configuration configuration) { StringBuilder regex = new StringBuilder(); regex.append(Pattern.quote(configuration .getStringPropertyValue(EngineConfigurationKey.START_DELIMITER))); regex.append(".*?"); regex.append(Pattern.quote(configuration .getStringPropertyValue(EngineConfigurationKey.END_DELIMITER))); return Pattern.compile(regex.toString()); } private Patterns(); } | Patterns { public static Pattern newMustacheTagPattern(Configuration configuration) { StringBuilder regex = new StringBuilder(); regex.append(Pattern.quote(configuration .getStringPropertyValue(EngineConfigurationKey.START_DELIMITER))); regex.append(".*?"); regex.append(Pattern.quote(configuration .getStringPropertyValue(EngineConfigurationKey.END_DELIMITER))); return Pattern.compile(regex.toString()); } private Patterns(); static Pattern newMustacheTagPattern(Configuration configuration); static Pattern newSetDelimitersContentPattern(); static Pattern newHelperIntegerLiteralPattern(); static Pattern newHelperLongLiteralPattern(); } | Patterns { public static Pattern newMustacheTagPattern(Configuration configuration) { StringBuilder regex = new StringBuilder(); regex.append(Pattern.quote(configuration .getStringPropertyValue(EngineConfigurationKey.START_DELIMITER))); regex.append(".*?"); regex.append(Pattern.quote(configuration .getStringPropertyValue(EngineConfigurationKey.END_DELIMITER))); return Pattern.compile(regex.toString()); } private Patterns(); static Pattern newMustacheTagPattern(Configuration configuration); static Pattern newSetDelimitersContentPattern(); static Pattern newHelperIntegerLiteralPattern(); static Pattern newHelperLongLiteralPattern(); } |
@Test public void testToString() throws IOException { assertEquals("foo", IOUtils.toString(new StringReader("foo"))); assertEquals("foo", IOUtils.toString(new StringReader("foo"), 1)); } | public static String toString(Reader input) throws IOException { return toString(input, DEFAULT_BUFFER_SIZE); } | IOUtils { public static String toString(Reader input) throws IOException { return toString(input, DEFAULT_BUFFER_SIZE); } } | IOUtils { public static String toString(Reader input) throws IOException { return toString(input, DEFAULT_BUFFER_SIZE); } private IOUtils(); } | IOUtils { public static String toString(Reader input) throws IOException { return toString(input, DEFAULT_BUFFER_SIZE); } private IOUtils(); static String toString(Reader input); static String toString(Reader input, int bufferSize); static String toString(Reader input, int bufferSize, boolean close); static void copy(Readable in, Appendable out, int bufferSize); } | IOUtils { public static String toString(Reader input) throws IOException { return toString(input, DEFAULT_BUFFER_SIZE); } private IOUtils(); static String toString(Reader input); static String toString(Reader input, int bufferSize); static String toString(Reader input, int bufferSize, boolean close); static void copy(Readable in, Appendable out, int bufferSize); } |
@Test public void testIsFalsy() { assertTrue(Checker.isFalsy(null)); assertTrue(Checker.isFalsy(false)); assertTrue(Checker.isFalsy(new String[] {})); assertTrue(Checker.isFalsy(Collections.emptyList())); assertTrue(Checker.isFalsy("")); assertTrue(Checker.isFalsy(new StringBuilder())); assertTrue(Checker.isFalsy(0)); assertTrue(Checker.isFalsy(BigDecimal.ZERO)); assertTrue(Checker.isFalsy(new BigDecimal("0.000"))); assertFalse(Checker.isFalsy(Boolean.TRUE)); assertFalse(Checker.isFalsy(new Object[] { "foo" })); assertFalse(Checker.isFalsy(Collections.singleton("foo"))); assertFalse(Checker.isFalsy("foo")); assertFalse(Checker.isFalsy(new StringBuilder().append("foo"))); assertFalse(Checker.isFalsy(-10)); assertFalse(Checker.isFalsy(BigDecimal.TEN)); assertFalse(Checker.isFalsy(0.2)); assertFalse(Checker.isFalsy(new BigDecimal("-0.01"))); } | @SuppressWarnings("rawtypes") public static boolean isFalsy(Object value) { if (value == null) { return true; } else if (value instanceof Boolean) { return !(Boolean) value; } else if (value instanceof Collection) { return ((Collection) value).isEmpty(); } else if (value instanceof Iterable) { return !((Iterable) value).iterator().hasNext(); } else if (value.getClass().isArray()) { return Array.getLength(value) == 0; } else if (value instanceof CharSequence) { return ((CharSequence) value).length() == 0; } else if (value instanceof Number) { return isZero((Number) value); } return false; } | Checker { @SuppressWarnings("rawtypes") public static boolean isFalsy(Object value) { if (value == null) { return true; } else if (value instanceof Boolean) { return !(Boolean) value; } else if (value instanceof Collection) { return ((Collection) value).isEmpty(); } else if (value instanceof Iterable) { return !((Iterable) value).iterator().hasNext(); } else if (value.getClass().isArray()) { return Array.getLength(value) == 0; } else if (value instanceof CharSequence) { return ((CharSequence) value).length() == 0; } else if (value instanceof Number) { return isZero((Number) value); } return false; } } | Checker { @SuppressWarnings("rawtypes") public static boolean isFalsy(Object value) { if (value == null) { return true; } else if (value instanceof Boolean) { return !(Boolean) value; } else if (value instanceof Collection) { return ((Collection) value).isEmpty(); } else if (value instanceof Iterable) { return !((Iterable) value).iterator().hasNext(); } else if (value.getClass().isArray()) { return Array.getLength(value) == 0; } else if (value instanceof CharSequence) { return ((CharSequence) value).length() == 0; } else if (value instanceof Number) { return isZero((Number) value); } return false; } private Checker(); } | Checker { @SuppressWarnings("rawtypes") public static boolean isFalsy(Object value) { if (value == null) { return true; } else if (value instanceof Boolean) { return !(Boolean) value; } else if (value instanceof Collection) { return ((Collection) value).isEmpty(); } else if (value instanceof Iterable) { return !((Iterable) value).iterator().hasNext(); } else if (value.getClass().isArray()) { return Array.getLength(value) == 0; } else if (value instanceof CharSequence) { return ((CharSequence) value).length() == 0; } else if (value instanceof Number) { return isZero((Number) value); } return false; } private Checker(); static void checkArgument(boolean condition, String errorMessage); static void checkArgumentsNotNull(Object... arguments); static void checkArgumentNotNull(Object argument); static void checkArgumentNotEmpty(String argument); static boolean isNullOrEmpty(Collection<?> collection); static boolean isNullOrEmpty(Map<?, ?> map); @SuppressWarnings("rawtypes") static boolean isFalsy(Object value); } | Checker { @SuppressWarnings("rawtypes") public static boolean isFalsy(Object value) { if (value == null) { return true; } else if (value instanceof Boolean) { return !(Boolean) value; } else if (value instanceof Collection) { return ((Collection) value).isEmpty(); } else if (value instanceof Iterable) { return !((Iterable) value).iterator().hasNext(); } else if (value.getClass().isArray()) { return Array.getLength(value) == 0; } else if (value instanceof CharSequence) { return ((CharSequence) value).length() == 0; } else if (value instanceof Number) { return isZero((Number) value); } return false; } private Checker(); static void checkArgument(boolean condition, String errorMessage); static void checkArgumentsNotNull(Object... arguments); static void checkArgumentNotNull(Object argument); static void checkArgumentNotEmpty(String argument); static boolean isNullOrEmpty(Collection<?> collection); static boolean isNullOrEmpty(Map<?, ?> map); @SuppressWarnings("rawtypes") static boolean isFalsy(Object value); } |
@Test public void testResolution() { ReflectionResolver resolver = new ReflectionResolver(); MustacheEngineBuilder.newBuilder().omitServiceLoaderConfigurationExtensions().addResolver(resolver).build(); Hammer hammer = new Hammer(); assertNull(resolver.resolve(null, "whatever", null)); assertNotNull(resolver.resolve(hammer, "age", null)); assertEquals(10, resolver.resolve(hammer, "age", null)); assertNull(resolver.resolve(hammer, "getAgeForName", null)); } | @Override public Object resolve(Object contextObject, String name, ResolutionContext context) { if (contextObject == null) { return null; } MemberWrapper wrapper; MemberKey key = MemberKey.newInstance(contextObject, name); if (memberCache != null) { wrapper = memberCache.get(key).orElse(null); } else { wrapper = findWrapper(key).orElse(null); } if (wrapper == null) { return null; } try { return wrapper.getValue(contextObject); } catch (Exception e) { throw new MustacheException( MustacheProblem.RENDER_REFLECT_INVOCATION_ERROR, e); } } | ReflectionResolver extends AbstractResolver { @Override public Object resolve(Object contextObject, String name, ResolutionContext context) { if (contextObject == null) { return null; } MemberWrapper wrapper; MemberKey key = MemberKey.newInstance(contextObject, name); if (memberCache != null) { wrapper = memberCache.get(key).orElse(null); } else { wrapper = findWrapper(key).orElse(null); } if (wrapper == null) { return null; } try { return wrapper.getValue(contextObject); } catch (Exception e) { throw new MustacheException( MustacheProblem.RENDER_REFLECT_INVOCATION_ERROR, e); } } } | ReflectionResolver extends AbstractResolver { @Override public Object resolve(Object contextObject, String name, ResolutionContext context) { if (contextObject == null) { return null; } MemberWrapper wrapper; MemberKey key = MemberKey.newInstance(contextObject, name); if (memberCache != null) { wrapper = memberCache.get(key).orElse(null); } else { wrapper = findWrapper(key).orElse(null); } if (wrapper == null) { return null; } try { return wrapper.getValue(contextObject); } catch (Exception e) { throw new MustacheException( MustacheProblem.RENDER_REFLECT_INVOCATION_ERROR, e); } } ReflectionResolver(); ReflectionResolver(int priority); } | ReflectionResolver extends AbstractResolver { @Override public Object resolve(Object contextObject, String name, ResolutionContext context) { if (contextObject == null) { return null; } MemberWrapper wrapper; MemberKey key = MemberKey.newInstance(contextObject, name); if (memberCache != null) { wrapper = memberCache.get(key).orElse(null); } else { wrapper = findWrapper(key).orElse(null); } if (wrapper == null) { return null; } try { return wrapper.getValue(contextObject); } catch (Exception e) { throw new MustacheException( MustacheProblem.RENDER_REFLECT_INVOCATION_ERROR, e); } } ReflectionResolver(); ReflectionResolver(int priority); @Override Object resolve(Object contextObject, String name,
ResolutionContext context); @Override Hint createHint(Object contextObject, String name,
ResolutionContext context); @Override void init(); @Override Set<ConfigurationKey> getConfigurationKeys(); void invalidateMemberCache(Predicate<Class<?>> predicate); } | ReflectionResolver extends AbstractResolver { @Override public Object resolve(Object contextObject, String name, ResolutionContext context) { if (contextObject == null) { return null; } MemberWrapper wrapper; MemberKey key = MemberKey.newInstance(contextObject, name); if (memberCache != null) { wrapper = memberCache.get(key).orElse(null); } else { wrapper = findWrapper(key).orElse(null); } if (wrapper == null) { return null; } try { return wrapper.getValue(contextObject); } catch (Exception e) { throw new MustacheException( MustacheProblem.RENDER_REFLECT_INVOCATION_ERROR, e); } } ReflectionResolver(); ReflectionResolver(int priority); @Override Object resolve(Object contextObject, String name,
ResolutionContext context); @Override Hint createHint(Object contextObject, String name,
ResolutionContext context); @Override void init(); @Override Set<ConfigurationKey> getConfigurationKeys(); void invalidateMemberCache(Predicate<Class<?>> predicate); static final int REFLECTION_RESOLVER_PRIORITY; static final String COMPUTING_CACHE_CONSUMER_ID; static final ConfigurationKey MEMBER_CACHE_MAX_SIZE_KEY; static final ConfigurationKey HINT_FALLBACK_ENABLED_KEY; static final String GET_PREFIX; static final String IS_PREFIX; } |
@Test(expected = IllegalStateException.class) public void testMultipleInit() { ReflectionResolver resolver = new ReflectionResolver(); MustacheEngineBuilder.newBuilder().omitServiceLoaderConfigurationExtensions().addResolver(resolver).build(); resolver.init(null); } | @Override public void init() { long memberCacheMaxSize = configuration .getLongPropertyValue(MEMBER_CACHE_MAX_SIZE_KEY); LOGGER.debug("Initialized [memberCacheMaxSize: {}]", memberCacheMaxSize); if (memberCacheMaxSize > 0) { memberCache = configuration.getComputingCacheFactory().create( COMPUTING_CACHE_CONSUMER_ID, ReflectionResolver::findWrapper, null, memberCacheMaxSize, null); } hintFallbackEnabled = configuration .getBooleanPropertyValue(HINT_FALLBACK_ENABLED_KEY); } | ReflectionResolver extends AbstractResolver { @Override public void init() { long memberCacheMaxSize = configuration .getLongPropertyValue(MEMBER_CACHE_MAX_SIZE_KEY); LOGGER.debug("Initialized [memberCacheMaxSize: {}]", memberCacheMaxSize); if (memberCacheMaxSize > 0) { memberCache = configuration.getComputingCacheFactory().create( COMPUTING_CACHE_CONSUMER_ID, ReflectionResolver::findWrapper, null, memberCacheMaxSize, null); } hintFallbackEnabled = configuration .getBooleanPropertyValue(HINT_FALLBACK_ENABLED_KEY); } } | ReflectionResolver extends AbstractResolver { @Override public void init() { long memberCacheMaxSize = configuration .getLongPropertyValue(MEMBER_CACHE_MAX_SIZE_KEY); LOGGER.debug("Initialized [memberCacheMaxSize: {}]", memberCacheMaxSize); if (memberCacheMaxSize > 0) { memberCache = configuration.getComputingCacheFactory().create( COMPUTING_CACHE_CONSUMER_ID, ReflectionResolver::findWrapper, null, memberCacheMaxSize, null); } hintFallbackEnabled = configuration .getBooleanPropertyValue(HINT_FALLBACK_ENABLED_KEY); } ReflectionResolver(); ReflectionResolver(int priority); } | ReflectionResolver extends AbstractResolver { @Override public void init() { long memberCacheMaxSize = configuration .getLongPropertyValue(MEMBER_CACHE_MAX_SIZE_KEY); LOGGER.debug("Initialized [memberCacheMaxSize: {}]", memberCacheMaxSize); if (memberCacheMaxSize > 0) { memberCache = configuration.getComputingCacheFactory().create( COMPUTING_CACHE_CONSUMER_ID, ReflectionResolver::findWrapper, null, memberCacheMaxSize, null); } hintFallbackEnabled = configuration .getBooleanPropertyValue(HINT_FALLBACK_ENABLED_KEY); } ReflectionResolver(); ReflectionResolver(int priority); @Override Object resolve(Object contextObject, String name,
ResolutionContext context); @Override Hint createHint(Object contextObject, String name,
ResolutionContext context); @Override void init(); @Override Set<ConfigurationKey> getConfigurationKeys(); void invalidateMemberCache(Predicate<Class<?>> predicate); } | ReflectionResolver extends AbstractResolver { @Override public void init() { long memberCacheMaxSize = configuration .getLongPropertyValue(MEMBER_CACHE_MAX_SIZE_KEY); LOGGER.debug("Initialized [memberCacheMaxSize: {}]", memberCacheMaxSize); if (memberCacheMaxSize > 0) { memberCache = configuration.getComputingCacheFactory().create( COMPUTING_CACHE_CONSUMER_ID, ReflectionResolver::findWrapper, null, memberCacheMaxSize, null); } hintFallbackEnabled = configuration .getBooleanPropertyValue(HINT_FALLBACK_ENABLED_KEY); } ReflectionResolver(); ReflectionResolver(int priority); @Override Object resolve(Object contextObject, String name,
ResolutionContext context); @Override Hint createHint(Object contextObject, String name,
ResolutionContext context); @Override void init(); @Override Set<ConfigurationKey> getConfigurationKeys(); void invalidateMemberCache(Predicate<Class<?>> predicate); static final int REFLECTION_RESOLVER_PRIORITY; static final String COMPUTING_CACHE_CONSUMER_ID; static final ConfigurationKey MEMBER_CACHE_MAX_SIZE_KEY; static final ConfigurationKey HINT_FALLBACK_ENABLED_KEY; static final String GET_PREFIX; static final String IS_PREFIX; } |
@Test(expected = IllegalStateException.class) public void testMultipleInit() { DateTimeFormatResolver resolver = new DateTimeFormatResolver(); MustacheEngineBuilder.newBuilder() .omitServiceLoaderConfigurationExtensions() .addResolver(resolver).build(); resolver.init(null); } | @Override public void init() { super.init(); customPattern = configuration .getStringPropertyValue(CUSTOM_PATTERN_KEY); LOGGER.info("Initialized [customPattern: {}]", customPattern); } | DateTimeFormatResolver extends TransformResolver { @Override public void init() { super.init(); customPattern = configuration .getStringPropertyValue(CUSTOM_PATTERN_KEY); LOGGER.info("Initialized [customPattern: {}]", customPattern); } } | DateTimeFormatResolver extends TransformResolver { @Override public void init() { super.init(); customPattern = configuration .getStringPropertyValue(CUSTOM_PATTERN_KEY); LOGGER.info("Initialized [customPattern: {}]", customPattern); } DateTimeFormatResolver(); DateTimeFormatResolver(int priority); } | DateTimeFormatResolver extends TransformResolver { @Override public void init() { super.init(); customPattern = configuration .getStringPropertyValue(CUSTOM_PATTERN_KEY); LOGGER.info("Initialized [customPattern: {}]", customPattern); } DateTimeFormatResolver(); DateTimeFormatResolver(int priority); @Override Object transform(Object contextObject, String name,
ResolutionContext context); @Override void init(); @Override Set<ConfigurationKey> getConfigurationKeys(); } | DateTimeFormatResolver extends TransformResolver { @Override public void init() { super.init(); customPattern = configuration .getStringPropertyValue(CUSTOM_PATTERN_KEY); LOGGER.info("Initialized [customPattern: {}]", customPattern); } DateTimeFormatResolver(); DateTimeFormatResolver(int priority); @Override Object transform(Object contextObject, String name,
ResolutionContext context); @Override void init(); @Override Set<ConfigurationKey> getConfigurationKeys(); static final int DATE_TIME_FORMAT_RESOLVER_PRIORITY; static final ConfigurationKey CUSTOM_PATTERN_KEY; } |
@Test public void testNotAnIndex() { IndexResolver indexResolver = new IndexResolver(0) { @Override public Object resolve(Object contextObject, String name, ResolutionContext context) { return null; } }; assertTrue(indexResolver.notAnIndex("-1")); assertTrue(indexResolver.notAnIndex("size")); assertTrue(indexResolver.notAnIndex(".1")); assertTrue(indexResolver.notAnIndex("1,5")); assertFalse(indexResolver.notAnIndex("1500")); } | protected boolean notAnIndex(String name) { return !isAnIndex(name); } | IndexResolver extends AbstractResolver { protected boolean notAnIndex(String name) { return !isAnIndex(name); } } | IndexResolver extends AbstractResolver { protected boolean notAnIndex(String name) { return !isAnIndex(name); } IndexResolver(int priority); } | IndexResolver extends AbstractResolver { protected boolean notAnIndex(String name) { return !isAnIndex(name); } IndexResolver(int priority); } | IndexResolver extends AbstractResolver { protected boolean notAnIndex(String name) { return !isAnIndex(name); } IndexResolver(int priority); } |
@Test public void testResolution() { MustacheEngineBuilder.newBuilder() .omitServiceLoaderConfigurationExtensions() .addResolver(resolver).build(); assertNull(resolver.resolve(null, "whatever", null)); Object marker = resolver.resolve(null, "ng", null); assertNotNull(marker); assertEquals("{{FOO}}", resolver.resolve(marker, "foo", null)); } | @Override public Object resolve(Object contextObject, String name, ResolutionContext context) { if (contextObject == null && matches(name)) { return marker; } else if (contextObject != null && contextObject.equals(marker)) { return performTransformation(contextObject, name, context); } return null; } | DummyTransformResolver extends TransformResolver { @Override public Object resolve(Object contextObject, String name, ResolutionContext context) { if (contextObject == null && matches(name)) { return marker; } else if (contextObject != null && contextObject.equals(marker)) { return performTransformation(contextObject, name, context); } return null; } } | DummyTransformResolver extends TransformResolver { @Override public Object resolve(Object contextObject, String name, ResolutionContext context) { if (contextObject == null && matches(name)) { return marker; } else if (contextObject != null && contextObject.equals(marker)) { return performTransformation(contextObject, name, context); } return null; } DummyTransformResolver(int priority,
String... matchNames); DummyTransformResolver(int priority,
Transformer transformer, String... matchNames); } | DummyTransformResolver extends TransformResolver { @Override public Object resolve(Object contextObject, String name, ResolutionContext context) { if (contextObject == null && matches(name)) { return marker; } else if (contextObject != null && contextObject.equals(marker)) { return performTransformation(contextObject, name, context); } return null; } DummyTransformResolver(int priority,
String... matchNames); DummyTransformResolver(int priority,
Transformer transformer, String... matchNames); @Override Object resolve(Object contextObject, String name,
ResolutionContext context); } | DummyTransformResolver extends TransformResolver { @Override public Object resolve(Object contextObject, String name, ResolutionContext context) { if (contextObject == null && matches(name)) { return marker; } else if (contextObject != null && contextObject.equals(marker)) { return performTransformation(contextObject, name, context); } return null; } DummyTransformResolver(int priority,
String... matchNames); DummyTransformResolver(int priority,
Transformer transformer, String... matchNames); @Override Object resolve(Object contextObject, String name,
ResolutionContext context); } |
@Test public void testGetDelegate() { Hammer hammer = new Hammer(); assertEquals("EDGAR vs Edgar", engine.compileMustache("{{name}} vs {{delegate.name}}") .render(decorate(hammer).compute("name", h -> h.getName().toUpperCase()).build(engine))); assertEquals("EDGAR vs Edgar", engine.compileMustache("{{name}} vs {{foo.name}}").render( decorate(hammer).delegateKey("foo").compute("name", h -> h.getName().toUpperCase()).build(engine))); } | public static <T> Builder<T> decorate(T delegate) { return new Builder<T>(delegate); } | Decorator implements Mapper { public static <T> Builder<T> decorate(T delegate) { return new Builder<T>(delegate); } } | Decorator implements Mapper { public static <T> Builder<T> decorate(T delegate) { return new Builder<T>(delegate); } private Decorator(T delegate, Map<String, Function<T, Object>> mappings, String delegateKey,
Configuration configuration); } | Decorator implements Mapper { public static <T> Builder<T> decorate(T delegate) { return new Builder<T>(delegate); } private Decorator(T delegate, Map<String, Function<T, Object>> mappings, String delegateKey,
Configuration configuration); static Builder<T> decorate(T delegate); static Decorator<T> decorate(T delegate, Map<String, Function<T, Object>> mappings, String delegateKey,
Configuration configuration); @SuppressWarnings("unchecked") static T unwrap(T instance); @Override Object get(String key); @Override String toString(); } | Decorator implements Mapper { public static <T> Builder<T> decorate(T delegate) { return new Builder<T>(delegate); } private Decorator(T delegate, Map<String, Function<T, Object>> mappings, String delegateKey,
Configuration configuration); static Builder<T> decorate(T delegate); static Decorator<T> decorate(T delegate, Map<String, Function<T, Object>> mappings, String delegateKey,
Configuration configuration); @SuppressWarnings("unchecked") static T unwrap(T instance); @Override Object get(String key); @Override String toString(); static final String KEY_GET_DELEGATE; } |
@Test public void testNestedDecorator() { Hammer hammer = new Hammer(5); assertEquals("5:Edgar:bar", engine.compileMustache("{{age}}:{{foo}}:{{bar}}") .render(decorate(decorate(hammer).compute("foo", h -> h.getName()).build(engine)) .put("bar", "bar").build(engine))); } | public static <T> Builder<T> decorate(T delegate) { return new Builder<T>(delegate); } | Decorator implements Mapper { public static <T> Builder<T> decorate(T delegate) { return new Builder<T>(delegate); } } | Decorator implements Mapper { public static <T> Builder<T> decorate(T delegate) { return new Builder<T>(delegate); } private Decorator(T delegate, Map<String, Function<T, Object>> mappings, String delegateKey,
Configuration configuration); } | Decorator implements Mapper { public static <T> Builder<T> decorate(T delegate) { return new Builder<T>(delegate); } private Decorator(T delegate, Map<String, Function<T, Object>> mappings, String delegateKey,
Configuration configuration); static Builder<T> decorate(T delegate); static Decorator<T> decorate(T delegate, Map<String, Function<T, Object>> mappings, String delegateKey,
Configuration configuration); @SuppressWarnings("unchecked") static T unwrap(T instance); @Override Object get(String key); @Override String toString(); } | Decorator implements Mapper { public static <T> Builder<T> decorate(T delegate) { return new Builder<T>(delegate); } private Decorator(T delegate, Map<String, Function<T, Object>> mappings, String delegateKey,
Configuration configuration); static Builder<T> decorate(T delegate); static Decorator<T> decorate(T delegate, Map<String, Function<T, Object>> mappings, String delegateKey,
Configuration configuration); @SuppressWarnings("unchecked") static T unwrap(T instance); @Override Object get(String key); @Override String toString(); static final String KEY_GET_DELEGATE; } |
@Test public void testResolution() { MapResolver resolver = new MapResolver(); assertNull(resolver.resolve(null, "foo", null)); assertNotNull( resolver.resolve(ImmutableMap.of("bar", "baz"), "bar", null)); assertNull( resolver.resolve(ImmutableMap.of("bar", "baz"), "qux", null)); } | @SuppressWarnings("rawtypes") @Override public Object resolve(Object contextObject, String name, ResolutionContext context) { if (contextObject == null) { return null; } if (contextObject instanceof Map) { Map map = (Map) contextObject; return map.get(name); } if (contextObject instanceof Mapper) { Mapper mapper = (Mapper) contextObject; return mapper.get(name); } return null; } | MapResolver extends AbstractResolver { @SuppressWarnings("rawtypes") @Override public Object resolve(Object contextObject, String name, ResolutionContext context) { if (contextObject == null) { return null; } if (contextObject instanceof Map) { Map map = (Map) contextObject; return map.get(name); } if (contextObject instanceof Mapper) { Mapper mapper = (Mapper) contextObject; return mapper.get(name); } return null; } } | MapResolver extends AbstractResolver { @SuppressWarnings("rawtypes") @Override public Object resolve(Object contextObject, String name, ResolutionContext context) { if (contextObject == null) { return null; } if (contextObject instanceof Map) { Map map = (Map) contextObject; return map.get(name); } if (contextObject instanceof Mapper) { Mapper mapper = (Mapper) contextObject; return mapper.get(name); } return null; } MapResolver(); MapResolver(int priority); } | MapResolver extends AbstractResolver { @SuppressWarnings("rawtypes") @Override public Object resolve(Object contextObject, String name, ResolutionContext context) { if (contextObject == null) { return null; } if (contextObject instanceof Map) { Map map = (Map) contextObject; return map.get(name); } if (contextObject instanceof Mapper) { Mapper mapper = (Mapper) contextObject; return mapper.get(name); } return null; } MapResolver(); MapResolver(int priority); @SuppressWarnings("rawtypes") @Override Object resolve(Object contextObject, String name,
ResolutionContext context); @Override Hint createHint(Object contextObject, String name,
ResolutionContext context); } | MapResolver extends AbstractResolver { @SuppressWarnings("rawtypes") @Override public Object resolve(Object contextObject, String name, ResolutionContext context) { if (contextObject == null) { return null; } if (contextObject instanceof Map) { Map map = (Map) contextObject; return map.get(name); } if (contextObject instanceof Mapper) { Mapper mapper = (Mapper) contextObject; return mapper.get(name); } return null; } MapResolver(); MapResolver(int priority); @SuppressWarnings("rawtypes") @Override Object resolve(Object contextObject, String name,
ResolutionContext context); @Override Hint createHint(Object contextObject, String name,
ResolutionContext context); static final int MAP_RESOLVER_PRIORITY; } |
@Test public void testSetDelimitersPattern() { String set1 = "<% %>"; String set2 = "[ ]"; String set3 = "= ="; Pattern setDelimitersPattern = Patterns .newSetDelimitersContentPattern(); Matcher set1Matcher = setDelimitersPattern.matcher(set1); assertEquals(true, set1Matcher.find()); assertEquals("<%", set1Matcher.group(1)); assertEquals("%>", set1Matcher.group(3)); Matcher set2Matcher = setDelimitersPattern.matcher(set2); assertEquals(true, set2Matcher.find()); assertEquals("[", set2Matcher.group(1)); assertEquals("]", set2Matcher.group(3)); Matcher set3Matcher = setDelimitersPattern.matcher(set3); assertEquals(true, set3Matcher.find()); assertEquals("=", set3Matcher.group(1)); assertEquals("=", set3Matcher.group(3)); } | public static Pattern newSetDelimitersContentPattern() { return Pattern.compile("(\\S+)(\\s+)(\\S+)"); } | Patterns { public static Pattern newSetDelimitersContentPattern() { return Pattern.compile("(\\S+)(\\s+)(\\S+)"); } } | Patterns { public static Pattern newSetDelimitersContentPattern() { return Pattern.compile("(\\S+)(\\s+)(\\S+)"); } private Patterns(); } | Patterns { public static Pattern newSetDelimitersContentPattern() { return Pattern.compile("(\\S+)(\\s+)(\\S+)"); } private Patterns(); static Pattern newMustacheTagPattern(Configuration configuration); static Pattern newSetDelimitersContentPattern(); static Pattern newHelperIntegerLiteralPattern(); static Pattern newHelperLongLiteralPattern(); } | Patterns { public static Pattern newSetDelimitersContentPattern() { return Pattern.compile("(\\S+)(\\s+)(\\S+)"); } private Patterns(); static Pattern newMustacheTagPattern(Configuration configuration); static Pattern newSetDelimitersContentPattern(); static Pattern newHelperIntegerLiteralPattern(); static Pattern newHelperLongLiteralPattern(); } |
@Test public void testSplitHelperName() { assertHelperNameParts("name foo.bar", "name", "foo.bar"); assertHelperNameParts("name hash1=\"DD-MM-yyyy HH:mm\"", "name", "hash1=\"DD-MM-yyyy HH:mm\""); assertHelperNameParts("name key='value'", "name", "key='value'"); assertHelperNameParts("name key=''value''", "name", "key=''value''"); assertHelperNameParts("key='value foo=' 'bar'", "key='value foo='", "'bar'"); assertHelperNameParts("'key'='value foo=' 'bar'", "'key'='value foo='", "'bar'"); assertHelperNameParts("foo='bar = \n baz' qux", "foo='bar = \n baz'", "qux"); assertHelperNameParts("[ 'foo', 'bar', qux] foo", "[ 'foo', 'bar', qux]", "foo"); assertHelperNameParts("1 20 ['', '1'] foo", "1", "20", "['', '1']", "foo"); assertHelperNameParts("'[1, 2]'", "'[1, 2]'"); assertHelperNameParts("'[1, '2', 'alpha']'", "'[1, '2', 'alpha']'"); assertHelperNameParts("foo=[1, '2']", "foo=[1, '2']"); assertHelperNameParts("if \"var eq 'value_without_space'\"", "if", "\"var eq 'value_without_space'\""); assertHelperNameParts("key='value\" foo=' 'bar'", "key='value\" foo='", "'bar'"); assertHelperNameParts("if \"var eq 'value with space'\"", "if", "\"var eq 'value with space'\""); MustacheExceptionAssert .expect(MustacheProblem.COMPILE_HELPER_VALIDATION_FAILURE) .check(() -> assertHelperNameParts("name key=''value'")) .check(() -> assertHelperNameParts("name key=value'")) .check(() -> assertHelperNameParts("name key='value foo")) .check(() -> assertHelperNameParts("name key=value' foo")) .check(() -> assertHelperNameParts("'name key=value")) .check(() -> assertHelperNameParts("key=\"value \" and\"")) .check(() -> assertHelperNameParts("foo='bar\"")); } | static Iterator<String> splitHelperName(String name, Segment segment) { Character stringLiteral = null; boolean arrayLiteral = false; boolean space = false; List<String> parts = new ArrayList<>(); StringBuilder buffer = new StringBuilder(); for (int i = 0; i < name.length(); i++) { char character = name.charAt(i); if (character == ' ') { if (!space) { if (stringLiteral == null && !arrayLiteral) { if (buffer.length() > 0) { parts.add(buffer.toString()); buffer = new StringBuilder(); } space = true; } else { buffer.append(character); } } } else { if (!arrayLiteral && Strings.isStringLiteralSeparator(character)) { if (stringLiteral != null) { if (character == stringLiteral.charValue()) { stringLiteral = null; } } else { stringLiteral = character; } } else if (stringLiteral == null && Strings.isListLiteralStart(character)) { arrayLiteral = true; } else if (stringLiteral == null && Strings.isListLiteralEnd(character)) { arrayLiteral = false; } space = false; buffer.append(character); } } if (buffer.length() > 0) { if (stringLiteral != null || arrayLiteral) { throw new MustacheException( MustacheProblem.COMPILE_HELPER_VALIDATION_FAILURE, "Unterminated string or array literal detected: %s", segment); } parts.add(buffer.toString()); } return parts.iterator(); } | HelperExecutionHandler { static Iterator<String> splitHelperName(String name, Segment segment) { Character stringLiteral = null; boolean arrayLiteral = false; boolean space = false; List<String> parts = new ArrayList<>(); StringBuilder buffer = new StringBuilder(); for (int i = 0; i < name.length(); i++) { char character = name.charAt(i); if (character == ' ') { if (!space) { if (stringLiteral == null && !arrayLiteral) { if (buffer.length() > 0) { parts.add(buffer.toString()); buffer = new StringBuilder(); } space = true; } else { buffer.append(character); } } } else { if (!arrayLiteral && Strings.isStringLiteralSeparator(character)) { if (stringLiteral != null) { if (character == stringLiteral.charValue()) { stringLiteral = null; } } else { stringLiteral = character; } } else if (stringLiteral == null && Strings.isListLiteralStart(character)) { arrayLiteral = true; } else if (stringLiteral == null && Strings.isListLiteralEnd(character)) { arrayLiteral = false; } space = false; buffer.append(character); } } if (buffer.length() > 0) { if (stringLiteral != null || arrayLiteral) { throw new MustacheException( MustacheProblem.COMPILE_HELPER_VALIDATION_FAILURE, "Unterminated string or array literal detected: %s", segment); } parts.add(buffer.toString()); } return parts.iterator(); } } | HelperExecutionHandler { static Iterator<String> splitHelperName(String name, Segment segment) { Character stringLiteral = null; boolean arrayLiteral = false; boolean space = false; List<String> parts = new ArrayList<>(); StringBuilder buffer = new StringBuilder(); for (int i = 0; i < name.length(); i++) { char character = name.charAt(i); if (character == ' ') { if (!space) { if (stringLiteral == null && !arrayLiteral) { if (buffer.length() > 0) { parts.add(buffer.toString()); buffer = new StringBuilder(); } space = true; } else { buffer.append(character); } } } else { if (!arrayLiteral && Strings.isStringLiteralSeparator(character)) { if (stringLiteral != null) { if (character == stringLiteral.charValue()) { stringLiteral = null; } } else { stringLiteral = character; } } else if (stringLiteral == null && Strings.isListLiteralStart(character)) { arrayLiteral = true; } else if (stringLiteral == null && Strings.isListLiteralEnd(character)) { arrayLiteral = false; } space = false; buffer.append(character); } } if (buffer.length() > 0) { if (stringLiteral != null || arrayLiteral) { throw new MustacheException( MustacheProblem.COMPILE_HELPER_VALIDATION_FAILURE, "Unterminated string or array literal detected: %s", segment); } parts.add(buffer.toString()); } return parts.iterator(); } private HelperExecutionHandler(Helper helper,
OptionsBuilder optionsBuilder); } | HelperExecutionHandler { static Iterator<String> splitHelperName(String name, Segment segment) { Character stringLiteral = null; boolean arrayLiteral = false; boolean space = false; List<String> parts = new ArrayList<>(); StringBuilder buffer = new StringBuilder(); for (int i = 0; i < name.length(); i++) { char character = name.charAt(i); if (character == ' ') { if (!space) { if (stringLiteral == null && !arrayLiteral) { if (buffer.length() > 0) { parts.add(buffer.toString()); buffer = new StringBuilder(); } space = true; } else { buffer.append(character); } } } else { if (!arrayLiteral && Strings.isStringLiteralSeparator(character)) { if (stringLiteral != null) { if (character == stringLiteral.charValue()) { stringLiteral = null; } } else { stringLiteral = character; } } else if (stringLiteral == null && Strings.isListLiteralStart(character)) { arrayLiteral = true; } else if (stringLiteral == null && Strings.isListLiteralEnd(character)) { arrayLiteral = false; } space = false; buffer.append(character); } } if (buffer.length() > 0) { if (stringLiteral != null || arrayLiteral) { throw new MustacheException( MustacheProblem.COMPILE_HELPER_VALIDATION_FAILURE, "Unterminated string or array literal detected: %s", segment); } parts.add(buffer.toString()); } return parts.iterator(); } private HelperExecutionHandler(Helper helper,
OptionsBuilder optionsBuilder); } | HelperExecutionHandler { static Iterator<String> splitHelperName(String name, Segment segment) { Character stringLiteral = null; boolean arrayLiteral = false; boolean space = false; List<String> parts = new ArrayList<>(); StringBuilder buffer = new StringBuilder(); for (int i = 0; i < name.length(); i++) { char character = name.charAt(i); if (character == ' ') { if (!space) { if (stringLiteral == null && !arrayLiteral) { if (buffer.length() > 0) { parts.add(buffer.toString()); buffer = new StringBuilder(); } space = true; } else { buffer.append(character); } } } else { if (!arrayLiteral && Strings.isStringLiteralSeparator(character)) { if (stringLiteral != null) { if (character == stringLiteral.charValue()) { stringLiteral = null; } } else { stringLiteral = character; } } else if (stringLiteral == null && Strings.isListLiteralStart(character)) { arrayLiteral = true; } else if (stringLiteral == null && Strings.isListLiteralEnd(character)) { arrayLiteral = false; } space = false; buffer.append(character); } } if (buffer.length() > 0) { if (stringLiteral != null || arrayLiteral) { throw new MustacheException( MustacheProblem.COMPILE_HELPER_VALIDATION_FAILURE, "Unterminated string or array literal detected: %s", segment); } parts.add(buffer.toString()); } return parts.iterator(); } private HelperExecutionHandler(Helper helper,
OptionsBuilder optionsBuilder); } |
@Test public void testGetFirstDeterminingEqualsCharPosition() { assertEquals(3, HelperExecutionHandler .getFirstDeterminingEqualsCharPosition("foo=bar")); assertEquals(3, HelperExecutionHandler .getFirstDeterminingEqualsCharPosition("foo='bar='")); assertEquals(1, HelperExecutionHandler .getFirstDeterminingEqualsCharPosition("1='bar='")); assertEquals(-1, HelperExecutionHandler .getFirstDeterminingEqualsCharPosition("'m=n'")); assertEquals(-1, HelperExecutionHandler .getFirstDeterminingEqualsCharPosition(" ' m=n'")); assertEquals(-1, HelperExecutionHandler .getFirstDeterminingEqualsCharPosition("'1'")); assertEquals(-1, HelperExecutionHandler .getFirstDeterminingEqualsCharPosition("\"foo\"")); } | static int getFirstDeterminingEqualsCharPosition(String part) { boolean stringLiteral = false; for (int i = 0; i < part.length(); i++) { if (Strings.isStringLiteralSeparator(part.charAt(i))) { if (i == 0) { return -1; } stringLiteral = !stringLiteral; } else { if (!stringLiteral && part.charAt(i) == '=') { return i; } } } return -1; } | HelperExecutionHandler { static int getFirstDeterminingEqualsCharPosition(String part) { boolean stringLiteral = false; for (int i = 0; i < part.length(); i++) { if (Strings.isStringLiteralSeparator(part.charAt(i))) { if (i == 0) { return -1; } stringLiteral = !stringLiteral; } else { if (!stringLiteral && part.charAt(i) == '=') { return i; } } } return -1; } } | HelperExecutionHandler { static int getFirstDeterminingEqualsCharPosition(String part) { boolean stringLiteral = false; for (int i = 0; i < part.length(); i++) { if (Strings.isStringLiteralSeparator(part.charAt(i))) { if (i == 0) { return -1; } stringLiteral = !stringLiteral; } else { if (!stringLiteral && part.charAt(i) == '=') { return i; } } } return -1; } private HelperExecutionHandler(Helper helper,
OptionsBuilder optionsBuilder); } | HelperExecutionHandler { static int getFirstDeterminingEqualsCharPosition(String part) { boolean stringLiteral = false; for (int i = 0; i < part.length(); i++) { if (Strings.isStringLiteralSeparator(part.charAt(i))) { if (i == 0) { return -1; } stringLiteral = !stringLiteral; } else { if (!stringLiteral && part.charAt(i) == '=') { return i; } } } return -1; } private HelperExecutionHandler(Helper helper,
OptionsBuilder optionsBuilder); } | HelperExecutionHandler { static int getFirstDeterminingEqualsCharPosition(String part) { boolean stringLiteral = false; for (int i = 0; i < part.length(); i++) { if (Strings.isStringLiteralSeparator(part.charAt(i))) { if (i == 0) { return -1; } stringLiteral = !stringLiteral; } else { if (!stringLiteral && part.charAt(i) == '=') { return i; } } } return -1; } private HelperExecutionHandler(Helper helper,
OptionsBuilder optionsBuilder); } |
@Test public void testBuildPropertyKey() { assertEquals("org.trimou.engine.config.myPropertyName", ConfigurationProperties.buildPropertyKey("MY_PROPERTY_NAME", new String[] { ConfigurationPropertiesTest.class .getPackage().getName() })); assertEquals("org.trimou.engine.config.myPropertyName", ConfigurationProperties.buildPropertyKey("MY.PROPERTY.NAME", ".", new String[] { ConfigurationPropertiesTest.class .getPackage().getName() })); } | static String buildPropertyKey(String propertyName, String[] prefixParts) { return buildPropertyKey(propertyName, Strings.UNDERSCORE, prefixParts); } | ConfigurationProperties { static String buildPropertyKey(String propertyName, String[] prefixParts) { return buildPropertyKey(propertyName, Strings.UNDERSCORE, prefixParts); } } | ConfigurationProperties { static String buildPropertyKey(String propertyName, String[] prefixParts) { return buildPropertyKey(propertyName, Strings.UNDERSCORE, prefixParts); } private ConfigurationProperties(); } | ConfigurationProperties { static String buildPropertyKey(String propertyName, String[] prefixParts) { return buildPropertyKey(propertyName, Strings.UNDERSCORE, prefixParts); } private ConfigurationProperties(); } | ConfigurationProperties { static String buildPropertyKey(String propertyName, String[] prefixParts) { return buildPropertyKey(propertyName, Strings.UNDERSCORE, prefixParts); } private ConfigurationProperties(); } |
@Test public void testConvertConfigValue() { assertEquals(10, ConfigurationProperties .convertConfigValue(Integer.class, "10")); assertEquals(10L, ConfigurationProperties.convertConfigValue(Long.class, "10")); assertEquals(Boolean.FALSE, ConfigurationProperties .convertConfigValue(Boolean.class, "10")); } | static Object convertConfigValue(Class<?> defaultValueType, Object value) { if (defaultValueType.equals(String.class)) { return value.toString(); } else if (defaultValueType.equals(Boolean.class)) { return Boolean.valueOf(value.toString()); } else if (defaultValueType.equals(Long.class)) { return Long.valueOf(value.toString()); } else if (defaultValueType.equals(Integer.class)) { return Integer.valueOf(value.toString()); } throw new IllegalStateException( "Unsupported default value type: " + defaultValueType); } | ConfigurationProperties { static Object convertConfigValue(Class<?> defaultValueType, Object value) { if (defaultValueType.equals(String.class)) { return value.toString(); } else if (defaultValueType.equals(Boolean.class)) { return Boolean.valueOf(value.toString()); } else if (defaultValueType.equals(Long.class)) { return Long.valueOf(value.toString()); } else if (defaultValueType.equals(Integer.class)) { return Integer.valueOf(value.toString()); } throw new IllegalStateException( "Unsupported default value type: " + defaultValueType); } } | ConfigurationProperties { static Object convertConfigValue(Class<?> defaultValueType, Object value) { if (defaultValueType.equals(String.class)) { return value.toString(); } else if (defaultValueType.equals(Boolean.class)) { return Boolean.valueOf(value.toString()); } else if (defaultValueType.equals(Long.class)) { return Long.valueOf(value.toString()); } else if (defaultValueType.equals(Integer.class)) { return Integer.valueOf(value.toString()); } throw new IllegalStateException( "Unsupported default value type: " + defaultValueType); } private ConfigurationProperties(); } | ConfigurationProperties { static Object convertConfigValue(Class<?> defaultValueType, Object value) { if (defaultValueType.equals(String.class)) { return value.toString(); } else if (defaultValueType.equals(Boolean.class)) { return Boolean.valueOf(value.toString()); } else if (defaultValueType.equals(Long.class)) { return Long.valueOf(value.toString()); } else if (defaultValueType.equals(Integer.class)) { return Integer.valueOf(value.toString()); } throw new IllegalStateException( "Unsupported default value type: " + defaultValueType); } private ConfigurationProperties(); } | ConfigurationProperties { static Object convertConfigValue(Class<?> defaultValueType, Object value) { if (defaultValueType.equals(String.class)) { return value.toString(); } else if (defaultValueType.equals(Boolean.class)) { return Boolean.valueOf(value.toString()); } else if (defaultValueType.equals(Long.class)) { return Long.valueOf(value.toString()); } else if (defaultValueType.equals(Integer.class)) { return Integer.valueOf(value.toString()); } throw new IllegalStateException( "Unsupported default value type: " + defaultValueType); } private ConfigurationProperties(); } |
@Test(expected = IllegalStateException.class) public void testConvertConfigValueFails() { ConfigurationProperties.convertConfigValue(BigDecimal.class, "10"); } | static Object convertConfigValue(Class<?> defaultValueType, Object value) { if (defaultValueType.equals(String.class)) { return value.toString(); } else if (defaultValueType.equals(Boolean.class)) { return Boolean.valueOf(value.toString()); } else if (defaultValueType.equals(Long.class)) { return Long.valueOf(value.toString()); } else if (defaultValueType.equals(Integer.class)) { return Integer.valueOf(value.toString()); } throw new IllegalStateException( "Unsupported default value type: " + defaultValueType); } | ConfigurationProperties { static Object convertConfigValue(Class<?> defaultValueType, Object value) { if (defaultValueType.equals(String.class)) { return value.toString(); } else if (defaultValueType.equals(Boolean.class)) { return Boolean.valueOf(value.toString()); } else if (defaultValueType.equals(Long.class)) { return Long.valueOf(value.toString()); } else if (defaultValueType.equals(Integer.class)) { return Integer.valueOf(value.toString()); } throw new IllegalStateException( "Unsupported default value type: " + defaultValueType); } } | ConfigurationProperties { static Object convertConfigValue(Class<?> defaultValueType, Object value) { if (defaultValueType.equals(String.class)) { return value.toString(); } else if (defaultValueType.equals(Boolean.class)) { return Boolean.valueOf(value.toString()); } else if (defaultValueType.equals(Long.class)) { return Long.valueOf(value.toString()); } else if (defaultValueType.equals(Integer.class)) { return Integer.valueOf(value.toString()); } throw new IllegalStateException( "Unsupported default value type: " + defaultValueType); } private ConfigurationProperties(); } | ConfigurationProperties { static Object convertConfigValue(Class<?> defaultValueType, Object value) { if (defaultValueType.equals(String.class)) { return value.toString(); } else if (defaultValueType.equals(Boolean.class)) { return Boolean.valueOf(value.toString()); } else if (defaultValueType.equals(Long.class)) { return Long.valueOf(value.toString()); } else if (defaultValueType.equals(Integer.class)) { return Integer.valueOf(value.toString()); } throw new IllegalStateException( "Unsupported default value type: " + defaultValueType); } private ConfigurationProperties(); } | ConfigurationProperties { static Object convertConfigValue(Class<?> defaultValueType, Object value) { if (defaultValueType.equals(String.class)) { return value.toString(); } else if (defaultValueType.equals(Boolean.class)) { return Boolean.valueOf(value.toString()); } else if (defaultValueType.equals(Long.class)) { return Long.valueOf(value.toString()); } else if (defaultValueType.equals(Integer.class)) { return Integer.valueOf(value.toString()); } throw new IllegalStateException( "Unsupported default value type: " + defaultValueType); } private ConfigurationProperties(); } |
@Test public void testGetKey() { final AtomicReference<String> key = new AtomicReference<>(); MustacheEngineBuilder .newBuilder() .omitServiceLoaderConfigurationExtensions() .addResolver( new AbstractResolver( 1) { @Override public Object resolve(Object contextObject, String name, ResolutionContext context) { key.set(context.getKey()); return null; } }).build().compileMustache("getkey", "{{my.key.foo}}") .render(null); assertEquals("my.key.foo", key.get()); } | @Override public String getKey() { return key; } | ValueWrapper extends AbstractReleaseCallbackContainer implements ResolutionContext { @Override public String getKey() { return key; } } | ValueWrapper extends AbstractReleaseCallbackContainer implements ResolutionContext { @Override public String getKey() { return key; } ValueWrapper(String key); } | ValueWrapper extends AbstractReleaseCallbackContainer implements ResolutionContext { @Override public String getKey() { return key; } ValueWrapper(String key); Object get(); boolean isNull(); @Override String getKey(); @Override int getKeyPartIndex(); Hint getHint(); } | ValueWrapper extends AbstractReleaseCallbackContainer implements ResolutionContext { @Override public String getKey() { return key; } ValueWrapper(String key); Object get(); boolean isNull(); @Override String getKey(); @Override int getKeyPartIndex(); Hint getHint(); } |
@Test public void testGetKeyPartIndex() { final List<Integer> indexes = new ArrayList<>(); MustacheEngineBuilder .newBuilder() .omitServiceLoaderConfigurationExtensions() .addResolver(new AbstractResolver(1) { @Override public Object resolve(Object contextObject, String name, ResolutionContext context) { indexes.add(context.getKeyPartIndex()); return "OK"; } }).build().compileMustache("getkeypartindex", "{{my.key.foo}}") .render(null); assertEquals(3L, indexes.size()); assertEquals(Integer.valueOf(0), indexes.get(0)); assertEquals(Integer.valueOf(1), indexes.get(1)); assertEquals(Integer.valueOf(2), indexes.get(2)); } | @Override public int getKeyPartIndex() { return keyPartIndex; } | ValueWrapper extends AbstractReleaseCallbackContainer implements ResolutionContext { @Override public int getKeyPartIndex() { return keyPartIndex; } } | ValueWrapper extends AbstractReleaseCallbackContainer implements ResolutionContext { @Override public int getKeyPartIndex() { return keyPartIndex; } ValueWrapper(String key); } | ValueWrapper extends AbstractReleaseCallbackContainer implements ResolutionContext { @Override public int getKeyPartIndex() { return keyPartIndex; } ValueWrapper(String key); Object get(); boolean isNull(); @Override String getKey(); @Override int getKeyPartIndex(); Hint getHint(); } | ValueWrapper extends AbstractReleaseCallbackContainer implements ResolutionContext { @Override public int getKeyPartIndex() { return keyPartIndex; } ValueWrapper(String key); Object get(); boolean isNull(); @Override String getKey(); @Override int getKeyPartIndex(); Hint getHint(); } |
@Test public void testGetLiteral() { LiteralSupport literalSupport = new DefaultLiteralSupport(); assertNull(literalSupport.getLiteral("foo", null)); assertNull(literalSupport.getLiteral("1.0", null)); assertEquals(10, literalSupport.getLiteral("+10", null)); assertEquals(-2010, literalSupport.getLiteral("-2010", null)); assertEquals("foo", literalSupport.getLiteral("'foo'", null)); assertEquals("bar.me", literalSupport.getLiteral("\"bar.me\"", null)); assertEquals(10L, literalSupport.getLiteral("10L", null)); assertEquals(-2010L, literalSupport.getLiteral("-2010l", null)); assertNull(literalSupport.getLiteral("2.0", null)); assertEquals(Boolean.TRUE, literalSupport.getLiteral("true", null)); assertEquals(Boolean.FALSE, literalSupport.getLiteral("false", null)); } | @Override public Object getLiteral(String value, MustacheTagInfo tagInfo) { if (Strings.isEmpty(value)) { return null; } Object literal = null; if (Strings.isStringLiteralSeparator(value.charAt(0))) { literal = value.substring(1, value.length() - 1); } else if (value.equals("true")) { literal = Boolean.TRUE; } else if (value.equals("false")) { literal = Boolean.FALSE; } else if (integerLiteralPattern.matcher(value).matches()) { try { literal = Integer.parseInt(value); } catch (NumberFormatException e) { LOGGER.warn("Unable to parse integer literal: " + value, e); } } else if (longLiteralPattern.matcher(value).matches()) { try { literal = Long .parseLong(value.substring(0, value.length() - 1)); } catch (NumberFormatException e) { LOGGER.warn("Unable to parse long literal: " + value, e); } } return literal; } | DefaultLiteralSupport extends AbstractConfigurationAware implements LiteralSupport { @Override public Object getLiteral(String value, MustacheTagInfo tagInfo) { if (Strings.isEmpty(value)) { return null; } Object literal = null; if (Strings.isStringLiteralSeparator(value.charAt(0))) { literal = value.substring(1, value.length() - 1); } else if (value.equals("true")) { literal = Boolean.TRUE; } else if (value.equals("false")) { literal = Boolean.FALSE; } else if (integerLiteralPattern.matcher(value).matches()) { try { literal = Integer.parseInt(value); } catch (NumberFormatException e) { LOGGER.warn("Unable to parse integer literal: " + value, e); } } else if (longLiteralPattern.matcher(value).matches()) { try { literal = Long .parseLong(value.substring(0, value.length() - 1)); } catch (NumberFormatException e) { LOGGER.warn("Unable to parse long literal: " + value, e); } } return literal; } } | DefaultLiteralSupport extends AbstractConfigurationAware implements LiteralSupport { @Override public Object getLiteral(String value, MustacheTagInfo tagInfo) { if (Strings.isEmpty(value)) { return null; } Object literal = null; if (Strings.isStringLiteralSeparator(value.charAt(0))) { literal = value.substring(1, value.length() - 1); } else if (value.equals("true")) { literal = Boolean.TRUE; } else if (value.equals("false")) { literal = Boolean.FALSE; } else if (integerLiteralPattern.matcher(value).matches()) { try { literal = Integer.parseInt(value); } catch (NumberFormatException e) { LOGGER.warn("Unable to parse integer literal: " + value, e); } } else if (longLiteralPattern.matcher(value).matches()) { try { literal = Long .parseLong(value.substring(0, value.length() - 1)); } catch (NumberFormatException e) { LOGGER.warn("Unable to parse long literal: " + value, e); } } return literal; } } | DefaultLiteralSupport extends AbstractConfigurationAware implements LiteralSupport { @Override public Object getLiteral(String value, MustacheTagInfo tagInfo) { if (Strings.isEmpty(value)) { return null; } Object literal = null; if (Strings.isStringLiteralSeparator(value.charAt(0))) { literal = value.substring(1, value.length() - 1); } else if (value.equals("true")) { literal = Boolean.TRUE; } else if (value.equals("false")) { literal = Boolean.FALSE; } else if (integerLiteralPattern.matcher(value).matches()) { try { literal = Integer.parseInt(value); } catch (NumberFormatException e) { LOGGER.warn("Unable to parse integer literal: " + value, e); } } else if (longLiteralPattern.matcher(value).matches()) { try { literal = Long .parseLong(value.substring(0, value.length() - 1)); } catch (NumberFormatException e) { LOGGER.warn("Unable to parse long literal: " + value, e); } } return literal; } @Override Object getLiteral(String value, MustacheTagInfo tagInfo); } | DefaultLiteralSupport extends AbstractConfigurationAware implements LiteralSupport { @Override public Object getLiteral(String value, MustacheTagInfo tagInfo) { if (Strings.isEmpty(value)) { return null; } Object literal = null; if (Strings.isStringLiteralSeparator(value.charAt(0))) { literal = value.substring(1, value.length() - 1); } else if (value.equals("true")) { literal = Boolean.TRUE; } else if (value.equals("false")) { literal = Boolean.FALSE; } else if (integerLiteralPattern.matcher(value).matches()) { try { literal = Integer.parseInt(value); } catch (NumberFormatException e) { LOGGER.warn("Unable to parse integer literal: " + value, e); } } else if (longLiteralPattern.matcher(value).matches()) { try { literal = Long .parseLong(value.substring(0, value.length() - 1)); } catch (NumberFormatException e) { LOGGER.warn("Unable to parse long literal: " + value, e); } } return literal; } @Override Object getLiteral(String value, MustacheTagInfo tagInfo); } |
@Test public void testSplit() { BracketDotKeySplitter splitter = new BracketDotKeySplitter(); assertIterator(splitter.split("a..bar:.c"), "a", "bar:", "c"); assertIterator(splitter.split(". "), " "); assertIterator(splitter.split("."), "."); assertIterator(splitter.split("foo"), "foo"); assertIterator(splitter.split("foo[\"bar\"]"), "foo", "bar"); assertIterator(splitter.split("foo[\"a.b.c\"]"), "foo", "a.b.c"); assertIterator(splitter.split("foo[\"bar\"].baz"), "foo", "bar", "baz"); assertIterator(splitter.split("a[\"b\"].c.d[\"e\"][\"f\"]"), "a", "b", "c", "d", "e", "f"); assertIterator(splitter.split("foo['bar']"), "foo", "bar"); assertIterator(splitter.split("foo['bar dot'][\"qux\"].me"), "foo", "bar dot", "qux", "me"); } | @Override public Iterator<String> split(String key) { if (key.equals(Strings.DOT) || key.equals(Strings.THIS)) { return Iterables.singletonIterator(key); } boolean stringLiteral = false; boolean separator = false; List<String> parts = new ArrayList<>(); StringBuilder buffer = new StringBuilder(); for (int i = 0; i < key.length(); i++) { if (isSeparator(key.charAt(i))) { if (!separator) { if (!stringLiteral) { if (buffer.length() > 0) { parts.add(buffer.toString()); buffer = new StringBuilder(); } separator = true; } else { buffer.append(key.charAt(i)); } } } else { if (Strings.isStringLiteralSeparator(key.charAt(i))) { stringLiteral = !stringLiteral; } else { buffer.append(key.charAt(i)); } separator = false; } } if (buffer.length() > 0) { parts.add(buffer.toString()); } return parts.iterator(); } | BracketDotKeySplitter extends AbstractConfigurationAware implements KeySplitter { @Override public Iterator<String> split(String key) { if (key.equals(Strings.DOT) || key.equals(Strings.THIS)) { return Iterables.singletonIterator(key); } boolean stringLiteral = false; boolean separator = false; List<String> parts = new ArrayList<>(); StringBuilder buffer = new StringBuilder(); for (int i = 0; i < key.length(); i++) { if (isSeparator(key.charAt(i))) { if (!separator) { if (!stringLiteral) { if (buffer.length() > 0) { parts.add(buffer.toString()); buffer = new StringBuilder(); } separator = true; } else { buffer.append(key.charAt(i)); } } } else { if (Strings.isStringLiteralSeparator(key.charAt(i))) { stringLiteral = !stringLiteral; } else { buffer.append(key.charAt(i)); } separator = false; } } if (buffer.length() > 0) { parts.add(buffer.toString()); } return parts.iterator(); } } | BracketDotKeySplitter extends AbstractConfigurationAware implements KeySplitter { @Override public Iterator<String> split(String key) { if (key.equals(Strings.DOT) || key.equals(Strings.THIS)) { return Iterables.singletonIterator(key); } boolean stringLiteral = false; boolean separator = false; List<String> parts = new ArrayList<>(); StringBuilder buffer = new StringBuilder(); for (int i = 0; i < key.length(); i++) { if (isSeparator(key.charAt(i))) { if (!separator) { if (!stringLiteral) { if (buffer.length() > 0) { parts.add(buffer.toString()); buffer = new StringBuilder(); } separator = true; } else { buffer.append(key.charAt(i)); } } } else { if (Strings.isStringLiteralSeparator(key.charAt(i))) { stringLiteral = !stringLiteral; } else { buffer.append(key.charAt(i)); } separator = false; } } if (buffer.length() > 0) { parts.add(buffer.toString()); } return parts.iterator(); } } | BracketDotKeySplitter extends AbstractConfigurationAware implements KeySplitter { @Override public Iterator<String> split(String key) { if (key.equals(Strings.DOT) || key.equals(Strings.THIS)) { return Iterables.singletonIterator(key); } boolean stringLiteral = false; boolean separator = false; List<String> parts = new ArrayList<>(); StringBuilder buffer = new StringBuilder(); for (int i = 0; i < key.length(); i++) { if (isSeparator(key.charAt(i))) { if (!separator) { if (!stringLiteral) { if (buffer.length() > 0) { parts.add(buffer.toString()); buffer = new StringBuilder(); } separator = true; } else { buffer.append(key.charAt(i)); } } } else { if (Strings.isStringLiteralSeparator(key.charAt(i))) { stringLiteral = !stringLiteral; } else { buffer.append(key.charAt(i)); } separator = false; } } if (buffer.length() > 0) { parts.add(buffer.toString()); } return parts.iterator(); } @Override Iterator<String> split(String key); } | BracketDotKeySplitter extends AbstractConfigurationAware implements KeySplitter { @Override public Iterator<String> split(String key) { if (key.equals(Strings.DOT) || key.equals(Strings.THIS)) { return Iterables.singletonIterator(key); } boolean stringLiteral = false; boolean separator = false; List<String> parts = new ArrayList<>(); StringBuilder buffer = new StringBuilder(); for (int i = 0; i < key.length(); i++) { if (isSeparator(key.charAt(i))) { if (!separator) { if (!stringLiteral) { if (buffer.length() > 0) { parts.add(buffer.toString()); buffer = new StringBuilder(); } separator = true; } else { buffer.append(key.charAt(i)); } } } else { if (Strings.isStringLiteralSeparator(key.charAt(i))) { stringLiteral = !stringLiteral; } else { buffer.append(key.charAt(i)); } separator = false; } } if (buffer.length() > 0) { parts.add(buffer.toString()); } return parts.iterator(); } @Override Iterator<String> split(String key); } |
@Test public void testSplit() { DotKeySplitter splitter = new DotKeySplitter(); assertIterator(splitter.split("a..bar:.c"), "a", "bar:", "c"); assertIterator(splitter.split(". "), " "); assertIterator(splitter.split("."), "."); assertIterator(splitter.split("foo"), "foo"); } | @Override public Iterator<String> split(String key) { if (key.equals(Strings.DOT) || key.equals(Strings.THIS) || !key.contains(Strings.DOT)) { return Iterables.singletonIterator(key); } boolean separator = false; List<String> parts = new ArrayList<>(); StringBuilder buffer = new StringBuilder(); for (int i = 0; i < key.length(); i++) { if (isSeparator(key.charAt(i))) { if (!separator) { if (buffer.length() > 0) { parts.add(buffer.toString()); buffer = new StringBuilder(); } separator = true; } } else { buffer.append(key.charAt(i)); separator = false; } } if (buffer.length() > 0) { parts.add(buffer.toString()); } return parts.iterator(); } | DotKeySplitter extends AbstractConfigurationAware implements KeySplitter { @Override public Iterator<String> split(String key) { if (key.equals(Strings.DOT) || key.equals(Strings.THIS) || !key.contains(Strings.DOT)) { return Iterables.singletonIterator(key); } boolean separator = false; List<String> parts = new ArrayList<>(); StringBuilder buffer = new StringBuilder(); for (int i = 0; i < key.length(); i++) { if (isSeparator(key.charAt(i))) { if (!separator) { if (buffer.length() > 0) { parts.add(buffer.toString()); buffer = new StringBuilder(); } separator = true; } } else { buffer.append(key.charAt(i)); separator = false; } } if (buffer.length() > 0) { parts.add(buffer.toString()); } return parts.iterator(); } } | DotKeySplitter extends AbstractConfigurationAware implements KeySplitter { @Override public Iterator<String> split(String key) { if (key.equals(Strings.DOT) || key.equals(Strings.THIS) || !key.contains(Strings.DOT)) { return Iterables.singletonIterator(key); } boolean separator = false; List<String> parts = new ArrayList<>(); StringBuilder buffer = new StringBuilder(); for (int i = 0; i < key.length(); i++) { if (isSeparator(key.charAt(i))) { if (!separator) { if (buffer.length() > 0) { parts.add(buffer.toString()); buffer = new StringBuilder(); } separator = true; } } else { buffer.append(key.charAt(i)); separator = false; } } if (buffer.length() > 0) { parts.add(buffer.toString()); } return parts.iterator(); } } | DotKeySplitter extends AbstractConfigurationAware implements KeySplitter { @Override public Iterator<String> split(String key) { if (key.equals(Strings.DOT) || key.equals(Strings.THIS) || !key.contains(Strings.DOT)) { return Iterables.singletonIterator(key); } boolean separator = false; List<String> parts = new ArrayList<>(); StringBuilder buffer = new StringBuilder(); for (int i = 0; i < key.length(); i++) { if (isSeparator(key.charAt(i))) { if (!separator) { if (buffer.length() > 0) { parts.add(buffer.toString()); buffer = new StringBuilder(); } separator = true; } } else { buffer.append(key.charAt(i)); separator = false; } } if (buffer.length() > 0) { parts.add(buffer.toString()); } return parts.iterator(); } @Override Iterator<String> split(String key); } | DotKeySplitter extends AbstractConfigurationAware implements KeySplitter { @Override public Iterator<String> split(String key) { if (key.equals(Strings.DOT) || key.equals(Strings.THIS) || !key.contains(Strings.DOT)) { return Iterables.singletonIterator(key); } boolean separator = false; List<String> parts = new ArrayList<>(); StringBuilder buffer = new StringBuilder(); for (int i = 0; i < key.length(); i++) { if (isSeparator(key.charAt(i))) { if (!separator) { if (buffer.length() > 0) { parts.add(buffer.toString()); buffer = new StringBuilder(); } separator = true; } } else { buffer.append(key.charAt(i)); separator = false; } } if (buffer.length() > 0) { parts.add(buffer.toString()); } return parts.iterator(); } @Override Iterator<String> split(String key); } |
@Test public void testHelperIntOrLongLiteralPattern() { assertFalse(Patterns.newHelperIntegerLiteralPattern() .matcher("\"foo\"").matches()); assertTrue(Patterns.newHelperIntegerLiteralPattern().matcher("1") .matches()); assertTrue(Patterns.newHelperIntegerLiteralPattern().matcher("+12") .matches()); assertTrue(Patterns.newHelperIntegerLiteralPattern().matcher("-10000") .matches()); assertFalse(Patterns.newHelperIntegerLiteralPattern().matcher("1.0") .matches()); assertFalse(Patterns.newHelperIntegerLiteralPattern() .matcher("1000000000000").matches()); } | public static Pattern newHelperIntegerLiteralPattern() { return Pattern.compile("(\\+|-)?\\d{1,10}"); } | Patterns { public static Pattern newHelperIntegerLiteralPattern() { return Pattern.compile("(\\+|-)?\\d{1,10}"); } } | Patterns { public static Pattern newHelperIntegerLiteralPattern() { return Pattern.compile("(\\+|-)?\\d{1,10}"); } private Patterns(); } | Patterns { public static Pattern newHelperIntegerLiteralPattern() { return Pattern.compile("(\\+|-)?\\d{1,10}"); } private Patterns(); static Pattern newMustacheTagPattern(Configuration configuration); static Pattern newSetDelimitersContentPattern(); static Pattern newHelperIntegerLiteralPattern(); static Pattern newHelperLongLiteralPattern(); } | Patterns { public static Pattern newHelperIntegerLiteralPattern() { return Pattern.compile("(\\+|-)?\\d{1,10}"); } private Patterns(); static Pattern newMustacheTagPattern(Configuration configuration); static Pattern newSetDelimitersContentPattern(); static Pattern newHelperIntegerLiteralPattern(); static Pattern newHelperLongLiteralPattern(); } |
@Test public void testLocatorNoSuffix() throws IOException { TemplateLocator locator = FileSystemTemplateLocator.builder() .setRootPath("src/test/resources/locator/file").build(); MustacheEngineBuilder.newBuilder().addTemplateLocator(locator).build(); Set<String> ids = locator.getAllIdentifiers(); assertEquals(7, ids.size()); assertTrue(ids.contains("index.foo")); assertTrue(ids.contains("home.foo")); assertTrue(ids.contains("foo.foo")); assertTrue(ids.contains("detail.html")); assertTrue(ids.contains("encoding.html")); assertTrue(ids.contains("sub/bar.foo")); assertTrue(ids.contains("sub/subsub/qux.foo")); assertEquals("{{foo}}", read(locator.locate("index.foo"))); assertEquals("bar", read(locator.locate("home.foo"))); assertEquals("foo", read(locator.locate("foo.foo"))); assertEquals("<html/>", read(locator.locate("detail.html"))); assertEquals("{{foo}}", read(locator.locate("sub/bar.foo"))); assertEquals("{{bar}}", read(locator.locate("sub/subsub/qux.foo"))); } | public static Builder builder() { return new Builder(); } | FileSystemTemplateLocator extends FilePathTemplateLocator { public static Builder builder() { return new Builder(); } } | FileSystemTemplateLocator extends FilePathTemplateLocator { public static Builder builder() { return new Builder(); } FileSystemTemplateLocator(int priority, String rootPath); FileSystemTemplateLocator(int priority, String rootPath,
String suffix); } | FileSystemTemplateLocator extends FilePathTemplateLocator { public static Builder builder() { return new Builder(); } FileSystemTemplateLocator(int priority, String rootPath); FileSystemTemplateLocator(int priority, String rootPath,
String suffix); @Override Reader locateRealPath(String realPath); static Builder builder(); } | FileSystemTemplateLocator extends FilePathTemplateLocator { public static Builder builder() { return new Builder(); } FileSystemTemplateLocator(int priority, String rootPath); FileSystemTemplateLocator(int priority, String rootPath,
String suffix); @Override Reader locateRealPath(String realPath); static Builder builder(); } |
@Test public void testCustomVirtualPathSeparator() throws IOException { TemplateLocator locator = FileSystemTemplateLocator.builder() .setPriority(1).setRootPath("src/test/resources/locator/file") .setSuffix("foo").build(); MustacheEngineBuilder.newBuilder().addTemplateLocator(locator) .setProperty(PathTemplateLocator.VIRTUAL_PATH_SEPARATOR_KEY, "*") .build(); Set<String> names = locator.getAllIdentifiers(); assertEquals(5, names.size()); assertTrue(names.contains("index")); assertTrue(names.contains("home")); assertTrue(names.contains("foo")); assertTrue(names.contains("sub*bar")); assertTrue(names.contains("sub*subsub*qux")); assertEquals("{{foo}}", read(locator.locate("index"))); assertEquals("bar", read(locator.locate("home"))); assertEquals("{{foo}}", read(locator.locate("sub*bar"))); assertEquals("{{bar}}", read(locator.locate("sub*subsub*qux"))); } | public static Builder builder() { return new Builder(); } | FileSystemTemplateLocator extends FilePathTemplateLocator { public static Builder builder() { return new Builder(); } } | FileSystemTemplateLocator extends FilePathTemplateLocator { public static Builder builder() { return new Builder(); } FileSystemTemplateLocator(int priority, String rootPath); FileSystemTemplateLocator(int priority, String rootPath,
String suffix); } | FileSystemTemplateLocator extends FilePathTemplateLocator { public static Builder builder() { return new Builder(); } FileSystemTemplateLocator(int priority, String rootPath); FileSystemTemplateLocator(int priority, String rootPath,
String suffix); @Override Reader locateRealPath(String realPath); static Builder builder(); } | FileSystemTemplateLocator extends FilePathTemplateLocator { public static Builder builder() { return new Builder(); } FileSystemTemplateLocator(int priority, String rootPath); FileSystemTemplateLocator(int priority, String rootPath,
String suffix); @Override Reader locateRealPath(String realPath); static Builder builder(); } |
@Test public void testIsStandaloneLine() { assertTrue(SegmentBases.isStandaloneLine(ImmutableList.of( new SegmentBase(SegmentType.LINE_SEPARATOR, Strings.LINE_SEPARATOR_LF, 0, 0), new SegmentBase(SegmentType.TEXT, " ", 0, 0), new ContainerSegmentBase(SegmentType.SECTION, "test", 0, 0)))); assertFalse(SegmentBases.isStandaloneLine(ImmutableList.of( new SegmentBase(SegmentType.LINE_SEPARATOR, Strings.LINE_SEPARATOR_LF, 0, 0), new SegmentBase(SegmentType.TEXT, "Not empty", 0, 0), new ContainerSegmentBase(SegmentType.SECTION, "test", 0, 0)))); } | static boolean isStandaloneLine(List<SegmentBase> line) { boolean standaloneCandidate = false; for (SegmentBase segment : line) { if (SegmentType.VALUE.equals(segment.getType())) { return false; } else if (SegmentType.TEXT.equals(segment.getType())) { if (!Strings.containsOnlyWhitespace(segment.getContent())) { return false; } } else if (isStandaloneCandidate(segment.getType())) { standaloneCandidate = true; } } return standaloneCandidate; } | SegmentBases { static boolean isStandaloneLine(List<SegmentBase> line) { boolean standaloneCandidate = false; for (SegmentBase segment : line) { if (SegmentType.VALUE.equals(segment.getType())) { return false; } else if (SegmentType.TEXT.equals(segment.getType())) { if (!Strings.containsOnlyWhitespace(segment.getContent())) { return false; } } else if (isStandaloneCandidate(segment.getType())) { standaloneCandidate = true; } } return standaloneCandidate; } } | SegmentBases { static boolean isStandaloneLine(List<SegmentBase> line) { boolean standaloneCandidate = false; for (SegmentBase segment : line) { if (SegmentType.VALUE.equals(segment.getType())) { return false; } else if (SegmentType.TEXT.equals(segment.getType())) { if (!Strings.containsOnlyWhitespace(segment.getContent())) { return false; } } else if (isStandaloneCandidate(segment.getType())) { standaloneCandidate = true; } } return standaloneCandidate; } private SegmentBases(); } | SegmentBases { static boolean isStandaloneLine(List<SegmentBase> line) { boolean standaloneCandidate = false; for (SegmentBase segment : line) { if (SegmentType.VALUE.equals(segment.getType())) { return false; } else if (SegmentType.TEXT.equals(segment.getType())) { if (!Strings.containsOnlyWhitespace(segment.getContent())) { return false; } } else if (isStandaloneCandidate(segment.getType())) { standaloneCandidate = true; } } return standaloneCandidate; } private SegmentBases(); } | SegmentBases { static boolean isStandaloneLine(List<SegmentBase> line) { boolean standaloneCandidate = false; for (SegmentBase segment : line) { if (SegmentType.VALUE.equals(segment.getType())) { return false; } else if (SegmentType.TEXT.equals(segment.getType())) { if (!Strings.containsOnlyWhitespace(segment.getContent())) { return false; } } else if (isStandaloneCandidate(segment.getType())) { standaloneCandidate = true; } } return standaloneCandidate; } private SegmentBases(); } |
@Test public void testClearData() { EnhancedStatsCollector collector = new EnhancedStatsCollector(); Mustache mustache = MustacheEngineBuilder.newBuilder() .addMustacheListener(collector).build() .compileMustache("bar", "BAR"); mustache.render(null); assertEquals(1, collector.getStats(mustache).getFinished()); collector.clearData(); assertNull(collector.getStats(mustache)); } | public void clearData() { data.clear(); } | EnhancedStatsCollector extends AbstractStatsCollector { public void clearData() { data.clear(); } } | EnhancedStatsCollector extends AbstractStatsCollector { public void clearData() { data.clear(); } EnhancedStatsCollector(); EnhancedStatsCollector(Predicate<String> templatePredicate,
TimeUnit timeUnit); } | EnhancedStatsCollector extends AbstractStatsCollector { public void clearData() { data.clear(); } EnhancedStatsCollector(); EnhancedStatsCollector(Predicate<String> templatePredicate,
TimeUnit timeUnit); @Override void renderingStarted(MustacheRenderingEvent event); @Override void renderingFinished(MustacheRenderingEvent event); Stats getStats(Mustache mustache); Set<Stats> getStats(); Collection<ExecutionData> getRawData(Mustache mustache); void clearData(); } | EnhancedStatsCollector extends AbstractStatsCollector { public void clearData() { data.clear(); } EnhancedStatsCollector(); EnhancedStatsCollector(Predicate<String> templatePredicate,
TimeUnit timeUnit); @Override void renderingStarted(MustacheRenderingEvent event); @Override void renderingFinished(MustacheRenderingEvent event); Stats getStats(Mustache mustache); Set<Stats> getStats(); Collection<ExecutionData> getRawData(Mustache mustache); void clearData(); static final String COMPUTING_CACHE_CONSUMER_ID; } |
@Test public void testCustomPredicate() { EnhancedStatsCollector collector = new EnhancedStatsCollector( (t) -> false, TimeUnit.DAYS); Mustache mustache = MustacheEngineBuilder.newBuilder() .addMustacheListener(collector).build() .compileMustache("qux", "Oops"); mustache.render(null); assertNull(collector.getStats(mustache)); } | public Stats getStats(Mustache mustache) { Checker.checkArgumentNotNull(mustache); ConcurrentMap<Long, ExecutionData> times = data.getIfPresent(mustache .getGeneratedId()); if (times != null) { return parseData(mustache.getName(), mustache.getGeneratedId(), times.values()); } return null; } | EnhancedStatsCollector extends AbstractStatsCollector { public Stats getStats(Mustache mustache) { Checker.checkArgumentNotNull(mustache); ConcurrentMap<Long, ExecutionData> times = data.getIfPresent(mustache .getGeneratedId()); if (times != null) { return parseData(mustache.getName(), mustache.getGeneratedId(), times.values()); } return null; } } | EnhancedStatsCollector extends AbstractStatsCollector { public Stats getStats(Mustache mustache) { Checker.checkArgumentNotNull(mustache); ConcurrentMap<Long, ExecutionData> times = data.getIfPresent(mustache .getGeneratedId()); if (times != null) { return parseData(mustache.getName(), mustache.getGeneratedId(), times.values()); } return null; } EnhancedStatsCollector(); EnhancedStatsCollector(Predicate<String> templatePredicate,
TimeUnit timeUnit); } | EnhancedStatsCollector extends AbstractStatsCollector { public Stats getStats(Mustache mustache) { Checker.checkArgumentNotNull(mustache); ConcurrentMap<Long, ExecutionData> times = data.getIfPresent(mustache .getGeneratedId()); if (times != null) { return parseData(mustache.getName(), mustache.getGeneratedId(), times.values()); } return null; } EnhancedStatsCollector(); EnhancedStatsCollector(Predicate<String> templatePredicate,
TimeUnit timeUnit); @Override void renderingStarted(MustacheRenderingEvent event); @Override void renderingFinished(MustacheRenderingEvent event); Stats getStats(Mustache mustache); Set<Stats> getStats(); Collection<ExecutionData> getRawData(Mustache mustache); void clearData(); } | EnhancedStatsCollector extends AbstractStatsCollector { public Stats getStats(Mustache mustache) { Checker.checkArgumentNotNull(mustache); ConcurrentMap<Long, ExecutionData> times = data.getIfPresent(mustache .getGeneratedId()); if (times != null) { return parseData(mustache.getName(), mustache.getGeneratedId(), times.values()); } return null; } EnhancedStatsCollector(); EnhancedStatsCollector(Predicate<String> templatePredicate,
TimeUnit timeUnit); @Override void renderingStarted(MustacheRenderingEvent event); @Override void renderingFinished(MustacheRenderingEvent event); Stats getStats(Mustache mustache); Set<Stats> getStats(); Collection<ExecutionData> getRawData(Mustache mustache); void clearData(); static final String COMPUTING_CACHE_CONSUMER_ID; } |
@Test public void testClearData() { SimpleStatsCollector collector = new SimpleStatsCollector(); Mustache mustache = MustacheEngineBuilder.newBuilder() .addMustacheListener(collector).build() .compileMustache("bar", "BAR"); mustache.render(null); assertEquals(1, collector.getSimpleStats("bar").getExecutions()); collector.clearData(); assertNull(collector.getSimpleStats("bar")); } | public void clearData() { data.clear(); } | SimpleStatsCollector extends AbstractStatsCollector { public void clearData() { data.clear(); } } | SimpleStatsCollector extends AbstractStatsCollector { public void clearData() { data.clear(); } SimpleStatsCollector(); SimpleStatsCollector(Predicate<String> templatePredicate,
TimeUnit timeUnit); } | SimpleStatsCollector extends AbstractStatsCollector { public void clearData() { data.clear(); } SimpleStatsCollector(); SimpleStatsCollector(Predicate<String> templatePredicate,
TimeUnit timeUnit); @Override void init(); @Override void renderingStarted(final MustacheRenderingEvent event); void clearData(); Map<Long, Long> getData(String templateId); Map<String, Map<Long, Long>> getData(); SimpleStats getSimpleStats(String templateId); Set<SimpleStats> getSimpleStats(); } | SimpleStatsCollector extends AbstractStatsCollector { public void clearData() { data.clear(); } SimpleStatsCollector(); SimpleStatsCollector(Predicate<String> templatePredicate,
TimeUnit timeUnit); @Override void init(); @Override void renderingStarted(final MustacheRenderingEvent event); void clearData(); Map<Long, Long> getData(String templateId); Map<String, Map<Long, Long>> getData(); SimpleStats getSimpleStats(String templateId); Set<SimpleStats> getSimpleStats(); static final String COMPUTING_CACHE_CONSUMER_ID; } |
@Test public void testCustomPredicate() { SimpleStatsCollector collector = new SimpleStatsCollector((t) -> false, TimeUnit.DAYS); Mustache mustache = MustacheEngineBuilder.newBuilder() .addMustacheListener(collector).build() .compileMustache("qux", "Oops"); mustache.render(null); assertNull(collector.getSimpleStats("qux")); } | public SimpleStats getSimpleStats(String templateId) { ComputingCache<Long, AtomicLong> entry = data.getIfPresent(templateId); if (entry != null) { return new SimpleStats(templateId, entry.getAllPresent()); } return null; } | SimpleStatsCollector extends AbstractStatsCollector { public SimpleStats getSimpleStats(String templateId) { ComputingCache<Long, AtomicLong> entry = data.getIfPresent(templateId); if (entry != null) { return new SimpleStats(templateId, entry.getAllPresent()); } return null; } } | SimpleStatsCollector extends AbstractStatsCollector { public SimpleStats getSimpleStats(String templateId) { ComputingCache<Long, AtomicLong> entry = data.getIfPresent(templateId); if (entry != null) { return new SimpleStats(templateId, entry.getAllPresent()); } return null; } SimpleStatsCollector(); SimpleStatsCollector(Predicate<String> templatePredicate,
TimeUnit timeUnit); } | SimpleStatsCollector extends AbstractStatsCollector { public SimpleStats getSimpleStats(String templateId) { ComputingCache<Long, AtomicLong> entry = data.getIfPresent(templateId); if (entry != null) { return new SimpleStats(templateId, entry.getAllPresent()); } return null; } SimpleStatsCollector(); SimpleStatsCollector(Predicate<String> templatePredicate,
TimeUnit timeUnit); @Override void init(); @Override void renderingStarted(final MustacheRenderingEvent event); void clearData(); Map<Long, Long> getData(String templateId); Map<String, Map<Long, Long>> getData(); SimpleStats getSimpleStats(String templateId); Set<SimpleStats> getSimpleStats(); } | SimpleStatsCollector extends AbstractStatsCollector { public SimpleStats getSimpleStats(String templateId) { ComputingCache<Long, AtomicLong> entry = data.getIfPresent(templateId); if (entry != null) { return new SimpleStats(templateId, entry.getAllPresent()); } return null; } SimpleStatsCollector(); SimpleStatsCollector(Predicate<String> templatePredicate,
TimeUnit timeUnit); @Override void init(); @Override void renderingStarted(final MustacheRenderingEvent event); void clearData(); Map<Long, Long> getData(String templateId); Map<String, Map<Long, Long>> getData(); SimpleStats getSimpleStats(String templateId); Set<SimpleStats> getSimpleStats(); static final String COMPUTING_CACHE_CONSUMER_ID; } |
@Test public void testConverter() { String pattern = "yyyy.MM.dd HH:mm:ss.SSS"; SimpleDateFormat format = new SimpleDateFormat(pattern); ObjectToDateConverter converter = new ObjectToDateConverter(pattern); Date now = new Date(); Calendar cal = Calendar.getInstance(); Calendar midnight = Calendar.getInstance(); midnight.set(Calendar.HOUR_OF_DAY, 0); midnight.set(Calendar.MINUTE, 0); midnight.set(Calendar.SECOND, 0); midnight.set(Calendar.MILLISECOND, 0); LocalDateTime dateTime = LocalDateTime.ofInstant(now.toInstant(), ZoneId.systemDefault()); LocalDate date = LocalDateTime.ofInstant(midnight.toInstant(), ZoneId.systemDefault()).toLocalDate(); assertNull(converter.convert(Float.MIN_NORMAL)); assertEquals(now, converter.convert(BigDecimal.valueOf(now.getTime()))); assertEquals(now, converter.convert(now)); assertEquals(now, converter.convert(now.getTime())); assertEquals(cal.getTime(), converter.convert(cal)); assertEquals(now, converter.convert(format.format(now))); assertEquals(now, converter.convert(dateTime)); assertEquals(midnight.getTime(), converter.convert(date)); } | @Override public Date convert(Object value) { Date converted = null; if (value instanceof Date) { converted = (Date) value; } else if (value instanceof Calendar) { converted = ((Calendar) value).getTime(); } else if (value instanceof LocalDateTime) { converted = Date.from(((LocalDateTime) value) .atZone(ZoneId.systemDefault()).toInstant()); } else if (value instanceof LocalDate) { converted = Date.from(((LocalDate) value) .atStartOfDay(ZoneId.systemDefault()).toInstant()); } else if (value instanceof Long) { converted = new Date((Long) value); } else if (value instanceof BigDecimal) { converted = new Date(((BigDecimal) value).longValue()); } else if (value instanceof String && pattern != null) { try { converted = new SimpleDateFormat(pattern).parse((String) value); } catch (ParseException e) { throw new MustacheException( MustacheProblem.RENDER_GENERIC_ERROR, "Unable to parse the string value %s using pattern %s", value, pattern); } } return converted; } | ObjectToDateConverter implements Converter<Object, Date> { @Override public Date convert(Object value) { Date converted = null; if (value instanceof Date) { converted = (Date) value; } else if (value instanceof Calendar) { converted = ((Calendar) value).getTime(); } else if (value instanceof LocalDateTime) { converted = Date.from(((LocalDateTime) value) .atZone(ZoneId.systemDefault()).toInstant()); } else if (value instanceof LocalDate) { converted = Date.from(((LocalDate) value) .atStartOfDay(ZoneId.systemDefault()).toInstant()); } else if (value instanceof Long) { converted = new Date((Long) value); } else if (value instanceof BigDecimal) { converted = new Date(((BigDecimal) value).longValue()); } else if (value instanceof String && pattern != null) { try { converted = new SimpleDateFormat(pattern).parse((String) value); } catch (ParseException e) { throw new MustacheException( MustacheProblem.RENDER_GENERIC_ERROR, "Unable to parse the string value %s using pattern %s", value, pattern); } } return converted; } } | ObjectToDateConverter implements Converter<Object, Date> { @Override public Date convert(Object value) { Date converted = null; if (value instanceof Date) { converted = (Date) value; } else if (value instanceof Calendar) { converted = ((Calendar) value).getTime(); } else if (value instanceof LocalDateTime) { converted = Date.from(((LocalDateTime) value) .atZone(ZoneId.systemDefault()).toInstant()); } else if (value instanceof LocalDate) { converted = Date.from(((LocalDate) value) .atStartOfDay(ZoneId.systemDefault()).toInstant()); } else if (value instanceof Long) { converted = new Date((Long) value); } else if (value instanceof BigDecimal) { converted = new Date(((BigDecimal) value).longValue()); } else if (value instanceof String && pattern != null) { try { converted = new SimpleDateFormat(pattern).parse((String) value); } catch (ParseException e) { throw new MustacheException( MustacheProblem.RENDER_GENERIC_ERROR, "Unable to parse the string value %s using pattern %s", value, pattern); } } return converted; } ObjectToDateConverter(); ObjectToDateConverter(String pattern); } | ObjectToDateConverter implements Converter<Object, Date> { @Override public Date convert(Object value) { Date converted = null; if (value instanceof Date) { converted = (Date) value; } else if (value instanceof Calendar) { converted = ((Calendar) value).getTime(); } else if (value instanceof LocalDateTime) { converted = Date.from(((LocalDateTime) value) .atZone(ZoneId.systemDefault()).toInstant()); } else if (value instanceof LocalDate) { converted = Date.from(((LocalDate) value) .atStartOfDay(ZoneId.systemDefault()).toInstant()); } else if (value instanceof Long) { converted = new Date((Long) value); } else if (value instanceof BigDecimal) { converted = new Date(((BigDecimal) value).longValue()); } else if (value instanceof String && pattern != null) { try { converted = new SimpleDateFormat(pattern).parse((String) value); } catch (ParseException e) { throw new MustacheException( MustacheProblem.RENDER_GENERIC_ERROR, "Unable to parse the string value %s using pattern %s", value, pattern); } } return converted; } ObjectToDateConverter(); ObjectToDateConverter(String pattern); @Override Date convert(Object value); } | ObjectToDateConverter implements Converter<Object, Date> { @Override public Date convert(Object value) { Date converted = null; if (value instanceof Date) { converted = (Date) value; } else if (value instanceof Calendar) { converted = ((Calendar) value).getTime(); } else if (value instanceof LocalDateTime) { converted = Date.from(((LocalDateTime) value) .atZone(ZoneId.systemDefault()).toInstant()); } else if (value instanceof LocalDate) { converted = Date.from(((LocalDate) value) .atStartOfDay(ZoneId.systemDefault()).toInstant()); } else if (value instanceof Long) { converted = new Date((Long) value); } else if (value instanceof BigDecimal) { converted = new Date(((BigDecimal) value).longValue()); } else if (value instanceof String && pattern != null) { try { converted = new SimpleDateFormat(pattern).parse((String) value); } catch (ParseException e) { throw new MustacheException( MustacheProblem.RENDER_GENERIC_ERROR, "Unable to parse the string value %s using pattern %s", value, pattern); } } return converted; } ObjectToDateConverter(); ObjectToDateConverter(String pattern); @Override Date convert(Object value); } |
@SuppressWarnings("unchecked") @Test public void testInterpolation() { MustacheEngine engine = MustacheEngineBuilder.newBuilder() .addContextConverter(decorate(String.class) .compute("reverse", string -> new StringBuilder(string).reverse().toString()).build()) .addContextConverter(decorate(Hammer.class).put("translate", "kladivo") .compute("name", hammer -> hammer.getName().toUpperCase()).build()) .addContextConverter(decorate(List.class).compute("reversed", list -> { List<?> reversed = new ArrayList<>(list); Collections.reverse(reversed); return reversed; }).build()).build(); assertEquals("ooF", engine.compileMustache("{{reverse}}").render("Foo")); assertEquals("kladivo EDGAR 10", engine.compileMustache("{{translate}} {{name}} {{age}}").render(new Hammer())); assertEquals("bravo:charlie:alpha:", engine.compileMustache("{{#each this.reversed}}{{.}}:{{/each}}") .render(ImmutableList.of("alpha", "charlie", "bravo"))); assertEquals("EDGAR 1000", engine.compileMustache("{{name}} {{age}}") .render(decorate(new Hammer()).put("age", 1000).build(engine))); } | public static <T> Builder<T> decorate(Class<T> delegateType) { return decorate(o -> (delegateType.isAssignableFrom(Decorator.unwrap(o).getClass()))); } | DecoratorConverter extends AbstractConfigurationAware implements ContextConverter { public static <T> Builder<T> decorate(Class<T> delegateType) { return decorate(o -> (delegateType.isAssignableFrom(Decorator.unwrap(o).getClass()))); } } | DecoratorConverter extends AbstractConfigurationAware implements ContextConverter { public static <T> Builder<T> decorate(Class<T> delegateType) { return decorate(o -> (delegateType.isAssignableFrom(Decorator.unwrap(o).getClass()))); } private DecoratorConverter(Predicate<Object> test, String delegateKey, Map<String, Function<T, Object>> mappings); } | DecoratorConverter extends AbstractConfigurationAware implements ContextConverter { public static <T> Builder<T> decorate(Class<T> delegateType) { return decorate(o -> (delegateType.isAssignableFrom(Decorator.unwrap(o).getClass()))); } private DecoratorConverter(Predicate<Object> test, String delegateKey, Map<String, Function<T, Object>> mappings); static Builder<T> decorate(Class<T> delegateType); static Builder<T> decorate(Predicate<Object> test); @SuppressWarnings("unchecked") @Override Object convert(Object from); } | DecoratorConverter extends AbstractConfigurationAware implements ContextConverter { public static <T> Builder<T> decorate(Class<T> delegateType) { return decorate(o -> (delegateType.isAssignableFrom(Decorator.unwrap(o).getClass()))); } private DecoratorConverter(Predicate<Object> test, String delegateKey, Map<String, Function<T, Object>> mappings); static Builder<T> decorate(Class<T> delegateType); static Builder<T> decorate(Predicate<Object> test); @SuppressWarnings("unchecked") @Override Object convert(Object from); } |
@Test public void testGetDelegate() { MustacheEngine engine = MustacheEngineBuilder.newBuilder() .addContextConverter(decorate(Hammer.class).compute("name", h -> h.getName().toUpperCase()).build()) .build(); Hammer hammer = new Hammer(); assertEquals("EDGAR vs Edgar", engine.compileMustache("{{name}} vs {{delegate.name}}").render(hammer)); } | public static <T> Builder<T> decorate(Class<T> delegateType) { return decorate(o -> (delegateType.isAssignableFrom(Decorator.unwrap(o).getClass()))); } | DecoratorConverter extends AbstractConfigurationAware implements ContextConverter { public static <T> Builder<T> decorate(Class<T> delegateType) { return decorate(o -> (delegateType.isAssignableFrom(Decorator.unwrap(o).getClass()))); } } | DecoratorConverter extends AbstractConfigurationAware implements ContextConverter { public static <T> Builder<T> decorate(Class<T> delegateType) { return decorate(o -> (delegateType.isAssignableFrom(Decorator.unwrap(o).getClass()))); } private DecoratorConverter(Predicate<Object> test, String delegateKey, Map<String, Function<T, Object>> mappings); } | DecoratorConverter extends AbstractConfigurationAware implements ContextConverter { public static <T> Builder<T> decorate(Class<T> delegateType) { return decorate(o -> (delegateType.isAssignableFrom(Decorator.unwrap(o).getClass()))); } private DecoratorConverter(Predicate<Object> test, String delegateKey, Map<String, Function<T, Object>> mappings); static Builder<T> decorate(Class<T> delegateType); static Builder<T> decorate(Predicate<Object> test); @SuppressWarnings("unchecked") @Override Object convert(Object from); } | DecoratorConverter extends AbstractConfigurationAware implements ContextConverter { public static <T> Builder<T> decorate(Class<T> delegateType) { return decorate(o -> (delegateType.isAssignableFrom(Decorator.unwrap(o).getClass()))); } private DecoratorConverter(Predicate<Object> test, String delegateKey, Map<String, Function<T, Object>> mappings); static Builder<T> decorate(Class<T> delegateType); static Builder<T> decorate(Predicate<Object> test); @SuppressWarnings("unchecked") @Override Object convert(Object from); } |
@Test public void testReplace() { assertEquals("foobar", Strings.replace("foo:bar", ":", "")); } | public static String replace(String text, String search, String replacement) { if (isEmpty(text) || isEmpty(search) || replacement == null) { return text; } int start = 0; int end = text.indexOf(search, start); if (end == -1) { return text; } StringBuilder builder = new StringBuilder(); while (end != -1) { builder.append(text.substring(start, end)); builder.append(replacement); start = end + search.length(); end = text.indexOf(search, start); } builder.append(text.substring(start)); return builder.toString(); } | Strings { public static String replace(String text, String search, String replacement) { if (isEmpty(text) || isEmpty(search) || replacement == null) { return text; } int start = 0; int end = text.indexOf(search, start); if (end == -1) { return text; } StringBuilder builder = new StringBuilder(); while (end != -1) { builder.append(text.substring(start, end)); builder.append(replacement); start = end + search.length(); end = text.indexOf(search, start); } builder.append(text.substring(start)); return builder.toString(); } } | Strings { public static String replace(String text, String search, String replacement) { if (isEmpty(text) || isEmpty(search) || replacement == null) { return text; } int start = 0; int end = text.indexOf(search, start); if (end == -1) { return text; } StringBuilder builder = new StringBuilder(); while (end != -1) { builder.append(text.substring(start, end)); builder.append(replacement); start = end + search.length(); end = text.indexOf(search, start); } builder.append(text.substring(start)); return builder.toString(); } private Strings(); } | Strings { public static String replace(String text, String search, String replacement) { if (isEmpty(text) || isEmpty(search) || replacement == null) { return text; } int start = 0; int end = text.indexOf(search, start); if (end == -1) { return text; } StringBuilder builder = new StringBuilder(); while (end != -1) { builder.append(text.substring(start, end)); builder.append(replacement); start = end + search.length(); end = text.indexOf(search, start); } builder.append(text.substring(start)); return builder.toString(); } private Strings(); static boolean isStringLiteralSeparator(char character); static boolean isEmpty(CharSequence sequence); static String uncapitalize(String word); static String capitalizeFully(String text, Character delimiter); static String replace(String text, String search,
String replacement); static String removeSuffix(String text, String suffix); static List<String> split(String text, String delimiter); static boolean containsWhitespace(String text); static boolean containsOnlyWhitespace(String text); static boolean containsOnlyDigits(String text); static String repeat(String text, int times, String separator); static String substringAfter(String text, String delimiter); static boolean isListLiteralStart(char character); static boolean isListLiteralEnd(char character); static boolean isListLiteral(String value); } | Strings { public static String replace(String text, String search, String replacement) { if (isEmpty(text) || isEmpty(search) || replacement == null) { return text; } int start = 0; int end = text.indexOf(search, start); if (end == -1) { return text; } StringBuilder builder = new StringBuilder(); while (end != -1) { builder.append(text.substring(start, end)); builder.append(replacement); start = end + search.length(); end = text.indexOf(search, start); } builder.append(text.substring(start)); return builder.toString(); } private Strings(); static boolean isStringLiteralSeparator(char character); static boolean isEmpty(CharSequence sequence); static String uncapitalize(String word); static String capitalizeFully(String text, Character delimiter); static String replace(String text, String search,
String replacement); static String removeSuffix(String text, String suffix); static List<String> split(String text, String delimiter); static boolean containsWhitespace(String text); static boolean containsOnlyWhitespace(String text); static boolean containsOnlyDigits(String text); static String repeat(String text, int times, String separator); static String substringAfter(String text, String delimiter); static boolean isListLiteralStart(char character); static boolean isListLiteralEnd(char character); static boolean isListLiteral(String value); static final String EMPTY; static final String GAP; static final String LINE_SEPARATOR; static final String LINE_SEPARATOR_LF; static final String LINE_SEPARATOR_CRLF; static final String LINE_SEPARATOR_CR; static final String SLASH; static final String FILE_SEPARATOR; static final String DOT; static final String UNDERSCORE; static final String NOT_AVAILABLE; static final String URL_PROCOTOL_FILE; static final String THIS; static final String HASH; } |
@Test public void testLogHelper() { String name = "MyLogger"; TestLoggerAdapter adapter = new TestLoggerAdapter(name); MustacheEngine engine = MustacheEngineBuilder.newBuilder() .registerHelpers(HelpersBuilder.empty() .add("log", LogHelper.builder().setDefaultLevel(Level.INFO) .setLoggerAdapter(adapter).build()) .build()) .build(); String msg = "Hello me!"; engine.compileMustache("log_helper1", "{{log \"" + msg + "\" level=\"WARN\"}}").render(null); assertEquals(Level.WARN, adapter.getLevels().get(0)); assertEquals(msg + " [log_helper1:1]", adapter.getMessages().get(0)); assertEquals(adapter.getParameters().get(0).length, 0); msg = "Hello {}!"; engine.compileMustache("log_helper2", "{{log this \"me\"}}") .render(msg); assertEquals(Level.INFO, adapter.getLevels().get(1)); assertEquals(msg + " [log_helper2:1]", adapter.getMessages().get(1)); assertEquals(adapter.getParameters().get(1).length, 1); engine = MustacheEngineBuilder.newBuilder() .registerHelpers(HelpersBuilder.empty() .add("log", LogHelper.builder().setAppendTemplateInfo(false) .setDefaultLevel(Level.INFO) .setLoggerAdapter(adapter).build()) .build()) .build(); engine.compileMustache("log_helper3", "{{log \"" + msg + "\"}}") .render(null); assertEquals(Level.INFO, adapter.getLevels().get(2)); assertEquals(msg, adapter.getMessages().get(2)); assertEquals(adapter.getParameters().get(2).length, 0); } | public LogHelper(LoggerAdapter adapter, Level defaultLevel, boolean appendTemplateInfo) { Checker.checkArgumentsNotNull(adapter, defaultLevel); this.defaultLevel = defaultLevel; this.adapter = adapter; this.appendTemplateInfo = appendTemplateInfo; } | LogHelper extends BasicValueHelper { public LogHelper(LoggerAdapter adapter, Level defaultLevel, boolean appendTemplateInfo) { Checker.checkArgumentsNotNull(adapter, defaultLevel); this.defaultLevel = defaultLevel; this.adapter = adapter; this.appendTemplateInfo = appendTemplateInfo; } } | LogHelper extends BasicValueHelper { public LogHelper(LoggerAdapter adapter, Level defaultLevel, boolean appendTemplateInfo) { Checker.checkArgumentsNotNull(adapter, defaultLevel); this.defaultLevel = defaultLevel; this.adapter = adapter; this.appendTemplateInfo = appendTemplateInfo; } LogHelper(LoggerAdapter adapter, Level defaultLevel,
boolean appendTemplateInfo); } | LogHelper extends BasicValueHelper { public LogHelper(LoggerAdapter adapter, Level defaultLevel, boolean appendTemplateInfo) { Checker.checkArgumentsNotNull(adapter, defaultLevel); this.defaultLevel = defaultLevel; this.adapter = adapter; this.appendTemplateInfo = appendTemplateInfo; } LogHelper(LoggerAdapter adapter, Level defaultLevel,
boolean appendTemplateInfo); @Override void execute(Options options); static Builder builder(); } | LogHelper extends BasicValueHelper { public LogHelper(LoggerAdapter adapter, Level defaultLevel, boolean appendTemplateInfo) { Checker.checkArgumentsNotNull(adapter, defaultLevel); this.defaultLevel = defaultLevel; this.adapter = adapter; this.appendTemplateInfo = appendTemplateInfo; } LogHelper(LoggerAdapter adapter, Level defaultLevel,
boolean appendTemplateInfo); @Override void execute(Options options); static Builder builder(); } |
@Test public void testLogHelperValidation() { final MustacheEngine engine = MustacheEngineBuilder.newBuilder() .registerHelpers(HelpersBuilder.empty() .add("log", LogHelper.builder().build()).build()) .build(); MustacheExceptionAssert .expect(MustacheProblem.COMPILE_HELPER_VALIDATION_FAILURE) .check(() -> engine.compileMustache("log_helper_validation01", "{{#log \"Foo\"}}{{/log}}")) .check(() -> engine.compileMustache("log_helper_validation02", "{{log}}")); } | public static Builder builder() { return new Builder(); } | LogHelper extends BasicValueHelper { public static Builder builder() { return new Builder(); } } | LogHelper extends BasicValueHelper { public static Builder builder() { return new Builder(); } LogHelper(LoggerAdapter adapter, Level defaultLevel,
boolean appendTemplateInfo); } | LogHelper extends BasicValueHelper { public static Builder builder() { return new Builder(); } LogHelper(LoggerAdapter adapter, Level defaultLevel,
boolean appendTemplateInfo); @Override void execute(Options options); static Builder builder(); } | LogHelper extends BasicValueHelper { public static Builder builder() { return new Builder(); } LogHelper(LoggerAdapter adapter, Level defaultLevel,
boolean appendTemplateInfo); @Override void execute(Options options); static Builder builder(); } |
@SuppressWarnings("unchecked") @Test public void testHelper() { final MustacheEngine engine = MustacheEngineBuilder.newBuilder() .registerHelper("decorateCat", decorate(Cat.class).put("const", "Cat") .compute("name", cat -> cat.getName().toUpperCase()) .compute("overweight", (cat) -> cat.getWeight() > 4500 ? cat.getWeight() - 4500 : 0).build()) .registerHelper("decorateIntList", decorate(List.class) .compute("sum", l -> l.stream().mapToInt(e -> Integer.valueOf(e.toString())).sum()).build()) .registerHelper("dummy", decorate(String.class).delegateKey("foo").compute("toUpperCase", s -> s.toLowerCase()).build()) .registerHelper("decorateStr", decorate(String.class) .compute("reverse", s -> new StringBuilder(s).reverse().toString()).build()) .build(); assertEquals("ooF", engine.compileMustache("{{#decorateStr}}{{reverse}}{{/decorateStr}}").render("Foo")); List<Cat> cats = new ArrayList<>(); cats.add(new Cat("Mikes", 3000)); cats.add(new Cat("Mourek", 5000)); assertEquals("Cat MIKES [3000g] has overweight 0g.Cat MOUREK [5000g] has overweight 500g.", engine.compileMustache( "{{#each}}{{#decorateCat}}{{const}} {{name}} [{{weight}}g] has overweight {{overweight}}g.{{/decorateCat}}{{/each}}") .render(cats)); try { engine.compileMustache("{{#decorateCat}}{{name}}{{/decorateCat}}").render("foo"); fail(); } catch (IllegalStateException expected) { } assertEquals("6:123", engine.compileMustache("{{#decorateIntList}}{{sum}}:{{#each}}{{.}}{{/each}}{{/decorateIntList}}") .render(Arrays.asList(1, 2, 3))); assertEquals("lu vs LU", engine.compileMustache("{{#dummy}}{{toUpperCase}} vs {{foo.toUpperCase}}{{/dummy}}").render("Lu")); } | public static <T> Builder<T> decorate(Class<T> delegateType) { return new Builder<>(o -> delegateType.isAssignableFrom(o.getClass())); } | DecoratorHelper extends BasicSectionHelper { public static <T> Builder<T> decorate(Class<T> delegateType) { return new Builder<>(o -> delegateType.isAssignableFrom(o.getClass())); } } | DecoratorHelper extends BasicSectionHelper { public static <T> Builder<T> decorate(Class<T> delegateType) { return new Builder<>(o -> delegateType.isAssignableFrom(o.getClass())); } private DecoratorHelper(Predicate<Object> test, Map<String, Function<T, Object>> mappings, String delegateKey); } | DecoratorHelper extends BasicSectionHelper { public static <T> Builder<T> decorate(Class<T> delegateType) { return new Builder<>(o -> delegateType.isAssignableFrom(o.getClass())); } private DecoratorHelper(Predicate<Object> test, Map<String, Function<T, Object>> mappings, String delegateKey); static Builder<T> decorate(Class<T> delegateType); static Builder<T> decorate(Predicate<Object> test); @SuppressWarnings("unchecked") @Override void execute(Options options); } | DecoratorHelper extends BasicSectionHelper { public static <T> Builder<T> decorate(Class<T> delegateType) { return new Builder<>(o -> delegateType.isAssignableFrom(o.getClass())); } private DecoratorHelper(Predicate<Object> test, Map<String, Function<T, Object>> mappings, String delegateKey); static Builder<T> decorate(Class<T> delegateType); static Builder<T> decorate(Predicate<Object> test); @SuppressWarnings("unchecked") @Override void execute(Options options); } |
@Test public void testEqualsHelper() { MustacheEngine engine = MustacheEngineBuilder.newBuilder() .addGlobalData("archiveType", ArchiveType.class) .registerHelpers(HelpersBuilder.empty().addIsEqual() .addIsNotEqual().build()) .build(); assertEquals("EQUALS", engine.compileMustache("equals_helper1", "{{#isEq this.age this.age}}EQUALS{{/isEq}}") .render(new Hammer())); assertEquals( "EQUALS", engine .compileMustache("equals_helper2", "{{#isEq this}}EQUALS{{/isEq}}") .render(new Hammer())); assertEquals("NOT_EQUALS", engine.compileMustache("equals_helper3", "{{#isNotEq this.age}}NOT_EQUALS{{/isNotEq}}") .render(new Hammer())); assertEquals("NOT_EQUALS", engine.compileMustache("equals_helper4", "{{#isNotEq this.age this.toString}}NOT_EQUALS{{/isNotEq}}") .render(new Hammer())); assertEquals("It's a WAR!", engine .compileMustache("equals_helper5", "{{#with this.archiveType}}" + "{{#isEq archiveType.WAR}}" + "It's a WAR!" + "{{/isEq}}" + "{{#isEq archiveType.EAR}}" + "It's an EAR!" + "{{/isEq}}" + "{{/with}}") .render(new Hammer())); } | public EqualsHelper() { this(false); } | EqualsHelper extends BasicSectionHelper { public EqualsHelper() { this(false); } } | EqualsHelper extends BasicSectionHelper { public EqualsHelper() { this(false); } EqualsHelper(); EqualsHelper(boolean testInequality); } | EqualsHelper extends BasicSectionHelper { public EqualsHelper() { this(false); } EqualsHelper(); EqualsHelper(boolean testInequality); @Override void execute(Options options); } | EqualsHelper extends BasicSectionHelper { public EqualsHelper() { this(false); } EqualsHelper(); EqualsHelper(boolean testInequality); @Override void execute(Options options); } |
@Test public void testHelper() { final MustacheEngine engine = MustacheEngineBuilder.newBuilder() .registerHelpers(HelpersBuilder.empty().addInvoke().build()) .build(); List<String> list = ImmutableList.of("foo", "bar", "baz"); Map<String, Object> data = ImmutableMap.of("string", "foo", "list", list); assertEquals("oo", engine .compileMustache("invoke_01", "{{invoke 1 m='substring'}}") .render("foo")); assertEquals("bar", engine.compileMustache("invoke_02", "{{invoke 1 m='get'}}") .render(list)); assertEquals("FOOBARBAZ", engine.compileMustache("invoke_03", "{{#invoke 'list' m='get'}}{{#each this}}{{toUpperCase}}{{/each}}{{/invoke}}") .render(data)); assertEquals("3", engine .compileMustache("invoke_04", "{{invoke on=list m='size'}}") .render(data)); assertEquals( "false", engine .compileMustache("invoke_05", "{{invoke on=list method='isEmpty'}}") .render(data)); assertEquals("boo", engine.compileMustache("invoke_06", "{{invoke 'f' 'b' on='foo' m='replace'}}") .render(null)); assertEquals("2", engine.compileMustache("invoke_07", "{{#invoke ':' on='foo:bar' m='split'}}{{this.length}}{{/invoke}}") .render(null)); } | public static InvokeHelper of(String defaultMethodName) { return new InvokeHelper(null, defaultMethodName); } | InvokeHelper extends BasicHelper { public static InvokeHelper of(String defaultMethodName) { return new InvokeHelper(null, defaultMethodName); } } | InvokeHelper extends BasicHelper { public static InvokeHelper of(String defaultMethodName) { return new InvokeHelper(null, defaultMethodName); } InvokeHelper(); InvokeHelper(ClassLoader classLoader); InvokeHelper(ClassLoader classLoader, String defaultMethodName); } | InvokeHelper extends BasicHelper { public static InvokeHelper of(String defaultMethodName) { return new InvokeHelper(null, defaultMethodName); } InvokeHelper(); InvokeHelper(ClassLoader classLoader); InvokeHelper(ClassLoader classLoader, String defaultMethodName); static InvokeHelper of(String defaultMethodName); @Override void execute(Options options); @Override void init(); @Override Set<ConfigurationKey> getConfigurationKeys(); @Override void validate(HelperDefinition definition); } | InvokeHelper extends BasicHelper { public static InvokeHelper of(String defaultMethodName) { return new InvokeHelper(null, defaultMethodName); } InvokeHelper(); InvokeHelper(ClassLoader classLoader); InvokeHelper(ClassLoader classLoader, String defaultMethodName); static InvokeHelper of(String defaultMethodName); @Override void execute(Options options); @Override void init(); @Override Set<ConfigurationKey> getConfigurationKeys(); @Override void validate(HelperDefinition definition); static final ConfigurationKey METHOD_CACHE_MAX_SIZE_KEY; } |
@Test public void testDefaultMethodName() { MustacheEngine engine = MustacheEngineBuilder.newBuilder() .registerHelpers(HelpersBuilder.empty() .add("substring", InvokeHelper.of("substring")) .build()) .build(); assertEquals("345", engine .compileMustache("invoke_defmethodname_01", "{{substring 3}}") .render("012345")); assertEquals("lo", engine .compileMustache("invoke_defmethodname_01", "{{substring 3 on='hello' m='whatever'}}") .render(null)); } | public static InvokeHelper of(String defaultMethodName) { return new InvokeHelper(null, defaultMethodName); } | InvokeHelper extends BasicHelper { public static InvokeHelper of(String defaultMethodName) { return new InvokeHelper(null, defaultMethodName); } } | InvokeHelper extends BasicHelper { public static InvokeHelper of(String defaultMethodName) { return new InvokeHelper(null, defaultMethodName); } InvokeHelper(); InvokeHelper(ClassLoader classLoader); InvokeHelper(ClassLoader classLoader, String defaultMethodName); } | InvokeHelper extends BasicHelper { public static InvokeHelper of(String defaultMethodName) { return new InvokeHelper(null, defaultMethodName); } InvokeHelper(); InvokeHelper(ClassLoader classLoader); InvokeHelper(ClassLoader classLoader, String defaultMethodName); static InvokeHelper of(String defaultMethodName); @Override void execute(Options options); @Override void init(); @Override Set<ConfigurationKey> getConfigurationKeys(); @Override void validate(HelperDefinition definition); } | InvokeHelper extends BasicHelper { public static InvokeHelper of(String defaultMethodName) { return new InvokeHelper(null, defaultMethodName); } InvokeHelper(); InvokeHelper(ClassLoader classLoader); InvokeHelper(ClassLoader classLoader, String defaultMethodName); static InvokeHelper of(String defaultMethodName); @Override void execute(Options options); @Override void init(); @Override Set<ConfigurationKey> getConfigurationKeys(); @Override void validate(HelperDefinition definition); static final ConfigurationKey METHOD_CACHE_MAX_SIZE_KEY; } |
@Test public void testNullCheckHelper() { MustacheEngine engine = MustacheEngineBuilder .newBuilder() .registerHelpers( HelpersBuilder.empty() .addIsNull() .addIsNotNull() .build()).build(); assertEquals( "NULL|NOTNULL", engine.compileMustache( "nullcheck_helper1", "{{#isNull this.getNull}}NULL{{/isNull}}|{{#isNotNull this.toString}}NOTNULL{{/isNotNull}}") .render(new Hammer())); assertEquals( "NULL", engine.compileMustache( "nullcheck_helper2", "{{#isNull this.getNull this.null}}NULL{{/isNull}}") .render(new Hammer())); assertEquals( "NULL", engine.compileMustache( "nullcheck_helper3", "{{#isNull this.getNull this.age logic=\"or\"}}NULL{{/isNull}}") .render(new Hammer())); assertEquals( "NOTNULL", engine.compileMustache( "nullcheck_helper3", "{{#isNotNull this.getNull this.age logic=\"or\"}}NOTNULL{{/isNotNull}}") .render(new Hammer())); assertEquals( "ISNULL", engine.compileMustache( "nullcheck_helper4", "{{#isNotNull this.getNull else='ISNULL'}}NOTNULL{{/isNotNull}}") .render(new Hammer())); } | public NullCheckHelper() { this(false); } | NullCheckHelper extends MatchingSectionHelper { public NullCheckHelper() { this(false); } } | NullCheckHelper extends MatchingSectionHelper { public NullCheckHelper() { this(false); } NullCheckHelper(); NullCheckHelper(boolean testNotNull); } | NullCheckHelper extends MatchingSectionHelper { public NullCheckHelper() { this(false); } NullCheckHelper(); NullCheckHelper(boolean testNotNull); } | NullCheckHelper extends MatchingSectionHelper { public NullCheckHelper() { this(false); } NullCheckHelper(); NullCheckHelper(boolean testNotNull); } |
@Test public void testHelper() throws InterruptedException { final MustacheEngine engine = MustacheEngineBuilder.newBuilder() .registerHelpers(HelpersBuilder.empty().addCache().build()) .build(); CacheHelper cacheHelper = (CacheHelper) engine.getConfiguration() .getHelpers().get(HelpersBuilder.CACHE); final AtomicInteger hits = new AtomicInteger(); Mustache mustache = engine.compileMustache("cache_01", "{{#cache}}{{this.age}}{{/cache}}"); Hammer hammer = new Hammer() { @Override public Integer getAge() { hits.incrementAndGet(); return super.getAge(); } }; assertEquals("10", mustache.render(hammer)); assertEquals("10", mustache.render(hammer)); hammer.setAge(11); assertEquals("10", mustache.render(hammer)); assertEquals(1, hits.get()); cacheHelper.invalidateFragments(); hammer.setAge(1); mustache = engine.compileMustache("cache_02", "{{#cache expire=1 unit='MILLISECONDS'}}{{this.age}}{{/cache}}"); assertEquals("1", mustache.render(hammer)); Thread.sleep(50); hammer.setAge(2); assertEquals("2", mustache.render(hammer)); cacheHelper.invalidateFragments(); hammer.setAge(5); mustache = engine.compileMustache("cache_03", "{{#cache guard=this.age}}{{this.age}}{{/cache}}"); assertEquals("5", mustache.render(hammer)); assertEquals("5", mustache.render(hammer)); hammer.setAge(50); assertEquals("50", mustache.render(hammer)); cacheHelper.invalidateFragments(); mustache = engine.compileMustache("cache_04", "{{#cache key=this.id}}{{this.age}}{{/cache}}"); hammer.setAge(1000); Hammer hammer2 = new Hammer(2000) { @Override public Integer getAge() { hits.incrementAndGet(); return super.getAge(); } }; Hammer hammer3 = new Hammer(3000) { @Override public Integer getAge() { hits.incrementAndGet(); return super.getAge(); } }; assertEquals("1000", mustache.render(hammer)); assertEquals("2000", mustache.render(hammer2)); assertEquals("3000", mustache.render(hammer3)); hammer.setAge(1001); hammer2.setAge(2001); hammer3.setAge(3001); assertEquals("1000", mustache.render(hammer)); assertEquals("2000", mustache.render(hammer2)); assertEquals("3000", mustache.render(hammer3)); cacheHelper.invalidateFragments(hammer.getId()); assertEquals("1001", mustache.render(hammer)); assertEquals("2000", mustache.render(hammer2)); assertEquals("3000", mustache.render(hammer3)); } | public void invalidateFragments() { if (fragments == null) { return; } fragments.clear(); } | CacheHelper extends BasicSectionHelper { public void invalidateFragments() { if (fragments == null) { return; } fragments.clear(); } } | CacheHelper extends BasicSectionHelper { public void invalidateFragments() { if (fragments == null) { return; } fragments.clear(); } } | CacheHelper extends BasicSectionHelper { public void invalidateFragments() { if (fragments == null) { return; } fragments.clear(); } @Override void execute(Options options); void init(); @Override Set<ConfigurationKey> getConfigurationKeys(); @Override void validate(HelperDefinition definition); void invalidateFragments(); void invalidateFragments(final String keyPart); } | CacheHelper extends BasicSectionHelper { public void invalidateFragments() { if (fragments == null) { return; } fragments.clear(); } @Override void execute(Options options); void init(); @Override Set<ConfigurationKey> getConfigurationKeys(); @Override void validate(HelperDefinition definition); void invalidateFragments(); void invalidateFragments(final String keyPart); static final ConfigurationKey FRAGMENT_CACHE_MAX_SIZE_KEY; } |
@Test public void testBuiltin() { Map<String, Helper> helpers = HelpersBuilder.builtin().build(); assertEquals(5, helpers.size()); assertTrue(helpers.containsKey(HelpersBuilder.EACH)); assertTrue(helpers.containsKey(HelpersBuilder.IF)); assertTrue(helpers.containsKey(HelpersBuilder.IS)); assertTrue(helpers.containsKey(HelpersBuilder.UNLESS)); assertTrue(helpers.containsKey(HelpersBuilder.WITH)); } | public static HelpersBuilder builtin() { return empty().addBuiltin(); } | HelpersBuilder { public static HelpersBuilder builtin() { return empty().addBuiltin(); } } | HelpersBuilder { public static HelpersBuilder builtin() { return empty().addBuiltin(); } private HelpersBuilder(); } | HelpersBuilder { public static HelpersBuilder builtin() { return empty().addBuiltin(); } private HelpersBuilder(); HelpersBuilder add(String name, Helper helper); HelpersBuilder addEach(); HelpersBuilder addIf(); HelpersBuilder addIf(String elseStartDelimiter, String elseEndDelimiter); HelpersBuilder addUnless(); HelpersBuilder addWith(); HelpersBuilder addIs(); HelpersBuilder addIsEven(); HelpersBuilder addIsOdd(); HelpersBuilder addSet(); HelpersBuilder addInclude(); HelpersBuilder addEmbed(); HelpersBuilder addEmbed(SourceProcessor processor); HelpersBuilder addIsEqual(); HelpersBuilder addIsNotEqual(); HelpersBuilder addIsNull(); HelpersBuilder addIsNotNull(); HelpersBuilder addChoose(); HelpersBuilder addSwitch(); HelpersBuilder addSwitch(boolean caseDefaultIsBreak); HelpersBuilder addJoin(); HelpersBuilder addEval(); HelpersBuilder addEval(Notation notation); HelpersBuilder addNumExpr(); HelpersBuilder addNumExpr(Operator defaultOperator); HelpersBuilder addAsync(); HelpersBuilder addInvoke(); HelpersBuilder addAlt(); HelpersBuilder addAlt(Selector selector); HelpersBuilder addMin(); HelpersBuilder addMax(); HelpersBuilder addCache(); HelpersBuilder addRepeat(); HelpersBuilder addFmt(); HelpersBuilder addTag(); HelpersBuilder addBuiltin(); HelpersBuilder addExtra(); Map<String, Helper> build(); static HelpersBuilder empty(); static HelpersBuilder builtin(); static HelpersBuilder extra(); static HelpersBuilder all(); } | HelpersBuilder { public static HelpersBuilder builtin() { return empty().addBuiltin(); } private HelpersBuilder(); HelpersBuilder add(String name, Helper helper); HelpersBuilder addEach(); HelpersBuilder addIf(); HelpersBuilder addIf(String elseStartDelimiter, String elseEndDelimiter); HelpersBuilder addUnless(); HelpersBuilder addWith(); HelpersBuilder addIs(); HelpersBuilder addIsEven(); HelpersBuilder addIsOdd(); HelpersBuilder addSet(); HelpersBuilder addInclude(); HelpersBuilder addEmbed(); HelpersBuilder addEmbed(SourceProcessor processor); HelpersBuilder addIsEqual(); HelpersBuilder addIsNotEqual(); HelpersBuilder addIsNull(); HelpersBuilder addIsNotNull(); HelpersBuilder addChoose(); HelpersBuilder addSwitch(); HelpersBuilder addSwitch(boolean caseDefaultIsBreak); HelpersBuilder addJoin(); HelpersBuilder addEval(); HelpersBuilder addEval(Notation notation); HelpersBuilder addNumExpr(); HelpersBuilder addNumExpr(Operator defaultOperator); HelpersBuilder addAsync(); HelpersBuilder addInvoke(); HelpersBuilder addAlt(); HelpersBuilder addAlt(Selector selector); HelpersBuilder addMin(); HelpersBuilder addMax(); HelpersBuilder addCache(); HelpersBuilder addRepeat(); HelpersBuilder addFmt(); HelpersBuilder addTag(); HelpersBuilder addBuiltin(); HelpersBuilder addExtra(); Map<String, Helper> build(); static HelpersBuilder empty(); static HelpersBuilder builtin(); static HelpersBuilder extra(); static HelpersBuilder all(); static final String EACH; static final String IF; static final String UNLESS; static final String WITH; static final String IS; static final String IS_EVEN; static final String IS_ODD; static final String SET; static final String INCLUDE; static final String EMBED; static final String IS_EQUAL; static final String IS_NOT_EQUAL; static final String IS_NULL; static final String IS_NOT_NULL; static final String CHOOSE; static final String WHEN; static final String OTHERWISE; static final String SWITCH; static final String CASE; static final String DEFAULT; static final String JOIN; static final String EVAL; static final String NUMERIC_EXPRESSION; static final String ASYNC; static final String INVOKE; static final String ALT; static final String MIN; static final String MAX; static final String CACHE; static final String REPEAT; static final String FMT; static final String TAG; } |
@Test public void testExtra() { Map<String, Helper> helpers = HelpersBuilder.extra().build(); assertEquals(27, helpers.size()); assertTrue(helpers.containsKey(HelpersBuilder.EMBED)); assertTrue(helpers.containsKey(HelpersBuilder.INCLUDE)); assertTrue(helpers.containsKey(HelpersBuilder.IS_EQUAL)); assertTrue(helpers.containsKey(HelpersBuilder.IS_NOT_EQUAL)); assertTrue(helpers.containsKey(HelpersBuilder.IS_NULL)); assertTrue(helpers.containsKey(HelpersBuilder.IS_NOT_NULL)); assertTrue(helpers.containsKey(HelpersBuilder.SET)); assertTrue(helpers.containsKey(HelpersBuilder.IS_EVEN)); assertTrue(helpers.containsKey(HelpersBuilder.IS_ODD)); assertTrue(helpers.containsKey(HelpersBuilder.SWITCH)); assertTrue(helpers.containsKey(HelpersBuilder.CHOOSE)); assertTrue(helpers.containsKey(HelpersBuilder.JOIN)); assertTrue(helpers.containsKey(HelpersBuilder.EVAL)); assertTrue(helpers.containsKey(HelpersBuilder.NUMERIC_EXPRESSION)); assertTrue(helpers.containsKey(HelpersBuilder.ASYNC)); assertTrue(helpers.containsKey(HelpersBuilder.INVOKE)); assertTrue(helpers.containsKey(HelpersBuilder.ALT)); assertTrue(helpers.containsKey(HelpersBuilder.MIN)); assertTrue(helpers.containsKey(HelpersBuilder.MAX)); assertTrue(helpers.containsKey(HelpersBuilder.CACHE)); assertTrue(helpers.containsKey(HelpersBuilder.REPEAT)); assertTrue(helpers.containsKey(HelpersBuilder.FMT)); assertTrue(helpers.containsKey(HelpersBuilder.TAG)); } | public static HelpersBuilder extra() { return empty().addExtra(); } | HelpersBuilder { public static HelpersBuilder extra() { return empty().addExtra(); } } | HelpersBuilder { public static HelpersBuilder extra() { return empty().addExtra(); } private HelpersBuilder(); } | HelpersBuilder { public static HelpersBuilder extra() { return empty().addExtra(); } private HelpersBuilder(); HelpersBuilder add(String name, Helper helper); HelpersBuilder addEach(); HelpersBuilder addIf(); HelpersBuilder addIf(String elseStartDelimiter, String elseEndDelimiter); HelpersBuilder addUnless(); HelpersBuilder addWith(); HelpersBuilder addIs(); HelpersBuilder addIsEven(); HelpersBuilder addIsOdd(); HelpersBuilder addSet(); HelpersBuilder addInclude(); HelpersBuilder addEmbed(); HelpersBuilder addEmbed(SourceProcessor processor); HelpersBuilder addIsEqual(); HelpersBuilder addIsNotEqual(); HelpersBuilder addIsNull(); HelpersBuilder addIsNotNull(); HelpersBuilder addChoose(); HelpersBuilder addSwitch(); HelpersBuilder addSwitch(boolean caseDefaultIsBreak); HelpersBuilder addJoin(); HelpersBuilder addEval(); HelpersBuilder addEval(Notation notation); HelpersBuilder addNumExpr(); HelpersBuilder addNumExpr(Operator defaultOperator); HelpersBuilder addAsync(); HelpersBuilder addInvoke(); HelpersBuilder addAlt(); HelpersBuilder addAlt(Selector selector); HelpersBuilder addMin(); HelpersBuilder addMax(); HelpersBuilder addCache(); HelpersBuilder addRepeat(); HelpersBuilder addFmt(); HelpersBuilder addTag(); HelpersBuilder addBuiltin(); HelpersBuilder addExtra(); Map<String, Helper> build(); static HelpersBuilder empty(); static HelpersBuilder builtin(); static HelpersBuilder extra(); static HelpersBuilder all(); } | HelpersBuilder { public static HelpersBuilder extra() { return empty().addExtra(); } private HelpersBuilder(); HelpersBuilder add(String name, Helper helper); HelpersBuilder addEach(); HelpersBuilder addIf(); HelpersBuilder addIf(String elseStartDelimiter, String elseEndDelimiter); HelpersBuilder addUnless(); HelpersBuilder addWith(); HelpersBuilder addIs(); HelpersBuilder addIsEven(); HelpersBuilder addIsOdd(); HelpersBuilder addSet(); HelpersBuilder addInclude(); HelpersBuilder addEmbed(); HelpersBuilder addEmbed(SourceProcessor processor); HelpersBuilder addIsEqual(); HelpersBuilder addIsNotEqual(); HelpersBuilder addIsNull(); HelpersBuilder addIsNotNull(); HelpersBuilder addChoose(); HelpersBuilder addSwitch(); HelpersBuilder addSwitch(boolean caseDefaultIsBreak); HelpersBuilder addJoin(); HelpersBuilder addEval(); HelpersBuilder addEval(Notation notation); HelpersBuilder addNumExpr(); HelpersBuilder addNumExpr(Operator defaultOperator); HelpersBuilder addAsync(); HelpersBuilder addInvoke(); HelpersBuilder addAlt(); HelpersBuilder addAlt(Selector selector); HelpersBuilder addMin(); HelpersBuilder addMax(); HelpersBuilder addCache(); HelpersBuilder addRepeat(); HelpersBuilder addFmt(); HelpersBuilder addTag(); HelpersBuilder addBuiltin(); HelpersBuilder addExtra(); Map<String, Helper> build(); static HelpersBuilder empty(); static HelpersBuilder builtin(); static HelpersBuilder extra(); static HelpersBuilder all(); static final String EACH; static final String IF; static final String UNLESS; static final String WITH; static final String IS; static final String IS_EVEN; static final String IS_ODD; static final String SET; static final String INCLUDE; static final String EMBED; static final String IS_EQUAL; static final String IS_NOT_EQUAL; static final String IS_NULL; static final String IS_NOT_NULL; static final String CHOOSE; static final String WHEN; static final String OTHERWISE; static final String SWITCH; static final String CASE; static final String DEFAULT; static final String JOIN; static final String EVAL; static final String NUMERIC_EXPRESSION; static final String ASYNC; static final String INVOKE; static final String ALT; static final String MIN; static final String MAX; static final String CACHE; static final String REPEAT; static final String FMT; static final String TAG; } |
@Test public void testContainsWhitespace() { assertTrue(Strings.containsWhitespace("foo bar")); assertTrue(Strings .containsWhitespace(System.getProperty("line.separator"))); assertFalse(Strings.containsWhitespace("foobar")); } | public static boolean containsWhitespace(String text) { if (isEmpty(text)) { return false; } for (int i = 0; i < text.length(); i++) { if (Character.isWhitespace(text.charAt(i))) { return true; } } return false; } | Strings { public static boolean containsWhitespace(String text) { if (isEmpty(text)) { return false; } for (int i = 0; i < text.length(); i++) { if (Character.isWhitespace(text.charAt(i))) { return true; } } return false; } } | Strings { public static boolean containsWhitespace(String text) { if (isEmpty(text)) { return false; } for (int i = 0; i < text.length(); i++) { if (Character.isWhitespace(text.charAt(i))) { return true; } } return false; } private Strings(); } | Strings { public static boolean containsWhitespace(String text) { if (isEmpty(text)) { return false; } for (int i = 0; i < text.length(); i++) { if (Character.isWhitespace(text.charAt(i))) { return true; } } return false; } private Strings(); static boolean isStringLiteralSeparator(char character); static boolean isEmpty(CharSequence sequence); static String uncapitalize(String word); static String capitalizeFully(String text, Character delimiter); static String replace(String text, String search,
String replacement); static String removeSuffix(String text, String suffix); static List<String> split(String text, String delimiter); static boolean containsWhitespace(String text); static boolean containsOnlyWhitespace(String text); static boolean containsOnlyDigits(String text); static String repeat(String text, int times, String separator); static String substringAfter(String text, String delimiter); static boolean isListLiteralStart(char character); static boolean isListLiteralEnd(char character); static boolean isListLiteral(String value); } | Strings { public static boolean containsWhitespace(String text) { if (isEmpty(text)) { return false; } for (int i = 0; i < text.length(); i++) { if (Character.isWhitespace(text.charAt(i))) { return true; } } return false; } private Strings(); static boolean isStringLiteralSeparator(char character); static boolean isEmpty(CharSequence sequence); static String uncapitalize(String word); static String capitalizeFully(String text, Character delimiter); static String replace(String text, String search,
String replacement); static String removeSuffix(String text, String suffix); static List<String> split(String text, String delimiter); static boolean containsWhitespace(String text); static boolean containsOnlyWhitespace(String text); static boolean containsOnlyDigits(String text); static String repeat(String text, int times, String separator); static String substringAfter(String text, String delimiter); static boolean isListLiteralStart(char character); static boolean isListLiteralEnd(char character); static boolean isListLiteral(String value); static final String EMPTY; static final String GAP; static final String LINE_SEPARATOR; static final String LINE_SEPARATOR_LF; static final String LINE_SEPARATOR_CRLF; static final String LINE_SEPARATOR_CR; static final String SLASH; static final String FILE_SEPARATOR; static final String DOT; static final String UNDERSCORE; static final String NOT_AVAILABLE; static final String URL_PROCOTOL_FILE; static final String THIS; static final String HASH; } |
@Test public void testCustomConverter() { final Calendar day = Calendar.getInstance(); day.set(Calendar.YEAR, day.get(Calendar.YEAR) - 1); day.set(Calendar.MONTH, day.get(Calendar.MONTH) - 1); MustacheEngine engine = MustacheEngineBuilder.newBuilder() .omitServiceLoaderConfigurationExtensions() .setLocaleSupport(FixedLocaleSupport.from(Locale.ENGLISH)) .addResolver(new ThisResolver()) .registerHelper("pretty", PrettyTimeHelper.builder() .setConverter(from -> day.getTime()).build()) .build(); assertEquals("1 year ago", engine.compileMustache("pretty_conv", "{{pretty this}}") .render(Calendar.getInstance())); } | public static Builder builder() { return new Builder(); } | PrettyTimeHelper extends LocaleAwareValueHelper { public static Builder builder() { return new Builder(); } } | PrettyTimeHelper extends LocaleAwareValueHelper { public static Builder builder() { return new Builder(); } PrettyTimeHelper(); PrettyTimeHelper(PrettyTimeFactory prettyTimeFactory); PrettyTimeHelper(PrettyTimeFactory factory,
Converter<Object, Date> converter); } | PrettyTimeHelper extends LocaleAwareValueHelper { public static Builder builder() { return new Builder(); } PrettyTimeHelper(); PrettyTimeHelper(PrettyTimeFactory prettyTimeFactory); PrettyTimeHelper(PrettyTimeFactory factory,
Converter<Object, Date> converter); @Override void init(Configuration configuration); @Override void execute(Options options); static Builder builder(); } | PrettyTimeHelper extends LocaleAwareValueHelper { public static Builder builder() { return new Builder(); } PrettyTimeHelper(); PrettyTimeHelper(PrettyTimeFactory prettyTimeFactory); PrettyTimeHelper(PrettyTimeFactory factory,
Converter<Object, Date> converter); @Override void init(Configuration configuration); @Override void execute(Options options); static Builder builder(); static final String COMPUTING_CACHE_CONSUMER_ID; static final String DEFAULT_NAME; } |
@Test public void availabilityOfTemplateInDefaultLocation() throws Exception { assertThat(provider.isTemplateAvailable("home", environment, getClass().getClassLoader(), resourceLoader), is(true)); assertThat(provider.isTemplateAvailable("prefix/prefixed", environment, getClass().getClassLoader(), resourceLoader), is(true)); } | public boolean isTemplateAvailable(final String view, final Environment environment, final ClassLoader classLoader, final ResourceLoader resourceLoader) { if (ClassUtils.isPresent("org.trimou.Mustache", classLoader)) { final PropertyResolver resolver = new RelaxedPropertyResolver(environment, TrimouProperties.PROPERTY_PREFIX + '.'); final String prefix = resolver.getProperty("prefix", SpringResourceTemplateLocator.DEFAULT_PREFIX); final String suffix = resolver.getProperty("suffix", SpringResourceTemplateLocator.DEFAULT_SUFFIX); final String resourceLocation = prefix + view + suffix; return resourceLoader.getResource(resourceLocation).exists(); } return false; } | TrimouTemplateAvailabilityProvider implements TemplateAvailabilityProvider { public boolean isTemplateAvailable(final String view, final Environment environment, final ClassLoader classLoader, final ResourceLoader resourceLoader) { if (ClassUtils.isPresent("org.trimou.Mustache", classLoader)) { final PropertyResolver resolver = new RelaxedPropertyResolver(environment, TrimouProperties.PROPERTY_PREFIX + '.'); final String prefix = resolver.getProperty("prefix", SpringResourceTemplateLocator.DEFAULT_PREFIX); final String suffix = resolver.getProperty("suffix", SpringResourceTemplateLocator.DEFAULT_SUFFIX); final String resourceLocation = prefix + view + suffix; return resourceLoader.getResource(resourceLocation).exists(); } return false; } } | TrimouTemplateAvailabilityProvider implements TemplateAvailabilityProvider { public boolean isTemplateAvailable(final String view, final Environment environment, final ClassLoader classLoader, final ResourceLoader resourceLoader) { if (ClassUtils.isPresent("org.trimou.Mustache", classLoader)) { final PropertyResolver resolver = new RelaxedPropertyResolver(environment, TrimouProperties.PROPERTY_PREFIX + '.'); final String prefix = resolver.getProperty("prefix", SpringResourceTemplateLocator.DEFAULT_PREFIX); final String suffix = resolver.getProperty("suffix", SpringResourceTemplateLocator.DEFAULT_SUFFIX); final String resourceLocation = prefix + view + suffix; return resourceLoader.getResource(resourceLocation).exists(); } return false; } } | TrimouTemplateAvailabilityProvider implements TemplateAvailabilityProvider { public boolean isTemplateAvailable(final String view, final Environment environment, final ClassLoader classLoader, final ResourceLoader resourceLoader) { if (ClassUtils.isPresent("org.trimou.Mustache", classLoader)) { final PropertyResolver resolver = new RelaxedPropertyResolver(environment, TrimouProperties.PROPERTY_PREFIX + '.'); final String prefix = resolver.getProperty("prefix", SpringResourceTemplateLocator.DEFAULT_PREFIX); final String suffix = resolver.getProperty("suffix", SpringResourceTemplateLocator.DEFAULT_SUFFIX); final String resourceLocation = prefix + view + suffix; return resourceLoader.getResource(resourceLocation).exists(); } return false; } boolean isTemplateAvailable(final String view, final Environment environment, final ClassLoader classLoader,
final ResourceLoader resourceLoader); } | TrimouTemplateAvailabilityProvider implements TemplateAvailabilityProvider { public boolean isTemplateAvailable(final String view, final Environment environment, final ClassLoader classLoader, final ResourceLoader resourceLoader) { if (ClassUtils.isPresent("org.trimou.Mustache", classLoader)) { final PropertyResolver resolver = new RelaxedPropertyResolver(environment, TrimouProperties.PROPERTY_PREFIX + '.'); final String prefix = resolver.getProperty("prefix", SpringResourceTemplateLocator.DEFAULT_PREFIX); final String suffix = resolver.getProperty("suffix", SpringResourceTemplateLocator.DEFAULT_SUFFIX); final String resourceLocation = prefix + view + suffix; return resourceLoader.getResource(resourceLocation).exists(); } return false; } boolean isTemplateAvailable(final String view, final Environment environment, final ClassLoader classLoader,
final ResourceLoader resourceLoader); } |
@Test public void availabilityOfTemplateThatDoesNotExist() throws Exception { assertThat(provider.isTemplateAvailable("unknown", environment, getClass().getClassLoader(), resourceLoader), is(false)); } | public boolean isTemplateAvailable(final String view, final Environment environment, final ClassLoader classLoader, final ResourceLoader resourceLoader) { if (ClassUtils.isPresent("org.trimou.Mustache", classLoader)) { final PropertyResolver resolver = new RelaxedPropertyResolver(environment, TrimouProperties.PROPERTY_PREFIX + '.'); final String prefix = resolver.getProperty("prefix", SpringResourceTemplateLocator.DEFAULT_PREFIX); final String suffix = resolver.getProperty("suffix", SpringResourceTemplateLocator.DEFAULT_SUFFIX); final String resourceLocation = prefix + view + suffix; return resourceLoader.getResource(resourceLocation).exists(); } return false; } | TrimouTemplateAvailabilityProvider implements TemplateAvailabilityProvider { public boolean isTemplateAvailable(final String view, final Environment environment, final ClassLoader classLoader, final ResourceLoader resourceLoader) { if (ClassUtils.isPresent("org.trimou.Mustache", classLoader)) { final PropertyResolver resolver = new RelaxedPropertyResolver(environment, TrimouProperties.PROPERTY_PREFIX + '.'); final String prefix = resolver.getProperty("prefix", SpringResourceTemplateLocator.DEFAULT_PREFIX); final String suffix = resolver.getProperty("suffix", SpringResourceTemplateLocator.DEFAULT_SUFFIX); final String resourceLocation = prefix + view + suffix; return resourceLoader.getResource(resourceLocation).exists(); } return false; } } | TrimouTemplateAvailabilityProvider implements TemplateAvailabilityProvider { public boolean isTemplateAvailable(final String view, final Environment environment, final ClassLoader classLoader, final ResourceLoader resourceLoader) { if (ClassUtils.isPresent("org.trimou.Mustache", classLoader)) { final PropertyResolver resolver = new RelaxedPropertyResolver(environment, TrimouProperties.PROPERTY_PREFIX + '.'); final String prefix = resolver.getProperty("prefix", SpringResourceTemplateLocator.DEFAULT_PREFIX); final String suffix = resolver.getProperty("suffix", SpringResourceTemplateLocator.DEFAULT_SUFFIX); final String resourceLocation = prefix + view + suffix; return resourceLoader.getResource(resourceLocation).exists(); } return false; } } | TrimouTemplateAvailabilityProvider implements TemplateAvailabilityProvider { public boolean isTemplateAvailable(final String view, final Environment environment, final ClassLoader classLoader, final ResourceLoader resourceLoader) { if (ClassUtils.isPresent("org.trimou.Mustache", classLoader)) { final PropertyResolver resolver = new RelaxedPropertyResolver(environment, TrimouProperties.PROPERTY_PREFIX + '.'); final String prefix = resolver.getProperty("prefix", SpringResourceTemplateLocator.DEFAULT_PREFIX); final String suffix = resolver.getProperty("suffix", SpringResourceTemplateLocator.DEFAULT_SUFFIX); final String resourceLocation = prefix + view + suffix; return resourceLoader.getResource(resourceLocation).exists(); } return false; } boolean isTemplateAvailable(final String view, final Environment environment, final ClassLoader classLoader,
final ResourceLoader resourceLoader); } | TrimouTemplateAvailabilityProvider implements TemplateAvailabilityProvider { public boolean isTemplateAvailable(final String view, final Environment environment, final ClassLoader classLoader, final ResourceLoader resourceLoader) { if (ClassUtils.isPresent("org.trimou.Mustache", classLoader)) { final PropertyResolver resolver = new RelaxedPropertyResolver(environment, TrimouProperties.PROPERTY_PREFIX + '.'); final String prefix = resolver.getProperty("prefix", SpringResourceTemplateLocator.DEFAULT_PREFIX); final String suffix = resolver.getProperty("suffix", SpringResourceTemplateLocator.DEFAULT_SUFFIX); final String resourceLocation = prefix + view + suffix; return resourceLoader.getResource(resourceLocation).exists(); } return false; } boolean isTemplateAvailable(final String view, final Environment environment, final ClassLoader classLoader,
final ResourceLoader resourceLoader); } |
@Test public void availabilityOfTemplateWithCustomPrefix() throws Exception { environment.setProperty("trimou.prefix", "classpath:/custom-templates/"); assertThat(provider.isTemplateAvailable("custom", environment, getClass().getClassLoader(), resourceLoader), is(true)); } | public boolean isTemplateAvailable(final String view, final Environment environment, final ClassLoader classLoader, final ResourceLoader resourceLoader) { if (ClassUtils.isPresent("org.trimou.Mustache", classLoader)) { final PropertyResolver resolver = new RelaxedPropertyResolver(environment, TrimouProperties.PROPERTY_PREFIX + '.'); final String prefix = resolver.getProperty("prefix", SpringResourceTemplateLocator.DEFAULT_PREFIX); final String suffix = resolver.getProperty("suffix", SpringResourceTemplateLocator.DEFAULT_SUFFIX); final String resourceLocation = prefix + view + suffix; return resourceLoader.getResource(resourceLocation).exists(); } return false; } | TrimouTemplateAvailabilityProvider implements TemplateAvailabilityProvider { public boolean isTemplateAvailable(final String view, final Environment environment, final ClassLoader classLoader, final ResourceLoader resourceLoader) { if (ClassUtils.isPresent("org.trimou.Mustache", classLoader)) { final PropertyResolver resolver = new RelaxedPropertyResolver(environment, TrimouProperties.PROPERTY_PREFIX + '.'); final String prefix = resolver.getProperty("prefix", SpringResourceTemplateLocator.DEFAULT_PREFIX); final String suffix = resolver.getProperty("suffix", SpringResourceTemplateLocator.DEFAULT_SUFFIX); final String resourceLocation = prefix + view + suffix; return resourceLoader.getResource(resourceLocation).exists(); } return false; } } | TrimouTemplateAvailabilityProvider implements TemplateAvailabilityProvider { public boolean isTemplateAvailable(final String view, final Environment environment, final ClassLoader classLoader, final ResourceLoader resourceLoader) { if (ClassUtils.isPresent("org.trimou.Mustache", classLoader)) { final PropertyResolver resolver = new RelaxedPropertyResolver(environment, TrimouProperties.PROPERTY_PREFIX + '.'); final String prefix = resolver.getProperty("prefix", SpringResourceTemplateLocator.DEFAULT_PREFIX); final String suffix = resolver.getProperty("suffix", SpringResourceTemplateLocator.DEFAULT_SUFFIX); final String resourceLocation = prefix + view + suffix; return resourceLoader.getResource(resourceLocation).exists(); } return false; } } | TrimouTemplateAvailabilityProvider implements TemplateAvailabilityProvider { public boolean isTemplateAvailable(final String view, final Environment environment, final ClassLoader classLoader, final ResourceLoader resourceLoader) { if (ClassUtils.isPresent("org.trimou.Mustache", classLoader)) { final PropertyResolver resolver = new RelaxedPropertyResolver(environment, TrimouProperties.PROPERTY_PREFIX + '.'); final String prefix = resolver.getProperty("prefix", SpringResourceTemplateLocator.DEFAULT_PREFIX); final String suffix = resolver.getProperty("suffix", SpringResourceTemplateLocator.DEFAULT_SUFFIX); final String resourceLocation = prefix + view + suffix; return resourceLoader.getResource(resourceLocation).exists(); } return false; } boolean isTemplateAvailable(final String view, final Environment environment, final ClassLoader classLoader,
final ResourceLoader resourceLoader); } | TrimouTemplateAvailabilityProvider implements TemplateAvailabilityProvider { public boolean isTemplateAvailable(final String view, final Environment environment, final ClassLoader classLoader, final ResourceLoader resourceLoader) { if (ClassUtils.isPresent("org.trimou.Mustache", classLoader)) { final PropertyResolver resolver = new RelaxedPropertyResolver(environment, TrimouProperties.PROPERTY_PREFIX + '.'); final String prefix = resolver.getProperty("prefix", SpringResourceTemplateLocator.DEFAULT_PREFIX); final String suffix = resolver.getProperty("suffix", SpringResourceTemplateLocator.DEFAULT_SUFFIX); final String resourceLocation = prefix + view + suffix; return resourceLoader.getResource(resourceLocation).exists(); } return false; } boolean isTemplateAvailable(final String view, final Environment environment, final ClassLoader classLoader,
final ResourceLoader resourceLoader); } |
@Test public void availabilityOfTemplateWithCustomSuffix() throws Exception { environment.setProperty("trimou.suffix", ".html"); assertThat(provider.isTemplateAvailable("suffixed", environment, getClass().getClassLoader(), resourceLoader), is(true)); } | public boolean isTemplateAvailable(final String view, final Environment environment, final ClassLoader classLoader, final ResourceLoader resourceLoader) { if (ClassUtils.isPresent("org.trimou.Mustache", classLoader)) { final PropertyResolver resolver = new RelaxedPropertyResolver(environment, TrimouProperties.PROPERTY_PREFIX + '.'); final String prefix = resolver.getProperty("prefix", SpringResourceTemplateLocator.DEFAULT_PREFIX); final String suffix = resolver.getProperty("suffix", SpringResourceTemplateLocator.DEFAULT_SUFFIX); final String resourceLocation = prefix + view + suffix; return resourceLoader.getResource(resourceLocation).exists(); } return false; } | TrimouTemplateAvailabilityProvider implements TemplateAvailabilityProvider { public boolean isTemplateAvailable(final String view, final Environment environment, final ClassLoader classLoader, final ResourceLoader resourceLoader) { if (ClassUtils.isPresent("org.trimou.Mustache", classLoader)) { final PropertyResolver resolver = new RelaxedPropertyResolver(environment, TrimouProperties.PROPERTY_PREFIX + '.'); final String prefix = resolver.getProperty("prefix", SpringResourceTemplateLocator.DEFAULT_PREFIX); final String suffix = resolver.getProperty("suffix", SpringResourceTemplateLocator.DEFAULT_SUFFIX); final String resourceLocation = prefix + view + suffix; return resourceLoader.getResource(resourceLocation).exists(); } return false; } } | TrimouTemplateAvailabilityProvider implements TemplateAvailabilityProvider { public boolean isTemplateAvailable(final String view, final Environment environment, final ClassLoader classLoader, final ResourceLoader resourceLoader) { if (ClassUtils.isPresent("org.trimou.Mustache", classLoader)) { final PropertyResolver resolver = new RelaxedPropertyResolver(environment, TrimouProperties.PROPERTY_PREFIX + '.'); final String prefix = resolver.getProperty("prefix", SpringResourceTemplateLocator.DEFAULT_PREFIX); final String suffix = resolver.getProperty("suffix", SpringResourceTemplateLocator.DEFAULT_SUFFIX); final String resourceLocation = prefix + view + suffix; return resourceLoader.getResource(resourceLocation).exists(); } return false; } } | TrimouTemplateAvailabilityProvider implements TemplateAvailabilityProvider { public boolean isTemplateAvailable(final String view, final Environment environment, final ClassLoader classLoader, final ResourceLoader resourceLoader) { if (ClassUtils.isPresent("org.trimou.Mustache", classLoader)) { final PropertyResolver resolver = new RelaxedPropertyResolver(environment, TrimouProperties.PROPERTY_PREFIX + '.'); final String prefix = resolver.getProperty("prefix", SpringResourceTemplateLocator.DEFAULT_PREFIX); final String suffix = resolver.getProperty("suffix", SpringResourceTemplateLocator.DEFAULT_SUFFIX); final String resourceLocation = prefix + view + suffix; return resourceLoader.getResource(resourceLocation).exists(); } return false; } boolean isTemplateAvailable(final String view, final Environment environment, final ClassLoader classLoader,
final ResourceLoader resourceLoader); } | TrimouTemplateAvailabilityProvider implements TemplateAvailabilityProvider { public boolean isTemplateAvailable(final String view, final Environment environment, final ClassLoader classLoader, final ResourceLoader resourceLoader) { if (ClassUtils.isPresent("org.trimou.Mustache", classLoader)) { final PropertyResolver resolver = new RelaxedPropertyResolver(environment, TrimouProperties.PROPERTY_PREFIX + '.'); final String prefix = resolver.getProperty("prefix", SpringResourceTemplateLocator.DEFAULT_PREFIX); final String suffix = resolver.getProperty("suffix", SpringResourceTemplateLocator.DEFAULT_SUFFIX); final String resourceLocation = prefix + view + suffix; return resourceLoader.getResource(resourceLocation).exists(); } return false; } boolean isTemplateAvailable(final String view, final Environment environment, final ClassLoader classLoader,
final ResourceLoader resourceLoader); } |
@Test public void testNulltIsResolved() { HttpServletRequestResolver resolver = new HttpServletRequestResolver(); assertNull(resolver.resolve("whatever", "request", null)); assertNull(resolver.resolve(null, "foo", null)); } | @Override public Object resolve(Object contextObject, String name, ResolutionContext context) { if (contextObject != null) { return null; } if (NAME_REQUEST.equals(name)) { HttpServletRequestWrapper wrapper = REQUEST_WRAPPER.get(); if (wrapper == null) { HttpServletRequest request = RequestHolder.getCurrentRequest(); if (request != null) { wrapper = new HttpServletRequestWrapper(request); REQUEST_WRAPPER.set(wrapper); } else { LOGGER.warn("Unable to get the current HTTP request"); } } return wrapper; } return null; } | HttpServletRequestResolver extends AbstractResolver implements MustacheListener, Validateable { @Override public Object resolve(Object contextObject, String name, ResolutionContext context) { if (contextObject != null) { return null; } if (NAME_REQUEST.equals(name)) { HttpServletRequestWrapper wrapper = REQUEST_WRAPPER.get(); if (wrapper == null) { HttpServletRequest request = RequestHolder.getCurrentRequest(); if (request != null) { wrapper = new HttpServletRequestWrapper(request); REQUEST_WRAPPER.set(wrapper); } else { LOGGER.warn("Unable to get the current HTTP request"); } } return wrapper; } return null; } } | HttpServletRequestResolver extends AbstractResolver implements MustacheListener, Validateable { @Override public Object resolve(Object contextObject, String name, ResolutionContext context) { if (contextObject != null) { return null; } if (NAME_REQUEST.equals(name)) { HttpServletRequestWrapper wrapper = REQUEST_WRAPPER.get(); if (wrapper == null) { HttpServletRequest request = RequestHolder.getCurrentRequest(); if (request != null) { wrapper = new HttpServletRequestWrapper(request); REQUEST_WRAPPER.set(wrapper); } else { LOGGER.warn("Unable to get the current HTTP request"); } } return wrapper; } return null; } HttpServletRequestResolver(); HttpServletRequestResolver(int priority); } | HttpServletRequestResolver extends AbstractResolver implements MustacheListener, Validateable { @Override public Object resolve(Object contextObject, String name, ResolutionContext context) { if (contextObject != null) { return null; } if (NAME_REQUEST.equals(name)) { HttpServletRequestWrapper wrapper = REQUEST_WRAPPER.get(); if (wrapper == null) { HttpServletRequest request = RequestHolder.getCurrentRequest(); if (request != null) { wrapper = new HttpServletRequestWrapper(request); REQUEST_WRAPPER.set(wrapper); } else { LOGGER.warn("Unable to get the current HTTP request"); } } return wrapper; } return null; } HttpServletRequestResolver(); HttpServletRequestResolver(int priority); @Override Object resolve(Object contextObject, String name,
ResolutionContext context); @Override void init(); @Override Set<ConfigurationKey> getConfigurationKeys(); @Override void renderingStarted(MustacheRenderingEvent event); @Override boolean isValid(); } | HttpServletRequestResolver extends AbstractResolver implements MustacheListener, Validateable { @Override public Object resolve(Object contextObject, String name, ResolutionContext context) { if (contextObject != null) { return null; } if (NAME_REQUEST.equals(name)) { HttpServletRequestWrapper wrapper = REQUEST_WRAPPER.get(); if (wrapper == null) { HttpServletRequest request = RequestHolder.getCurrentRequest(); if (request != null) { wrapper = new HttpServletRequestWrapper(request); REQUEST_WRAPPER.set(wrapper); } else { LOGGER.warn("Unable to get the current HTTP request"); } } return wrapper; } return null; } HttpServletRequestResolver(); HttpServletRequestResolver(int priority); @Override Object resolve(Object contextObject, String name,
ResolutionContext context); @Override void init(); @Override Set<ConfigurationKey> getConfigurationKeys(); @Override void renderingStarted(MustacheRenderingEvent event); @Override boolean isValid(); static final int SERVLET_REQUEST_RESOLVER_PRIORITY; static final ConfigurationKey ENABLED_KEY; } |
@Test public void testResolution() { JsonElementResolver resolver = new JsonElementResolver(); ResolutionContext ctx = new DummyResolutionContext(); MustacheEngineBuilder.newBuilder() .omitServiceLoaderConfigurationExtensions() .setProperty(JsonElementResolver.UNWRAP_JSON_PRIMITIVE_KEY, true) .setProperty(GsonValueConverter.ENABLED_KEY, false) .addResolver(resolver).build(); assertNull(resolver.resolve(null, "foo", ctx)); assertNull(resolver.resolve("bar", "foo", ctx)); assertEquals(Boolean.TRUE, resolver.resolve(new JsonPrimitive(true), "unwrapThis", ctx)); assertNull(resolver.resolve(new JsonPrimitive(true), "whatever", ctx)); assertEquals(Placeholder.NULL, resolver.resolve(JsonNull.INSTANCE, "unwrapThis", ctx)); JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("foo", "bar"); jsonObject.addProperty("baz", true); assertEquals("bar", resolver.resolve(jsonObject, "foo", ctx)); assertEquals(Boolean.TRUE, resolver.resolve(jsonObject, "baz", ctx)); JsonArray jsonArray = new JsonArray(); jsonArray.add(new JsonPrimitive(true)); jsonArray.add(new JsonPrimitive(1)); assertEquals(true, resolver.resolve(jsonArray, "0", ctx)); assertEquals(1, resolver.resolve(jsonArray, "1", ctx)); } | @Override public Object resolve(Object contextObject, String name, ResolutionContext context) { if (contextObject == null || !(contextObject instanceof JsonElement)) { return null; } JsonElement element = (JsonElement) contextObject; if (element.isJsonArray() && isAnIndex(name)) { JsonArray jsonArray = (JsonArray) element; final Integer index = getIndexValue(name, context.getKey(), jsonArray.size()); if (index != null) { return unwrapJsonElementIfNecessary(jsonArray.get(index), unwrapJsonPrimitive); } } else if (element.isJsonObject()) { JsonObject jsonObject = (JsonObject) element; JsonElement member = jsonObject.get(name); if (member != null) { return unwrapJsonElementIfNecessary(member, unwrapJsonPrimitive); } } else if (name.equals(NAME_UNWRAP_THIS)) { return unwrapJsonElementIfNecessary(element, true); } return null; } | JsonElementResolver extends IndexResolver { @Override public Object resolve(Object contextObject, String name, ResolutionContext context) { if (contextObject == null || !(contextObject instanceof JsonElement)) { return null; } JsonElement element = (JsonElement) contextObject; if (element.isJsonArray() && isAnIndex(name)) { JsonArray jsonArray = (JsonArray) element; final Integer index = getIndexValue(name, context.getKey(), jsonArray.size()); if (index != null) { return unwrapJsonElementIfNecessary(jsonArray.get(index), unwrapJsonPrimitive); } } else if (element.isJsonObject()) { JsonObject jsonObject = (JsonObject) element; JsonElement member = jsonObject.get(name); if (member != null) { return unwrapJsonElementIfNecessary(member, unwrapJsonPrimitive); } } else if (name.equals(NAME_UNWRAP_THIS)) { return unwrapJsonElementIfNecessary(element, true); } return null; } } | JsonElementResolver extends IndexResolver { @Override public Object resolve(Object contextObject, String name, ResolutionContext context) { if (contextObject == null || !(contextObject instanceof JsonElement)) { return null; } JsonElement element = (JsonElement) contextObject; if (element.isJsonArray() && isAnIndex(name)) { JsonArray jsonArray = (JsonArray) element; final Integer index = getIndexValue(name, context.getKey(), jsonArray.size()); if (index != null) { return unwrapJsonElementIfNecessary(jsonArray.get(index), unwrapJsonPrimitive); } } else if (element.isJsonObject()) { JsonObject jsonObject = (JsonObject) element; JsonElement member = jsonObject.get(name); if (member != null) { return unwrapJsonElementIfNecessary(member, unwrapJsonPrimitive); } } else if (name.equals(NAME_UNWRAP_THIS)) { return unwrapJsonElementIfNecessary(element, true); } return null; } JsonElementResolver(); JsonElementResolver(int priority); } | JsonElementResolver extends IndexResolver { @Override public Object resolve(Object contextObject, String name, ResolutionContext context) { if (contextObject == null || !(contextObject instanceof JsonElement)) { return null; } JsonElement element = (JsonElement) contextObject; if (element.isJsonArray() && isAnIndex(name)) { JsonArray jsonArray = (JsonArray) element; final Integer index = getIndexValue(name, context.getKey(), jsonArray.size()); if (index != null) { return unwrapJsonElementIfNecessary(jsonArray.get(index), unwrapJsonPrimitive); } } else if (element.isJsonObject()) { JsonObject jsonObject = (JsonObject) element; JsonElement member = jsonObject.get(name); if (member != null) { return unwrapJsonElementIfNecessary(member, unwrapJsonPrimitive); } } else if (name.equals(NAME_UNWRAP_THIS)) { return unwrapJsonElementIfNecessary(element, true); } return null; } JsonElementResolver(); JsonElementResolver(int priority); @Override Object resolve(Object contextObject, String name,
ResolutionContext context); @Override void init(); @Override Set<ConfigurationKey> getConfigurationKeys(); @Override Hint createHint(Object contextObject, String name,
ResolutionContext context); } | JsonElementResolver extends IndexResolver { @Override public Object resolve(Object contextObject, String name, ResolutionContext context) { if (contextObject == null || !(contextObject instanceof JsonElement)) { return null; } JsonElement element = (JsonElement) contextObject; if (element.isJsonArray() && isAnIndex(name)) { JsonArray jsonArray = (JsonArray) element; final Integer index = getIndexValue(name, context.getKey(), jsonArray.size()); if (index != null) { return unwrapJsonElementIfNecessary(jsonArray.get(index), unwrapJsonPrimitive); } } else if (element.isJsonObject()) { JsonObject jsonObject = (JsonObject) element; JsonElement member = jsonObject.get(name); if (member != null) { return unwrapJsonElementIfNecessary(member, unwrapJsonPrimitive); } } else if (name.equals(NAME_UNWRAP_THIS)) { return unwrapJsonElementIfNecessary(element, true); } return null; } JsonElementResolver(); JsonElementResolver(int priority); @Override Object resolve(Object contextObject, String name,
ResolutionContext context); @Override void init(); @Override Set<ConfigurationKey> getConfigurationKeys(); @Override Hint createHint(Object contextObject, String name,
ResolutionContext context); static final int JSON_ELEMENT_RESOLVER_PRIORITY; static final String NAME_UNWRAP_THIS; static final ConfigurationKey UNWRAP_JSON_PRIMITIVE_KEY; } |
@Test public void testResolution() { JsonValueResolver resolver = new JsonValueResolver(); ResolutionContext ctx = new DummyResolutionContext(); MustacheEngineBuilder.newBuilder() .omitServiceLoaderConfigurationExtensions() .addResolver(resolver) .setProperty(JsonValueResolver.ENABLED_KEY, true).build(); assertNull(resolver.resolve(null, "foo", ctx)); assertNull(resolver.resolve("bar", "foo", ctx)); assertEquals(Boolean.TRUE, resolver.resolve(JsonValue.TRUE, "unwrapThis", ctx)); assertNull(resolver.resolve(JsonValue.TRUE, "whatever", ctx)); assertEquals(Placeholder.NULL, resolver.resolve(JsonValue.NULL, "unwrapThis", ctx)); JsonObject jsonObject = Json.createObjectBuilder().add("foo", "bar") .add("baz", true).build(); assertEquals("bar", resolver.resolve(jsonObject, "foo", ctx)); assertEquals(Boolean.TRUE, resolver.resolve(jsonObject, "baz", ctx)); JsonArray jsonArray = Json.createArrayBuilder().add(true).add(1) .build(); assertEquals(true, resolver.resolve(jsonArray, "0", ctx)); assertEquals(BigDecimal.ONE, resolver.resolve(jsonArray, "1", ctx)); } | @Override public Object resolve(Object contextObject, String name, ResolutionContext context) { if (contextObject == null || !(contextObject instanceof JsonValue)) { return null; } JsonValue jsonValue = (JsonValue) contextObject; if (ValueType.ARRAY.equals(jsonValue.getValueType()) && isAnIndex(name)) { JsonArray jsonArray = (JsonArray) jsonValue; final Integer index = getIndexValue(name, context.getKey(), jsonArray.size()); if (index != null) { return unwrapJsonValueIfNecessary(jsonArray.get(index)); } } else if (ValueType.OBJECT.equals(jsonValue.getValueType())) { JsonObject jsonObject = (JsonObject) jsonValue; JsonValue member = jsonObject.get(name); if (member != null) { return unwrapJsonValueIfNecessary(member); } } else if (name.equals(NAME_UNWRAP_THIS)) { return unwrapJsonValueIfNecessary(jsonValue); } return null; } | JsonValueResolver extends IndexResolver implements Validateable { @Override public Object resolve(Object contextObject, String name, ResolutionContext context) { if (contextObject == null || !(contextObject instanceof JsonValue)) { return null; } JsonValue jsonValue = (JsonValue) contextObject; if (ValueType.ARRAY.equals(jsonValue.getValueType()) && isAnIndex(name)) { JsonArray jsonArray = (JsonArray) jsonValue; final Integer index = getIndexValue(name, context.getKey(), jsonArray.size()); if (index != null) { return unwrapJsonValueIfNecessary(jsonArray.get(index)); } } else if (ValueType.OBJECT.equals(jsonValue.getValueType())) { JsonObject jsonObject = (JsonObject) jsonValue; JsonValue member = jsonObject.get(name); if (member != null) { return unwrapJsonValueIfNecessary(member); } } else if (name.equals(NAME_UNWRAP_THIS)) { return unwrapJsonValueIfNecessary(jsonValue); } return null; } } | JsonValueResolver extends IndexResolver implements Validateable { @Override public Object resolve(Object contextObject, String name, ResolutionContext context) { if (contextObject == null || !(contextObject instanceof JsonValue)) { return null; } JsonValue jsonValue = (JsonValue) contextObject; if (ValueType.ARRAY.equals(jsonValue.getValueType()) && isAnIndex(name)) { JsonArray jsonArray = (JsonArray) jsonValue; final Integer index = getIndexValue(name, context.getKey(), jsonArray.size()); if (index != null) { return unwrapJsonValueIfNecessary(jsonArray.get(index)); } } else if (ValueType.OBJECT.equals(jsonValue.getValueType())) { JsonObject jsonObject = (JsonObject) jsonValue; JsonValue member = jsonObject.get(name); if (member != null) { return unwrapJsonValueIfNecessary(member); } } else if (name.equals(NAME_UNWRAP_THIS)) { return unwrapJsonValueIfNecessary(jsonValue); } return null; } JsonValueResolver(); JsonValueResolver(int priority); } | JsonValueResolver extends IndexResolver implements Validateable { @Override public Object resolve(Object contextObject, String name, ResolutionContext context) { if (contextObject == null || !(contextObject instanceof JsonValue)) { return null; } JsonValue jsonValue = (JsonValue) contextObject; if (ValueType.ARRAY.equals(jsonValue.getValueType()) && isAnIndex(name)) { JsonArray jsonArray = (JsonArray) jsonValue; final Integer index = getIndexValue(name, context.getKey(), jsonArray.size()); if (index != null) { return unwrapJsonValueIfNecessary(jsonArray.get(index)); } } else if (ValueType.OBJECT.equals(jsonValue.getValueType())) { JsonObject jsonObject = (JsonObject) jsonValue; JsonValue member = jsonObject.get(name); if (member != null) { return unwrapJsonValueIfNecessary(member); } } else if (name.equals(NAME_UNWRAP_THIS)) { return unwrapJsonValueIfNecessary(jsonValue); } return null; } JsonValueResolver(); JsonValueResolver(int priority); @Override Object resolve(Object contextObject, String name,
ResolutionContext context); @Override Hint createHint(Object contextObject, String name,
ResolutionContext context); @Override void init(Configuration configuration); @Override Set<ConfigurationKey> getConfigurationKeys(); } | JsonValueResolver extends IndexResolver implements Validateable { @Override public Object resolve(Object contextObject, String name, ResolutionContext context) { if (contextObject == null || !(contextObject instanceof JsonValue)) { return null; } JsonValue jsonValue = (JsonValue) contextObject; if (ValueType.ARRAY.equals(jsonValue.getValueType()) && isAnIndex(name)) { JsonArray jsonArray = (JsonArray) jsonValue; final Integer index = getIndexValue(name, context.getKey(), jsonArray.size()); if (index != null) { return unwrapJsonValueIfNecessary(jsonArray.get(index)); } } else if (ValueType.OBJECT.equals(jsonValue.getValueType())) { JsonObject jsonObject = (JsonObject) jsonValue; JsonValue member = jsonObject.get(name); if (member != null) { return unwrapJsonValueIfNecessary(member); } } else if (name.equals(NAME_UNWRAP_THIS)) { return unwrapJsonValueIfNecessary(jsonValue); } return null; } JsonValueResolver(); JsonValueResolver(int priority); @Override Object resolve(Object contextObject, String name,
ResolutionContext context); @Override Hint createHint(Object contextObject, String name,
ResolutionContext context); @Override void init(Configuration configuration); @Override Set<ConfigurationKey> getConfigurationKeys(); static final int JSON_VALUE_RESOLVER_PRIORITY; static final ConfigurationKey ENABLED_KEY; static final String NAME_UNWRAP_THIS; } |
@Test public void availabilityOfTemplateInDefaultLocation() throws Exception { final SpringResourceTemplateLocator loader = new SpringResourceTemplateLocator(); final Reader r1 = loader.locate("home"); assertThat(readContent(r1), is("home")); final Reader r2 = loader.locate("prefix/prefixed"); assertThat(readContent(r2), is("prefixed")); } | public Reader locate(final String name) { final String resourceLocation = prefix + name + suffix; try { if (Strings.isEmpty(charset)) { return new InputStreamReader(resourceLoader.getResource(resourceLocation).getInputStream()); } return new InputStreamReader(resourceLoader.getResource(resourceLocation).getInputStream(), charset); } catch (UnsupportedEncodingException e) { LOGGER.warn("Charset not supported: {}", charset); } catch (IOException e) { LOGGER.warn("Template not found: {}", resourceLocation); } return null; } | SpringResourceTemplateLocator extends AbstractTemplateLocator implements ResourceLoaderAware { public Reader locate(final String name) { final String resourceLocation = prefix + name + suffix; try { if (Strings.isEmpty(charset)) { return new InputStreamReader(resourceLoader.getResource(resourceLocation).getInputStream()); } return new InputStreamReader(resourceLoader.getResource(resourceLocation).getInputStream(), charset); } catch (UnsupportedEncodingException e) { LOGGER.warn("Charset not supported: {}", charset); } catch (IOException e) { LOGGER.warn("Template not found: {}", resourceLocation); } return null; } } | SpringResourceTemplateLocator extends AbstractTemplateLocator implements ResourceLoaderAware { public Reader locate(final String name) { final String resourceLocation = prefix + name + suffix; try { if (Strings.isEmpty(charset)) { return new InputStreamReader(resourceLoader.getResource(resourceLocation).getInputStream()); } return new InputStreamReader(resourceLoader.getResource(resourceLocation).getInputStream(), charset); } catch (UnsupportedEncodingException e) { LOGGER.warn("Charset not supported: {}", charset); } catch (IOException e) { LOGGER.warn("Template not found: {}", resourceLocation); } return null; } SpringResourceTemplateLocator(); SpringResourceTemplateLocator(final int priority, final String prefix, final String suffix); } | SpringResourceTemplateLocator extends AbstractTemplateLocator implements ResourceLoaderAware { public Reader locate(final String name) { final String resourceLocation = prefix + name + suffix; try { if (Strings.isEmpty(charset)) { return new InputStreamReader(resourceLoader.getResource(resourceLocation).getInputStream()); } return new InputStreamReader(resourceLoader.getResource(resourceLocation).getInputStream(), charset); } catch (UnsupportedEncodingException e) { LOGGER.warn("Charset not supported: {}", charset); } catch (IOException e) { LOGGER.warn("Template not found: {}", resourceLocation); } return null; } SpringResourceTemplateLocator(); SpringResourceTemplateLocator(final int priority, final String prefix, final String suffix); void setResourceLoader(final ResourceLoader resourceLoader); Reader locate(final String name); String getPrefix(); void setPrefix(final String prefix); String getSuffix(); void setSuffix(final String suffix); String getCharset(); void setCharset(final String charset); } | SpringResourceTemplateLocator extends AbstractTemplateLocator implements ResourceLoaderAware { public Reader locate(final String name) { final String resourceLocation = prefix + name + suffix; try { if (Strings.isEmpty(charset)) { return new InputStreamReader(resourceLoader.getResource(resourceLocation).getInputStream()); } return new InputStreamReader(resourceLoader.getResource(resourceLocation).getInputStream(), charset); } catch (UnsupportedEncodingException e) { LOGGER.warn("Charset not supported: {}", charset); } catch (IOException e) { LOGGER.warn("Template not found: {}", resourceLocation); } return null; } SpringResourceTemplateLocator(); SpringResourceTemplateLocator(final int priority, final String prefix, final String suffix); void setResourceLoader(final ResourceLoader resourceLoader); Reader locate(final String name); String getPrefix(); void setPrefix(final String prefix); String getSuffix(); void setSuffix(final String suffix); String getCharset(); void setCharset(final String charset); static final String DEFAULT_PREFIX; static final String DEFAULT_SUFFIX; } |
@Test public void availabilityOfTemplateThatDoesNotExist() throws Exception { final SpringResourceTemplateLocator loader = new SpringResourceTemplateLocator(); assertThat(loader.locate("unknown"), is(nullValue())); } | public Reader locate(final String name) { final String resourceLocation = prefix + name + suffix; try { if (Strings.isEmpty(charset)) { return new InputStreamReader(resourceLoader.getResource(resourceLocation).getInputStream()); } return new InputStreamReader(resourceLoader.getResource(resourceLocation).getInputStream(), charset); } catch (UnsupportedEncodingException e) { LOGGER.warn("Charset not supported: {}", charset); } catch (IOException e) { LOGGER.warn("Template not found: {}", resourceLocation); } return null; } | SpringResourceTemplateLocator extends AbstractTemplateLocator implements ResourceLoaderAware { public Reader locate(final String name) { final String resourceLocation = prefix + name + suffix; try { if (Strings.isEmpty(charset)) { return new InputStreamReader(resourceLoader.getResource(resourceLocation).getInputStream()); } return new InputStreamReader(resourceLoader.getResource(resourceLocation).getInputStream(), charset); } catch (UnsupportedEncodingException e) { LOGGER.warn("Charset not supported: {}", charset); } catch (IOException e) { LOGGER.warn("Template not found: {}", resourceLocation); } return null; } } | SpringResourceTemplateLocator extends AbstractTemplateLocator implements ResourceLoaderAware { public Reader locate(final String name) { final String resourceLocation = prefix + name + suffix; try { if (Strings.isEmpty(charset)) { return new InputStreamReader(resourceLoader.getResource(resourceLocation).getInputStream()); } return new InputStreamReader(resourceLoader.getResource(resourceLocation).getInputStream(), charset); } catch (UnsupportedEncodingException e) { LOGGER.warn("Charset not supported: {}", charset); } catch (IOException e) { LOGGER.warn("Template not found: {}", resourceLocation); } return null; } SpringResourceTemplateLocator(); SpringResourceTemplateLocator(final int priority, final String prefix, final String suffix); } | SpringResourceTemplateLocator extends AbstractTemplateLocator implements ResourceLoaderAware { public Reader locate(final String name) { final String resourceLocation = prefix + name + suffix; try { if (Strings.isEmpty(charset)) { return new InputStreamReader(resourceLoader.getResource(resourceLocation).getInputStream()); } return new InputStreamReader(resourceLoader.getResource(resourceLocation).getInputStream(), charset); } catch (UnsupportedEncodingException e) { LOGGER.warn("Charset not supported: {}", charset); } catch (IOException e) { LOGGER.warn("Template not found: {}", resourceLocation); } return null; } SpringResourceTemplateLocator(); SpringResourceTemplateLocator(final int priority, final String prefix, final String suffix); void setResourceLoader(final ResourceLoader resourceLoader); Reader locate(final String name); String getPrefix(); void setPrefix(final String prefix); String getSuffix(); void setSuffix(final String suffix); String getCharset(); void setCharset(final String charset); } | SpringResourceTemplateLocator extends AbstractTemplateLocator implements ResourceLoaderAware { public Reader locate(final String name) { final String resourceLocation = prefix + name + suffix; try { if (Strings.isEmpty(charset)) { return new InputStreamReader(resourceLoader.getResource(resourceLocation).getInputStream()); } return new InputStreamReader(resourceLoader.getResource(resourceLocation).getInputStream(), charset); } catch (UnsupportedEncodingException e) { LOGGER.warn("Charset not supported: {}", charset); } catch (IOException e) { LOGGER.warn("Template not found: {}", resourceLocation); } return null; } SpringResourceTemplateLocator(); SpringResourceTemplateLocator(final int priority, final String prefix, final String suffix); void setResourceLoader(final ResourceLoader resourceLoader); Reader locate(final String name); String getPrefix(); void setPrefix(final String prefix); String getSuffix(); void setSuffix(final String suffix); String getCharset(); void setCharset(final String charset); static final String DEFAULT_PREFIX; static final String DEFAULT_SUFFIX; } |
@Test public void testContainsOnlyWhitespace() { assertTrue(Strings.containsOnlyWhitespace(" ")); assertTrue(Strings.containsOnlyWhitespace( " " + System.getProperty("line.separator"))); assertFalse(Strings.containsOnlyWhitespace(" !")); } | public static boolean containsOnlyWhitespace(String text) { if (isEmpty(text)) { return false; } for (int i = 0; i < text.length(); i++) { if (!Character.isWhitespace(text.charAt(i))) { return false; } } return true; } | Strings { public static boolean containsOnlyWhitespace(String text) { if (isEmpty(text)) { return false; } for (int i = 0; i < text.length(); i++) { if (!Character.isWhitespace(text.charAt(i))) { return false; } } return true; } } | Strings { public static boolean containsOnlyWhitespace(String text) { if (isEmpty(text)) { return false; } for (int i = 0; i < text.length(); i++) { if (!Character.isWhitespace(text.charAt(i))) { return false; } } return true; } private Strings(); } | Strings { public static boolean containsOnlyWhitespace(String text) { if (isEmpty(text)) { return false; } for (int i = 0; i < text.length(); i++) { if (!Character.isWhitespace(text.charAt(i))) { return false; } } return true; } private Strings(); static boolean isStringLiteralSeparator(char character); static boolean isEmpty(CharSequence sequence); static String uncapitalize(String word); static String capitalizeFully(String text, Character delimiter); static String replace(String text, String search,
String replacement); static String removeSuffix(String text, String suffix); static List<String> split(String text, String delimiter); static boolean containsWhitespace(String text); static boolean containsOnlyWhitespace(String text); static boolean containsOnlyDigits(String text); static String repeat(String text, int times, String separator); static String substringAfter(String text, String delimiter); static boolean isListLiteralStart(char character); static boolean isListLiteralEnd(char character); static boolean isListLiteral(String value); } | Strings { public static boolean containsOnlyWhitespace(String text) { if (isEmpty(text)) { return false; } for (int i = 0; i < text.length(); i++) { if (!Character.isWhitespace(text.charAt(i))) { return false; } } return true; } private Strings(); static boolean isStringLiteralSeparator(char character); static boolean isEmpty(CharSequence sequence); static String uncapitalize(String word); static String capitalizeFully(String text, Character delimiter); static String replace(String text, String search,
String replacement); static String removeSuffix(String text, String suffix); static List<String> split(String text, String delimiter); static boolean containsWhitespace(String text); static boolean containsOnlyWhitespace(String text); static boolean containsOnlyDigits(String text); static String repeat(String text, int times, String separator); static String substringAfter(String text, String delimiter); static boolean isListLiteralStart(char character); static boolean isListLiteralEnd(char character); static boolean isListLiteral(String value); static final String EMPTY; static final String GAP; static final String LINE_SEPARATOR; static final String LINE_SEPARATOR_LF; static final String LINE_SEPARATOR_CRLF; static final String LINE_SEPARATOR_CR; static final String SLASH; static final String FILE_SEPARATOR; static final String DOT; static final String UNDERSCORE; static final String NOT_AVAILABLE; static final String URL_PROCOTOL_FILE; static final String THIS; static final String HASH; } |
@Test public void availabilityOfTemplateWithCustomPrefix() throws Exception { final SpringResourceTemplateLocator loader = new SpringResourceTemplateLocator(1, "classpath:/custom-templates/", SpringResourceTemplateLocator.DEFAULT_SUFFIX); final Reader reader = loader.locate("custom"); assertThat(readContent(reader), is("custom")); } | public Reader locate(final String name) { final String resourceLocation = prefix + name + suffix; try { if (Strings.isEmpty(charset)) { return new InputStreamReader(resourceLoader.getResource(resourceLocation).getInputStream()); } return new InputStreamReader(resourceLoader.getResource(resourceLocation).getInputStream(), charset); } catch (UnsupportedEncodingException e) { LOGGER.warn("Charset not supported: {}", charset); } catch (IOException e) { LOGGER.warn("Template not found: {}", resourceLocation); } return null; } | SpringResourceTemplateLocator extends AbstractTemplateLocator implements ResourceLoaderAware { public Reader locate(final String name) { final String resourceLocation = prefix + name + suffix; try { if (Strings.isEmpty(charset)) { return new InputStreamReader(resourceLoader.getResource(resourceLocation).getInputStream()); } return new InputStreamReader(resourceLoader.getResource(resourceLocation).getInputStream(), charset); } catch (UnsupportedEncodingException e) { LOGGER.warn("Charset not supported: {}", charset); } catch (IOException e) { LOGGER.warn("Template not found: {}", resourceLocation); } return null; } } | SpringResourceTemplateLocator extends AbstractTemplateLocator implements ResourceLoaderAware { public Reader locate(final String name) { final String resourceLocation = prefix + name + suffix; try { if (Strings.isEmpty(charset)) { return new InputStreamReader(resourceLoader.getResource(resourceLocation).getInputStream()); } return new InputStreamReader(resourceLoader.getResource(resourceLocation).getInputStream(), charset); } catch (UnsupportedEncodingException e) { LOGGER.warn("Charset not supported: {}", charset); } catch (IOException e) { LOGGER.warn("Template not found: {}", resourceLocation); } return null; } SpringResourceTemplateLocator(); SpringResourceTemplateLocator(final int priority, final String prefix, final String suffix); } | SpringResourceTemplateLocator extends AbstractTemplateLocator implements ResourceLoaderAware { public Reader locate(final String name) { final String resourceLocation = prefix + name + suffix; try { if (Strings.isEmpty(charset)) { return new InputStreamReader(resourceLoader.getResource(resourceLocation).getInputStream()); } return new InputStreamReader(resourceLoader.getResource(resourceLocation).getInputStream(), charset); } catch (UnsupportedEncodingException e) { LOGGER.warn("Charset not supported: {}", charset); } catch (IOException e) { LOGGER.warn("Template not found: {}", resourceLocation); } return null; } SpringResourceTemplateLocator(); SpringResourceTemplateLocator(final int priority, final String prefix, final String suffix); void setResourceLoader(final ResourceLoader resourceLoader); Reader locate(final String name); String getPrefix(); void setPrefix(final String prefix); String getSuffix(); void setSuffix(final String suffix); String getCharset(); void setCharset(final String charset); } | SpringResourceTemplateLocator extends AbstractTemplateLocator implements ResourceLoaderAware { public Reader locate(final String name) { final String resourceLocation = prefix + name + suffix; try { if (Strings.isEmpty(charset)) { return new InputStreamReader(resourceLoader.getResource(resourceLocation).getInputStream()); } return new InputStreamReader(resourceLoader.getResource(resourceLocation).getInputStream(), charset); } catch (UnsupportedEncodingException e) { LOGGER.warn("Charset not supported: {}", charset); } catch (IOException e) { LOGGER.warn("Template not found: {}", resourceLocation); } return null; } SpringResourceTemplateLocator(); SpringResourceTemplateLocator(final int priority, final String prefix, final String suffix); void setResourceLoader(final ResourceLoader resourceLoader); Reader locate(final String name); String getPrefix(); void setPrefix(final String prefix); String getSuffix(); void setSuffix(final String suffix); String getCharset(); void setCharset(final String charset); static final String DEFAULT_PREFIX; static final String DEFAULT_SUFFIX; } |
@Test public void availabilityOfTemplateWithCustomSuffix() throws Exception { final SpringResourceTemplateLocator loader = new SpringResourceTemplateLocator(1, SpringResourceTemplateLocator.DEFAULT_PREFIX, ".html"); final Reader reader = loader.locate("suffixed"); assertThat(readContent(reader), is("suffixed")); } | public Reader locate(final String name) { final String resourceLocation = prefix + name + suffix; try { if (Strings.isEmpty(charset)) { return new InputStreamReader(resourceLoader.getResource(resourceLocation).getInputStream()); } return new InputStreamReader(resourceLoader.getResource(resourceLocation).getInputStream(), charset); } catch (UnsupportedEncodingException e) { LOGGER.warn("Charset not supported: {}", charset); } catch (IOException e) { LOGGER.warn("Template not found: {}", resourceLocation); } return null; } | SpringResourceTemplateLocator extends AbstractTemplateLocator implements ResourceLoaderAware { public Reader locate(final String name) { final String resourceLocation = prefix + name + suffix; try { if (Strings.isEmpty(charset)) { return new InputStreamReader(resourceLoader.getResource(resourceLocation).getInputStream()); } return new InputStreamReader(resourceLoader.getResource(resourceLocation).getInputStream(), charset); } catch (UnsupportedEncodingException e) { LOGGER.warn("Charset not supported: {}", charset); } catch (IOException e) { LOGGER.warn("Template not found: {}", resourceLocation); } return null; } } | SpringResourceTemplateLocator extends AbstractTemplateLocator implements ResourceLoaderAware { public Reader locate(final String name) { final String resourceLocation = prefix + name + suffix; try { if (Strings.isEmpty(charset)) { return new InputStreamReader(resourceLoader.getResource(resourceLocation).getInputStream()); } return new InputStreamReader(resourceLoader.getResource(resourceLocation).getInputStream(), charset); } catch (UnsupportedEncodingException e) { LOGGER.warn("Charset not supported: {}", charset); } catch (IOException e) { LOGGER.warn("Template not found: {}", resourceLocation); } return null; } SpringResourceTemplateLocator(); SpringResourceTemplateLocator(final int priority, final String prefix, final String suffix); } | SpringResourceTemplateLocator extends AbstractTemplateLocator implements ResourceLoaderAware { public Reader locate(final String name) { final String resourceLocation = prefix + name + suffix; try { if (Strings.isEmpty(charset)) { return new InputStreamReader(resourceLoader.getResource(resourceLocation).getInputStream()); } return new InputStreamReader(resourceLoader.getResource(resourceLocation).getInputStream(), charset); } catch (UnsupportedEncodingException e) { LOGGER.warn("Charset not supported: {}", charset); } catch (IOException e) { LOGGER.warn("Template not found: {}", resourceLocation); } return null; } SpringResourceTemplateLocator(); SpringResourceTemplateLocator(final int priority, final String prefix, final String suffix); void setResourceLoader(final ResourceLoader resourceLoader); Reader locate(final String name); String getPrefix(); void setPrefix(final String prefix); String getSuffix(); void setSuffix(final String suffix); String getCharset(); void setCharset(final String charset); } | SpringResourceTemplateLocator extends AbstractTemplateLocator implements ResourceLoaderAware { public Reader locate(final String name) { final String resourceLocation = prefix + name + suffix; try { if (Strings.isEmpty(charset)) { return new InputStreamReader(resourceLoader.getResource(resourceLocation).getInputStream()); } return new InputStreamReader(resourceLoader.getResource(resourceLocation).getInputStream(), charset); } catch (UnsupportedEncodingException e) { LOGGER.warn("Charset not supported: {}", charset); } catch (IOException e) { LOGGER.warn("Template not found: {}", resourceLocation); } return null; } SpringResourceTemplateLocator(); SpringResourceTemplateLocator(final int priority, final String prefix, final String suffix); void setResourceLoader(final ResourceLoader resourceLoader); Reader locate(final String name); String getPrefix(); void setPrefix(final String prefix); String getSuffix(); void setSuffix(final String suffix); String getCharset(); void setCharset(final String charset); static final String DEFAULT_PREFIX; static final String DEFAULT_SUFFIX; } |
@Test public void cacheEnabled() throws Exception { assertThat(resolver.isCache(), is(true)); } | @Override public boolean isCache() { return engine.getConfiguration().getBooleanPropertyValue(EngineConfigurationKey.TEMPLATE_CACHE_ENABLED) && !engine.getConfiguration().getBooleanPropertyValue(EngineConfigurationKey.DEBUG_MODE) && super.isCache(); } | TrimouViewResolver extends AbstractTemplateViewResolver { @Override public boolean isCache() { return engine.getConfiguration().getBooleanPropertyValue(EngineConfigurationKey.TEMPLATE_CACHE_ENABLED) && !engine.getConfiguration().getBooleanPropertyValue(EngineConfigurationKey.DEBUG_MODE) && super.isCache(); } } | TrimouViewResolver extends AbstractTemplateViewResolver { @Override public boolean isCache() { return engine.getConfiguration().getBooleanPropertyValue(EngineConfigurationKey.TEMPLATE_CACHE_ENABLED) && !engine.getConfiguration().getBooleanPropertyValue(EngineConfigurationKey.DEBUG_MODE) && super.isCache(); } TrimouViewResolver(); TrimouViewResolver(final MustacheEngine engine); } | TrimouViewResolver extends AbstractTemplateViewResolver { @Override public boolean isCache() { return engine.getConfiguration().getBooleanPropertyValue(EngineConfigurationKey.TEMPLATE_CACHE_ENABLED) && !engine.getConfiguration().getBooleanPropertyValue(EngineConfigurationKey.DEBUG_MODE) && super.isCache(); } TrimouViewResolver(); TrimouViewResolver(final MustacheEngine engine); @Override boolean isCache(); void setEngine(final MustacheEngine engine); @Override void setPrefix(final String prefix); @Override void setSuffix(final String suffix); } | TrimouViewResolver extends AbstractTemplateViewResolver { @Override public boolean isCache() { return engine.getConfiguration().getBooleanPropertyValue(EngineConfigurationKey.TEMPLATE_CACHE_ENABLED) && !engine.getConfiguration().getBooleanPropertyValue(EngineConfigurationKey.DEBUG_MODE) && super.isCache(); } TrimouViewResolver(); TrimouViewResolver(final MustacheEngine engine); @Override boolean isCache(); void setEngine(final MustacheEngine engine); @Override void setPrefix(final String prefix); @Override void setSuffix(final String suffix); } |
@Test public void testContainsOnlyDigits() { assertTrue(Strings.containsOnlyDigits("123")); assertFalse(Strings.containsOnlyDigits("5!")); } | public static boolean containsOnlyDigits(String text) { if (isEmpty(text)) { return false; } for (int i = 0; i < text.length(); i++) { if (!Character.isDigit(text.charAt(i))) { return false; } } return true; } | Strings { public static boolean containsOnlyDigits(String text) { if (isEmpty(text)) { return false; } for (int i = 0; i < text.length(); i++) { if (!Character.isDigit(text.charAt(i))) { return false; } } return true; } } | Strings { public static boolean containsOnlyDigits(String text) { if (isEmpty(text)) { return false; } for (int i = 0; i < text.length(); i++) { if (!Character.isDigit(text.charAt(i))) { return false; } } return true; } private Strings(); } | Strings { public static boolean containsOnlyDigits(String text) { if (isEmpty(text)) { return false; } for (int i = 0; i < text.length(); i++) { if (!Character.isDigit(text.charAt(i))) { return false; } } return true; } private Strings(); static boolean isStringLiteralSeparator(char character); static boolean isEmpty(CharSequence sequence); static String uncapitalize(String word); static String capitalizeFully(String text, Character delimiter); static String replace(String text, String search,
String replacement); static String removeSuffix(String text, String suffix); static List<String> split(String text, String delimiter); static boolean containsWhitespace(String text); static boolean containsOnlyWhitespace(String text); static boolean containsOnlyDigits(String text); static String repeat(String text, int times, String separator); static String substringAfter(String text, String delimiter); static boolean isListLiteralStart(char character); static boolean isListLiteralEnd(char character); static boolean isListLiteral(String value); } | Strings { public static boolean containsOnlyDigits(String text) { if (isEmpty(text)) { return false; } for (int i = 0; i < text.length(); i++) { if (!Character.isDigit(text.charAt(i))) { return false; } } return true; } private Strings(); static boolean isStringLiteralSeparator(char character); static boolean isEmpty(CharSequence sequence); static String uncapitalize(String word); static String capitalizeFully(String text, Character delimiter); static String replace(String text, String search,
String replacement); static String removeSuffix(String text, String suffix); static List<String> split(String text, String delimiter); static boolean containsWhitespace(String text); static boolean containsOnlyWhitespace(String text); static boolean containsOnlyDigits(String text); static String repeat(String text, int times, String separator); static String substringAfter(String text, String delimiter); static boolean isListLiteralStart(char character); static boolean isListLiteralEnd(char character); static boolean isListLiteral(String value); static final String EMPTY; static final String GAP; static final String LINE_SEPARATOR; static final String LINE_SEPARATOR_LF; static final String LINE_SEPARATOR_CRLF; static final String LINE_SEPARATOR_CR; static final String SLASH; static final String FILE_SEPARATOR; static final String DOT; static final String UNDERSCORE; static final String NOT_AVAILABLE; static final String URL_PROCOTOL_FILE; static final String THIS; static final String HASH; } |
@Test public void testRepeat() { assertEquals("foo,foo", Strings.repeat("foo", 2, ",")); assertEquals("ooo", Strings.repeat("o", 3, "")); assertEquals("o", Strings.repeat("o", -3, "")); assertEquals("", Strings.repeat("ouch", 0, "")); } | public static String repeat(String text, int times, String separator) { if (isEmpty(text) || times < 0) { return text; } if (times == 0) { return EMPTY; } StringBuilder builder = new StringBuilder(); for (int i = 0; i < times; i++) { builder.append(text); if (i + 1 < times) { builder.append(separator); } } return builder.toString(); } | Strings { public static String repeat(String text, int times, String separator) { if (isEmpty(text) || times < 0) { return text; } if (times == 0) { return EMPTY; } StringBuilder builder = new StringBuilder(); for (int i = 0; i < times; i++) { builder.append(text); if (i + 1 < times) { builder.append(separator); } } return builder.toString(); } } | Strings { public static String repeat(String text, int times, String separator) { if (isEmpty(text) || times < 0) { return text; } if (times == 0) { return EMPTY; } StringBuilder builder = new StringBuilder(); for (int i = 0; i < times; i++) { builder.append(text); if (i + 1 < times) { builder.append(separator); } } return builder.toString(); } private Strings(); } | Strings { public static String repeat(String text, int times, String separator) { if (isEmpty(text) || times < 0) { return text; } if (times == 0) { return EMPTY; } StringBuilder builder = new StringBuilder(); for (int i = 0; i < times; i++) { builder.append(text); if (i + 1 < times) { builder.append(separator); } } return builder.toString(); } private Strings(); static boolean isStringLiteralSeparator(char character); static boolean isEmpty(CharSequence sequence); static String uncapitalize(String word); static String capitalizeFully(String text, Character delimiter); static String replace(String text, String search,
String replacement); static String removeSuffix(String text, String suffix); static List<String> split(String text, String delimiter); static boolean containsWhitespace(String text); static boolean containsOnlyWhitespace(String text); static boolean containsOnlyDigits(String text); static String repeat(String text, int times, String separator); static String substringAfter(String text, String delimiter); static boolean isListLiteralStart(char character); static boolean isListLiteralEnd(char character); static boolean isListLiteral(String value); } | Strings { public static String repeat(String text, int times, String separator) { if (isEmpty(text) || times < 0) { return text; } if (times == 0) { return EMPTY; } StringBuilder builder = new StringBuilder(); for (int i = 0; i < times; i++) { builder.append(text); if (i + 1 < times) { builder.append(separator); } } return builder.toString(); } private Strings(); static boolean isStringLiteralSeparator(char character); static boolean isEmpty(CharSequence sequence); static String uncapitalize(String word); static String capitalizeFully(String text, Character delimiter); static String replace(String text, String search,
String replacement); static String removeSuffix(String text, String suffix); static List<String> split(String text, String delimiter); static boolean containsWhitespace(String text); static boolean containsOnlyWhitespace(String text); static boolean containsOnlyDigits(String text); static String repeat(String text, int times, String separator); static String substringAfter(String text, String delimiter); static boolean isListLiteralStart(char character); static boolean isListLiteralEnd(char character); static boolean isListLiteral(String value); static final String EMPTY; static final String GAP; static final String LINE_SEPARATOR; static final String LINE_SEPARATOR_LF; static final String LINE_SEPARATOR_CRLF; static final String LINE_SEPARATOR_CR; static final String SLASH; static final String FILE_SEPARATOR; static final String DOT; static final String UNDERSCORE; static final String NOT_AVAILABLE; static final String URL_PROCOTOL_FILE; static final String THIS; static final String HASH; } |
@Test public void testSubstringAfter() { assertEquals("o", Strings.substringAfter("foo", "o")); assertEquals("", Strings.substringAfter("foo", "a")); } | public static String substringAfter(String text, String delimiter) { Checker.checkArgumentsNotNull(text, delimiter); int index = text.indexOf(delimiter); if (index == -1) { return EMPTY; } return text.substring(index + delimiter.length()); } | Strings { public static String substringAfter(String text, String delimiter) { Checker.checkArgumentsNotNull(text, delimiter); int index = text.indexOf(delimiter); if (index == -1) { return EMPTY; } return text.substring(index + delimiter.length()); } } | Strings { public static String substringAfter(String text, String delimiter) { Checker.checkArgumentsNotNull(text, delimiter); int index = text.indexOf(delimiter); if (index == -1) { return EMPTY; } return text.substring(index + delimiter.length()); } private Strings(); } | Strings { public static String substringAfter(String text, String delimiter) { Checker.checkArgumentsNotNull(text, delimiter); int index = text.indexOf(delimiter); if (index == -1) { return EMPTY; } return text.substring(index + delimiter.length()); } private Strings(); static boolean isStringLiteralSeparator(char character); static boolean isEmpty(CharSequence sequence); static String uncapitalize(String word); static String capitalizeFully(String text, Character delimiter); static String replace(String text, String search,
String replacement); static String removeSuffix(String text, String suffix); static List<String> split(String text, String delimiter); static boolean containsWhitespace(String text); static boolean containsOnlyWhitespace(String text); static boolean containsOnlyDigits(String text); static String repeat(String text, int times, String separator); static String substringAfter(String text, String delimiter); static boolean isListLiteralStart(char character); static boolean isListLiteralEnd(char character); static boolean isListLiteral(String value); } | Strings { public static String substringAfter(String text, String delimiter) { Checker.checkArgumentsNotNull(text, delimiter); int index = text.indexOf(delimiter); if (index == -1) { return EMPTY; } return text.substring(index + delimiter.length()); } private Strings(); static boolean isStringLiteralSeparator(char character); static boolean isEmpty(CharSequence sequence); static String uncapitalize(String word); static String capitalizeFully(String text, Character delimiter); static String replace(String text, String search,
String replacement); static String removeSuffix(String text, String suffix); static List<String> split(String text, String delimiter); static boolean containsWhitespace(String text); static boolean containsOnlyWhitespace(String text); static boolean containsOnlyDigits(String text); static String repeat(String text, int times, String separator); static String substringAfter(String text, String delimiter); static boolean isListLiteralStart(char character); static boolean isListLiteralEnd(char character); static boolean isListLiteral(String value); static final String EMPTY; static final String GAP; static final String LINE_SEPARATOR; static final String LINE_SEPARATOR_LF; static final String LINE_SEPARATOR_CRLF; static final String LINE_SEPARATOR_CR; static final String SLASH; static final String FILE_SEPARATOR; static final String DOT; static final String UNDERSCORE; static final String NOT_AVAILABLE; static final String URL_PROCOTOL_FILE; static final String THIS; static final String HASH; } |
@Test public void testContains() { assertTrue(Arrays.contains(new Character[] { 'v', 'o', 'j', 't', 'a' }, 'a')); assertFalse( Arrays.contains(new Character[] { 'j', 'a', 's', 'a' }, null)); assertTrue(Arrays.contains(new Character[] { 'l', null }, null)); } | public static boolean contains(Object[] array, Object object) { if (array == null) { return false; } for (final Object element : array) { if ((object != null && object.equals(element)) || (object == null && element == null)) { return true; } } return false; } | Arrays { public static boolean contains(Object[] array, Object object) { if (array == null) { return false; } for (final Object element : array) { if ((object != null && object.equals(element)) || (object == null && element == null)) { return true; } } return false; } } | Arrays { public static boolean contains(Object[] array, Object object) { if (array == null) { return false; } for (final Object element : array) { if ((object != null && object.equals(element)) || (object == null && element == null)) { return true; } } return false; } } | Arrays { public static boolean contains(Object[] array, Object object) { if (array == null) { return false; } for (final Object element : array) { if ((object != null && object.equals(element)) || (object == null && element == null)) { return true; } } return false; } static boolean contains(Object[] array, Object object); } | Arrays { public static boolean contains(Object[] array, Object object) { if (array == null) { return false; } for (final Object element : array) { if ((object != null && object.equals(element)) || (object == null && element == null)) { return true; } } return false; } static boolean contains(Object[] array, Object object); static final Object[] EMPTY_OBJECT_ARRAY; } |
@Test public void testHelloWorld(){ HelloWorld helloWorld = new HelloWorld(); FlowContext context = new FlowContext(); context.put("name", "John"); try { int result = helloWorld.execute(context); context.get("message"); assertEquals(ActionBlock.NEXT, result); assertEquals("Hello World! John", context.get("message")); } catch (FlowExecutionException e) { e.printStackTrace(); } } | public int execute(FlowContext ctx) throws FlowExecutionException { String name = (String) ctx.get(IN_NAME); String message = "Hello World! "; if (name != null) { message += name; } logger.debug("Message: {}", message); ctx.put(OUT_MESSAGE, message); return NEXT; } | HelloWorld implements ActionBlock { public int execute(FlowContext ctx) throws FlowExecutionException { String name = (String) ctx.get(IN_NAME); String message = "Hello World! "; if (name != null) { message += name; } logger.debug("Message: {}", message); ctx.put(OUT_MESSAGE, message); return NEXT; } } | HelloWorld implements ActionBlock { public int execute(FlowContext ctx) throws FlowExecutionException { String name = (String) ctx.get(IN_NAME); String message = "Hello World! "; if (name != null) { message += name; } logger.debug("Message: {}", message); ctx.put(OUT_MESSAGE, message); return NEXT; } } | HelloWorld implements ActionBlock { public int execute(FlowContext ctx) throws FlowExecutionException { String name = (String) ctx.get(IN_NAME); String message = "Hello World! "; if (name != null) { message += name; } logger.debug("Message: {}", message); ctx.put(OUT_MESSAGE, message); return NEXT; } int execute(FlowContext ctx); } | HelloWorld implements ActionBlock { public int execute(FlowContext ctx) throws FlowExecutionException { String name = (String) ctx.get(IN_NAME); String message = "Hello World! "; if (name != null) { message += name; } logger.debug("Message: {}", message); ctx.put(OUT_MESSAGE, message); return NEXT; } int execute(FlowContext ctx); } |
@Test public void testGetSpeedMph(){ double timeSec = 10.0; int engineHorsePower = 246; int vehicleWeightPounds = 4000; Engine engine = new Engine(); engine.setHorsePower(engineHorsePower); Vehicle vehicle = new Vehicle(vehicleWeightPounds, engine); double speed = vehicle.getSpeedMph(timeSec); assertEquals("Assert vehicle (" + engineHorsePower + " hp, " + vehicleWeightPounds + " lb) speed in " + timeSec + " sec: ", 117, speed, 0.001 * speed); } | protected double getSpeedMph(double timeSec){ double v = 2.0*this.engine.getHorsePower()*746; v = v*timeSec*32.174/this.weightPounds; return Math.round(Math.sqrt(v)*0.68); } | Vehicle { protected double getSpeedMph(double timeSec){ double v = 2.0*this.engine.getHorsePower()*746; v = v*timeSec*32.174/this.weightPounds; return Math.round(Math.sqrt(v)*0.68); } } | Vehicle { protected double getSpeedMph(double timeSec){ double v = 2.0*this.engine.getHorsePower()*746; v = v*timeSec*32.174/this.weightPounds; return Math.round(Math.sqrt(v)*0.68); } Vehicle(int weightPounds, Engine engine); } | Vehicle { protected double getSpeedMph(double timeSec){ double v = 2.0*this.engine.getHorsePower()*746; v = v*timeSec*32.174/this.weightPounds; return Math.round(Math.sqrt(v)*0.68); } Vehicle(int weightPounds, Engine engine); int getWeightPounds(); Engine getEngine(); } | Vehicle { protected double getSpeedMph(double timeSec){ double v = 2.0*this.engine.getHorsePower()*746; v = v*timeSec*32.174/this.weightPounds; return Math.round(Math.sqrt(v)*0.68); } Vehicle(int weightPounds, Engine engine); int getWeightPounds(); Engine getEngine(); } |
@Test public void testCalcSpeed(){ double timeSec = 10.0; TrafficDensity3 trafficDensity = new TrafficDensity3(); Vehicle vehicle = Mockito.mock(Vehicle.class); Mockito.when(vehicle.getSpeedMph(timeSec)).thenReturn(100d); double traction = 0.2; double speed = trafficDensity.calcSpeed(vehicle, traction, timeSec); assertEquals("Assert speed (traction=" + traction + ") in " + timeSec + " sec: ", 20, speed, 0.001 * speed); } | protected double calcSpeed(Vehicle vehicle, double traction, double timeSec){ double speed = vehicle.getSpeedMph(timeSec); return Math.round(speed * traction); } | TrafficDensity3 { protected double calcSpeed(Vehicle vehicle, double traction, double timeSec){ double speed = vehicle.getSpeedMph(timeSec); return Math.round(speed * traction); } } | TrafficDensity3 { protected double calcSpeed(Vehicle vehicle, double traction, double timeSec){ double speed = vehicle.getSpeedMph(timeSec); return Math.round(speed * traction); } } | TrafficDensity3 { protected double calcSpeed(Vehicle vehicle, double traction, double timeSec){ double speed = vehicle.getSpeedMph(timeSec); return Math.round(speed * traction); } Integer[] trafficByLane(Stream<TrafficUnit> stream, int trafficUnitsNumber, double timeSec,
SpeedModel speedModel, double[] speedLimitByLane); } | TrafficDensity3 { protected double calcSpeed(Vehicle vehicle, double traction, double timeSec){ double speed = vehicle.getSpeedMph(timeSec); return Math.round(speed * traction); } Integer[] trafficByLane(Stream<TrafficUnit> stream, int trafficUnitsNumber, double timeSec,
SpeedModel speedModel, double[] speedLimitByLane); } |
@Test public void testCalcLaneNumber() { double[] speeds = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; double[] speedLimitByLane = {4.5, 8.5, 12.5}; int[] expectedLaneNumber = {1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3}; TrafficDensityTestCalcLaneNumber trafficDensity = new TrafficDensityTestCalcLaneNumber(); for(int i = 0; i < speeds.length; i++){ int ln = trafficDensity.calcLaneNumber(speedLimitByLane.length, speedLimitByLane, speeds[i]); assertEquals("Assert lane number of speed " + speeds + " with speed limit " + Arrays.stream(speedLimitByLane).mapToObj(Double::toString).collect(Collectors.joining(", ")), expectedLaneNumber[i], ln); } } | protected int calcLaneNumber(int lanesCount, double[] speedLimitByLane, double speed){ for(int i = 1; i <= lanesCount; i++){ if(speed <= speedLimitByLane[i - 1]){ return i; } } return lanesCount; } | TrafficDensity3 { protected int calcLaneNumber(int lanesCount, double[] speedLimitByLane, double speed){ for(int i = 1; i <= lanesCount; i++){ if(speed <= speedLimitByLane[i - 1]){ return i; } } return lanesCount; } } | TrafficDensity3 { protected int calcLaneNumber(int lanesCount, double[] speedLimitByLane, double speed){ for(int i = 1; i <= lanesCount; i++){ if(speed <= speedLimitByLane[i - 1]){ return i; } } return lanesCount; } } | TrafficDensity3 { protected int calcLaneNumber(int lanesCount, double[] speedLimitByLane, double speed){ for(int i = 1; i <= lanesCount; i++){ if(speed <= speedLimitByLane[i - 1]){ return i; } } return lanesCount; } Integer[] trafficByLane(Stream<TrafficUnit> stream, int trafficUnitsNumber, double timeSec,
SpeedModel speedModel, double[] speedLimitByLane); } | TrafficDensity3 { protected int calcLaneNumber(int lanesCount, double[] speedLimitByLane, double speed){ for(int i = 1; i <= lanesCount; i++){ if(speed <= speedLimitByLane[i - 1]){ return i; } } return lanesCount; } Integer[] trafficByLane(Stream<TrafficUnit> stream, int trafficUnitsNumber, double timeSec,
SpeedModel speedModel, double[] speedLimitByLane); } |
@Test public void testCalcLaneNumber2() { int[] count ={0}; double[] speeds = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; Integer[] expectedCountByLane = {4, 4, 4}; TrafficDensity3 trafficDensity = new TrafficDensity3(){ @Override protected double calcSpeed(Vehicle vehicle, double traction, double timeSec) { return speeds[count[0]++]; } }; double timeSec = 10.0; int trafficUnitsNumber = speeds.length; double[] speedLimitByLane = {4.5, 8.5, 12.5}; Integer[] trafficByLane = trafficDensity.trafficByLane(getTrafficUnitStream(trafficUnitsNumber), trafficUnitsNumber, timeSec, FactorySpeedModel.getSpeedModel(), speedLimitByLane ); assertArrayEquals("Assert count of " + speeds.length + " vehicles by " + speedLimitByLane.length + " lanes with speed limit " + Arrays.stream(speedLimitByLane).mapToObj(Double::toString).collect(Collectors.joining(", ")), expectedCountByLane, trafficByLane); } | public Integer[] trafficByLane(Stream<TrafficUnit> stream, int trafficUnitsNumber, double timeSec, SpeedModel speedModel, double[] speedLimitByLane) { int lanesCount = speedLimitByLane.length; Map<Integer, Integer> trafficByLane = new HashMap<>(); for(int i = 1; i <= lanesCount; i++){ trafficByLane.put(i, 0); } stream.limit(trafficUnitsNumber) .map(TrafficUnitWrapper::new) .map(tuw -> tuw.setSpeedModel(speedModel)) .map(tuw -> calcSpeed(tuw.getVehicle(), tuw.getTraction(), timeSec)) .forEach(speed -> trafficByLane.computeIfPresent(calcLaneNumber(lanesCount, speedLimitByLane, speed), (k, v) -> ++v)); return trafficByLane.values().toArray(new Integer[lanesCount]); } | TrafficDensity3 { public Integer[] trafficByLane(Stream<TrafficUnit> stream, int trafficUnitsNumber, double timeSec, SpeedModel speedModel, double[] speedLimitByLane) { int lanesCount = speedLimitByLane.length; Map<Integer, Integer> trafficByLane = new HashMap<>(); for(int i = 1; i <= lanesCount; i++){ trafficByLane.put(i, 0); } stream.limit(trafficUnitsNumber) .map(TrafficUnitWrapper::new) .map(tuw -> tuw.setSpeedModel(speedModel)) .map(tuw -> calcSpeed(tuw.getVehicle(), tuw.getTraction(), timeSec)) .forEach(speed -> trafficByLane.computeIfPresent(calcLaneNumber(lanesCount, speedLimitByLane, speed), (k, v) -> ++v)); return trafficByLane.values().toArray(new Integer[lanesCount]); } } | TrafficDensity3 { public Integer[] trafficByLane(Stream<TrafficUnit> stream, int trafficUnitsNumber, double timeSec, SpeedModel speedModel, double[] speedLimitByLane) { int lanesCount = speedLimitByLane.length; Map<Integer, Integer> trafficByLane = new HashMap<>(); for(int i = 1; i <= lanesCount; i++){ trafficByLane.put(i, 0); } stream.limit(trafficUnitsNumber) .map(TrafficUnitWrapper::new) .map(tuw -> tuw.setSpeedModel(speedModel)) .map(tuw -> calcSpeed(tuw.getVehicle(), tuw.getTraction(), timeSec)) .forEach(speed -> trafficByLane.computeIfPresent(calcLaneNumber(lanesCount, speedLimitByLane, speed), (k, v) -> ++v)); return trafficByLane.values().toArray(new Integer[lanesCount]); } } | TrafficDensity3 { public Integer[] trafficByLane(Stream<TrafficUnit> stream, int trafficUnitsNumber, double timeSec, SpeedModel speedModel, double[] speedLimitByLane) { int lanesCount = speedLimitByLane.length; Map<Integer, Integer> trafficByLane = new HashMap<>(); for(int i = 1; i <= lanesCount; i++){ trafficByLane.put(i, 0); } stream.limit(trafficUnitsNumber) .map(TrafficUnitWrapper::new) .map(tuw -> tuw.setSpeedModel(speedModel)) .map(tuw -> calcSpeed(tuw.getVehicle(), tuw.getTraction(), timeSec)) .forEach(speed -> trafficByLane.computeIfPresent(calcLaneNumber(lanesCount, speedLimitByLane, speed), (k, v) -> ++v)); return trafficByLane.values().toArray(new Integer[lanesCount]); } Integer[] trafficByLane(Stream<TrafficUnit> stream, int trafficUnitsNumber, double timeSec,
SpeedModel speedModel, double[] speedLimitByLane); } | TrafficDensity3 { public Integer[] trafficByLane(Stream<TrafficUnit> stream, int trafficUnitsNumber, double timeSec, SpeedModel speedModel, double[] speedLimitByLane) { int lanesCount = speedLimitByLane.length; Map<Integer, Integer> trafficByLane = new HashMap<>(); for(int i = 1; i <= lanesCount; i++){ trafficByLane.put(i, 0); } stream.limit(trafficUnitsNumber) .map(TrafficUnitWrapper::new) .map(tuw -> tuw.setSpeedModel(speedModel)) .map(tuw -> calcSpeed(tuw.getVehicle(), tuw.getTraction(), timeSec)) .forEach(speed -> trafficByLane.computeIfPresent(calcLaneNumber(lanesCount, speedLimitByLane, speed), (k, v) -> ++v)); return trafficByLane.values().toArray(new Integer[lanesCount]); } Integer[] trafficByLane(Stream<TrafficUnit> stream, int trafficUnitsNumber, double timeSec,
SpeedModel speedModel, double[] speedLimitByLane); } |
@Test public void testCalcSpeed(){ double timeSec = 10.0; TrafficDensity2 trafficDensity = new TrafficDensity2(); Vehicle vehicle = Mockito.mock(Vehicle.class); Mockito.when(vehicle.getSpeedMph(timeSec)).thenReturn(100d); double traction = 0.2; double speed = trafficDensity.calcSpeed(vehicle, traction, timeSec); assertEquals("Assert speed (traction=" + traction + ") in " + timeSec + " sec: ", 20, speed, 0.001 * speed); } | protected double calcSpeed(Vehicle vehicle, double traction, double timeSec){ double speed = vehicle.getSpeedMph(timeSec); return Math.round(speed * traction); } | TrafficDensity2 { protected double calcSpeed(Vehicle vehicle, double traction, double timeSec){ double speed = vehicle.getSpeedMph(timeSec); return Math.round(speed * traction); } } | TrafficDensity2 { protected double calcSpeed(Vehicle vehicle, double traction, double timeSec){ double speed = vehicle.getSpeedMph(timeSec); return Math.round(speed * traction); } } | TrafficDensity2 { protected double calcSpeed(Vehicle vehicle, double traction, double timeSec){ double speed = vehicle.getSpeedMph(timeSec); return Math.round(speed * traction); } Integer[] trafficByLane(Stream<TrafficUnit> stream, int trafficUnitsNumber, double timeSec,
SpeedModel speedModel, double[] speedLimitByLane); } | TrafficDensity2 { protected double calcSpeed(Vehicle vehicle, double traction, double timeSec){ double speed = vehicle.getSpeedMph(timeSec); return Math.round(speed * traction); } Integer[] trafficByLane(Stream<TrafficUnit> stream, int trafficUnitsNumber, double timeSec,
SpeedModel speedModel, double[] speedLimitByLane); } |
@Test public void testCountByLane() { int[] count ={0}; double[] speeds = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; TrafficDensity2 trafficDensity = new TrafficDensity2(){ @Override protected double calcSpeed(Vehicle vehicle, double traction, double timeSec) { return speeds[count[0]++]; } }; double timeSec = 10.0; int trafficUnitsNumber = speeds.length; double[] speedLimitByLane = {4.5, 8.5, 12.5}; Integer[] expectedCountByLane = {4, 4, 4}; Integer[] trafficByLane = trafficDensity.trafficByLane(getTrafficUnitStream(trafficUnitsNumber), trafficUnitsNumber, timeSec, FactorySpeedModel.getSpeedModel(), speedLimitByLane ); assertArrayEquals("Assert count of " + speeds.length + " vehicles by " + speedLimitByLane.length + " lanes with speed limit " + Arrays.stream(speedLimitByLane).mapToObj(Double::toString).collect(Collectors.joining(", ")), expectedCountByLane, trafficByLane); } | private CountByLane countByLane(int lanesNumber, double[] speedLimit, double speed){ for(int i = 1; i <= lanesNumber; i++){ if(speed <= speedLimit[i - 1]){ return new CountByLane(1, i); } } return new CountByLane(1, lanesNumber); } | TrafficDensity2 { private CountByLane countByLane(int lanesNumber, double[] speedLimit, double speed){ for(int i = 1; i <= lanesNumber; i++){ if(speed <= speedLimit[i - 1]){ return new CountByLane(1, i); } } return new CountByLane(1, lanesNumber); } } | TrafficDensity2 { private CountByLane countByLane(int lanesNumber, double[] speedLimit, double speed){ for(int i = 1; i <= lanesNumber; i++){ if(speed <= speedLimit[i - 1]){ return new CountByLane(1, i); } } return new CountByLane(1, lanesNumber); } } | TrafficDensity2 { private CountByLane countByLane(int lanesNumber, double[] speedLimit, double speed){ for(int i = 1; i <= lanesNumber; i++){ if(speed <= speedLimit[i - 1]){ return new CountByLane(1, i); } } return new CountByLane(1, lanesNumber); } Integer[] trafficByLane(Stream<TrafficUnit> stream, int trafficUnitsNumber, double timeSec,
SpeedModel speedModel, double[] speedLimitByLane); } | TrafficDensity2 { private CountByLane countByLane(int lanesNumber, double[] speedLimit, double speed){ for(int i = 1; i <= lanesNumber; i++){ if(speed <= speedLimit[i - 1]){ return new CountByLane(1, i); } } return new CountByLane(1, lanesNumber); } Integer[] trafficByLane(Stream<TrafficUnit> stream, int trafficUnitsNumber, double timeSec,
SpeedModel speedModel, double[] speedLimitByLane); } |
@Test public void testTrafficByLane() { TrafficDensity1 trafficDensity = new TrafficDensity1(); double timeSec = 10.0; int trafficUnitsNumber = 120; double[] speedLimitByLane = {30, 50, 65}; Integer[] expectedCountByLane = {30, 30, 60}; Integer[] trafficByLane = trafficDensity.trafficByLane(getTrafficUnitStream2(trafficUnitsNumber), trafficUnitsNumber, timeSec, FactorySpeedModel.getSpeedModel(), speedLimitByLane ); assertArrayEquals("Assert count of " + trafficUnitsNumber + " vehicles by " + speedLimitByLane.length + " lanes with speed limit " + Arrays.stream(speedLimitByLane).mapToObj(Double::toString).collect(Collectors.joining(", ")), expectedCountByLane, trafficByLane); } | public Integer[] trafficByLane(Stream<TrafficUnit> stream, int trafficUnitsNumber, double timeSec, SpeedModel speedModel, double[] speedLimitByLane) { int lanesCount = speedLimitByLane.length; Map<Integer, Integer> trafficByLane = stream .limit(trafficUnitsNumber) .map(TrafficUnitWrapper::new) .map(tuw -> tuw.setSpeedModel(speedModel)) .map(tuw -> tuw.calcSpeed(timeSec)) .map(speed -> countByLane(lanesCount, speedLimitByLane, speed)) .collect(Collectors.groupingBy(CountByLane::getLane, Collectors.summingInt(CountByLane::getCount))); for(int i = 1; i <= lanesCount; i++){ trafficByLane.putIfAbsent(i, 0); } return trafficByLane.values().toArray(new Integer[lanesCount]); } | TrafficDensity1 { public Integer[] trafficByLane(Stream<TrafficUnit> stream, int trafficUnitsNumber, double timeSec, SpeedModel speedModel, double[] speedLimitByLane) { int lanesCount = speedLimitByLane.length; Map<Integer, Integer> trafficByLane = stream .limit(trafficUnitsNumber) .map(TrafficUnitWrapper::new) .map(tuw -> tuw.setSpeedModel(speedModel)) .map(tuw -> tuw.calcSpeed(timeSec)) .map(speed -> countByLane(lanesCount, speedLimitByLane, speed)) .collect(Collectors.groupingBy(CountByLane::getLane, Collectors.summingInt(CountByLane::getCount))); for(int i = 1; i <= lanesCount; i++){ trafficByLane.putIfAbsent(i, 0); } return trafficByLane.values().toArray(new Integer[lanesCount]); } } | TrafficDensity1 { public Integer[] trafficByLane(Stream<TrafficUnit> stream, int trafficUnitsNumber, double timeSec, SpeedModel speedModel, double[] speedLimitByLane) { int lanesCount = speedLimitByLane.length; Map<Integer, Integer> trafficByLane = stream .limit(trafficUnitsNumber) .map(TrafficUnitWrapper::new) .map(tuw -> tuw.setSpeedModel(speedModel)) .map(tuw -> tuw.calcSpeed(timeSec)) .map(speed -> countByLane(lanesCount, speedLimitByLane, speed)) .collect(Collectors.groupingBy(CountByLane::getLane, Collectors.summingInt(CountByLane::getCount))); for(int i = 1; i <= lanesCount; i++){ trafficByLane.putIfAbsent(i, 0); } return trafficByLane.values().toArray(new Integer[lanesCount]); } } | TrafficDensity1 { public Integer[] trafficByLane(Stream<TrafficUnit> stream, int trafficUnitsNumber, double timeSec, SpeedModel speedModel, double[] speedLimitByLane) { int lanesCount = speedLimitByLane.length; Map<Integer, Integer> trafficByLane = stream .limit(trafficUnitsNumber) .map(TrafficUnitWrapper::new) .map(tuw -> tuw.setSpeedModel(speedModel)) .map(tuw -> tuw.calcSpeed(timeSec)) .map(speed -> countByLane(lanesCount, speedLimitByLane, speed)) .collect(Collectors.groupingBy(CountByLane::getLane, Collectors.summingInt(CountByLane::getCount))); for(int i = 1; i <= lanesCount; i++){ trafficByLane.putIfAbsent(i, 0); } return trafficByLane.values().toArray(new Integer[lanesCount]); } Integer[] trafficByLane(Stream<TrafficUnit> stream, int trafficUnitsNumber, double timeSec,
SpeedModel speedModel, double[] speedLimitByLane); } | TrafficDensity1 { public Integer[] trafficByLane(Stream<TrafficUnit> stream, int trafficUnitsNumber, double timeSec, SpeedModel speedModel, double[] speedLimitByLane) { int lanesCount = speedLimitByLane.length; Map<Integer, Integer> trafficByLane = stream .limit(trafficUnitsNumber) .map(TrafficUnitWrapper::new) .map(tuw -> tuw.setSpeedModel(speedModel)) .map(tuw -> tuw.calcSpeed(timeSec)) .map(speed -> countByLane(lanesCount, speedLimitByLane, speed)) .collect(Collectors.groupingBy(CountByLane::getLane, Collectors.summingInt(CountByLane::getCount))); for(int i = 1; i <= lanesCount; i++){ trafficByLane.putIfAbsent(i, 0); } return trafficByLane.values().toArray(new Integer[lanesCount]); } Integer[] trafficByLane(Stream<TrafficUnit> stream, int trafficUnitsNumber, double timeSec,
SpeedModel speedModel, double[] speedLimitByLane); } |
@Test @Disabled public void testBytesPerf() { long t0 = System.currentTimeMillis(); for ( int j = 0; j < 1000; j++ ) { Asn1Buffer buffer = new Asn1Buffer(); for ( int i = 0; i < 409600; i++ ) { buffer.put( new byte[] { 0x01, ( byte ) i } ); } } long t1 = System.currentTimeMillis(); System.out.println( "Delta: " + ( t1 - t0 ) ); } | public void put( byte b ) { if ( pos == buffer.length ) { extend( 1 ); } pos++; buffer[buffer.length - pos] = b; } | Asn1Buffer { public void put( byte b ) { if ( pos == buffer.length ) { extend( 1 ); } pos++; buffer[buffer.length - pos] = b; } } | Asn1Buffer { public void put( byte b ) { if ( pos == buffer.length ) { extend( 1 ); } pos++; buffer[buffer.length - pos] = b; } Asn1Buffer(); } | Asn1Buffer { public void put( byte b ) { if ( pos == buffer.length ) { extend( 1 ); } pos++; buffer[buffer.length - pos] = b; } Asn1Buffer(); int getPos(); void setPos( int pos ); void put( byte b ); void put( byte[] bytes ); ByteBuffer getBytes(); int getSize(); void clear(); @Override String toString(); } | Asn1Buffer { public void put( byte b ) { if ( pos == buffer.length ) { extend( 1 ); } pos++; buffer[buffer.length - pos] = b; } Asn1Buffer(); int getPos(); void setPos( int pos ); void put( byte b ); void put( byte[] bytes ); ByteBuffer getBytes(); int getSize(); void clear(); @Override String toString(); } |
@Test public void testNotEqualDiffValue() throws Exception { assertFalse( maxValueCountItemA.equals( maxValueCountItemC ) ); assertFalse( maxValueCountItemC.equals( maxValueCountItemA ) ); assertFalse( maxValueCountItemA.equals( maxValueCountItemD ) ); assertFalse( maxValueCountItemD.equals( maxValueCountItemA ) ); } | @Override public boolean equals( Object o ) { if ( this == o ) { return true; } if ( o instanceof MaxValueCountItem ) { MaxValueCountItem that = ( MaxValueCountItem ) o; return items.equals( that.items ); } return false; } | MaxValueCountItem extends ProtectedItem { @Override public boolean equals( Object o ) { if ( this == o ) { return true; } if ( o instanceof MaxValueCountItem ) { MaxValueCountItem that = ( MaxValueCountItem ) o; return items.equals( that.items ); } return false; } } | MaxValueCountItem extends ProtectedItem { @Override public boolean equals( Object o ) { if ( this == o ) { return true; } if ( o instanceof MaxValueCountItem ) { MaxValueCountItem that = ( MaxValueCountItem ) o; return items.equals( that.items ); } return false; } MaxValueCountItem( Set<MaxValueCountElem> items ); } | MaxValueCountItem extends ProtectedItem { @Override public boolean equals( Object o ) { if ( this == o ) { return true; } if ( o instanceof MaxValueCountItem ) { MaxValueCountItem that = ( MaxValueCountItem ) o; return items.equals( that.items ); } return false; } MaxValueCountItem( Set<MaxValueCountElem> items ); Iterator<MaxValueCountElem> iterator(); @Override int hashCode(); @Override boolean equals( Object o ); @Override String toString(); } | MaxValueCountItem extends ProtectedItem { @Override public boolean equals( Object o ) { if ( this == o ) { return true; } if ( o instanceof MaxValueCountItem ) { MaxValueCountItem that = ( MaxValueCountItem ) o; return items.equals( that.items ); } return false; } MaxValueCountItem( Set<MaxValueCountElem> items ); Iterator<MaxValueCountElem> iterator(); @Override int hashCode(); @Override boolean equals( Object o ); @Override String toString(); } |
@Test public void testEqualsNotInstanceOf() throws Exception { assertFalse( restrictedByItemA.equals( UndefinedNode.UNDEFINED_NODE ) ); } | @Override public boolean equals( Object o ) { if ( this == o ) { return true; } if ( o instanceof RestrictedByItem ) { RestrictedByItem that = ( RestrictedByItem ) o; if ( items != null ) { if ( that.items == null ) { return false; } if ( items.size() != that.items.size() ) { return false; } for ( RestrictedByElem item : items ) { if ( !that.items.contains( item ) ) { return false; } } return true; } else { return that.items == null; } } return false; } | RestrictedByItem extends ProtectedItem { @Override public boolean equals( Object o ) { if ( this == o ) { return true; } if ( o instanceof RestrictedByItem ) { RestrictedByItem that = ( RestrictedByItem ) o; if ( items != null ) { if ( that.items == null ) { return false; } if ( items.size() != that.items.size() ) { return false; } for ( RestrictedByElem item : items ) { if ( !that.items.contains( item ) ) { return false; } } return true; } else { return that.items == null; } } return false; } } | RestrictedByItem extends ProtectedItem { @Override public boolean equals( Object o ) { if ( this == o ) { return true; } if ( o instanceof RestrictedByItem ) { RestrictedByItem that = ( RestrictedByItem ) o; if ( items != null ) { if ( that.items == null ) { return false; } if ( items.size() != that.items.size() ) { return false; } for ( RestrictedByElem item : items ) { if ( !that.items.contains( item ) ) { return false; } } return true; } else { return that.items == null; } } return false; } RestrictedByItem( Set<RestrictedByElem> items ); } | RestrictedByItem extends ProtectedItem { @Override public boolean equals( Object o ) { if ( this == o ) { return true; } if ( o instanceof RestrictedByItem ) { RestrictedByItem that = ( RestrictedByItem ) o; if ( items != null ) { if ( that.items == null ) { return false; } if ( items.size() != that.items.size() ) { return false; } for ( RestrictedByElem item : items ) { if ( !that.items.contains( item ) ) { return false; } } return true; } else { return that.items == null; } } return false; } RestrictedByItem( Set<RestrictedByElem> items ); Iterator<RestrictedByElem> iterator(); @Override int hashCode(); @Override boolean equals( Object o ); @Override String toString(); } | RestrictedByItem extends ProtectedItem { @Override public boolean equals( Object o ) { if ( this == o ) { return true; } if ( o instanceof RestrictedByItem ) { RestrictedByItem that = ( RestrictedByItem ) o; if ( items != null ) { if ( that.items == null ) { return false; } if ( items.size() != that.items.size() ) { return false; } for ( RestrictedByElem item : items ) { if ( !that.items.contains( item ) ) { return false; } } return true; } else { return that.items == null; } } return false; } RestrictedByItem( Set<RestrictedByElem> items ); Iterator<RestrictedByElem> iterator(); @Override int hashCode(); @Override boolean equals( Object o ); @Override String toString(); } |
@Test public void testEqualsNull() throws Exception { assertFalse( restrictedByItemA.equals( null ) ); } | @Override public boolean equals( Object o ) { if ( this == o ) { return true; } if ( o instanceof RestrictedByItem ) { RestrictedByItem that = ( RestrictedByItem ) o; if ( items != null ) { if ( that.items == null ) { return false; } if ( items.size() != that.items.size() ) { return false; } for ( RestrictedByElem item : items ) { if ( !that.items.contains( item ) ) { return false; } } return true; } else { return that.items == null; } } return false; } | RestrictedByItem extends ProtectedItem { @Override public boolean equals( Object o ) { if ( this == o ) { return true; } if ( o instanceof RestrictedByItem ) { RestrictedByItem that = ( RestrictedByItem ) o; if ( items != null ) { if ( that.items == null ) { return false; } if ( items.size() != that.items.size() ) { return false; } for ( RestrictedByElem item : items ) { if ( !that.items.contains( item ) ) { return false; } } return true; } else { return that.items == null; } } return false; } } | RestrictedByItem extends ProtectedItem { @Override public boolean equals( Object o ) { if ( this == o ) { return true; } if ( o instanceof RestrictedByItem ) { RestrictedByItem that = ( RestrictedByItem ) o; if ( items != null ) { if ( that.items == null ) { return false; } if ( items.size() != that.items.size() ) { return false; } for ( RestrictedByElem item : items ) { if ( !that.items.contains( item ) ) { return false; } } return true; } else { return that.items == null; } } return false; } RestrictedByItem( Set<RestrictedByElem> items ); } | RestrictedByItem extends ProtectedItem { @Override public boolean equals( Object o ) { if ( this == o ) { return true; } if ( o instanceof RestrictedByItem ) { RestrictedByItem that = ( RestrictedByItem ) o; if ( items != null ) { if ( that.items == null ) { return false; } if ( items.size() != that.items.size() ) { return false; } for ( RestrictedByElem item : items ) { if ( !that.items.contains( item ) ) { return false; } } return true; } else { return that.items == null; } } return false; } RestrictedByItem( Set<RestrictedByElem> items ); Iterator<RestrictedByElem> iterator(); @Override int hashCode(); @Override boolean equals( Object o ); @Override String toString(); } | RestrictedByItem extends ProtectedItem { @Override public boolean equals( Object o ) { if ( this == o ) { return true; } if ( o instanceof RestrictedByItem ) { RestrictedByItem that = ( RestrictedByItem ) o; if ( items != null ) { if ( that.items == null ) { return false; } if ( items.size() != that.items.size() ) { return false; } for ( RestrictedByElem item : items ) { if ( !that.items.contains( item ) ) { return false; } } return true; } else { return that.items == null; } } return false; } RestrictedByItem( Set<RestrictedByElem> items ); Iterator<RestrictedByElem> iterator(); @Override int hashCode(); @Override boolean equals( Object o ); @Override String toString(); } |
@Test public void testHashCodeReflexive() throws Exception { assertEquals( restrictedByItemA.hashCode(), restrictedByItemA.hashCode() ); } | @Override public int hashCode() { int hash = 37; if ( items != null ) { for ( RestrictedByElem item : items ) { if ( item != null ) { hash = hash * item.hashCode(); } else { hash = hash * 37; } } } return hash; } | RestrictedByItem extends ProtectedItem { @Override public int hashCode() { int hash = 37; if ( items != null ) { for ( RestrictedByElem item : items ) { if ( item != null ) { hash = hash * item.hashCode(); } else { hash = hash * 37; } } } return hash; } } | RestrictedByItem extends ProtectedItem { @Override public int hashCode() { int hash = 37; if ( items != null ) { for ( RestrictedByElem item : items ) { if ( item != null ) { hash = hash * item.hashCode(); } else { hash = hash * 37; } } } return hash; } RestrictedByItem( Set<RestrictedByElem> items ); } | RestrictedByItem extends ProtectedItem { @Override public int hashCode() { int hash = 37; if ( items != null ) { for ( RestrictedByElem item : items ) { if ( item != null ) { hash = hash * item.hashCode(); } else { hash = hash * 37; } } } return hash; } RestrictedByItem( Set<RestrictedByElem> items ); Iterator<RestrictedByElem> iterator(); @Override int hashCode(); @Override boolean equals( Object o ); @Override String toString(); } | RestrictedByItem extends ProtectedItem { @Override public int hashCode() { int hash = 37; if ( items != null ) { for ( RestrictedByElem item : items ) { if ( item != null ) { hash = hash * item.hashCode(); } else { hash = hash * 37; } } } return hash; } RestrictedByItem( Set<RestrictedByElem> items ); Iterator<RestrictedByElem> iterator(); @Override int hashCode(); @Override boolean equals( Object o ); @Override String toString(); } |
@Test public void testHashCodeSymmetric() throws Exception { assertEquals( restrictedByItemA.hashCode(), restrictedByItemACopy.hashCode() ); assertEquals( restrictedByItemACopy.hashCode(), restrictedByItemA.hashCode() ); } | @Override public int hashCode() { int hash = 37; if ( items != null ) { for ( RestrictedByElem item : items ) { if ( item != null ) { hash = hash * item.hashCode(); } else { hash = hash * 37; } } } return hash; } | RestrictedByItem extends ProtectedItem { @Override public int hashCode() { int hash = 37; if ( items != null ) { for ( RestrictedByElem item : items ) { if ( item != null ) { hash = hash * item.hashCode(); } else { hash = hash * 37; } } } return hash; } } | RestrictedByItem extends ProtectedItem { @Override public int hashCode() { int hash = 37; if ( items != null ) { for ( RestrictedByElem item : items ) { if ( item != null ) { hash = hash * item.hashCode(); } else { hash = hash * 37; } } } return hash; } RestrictedByItem( Set<RestrictedByElem> items ); } | RestrictedByItem extends ProtectedItem { @Override public int hashCode() { int hash = 37; if ( items != null ) { for ( RestrictedByElem item : items ) { if ( item != null ) { hash = hash * item.hashCode(); } else { hash = hash * 37; } } } return hash; } RestrictedByItem( Set<RestrictedByElem> items ); Iterator<RestrictedByElem> iterator(); @Override int hashCode(); @Override boolean equals( Object o ); @Override String toString(); } | RestrictedByItem extends ProtectedItem { @Override public int hashCode() { int hash = 37; if ( items != null ) { for ( RestrictedByElem item : items ) { if ( item != null ) { hash = hash * item.hashCode(); } else { hash = hash * 37; } } } return hash; } RestrictedByItem( Set<RestrictedByElem> items ); Iterator<RestrictedByElem> iterator(); @Override int hashCode(); @Override boolean equals( Object o ); @Override String toString(); } |
@Test public void testHashCodeTransitive() throws Exception { assertEquals( restrictedByItemA.hashCode(), restrictedByItemACopy.hashCode() ); assertEquals( restrictedByItemACopy.hashCode(), restrictedByItemB.hashCode() ); assertEquals( restrictedByItemA.hashCode(), restrictedByItemB.hashCode() ); } | @Override public int hashCode() { int hash = 37; if ( items != null ) { for ( RestrictedByElem item : items ) { if ( item != null ) { hash = hash * item.hashCode(); } else { hash = hash * 37; } } } return hash; } | RestrictedByItem extends ProtectedItem { @Override public int hashCode() { int hash = 37; if ( items != null ) { for ( RestrictedByElem item : items ) { if ( item != null ) { hash = hash * item.hashCode(); } else { hash = hash * 37; } } } return hash; } } | RestrictedByItem extends ProtectedItem { @Override public int hashCode() { int hash = 37; if ( items != null ) { for ( RestrictedByElem item : items ) { if ( item != null ) { hash = hash * item.hashCode(); } else { hash = hash * 37; } } } return hash; } RestrictedByItem( Set<RestrictedByElem> items ); } | RestrictedByItem extends ProtectedItem { @Override public int hashCode() { int hash = 37; if ( items != null ) { for ( RestrictedByElem item : items ) { if ( item != null ) { hash = hash * item.hashCode(); } else { hash = hash * 37; } } } return hash; } RestrictedByItem( Set<RestrictedByElem> items ); Iterator<RestrictedByElem> iterator(); @Override int hashCode(); @Override boolean equals( Object o ); @Override String toString(); } | RestrictedByItem extends ProtectedItem { @Override public int hashCode() { int hash = 37; if ( items != null ) { for ( RestrictedByElem item : items ) { if ( item != null ) { hash = hash * item.hashCode(); } else { hash = hash * 37; } } } return hash; } RestrictedByItem( Set<RestrictedByElem> items ); Iterator<RestrictedByElem> iterator(); @Override int hashCode(); @Override boolean equals( Object o ); @Override String toString(); } |
@Test public void testNotEqualDiffValue() throws Exception { assertFalse( restrictedByItemA.equals( restrictedByItemC ) ); assertFalse( restrictedByItemC.equals( restrictedByItemA ) ); assertFalse( restrictedByItemA.equals( restrictedByItemD ) ); assertFalse( restrictedByItemD.equals( restrictedByItemA ) ); } | @Override public boolean equals( Object o ) { if ( this == o ) { return true; } if ( o instanceof RestrictedByItem ) { RestrictedByItem that = ( RestrictedByItem ) o; if ( items != null ) { if ( that.items == null ) { return false; } if ( items.size() != that.items.size() ) { return false; } for ( RestrictedByElem item : items ) { if ( !that.items.contains( item ) ) { return false; } } return true; } else { return that.items == null; } } return false; } | RestrictedByItem extends ProtectedItem { @Override public boolean equals( Object o ) { if ( this == o ) { return true; } if ( o instanceof RestrictedByItem ) { RestrictedByItem that = ( RestrictedByItem ) o; if ( items != null ) { if ( that.items == null ) { return false; } if ( items.size() != that.items.size() ) { return false; } for ( RestrictedByElem item : items ) { if ( !that.items.contains( item ) ) { return false; } } return true; } else { return that.items == null; } } return false; } } | RestrictedByItem extends ProtectedItem { @Override public boolean equals( Object o ) { if ( this == o ) { return true; } if ( o instanceof RestrictedByItem ) { RestrictedByItem that = ( RestrictedByItem ) o; if ( items != null ) { if ( that.items == null ) { return false; } if ( items.size() != that.items.size() ) { return false; } for ( RestrictedByElem item : items ) { if ( !that.items.contains( item ) ) { return false; } } return true; } else { return that.items == null; } } return false; } RestrictedByItem( Set<RestrictedByElem> items ); } | RestrictedByItem extends ProtectedItem { @Override public boolean equals( Object o ) { if ( this == o ) { return true; } if ( o instanceof RestrictedByItem ) { RestrictedByItem that = ( RestrictedByItem ) o; if ( items != null ) { if ( that.items == null ) { return false; } if ( items.size() != that.items.size() ) { return false; } for ( RestrictedByElem item : items ) { if ( !that.items.contains( item ) ) { return false; } } return true; } else { return that.items == null; } } return false; } RestrictedByItem( Set<RestrictedByElem> items ); Iterator<RestrictedByElem> iterator(); @Override int hashCode(); @Override boolean equals( Object o ); @Override String toString(); } | RestrictedByItem extends ProtectedItem { @Override public boolean equals( Object o ) { if ( this == o ) { return true; } if ( o instanceof RestrictedByItem ) { RestrictedByItem that = ( RestrictedByItem ) o; if ( items != null ) { if ( that.items == null ) { return false; } if ( items.size() != that.items.size() ) { return false; } for ( RestrictedByElem item : items ) { if ( !that.items.contains( item ) ) { return false; } } return true; } else { return that.items == null; } } return false; } RestrictedByItem( Set<RestrictedByElem> items ); Iterator<RestrictedByElem> iterator(); @Override int hashCode(); @Override boolean equals( Object o ); @Override String toString(); } |
@Test public void testEqualsNotInstanceOf() throws Exception { assertFalse( attributeValueItemA.equals( UndefinedNode.UNDEFINED_NODE ) ); } | @Override public boolean equals( Object o ) { if ( this == o ) { return true; } if ( o instanceof AttributeValueItem ) { AttributeValueItem that = ( AttributeValueItem ) o; if ( attributes != null ) { if ( ( that.attributes == null ) || ( that.attributes.size() != attributes.size() ) ) { return false; } for ( Attribute attribute : attributes ) { if ( !that.attributes.contains( attribute ) ) { return false; } } return true; } else { return attributes == null; } } return false; } | AttributeValueItem extends ProtectedItem { @Override public boolean equals( Object o ) { if ( this == o ) { return true; } if ( o instanceof AttributeValueItem ) { AttributeValueItem that = ( AttributeValueItem ) o; if ( attributes != null ) { if ( ( that.attributes == null ) || ( that.attributes.size() != attributes.size() ) ) { return false; } for ( Attribute attribute : attributes ) { if ( !that.attributes.contains( attribute ) ) { return false; } } return true; } else { return attributes == null; } } return false; } } | AttributeValueItem extends ProtectedItem { @Override public boolean equals( Object o ) { if ( this == o ) { return true; } if ( o instanceof AttributeValueItem ) { AttributeValueItem that = ( AttributeValueItem ) o; if ( attributes != null ) { if ( ( that.attributes == null ) || ( that.attributes.size() != attributes.size() ) ) { return false; } for ( Attribute attribute : attributes ) { if ( !that.attributes.contains( attribute ) ) { return false; } } return true; } else { return attributes == null; } } return false; } AttributeValueItem( Set<Attribute> attributes ); } | AttributeValueItem extends ProtectedItem { @Override public boolean equals( Object o ) { if ( this == o ) { return true; } if ( o instanceof AttributeValueItem ) { AttributeValueItem that = ( AttributeValueItem ) o; if ( attributes != null ) { if ( ( that.attributes == null ) || ( that.attributes.size() != attributes.size() ) ) { return false; } for ( Attribute attribute : attributes ) { if ( !that.attributes.contains( attribute ) ) { return false; } } return true; } else { return attributes == null; } } return false; } AttributeValueItem( Set<Attribute> attributes ); Iterator<Attribute> iterator(); @Override int hashCode(); @Override boolean equals( Object o ); @Override String toString(); } | AttributeValueItem extends ProtectedItem { @Override public boolean equals( Object o ) { if ( this == o ) { return true; } if ( o instanceof AttributeValueItem ) { AttributeValueItem that = ( AttributeValueItem ) o; if ( attributes != null ) { if ( ( that.attributes == null ) || ( that.attributes.size() != attributes.size() ) ) { return false; } for ( Attribute attribute : attributes ) { if ( !that.attributes.contains( attribute ) ) { return false; } } return true; } else { return attributes == null; } } return false; } AttributeValueItem( Set<Attribute> attributes ); Iterator<Attribute> iterator(); @Override int hashCode(); @Override boolean equals( Object o ); @Override String toString(); } |
@Test public void testEqualsNull() throws Exception { assertFalse( attributeValueItemA.equals( null ) ); } | @Override public boolean equals( Object o ) { if ( this == o ) { return true; } if ( o instanceof AttributeValueItem ) { AttributeValueItem that = ( AttributeValueItem ) o; if ( attributes != null ) { if ( ( that.attributes == null ) || ( that.attributes.size() != attributes.size() ) ) { return false; } for ( Attribute attribute : attributes ) { if ( !that.attributes.contains( attribute ) ) { return false; } } return true; } else { return attributes == null; } } return false; } | AttributeValueItem extends ProtectedItem { @Override public boolean equals( Object o ) { if ( this == o ) { return true; } if ( o instanceof AttributeValueItem ) { AttributeValueItem that = ( AttributeValueItem ) o; if ( attributes != null ) { if ( ( that.attributes == null ) || ( that.attributes.size() != attributes.size() ) ) { return false; } for ( Attribute attribute : attributes ) { if ( !that.attributes.contains( attribute ) ) { return false; } } return true; } else { return attributes == null; } } return false; } } | AttributeValueItem extends ProtectedItem { @Override public boolean equals( Object o ) { if ( this == o ) { return true; } if ( o instanceof AttributeValueItem ) { AttributeValueItem that = ( AttributeValueItem ) o; if ( attributes != null ) { if ( ( that.attributes == null ) || ( that.attributes.size() != attributes.size() ) ) { return false; } for ( Attribute attribute : attributes ) { if ( !that.attributes.contains( attribute ) ) { return false; } } return true; } else { return attributes == null; } } return false; } AttributeValueItem( Set<Attribute> attributes ); } | AttributeValueItem extends ProtectedItem { @Override public boolean equals( Object o ) { if ( this == o ) { return true; } if ( o instanceof AttributeValueItem ) { AttributeValueItem that = ( AttributeValueItem ) o; if ( attributes != null ) { if ( ( that.attributes == null ) || ( that.attributes.size() != attributes.size() ) ) { return false; } for ( Attribute attribute : attributes ) { if ( !that.attributes.contains( attribute ) ) { return false; } } return true; } else { return attributes == null; } } return false; } AttributeValueItem( Set<Attribute> attributes ); Iterator<Attribute> iterator(); @Override int hashCode(); @Override boolean equals( Object o ); @Override String toString(); } | AttributeValueItem extends ProtectedItem { @Override public boolean equals( Object o ) { if ( this == o ) { return true; } if ( o instanceof AttributeValueItem ) { AttributeValueItem that = ( AttributeValueItem ) o; if ( attributes != null ) { if ( ( that.attributes == null ) || ( that.attributes.size() != attributes.size() ) ) { return false; } for ( Attribute attribute : attributes ) { if ( !that.attributes.contains( attribute ) ) { return false; } } return true; } else { return attributes == null; } } return false; } AttributeValueItem( Set<Attribute> attributes ); Iterator<Attribute> iterator(); @Override int hashCode(); @Override boolean equals( Object o ); @Override String toString(); } |
@Test public void testHashCodeReflexive() throws Exception { assertEquals( attributeValueItemA.hashCode(), attributeValueItemA.hashCode() ); } | @Override public int hashCode() { int hash = 37; if ( attributes != null ) { for ( Attribute attribute : attributes ) { hash = hash * 17 + attribute.hashCode(); } } return hash; } | AttributeValueItem extends ProtectedItem { @Override public int hashCode() { int hash = 37; if ( attributes != null ) { for ( Attribute attribute : attributes ) { hash = hash * 17 + attribute.hashCode(); } } return hash; } } | AttributeValueItem extends ProtectedItem { @Override public int hashCode() { int hash = 37; if ( attributes != null ) { for ( Attribute attribute : attributes ) { hash = hash * 17 + attribute.hashCode(); } } return hash; } AttributeValueItem( Set<Attribute> attributes ); } | AttributeValueItem extends ProtectedItem { @Override public int hashCode() { int hash = 37; if ( attributes != null ) { for ( Attribute attribute : attributes ) { hash = hash * 17 + attribute.hashCode(); } } return hash; } AttributeValueItem( Set<Attribute> attributes ); Iterator<Attribute> iterator(); @Override int hashCode(); @Override boolean equals( Object o ); @Override String toString(); } | AttributeValueItem extends ProtectedItem { @Override public int hashCode() { int hash = 37; if ( attributes != null ) { for ( Attribute attribute : attributes ) { hash = hash * 17 + attribute.hashCode(); } } return hash; } AttributeValueItem( Set<Attribute> attributes ); Iterator<Attribute> iterator(); @Override int hashCode(); @Override boolean equals( Object o ); @Override String toString(); } |
@Test public void testYearMonthDayHourMinSecMinusHourMin() throws ParseException { String gt = "20080102121314-1030"; GeneralizedTime generalizedTime = new GeneralizedTime( gt ); String result = generalizedTime.toGeneralizedTime(); assertEquals( gt, result ); } | public String toGeneralizedTime() { return toGeneralizedTime( upFormat, upFractionDelimiter, upFractionLength, upTimeZoneFormat ); } | GeneralizedTime implements Comparable<GeneralizedTime> { public String toGeneralizedTime() { return toGeneralizedTime( upFormat, upFractionDelimiter, upFractionLength, upTimeZoneFormat ); } } | GeneralizedTime implements Comparable<GeneralizedTime> { public String toGeneralizedTime() { return toGeneralizedTime( upFormat, upFractionDelimiter, upFractionLength, upTimeZoneFormat ); } GeneralizedTime( Date date ); GeneralizedTime( Calendar calendar ); GeneralizedTime( long timeInMillis ); GeneralizedTime( String generalizedTime ); } | GeneralizedTime implements Comparable<GeneralizedTime> { public String toGeneralizedTime() { return toGeneralizedTime( upFormat, upFractionDelimiter, upFractionLength, upTimeZoneFormat ); } GeneralizedTime( Date date ); GeneralizedTime( Calendar calendar ); GeneralizedTime( long timeInMillis ); GeneralizedTime( String generalizedTime ); String toGeneralizedTime(); String toGeneralizedTimeWithoutFraction(); String toGeneralizedTime( Format format, FractionDelimiter fractionDelimiter, int fractionLength,
TimeZoneFormat timeZoneFormat ); Calendar getCalendar(); @Override String toString(); @Override int hashCode(); @Override boolean equals( Object obj ); @Override int compareTo( GeneralizedTime other ); long getTime(); Date getDate(); int getYear(); int getMonth(); int getDay(); int getHour(); int getMinutes(); int getSeconds(); int getFraction(); static Date getDate( String zuluTime ); } | GeneralizedTime implements Comparable<GeneralizedTime> { public String toGeneralizedTime() { return toGeneralizedTime( upFormat, upFractionDelimiter, upFractionLength, upTimeZoneFormat ); } GeneralizedTime( Date date ); GeneralizedTime( Calendar calendar ); GeneralizedTime( long timeInMillis ); GeneralizedTime( String generalizedTime ); String toGeneralizedTime(); String toGeneralizedTimeWithoutFraction(); String toGeneralizedTime( Format format, FractionDelimiter fractionDelimiter, int fractionLength,
TimeZoneFormat timeZoneFormat ); Calendar getCalendar(); @Override String toString(); @Override int hashCode(); @Override boolean equals( Object obj ); @Override int compareTo( GeneralizedTime other ); long getTime(); Date getDate(); int getYear(); int getMonth(); int getDay(); int getHour(); int getMinutes(); int getSeconds(); int getFraction(); static Date getDate( String zuluTime ); } |
@Test public void testHashCodeSymmetric() throws Exception { assertEquals( attributeValueItemA.hashCode(), attributeValueItemACopy.hashCode() ); assertEquals( attributeValueItemACopy.hashCode(), attributeValueItemA.hashCode() ); } | @Override public int hashCode() { int hash = 37; if ( attributes != null ) { for ( Attribute attribute : attributes ) { hash = hash * 17 + attribute.hashCode(); } } return hash; } | AttributeValueItem extends ProtectedItem { @Override public int hashCode() { int hash = 37; if ( attributes != null ) { for ( Attribute attribute : attributes ) { hash = hash * 17 + attribute.hashCode(); } } return hash; } } | AttributeValueItem extends ProtectedItem { @Override public int hashCode() { int hash = 37; if ( attributes != null ) { for ( Attribute attribute : attributes ) { hash = hash * 17 + attribute.hashCode(); } } return hash; } AttributeValueItem( Set<Attribute> attributes ); } | AttributeValueItem extends ProtectedItem { @Override public int hashCode() { int hash = 37; if ( attributes != null ) { for ( Attribute attribute : attributes ) { hash = hash * 17 + attribute.hashCode(); } } return hash; } AttributeValueItem( Set<Attribute> attributes ); Iterator<Attribute> iterator(); @Override int hashCode(); @Override boolean equals( Object o ); @Override String toString(); } | AttributeValueItem extends ProtectedItem { @Override public int hashCode() { int hash = 37; if ( attributes != null ) { for ( Attribute attribute : attributes ) { hash = hash * 17 + attribute.hashCode(); } } return hash; } AttributeValueItem( Set<Attribute> attributes ); Iterator<Attribute> iterator(); @Override int hashCode(); @Override boolean equals( Object o ); @Override String toString(); } |
Subsets and Splits