repo_name stringlengths 7 104 | file_path stringlengths 13 198 | context stringlengths 67 7.15k | import_statement stringlengths 16 4.43k | code stringlengths 40 6.98k | prompt stringlengths 227 8.27k | next_line stringlengths 8 795 |
|---|---|---|---|---|---|---|
jdereg/java-util | src/main/java/com/cedarsoftware/util/DeepEquals.java | // Path: src/main/java/com/cedarsoftware/util/Converter.java
// public static BigDecimal convert2BigDecimal(Object fromInstance)
// {
// if (fromInstance == null)
// {
// return BIG_DECIMAL_ZERO;
// }
// return convertToBigDecimal(fromInstance);
// }
//
// Path: src/main/java/com/cedarsoftware/util/Converter.java
// public static boolean convert2boolean(Object fromInstance)
// {
// if (fromInstance == null)
// {
// return false;
// }
// return convertToBoolean(fromInstance);
// }
//
// Path: src/main/java/com/cedarsoftware/util/ReflectionUtils.java
// protected static String getClassLoaderName(Class<?> c)
// {
// ClassLoader loader = c.getClassLoader();
// return loader == null ? "bootstrap" : loader.toString();
// }
| import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import static com.cedarsoftware.util.Converter.convert2BigDecimal;
import static com.cedarsoftware.util.Converter.convert2boolean;
import static com.cedarsoftware.util.ReflectionUtils.getClassLoaderName; | * existence in a cache. Relying on an objects identity will not locate an
* object in cache, yet relying on it being equivalent will.<br><br>
*
* This method will handle cycles correctly, for example A->B->C->A. Suppose a and
* a' are two separate instances of the A with the same values for all fields on
* A, B, and C. Then a.deepEquals(a') will return true. It uses cycle detection
* storing visited objects in a Set to prevent endless loops.
* @param a Object one to compare
* @param b Object two to compare
* @param options Map options for compare. With no option, if a custom equals()
* method is present, it will be used. If IGNORE_CUSTOM_EQUALS is
* present, it will be expected to be a Set of classes to ignore.
* It is a black-list of classes that will not be compared
* using .equals() even if the classes have a custom .equals() method
* present. If it is and empty set, then no custom .equals() methods
* will be called.
*
* @return true if a is equivalent to b, false otherwise. Equivalent means that
* all field values of both subgraphs are the same, either at the field level
* or via the respectively encountered overridden .equals() methods during
* traversal.
*/
public static boolean deepEquals(Object a, Object b, Map<?, ?> options) {
Set<ItemsToCompare> visited = new HashSet<>();
return deepEquals(a, b, options,visited);
}
private static boolean deepEquals(Object a, Object b, Map<?, ?> options, Set<ItemsToCompare> visited) {
Deque<ItemsToCompare> stack = new LinkedList<>();
Set<String> ignoreCustomEquals = (Set<String>) options.get(IGNORE_CUSTOM_EQUALS); | // Path: src/main/java/com/cedarsoftware/util/Converter.java
// public static BigDecimal convert2BigDecimal(Object fromInstance)
// {
// if (fromInstance == null)
// {
// return BIG_DECIMAL_ZERO;
// }
// return convertToBigDecimal(fromInstance);
// }
//
// Path: src/main/java/com/cedarsoftware/util/Converter.java
// public static boolean convert2boolean(Object fromInstance)
// {
// if (fromInstance == null)
// {
// return false;
// }
// return convertToBoolean(fromInstance);
// }
//
// Path: src/main/java/com/cedarsoftware/util/ReflectionUtils.java
// protected static String getClassLoaderName(Class<?> c)
// {
// ClassLoader loader = c.getClassLoader();
// return loader == null ? "bootstrap" : loader.toString();
// }
// Path: src/main/java/com/cedarsoftware/util/DeepEquals.java
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import static com.cedarsoftware.util.Converter.convert2BigDecimal;
import static com.cedarsoftware.util.Converter.convert2boolean;
import static com.cedarsoftware.util.ReflectionUtils.getClassLoaderName;
* existence in a cache. Relying on an objects identity will not locate an
* object in cache, yet relying on it being equivalent will.<br><br>
*
* This method will handle cycles correctly, for example A->B->C->A. Suppose a and
* a' are two separate instances of the A with the same values for all fields on
* A, B, and C. Then a.deepEquals(a') will return true. It uses cycle detection
* storing visited objects in a Set to prevent endless loops.
* @param a Object one to compare
* @param b Object two to compare
* @param options Map options for compare. With no option, if a custom equals()
* method is present, it will be used. If IGNORE_CUSTOM_EQUALS is
* present, it will be expected to be a Set of classes to ignore.
* It is a black-list of classes that will not be compared
* using .equals() even if the classes have a custom .equals() method
* present. If it is and empty set, then no custom .equals() methods
* will be called.
*
* @return true if a is equivalent to b, false otherwise. Equivalent means that
* all field values of both subgraphs are the same, either at the field level
* or via the respectively encountered overridden .equals() methods during
* traversal.
*/
public static boolean deepEquals(Object a, Object b, Map<?, ?> options) {
Set<ItemsToCompare> visited = new HashSet<>();
return deepEquals(a, b, options,visited);
}
private static boolean deepEquals(Object a, Object b, Map<?, ?> options, Set<ItemsToCompare> visited) {
Deque<ItemsToCompare> stack = new LinkedList<>();
Set<String> ignoreCustomEquals = (Set<String>) options.get(IGNORE_CUSTOM_EQUALS); | final boolean allowStringsToMatchNumbers = convert2boolean(options.get(ALLOW_STRINGS_TO_MATCH_NUMBERS)); |
jdereg/java-util | src/main/java/com/cedarsoftware/util/DeepEquals.java | // Path: src/main/java/com/cedarsoftware/util/Converter.java
// public static BigDecimal convert2BigDecimal(Object fromInstance)
// {
// if (fromInstance == null)
// {
// return BIG_DECIMAL_ZERO;
// }
// return convertToBigDecimal(fromInstance);
// }
//
// Path: src/main/java/com/cedarsoftware/util/Converter.java
// public static boolean convert2boolean(Object fromInstance)
// {
// if (fromInstance == null)
// {
// return false;
// }
// return convertToBoolean(fromInstance);
// }
//
// Path: src/main/java/com/cedarsoftware/util/ReflectionUtils.java
// protected static String getClassLoaderName(Class<?> c)
// {
// ClassLoader loader = c.getClassLoader();
// return loader == null ? "bootstrap" : loader.toString();
// }
| import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import static com.cedarsoftware.util.Converter.convert2BigDecimal;
import static com.cedarsoftware.util.Converter.convert2boolean;
import static com.cedarsoftware.util.ReflectionUtils.getClassLoaderName; | stack.addFirst(new ItemsToCompare(a, b));
while (!stack.isEmpty())
{
ItemsToCompare itemsToCompare = stack.removeFirst();
visited.add(itemsToCompare);
final Object key1 = itemsToCompare._key1;
final Object key2 = itemsToCompare._key2;
if (key1 == key2)
{ // Same instance is always equal to itself.
continue;
}
if (key1 == null || key2 == null)
{ // If either one is null, they are not equal (both can't be null, due to above comparison).
return false;
}
if (key1 instanceof Number && key2 instanceof Number && compareNumbers((Number)key1, (Number)key2))
{
continue;
}
if (key1 instanceof Number || key2 instanceof Number)
{ // If one is a Number and the other one is not, then optionally compare them as strings, otherwise return false
if (allowStringsToMatchNumbers)
{
try
{ | // Path: src/main/java/com/cedarsoftware/util/Converter.java
// public static BigDecimal convert2BigDecimal(Object fromInstance)
// {
// if (fromInstance == null)
// {
// return BIG_DECIMAL_ZERO;
// }
// return convertToBigDecimal(fromInstance);
// }
//
// Path: src/main/java/com/cedarsoftware/util/Converter.java
// public static boolean convert2boolean(Object fromInstance)
// {
// if (fromInstance == null)
// {
// return false;
// }
// return convertToBoolean(fromInstance);
// }
//
// Path: src/main/java/com/cedarsoftware/util/ReflectionUtils.java
// protected static String getClassLoaderName(Class<?> c)
// {
// ClassLoader loader = c.getClassLoader();
// return loader == null ? "bootstrap" : loader.toString();
// }
// Path: src/main/java/com/cedarsoftware/util/DeepEquals.java
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import static com.cedarsoftware.util.Converter.convert2BigDecimal;
import static com.cedarsoftware.util.Converter.convert2boolean;
import static com.cedarsoftware.util.ReflectionUtils.getClassLoaderName;
stack.addFirst(new ItemsToCompare(a, b));
while (!stack.isEmpty())
{
ItemsToCompare itemsToCompare = stack.removeFirst();
visited.add(itemsToCompare);
final Object key1 = itemsToCompare._key1;
final Object key2 = itemsToCompare._key2;
if (key1 == key2)
{ // Same instance is always equal to itself.
continue;
}
if (key1 == null || key2 == null)
{ // If either one is null, they are not equal (both can't be null, due to above comparison).
return false;
}
if (key1 instanceof Number && key2 instanceof Number && compareNumbers((Number)key1, (Number)key2))
{
continue;
}
if (key1 instanceof Number || key2 instanceof Number)
{ // If one is a Number and the other one is not, then optionally compare them as strings, otherwise return false
if (allowStringsToMatchNumbers)
{
try
{ | if (key1 instanceof String && compareNumbers(convert2BigDecimal(key1), (Number)key2)) |
jdereg/java-util | src/main/java/com/cedarsoftware/util/DeepEquals.java | // Path: src/main/java/com/cedarsoftware/util/Converter.java
// public static BigDecimal convert2BigDecimal(Object fromInstance)
// {
// if (fromInstance == null)
// {
// return BIG_DECIMAL_ZERO;
// }
// return convertToBigDecimal(fromInstance);
// }
//
// Path: src/main/java/com/cedarsoftware/util/Converter.java
// public static boolean convert2boolean(Object fromInstance)
// {
// if (fromInstance == null)
// {
// return false;
// }
// return convertToBoolean(fromInstance);
// }
//
// Path: src/main/java/com/cedarsoftware/util/ReflectionUtils.java
// protected static String getClassLoaderName(Class<?> c)
// {
// ClassLoader loader = c.getClassLoader();
// return loader == null ? "bootstrap" : loader.toString();
// }
| import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import static com.cedarsoftware.util.Converter.convert2BigDecimal;
import static com.cedarsoftware.util.Converter.convert2boolean;
import static com.cedarsoftware.util.ReflectionUtils.getClassLoaderName; | final double absA = Math.abs(a);
final double absB = Math.abs(b);
final double diff = Math.abs(a - b);
if (a == b)
{ // shortcut, handles infinities
return true;
}
else if (a == 0 || b == 0 || diff < Double.MIN_NORMAL)
{
// a or b is zero or both are extremely close to it
// relative error is less meaningful here
return diff < (epsilon * Double.MIN_NORMAL);
}
else
{ // use relative error
return diff / (absA + absB) < epsilon;
}
}
/**
* Determine if the passed in class has a non-Object.equals() method. This
* method caches its results in static ConcurrentHashMap to benefit
* execution performance.
* @param c Class to check.
* @return true, if the passed in Class has a .equals() method somewhere between
* itself and just below Object in it's inheritance.
*/
public static boolean hasCustomEquals(Class<?> c)
{ | // Path: src/main/java/com/cedarsoftware/util/Converter.java
// public static BigDecimal convert2BigDecimal(Object fromInstance)
// {
// if (fromInstance == null)
// {
// return BIG_DECIMAL_ZERO;
// }
// return convertToBigDecimal(fromInstance);
// }
//
// Path: src/main/java/com/cedarsoftware/util/Converter.java
// public static boolean convert2boolean(Object fromInstance)
// {
// if (fromInstance == null)
// {
// return false;
// }
// return convertToBoolean(fromInstance);
// }
//
// Path: src/main/java/com/cedarsoftware/util/ReflectionUtils.java
// protected static String getClassLoaderName(Class<?> c)
// {
// ClassLoader loader = c.getClassLoader();
// return loader == null ? "bootstrap" : loader.toString();
// }
// Path: src/main/java/com/cedarsoftware/util/DeepEquals.java
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import static com.cedarsoftware.util.Converter.convert2BigDecimal;
import static com.cedarsoftware.util.Converter.convert2boolean;
import static com.cedarsoftware.util.ReflectionUtils.getClassLoaderName;
final double absA = Math.abs(a);
final double absB = Math.abs(b);
final double diff = Math.abs(a - b);
if (a == b)
{ // shortcut, handles infinities
return true;
}
else if (a == 0 || b == 0 || diff < Double.MIN_NORMAL)
{
// a or b is zero or both are extremely close to it
// relative error is less meaningful here
return diff < (epsilon * Double.MIN_NORMAL);
}
else
{ // use relative error
return diff / (absA + absB) < epsilon;
}
}
/**
* Determine if the passed in class has a non-Object.equals() method. This
* method caches its results in static ConcurrentHashMap to benefit
* execution performance.
* @param c Class to check.
* @return true, if the passed in Class has a .equals() method somewhere between
* itself and just below Object in it's inheritance.
*/
public static boolean hasCustomEquals(Class<?> c)
{ | StringBuilder sb = new StringBuilder(getClassLoaderName(c)); |
jdereg/java-util | src/main/java/com/cedarsoftware/util/CompactMap.java | // Path: src/main/java/com/cedarsoftware/util/StringUtilities.java
// public static int hashCodeIgnoreCase(String s)
// {
// if (s == null)
// {
// return 0;
// }
// final int len = s.length();
// int hash = 0;
// for (int i = 0; i < len; i++)
// {
// hash = 31 * hash + Character.toLowerCase((int)s.charAt(i));
// }
// return hash;
// }
| import java.lang.reflect.Constructor;
import java.util.*;
import static com.cedarsoftware.util.StringUtilities.hashCodeIgnoreCase; |
public V setValue(V value)
{
V save = this.getValue();
super.setValue(value);
CompactMap.this.put(getKey(), value); // "Transmit" (write-thru) to underlying Map.
return save;
}
public boolean equals(Object o)
{
if (!(o instanceof Map.Entry)) { return false; }
if (o == this) { return true; }
Map.Entry<?,?> e = (Map.Entry<?,?>)o;
return compareKeys(getKey(), e.getKey()) && Objects.equals(getValue(), e.getValue());
}
public int hashCode()
{
return computeKeyHashCode(getKey()) ^ computeValueHashCode(getValue());
}
}
protected int computeKeyHashCode(Object key)
{
if (key instanceof String)
{
if (isCaseInsensitive())
{ | // Path: src/main/java/com/cedarsoftware/util/StringUtilities.java
// public static int hashCodeIgnoreCase(String s)
// {
// if (s == null)
// {
// return 0;
// }
// final int len = s.length();
// int hash = 0;
// for (int i = 0; i < len; i++)
// {
// hash = 31 * hash + Character.toLowerCase((int)s.charAt(i));
// }
// return hash;
// }
// Path: src/main/java/com/cedarsoftware/util/CompactMap.java
import java.lang.reflect.Constructor;
import java.util.*;
import static com.cedarsoftware.util.StringUtilities.hashCodeIgnoreCase;
public V setValue(V value)
{
V save = this.getValue();
super.setValue(value);
CompactMap.this.put(getKey(), value); // "Transmit" (write-thru) to underlying Map.
return save;
}
public boolean equals(Object o)
{
if (!(o instanceof Map.Entry)) { return false; }
if (o == this) { return true; }
Map.Entry<?,?> e = (Map.Entry<?,?>)o;
return compareKeys(getKey(), e.getKey()) && Objects.equals(getValue(), e.getValue());
}
public int hashCode()
{
return computeKeyHashCode(getKey()) ^ computeValueHashCode(getValue());
}
}
protected int computeKeyHashCode(Object key)
{
if (key instanceof String)
{
if (isCaseInsensitive())
{ | return hashCodeIgnoreCase((String)key); |
jdereg/java-util | src/main/java/com/cedarsoftware/util/UniqueIdGenerator.java | // Path: src/main/java/com/cedarsoftware/util/StringUtilities.java
// public static boolean hasContent(final String s)
// {
// return !(trimLength(s) == 0); // faster than returning !isEmpty()
// }
| import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.security.SecureRandom;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;
import static com.cedarsoftware.util.StringUtilities.hasContent;
import static java.lang.Integer.parseInt;
import static java.lang.Math.abs;
import static java.lang.System.currentTimeMillis; |
private static final Object lock = new Object();
private static final Object lock19 = new Object();
private static int count = 0;
private static int count2 = 0;
private static long previousTimeMilliseconds = 0;
private static long previousTimeMilliseconds2 = 0;
private static final int serverId;
private static final Map<Long, Long> lastIds = new LinkedHashMap<Long, Long>()
{
protected boolean removeEldestEntry(Map.Entry<Long, Long> eldest)
{
return size() > 1000;
}
};
private static final Map<Long, Long> lastIdsFull = new LinkedHashMap<Long, Long>()
{
protected boolean removeEldestEntry(Map.Entry<Long, Long> eldest)
{
return size() > 10000;
}
};
static
{
int id = getServerId(JAVA_UTIL_CLUSTERID);
String setVia = "environment variable: " + JAVA_UTIL_CLUSTERID;
if (id == -1)
{
String envName = SystemUtilities.getExternalVariable(JAVA_UTIL_CLUSTERID); | // Path: src/main/java/com/cedarsoftware/util/StringUtilities.java
// public static boolean hasContent(final String s)
// {
// return !(trimLength(s) == 0); // faster than returning !isEmpty()
// }
// Path: src/main/java/com/cedarsoftware/util/UniqueIdGenerator.java
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.security.SecureRandom;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;
import static com.cedarsoftware.util.StringUtilities.hasContent;
import static java.lang.Integer.parseInt;
import static java.lang.Math.abs;
import static java.lang.System.currentTimeMillis;
private static final Object lock = new Object();
private static final Object lock19 = new Object();
private static int count = 0;
private static int count2 = 0;
private static long previousTimeMilliseconds = 0;
private static long previousTimeMilliseconds2 = 0;
private static final int serverId;
private static final Map<Long, Long> lastIds = new LinkedHashMap<Long, Long>()
{
protected boolean removeEldestEntry(Map.Entry<Long, Long> eldest)
{
return size() > 1000;
}
};
private static final Map<Long, Long> lastIdsFull = new LinkedHashMap<Long, Long>()
{
protected boolean removeEldestEntry(Map.Entry<Long, Long> eldest)
{
return size() > 10000;
}
};
static
{
int id = getServerId(JAVA_UTIL_CLUSTERID);
String setVia = "environment variable: " + JAVA_UTIL_CLUSTERID;
if (id == -1)
{
String envName = SystemUtilities.getExternalVariable(JAVA_UTIL_CLUSTERID); | if (hasContent(envName)) |
trustedanalytics/hdfs-broker | src/main/java/org/trustedanalytics/servicebroker/hdfs/plans/binding/HdfsBindingClient.java | // Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/config/HdfsConstants.java
// public class HdfsConstants {
// public static final String HADOOP_DEFAULT_FS = "fs.defaultFS";
// public static final String USER_QUALIFIER = "user";
// public static final String SUPER_USER_QUALIFIER = "superUser";
// }
| import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.trustedanalytics.cfbroker.store.hdfs.helper.DirHelper;
import org.trustedanalytics.cfbroker.store.hdfs.helper.HdfsPathTemplateUtils;
import org.trustedanalytics.servicebroker.framework.Credentials;
import org.trustedanalytics.servicebroker.hdfs.config.HdfsConstants; | /**
* Copyright (c) 2015 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.trustedanalytics.servicebroker.hdfs.plans.binding;
@Component
class HdfsBindingClient
implements HdfsBareBindingOperations, HdfsSimpleBindingOperations, HdfsSpecificOrgBindingOperations {
private final Credentials credentials;
private final String userspacePathTemplate;
@Autowired
public HdfsBindingClient(Credentials credentials, String userspacePathTemplate) {
this.credentials = credentials;
this.userspacePathTemplate = userspacePathTemplate;
}
@Override
public Map<String, Object> createCredentialsMap() {
return credentials.getCredentialsMap();
}
@Override
public Map<String, Object> createCredentialsMap(UUID instanceId) {
return createCredentialsMap(instanceId, null);
}
@Override
public Map<String, Object> createCredentialsMap(UUID instanceId, UUID orgId) {
Map<String, Object> credentialsCopy = new HashMap<>(credentials.getCredentialsMap());
String dir = HdfsPathTemplateUtils.fill(userspacePathTemplate, instanceId, orgId); | // Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/config/HdfsConstants.java
// public class HdfsConstants {
// public static final String HADOOP_DEFAULT_FS = "fs.defaultFS";
// public static final String USER_QUALIFIER = "user";
// public static final String SUPER_USER_QUALIFIER = "superUser";
// }
// Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/plans/binding/HdfsBindingClient.java
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.trustedanalytics.cfbroker.store.hdfs.helper.DirHelper;
import org.trustedanalytics.cfbroker.store.hdfs.helper.HdfsPathTemplateUtils;
import org.trustedanalytics.servicebroker.framework.Credentials;
import org.trustedanalytics.servicebroker.hdfs.config.HdfsConstants;
/**
* Copyright (c) 2015 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.trustedanalytics.servicebroker.hdfs.plans.binding;
@Component
class HdfsBindingClient
implements HdfsBareBindingOperations, HdfsSimpleBindingOperations, HdfsSpecificOrgBindingOperations {
private final Credentials credentials;
private final String userspacePathTemplate;
@Autowired
public HdfsBindingClient(Credentials credentials, String userspacePathTemplate) {
this.credentials = credentials;
this.userspacePathTemplate = userspacePathTemplate;
}
@Override
public Map<String, Object> createCredentialsMap() {
return credentials.getCredentialsMap();
}
@Override
public Map<String, Object> createCredentialsMap(UUID instanceId) {
return createCredentialsMap(instanceId, null);
}
@Override
public Map<String, Object> createCredentialsMap(UUID instanceId, UUID orgId) {
Map<String, Object> credentialsCopy = new HashMap<>(credentials.getCredentialsMap());
String dir = HdfsPathTemplateUtils.fill(userspacePathTemplate, instanceId, orgId); | String uri = DirHelper.concat(credentialsCopy.get(HdfsConstants.HADOOP_DEFAULT_FS).toString(), dir); |
trustedanalytics/hdfs-broker | src/test/java/org/trustedanalytics/servicebroker/hdfs/plans/HdfsPlanBareTest.java | // Path: src/test/java/org/trustedanalytics/servicebroker/hdfs/plans/binding/HdfsBindingClientFactory.java
// public class HdfsBindingClientFactory {
// public static HdfsBindingClient create(Credentials credentials, String userspacePathTemplate){
// return new HdfsBindingClient(credentials, userspacePathTemplate);
// }
// }
| import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
import static org.trustedanalytics.servicebroker.test.cloudfoundry.CfModelsFactory.getServiceInstance;
import java.util.Map;
import com.google.common.collect.ImmutableMap;
import org.cloudfoundry.community.servicebroker.model.ServiceInstance;
import org.junit.Test;
import org.trustedanalytics.servicebroker.hdfs.plans.binding.HdfsBindingClientFactory; | /**
* Copyright (c) 2015 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.trustedanalytics.servicebroker.hdfs.plans;
public final class HdfsPlanBareTest extends HdfsPlanTestBase {
@Test
public void bind_templateWithOrgAndInstanceVariables_replaceVariablesWithValuesAndAppendUriToCredentialsMap()
throws Exception {
//arrange
HdfsPlanBare plan = | // Path: src/test/java/org/trustedanalytics/servicebroker/hdfs/plans/binding/HdfsBindingClientFactory.java
// public class HdfsBindingClientFactory {
// public static HdfsBindingClient create(Credentials credentials, String userspacePathTemplate){
// return new HdfsBindingClient(credentials, userspacePathTemplate);
// }
// }
// Path: src/test/java/org/trustedanalytics/servicebroker/hdfs/plans/HdfsPlanBareTest.java
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
import static org.trustedanalytics.servicebroker.test.cloudfoundry.CfModelsFactory.getServiceInstance;
import java.util.Map;
import com.google.common.collect.ImmutableMap;
import org.cloudfoundry.community.servicebroker.model.ServiceInstance;
import org.junit.Test;
import org.trustedanalytics.servicebroker.hdfs.plans.binding.HdfsBindingClientFactory;
/**
* Copyright (c) 2015 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.trustedanalytics.servicebroker.hdfs.plans;
public final class HdfsPlanBareTest extends HdfsPlanTestBase {
@Test
public void bind_templateWithOrgAndInstanceVariables_replaceVariablesWithValuesAndAppendUriToCredentialsMap()
throws Exception {
//arrange
HdfsPlanBare plan = | new HdfsPlanBare(HdfsBindingClientFactory.create(getInputCredentials(), USERSPACE_PATH_TEMPLATE)); |
trustedanalytics/hdfs-broker | src/main/java/org/trustedanalytics/servicebroker/hdfs/config/hgm/HgmHttpsConfiguration.java | // Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/config/hgm/HgmConfiguration.java
// @Configuration
// public class HgmConfiguration {
//
// @Value("${group.mapping.url}")
// @NotNull
// @Getter @Setter
// private String url;
//
// @Value("${group.mapping.https.username}")
// @Getter @Setter
// private String username;
//
// @Value("${group.mapping.https.password}")
// @Getter @Setter
// private String password;
//
// @Value("${group.mapping.kerberos.principal}")
// @Getter @Setter
// private String principal;
//
// @Value("${group.mapping.kerberos.principalKeyTab}")
// @Getter @Setter
// private String principalKeyTab;
//
// }
| import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import javax.net.ssl.SSLContext;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.HttpClient;
import org.apache.http.conn.ssl.AllowAllHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
import org.trustedanalytics.servicebroker.hdfs.config.hgm.HgmConfiguration; | /**
* Copyright (c) 2015 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.trustedanalytics.servicebroker.hdfs.config.hgm;
@Profile("!kerberos")
@Configuration
public class HgmHttpsConfiguration {
@Autowired | // Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/config/hgm/HgmConfiguration.java
// @Configuration
// public class HgmConfiguration {
//
// @Value("${group.mapping.url}")
// @NotNull
// @Getter @Setter
// private String url;
//
// @Value("${group.mapping.https.username}")
// @Getter @Setter
// private String username;
//
// @Value("${group.mapping.https.password}")
// @Getter @Setter
// private String password;
//
// @Value("${group.mapping.kerberos.principal}")
// @Getter @Setter
// private String principal;
//
// @Value("${group.mapping.kerberos.principalKeyTab}")
// @Getter @Setter
// private String principalKeyTab;
//
// }
// Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/config/hgm/HgmHttpsConfiguration.java
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import javax.net.ssl.SSLContext;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.HttpClient;
import org.apache.http.conn.ssl.AllowAllHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
import org.trustedanalytics.servicebroker.hdfs.config.hgm.HgmConfiguration;
/**
* Copyright (c) 2015 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.trustedanalytics.servicebroker.hdfs.config.hgm;
@Profile("!kerberos")
@Configuration
public class HgmHttpsConfiguration {
@Autowired | private HgmConfiguration configuration; |
trustedanalytics/hdfs-broker | src/test/java/org/trustedanalytics/servicebroker/hdfs/plans/HdfsPlanSharedTest.java | // Path: src/test/java/org/trustedanalytics/servicebroker/hdfs/plans/binding/HdfsBindingClientFactory.java
// public class HdfsBindingClientFactory {
// public static HdfsBindingClient create(Credentials credentials, String userspacePathTemplate){
// return new HdfsBindingClient(credentials, userspacePathTemplate);
// }
// }
//
// Path: src/test/java/org/trustedanalytics/servicebroker/hdfs/plans/provisioning/HdfsProvisioningClientFactory.java
// public class HdfsProvisioningClientFactory {
// public static HdfsProvisioningClient create(HdfsClient hdfsClient, HdfsClient encryptedHdfsClient,
// String userspacePathTemplate) {
// return new HdfsProvisioningClient(hdfsClient, encryptedHdfsClient, userspacePathTemplate);
// }
// }
| import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.trustedanalytics.servicebroker.test.cloudfoundry.CfModelsFactory.getServiceInstance;
import java.io.IOException;
import java.util.Map;
import java.util.Optional;
import com.google.common.collect.ImmutableMap;
import org.apache.hadoop.fs.permission.FsAction;
import org.apache.hadoop.fs.permission.FsPermission;
import org.apache.http.annotation.Immutable;
import org.cloudfoundry.community.servicebroker.exception.ServiceBrokerException;
import org.cloudfoundry.community.servicebroker.model.ServiceInstance;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.trustedanalytics.cfbroker.store.hdfs.service.HdfsClient;
import org.trustedanalytics.servicebroker.hdfs.plans.binding.HdfsBindingClientFactory;
import org.trustedanalytics.servicebroker.hdfs.plans.provisioning.HdfsProvisioningClientFactory; | /**
* Copyright (c) 2015 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.trustedanalytics.servicebroker.hdfs.plans;
@RunWith(MockitoJUnitRunner.class)
public final class HdfsPlanSharedTest extends HdfsPlanTestBase {
private static final FsPermission FS_PERMISSION = new FsPermission(FsAction.ALL, FsAction.ALL,
FsAction.NONE);
private HdfsPlanShared planUnderTest;
@Mock
private HdfsClient hdfsClient;
@Mock
private HdfsClient encryptedHdfsClient;
@Before
public void setup() {
planUnderTest = new HdfsPlanShared( | // Path: src/test/java/org/trustedanalytics/servicebroker/hdfs/plans/binding/HdfsBindingClientFactory.java
// public class HdfsBindingClientFactory {
// public static HdfsBindingClient create(Credentials credentials, String userspacePathTemplate){
// return new HdfsBindingClient(credentials, userspacePathTemplate);
// }
// }
//
// Path: src/test/java/org/trustedanalytics/servicebroker/hdfs/plans/provisioning/HdfsProvisioningClientFactory.java
// public class HdfsProvisioningClientFactory {
// public static HdfsProvisioningClient create(HdfsClient hdfsClient, HdfsClient encryptedHdfsClient,
// String userspacePathTemplate) {
// return new HdfsProvisioningClient(hdfsClient, encryptedHdfsClient, userspacePathTemplate);
// }
// }
// Path: src/test/java/org/trustedanalytics/servicebroker/hdfs/plans/HdfsPlanSharedTest.java
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.trustedanalytics.servicebroker.test.cloudfoundry.CfModelsFactory.getServiceInstance;
import java.io.IOException;
import java.util.Map;
import java.util.Optional;
import com.google.common.collect.ImmutableMap;
import org.apache.hadoop.fs.permission.FsAction;
import org.apache.hadoop.fs.permission.FsPermission;
import org.apache.http.annotation.Immutable;
import org.cloudfoundry.community.servicebroker.exception.ServiceBrokerException;
import org.cloudfoundry.community.servicebroker.model.ServiceInstance;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.trustedanalytics.cfbroker.store.hdfs.service.HdfsClient;
import org.trustedanalytics.servicebroker.hdfs.plans.binding.HdfsBindingClientFactory;
import org.trustedanalytics.servicebroker.hdfs.plans.provisioning.HdfsProvisioningClientFactory;
/**
* Copyright (c) 2015 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.trustedanalytics.servicebroker.hdfs.plans;
@RunWith(MockitoJUnitRunner.class)
public final class HdfsPlanSharedTest extends HdfsPlanTestBase {
private static final FsPermission FS_PERMISSION = new FsPermission(FsAction.ALL, FsAction.ALL,
FsAction.NONE);
private HdfsPlanShared planUnderTest;
@Mock
private HdfsClient hdfsClient;
@Mock
private HdfsClient encryptedHdfsClient;
@Before
public void setup() {
planUnderTest = new HdfsPlanShared( | HdfsProvisioningClientFactory.create(hdfsClient, encryptedHdfsClient, USERSPACE_PATH_TEMPLATE), |
trustedanalytics/hdfs-broker | src/test/java/org/trustedanalytics/servicebroker/hdfs/plans/HdfsPlanSharedTest.java | // Path: src/test/java/org/trustedanalytics/servicebroker/hdfs/plans/binding/HdfsBindingClientFactory.java
// public class HdfsBindingClientFactory {
// public static HdfsBindingClient create(Credentials credentials, String userspacePathTemplate){
// return new HdfsBindingClient(credentials, userspacePathTemplate);
// }
// }
//
// Path: src/test/java/org/trustedanalytics/servicebroker/hdfs/plans/provisioning/HdfsProvisioningClientFactory.java
// public class HdfsProvisioningClientFactory {
// public static HdfsProvisioningClient create(HdfsClient hdfsClient, HdfsClient encryptedHdfsClient,
// String userspacePathTemplate) {
// return new HdfsProvisioningClient(hdfsClient, encryptedHdfsClient, userspacePathTemplate);
// }
// }
| import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.trustedanalytics.servicebroker.test.cloudfoundry.CfModelsFactory.getServiceInstance;
import java.io.IOException;
import java.util.Map;
import java.util.Optional;
import com.google.common.collect.ImmutableMap;
import org.apache.hadoop.fs.permission.FsAction;
import org.apache.hadoop.fs.permission.FsPermission;
import org.apache.http.annotation.Immutable;
import org.cloudfoundry.community.servicebroker.exception.ServiceBrokerException;
import org.cloudfoundry.community.servicebroker.model.ServiceInstance;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.trustedanalytics.cfbroker.store.hdfs.service.HdfsClient;
import org.trustedanalytics.servicebroker.hdfs.plans.binding.HdfsBindingClientFactory;
import org.trustedanalytics.servicebroker.hdfs.plans.provisioning.HdfsProvisioningClientFactory; | /**
* Copyright (c) 2015 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.trustedanalytics.servicebroker.hdfs.plans;
@RunWith(MockitoJUnitRunner.class)
public final class HdfsPlanSharedTest extends HdfsPlanTestBase {
private static final FsPermission FS_PERMISSION = new FsPermission(FsAction.ALL, FsAction.ALL,
FsAction.NONE);
private HdfsPlanShared planUnderTest;
@Mock
private HdfsClient hdfsClient;
@Mock
private HdfsClient encryptedHdfsClient;
@Before
public void setup() {
planUnderTest = new HdfsPlanShared(
HdfsProvisioningClientFactory.create(hdfsClient, encryptedHdfsClient, USERSPACE_PATH_TEMPLATE), | // Path: src/test/java/org/trustedanalytics/servicebroker/hdfs/plans/binding/HdfsBindingClientFactory.java
// public class HdfsBindingClientFactory {
// public static HdfsBindingClient create(Credentials credentials, String userspacePathTemplate){
// return new HdfsBindingClient(credentials, userspacePathTemplate);
// }
// }
//
// Path: src/test/java/org/trustedanalytics/servicebroker/hdfs/plans/provisioning/HdfsProvisioningClientFactory.java
// public class HdfsProvisioningClientFactory {
// public static HdfsProvisioningClient create(HdfsClient hdfsClient, HdfsClient encryptedHdfsClient,
// String userspacePathTemplate) {
// return new HdfsProvisioningClient(hdfsClient, encryptedHdfsClient, userspacePathTemplate);
// }
// }
// Path: src/test/java/org/trustedanalytics/servicebroker/hdfs/plans/HdfsPlanSharedTest.java
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.trustedanalytics.servicebroker.test.cloudfoundry.CfModelsFactory.getServiceInstance;
import java.io.IOException;
import java.util.Map;
import java.util.Optional;
import com.google.common.collect.ImmutableMap;
import org.apache.hadoop.fs.permission.FsAction;
import org.apache.hadoop.fs.permission.FsPermission;
import org.apache.http.annotation.Immutable;
import org.cloudfoundry.community.servicebroker.exception.ServiceBrokerException;
import org.cloudfoundry.community.servicebroker.model.ServiceInstance;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.trustedanalytics.cfbroker.store.hdfs.service.HdfsClient;
import org.trustedanalytics.servicebroker.hdfs.plans.binding.HdfsBindingClientFactory;
import org.trustedanalytics.servicebroker.hdfs.plans.provisioning.HdfsProvisioningClientFactory;
/**
* Copyright (c) 2015 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.trustedanalytics.servicebroker.hdfs.plans;
@RunWith(MockitoJUnitRunner.class)
public final class HdfsPlanSharedTest extends HdfsPlanTestBase {
private static final FsPermission FS_PERMISSION = new FsPermission(FsAction.ALL, FsAction.ALL,
FsAction.NONE);
private HdfsPlanShared planUnderTest;
@Mock
private HdfsClient hdfsClient;
@Mock
private HdfsClient encryptedHdfsClient;
@Before
public void setup() {
planUnderTest = new HdfsPlanShared(
HdfsProvisioningClientFactory.create(hdfsClient, encryptedHdfsClient, USERSPACE_PATH_TEMPLATE), | HdfsBindingClientFactory.create(getInputCredentials(), USERSPACE_PATH_TEMPLATE)); |
trustedanalytics/hdfs-broker | src/main/java/org/trustedanalytics/servicebroker/hdfs/plans/HdfsPlanEncrypted.java | // Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/plans/binding/HdfsSpecificOrgBindingOperations.java
// public interface HdfsSpecificOrgBindingOperations {
// Map<String, Object> createCredentialsMap(UUID instanceId, UUID orgId);
// }
//
// Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/plans/provisioning/HdfsPlanEncryptedDirectoryProvisioningOperations.java
// public interface HdfsPlanEncryptedDirectoryProvisioningOperations
// extends HdfsDirectoryProvisioningOperations {
// void createEncryptedZone(UUID instanceId, UUID orgId) throws ServiceBrokerException;
// }
| import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import org.cloudfoundry.community.servicebroker.exception.ServiceBrokerException;
import org.cloudfoundry.community.servicebroker.exception.ServiceInstanceExistsException;
import org.cloudfoundry.community.servicebroker.model.ServiceInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.trustedanalytics.servicebroker.framework.service.ServicePlanDefinition;
import org.trustedanalytics.servicebroker.hdfs.plans.binding.HdfsSpecificOrgBindingOperations;
import org.trustedanalytics.servicebroker.hdfs.plans.provisioning.HdfsPlanEncryptedDirectoryProvisioningOperations; | /**
* Copyright (c) 2015 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.trustedanalytics.servicebroker.hdfs.plans;
@Component("encrypted")
class HdfsPlanEncrypted implements ServicePlanDefinition {
| // Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/plans/binding/HdfsSpecificOrgBindingOperations.java
// public interface HdfsSpecificOrgBindingOperations {
// Map<String, Object> createCredentialsMap(UUID instanceId, UUID orgId);
// }
//
// Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/plans/provisioning/HdfsPlanEncryptedDirectoryProvisioningOperations.java
// public interface HdfsPlanEncryptedDirectoryProvisioningOperations
// extends HdfsDirectoryProvisioningOperations {
// void createEncryptedZone(UUID instanceId, UUID orgId) throws ServiceBrokerException;
// }
// Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/plans/HdfsPlanEncrypted.java
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import org.cloudfoundry.community.servicebroker.exception.ServiceBrokerException;
import org.cloudfoundry.community.servicebroker.exception.ServiceInstanceExistsException;
import org.cloudfoundry.community.servicebroker.model.ServiceInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.trustedanalytics.servicebroker.framework.service.ServicePlanDefinition;
import org.trustedanalytics.servicebroker.hdfs.plans.binding.HdfsSpecificOrgBindingOperations;
import org.trustedanalytics.servicebroker.hdfs.plans.provisioning.HdfsPlanEncryptedDirectoryProvisioningOperations;
/**
* Copyright (c) 2015 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.trustedanalytics.servicebroker.hdfs.plans;
@Component("encrypted")
class HdfsPlanEncrypted implements ServicePlanDefinition {
| private final HdfsPlanEncryptedDirectoryProvisioningOperations hdfsOperations; |
trustedanalytics/hdfs-broker | src/main/java/org/trustedanalytics/servicebroker/hdfs/plans/HdfsPlanEncrypted.java | // Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/plans/binding/HdfsSpecificOrgBindingOperations.java
// public interface HdfsSpecificOrgBindingOperations {
// Map<String, Object> createCredentialsMap(UUID instanceId, UUID orgId);
// }
//
// Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/plans/provisioning/HdfsPlanEncryptedDirectoryProvisioningOperations.java
// public interface HdfsPlanEncryptedDirectoryProvisioningOperations
// extends HdfsDirectoryProvisioningOperations {
// void createEncryptedZone(UUID instanceId, UUID orgId) throws ServiceBrokerException;
// }
| import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import org.cloudfoundry.community.servicebroker.exception.ServiceBrokerException;
import org.cloudfoundry.community.servicebroker.exception.ServiceInstanceExistsException;
import org.cloudfoundry.community.servicebroker.model.ServiceInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.trustedanalytics.servicebroker.framework.service.ServicePlanDefinition;
import org.trustedanalytics.servicebroker.hdfs.plans.binding.HdfsSpecificOrgBindingOperations;
import org.trustedanalytics.servicebroker.hdfs.plans.provisioning.HdfsPlanEncryptedDirectoryProvisioningOperations; | /**
* Copyright (c) 2015 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.trustedanalytics.servicebroker.hdfs.plans;
@Component("encrypted")
class HdfsPlanEncrypted implements ServicePlanDefinition {
private final HdfsPlanEncryptedDirectoryProvisioningOperations hdfsOperations; | // Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/plans/binding/HdfsSpecificOrgBindingOperations.java
// public interface HdfsSpecificOrgBindingOperations {
// Map<String, Object> createCredentialsMap(UUID instanceId, UUID orgId);
// }
//
// Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/plans/provisioning/HdfsPlanEncryptedDirectoryProvisioningOperations.java
// public interface HdfsPlanEncryptedDirectoryProvisioningOperations
// extends HdfsDirectoryProvisioningOperations {
// void createEncryptedZone(UUID instanceId, UUID orgId) throws ServiceBrokerException;
// }
// Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/plans/HdfsPlanEncrypted.java
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import org.cloudfoundry.community.servicebroker.exception.ServiceBrokerException;
import org.cloudfoundry.community.servicebroker.exception.ServiceInstanceExistsException;
import org.cloudfoundry.community.servicebroker.model.ServiceInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.trustedanalytics.servicebroker.framework.service.ServicePlanDefinition;
import org.trustedanalytics.servicebroker.hdfs.plans.binding.HdfsSpecificOrgBindingOperations;
import org.trustedanalytics.servicebroker.hdfs.plans.provisioning.HdfsPlanEncryptedDirectoryProvisioningOperations;
/**
* Copyright (c) 2015 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.trustedanalytics.servicebroker.hdfs.plans;
@Component("encrypted")
class HdfsPlanEncrypted implements ServicePlanDefinition {
private final HdfsPlanEncryptedDirectoryProvisioningOperations hdfsOperations; | private final HdfsSpecificOrgBindingOperations bindingOperations; |
trustedanalytics/hdfs-broker | src/main/java/org/trustedanalytics/servicebroker/hdfs/users/UaaUsersOperations.java | // Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/config/uaa/UaaConfiguration.java
// @Configuration
// public class UaaConfiguration {
//
// @Value("${uaa.uri}")
// @NotNull
// @Getter @Setter
// private String uri;
//
// @Value("${uaa.tokenUri}")
// @NotNull
// @Getter @Setter
// private String tokenUri;
//
// @Value("${uaa.clientId}")
// @NotNull
// @Getter @Setter
// private String clientId;
//
// @Value("${uaa.clientSecret}")
// @NotNull
// @Getter @Setter
// private String clientSecret;
// }
| import static java.util.Collections.singletonList;
import java.util.UUID;
import org.cloudfoundry.community.servicebroker.exception.ServiceBrokerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.trustedanalytics.cloud.auth.HeaderAddingHttpInterceptor;
import org.trustedanalytics.cloud.uaa.UaaClient;
import org.trustedanalytics.servicebroker.hdfs.config.uaa.UaaConfiguration; | /**
* Copyright (c) 2015 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.trustedanalytics.servicebroker.hdfs.users;
@Component
class UaaUsersOperations {
| // Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/config/uaa/UaaConfiguration.java
// @Configuration
// public class UaaConfiguration {
//
// @Value("${uaa.uri}")
// @NotNull
// @Getter @Setter
// private String uri;
//
// @Value("${uaa.tokenUri}")
// @NotNull
// @Getter @Setter
// private String tokenUri;
//
// @Value("${uaa.clientId}")
// @NotNull
// @Getter @Setter
// private String clientId;
//
// @Value("${uaa.clientSecret}")
// @NotNull
// @Getter @Setter
// private String clientSecret;
// }
// Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/users/UaaUsersOperations.java
import static java.util.Collections.singletonList;
import java.util.UUID;
import org.cloudfoundry.community.servicebroker.exception.ServiceBrokerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.trustedanalytics.cloud.auth.HeaderAddingHttpInterceptor;
import org.trustedanalytics.cloud.uaa.UaaClient;
import org.trustedanalytics.servicebroker.hdfs.config.uaa.UaaConfiguration;
/**
* Copyright (c) 2015 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.trustedanalytics.servicebroker.hdfs.users;
@Component
class UaaUsersOperations {
| private final UaaConfiguration uaaConfiguration; |
trustedanalytics/hdfs-broker | src/main/java/org/trustedanalytics/servicebroker/hdfs/config/hgm/HgmKerberosConfiguration.java | // Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/config/hgm/HgmConfiguration.java
// @Configuration
// public class HgmConfiguration {
//
// @Value("${group.mapping.url}")
// @NotNull
// @Getter @Setter
// private String url;
//
// @Value("${group.mapping.https.username}")
// @Getter @Setter
// private String username;
//
// @Value("${group.mapping.https.password}")
// @Getter @Setter
// private String password;
//
// @Value("${group.mapping.kerberos.principal}")
// @Getter @Setter
// private String principal;
//
// @Value("${group.mapping.kerberos.principalKeyTab}")
// @Getter @Setter
// private String principalKeyTab;
//
// }
| import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.security.kerberos.client.KerberosRestTemplate;
import org.springframework.web.client.RestTemplate;
import org.trustedanalytics.servicebroker.hdfs.config.hgm.HgmConfiguration; | /**
* Copyright (c) 2015 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.trustedanalytics.servicebroker.hdfs.config.hgm;
@Profile("kerberos")
@Configuration
public class HgmKerberosConfiguration {
private static final String KEYTAB_FILE_PATH = "/tmp/hgm.keytab";
@Autowired | // Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/config/hgm/HgmConfiguration.java
// @Configuration
// public class HgmConfiguration {
//
// @Value("${group.mapping.url}")
// @NotNull
// @Getter @Setter
// private String url;
//
// @Value("${group.mapping.https.username}")
// @Getter @Setter
// private String username;
//
// @Value("${group.mapping.https.password}")
// @Getter @Setter
// private String password;
//
// @Value("${group.mapping.kerberos.principal}")
// @Getter @Setter
// private String principal;
//
// @Value("${group.mapping.kerberos.principalKeyTab}")
// @Getter @Setter
// private String principalKeyTab;
//
// }
// Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/config/hgm/HgmKerberosConfiguration.java
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.security.kerberos.client.KerberosRestTemplate;
import org.springframework.web.client.RestTemplate;
import org.trustedanalytics.servicebroker.hdfs.config.hgm.HgmConfiguration;
/**
* Copyright (c) 2015 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.trustedanalytics.servicebroker.hdfs.config.hgm;
@Profile("kerberos")
@Configuration
public class HgmKerberosConfiguration {
private static final String KEYTAB_FILE_PATH = "/tmp/hgm.keytab";
@Autowired | private HgmConfiguration configuration; |
trustedanalytics/hdfs-broker | src/test/java/org/trustedanalytics/servicebroker/hdfs/plans/HdfsPlanMultitenantTest.java | // Path: src/test/java/org/trustedanalytics/servicebroker/hdfs/plans/binding/HdfsBindingClientFactory.java
// public class HdfsBindingClientFactory {
// public static HdfsBindingClient create(Credentials credentials, String userspacePathTemplate){
// return new HdfsBindingClient(credentials, userspacePathTemplate);
// }
// }
| import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
import static org.trustedanalytics.servicebroker.test.cloudfoundry.CfModelsFactory.getServiceInstance;
import java.util.Map;
import org.cloudfoundry.community.servicebroker.model.ServiceInstance;
import org.junit.Test;
import org.trustedanalytics.servicebroker.hdfs.plans.binding.HdfsBindingClientFactory;
import com.google.common.collect.ImmutableMap; | /**
* Copyright (c) 2015 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.trustedanalytics.servicebroker.hdfs.plans;
public final class HdfsPlanMultitenantTest extends HdfsPlanTestBase {
@Test
public void bind_templateWithOrgAndInstanceVariables_replaceInstanceVariableOnlyAndAppendUriToCredentialsMap()
throws Exception {
//arrange
HdfsPlanMultitenant plan = | // Path: src/test/java/org/trustedanalytics/servicebroker/hdfs/plans/binding/HdfsBindingClientFactory.java
// public class HdfsBindingClientFactory {
// public static HdfsBindingClient create(Credentials credentials, String userspacePathTemplate){
// return new HdfsBindingClient(credentials, userspacePathTemplate);
// }
// }
// Path: src/test/java/org/trustedanalytics/servicebroker/hdfs/plans/HdfsPlanMultitenantTest.java
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
import static org.trustedanalytics.servicebroker.test.cloudfoundry.CfModelsFactory.getServiceInstance;
import java.util.Map;
import org.cloudfoundry.community.servicebroker.model.ServiceInstance;
import org.junit.Test;
import org.trustedanalytics.servicebroker.hdfs.plans.binding.HdfsBindingClientFactory;
import com.google.common.collect.ImmutableMap;
/**
* Copyright (c) 2015 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.trustedanalytics.servicebroker.hdfs.plans;
public final class HdfsPlanMultitenantTest extends HdfsPlanTestBase {
@Test
public void bind_templateWithOrgAndInstanceVariables_replaceInstanceVariableOnlyAndAppendUriToCredentialsMap()
throws Exception {
//arrange
HdfsPlanMultitenant plan = | new HdfsPlanMultitenant(HdfsBindingClientFactory.create(getInputCredentials(), USERSPACE_PATH_TEMPLATE)); |
trustedanalytics/hdfs-broker | src/main/java/org/trustedanalytics/servicebroker/hdfs/plans/HdfsPlanMultitenant.java | // Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/plans/binding/HdfsSimpleBindingOperations.java
// public interface HdfsSimpleBindingOperations {
// Map<String, Object> createCredentialsMap(UUID instanceId);
// }
| import java.util.Map;
import java.util.UUID;
import org.cloudfoundry.community.servicebroker.exception.ServiceBrokerException;
import org.cloudfoundry.community.servicebroker.model.ServiceInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.trustedanalytics.servicebroker.framework.service.ServicePlanDefinition;
import org.trustedanalytics.servicebroker.hdfs.plans.binding.HdfsSimpleBindingOperations; | /**
* Copyright (c) 2015 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.trustedanalytics.servicebroker.hdfs.plans;
@Component("multitenant")
class HdfsPlanMultitenant implements ServicePlanDefinition {
| // Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/plans/binding/HdfsSimpleBindingOperations.java
// public interface HdfsSimpleBindingOperations {
// Map<String, Object> createCredentialsMap(UUID instanceId);
// }
// Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/plans/HdfsPlanMultitenant.java
import java.util.Map;
import java.util.UUID;
import org.cloudfoundry.community.servicebroker.exception.ServiceBrokerException;
import org.cloudfoundry.community.servicebroker.model.ServiceInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.trustedanalytics.servicebroker.framework.service.ServicePlanDefinition;
import org.trustedanalytics.servicebroker.hdfs.plans.binding.HdfsSimpleBindingOperations;
/**
* Copyright (c) 2015 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.trustedanalytics.servicebroker.hdfs.plans;
@Component("multitenant")
class HdfsPlanMultitenant implements ServicePlanDefinition {
| private final HdfsSimpleBindingOperations bindingOperations; |
trustedanalytics/hdfs-broker | src/test/java/org/trustedanalytics/servicebroker/hdfs/plans/HdfsPlanEncryptedTest.java | // Path: src/test/java/org/trustedanalytics/servicebroker/hdfs/plans/binding/HdfsBindingClientFactory.java
// public class HdfsBindingClientFactory {
// public static HdfsBindingClient create(Credentials credentials, String userspacePathTemplate){
// return new HdfsBindingClient(credentials, userspacePathTemplate);
// }
// }
//
// Path: src/test/java/org/trustedanalytics/servicebroker/hdfs/plans/provisioning/HdfsProvisioningClientFactory.java
// public class HdfsProvisioningClientFactory {
// public static HdfsProvisioningClient create(HdfsClient hdfsClient, HdfsClient encryptedHdfsClient,
// String userspacePathTemplate) {
// return new HdfsProvisioningClient(hdfsClient, encryptedHdfsClient, userspacePathTemplate);
// }
// }
| import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.*;
import static org.trustedanalytics.servicebroker.test.cloudfoundry.CfModelsFactory.getServiceInstance;
import java.io.IOException;
import java.util.Map;
import java.util.Optional;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.permission.FsAction;
import org.apache.hadoop.fs.permission.FsPermission;
import org.cloudfoundry.community.servicebroker.exception.ServiceBrokerException;
import org.cloudfoundry.community.servicebroker.model.ServiceInstance;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.trustedanalytics.cfbroker.store.hdfs.service.HdfsClient;
import org.trustedanalytics.servicebroker.hdfs.plans.binding.HdfsBindingClientFactory;
import org.trustedanalytics.servicebroker.hdfs.plans.provisioning.HdfsProvisioningClientFactory;
import com.google.common.collect.ImmutableMap; | /**
* Copyright (c) 2015 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.trustedanalytics.servicebroker.hdfs.plans;
@RunWith(MockitoJUnitRunner.class)
public final class HdfsPlanEncryptedTest extends HdfsPlanTestBase {
private static final FsPermission FS_PERMISSION = new FsPermission(FsAction.ALL, FsAction.ALL,
FsAction.NONE);
private HdfsPlanEncrypted planUnderTest;
@Mock
private HdfsClient hdfsClient;
@Mock
private HdfsClient encryptedHdfsClient;
@Before
public void setup() {
planUnderTest = new HdfsPlanEncrypted( | // Path: src/test/java/org/trustedanalytics/servicebroker/hdfs/plans/binding/HdfsBindingClientFactory.java
// public class HdfsBindingClientFactory {
// public static HdfsBindingClient create(Credentials credentials, String userspacePathTemplate){
// return new HdfsBindingClient(credentials, userspacePathTemplate);
// }
// }
//
// Path: src/test/java/org/trustedanalytics/servicebroker/hdfs/plans/provisioning/HdfsProvisioningClientFactory.java
// public class HdfsProvisioningClientFactory {
// public static HdfsProvisioningClient create(HdfsClient hdfsClient, HdfsClient encryptedHdfsClient,
// String userspacePathTemplate) {
// return new HdfsProvisioningClient(hdfsClient, encryptedHdfsClient, userspacePathTemplate);
// }
// }
// Path: src/test/java/org/trustedanalytics/servicebroker/hdfs/plans/HdfsPlanEncryptedTest.java
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.*;
import static org.trustedanalytics.servicebroker.test.cloudfoundry.CfModelsFactory.getServiceInstance;
import java.io.IOException;
import java.util.Map;
import java.util.Optional;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.permission.FsAction;
import org.apache.hadoop.fs.permission.FsPermission;
import org.cloudfoundry.community.servicebroker.exception.ServiceBrokerException;
import org.cloudfoundry.community.servicebroker.model.ServiceInstance;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.trustedanalytics.cfbroker.store.hdfs.service.HdfsClient;
import org.trustedanalytics.servicebroker.hdfs.plans.binding.HdfsBindingClientFactory;
import org.trustedanalytics.servicebroker.hdfs.plans.provisioning.HdfsProvisioningClientFactory;
import com.google.common.collect.ImmutableMap;
/**
* Copyright (c) 2015 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.trustedanalytics.servicebroker.hdfs.plans;
@RunWith(MockitoJUnitRunner.class)
public final class HdfsPlanEncryptedTest extends HdfsPlanTestBase {
private static final FsPermission FS_PERMISSION = new FsPermission(FsAction.ALL, FsAction.ALL,
FsAction.NONE);
private HdfsPlanEncrypted planUnderTest;
@Mock
private HdfsClient hdfsClient;
@Mock
private HdfsClient encryptedHdfsClient;
@Before
public void setup() {
planUnderTest = new HdfsPlanEncrypted( | HdfsProvisioningClientFactory.create(hdfsClient, encryptedHdfsClient, USERSPACE_PATH_TEMPLATE), |
trustedanalytics/hdfs-broker | src/test/java/org/trustedanalytics/servicebroker/hdfs/plans/HdfsPlanEncryptedTest.java | // Path: src/test/java/org/trustedanalytics/servicebroker/hdfs/plans/binding/HdfsBindingClientFactory.java
// public class HdfsBindingClientFactory {
// public static HdfsBindingClient create(Credentials credentials, String userspacePathTemplate){
// return new HdfsBindingClient(credentials, userspacePathTemplate);
// }
// }
//
// Path: src/test/java/org/trustedanalytics/servicebroker/hdfs/plans/provisioning/HdfsProvisioningClientFactory.java
// public class HdfsProvisioningClientFactory {
// public static HdfsProvisioningClient create(HdfsClient hdfsClient, HdfsClient encryptedHdfsClient,
// String userspacePathTemplate) {
// return new HdfsProvisioningClient(hdfsClient, encryptedHdfsClient, userspacePathTemplate);
// }
// }
| import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.*;
import static org.trustedanalytics.servicebroker.test.cloudfoundry.CfModelsFactory.getServiceInstance;
import java.io.IOException;
import java.util.Map;
import java.util.Optional;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.permission.FsAction;
import org.apache.hadoop.fs.permission.FsPermission;
import org.cloudfoundry.community.servicebroker.exception.ServiceBrokerException;
import org.cloudfoundry.community.servicebroker.model.ServiceInstance;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.trustedanalytics.cfbroker.store.hdfs.service.HdfsClient;
import org.trustedanalytics.servicebroker.hdfs.plans.binding.HdfsBindingClientFactory;
import org.trustedanalytics.servicebroker.hdfs.plans.provisioning.HdfsProvisioningClientFactory;
import com.google.common.collect.ImmutableMap; | /**
* Copyright (c) 2015 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.trustedanalytics.servicebroker.hdfs.plans;
@RunWith(MockitoJUnitRunner.class)
public final class HdfsPlanEncryptedTest extends HdfsPlanTestBase {
private static final FsPermission FS_PERMISSION = new FsPermission(FsAction.ALL, FsAction.ALL,
FsAction.NONE);
private HdfsPlanEncrypted planUnderTest;
@Mock
private HdfsClient hdfsClient;
@Mock
private HdfsClient encryptedHdfsClient;
@Before
public void setup() {
planUnderTest = new HdfsPlanEncrypted(
HdfsProvisioningClientFactory.create(hdfsClient, encryptedHdfsClient, USERSPACE_PATH_TEMPLATE), | // Path: src/test/java/org/trustedanalytics/servicebroker/hdfs/plans/binding/HdfsBindingClientFactory.java
// public class HdfsBindingClientFactory {
// public static HdfsBindingClient create(Credentials credentials, String userspacePathTemplate){
// return new HdfsBindingClient(credentials, userspacePathTemplate);
// }
// }
//
// Path: src/test/java/org/trustedanalytics/servicebroker/hdfs/plans/provisioning/HdfsProvisioningClientFactory.java
// public class HdfsProvisioningClientFactory {
// public static HdfsProvisioningClient create(HdfsClient hdfsClient, HdfsClient encryptedHdfsClient,
// String userspacePathTemplate) {
// return new HdfsProvisioningClient(hdfsClient, encryptedHdfsClient, userspacePathTemplate);
// }
// }
// Path: src/test/java/org/trustedanalytics/servicebroker/hdfs/plans/HdfsPlanEncryptedTest.java
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.*;
import static org.trustedanalytics.servicebroker.test.cloudfoundry.CfModelsFactory.getServiceInstance;
import java.io.IOException;
import java.util.Map;
import java.util.Optional;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.permission.FsAction;
import org.apache.hadoop.fs.permission.FsPermission;
import org.cloudfoundry.community.servicebroker.exception.ServiceBrokerException;
import org.cloudfoundry.community.servicebroker.model.ServiceInstance;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.trustedanalytics.cfbroker.store.hdfs.service.HdfsClient;
import org.trustedanalytics.servicebroker.hdfs.plans.binding.HdfsBindingClientFactory;
import org.trustedanalytics.servicebroker.hdfs.plans.provisioning.HdfsProvisioningClientFactory;
import com.google.common.collect.ImmutableMap;
/**
* Copyright (c) 2015 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.trustedanalytics.servicebroker.hdfs.plans;
@RunWith(MockitoJUnitRunner.class)
public final class HdfsPlanEncryptedTest extends HdfsPlanTestBase {
private static final FsPermission FS_PERMISSION = new FsPermission(FsAction.ALL, FsAction.ALL,
FsAction.NONE);
private HdfsPlanEncrypted planUnderTest;
@Mock
private HdfsClient hdfsClient;
@Mock
private HdfsClient encryptedHdfsClient;
@Before
public void setup() {
planUnderTest = new HdfsPlanEncrypted(
HdfsProvisioningClientFactory.create(hdfsClient, encryptedHdfsClient, USERSPACE_PATH_TEMPLATE), | HdfsBindingClientFactory.create(getInputCredentials(), USERSPACE_PATH_TEMPLATE)); |
trustedanalytics/hdfs-broker | src/test/java/org/trustedanalytics/servicebroker/hdfs/integration/CreateDeleteThenGetTest.java | // Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/config/Application.java
// @EnableAutoConfiguration
// @EnableServiceBrokerConfig
// @EnableZookeeperBrokerStore
// @ComponentScan
// public class Application {
//
// public Application() {}
//
// public static void main(String[] args) {
// SpringApplication.run(Application.class, args);
// }
// }
//
// Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/config/ExternalConfiguration.java
// @Configuration
// public class ExternalConfiguration {
//
// @Value("${store.user}")
// @NotNull
// @Getter @Setter
// private String user;
//
// @Value("${store.password}")
// @NotNull
// @Getter @Setter
// private String password;
//
// @Value("${hdfs.userspace.chroot}")
// @NotNull
// @Getter @Setter
// private String userspaceChroot;
//
// @Value("${hdfs.provided.zip}")
// @NotNull
// @Getter @Setter
// private String hdfsProvidedZip;
//
// @Value("${hdfs.superuser}")
// @NotNull
// @Getter @Setter
// private String hdfsSuperuser;
//
// @Value("${hdfs.keytab}")
// @NotNull
// @Getter @Setter
// private String hdfsSuperuserKeytab;
//
// }
//
// Path: src/test/java/org/trustedanalytics/servicebroker/hdfs/integration/config/HdfsLocalConfiguration.java
// @Configuration
// @Profile("integration-test")
// public class HdfsLocalConfiguration {
//
// @Autowired
// private ExternalConfiguration externalConfiguration;
//
// @Bean
// @Qualifier("user")
// public FileSystem getUserFileSystem() throws InterruptedException, IOException,
// URISyntaxException {
// return FileSystemFactory.getFileSystem(externalConfiguration.getUserspaceChroot());
// }
//
// @Bean
// @Qualifier("superUser")
// public FileSystem getSuperUserFileSystem() throws InterruptedException, IOException,
// URISyntaxException {
// return FileSystemFactory.getFileSystem(externalConfiguration.getUserspaceChroot());
// }
//
// static class FileSystemFactory {
// private static FileSystem fileSystem;
//
// public static FileSystem getFileSystem(String userspace) throws IOException,
// InterruptedException, URISyntaxException {
// if (fileSystem == null) {
// File baseDir = new File("./target/hdfs/" + "testName").getAbsoluteFile();
// FileUtil.fullyDelete(baseDir);
// org.apache.hadoop.conf.Configuration conf = new org.apache.hadoop.conf.Configuration(false);
// conf.set(MiniDFSCluster.HDFS_MINIDFS_BASEDIR, baseDir.getAbsolutePath());
// MiniDFSCluster.Builder builder = new MiniDFSCluster.Builder(conf);
// MiniDFSCluster cluster = builder.build();
// fileSystem = cluster.getFileSystem();
//
// tryMkdirOrThrowException(fileSystem, userspace);
// }
// return fileSystem;
// }
//
// private static void tryMkdirOrThrowException(FileSystem fs, String path) throws IOException {
// if (!fs.mkdirs(new Path(path))) {
// throw new RuntimeException("Failure when try to create test root dir: " + path);
// }
// }
// }
// }
| import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.nullValue;
import static org.hamcrest.core.Is.is;
import static org.trustedanalytics.servicebroker.test.cloudfoundry.CfModelsFactory.getCreateBindingRequest;
import static org.trustedanalytics.servicebroker.test.cloudfoundry.CfModelsFactory.getCreateInstanceRequest;
import static org.trustedanalytics.servicebroker.test.cloudfoundry.CfModelsFactory.getDeleteBindingRequest;
import static org.trustedanalytics.servicebroker.test.cloudfoundry.CfModelsFactory.getDeleteInstanceRequest;
import static org.trustedanalytics.servicebroker.test.cloudfoundry.CfModelsFactory.getServiceInstance;
import java.io.IOException;
import java.util.UUID;
import org.cloudfoundry.community.servicebroker.model.CreateServiceInstanceBindingRequest;
import org.cloudfoundry.community.servicebroker.model.CreateServiceInstanceRequest;
import org.cloudfoundry.community.servicebroker.model.DeleteServiceInstanceBindingRequest;
import org.cloudfoundry.community.servicebroker.model.DeleteServiceInstanceRequest;
import org.cloudfoundry.community.servicebroker.model.ServiceInstance;
import org.cloudfoundry.community.servicebroker.service.ServiceInstanceBindingService;
import org.cloudfoundry.community.servicebroker.service.ServiceInstanceService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.IntegrationTest;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.trustedanalytics.cfbroker.store.zookeeper.service.ZookeeperClient;
import org.trustedanalytics.servicebroker.hdfs.config.Application;
import org.trustedanalytics.servicebroker.hdfs.config.ExternalConfiguration;
import org.trustedanalytics.servicebroker.hdfs.integration.config.HdfsLocalConfiguration; | /**
* Copyright (c) 2015 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.trustedanalytics.servicebroker.hdfs.integration;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = {Application.class, HdfsLocalConfiguration.class})
@WebAppConfiguration
@IntegrationTest("server.port=0")
@ActiveProfiles("integration-test")
public class CreateDeleteThenGetTest {
@Autowired
private ZookeeperClient zkClient;
@Autowired | // Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/config/Application.java
// @EnableAutoConfiguration
// @EnableServiceBrokerConfig
// @EnableZookeeperBrokerStore
// @ComponentScan
// public class Application {
//
// public Application() {}
//
// public static void main(String[] args) {
// SpringApplication.run(Application.class, args);
// }
// }
//
// Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/config/ExternalConfiguration.java
// @Configuration
// public class ExternalConfiguration {
//
// @Value("${store.user}")
// @NotNull
// @Getter @Setter
// private String user;
//
// @Value("${store.password}")
// @NotNull
// @Getter @Setter
// private String password;
//
// @Value("${hdfs.userspace.chroot}")
// @NotNull
// @Getter @Setter
// private String userspaceChroot;
//
// @Value("${hdfs.provided.zip}")
// @NotNull
// @Getter @Setter
// private String hdfsProvidedZip;
//
// @Value("${hdfs.superuser}")
// @NotNull
// @Getter @Setter
// private String hdfsSuperuser;
//
// @Value("${hdfs.keytab}")
// @NotNull
// @Getter @Setter
// private String hdfsSuperuserKeytab;
//
// }
//
// Path: src/test/java/org/trustedanalytics/servicebroker/hdfs/integration/config/HdfsLocalConfiguration.java
// @Configuration
// @Profile("integration-test")
// public class HdfsLocalConfiguration {
//
// @Autowired
// private ExternalConfiguration externalConfiguration;
//
// @Bean
// @Qualifier("user")
// public FileSystem getUserFileSystem() throws InterruptedException, IOException,
// URISyntaxException {
// return FileSystemFactory.getFileSystem(externalConfiguration.getUserspaceChroot());
// }
//
// @Bean
// @Qualifier("superUser")
// public FileSystem getSuperUserFileSystem() throws InterruptedException, IOException,
// URISyntaxException {
// return FileSystemFactory.getFileSystem(externalConfiguration.getUserspaceChroot());
// }
//
// static class FileSystemFactory {
// private static FileSystem fileSystem;
//
// public static FileSystem getFileSystem(String userspace) throws IOException,
// InterruptedException, URISyntaxException {
// if (fileSystem == null) {
// File baseDir = new File("./target/hdfs/" + "testName").getAbsoluteFile();
// FileUtil.fullyDelete(baseDir);
// org.apache.hadoop.conf.Configuration conf = new org.apache.hadoop.conf.Configuration(false);
// conf.set(MiniDFSCluster.HDFS_MINIDFS_BASEDIR, baseDir.getAbsolutePath());
// MiniDFSCluster.Builder builder = new MiniDFSCluster.Builder(conf);
// MiniDFSCluster cluster = builder.build();
// fileSystem = cluster.getFileSystem();
//
// tryMkdirOrThrowException(fileSystem, userspace);
// }
// return fileSystem;
// }
//
// private static void tryMkdirOrThrowException(FileSystem fs, String path) throws IOException {
// if (!fs.mkdirs(new Path(path))) {
// throw new RuntimeException("Failure when try to create test root dir: " + path);
// }
// }
// }
// }
// Path: src/test/java/org/trustedanalytics/servicebroker/hdfs/integration/CreateDeleteThenGetTest.java
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.nullValue;
import static org.hamcrest.core.Is.is;
import static org.trustedanalytics.servicebroker.test.cloudfoundry.CfModelsFactory.getCreateBindingRequest;
import static org.trustedanalytics.servicebroker.test.cloudfoundry.CfModelsFactory.getCreateInstanceRequest;
import static org.trustedanalytics.servicebroker.test.cloudfoundry.CfModelsFactory.getDeleteBindingRequest;
import static org.trustedanalytics.servicebroker.test.cloudfoundry.CfModelsFactory.getDeleteInstanceRequest;
import static org.trustedanalytics.servicebroker.test.cloudfoundry.CfModelsFactory.getServiceInstance;
import java.io.IOException;
import java.util.UUID;
import org.cloudfoundry.community.servicebroker.model.CreateServiceInstanceBindingRequest;
import org.cloudfoundry.community.servicebroker.model.CreateServiceInstanceRequest;
import org.cloudfoundry.community.servicebroker.model.DeleteServiceInstanceBindingRequest;
import org.cloudfoundry.community.servicebroker.model.DeleteServiceInstanceRequest;
import org.cloudfoundry.community.servicebroker.model.ServiceInstance;
import org.cloudfoundry.community.servicebroker.service.ServiceInstanceBindingService;
import org.cloudfoundry.community.servicebroker.service.ServiceInstanceService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.IntegrationTest;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.trustedanalytics.cfbroker.store.zookeeper.service.ZookeeperClient;
import org.trustedanalytics.servicebroker.hdfs.config.Application;
import org.trustedanalytics.servicebroker.hdfs.config.ExternalConfiguration;
import org.trustedanalytics.servicebroker.hdfs.integration.config.HdfsLocalConfiguration;
/**
* Copyright (c) 2015 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.trustedanalytics.servicebroker.hdfs.integration;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = {Application.class, HdfsLocalConfiguration.class})
@WebAppConfiguration
@IntegrationTest("server.port=0")
@ActiveProfiles("integration-test")
public class CreateDeleteThenGetTest {
@Autowired
private ZookeeperClient zkClient;
@Autowired | private ExternalConfiguration conf; |
trustedanalytics/hdfs-broker | src/main/java/org/trustedanalytics/servicebroker/hdfs/config/ServiceInstanceBindingConfig.java | // Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/config/HdfsConstants.java
// public static final String HADOOP_DEFAULT_FS = "fs.defaultFS";
| import static org.trustedanalytics.servicebroker.hdfs.config.HdfsConstants.HADOOP_DEFAULT_FS;
import java.io.IOException;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.trustedanalytics.cfbroker.config.HadoopZipConfiguration;
import org.trustedanalytics.servicebroker.framework.Credentials;
import com.google.common.collect.ImmutableMap;
import org.trustedanalytics.servicebroker.framework.kerberos.KerberosProperties; | /**
* Copyright (c) 2015 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.trustedanalytics.servicebroker.hdfs.config;
@Configuration
public class ServiceInstanceBindingConfig {
@Autowired
private ExternalConfiguration configuration;
@Autowired
private KerberosProperties kerberosProperties;
@Bean
public Credentials getCredentials() throws IOException {
HadoopZipConfiguration hadoopZipConfiguration =
HadoopZipConfiguration.createHadoopZipConfiguration(configuration.getHdfsProvidedZip());
Map<String, String> configParams = hadoopZipConfiguration.getAsParameterMap(); | // Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/config/HdfsConstants.java
// public static final String HADOOP_DEFAULT_FS = "fs.defaultFS";
// Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/config/ServiceInstanceBindingConfig.java
import static org.trustedanalytics.servicebroker.hdfs.config.HdfsConstants.HADOOP_DEFAULT_FS;
import java.io.IOException;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.trustedanalytics.cfbroker.config.HadoopZipConfiguration;
import org.trustedanalytics.servicebroker.framework.Credentials;
import com.google.common.collect.ImmutableMap;
import org.trustedanalytics.servicebroker.framework.kerberos.KerberosProperties;
/**
* Copyright (c) 2015 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.trustedanalytics.servicebroker.hdfs.config;
@Configuration
public class ServiceInstanceBindingConfig {
@Autowired
private ExternalConfiguration configuration;
@Autowired
private KerberosProperties kerberosProperties;
@Bean
public Credentials getCredentials() throws IOException {
HadoopZipConfiguration hadoopZipConfiguration =
HadoopZipConfiguration.createHadoopZipConfiguration(configuration.getHdfsProvidedZip());
Map<String, String> configParams = hadoopZipConfiguration.getAsParameterMap(); | if (!configParams.containsKey(HADOOP_DEFAULT_FS)) { |
trustedanalytics/hdfs-broker | src/main/java/org/trustedanalytics/servicebroker/hdfs/plans/HdfsPlanShared.java | // Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/plans/binding/HdfsSpecificOrgBindingOperations.java
// public interface HdfsSpecificOrgBindingOperations {
// Map<String, Object> createCredentialsMap(UUID instanceId, UUID orgId);
// }
//
// Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/plans/provisioning/HdfsDirectoryProvisioningOperations.java
// public interface HdfsDirectoryProvisioningOperations {
// void provisionDirectory(UUID instanceId, UUID orgId) throws ServiceBrokerException;
// void provisionDirectory(UUID instanceId, UUID orgId, UUID owner) throws ServiceBrokerException;
// }
| import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import org.cloudfoundry.community.servicebroker.exception.ServiceBrokerException;
import org.cloudfoundry.community.servicebroker.exception.ServiceInstanceExistsException;
import org.cloudfoundry.community.servicebroker.model.ServiceInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.trustedanalytics.servicebroker.framework.service.ServicePlanDefinition;
import org.trustedanalytics.servicebroker.hdfs.plans.binding.HdfsSpecificOrgBindingOperations;
import org.trustedanalytics.servicebroker.hdfs.plans.provisioning.HdfsDirectoryProvisioningOperations; | /**
* Copyright (c) 2015 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.trustedanalytics.servicebroker.hdfs.plans;
@Component("shared")
class HdfsPlanShared implements ServicePlanDefinition {
| // Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/plans/binding/HdfsSpecificOrgBindingOperations.java
// public interface HdfsSpecificOrgBindingOperations {
// Map<String, Object> createCredentialsMap(UUID instanceId, UUID orgId);
// }
//
// Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/plans/provisioning/HdfsDirectoryProvisioningOperations.java
// public interface HdfsDirectoryProvisioningOperations {
// void provisionDirectory(UUID instanceId, UUID orgId) throws ServiceBrokerException;
// void provisionDirectory(UUID instanceId, UUID orgId, UUID owner) throws ServiceBrokerException;
// }
// Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/plans/HdfsPlanShared.java
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import org.cloudfoundry.community.servicebroker.exception.ServiceBrokerException;
import org.cloudfoundry.community.servicebroker.exception.ServiceInstanceExistsException;
import org.cloudfoundry.community.servicebroker.model.ServiceInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.trustedanalytics.servicebroker.framework.service.ServicePlanDefinition;
import org.trustedanalytics.servicebroker.hdfs.plans.binding.HdfsSpecificOrgBindingOperations;
import org.trustedanalytics.servicebroker.hdfs.plans.provisioning.HdfsDirectoryProvisioningOperations;
/**
* Copyright (c) 2015 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.trustedanalytics.servicebroker.hdfs.plans;
@Component("shared")
class HdfsPlanShared implements ServicePlanDefinition {
| private final HdfsDirectoryProvisioningOperations hdfsOperations; |
trustedanalytics/hdfs-broker | src/main/java/org/trustedanalytics/servicebroker/hdfs/plans/HdfsPlanShared.java | // Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/plans/binding/HdfsSpecificOrgBindingOperations.java
// public interface HdfsSpecificOrgBindingOperations {
// Map<String, Object> createCredentialsMap(UUID instanceId, UUID orgId);
// }
//
// Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/plans/provisioning/HdfsDirectoryProvisioningOperations.java
// public interface HdfsDirectoryProvisioningOperations {
// void provisionDirectory(UUID instanceId, UUID orgId) throws ServiceBrokerException;
// void provisionDirectory(UUID instanceId, UUID orgId, UUID owner) throws ServiceBrokerException;
// }
| import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import org.cloudfoundry.community.servicebroker.exception.ServiceBrokerException;
import org.cloudfoundry.community.servicebroker.exception.ServiceInstanceExistsException;
import org.cloudfoundry.community.servicebroker.model.ServiceInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.trustedanalytics.servicebroker.framework.service.ServicePlanDefinition;
import org.trustedanalytics.servicebroker.hdfs.plans.binding.HdfsSpecificOrgBindingOperations;
import org.trustedanalytics.servicebroker.hdfs.plans.provisioning.HdfsDirectoryProvisioningOperations; | /**
* Copyright (c) 2015 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.trustedanalytics.servicebroker.hdfs.plans;
@Component("shared")
class HdfsPlanShared implements ServicePlanDefinition {
private final HdfsDirectoryProvisioningOperations hdfsOperations; | // Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/plans/binding/HdfsSpecificOrgBindingOperations.java
// public interface HdfsSpecificOrgBindingOperations {
// Map<String, Object> createCredentialsMap(UUID instanceId, UUID orgId);
// }
//
// Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/plans/provisioning/HdfsDirectoryProvisioningOperations.java
// public interface HdfsDirectoryProvisioningOperations {
// void provisionDirectory(UUID instanceId, UUID orgId) throws ServiceBrokerException;
// void provisionDirectory(UUID instanceId, UUID orgId, UUID owner) throws ServiceBrokerException;
// }
// Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/plans/HdfsPlanShared.java
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import org.cloudfoundry.community.servicebroker.exception.ServiceBrokerException;
import org.cloudfoundry.community.servicebroker.exception.ServiceInstanceExistsException;
import org.cloudfoundry.community.servicebroker.model.ServiceInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.trustedanalytics.servicebroker.framework.service.ServicePlanDefinition;
import org.trustedanalytics.servicebroker.hdfs.plans.binding.HdfsSpecificOrgBindingOperations;
import org.trustedanalytics.servicebroker.hdfs.plans.provisioning.HdfsDirectoryProvisioningOperations;
/**
* Copyright (c) 2015 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.trustedanalytics.servicebroker.hdfs.plans;
@Component("shared")
class HdfsPlanShared implements ServicePlanDefinition {
private final HdfsDirectoryProvisioningOperations hdfsOperations; | private final HdfsSpecificOrgBindingOperations bindingOperations; |
trustedanalytics/hdfs-broker | src/main/java/org/trustedanalytics/servicebroker/hdfs/users/UaaClientTokenRetriver.java | // Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/config/uaa/UaaConfiguration.java
// @Configuration
// public class UaaConfiguration {
//
// @Value("${uaa.uri}")
// @NotNull
// @Getter @Setter
// private String uri;
//
// @Value("${uaa.tokenUri}")
// @NotNull
// @Getter @Setter
// private String tokenUri;
//
// @Value("${uaa.clientId}")
// @NotNull
// @Getter @Setter
// private String clientId;
//
// @Value("${uaa.clientSecret}")
// @NotNull
// @Getter @Setter
// private String clientSecret;
// }
//
// Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/users/entity/UaaTokenResponse.java
// @Data
// public final class UaaTokenResponse {
// private final String jti;
// private final String scope;
// private final Integer expires;
// private final String tokenType;
// private final String accessToken;
//
// @JsonCreator
// public UaaTokenResponse(@JsonProperty("jti") String jti,
// @JsonProperty("scope") String scope,
// @JsonProperty("expires_in") Integer expires,
// @JsonProperty("token_type") String tokenType,
// @JsonProperty("access_token") String accessToken){
// this.jti = jti;
// this.scope = scope;
// this.expires = expires;
// this.tokenType = tokenType;
// this.accessToken = accessToken;
// }
// }
| import org.springframework.web.util.UriComponentsBuilder;
import org.trustedanalytics.servicebroker.hdfs.config.uaa.UaaConfiguration;
import org.trustedanalytics.servicebroker.hdfs.users.entity.UaaTokenResponse;
import java.net.URI;
import java.util.Arrays;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate; | /**
* Copyright (c) 2015 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.trustedanalytics.servicebroker.hdfs.users;
@Component
class UaaClientTokenRetriver {
private static final String GRANT_TYPE = "grant_type";
private static final String GRANT_TYPE_CREDENTIALS = "client_credentials";
private static final String RESPONSE_TYPE = "response_type";
private static final String RESPONSE_TYPE_TOKEN = "token";
private static final String PARAMETERS = "paramteres";
| // Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/config/uaa/UaaConfiguration.java
// @Configuration
// public class UaaConfiguration {
//
// @Value("${uaa.uri}")
// @NotNull
// @Getter @Setter
// private String uri;
//
// @Value("${uaa.tokenUri}")
// @NotNull
// @Getter @Setter
// private String tokenUri;
//
// @Value("${uaa.clientId}")
// @NotNull
// @Getter @Setter
// private String clientId;
//
// @Value("${uaa.clientSecret}")
// @NotNull
// @Getter @Setter
// private String clientSecret;
// }
//
// Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/users/entity/UaaTokenResponse.java
// @Data
// public final class UaaTokenResponse {
// private final String jti;
// private final String scope;
// private final Integer expires;
// private final String tokenType;
// private final String accessToken;
//
// @JsonCreator
// public UaaTokenResponse(@JsonProperty("jti") String jti,
// @JsonProperty("scope") String scope,
// @JsonProperty("expires_in") Integer expires,
// @JsonProperty("token_type") String tokenType,
// @JsonProperty("access_token") String accessToken){
// this.jti = jti;
// this.scope = scope;
// this.expires = expires;
// this.tokenType = tokenType;
// this.accessToken = accessToken;
// }
// }
// Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/users/UaaClientTokenRetriver.java
import org.springframework.web.util.UriComponentsBuilder;
import org.trustedanalytics.servicebroker.hdfs.config.uaa.UaaConfiguration;
import org.trustedanalytics.servicebroker.hdfs.users.entity.UaaTokenResponse;
import java.net.URI;
import java.util.Arrays;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
/**
* Copyright (c) 2015 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.trustedanalytics.servicebroker.hdfs.users;
@Component
class UaaClientTokenRetriver {
private static final String GRANT_TYPE = "grant_type";
private static final String GRANT_TYPE_CREDENTIALS = "client_credentials";
private static final String RESPONSE_TYPE = "response_type";
private static final String RESPONSE_TYPE_TOKEN = "token";
private static final String PARAMETERS = "paramteres";
| private final UaaConfiguration uaaConfiguration; |
trustedanalytics/hdfs-broker | src/main/java/org/trustedanalytics/servicebroker/hdfs/users/UaaClientTokenRetriver.java | // Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/config/uaa/UaaConfiguration.java
// @Configuration
// public class UaaConfiguration {
//
// @Value("${uaa.uri}")
// @NotNull
// @Getter @Setter
// private String uri;
//
// @Value("${uaa.tokenUri}")
// @NotNull
// @Getter @Setter
// private String tokenUri;
//
// @Value("${uaa.clientId}")
// @NotNull
// @Getter @Setter
// private String clientId;
//
// @Value("${uaa.clientSecret}")
// @NotNull
// @Getter @Setter
// private String clientSecret;
// }
//
// Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/users/entity/UaaTokenResponse.java
// @Data
// public final class UaaTokenResponse {
// private final String jti;
// private final String scope;
// private final Integer expires;
// private final String tokenType;
// private final String accessToken;
//
// @JsonCreator
// public UaaTokenResponse(@JsonProperty("jti") String jti,
// @JsonProperty("scope") String scope,
// @JsonProperty("expires_in") Integer expires,
// @JsonProperty("token_type") String tokenType,
// @JsonProperty("access_token") String accessToken){
// this.jti = jti;
// this.scope = scope;
// this.expires = expires;
// this.tokenType = tokenType;
// this.accessToken = accessToken;
// }
// }
| import org.springframework.web.util.UriComponentsBuilder;
import org.trustedanalytics.servicebroker.hdfs.config.uaa.UaaConfiguration;
import org.trustedanalytics.servicebroker.hdfs.users.entity.UaaTokenResponse;
import java.net.URI;
import java.util.Arrays;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate; | /**
* Copyright (c) 2015 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.trustedanalytics.servicebroker.hdfs.users;
@Component
class UaaClientTokenRetriver {
private static final String GRANT_TYPE = "grant_type";
private static final String GRANT_TYPE_CREDENTIALS = "client_credentials";
private static final String RESPONSE_TYPE = "response_type";
private static final String RESPONSE_TYPE_TOKEN = "token";
private static final String PARAMETERS = "paramteres";
private final UaaConfiguration uaaConfiguration;
private final RestTemplate uaaRestTemplate;
@Autowired
public UaaClientTokenRetriver(UaaConfiguration configuration) {
this.uaaConfiguration = configuration;
this.uaaRestTemplate = createRestTemplate();
}
public String getToken() {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
URI uaaUri =
UriComponentsBuilder.fromHttpUrl(uaaConfiguration.getTokenUri())
.queryParam(GRANT_TYPE, GRANT_TYPE_CREDENTIALS)
.queryParam(RESPONSE_TYPE, RESPONSE_TYPE_TOKEN).build().encode().toUri();
HttpEntity<String> entity = new HttpEntity<>(PARAMETERS, headers); | // Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/config/uaa/UaaConfiguration.java
// @Configuration
// public class UaaConfiguration {
//
// @Value("${uaa.uri}")
// @NotNull
// @Getter @Setter
// private String uri;
//
// @Value("${uaa.tokenUri}")
// @NotNull
// @Getter @Setter
// private String tokenUri;
//
// @Value("${uaa.clientId}")
// @NotNull
// @Getter @Setter
// private String clientId;
//
// @Value("${uaa.clientSecret}")
// @NotNull
// @Getter @Setter
// private String clientSecret;
// }
//
// Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/users/entity/UaaTokenResponse.java
// @Data
// public final class UaaTokenResponse {
// private final String jti;
// private final String scope;
// private final Integer expires;
// private final String tokenType;
// private final String accessToken;
//
// @JsonCreator
// public UaaTokenResponse(@JsonProperty("jti") String jti,
// @JsonProperty("scope") String scope,
// @JsonProperty("expires_in") Integer expires,
// @JsonProperty("token_type") String tokenType,
// @JsonProperty("access_token") String accessToken){
// this.jti = jti;
// this.scope = scope;
// this.expires = expires;
// this.tokenType = tokenType;
// this.accessToken = accessToken;
// }
// }
// Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/users/UaaClientTokenRetriver.java
import org.springframework.web.util.UriComponentsBuilder;
import org.trustedanalytics.servicebroker.hdfs.config.uaa.UaaConfiguration;
import org.trustedanalytics.servicebroker.hdfs.users.entity.UaaTokenResponse;
import java.net.URI;
import java.util.Arrays;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
/**
* Copyright (c) 2015 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.trustedanalytics.servicebroker.hdfs.users;
@Component
class UaaClientTokenRetriver {
private static final String GRANT_TYPE = "grant_type";
private static final String GRANT_TYPE_CREDENTIALS = "client_credentials";
private static final String RESPONSE_TYPE = "response_type";
private static final String RESPONSE_TYPE_TOKEN = "token";
private static final String PARAMETERS = "paramteres";
private final UaaConfiguration uaaConfiguration;
private final RestTemplate uaaRestTemplate;
@Autowired
public UaaClientTokenRetriver(UaaConfiguration configuration) {
this.uaaConfiguration = configuration;
this.uaaRestTemplate = createRestTemplate();
}
public String getToken() {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
URI uaaUri =
UriComponentsBuilder.fromHttpUrl(uaaConfiguration.getTokenUri())
.queryParam(GRANT_TYPE, GRANT_TYPE_CREDENTIALS)
.queryParam(RESPONSE_TYPE, RESPONSE_TYPE_TOKEN).build().encode().toUri();
HttpEntity<String> entity = new HttpEntity<>(PARAMETERS, headers); | return uaaRestTemplate.postForObject(uaaUri, entity, UaaTokenResponse.class).getAccessToken(); |
trustedanalytics/hdfs-broker | src/main/java/org/trustedanalytics/servicebroker/hdfs/users/GroupMappingOperations.java | // Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/config/hgm/HgmConfiguration.java
// @Configuration
// public class HgmConfiguration {
//
// @Value("${group.mapping.url}")
// @NotNull
// @Getter @Setter
// private String url;
//
// @Value("${group.mapping.https.username}")
// @Getter @Setter
// private String username;
//
// @Value("${group.mapping.https.password}")
// @Getter @Setter
// private String password;
//
// @Value("${group.mapping.kerberos.principal}")
// @Getter @Setter
// private String principal;
//
// @Value("${group.mapping.kerberos.principalKeyTab}")
// @Getter @Setter
// private String principalKeyTab;
//
// }
//
// Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/users/entity/User.java
// @Data
// public final class User {
//
// private final String username;
//
// @JsonCreator
// public User(@JsonProperty("username") String username) {
// this.username = username;
// }
//
// }
| import java.util.UUID;
import org.cloudfoundry.community.servicebroker.exception.ServiceBrokerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import org.trustedanalytics.servicebroker.hdfs.config.hgm.HgmConfiguration;
import org.trustedanalytics.servicebroker.hdfs.users.entity.User; | /**
* Copyright (c) 2015 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.trustedanalytics.servicebroker.hdfs.users;
@Component
public class GroupMappingOperations {
private static final String USER_GROUP_ENDPOINT = "/groups/{group}/users";
private static final String TECH_GROUP_POSTFIX = "_sys";
@Autowired
private UaaUsersOperations uaaUsersOperations;
@Autowired | // Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/config/hgm/HgmConfiguration.java
// @Configuration
// public class HgmConfiguration {
//
// @Value("${group.mapping.url}")
// @NotNull
// @Getter @Setter
// private String url;
//
// @Value("${group.mapping.https.username}")
// @Getter @Setter
// private String username;
//
// @Value("${group.mapping.https.password}")
// @Getter @Setter
// private String password;
//
// @Value("${group.mapping.kerberos.principal}")
// @Getter @Setter
// private String principal;
//
// @Value("${group.mapping.kerberos.principalKeyTab}")
// @Getter @Setter
// private String principalKeyTab;
//
// }
//
// Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/users/entity/User.java
// @Data
// public final class User {
//
// private final String username;
//
// @JsonCreator
// public User(@JsonProperty("username") String username) {
// this.username = username;
// }
//
// }
// Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/users/GroupMappingOperations.java
import java.util.UUID;
import org.cloudfoundry.community.servicebroker.exception.ServiceBrokerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import org.trustedanalytics.servicebroker.hdfs.config.hgm.HgmConfiguration;
import org.trustedanalytics.servicebroker.hdfs.users.entity.User;
/**
* Copyright (c) 2015 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.trustedanalytics.servicebroker.hdfs.users;
@Component
public class GroupMappingOperations {
private static final String USER_GROUP_ENDPOINT = "/groups/{group}/users";
private static final String TECH_GROUP_POSTFIX = "_sys";
@Autowired
private UaaUsersOperations uaaUsersOperations;
@Autowired | private HgmConfiguration configuration; |
trustedanalytics/hdfs-broker | src/main/java/org/trustedanalytics/servicebroker/hdfs/users/GroupMappingOperations.java | // Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/config/hgm/HgmConfiguration.java
// @Configuration
// public class HgmConfiguration {
//
// @Value("${group.mapping.url}")
// @NotNull
// @Getter @Setter
// private String url;
//
// @Value("${group.mapping.https.username}")
// @Getter @Setter
// private String username;
//
// @Value("${group.mapping.https.password}")
// @Getter @Setter
// private String password;
//
// @Value("${group.mapping.kerberos.principal}")
// @Getter @Setter
// private String principal;
//
// @Value("${group.mapping.kerberos.principalKeyTab}")
// @Getter @Setter
// private String principalKeyTab;
//
// }
//
// Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/users/entity/User.java
// @Data
// public final class User {
//
// private final String username;
//
// @JsonCreator
// public User(@JsonProperty("username") String username) {
// this.username = username;
// }
//
// }
| import java.util.UUID;
import org.cloudfoundry.community.servicebroker.exception.ServiceBrokerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import org.trustedanalytics.servicebroker.hdfs.config.hgm.HgmConfiguration;
import org.trustedanalytics.servicebroker.hdfs.users.entity.User; | /**
* Copyright (c) 2015 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.trustedanalytics.servicebroker.hdfs.users;
@Component
public class GroupMappingOperations {
private static final String USER_GROUP_ENDPOINT = "/groups/{group}/users";
private static final String TECH_GROUP_POSTFIX = "_sys";
@Autowired
private UaaUsersOperations uaaUsersOperations;
@Autowired
private HgmConfiguration configuration;
@Autowired
@Qualifier("hgmRestTemplate")
private RestTemplate restTemplate;
public UUID createSysUser(UUID groupId, UUID userId, String password) throws ServiceBrokerException {
UUID uaaUserId = uaaUsersOperations.createUser(userId, password);
try { | // Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/config/hgm/HgmConfiguration.java
// @Configuration
// public class HgmConfiguration {
//
// @Value("${group.mapping.url}")
// @NotNull
// @Getter @Setter
// private String url;
//
// @Value("${group.mapping.https.username}")
// @Getter @Setter
// private String username;
//
// @Value("${group.mapping.https.password}")
// @Getter @Setter
// private String password;
//
// @Value("${group.mapping.kerberos.principal}")
// @Getter @Setter
// private String principal;
//
// @Value("${group.mapping.kerberos.principalKeyTab}")
// @Getter @Setter
// private String principalKeyTab;
//
// }
//
// Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/users/entity/User.java
// @Data
// public final class User {
//
// private final String username;
//
// @JsonCreator
// public User(@JsonProperty("username") String username) {
// this.username = username;
// }
//
// }
// Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/users/GroupMappingOperations.java
import java.util.UUID;
import org.cloudfoundry.community.servicebroker.exception.ServiceBrokerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import org.trustedanalytics.servicebroker.hdfs.config.hgm.HgmConfiguration;
import org.trustedanalytics.servicebroker.hdfs.users.entity.User;
/**
* Copyright (c) 2015 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.trustedanalytics.servicebroker.hdfs.users;
@Component
public class GroupMappingOperations {
private static final String USER_GROUP_ENDPOINT = "/groups/{group}/users";
private static final String TECH_GROUP_POSTFIX = "_sys";
@Autowired
private UaaUsersOperations uaaUsersOperations;
@Autowired
private HgmConfiguration configuration;
@Autowired
@Qualifier("hgmRestTemplate")
private RestTemplate restTemplate;
public UUID createSysUser(UUID groupId, UUID userId, String password) throws ServiceBrokerException {
UUID uaaUserId = uaaUsersOperations.createUser(userId, password);
try { | restTemplate.postForObject(configuration.getUrl().concat(USER_GROUP_ENDPOINT), new User( |
trustedanalytics/hdfs-broker | src/main/java/org/trustedanalytics/servicebroker/hdfs/plans/HdfsPlanCreateUserDirectory.java | // Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/plans/binding/HdfsSpecificOrgBindingOperations.java
// public interface HdfsSpecificOrgBindingOperations {
// Map<String, Object> createCredentialsMap(UUID instanceId, UUID orgId);
// }
//
// Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/plans/provisioning/HdfsDirectoryProvisioningOperations.java
// public interface HdfsDirectoryProvisioningOperations {
// void provisionDirectory(UUID instanceId, UUID orgId) throws ServiceBrokerException;
// void provisionDirectory(UUID instanceId, UUID orgId, UUID owner) throws ServiceBrokerException;
// }
//
// Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/users/GroupMappingOperations.java
// @Component
// public class GroupMappingOperations {
//
// private static final String USER_GROUP_ENDPOINT = "/groups/{group}/users";
// private static final String TECH_GROUP_POSTFIX = "_sys";
//
// @Autowired
// private UaaUsersOperations uaaUsersOperations;
//
// @Autowired
// private HgmConfiguration configuration;
//
// @Autowired
// @Qualifier("hgmRestTemplate")
// private RestTemplate restTemplate;
//
// public UUID createSysUser(UUID groupId, UUID userId, String password) throws ServiceBrokerException {
// UUID uaaUserId = uaaUsersOperations.createUser(userId, password);
// try {
// restTemplate.postForObject(configuration.getUrl().concat(USER_GROUP_ENDPOINT), new User(
// uaaUserId.toString()), String.class, groupId.toString().concat(TECH_GROUP_POSTFIX));
// return uaaUserId;
// } catch (RestClientException e) {
// throw new ServiceBrokerException(String.format("Can't add user %s to group: %s",
// uaaUserId.toString(), groupId), e);
// }
// }
//
// }
| import org.trustedanalytics.servicebroker.hdfs.users.GroupMappingOperations;
import com.google.common.collect.ImmutableMap;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import org.apache.commons.lang.RandomStringUtils;
import org.cloudfoundry.community.servicebroker.exception.ServiceBrokerException;
import org.cloudfoundry.community.servicebroker.exception.ServiceInstanceExistsException;
import org.cloudfoundry.community.servicebroker.model.ServiceInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.trustedanalytics.servicebroker.framework.service.ServicePlanDefinition;
import org.trustedanalytics.servicebroker.framework.store.CredentialsStore;
import org.trustedanalytics.servicebroker.hdfs.plans.binding.HdfsSpecificOrgBindingOperations;
import org.trustedanalytics.servicebroker.hdfs.plans.provisioning.HdfsDirectoryProvisioningOperations; | /**
* Copyright (c) 2015 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.trustedanalytics.servicebroker.hdfs.plans;
@Component("create-user-directory")
class HdfsPlanCreateUserDirectory implements ServicePlanDefinition {
private static final String USER = "user";
private static final String PASSWORD = "password";
| // Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/plans/binding/HdfsSpecificOrgBindingOperations.java
// public interface HdfsSpecificOrgBindingOperations {
// Map<String, Object> createCredentialsMap(UUID instanceId, UUID orgId);
// }
//
// Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/plans/provisioning/HdfsDirectoryProvisioningOperations.java
// public interface HdfsDirectoryProvisioningOperations {
// void provisionDirectory(UUID instanceId, UUID orgId) throws ServiceBrokerException;
// void provisionDirectory(UUID instanceId, UUID orgId, UUID owner) throws ServiceBrokerException;
// }
//
// Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/users/GroupMappingOperations.java
// @Component
// public class GroupMappingOperations {
//
// private static final String USER_GROUP_ENDPOINT = "/groups/{group}/users";
// private static final String TECH_GROUP_POSTFIX = "_sys";
//
// @Autowired
// private UaaUsersOperations uaaUsersOperations;
//
// @Autowired
// private HgmConfiguration configuration;
//
// @Autowired
// @Qualifier("hgmRestTemplate")
// private RestTemplate restTemplate;
//
// public UUID createSysUser(UUID groupId, UUID userId, String password) throws ServiceBrokerException {
// UUID uaaUserId = uaaUsersOperations.createUser(userId, password);
// try {
// restTemplate.postForObject(configuration.getUrl().concat(USER_GROUP_ENDPOINT), new User(
// uaaUserId.toString()), String.class, groupId.toString().concat(TECH_GROUP_POSTFIX));
// return uaaUserId;
// } catch (RestClientException e) {
// throw new ServiceBrokerException(String.format("Can't add user %s to group: %s",
// uaaUserId.toString(), groupId), e);
// }
// }
//
// }
// Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/plans/HdfsPlanCreateUserDirectory.java
import org.trustedanalytics.servicebroker.hdfs.users.GroupMappingOperations;
import com.google.common.collect.ImmutableMap;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import org.apache.commons.lang.RandomStringUtils;
import org.cloudfoundry.community.servicebroker.exception.ServiceBrokerException;
import org.cloudfoundry.community.servicebroker.exception.ServiceInstanceExistsException;
import org.cloudfoundry.community.servicebroker.model.ServiceInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.trustedanalytics.servicebroker.framework.service.ServicePlanDefinition;
import org.trustedanalytics.servicebroker.framework.store.CredentialsStore;
import org.trustedanalytics.servicebroker.hdfs.plans.binding.HdfsSpecificOrgBindingOperations;
import org.trustedanalytics.servicebroker.hdfs.plans.provisioning.HdfsDirectoryProvisioningOperations;
/**
* Copyright (c) 2015 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.trustedanalytics.servicebroker.hdfs.plans;
@Component("create-user-directory")
class HdfsPlanCreateUserDirectory implements ServicePlanDefinition {
private static final String USER = "user";
private static final String PASSWORD = "password";
| private final HdfsDirectoryProvisioningOperations hdfsOperations; |
trustedanalytics/hdfs-broker | src/main/java/org/trustedanalytics/servicebroker/hdfs/plans/HdfsPlanCreateUserDirectory.java | // Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/plans/binding/HdfsSpecificOrgBindingOperations.java
// public interface HdfsSpecificOrgBindingOperations {
// Map<String, Object> createCredentialsMap(UUID instanceId, UUID orgId);
// }
//
// Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/plans/provisioning/HdfsDirectoryProvisioningOperations.java
// public interface HdfsDirectoryProvisioningOperations {
// void provisionDirectory(UUID instanceId, UUID orgId) throws ServiceBrokerException;
// void provisionDirectory(UUID instanceId, UUID orgId, UUID owner) throws ServiceBrokerException;
// }
//
// Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/users/GroupMappingOperations.java
// @Component
// public class GroupMappingOperations {
//
// private static final String USER_GROUP_ENDPOINT = "/groups/{group}/users";
// private static final String TECH_GROUP_POSTFIX = "_sys";
//
// @Autowired
// private UaaUsersOperations uaaUsersOperations;
//
// @Autowired
// private HgmConfiguration configuration;
//
// @Autowired
// @Qualifier("hgmRestTemplate")
// private RestTemplate restTemplate;
//
// public UUID createSysUser(UUID groupId, UUID userId, String password) throws ServiceBrokerException {
// UUID uaaUserId = uaaUsersOperations.createUser(userId, password);
// try {
// restTemplate.postForObject(configuration.getUrl().concat(USER_GROUP_ENDPOINT), new User(
// uaaUserId.toString()), String.class, groupId.toString().concat(TECH_GROUP_POSTFIX));
// return uaaUserId;
// } catch (RestClientException e) {
// throw new ServiceBrokerException(String.format("Can't add user %s to group: %s",
// uaaUserId.toString(), groupId), e);
// }
// }
//
// }
| import org.trustedanalytics.servicebroker.hdfs.users.GroupMappingOperations;
import com.google.common.collect.ImmutableMap;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import org.apache.commons.lang.RandomStringUtils;
import org.cloudfoundry.community.servicebroker.exception.ServiceBrokerException;
import org.cloudfoundry.community.servicebroker.exception.ServiceInstanceExistsException;
import org.cloudfoundry.community.servicebroker.model.ServiceInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.trustedanalytics.servicebroker.framework.service.ServicePlanDefinition;
import org.trustedanalytics.servicebroker.framework.store.CredentialsStore;
import org.trustedanalytics.servicebroker.hdfs.plans.binding.HdfsSpecificOrgBindingOperations;
import org.trustedanalytics.servicebroker.hdfs.plans.provisioning.HdfsDirectoryProvisioningOperations; | /**
* Copyright (c) 2015 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.trustedanalytics.servicebroker.hdfs.plans;
@Component("create-user-directory")
class HdfsPlanCreateUserDirectory implements ServicePlanDefinition {
private static final String USER = "user";
private static final String PASSWORD = "password";
private final HdfsDirectoryProvisioningOperations hdfsOperations; | // Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/plans/binding/HdfsSpecificOrgBindingOperations.java
// public interface HdfsSpecificOrgBindingOperations {
// Map<String, Object> createCredentialsMap(UUID instanceId, UUID orgId);
// }
//
// Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/plans/provisioning/HdfsDirectoryProvisioningOperations.java
// public interface HdfsDirectoryProvisioningOperations {
// void provisionDirectory(UUID instanceId, UUID orgId) throws ServiceBrokerException;
// void provisionDirectory(UUID instanceId, UUID orgId, UUID owner) throws ServiceBrokerException;
// }
//
// Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/users/GroupMappingOperations.java
// @Component
// public class GroupMappingOperations {
//
// private static final String USER_GROUP_ENDPOINT = "/groups/{group}/users";
// private static final String TECH_GROUP_POSTFIX = "_sys";
//
// @Autowired
// private UaaUsersOperations uaaUsersOperations;
//
// @Autowired
// private HgmConfiguration configuration;
//
// @Autowired
// @Qualifier("hgmRestTemplate")
// private RestTemplate restTemplate;
//
// public UUID createSysUser(UUID groupId, UUID userId, String password) throws ServiceBrokerException {
// UUID uaaUserId = uaaUsersOperations.createUser(userId, password);
// try {
// restTemplate.postForObject(configuration.getUrl().concat(USER_GROUP_ENDPOINT), new User(
// uaaUserId.toString()), String.class, groupId.toString().concat(TECH_GROUP_POSTFIX));
// return uaaUserId;
// } catch (RestClientException e) {
// throw new ServiceBrokerException(String.format("Can't add user %s to group: %s",
// uaaUserId.toString(), groupId), e);
// }
// }
//
// }
// Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/plans/HdfsPlanCreateUserDirectory.java
import org.trustedanalytics.servicebroker.hdfs.users.GroupMappingOperations;
import com.google.common.collect.ImmutableMap;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import org.apache.commons.lang.RandomStringUtils;
import org.cloudfoundry.community.servicebroker.exception.ServiceBrokerException;
import org.cloudfoundry.community.servicebroker.exception.ServiceInstanceExistsException;
import org.cloudfoundry.community.servicebroker.model.ServiceInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.trustedanalytics.servicebroker.framework.service.ServicePlanDefinition;
import org.trustedanalytics.servicebroker.framework.store.CredentialsStore;
import org.trustedanalytics.servicebroker.hdfs.plans.binding.HdfsSpecificOrgBindingOperations;
import org.trustedanalytics.servicebroker.hdfs.plans.provisioning.HdfsDirectoryProvisioningOperations;
/**
* Copyright (c) 2015 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.trustedanalytics.servicebroker.hdfs.plans;
@Component("create-user-directory")
class HdfsPlanCreateUserDirectory implements ServicePlanDefinition {
private static final String USER = "user";
private static final String PASSWORD = "password";
private final HdfsDirectoryProvisioningOperations hdfsOperations; | private final HdfsSpecificOrgBindingOperations bindingOperations; |
trustedanalytics/hdfs-broker | src/main/java/org/trustedanalytics/servicebroker/hdfs/plans/HdfsPlanCreateUserDirectory.java | // Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/plans/binding/HdfsSpecificOrgBindingOperations.java
// public interface HdfsSpecificOrgBindingOperations {
// Map<String, Object> createCredentialsMap(UUID instanceId, UUID orgId);
// }
//
// Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/plans/provisioning/HdfsDirectoryProvisioningOperations.java
// public interface HdfsDirectoryProvisioningOperations {
// void provisionDirectory(UUID instanceId, UUID orgId) throws ServiceBrokerException;
// void provisionDirectory(UUID instanceId, UUID orgId, UUID owner) throws ServiceBrokerException;
// }
//
// Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/users/GroupMappingOperations.java
// @Component
// public class GroupMappingOperations {
//
// private static final String USER_GROUP_ENDPOINT = "/groups/{group}/users";
// private static final String TECH_GROUP_POSTFIX = "_sys";
//
// @Autowired
// private UaaUsersOperations uaaUsersOperations;
//
// @Autowired
// private HgmConfiguration configuration;
//
// @Autowired
// @Qualifier("hgmRestTemplate")
// private RestTemplate restTemplate;
//
// public UUID createSysUser(UUID groupId, UUID userId, String password) throws ServiceBrokerException {
// UUID uaaUserId = uaaUsersOperations.createUser(userId, password);
// try {
// restTemplate.postForObject(configuration.getUrl().concat(USER_GROUP_ENDPOINT), new User(
// uaaUserId.toString()), String.class, groupId.toString().concat(TECH_GROUP_POSTFIX));
// return uaaUserId;
// } catch (RestClientException e) {
// throw new ServiceBrokerException(String.format("Can't add user %s to group: %s",
// uaaUserId.toString(), groupId), e);
// }
// }
//
// }
| import org.trustedanalytics.servicebroker.hdfs.users.GroupMappingOperations;
import com.google.common.collect.ImmutableMap;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import org.apache.commons.lang.RandomStringUtils;
import org.cloudfoundry.community.servicebroker.exception.ServiceBrokerException;
import org.cloudfoundry.community.servicebroker.exception.ServiceInstanceExistsException;
import org.cloudfoundry.community.servicebroker.model.ServiceInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.trustedanalytics.servicebroker.framework.service.ServicePlanDefinition;
import org.trustedanalytics.servicebroker.framework.store.CredentialsStore;
import org.trustedanalytics.servicebroker.hdfs.plans.binding.HdfsSpecificOrgBindingOperations;
import org.trustedanalytics.servicebroker.hdfs.plans.provisioning.HdfsDirectoryProvisioningOperations; | /**
* Copyright (c) 2015 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.trustedanalytics.servicebroker.hdfs.plans;
@Component("create-user-directory")
class HdfsPlanCreateUserDirectory implements ServicePlanDefinition {
private static final String USER = "user";
private static final String PASSWORD = "password";
private final HdfsDirectoryProvisioningOperations hdfsOperations;
private final HdfsSpecificOrgBindingOperations bindingOperations;
private final CredentialsStore credentialsStore; | // Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/plans/binding/HdfsSpecificOrgBindingOperations.java
// public interface HdfsSpecificOrgBindingOperations {
// Map<String, Object> createCredentialsMap(UUID instanceId, UUID orgId);
// }
//
// Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/plans/provisioning/HdfsDirectoryProvisioningOperations.java
// public interface HdfsDirectoryProvisioningOperations {
// void provisionDirectory(UUID instanceId, UUID orgId) throws ServiceBrokerException;
// void provisionDirectory(UUID instanceId, UUID orgId, UUID owner) throws ServiceBrokerException;
// }
//
// Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/users/GroupMappingOperations.java
// @Component
// public class GroupMappingOperations {
//
// private static final String USER_GROUP_ENDPOINT = "/groups/{group}/users";
// private static final String TECH_GROUP_POSTFIX = "_sys";
//
// @Autowired
// private UaaUsersOperations uaaUsersOperations;
//
// @Autowired
// private HgmConfiguration configuration;
//
// @Autowired
// @Qualifier("hgmRestTemplate")
// private RestTemplate restTemplate;
//
// public UUID createSysUser(UUID groupId, UUID userId, String password) throws ServiceBrokerException {
// UUID uaaUserId = uaaUsersOperations.createUser(userId, password);
// try {
// restTemplate.postForObject(configuration.getUrl().concat(USER_GROUP_ENDPOINT), new User(
// uaaUserId.toString()), String.class, groupId.toString().concat(TECH_GROUP_POSTFIX));
// return uaaUserId;
// } catch (RestClientException e) {
// throw new ServiceBrokerException(String.format("Can't add user %s to group: %s",
// uaaUserId.toString(), groupId), e);
// }
// }
//
// }
// Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/plans/HdfsPlanCreateUserDirectory.java
import org.trustedanalytics.servicebroker.hdfs.users.GroupMappingOperations;
import com.google.common.collect.ImmutableMap;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import org.apache.commons.lang.RandomStringUtils;
import org.cloudfoundry.community.servicebroker.exception.ServiceBrokerException;
import org.cloudfoundry.community.servicebroker.exception.ServiceInstanceExistsException;
import org.cloudfoundry.community.servicebroker.model.ServiceInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.trustedanalytics.servicebroker.framework.service.ServicePlanDefinition;
import org.trustedanalytics.servicebroker.framework.store.CredentialsStore;
import org.trustedanalytics.servicebroker.hdfs.plans.binding.HdfsSpecificOrgBindingOperations;
import org.trustedanalytics.servicebroker.hdfs.plans.provisioning.HdfsDirectoryProvisioningOperations;
/**
* Copyright (c) 2015 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.trustedanalytics.servicebroker.hdfs.plans;
@Component("create-user-directory")
class HdfsPlanCreateUserDirectory implements ServicePlanDefinition {
private static final String USER = "user";
private static final String PASSWORD = "password";
private final HdfsDirectoryProvisioningOperations hdfsOperations;
private final HdfsSpecificOrgBindingOperations bindingOperations;
private final CredentialsStore credentialsStore; | private final GroupMappingOperations groupMappingOperations; |
trustedanalytics/hdfs-broker | src/main/java/org/trustedanalytics/servicebroker/hdfs/plans/HdfsPlanGetUserDirectory.java | // Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/path/HdfsBrokerInstancePath.java
// public final class HdfsBrokerInstancePath {
// private static final String UUID_REGEX = "[0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12}";
// private static final String INSTANCE = "instance";
// private static final String NAMESPACE = "namespace";
// private static final String ORG = "org";
// private static final String HDFS_URI_REGEX = String.format(
// "^hdfs://(?<%s>\\w+)/org/(?<%s>%s)/brokers/userspace/(?<%s>%s)/", NAMESPACE, ORG, UUID_REGEX,
// INSTANCE, UUID_REGEX);
//
// @Getter
// private final String hdfsUri;
// @Getter
// private final UUID orgId;
// @Getter
// private final UUID instanceId;
// @Getter
// private final String namespace;
//
// private HdfsBrokerInstancePath(String hdfsUri, String namespace, UUID orgId, UUID instanceId) {
// this.hdfsUri = hdfsUri;
// this.orgId = orgId;
// this.instanceId = instanceId;
// this.namespace = namespace;
// }
//
// public static HdfsBrokerInstancePath createInstance(String hdfsUri) throws ServiceBrokerException {
// Matcher matcher = Pattern.compile(HDFS_URI_REGEX).matcher(hdfsUri);
// if (!matcher.find()) {
// throw new ServiceBrokerException(
// "Invalid hdfs path, doesn't match template: hdfs://<namespace>/org/<uuid>/brokers/userspace/<uuid>/ - "
// + hdfsUri);
// }
// return new HdfsBrokerInstancePath(hdfsUri, matcher.group(NAMESPACE), UUID.fromString(matcher
// .group(ORG)), UUID.fromString(matcher.group(INSTANCE)));
// }
//
// }
//
// Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/plans/binding/HdfsSpecificOrgBindingOperations.java
// public interface HdfsSpecificOrgBindingOperations {
// Map<String, Object> createCredentialsMap(UUID instanceId, UUID orgId);
// }
| import org.trustedanalytics.servicebroker.hdfs.plans.binding.HdfsSpecificOrgBindingOperations;
import com.google.common.collect.ImmutableMap;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import org.cloudfoundry.community.servicebroker.exception.ServiceBrokerException;
import org.cloudfoundry.community.servicebroker.exception.ServiceInstanceExistsException;
import org.cloudfoundry.community.servicebroker.model.ServiceInstance;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.trustedanalytics.servicebroker.framework.service.ServicePlanDefinition;
import org.trustedanalytics.servicebroker.framework.store.CredentialsStore;
import org.trustedanalytics.servicebroker.hdfs.path.HdfsBrokerInstancePath; | /**
* Copyright (c) 2015 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.trustedanalytics.servicebroker.hdfs.plans;
@Component("get-user-directory")
class HdfsPlanGetUserDirectory implements ServicePlanDefinition {
private static final Logger LOGGER = LoggerFactory.getLogger(HdfsPlanCreateUserDirectory.class);
private static final String URI_KEY = "uri";
| // Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/path/HdfsBrokerInstancePath.java
// public final class HdfsBrokerInstancePath {
// private static final String UUID_REGEX = "[0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12}";
// private static final String INSTANCE = "instance";
// private static final String NAMESPACE = "namespace";
// private static final String ORG = "org";
// private static final String HDFS_URI_REGEX = String.format(
// "^hdfs://(?<%s>\\w+)/org/(?<%s>%s)/brokers/userspace/(?<%s>%s)/", NAMESPACE, ORG, UUID_REGEX,
// INSTANCE, UUID_REGEX);
//
// @Getter
// private final String hdfsUri;
// @Getter
// private final UUID orgId;
// @Getter
// private final UUID instanceId;
// @Getter
// private final String namespace;
//
// private HdfsBrokerInstancePath(String hdfsUri, String namespace, UUID orgId, UUID instanceId) {
// this.hdfsUri = hdfsUri;
// this.orgId = orgId;
// this.instanceId = instanceId;
// this.namespace = namespace;
// }
//
// public static HdfsBrokerInstancePath createInstance(String hdfsUri) throws ServiceBrokerException {
// Matcher matcher = Pattern.compile(HDFS_URI_REGEX).matcher(hdfsUri);
// if (!matcher.find()) {
// throw new ServiceBrokerException(
// "Invalid hdfs path, doesn't match template: hdfs://<namespace>/org/<uuid>/brokers/userspace/<uuid>/ - "
// + hdfsUri);
// }
// return new HdfsBrokerInstancePath(hdfsUri, matcher.group(NAMESPACE), UUID.fromString(matcher
// .group(ORG)), UUID.fromString(matcher.group(INSTANCE)));
// }
//
// }
//
// Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/plans/binding/HdfsSpecificOrgBindingOperations.java
// public interface HdfsSpecificOrgBindingOperations {
// Map<String, Object> createCredentialsMap(UUID instanceId, UUID orgId);
// }
// Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/plans/HdfsPlanGetUserDirectory.java
import org.trustedanalytics.servicebroker.hdfs.plans.binding.HdfsSpecificOrgBindingOperations;
import com.google.common.collect.ImmutableMap;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import org.cloudfoundry.community.servicebroker.exception.ServiceBrokerException;
import org.cloudfoundry.community.servicebroker.exception.ServiceInstanceExistsException;
import org.cloudfoundry.community.servicebroker.model.ServiceInstance;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.trustedanalytics.servicebroker.framework.service.ServicePlanDefinition;
import org.trustedanalytics.servicebroker.framework.store.CredentialsStore;
import org.trustedanalytics.servicebroker.hdfs.path.HdfsBrokerInstancePath;
/**
* Copyright (c) 2015 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.trustedanalytics.servicebroker.hdfs.plans;
@Component("get-user-directory")
class HdfsPlanGetUserDirectory implements ServicePlanDefinition {
private static final Logger LOGGER = LoggerFactory.getLogger(HdfsPlanCreateUserDirectory.class);
private static final String URI_KEY = "uri";
| private final HdfsSpecificOrgBindingOperations bindingOperations; |
trustedanalytics/hdfs-broker | src/main/java/org/trustedanalytics/servicebroker/hdfs/plans/HdfsPlanGetUserDirectory.java | // Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/path/HdfsBrokerInstancePath.java
// public final class HdfsBrokerInstancePath {
// private static final String UUID_REGEX = "[0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12}";
// private static final String INSTANCE = "instance";
// private static final String NAMESPACE = "namespace";
// private static final String ORG = "org";
// private static final String HDFS_URI_REGEX = String.format(
// "^hdfs://(?<%s>\\w+)/org/(?<%s>%s)/brokers/userspace/(?<%s>%s)/", NAMESPACE, ORG, UUID_REGEX,
// INSTANCE, UUID_REGEX);
//
// @Getter
// private final String hdfsUri;
// @Getter
// private final UUID orgId;
// @Getter
// private final UUID instanceId;
// @Getter
// private final String namespace;
//
// private HdfsBrokerInstancePath(String hdfsUri, String namespace, UUID orgId, UUID instanceId) {
// this.hdfsUri = hdfsUri;
// this.orgId = orgId;
// this.instanceId = instanceId;
// this.namespace = namespace;
// }
//
// public static HdfsBrokerInstancePath createInstance(String hdfsUri) throws ServiceBrokerException {
// Matcher matcher = Pattern.compile(HDFS_URI_REGEX).matcher(hdfsUri);
// if (!matcher.find()) {
// throw new ServiceBrokerException(
// "Invalid hdfs path, doesn't match template: hdfs://<namespace>/org/<uuid>/brokers/userspace/<uuid>/ - "
// + hdfsUri);
// }
// return new HdfsBrokerInstancePath(hdfsUri, matcher.group(NAMESPACE), UUID.fromString(matcher
// .group(ORG)), UUID.fromString(matcher.group(INSTANCE)));
// }
//
// }
//
// Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/plans/binding/HdfsSpecificOrgBindingOperations.java
// public interface HdfsSpecificOrgBindingOperations {
// Map<String, Object> createCredentialsMap(UUID instanceId, UUID orgId);
// }
| import org.trustedanalytics.servicebroker.hdfs.plans.binding.HdfsSpecificOrgBindingOperations;
import com.google.common.collect.ImmutableMap;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import org.cloudfoundry.community.servicebroker.exception.ServiceBrokerException;
import org.cloudfoundry.community.servicebroker.exception.ServiceInstanceExistsException;
import org.cloudfoundry.community.servicebroker.model.ServiceInstance;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.trustedanalytics.servicebroker.framework.service.ServicePlanDefinition;
import org.trustedanalytics.servicebroker.framework.store.CredentialsStore;
import org.trustedanalytics.servicebroker.hdfs.path.HdfsBrokerInstancePath; | /**
* Copyright (c) 2015 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.trustedanalytics.servicebroker.hdfs.plans;
@Component("get-user-directory")
class HdfsPlanGetUserDirectory implements ServicePlanDefinition {
private static final Logger LOGGER = LoggerFactory.getLogger(HdfsPlanCreateUserDirectory.class);
private static final String URI_KEY = "uri";
private final HdfsSpecificOrgBindingOperations bindingOperations;
private final CredentialsStore credentialsStore;
@Autowired
public HdfsPlanGetUserDirectory(HdfsSpecificOrgBindingOperations bindingOperations,
CredentialsStore zookeeperCredentialsStore) {
this.bindingOperations = bindingOperations;
this.credentialsStore = zookeeperCredentialsStore;
}
@Override
public void provision(ServiceInstance serviceInstance, Optional<Map<String, Object>> parameters)
throws ServiceInstanceExistsException, ServiceBrokerException {
if (!isMapNotNullAndNotEmpty(parameters)) {
throw new ServiceBrokerException("This plan require parametere uri");
}
String uri =
getParameterUri(parameters.get(), URI_KEY).orElseThrow(
() -> new ServiceBrokerException("No required parameter uri")).toString();
LOGGER.info("Detected parameter path: " + uri);
| // Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/path/HdfsBrokerInstancePath.java
// public final class HdfsBrokerInstancePath {
// private static final String UUID_REGEX = "[0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12}";
// private static final String INSTANCE = "instance";
// private static final String NAMESPACE = "namespace";
// private static final String ORG = "org";
// private static final String HDFS_URI_REGEX = String.format(
// "^hdfs://(?<%s>\\w+)/org/(?<%s>%s)/brokers/userspace/(?<%s>%s)/", NAMESPACE, ORG, UUID_REGEX,
// INSTANCE, UUID_REGEX);
//
// @Getter
// private final String hdfsUri;
// @Getter
// private final UUID orgId;
// @Getter
// private final UUID instanceId;
// @Getter
// private final String namespace;
//
// private HdfsBrokerInstancePath(String hdfsUri, String namespace, UUID orgId, UUID instanceId) {
// this.hdfsUri = hdfsUri;
// this.orgId = orgId;
// this.instanceId = instanceId;
// this.namespace = namespace;
// }
//
// public static HdfsBrokerInstancePath createInstance(String hdfsUri) throws ServiceBrokerException {
// Matcher matcher = Pattern.compile(HDFS_URI_REGEX).matcher(hdfsUri);
// if (!matcher.find()) {
// throw new ServiceBrokerException(
// "Invalid hdfs path, doesn't match template: hdfs://<namespace>/org/<uuid>/brokers/userspace/<uuid>/ - "
// + hdfsUri);
// }
// return new HdfsBrokerInstancePath(hdfsUri, matcher.group(NAMESPACE), UUID.fromString(matcher
// .group(ORG)), UUID.fromString(matcher.group(INSTANCE)));
// }
//
// }
//
// Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/plans/binding/HdfsSpecificOrgBindingOperations.java
// public interface HdfsSpecificOrgBindingOperations {
// Map<String, Object> createCredentialsMap(UUID instanceId, UUID orgId);
// }
// Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/plans/HdfsPlanGetUserDirectory.java
import org.trustedanalytics.servicebroker.hdfs.plans.binding.HdfsSpecificOrgBindingOperations;
import com.google.common.collect.ImmutableMap;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import org.cloudfoundry.community.servicebroker.exception.ServiceBrokerException;
import org.cloudfoundry.community.servicebroker.exception.ServiceInstanceExistsException;
import org.cloudfoundry.community.servicebroker.model.ServiceInstance;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.trustedanalytics.servicebroker.framework.service.ServicePlanDefinition;
import org.trustedanalytics.servicebroker.framework.store.CredentialsStore;
import org.trustedanalytics.servicebroker.hdfs.path.HdfsBrokerInstancePath;
/**
* Copyright (c) 2015 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.trustedanalytics.servicebroker.hdfs.plans;
@Component("get-user-directory")
class HdfsPlanGetUserDirectory implements ServicePlanDefinition {
private static final Logger LOGGER = LoggerFactory.getLogger(HdfsPlanCreateUserDirectory.class);
private static final String URI_KEY = "uri";
private final HdfsSpecificOrgBindingOperations bindingOperations;
private final CredentialsStore credentialsStore;
@Autowired
public HdfsPlanGetUserDirectory(HdfsSpecificOrgBindingOperations bindingOperations,
CredentialsStore zookeeperCredentialsStore) {
this.bindingOperations = bindingOperations;
this.credentialsStore = zookeeperCredentialsStore;
}
@Override
public void provision(ServiceInstance serviceInstance, Optional<Map<String, Object>> parameters)
throws ServiceInstanceExistsException, ServiceBrokerException {
if (!isMapNotNullAndNotEmpty(parameters)) {
throw new ServiceBrokerException("This plan require parametere uri");
}
String uri =
getParameterUri(parameters.get(), URI_KEY).orElseThrow(
() -> new ServiceBrokerException("No required parameter uri")).toString();
LOGGER.info("Detected parameter path: " + uri);
| HdfsBrokerInstancePath instance = HdfsBrokerInstancePath.createInstance(uri); |
trustedanalytics/hdfs-broker | src/main/java/org/trustedanalytics/servicebroker/hdfs/plans/HdfsPlanBare.java | // Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/plans/binding/HdfsBareBindingOperations.java
// public interface HdfsBareBindingOperations {
// Map<String, Object> createCredentialsMap();
// }
| import java.util.Map;
import org.cloudfoundry.community.servicebroker.exception.ServiceBrokerException;
import org.cloudfoundry.community.servicebroker.model.ServiceInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.trustedanalytics.servicebroker.framework.service.ServicePlanDefinition;
import org.trustedanalytics.servicebroker.hdfs.plans.binding.HdfsBareBindingOperations; | /**
* Copyright (c) 2015 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.trustedanalytics.servicebroker.hdfs.plans;
@Component("bare")
class HdfsPlanBare implements ServicePlanDefinition {
| // Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/plans/binding/HdfsBareBindingOperations.java
// public interface HdfsBareBindingOperations {
// Map<String, Object> createCredentialsMap();
// }
// Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/plans/HdfsPlanBare.java
import java.util.Map;
import org.cloudfoundry.community.servicebroker.exception.ServiceBrokerException;
import org.cloudfoundry.community.servicebroker.model.ServiceInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.trustedanalytics.servicebroker.framework.service.ServicePlanDefinition;
import org.trustedanalytics.servicebroker.hdfs.plans.binding.HdfsBareBindingOperations;
/**
* Copyright (c) 2015 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.trustedanalytics.servicebroker.hdfs.plans;
@Component("bare")
class HdfsPlanBare implements ServicePlanDefinition {
| private final HdfsBareBindingOperations bindingOperations; |
trustedanalytics/hdfs-broker | src/test/java/org/trustedanalytics/servicebroker/hdfs/integration/config/HdfsLocalConfiguration.java | // Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/config/ExternalConfiguration.java
// @Configuration
// public class ExternalConfiguration {
//
// @Value("${store.user}")
// @NotNull
// @Getter @Setter
// private String user;
//
// @Value("${store.password}")
// @NotNull
// @Getter @Setter
// private String password;
//
// @Value("${hdfs.userspace.chroot}")
// @NotNull
// @Getter @Setter
// private String userspaceChroot;
//
// @Value("${hdfs.provided.zip}")
// @NotNull
// @Getter @Setter
// private String hdfsProvidedZip;
//
// @Value("${hdfs.superuser}")
// @NotNull
// @Getter @Setter
// private String hdfsSuperuser;
//
// @Value("${hdfs.keytab}")
// @NotNull
// @Getter @Setter
// private String hdfsSuperuserKeytab;
//
// }
| import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.FileUtil;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hdfs.MiniDFSCluster;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.trustedanalytics.servicebroker.hdfs.config.ExternalConfiguration; | /**
* Copyright (c) 2015 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.trustedanalytics.servicebroker.hdfs.integration.config;
@Configuration
@Profile("integration-test")
public class HdfsLocalConfiguration {
@Autowired | // Path: src/main/java/org/trustedanalytics/servicebroker/hdfs/config/ExternalConfiguration.java
// @Configuration
// public class ExternalConfiguration {
//
// @Value("${store.user}")
// @NotNull
// @Getter @Setter
// private String user;
//
// @Value("${store.password}")
// @NotNull
// @Getter @Setter
// private String password;
//
// @Value("${hdfs.userspace.chroot}")
// @NotNull
// @Getter @Setter
// private String userspaceChroot;
//
// @Value("${hdfs.provided.zip}")
// @NotNull
// @Getter @Setter
// private String hdfsProvidedZip;
//
// @Value("${hdfs.superuser}")
// @NotNull
// @Getter @Setter
// private String hdfsSuperuser;
//
// @Value("${hdfs.keytab}")
// @NotNull
// @Getter @Setter
// private String hdfsSuperuserKeytab;
//
// }
// Path: src/test/java/org/trustedanalytics/servicebroker/hdfs/integration/config/HdfsLocalConfiguration.java
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.FileUtil;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hdfs.MiniDFSCluster;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.trustedanalytics.servicebroker.hdfs.config.ExternalConfiguration;
/**
* Copyright (c) 2015 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.trustedanalytics.servicebroker.hdfs.integration.config;
@Configuration
@Profile("integration-test")
public class HdfsLocalConfiguration {
@Autowired | private ExternalConfiguration externalConfiguration; |
disassemble-io/asm-framework-full | src/test/java/GrepTest.java | // Path: src/main/java/io/disassemble/asm/util/Grep.java
// public class Grep {
//
// private final String pattern;
//
// /**
// * Creates a Grep object based on the given pattern.
// *
// * @param pattern The basic grep pattern to be used.
// */
// public Grep(String pattern) {
// this.pattern = pattern;
// }
//
// /**
// * Executes this Grep's pattern on the given string.
// *
// * @param test The string to be tested for matches.
// * @return The matches in a map denoted by their {label}
// */
// public Map<String, String> exec(String test) {
// Map<String, String> matches = new HashMap<>();
// int start = -1, prevEnd = 0, lookup = 0;
// StringBuilder tag = new StringBuilder();
// for (int i = 0; i < pattern.length(); i++) {
// char c = pattern.charAt(i);
// if (c == '{') {
// start = i;
// } else if (start != -1 && (tag.length() > 0) && c == '}') {
// String backwards = pattern.substring(prevEnd, start);
// int idx = test.indexOf(backwards, lookup);
// if (idx == -1) {
// return null;
// }
// // endIdx might actually need to be improved for inner string vars if it contains
// // whatever character comes after the grouping.
// int endIdx = test.indexOf(pattern.charAt(i + 1), lookup + 1);
// if (endIdx == -1) {
// return null;
// }
// matches.put(tag.toString(), test.substring(idx + backwards.length(), endIdx));
// lookup = idx;
// prevEnd = (i + 1);
// tag = new StringBuilder();
// start = -1;
// } else if (start != -1) {
// tag.append(c);
// }
// }
// return matches;
// }
// }
| import io.disassemble.asm.util.Grep;
import org.junit.Test;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern; |
/**
* @author Tyler Sedlar
* @since 6/24/16
*/
public class GrepTest {
@Test
public void test() {
String test = "client.qj(765, 503, 116)";
Pattern pattern = Pattern.compile("(.+)\\.(.+)\\(765, 503, (.+)\\)");
long start = System.nanoTime();
Matcher matcher = pattern.matcher(test);
boolean found = matcher.find();
long end = System.nanoTime();
System.out.println("regex: " + (end - start) + "ns");
System.out.printf(" %.5f millis\n", (end - start) / 1e6);
System.out.println(" " + matcher.group(3)); | // Path: src/main/java/io/disassemble/asm/util/Grep.java
// public class Grep {
//
// private final String pattern;
//
// /**
// * Creates a Grep object based on the given pattern.
// *
// * @param pattern The basic grep pattern to be used.
// */
// public Grep(String pattern) {
// this.pattern = pattern;
// }
//
// /**
// * Executes this Grep's pattern on the given string.
// *
// * @param test The string to be tested for matches.
// * @return The matches in a map denoted by their {label}
// */
// public Map<String, String> exec(String test) {
// Map<String, String> matches = new HashMap<>();
// int start = -1, prevEnd = 0, lookup = 0;
// StringBuilder tag = new StringBuilder();
// for (int i = 0; i < pattern.length(); i++) {
// char c = pattern.charAt(i);
// if (c == '{') {
// start = i;
// } else if (start != -1 && (tag.length() > 0) && c == '}') {
// String backwards = pattern.substring(prevEnd, start);
// int idx = test.indexOf(backwards, lookup);
// if (idx == -1) {
// return null;
// }
// // endIdx might actually need to be improved for inner string vars if it contains
// // whatever character comes after the grouping.
// int endIdx = test.indexOf(pattern.charAt(i + 1), lookup + 1);
// if (endIdx == -1) {
// return null;
// }
// matches.put(tag.toString(), test.substring(idx + backwards.length(), endIdx));
// lookup = idx;
// prevEnd = (i + 1);
// tag = new StringBuilder();
// start = -1;
// } else if (start != -1) {
// tag.append(c);
// }
// }
// return matches;
// }
// }
// Path: src/test/java/GrepTest.java
import io.disassemble.asm.util.Grep;
import org.junit.Test;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author Tyler Sedlar
* @since 6/24/16
*/
public class GrepTest {
@Test
public void test() {
String test = "client.qj(765, 503, 116)";
Pattern pattern = Pattern.compile("(.+)\\.(.+)\\(765, 503, (.+)\\)");
long start = System.nanoTime();
Matcher matcher = pattern.matcher(test);
boolean found = matcher.find();
long end = System.nanoTime();
System.out.println("regex: " + (end - start) + "ns");
System.out.printf(" %.5f millis\n", (end - start) / 1e6);
System.out.println(" " + matcher.group(3)); | Grep grep = new Grep("{class}.{method}(765, 503, {rev})"); |
disassemble-io/asm-framework-full | src/main/java/io/disassemble/asm/visitor/expr/grep/MethodExprGrep.java | // Path: src/main/java/io/disassemble/asm/visitor/expr/node/MethodExpr.java
// public class MethodExpr extends MemberExpr<MethodInsnNode> {
//
// /**
// * Constructs a BasicExpr for the given instruction and type.
// *
// * @param method The method this expression is in.
// * @param insn The instruction to use.
// * @param index The index of this instruction in the reverse stack.
// * @param size The amount of slots taken up by this instruction.
// */
// public MethodExpr(ClassMethod method, MethodInsnNode insn, int index, int size) {
// super(method, insn, index, size);
// }
//
// @Override
// public String key() {
// return (owner() + '.' + name() + desc());
// }
//
// @Override
// public String owner() {
// return ((MethodInsnNode) insn).owner;
// }
//
// @Override
// public String name() {
// return ((MethodInsnNode) insn).name;
// }
//
// @Override
// public String desc() {
// return ((MethodInsnNode) insn).desc;
// }
//
// @Override
// public String decompile() {
// return decompile(true);
// }
//
// public String decompile(boolean opaque) {
// String[] args = args(opaque);
// return (owner() + '.' + name() + '(' + String.join(", ", (CharSequence[]) args) + ')');
// }
//
// // This obviously needs to be improved, it's for debugging purposes, currently.
// private boolean hasOpaque() {
// BasicExpr expr = children.peekLast();
// return expr.opcode() == LDC && ((LdcInsnNode) expr.insn).cst instanceof Number;
// }
//
// public String[] args(boolean opaque) {
// if (children.isEmpty()) {
// return new String[0];
// }
// boolean skipFirst = (opcode() != INVOKESTATIC && opcode() != INVOKEDYNAMIC);
// String[] args = new String[skipFirst ? (children.size() - 1) : children.size()];
// boolean stripped = false;
// if (opaque && hasOpaque()) {
// args = new String[args.length - 1];
// stripped = true;
// }
// int idx = 0;
// for (BasicExpr child : children) {
// if (skipFirst && child == children.peekFirst()) {
// continue;
// } else if (stripped && (idx + 1) > args.length) {
// continue;
// }
// String val = ExprExtractor.extract(child);
// args[idx++] = val;
// }
// return args;
// }
//
// public String[] args() {
// return args(true);
// }
// }
| import io.disassemble.asm.visitor.expr.node.MethodExpr;
import java.util.Map;
import java.util.function.Consumer; | package io.disassemble.asm.visitor.expr.grep;
/**
* @author Tyler Sedlar
* @since 6/25/16
*/
public class MethodExprGrep extends GrepExpr {
public MethodExprGrep(String query, Consumer<Map<String, String>> consumer) { | // Path: src/main/java/io/disassemble/asm/visitor/expr/node/MethodExpr.java
// public class MethodExpr extends MemberExpr<MethodInsnNode> {
//
// /**
// * Constructs a BasicExpr for the given instruction and type.
// *
// * @param method The method this expression is in.
// * @param insn The instruction to use.
// * @param index The index of this instruction in the reverse stack.
// * @param size The amount of slots taken up by this instruction.
// */
// public MethodExpr(ClassMethod method, MethodInsnNode insn, int index, int size) {
// super(method, insn, index, size);
// }
//
// @Override
// public String key() {
// return (owner() + '.' + name() + desc());
// }
//
// @Override
// public String owner() {
// return ((MethodInsnNode) insn).owner;
// }
//
// @Override
// public String name() {
// return ((MethodInsnNode) insn).name;
// }
//
// @Override
// public String desc() {
// return ((MethodInsnNode) insn).desc;
// }
//
// @Override
// public String decompile() {
// return decompile(true);
// }
//
// public String decompile(boolean opaque) {
// String[] args = args(opaque);
// return (owner() + '.' + name() + '(' + String.join(", ", (CharSequence[]) args) + ')');
// }
//
// // This obviously needs to be improved, it's for debugging purposes, currently.
// private boolean hasOpaque() {
// BasicExpr expr = children.peekLast();
// return expr.opcode() == LDC && ((LdcInsnNode) expr.insn).cst instanceof Number;
// }
//
// public String[] args(boolean opaque) {
// if (children.isEmpty()) {
// return new String[0];
// }
// boolean skipFirst = (opcode() != INVOKESTATIC && opcode() != INVOKEDYNAMIC);
// String[] args = new String[skipFirst ? (children.size() - 1) : children.size()];
// boolean stripped = false;
// if (opaque && hasOpaque()) {
// args = new String[args.length - 1];
// stripped = true;
// }
// int idx = 0;
// for (BasicExpr child : children) {
// if (skipFirst && child == children.peekFirst()) {
// continue;
// } else if (stripped && (idx + 1) > args.length) {
// continue;
// }
// String val = ExprExtractor.extract(child);
// args[idx++] = val;
// }
// return args;
// }
//
// public String[] args() {
// return args(true);
// }
// }
// Path: src/main/java/io/disassemble/asm/visitor/expr/grep/MethodExprGrep.java
import io.disassemble.asm.visitor.expr.node.MethodExpr;
import java.util.Map;
import java.util.function.Consumer;
package io.disassemble.asm.visitor.expr.grep;
/**
* @author Tyler Sedlar
* @since 6/25/16
*/
public class MethodExprGrep extends GrepExpr {
public MethodExprGrep(String query, Consumer<Map<String, String>> consumer) { | super(query, MethodExpr.class, consumer); |
disassemble-io/asm-framework-full | src/main/java/io/disassemble/asm/pattern/nano/oop/FieldWriter.java | // Path: src/main/java/io/disassemble/asm/pattern/nano/AdvancedNanoPattern.java
// public abstract class AdvancedNanoPattern extends NanoPattern {
//
// @Override
// public final boolean matches(ClassMethod method) {
// return false;
// }
// }
| import io.disassemble.asm.pattern.nano.AdvancedNanoPattern;
import io.disassemble.asm.pattern.nano.PatternInfo;
import org.objectweb.asm.tree.AbstractInsnNode;
import static org.objectweb.asm.Opcodes.PUTFIELD;
import static org.objectweb.asm.Opcodes.PUTSTATIC; | package io.disassemble.asm.pattern.nano.oop;
/**
* @author Tyler Sedlar
* @since 2/1/16
*/
@PatternInfo(category = "Object-Orientation", name = "FieldWriter", simple = false,
description = "writes values to (static or instance) field of an object") | // Path: src/main/java/io/disassemble/asm/pattern/nano/AdvancedNanoPattern.java
// public abstract class AdvancedNanoPattern extends NanoPattern {
//
// @Override
// public final boolean matches(ClassMethod method) {
// return false;
// }
// }
// Path: src/main/java/io/disassemble/asm/pattern/nano/oop/FieldWriter.java
import io.disassemble.asm.pattern.nano.AdvancedNanoPattern;
import io.disassemble.asm.pattern.nano.PatternInfo;
import org.objectweb.asm.tree.AbstractInsnNode;
import static org.objectweb.asm.Opcodes.PUTFIELD;
import static org.objectweb.asm.Opcodes.PUTSTATIC;
package io.disassemble.asm.pattern.nano.oop;
/**
* @author Tyler Sedlar
* @since 2/1/16
*/
@PatternInfo(category = "Object-Orientation", name = "FieldWriter", simple = false,
description = "writes values to (static or instance) field of an object") | public class FieldWriter extends AdvancedNanoPattern { |
disassemble-io/asm-framework-full | src/test/java/Debugger.java | // Path: src/main/java/io/disassemble/asm/visitor/flow/FlowQueryResult.java
// public class FlowQueryResult {
//
// private final FlowQuery query;
// private final List<BasicInstruction> instructions;
//
// public FlowQueryResult(FlowQuery query, List<BasicInstruction> instructions) {
// this.query = query;
// this.instructions = instructions;
// }
//
// /**
// * Finds the BasicInstruction with the given name.
// *
// * @param name The name to search for.
// * @return The BasicInstruction with the given name.
// */
// public Optional<BasicInstruction> findBasicInstruction(String name) {
// for (int i = 0; i < instructions.size(); i++) {
// String nodeName = query.nameAt(i);
// if (nodeName != null && nodeName.equals(name)) {
// return Optional.ofNullable(instructions.get(i));
// }
// }
// return Optional.empty();
// }
//
// /**
// * Finds the AbstractInsnNode with the given name.
// *
// * @param name The name to search for.
// * @return The AbstractInsnNode with the given name.
// */
// public Optional<AbstractInsnNode> findInstruction(String name) {
// Optional<BasicInstruction> insn = findBasicInstruction(name);
// return (insn.flatMap(basicInstruction -> Optional.ofNullable(basicInstruction.insn)));
// }
//
// /**
// * Gets a map of the named instructions from the FlowQuery.
// *
// * @return A map of the named instructions from the FlowQuery.
// */
// public Map<String, AbstractInsnNode> namedInstructions() {
// Map<String, AbstractInsnNode> instructions = new HashMap<>();
// for (int i = 0; i < this.instructions.size(); i++) {
// String nodeName = query.nameAt(i);
// if (nodeName != null) {
// instructions.put(nodeName, this.instructions.get(i).insn);
// }
// }
// return instructions;
// }
// }
| import io.disassemble.asm.ClassMethod;
import io.disassemble.asm.visitor.flow.FlowQuery;
import io.disassemble.asm.visitor.flow.FlowQueryResult;
import org.junit.BeforeClass;
import org.junit.Test;
import java.util.HashMap;
import java.util.List;
import java.util.Map; |
/**
* @author Tyler Sedlar
* @since 2/1/16
*/
public class Debugger {
private static final String TEST_CLASS_NAME = "Sample";
private static final Map<String, ClassMethod> methods = new HashMap<>();
@BeforeClass
public static void setup() {
ClassScanner.scanClassPath(
cn -> cn.name.equals(TEST_CLASS_NAME),
cm -> methods.put(cm.key(), cm)
);
}
@Test
public void testControlFlowGraph() {
methods.values().forEach(cm -> {
if (cm.name().contains("<")) {
return;
}
if (cm.name().contains("cfg")) {
try {
long start = System.nanoTime();
cm.cfg().ifPresent(cfg -> {
cfg.execution().print(1);
// cfg.printBasicBlocks(); | // Path: src/main/java/io/disassemble/asm/visitor/flow/FlowQueryResult.java
// public class FlowQueryResult {
//
// private final FlowQuery query;
// private final List<BasicInstruction> instructions;
//
// public FlowQueryResult(FlowQuery query, List<BasicInstruction> instructions) {
// this.query = query;
// this.instructions = instructions;
// }
//
// /**
// * Finds the BasicInstruction with the given name.
// *
// * @param name The name to search for.
// * @return The BasicInstruction with the given name.
// */
// public Optional<BasicInstruction> findBasicInstruction(String name) {
// for (int i = 0; i < instructions.size(); i++) {
// String nodeName = query.nameAt(i);
// if (nodeName != null && nodeName.equals(name)) {
// return Optional.ofNullable(instructions.get(i));
// }
// }
// return Optional.empty();
// }
//
// /**
// * Finds the AbstractInsnNode with the given name.
// *
// * @param name The name to search for.
// * @return The AbstractInsnNode with the given name.
// */
// public Optional<AbstractInsnNode> findInstruction(String name) {
// Optional<BasicInstruction> insn = findBasicInstruction(name);
// return (insn.flatMap(basicInstruction -> Optional.ofNullable(basicInstruction.insn)));
// }
//
// /**
// * Gets a map of the named instructions from the FlowQuery.
// *
// * @return A map of the named instructions from the FlowQuery.
// */
// public Map<String, AbstractInsnNode> namedInstructions() {
// Map<String, AbstractInsnNode> instructions = new HashMap<>();
// for (int i = 0; i < this.instructions.size(); i++) {
// String nodeName = query.nameAt(i);
// if (nodeName != null) {
// instructions.put(nodeName, this.instructions.get(i).insn);
// }
// }
// return instructions;
// }
// }
// Path: src/test/java/Debugger.java
import io.disassemble.asm.ClassMethod;
import io.disassemble.asm.visitor.flow.FlowQuery;
import io.disassemble.asm.visitor.flow.FlowQueryResult;
import org.junit.BeforeClass;
import org.junit.Test;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author Tyler Sedlar
* @since 2/1/16
*/
public class Debugger {
private static final String TEST_CLASS_NAME = "Sample";
private static final Map<String, ClassMethod> methods = new HashMap<>();
@BeforeClass
public static void setup() {
ClassScanner.scanClassPath(
cn -> cn.name.equals(TEST_CLASS_NAME),
cm -> methods.put(cm.key(), cm)
);
}
@Test
public void testControlFlowGraph() {
methods.values().forEach(cm -> {
if (cm.name().contains("<")) {
return;
}
if (cm.name().contains("cfg")) {
try {
long start = System.nanoTime();
cm.cfg().ifPresent(cfg -> {
cfg.execution().print(1);
// cfg.printBasicBlocks(); | List<FlowQueryResult> results = cfg.execution().query( |
disassemble-io/asm-framework-full | src/main/java/io/disassemble/asm/pattern/nano/flow/data/LocalReader.java | // Path: src/main/java/io/disassemble/asm/pattern/nano/AdvancedNanoPattern.java
// public abstract class AdvancedNanoPattern extends NanoPattern {
//
// @Override
// public final boolean matches(ClassMethod method) {
// return false;
// }
// }
| import io.disassemble.asm.pattern.nano.AdvancedNanoPattern;
import io.disassemble.asm.pattern.nano.PatternInfo;
import org.objectweb.asm.tree.AbstractInsnNode;
import static org.objectweb.asm.Opcodes.ALOAD;
import static org.objectweb.asm.Opcodes.ILOAD; | package io.disassemble.asm.pattern.nano.flow.data;
/**
* @author Tyler Sedlar
* @since 2/1/16
*/
@PatternInfo(category = "Data Flow", name = "LocalReader", simple = false,
description = "reads values of local variables on stack frame") | // Path: src/main/java/io/disassemble/asm/pattern/nano/AdvancedNanoPattern.java
// public abstract class AdvancedNanoPattern extends NanoPattern {
//
// @Override
// public final boolean matches(ClassMethod method) {
// return false;
// }
// }
// Path: src/main/java/io/disassemble/asm/pattern/nano/flow/data/LocalReader.java
import io.disassemble.asm.pattern.nano.AdvancedNanoPattern;
import io.disassemble.asm.pattern.nano.PatternInfo;
import org.objectweb.asm.tree.AbstractInsnNode;
import static org.objectweb.asm.Opcodes.ALOAD;
import static org.objectweb.asm.Opcodes.ILOAD;
package io.disassemble.asm.pattern.nano.flow.data;
/**
* @author Tyler Sedlar
* @since 2/1/16
*/
@PatternInfo(category = "Data Flow", name = "LocalReader", simple = false,
description = "reads values of local variables on stack frame") | public class LocalReader extends AdvancedNanoPattern { |
disassemble-io/asm-framework-full | src/main/java/io/disassemble/asm/visitor/expr/node/MethodExpr.java | // Path: src/main/java/io/disassemble/asm/visitor/expr/ExprExtractor.java
// public class ExprExtractor {
//
// private static final String EMPTY_STRING = "";
//
// public static String extract(BasicExpr expr) {
// AbstractInsnNode insn = expr.insn();
// if (insn instanceof IntInsnNode) {
// int operand = ((IntInsnNode) insn).operand;
// return Integer.toString(operand);
// } else if (insn instanceof LdcInsnNode) {
// Object ldc = ((LdcInsnNode) insn).cst;
// return (ldc == null ? "null" : ldc.toString());
// }
// return EMPTY_STRING;
// }
// }
| import io.disassemble.asm.ClassMethod;
import io.disassemble.asm.visitor.expr.ExprExtractor;
import org.objectweb.asm.tree.LdcInsnNode;
import org.objectweb.asm.tree.MethodInsnNode;
import static org.objectweb.asm.Opcodes.*; |
public String decompile(boolean opaque) {
String[] args = args(opaque);
return (owner() + '.' + name() + '(' + String.join(", ", (CharSequence[]) args) + ')');
}
// This obviously needs to be improved, it's for debugging purposes, currently.
private boolean hasOpaque() {
BasicExpr expr = children.peekLast();
return expr.opcode() == LDC && ((LdcInsnNode) expr.insn).cst instanceof Number;
}
public String[] args(boolean opaque) {
if (children.isEmpty()) {
return new String[0];
}
boolean skipFirst = (opcode() != INVOKESTATIC && opcode() != INVOKEDYNAMIC);
String[] args = new String[skipFirst ? (children.size() - 1) : children.size()];
boolean stripped = false;
if (opaque && hasOpaque()) {
args = new String[args.length - 1];
stripped = true;
}
int idx = 0;
for (BasicExpr child : children) {
if (skipFirst && child == children.peekFirst()) {
continue;
} else if (stripped && (idx + 1) > args.length) {
continue;
} | // Path: src/main/java/io/disassemble/asm/visitor/expr/ExprExtractor.java
// public class ExprExtractor {
//
// private static final String EMPTY_STRING = "";
//
// public static String extract(BasicExpr expr) {
// AbstractInsnNode insn = expr.insn();
// if (insn instanceof IntInsnNode) {
// int operand = ((IntInsnNode) insn).operand;
// return Integer.toString(operand);
// } else if (insn instanceof LdcInsnNode) {
// Object ldc = ((LdcInsnNode) insn).cst;
// return (ldc == null ? "null" : ldc.toString());
// }
// return EMPTY_STRING;
// }
// }
// Path: src/main/java/io/disassemble/asm/visitor/expr/node/MethodExpr.java
import io.disassemble.asm.ClassMethod;
import io.disassemble.asm.visitor.expr.ExprExtractor;
import org.objectweb.asm.tree.LdcInsnNode;
import org.objectweb.asm.tree.MethodInsnNode;
import static org.objectweb.asm.Opcodes.*;
public String decompile(boolean opaque) {
String[] args = args(opaque);
return (owner() + '.' + name() + '(' + String.join(", ", (CharSequence[]) args) + ')');
}
// This obviously needs to be improved, it's for debugging purposes, currently.
private boolean hasOpaque() {
BasicExpr expr = children.peekLast();
return expr.opcode() == LDC && ((LdcInsnNode) expr.insn).cst instanceof Number;
}
public String[] args(boolean opaque) {
if (children.isEmpty()) {
return new String[0];
}
boolean skipFirst = (opcode() != INVOKESTATIC && opcode() != INVOKEDYNAMIC);
String[] args = new String[skipFirst ? (children.size() - 1) : children.size()];
boolean stripped = false;
if (opaque && hasOpaque()) {
args = new String[args.length - 1];
stripped = true;
}
int idx = 0;
for (BasicExpr child : children) {
if (skipFirst && child == children.peekFirst()) {
continue;
} else if (stripped && (idx + 1) > args.length) {
continue;
} | String val = ExprExtractor.extract(child); |
disassemble-io/asm-framework-full | src/main/java/io/disassemble/asm/pattern/nano/oop/FieldReader.java | // Path: src/main/java/io/disassemble/asm/pattern/nano/AdvancedNanoPattern.java
// public abstract class AdvancedNanoPattern extends NanoPattern {
//
// @Override
// public final boolean matches(ClassMethod method) {
// return false;
// }
// }
| import io.disassemble.asm.pattern.nano.AdvancedNanoPattern;
import io.disassemble.asm.pattern.nano.PatternInfo;
import org.objectweb.asm.tree.AbstractInsnNode;
import static org.objectweb.asm.Opcodes.GETFIELD;
import static org.objectweb.asm.Opcodes.GETSTATIC; | package io.disassemble.asm.pattern.nano.oop;
/**
* @author Tyler Sedlar
* @since 2/1/16
*/
@PatternInfo(category = "Object-Orientation", name = "FieldReader", simple = false,
description = "reads (static or instance) field values from an object") | // Path: src/main/java/io/disassemble/asm/pattern/nano/AdvancedNanoPattern.java
// public abstract class AdvancedNanoPattern extends NanoPattern {
//
// @Override
// public final boolean matches(ClassMethod method) {
// return false;
// }
// }
// Path: src/main/java/io/disassemble/asm/pattern/nano/oop/FieldReader.java
import io.disassemble.asm.pattern.nano.AdvancedNanoPattern;
import io.disassemble.asm.pattern.nano.PatternInfo;
import org.objectweb.asm.tree.AbstractInsnNode;
import static org.objectweb.asm.Opcodes.GETFIELD;
import static org.objectweb.asm.Opcodes.GETSTATIC;
package io.disassemble.asm.pattern.nano.oop;
/**
* @author Tyler Sedlar
* @since 2/1/16
*/
@PatternInfo(category = "Object-Orientation", name = "FieldReader", simple = false,
description = "reads (static or instance) field values from an object") | public class FieldReader extends AdvancedNanoPattern { |
disassemble-io/asm-framework-full | src/main/java/io/disassemble/asm/pattern/nano/flow/data/LocalWriter.java | // Path: src/main/java/io/disassemble/asm/pattern/nano/AdvancedNanoPattern.java
// public abstract class AdvancedNanoPattern extends NanoPattern {
//
// @Override
// public final boolean matches(ClassMethod method) {
// return false;
// }
// }
| import io.disassemble.asm.pattern.nano.AdvancedNanoPattern;
import io.disassemble.asm.pattern.nano.PatternInfo;
import org.objectweb.asm.tree.AbstractInsnNode;
import static org.objectweb.asm.Opcodes.ASTORE;
import static org.objectweb.asm.Opcodes.ISTORE; | package io.disassemble.asm.pattern.nano.flow.data;
/**
* @author Tyler Sedlar
* @since 2/1/16
*/
@PatternInfo(category = "Data Flow", name = "LocalWriter", simple = false,
description = "writes values of local variables on stack frame") | // Path: src/main/java/io/disassemble/asm/pattern/nano/AdvancedNanoPattern.java
// public abstract class AdvancedNanoPattern extends NanoPattern {
//
// @Override
// public final boolean matches(ClassMethod method) {
// return false;
// }
// }
// Path: src/main/java/io/disassemble/asm/pattern/nano/flow/data/LocalWriter.java
import io.disassemble.asm.pattern.nano.AdvancedNanoPattern;
import io.disassemble.asm.pattern.nano.PatternInfo;
import org.objectweb.asm.tree.AbstractInsnNode;
import static org.objectweb.asm.Opcodes.ASTORE;
import static org.objectweb.asm.Opcodes.ISTORE;
package io.disassemble.asm.pattern.nano.flow.data;
/**
* @author Tyler Sedlar
* @since 2/1/16
*/
@PatternInfo(category = "Data Flow", name = "LocalWriter", simple = false,
description = "writes values of local variables on stack frame") | public class LocalWriter extends AdvancedNanoPattern { |
ArthurHub/Android-Fast-Image-Loader | fastimageloader/src/main/java/com/theartofdev/fastimageloader/target/TargetHelper.java | // Path: fastimageloader/src/main/java/com/theartofdev/fastimageloader/LoadedFrom.java
// public enum LoadedFrom {
// MEMORY,
// DISK,
// NETWORK
// }
| import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import com.theartofdev.fastimageloader.LoadedFrom;
import static android.graphics.Color.GREEN;
import static android.graphics.Color.RED;
import static android.graphics.Color.WHITE;
import static android.graphics.Color.YELLOW; | // "Therefore those skilled at the unorthodox
// are infinite as heaven and earth,
// inexhaustible as the great rivers.
// When they come to an end,
// they begin again,
// like the days and months;
// they die and are reborn,
// like the four seasons."
//
// - Sun Tsu,
// "The Art of War"
package com.theartofdev.fastimageloader.target;
/**
* Helper methods for Target Drawable or Image View code.
*/
public final class TargetHelper {
/**
* Used to paint debug indicator
*/
private static Paint mDebugPaint;
/**
* Paint used to draw download progress
*/
private static Paint mProgressPaint;
/**
* If to show indicator if the image was loaded from MEMORY/DISK/NETWORK.
*/
public static boolean debugIndicator;
/**
* The density of the current
*/
public static float mDensity;
private TargetHelper() {
}
/**
* draw indicator on where the image was loaded from.<br>
* Green - memory, Yellow - disk, Red - network.
*/ | // Path: fastimageloader/src/main/java/com/theartofdev/fastimageloader/LoadedFrom.java
// public enum LoadedFrom {
// MEMORY,
// DISK,
// NETWORK
// }
// Path: fastimageloader/src/main/java/com/theartofdev/fastimageloader/target/TargetHelper.java
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import com.theartofdev.fastimageloader.LoadedFrom;
import static android.graphics.Color.GREEN;
import static android.graphics.Color.RED;
import static android.graphics.Color.WHITE;
import static android.graphics.Color.YELLOW;
// "Therefore those skilled at the unorthodox
// are infinite as heaven and earth,
// inexhaustible as the great rivers.
// When they come to an end,
// they begin again,
// like the days and months;
// they die and are reborn,
// like the four seasons."
//
// - Sun Tsu,
// "The Art of War"
package com.theartofdev.fastimageloader.target;
/**
* Helper methods for Target Drawable or Image View code.
*/
public final class TargetHelper {
/**
* Used to paint debug indicator
*/
private static Paint mDebugPaint;
/**
* Paint used to draw download progress
*/
private static Paint mProgressPaint;
/**
* If to show indicator if the image was loaded from MEMORY/DISK/NETWORK.
*/
public static boolean debugIndicator;
/**
* The density of the current
*/
public static float mDensity;
private TargetHelper() {
}
/**
* draw indicator on where the image was loaded from.<br>
* Green - memory, Yellow - disk, Red - network.
*/ | public static void drawDebugIndicator(Canvas canvas, LoadedFrom loadedFrom, int width, int height) { |
ArthurHub/Android-Fast-Image-Loader | fastimageloader/src/main/java/com/theartofdev/fastimageloader/adapter/IdentityAdapter.java | // Path: fastimageloader/src/main/java/com/theartofdev/fastimageloader/ImageLoadSpec.java
// public final class ImageLoadSpec {
//
// //region: Fields and Consts
//
// /**
// * the unique key of the spec used for identification and debug
// */
// private final String mKey;
//
// /**
// * the width of the image in pixels
// */
// private final int mWidth;
//
// /**
// * the height of the image in pixels
// */
// private final int mHeight;
//
// /**
// * The format of the image.
// */
// private final Format mFormat;
//
// /**
// * the pixel configuration to load the image in (4 bytes per image pixel, 2 bytes, etc.)
// */
// private final Bitmap.Config mPixelConfig;
//
// /**
// * The URI enhancer to use for this spec image loading
// */
// private final ImageServiceAdapter mImageServiceAdapter;
// //endregion
//
// /**
// * Init image loading spec.
// *
// * @param key the unique key of the spec used for identification and debug
// * @param width the width of the image in pixels
// * @param height the height of the image in pixels
// * @param format The format of the image.
// * @param pixelConfig the pixel configuration to load the image in (4 bytes per image pixel, 2 bytes, etc.)
// * @param imageServiceAdapter The URI enhancer to use for this spec image loading
// */
// ImageLoadSpec(String key, int width, int height, Format format, Bitmap.Config pixelConfig, ImageServiceAdapter imageServiceAdapter) {
// mKey = key;
// mWidth = width;
// mHeight = height;
// mFormat = format;
// mPixelConfig = pixelConfig;
// mImageServiceAdapter = imageServiceAdapter;
// }
//
// /**
// * the unique key of the spec used for identification and debug
// */
// public String getKey() {
// return mKey;
// }
//
// /**
// * the width of the image in pixels
// */
// public int getWidth() {
// return mWidth;
// }
//
// /**
// * the height of the image in pixels
// */
// public int getHeight() {
// return mHeight;
// }
//
// /**
// * The format of the image.
// */
// public Format getFormat() {
// return mFormat;
// }
//
// /**
// * the pixel configuration to load the image in (4 bytes per image pixel, 2 bytes, etc.)
// */
// public Bitmap.Config getPixelConfig() {
// return mPixelConfig;
// }
//
// /**
// * The URI enhancer to use for this spec image loading
// */
// public ImageServiceAdapter getImageServiceAdapter() {
// return mImageServiceAdapter;
// }
//
// /**
// * Is the spec define specific width and height for the image.
// */
// public boolean isSizeBounded() {
// return mWidth > 0 && mHeight > 0;
// }
//
// @Override
// public String toString() {
// return "ImageLoadSpec{" +
// "mKey='" + mKey + '\'' +
// ", mWidth=" + mWidth +
// ", mHeight=" + mHeight +
// ", mFormat=" + mFormat +
// ", mPixelConfig=" + mPixelConfig +
// ", mImageServiceAdapter=" + mImageServiceAdapter +
// '}';
// }
//
// //region: Inner class: Format
//
// /**
// * The format of the image.
// */
// public static enum Format {
// UNCHANGE,
// JPEG,
// PNG,
// WEBP,
// }
// //endregion
// }
//
// Path: fastimageloader/src/main/java/com/theartofdev/fastimageloader/ImageServiceAdapter.java
// public interface ImageServiceAdapter {
//
// /**
// * Add to raw image loading URI the required specifications (format/size/etc.) parameters.
// *
// * @param uri the raw image URI to convert
// * @param spec the image loading specification to convert by
// * @return URI with loading specification
// */
// String convert(String uri, ImageLoadSpec spec);
// }
| import com.theartofdev.fastimageloader.ImageLoadSpec;
import com.theartofdev.fastimageloader.ImageServiceAdapter; | // "Therefore those skilled at the unorthodox
// are infinite as heaven and earth,
// inexhaustible as the great rivers.
// When they come to an end,
// they begin again,
// like the days and months;
// they die and are reborn,
// like the four seasons."
//
// - Sun Tsu,
// "The Art of War"
package com.theartofdev.fastimageloader.adapter;
/**
* Doesn't change the URI.
*/
public class IdentityAdapter implements ImageServiceAdapter {
@Override | // Path: fastimageloader/src/main/java/com/theartofdev/fastimageloader/ImageLoadSpec.java
// public final class ImageLoadSpec {
//
// //region: Fields and Consts
//
// /**
// * the unique key of the spec used for identification and debug
// */
// private final String mKey;
//
// /**
// * the width of the image in pixels
// */
// private final int mWidth;
//
// /**
// * the height of the image in pixels
// */
// private final int mHeight;
//
// /**
// * The format of the image.
// */
// private final Format mFormat;
//
// /**
// * the pixel configuration to load the image in (4 bytes per image pixel, 2 bytes, etc.)
// */
// private final Bitmap.Config mPixelConfig;
//
// /**
// * The URI enhancer to use for this spec image loading
// */
// private final ImageServiceAdapter mImageServiceAdapter;
// //endregion
//
// /**
// * Init image loading spec.
// *
// * @param key the unique key of the spec used for identification and debug
// * @param width the width of the image in pixels
// * @param height the height of the image in pixels
// * @param format The format of the image.
// * @param pixelConfig the pixel configuration to load the image in (4 bytes per image pixel, 2 bytes, etc.)
// * @param imageServiceAdapter The URI enhancer to use for this spec image loading
// */
// ImageLoadSpec(String key, int width, int height, Format format, Bitmap.Config pixelConfig, ImageServiceAdapter imageServiceAdapter) {
// mKey = key;
// mWidth = width;
// mHeight = height;
// mFormat = format;
// mPixelConfig = pixelConfig;
// mImageServiceAdapter = imageServiceAdapter;
// }
//
// /**
// * the unique key of the spec used for identification and debug
// */
// public String getKey() {
// return mKey;
// }
//
// /**
// * the width of the image in pixels
// */
// public int getWidth() {
// return mWidth;
// }
//
// /**
// * the height of the image in pixels
// */
// public int getHeight() {
// return mHeight;
// }
//
// /**
// * The format of the image.
// */
// public Format getFormat() {
// return mFormat;
// }
//
// /**
// * the pixel configuration to load the image in (4 bytes per image pixel, 2 bytes, etc.)
// */
// public Bitmap.Config getPixelConfig() {
// return mPixelConfig;
// }
//
// /**
// * The URI enhancer to use for this spec image loading
// */
// public ImageServiceAdapter getImageServiceAdapter() {
// return mImageServiceAdapter;
// }
//
// /**
// * Is the spec define specific width and height for the image.
// */
// public boolean isSizeBounded() {
// return mWidth > 0 && mHeight > 0;
// }
//
// @Override
// public String toString() {
// return "ImageLoadSpec{" +
// "mKey='" + mKey + '\'' +
// ", mWidth=" + mWidth +
// ", mHeight=" + mHeight +
// ", mFormat=" + mFormat +
// ", mPixelConfig=" + mPixelConfig +
// ", mImageServiceAdapter=" + mImageServiceAdapter +
// '}';
// }
//
// //region: Inner class: Format
//
// /**
// * The format of the image.
// */
// public static enum Format {
// UNCHANGE,
// JPEG,
// PNG,
// WEBP,
// }
// //endregion
// }
//
// Path: fastimageloader/src/main/java/com/theartofdev/fastimageloader/ImageServiceAdapter.java
// public interface ImageServiceAdapter {
//
// /**
// * Add to raw image loading URI the required specifications (format/size/etc.) parameters.
// *
// * @param uri the raw image URI to convert
// * @param spec the image loading specification to convert by
// * @return URI with loading specification
// */
// String convert(String uri, ImageLoadSpec spec);
// }
// Path: fastimageloader/src/main/java/com/theartofdev/fastimageloader/adapter/IdentityAdapter.java
import com.theartofdev.fastimageloader.ImageLoadSpec;
import com.theartofdev.fastimageloader.ImageServiceAdapter;
// "Therefore those skilled at the unorthodox
// are infinite as heaven and earth,
// inexhaustible as the great rivers.
// When they come to an end,
// they begin again,
// like the days and months;
// they die and are reborn,
// like the four seasons."
//
// - Sun Tsu,
// "The Art of War"
package com.theartofdev.fastimageloader.adapter;
/**
* Doesn't change the URI.
*/
public class IdentityAdapter implements ImageServiceAdapter {
@Override | public String convert(String uri, ImageLoadSpec spec) { |
ArthurHub/Android-Fast-Image-Loader | fastimageloader/src/main/java/com/theartofdev/fastimageloader/adapter/ImgIXAdapter.java | // Path: fastimageloader/src/main/java/com/theartofdev/fastimageloader/ImageLoadSpec.java
// public final class ImageLoadSpec {
//
// //region: Fields and Consts
//
// /**
// * the unique key of the spec used for identification and debug
// */
// private final String mKey;
//
// /**
// * the width of the image in pixels
// */
// private final int mWidth;
//
// /**
// * the height of the image in pixels
// */
// private final int mHeight;
//
// /**
// * The format of the image.
// */
// private final Format mFormat;
//
// /**
// * the pixel configuration to load the image in (4 bytes per image pixel, 2 bytes, etc.)
// */
// private final Bitmap.Config mPixelConfig;
//
// /**
// * The URI enhancer to use for this spec image loading
// */
// private final ImageServiceAdapter mImageServiceAdapter;
// //endregion
//
// /**
// * Init image loading spec.
// *
// * @param key the unique key of the spec used for identification and debug
// * @param width the width of the image in pixels
// * @param height the height of the image in pixels
// * @param format The format of the image.
// * @param pixelConfig the pixel configuration to load the image in (4 bytes per image pixel, 2 bytes, etc.)
// * @param imageServiceAdapter The URI enhancer to use for this spec image loading
// */
// ImageLoadSpec(String key, int width, int height, Format format, Bitmap.Config pixelConfig, ImageServiceAdapter imageServiceAdapter) {
// mKey = key;
// mWidth = width;
// mHeight = height;
// mFormat = format;
// mPixelConfig = pixelConfig;
// mImageServiceAdapter = imageServiceAdapter;
// }
//
// /**
// * the unique key of the spec used for identification and debug
// */
// public String getKey() {
// return mKey;
// }
//
// /**
// * the width of the image in pixels
// */
// public int getWidth() {
// return mWidth;
// }
//
// /**
// * the height of the image in pixels
// */
// public int getHeight() {
// return mHeight;
// }
//
// /**
// * The format of the image.
// */
// public Format getFormat() {
// return mFormat;
// }
//
// /**
// * the pixel configuration to load the image in (4 bytes per image pixel, 2 bytes, etc.)
// */
// public Bitmap.Config getPixelConfig() {
// return mPixelConfig;
// }
//
// /**
// * The URI enhancer to use for this spec image loading
// */
// public ImageServiceAdapter getImageServiceAdapter() {
// return mImageServiceAdapter;
// }
//
// /**
// * Is the spec define specific width and height for the image.
// */
// public boolean isSizeBounded() {
// return mWidth > 0 && mHeight > 0;
// }
//
// @Override
// public String toString() {
// return "ImageLoadSpec{" +
// "mKey='" + mKey + '\'' +
// ", mWidth=" + mWidth +
// ", mHeight=" + mHeight +
// ", mFormat=" + mFormat +
// ", mPixelConfig=" + mPixelConfig +
// ", mImageServiceAdapter=" + mImageServiceAdapter +
// '}';
// }
//
// //region: Inner class: Format
//
// /**
// * The format of the image.
// */
// public static enum Format {
// UNCHANGE,
// JPEG,
// PNG,
// WEBP,
// }
// //endregion
// }
//
// Path: fastimageloader/src/main/java/com/theartofdev/fastimageloader/ImageServiceAdapter.java
// public interface ImageServiceAdapter {
//
// /**
// * Add to raw image loading URI the required specifications (format/size/etc.) parameters.
// *
// * @param uri the raw image URI to convert
// * @param spec the image loading specification to convert by
// * @return URI with loading specification
// */
// String convert(String uri, ImageLoadSpec spec);
// }
| import com.theartofdev.fastimageloader.ImageLoadSpec;
import com.theartofdev.fastimageloader.ImageServiceAdapter; | // "Therefore those skilled at the unorthodox
// are infinite as heaven and earth,
// inexhaustible as the great rivers.
// When they come to an end,
// they begin again,
// like the days and months;
// they die and are reborn,
// like the four seasons."
//
// - Sun Tsu,
// "The Art of War"
package com.theartofdev.fastimageloader.adapter;
/**
* imgIX image service (http://www.imgix.com) adapter.<br>
*/
public class ImgIXAdapter implements ImageServiceAdapter {
@Override | // Path: fastimageloader/src/main/java/com/theartofdev/fastimageloader/ImageLoadSpec.java
// public final class ImageLoadSpec {
//
// //region: Fields and Consts
//
// /**
// * the unique key of the spec used for identification and debug
// */
// private final String mKey;
//
// /**
// * the width of the image in pixels
// */
// private final int mWidth;
//
// /**
// * the height of the image in pixels
// */
// private final int mHeight;
//
// /**
// * The format of the image.
// */
// private final Format mFormat;
//
// /**
// * the pixel configuration to load the image in (4 bytes per image pixel, 2 bytes, etc.)
// */
// private final Bitmap.Config mPixelConfig;
//
// /**
// * The URI enhancer to use for this spec image loading
// */
// private final ImageServiceAdapter mImageServiceAdapter;
// //endregion
//
// /**
// * Init image loading spec.
// *
// * @param key the unique key of the spec used for identification and debug
// * @param width the width of the image in pixels
// * @param height the height of the image in pixels
// * @param format The format of the image.
// * @param pixelConfig the pixel configuration to load the image in (4 bytes per image pixel, 2 bytes, etc.)
// * @param imageServiceAdapter The URI enhancer to use for this spec image loading
// */
// ImageLoadSpec(String key, int width, int height, Format format, Bitmap.Config pixelConfig, ImageServiceAdapter imageServiceAdapter) {
// mKey = key;
// mWidth = width;
// mHeight = height;
// mFormat = format;
// mPixelConfig = pixelConfig;
// mImageServiceAdapter = imageServiceAdapter;
// }
//
// /**
// * the unique key of the spec used for identification and debug
// */
// public String getKey() {
// return mKey;
// }
//
// /**
// * the width of the image in pixels
// */
// public int getWidth() {
// return mWidth;
// }
//
// /**
// * the height of the image in pixels
// */
// public int getHeight() {
// return mHeight;
// }
//
// /**
// * The format of the image.
// */
// public Format getFormat() {
// return mFormat;
// }
//
// /**
// * the pixel configuration to load the image in (4 bytes per image pixel, 2 bytes, etc.)
// */
// public Bitmap.Config getPixelConfig() {
// return mPixelConfig;
// }
//
// /**
// * The URI enhancer to use for this spec image loading
// */
// public ImageServiceAdapter getImageServiceAdapter() {
// return mImageServiceAdapter;
// }
//
// /**
// * Is the spec define specific width and height for the image.
// */
// public boolean isSizeBounded() {
// return mWidth > 0 && mHeight > 0;
// }
//
// @Override
// public String toString() {
// return "ImageLoadSpec{" +
// "mKey='" + mKey + '\'' +
// ", mWidth=" + mWidth +
// ", mHeight=" + mHeight +
// ", mFormat=" + mFormat +
// ", mPixelConfig=" + mPixelConfig +
// ", mImageServiceAdapter=" + mImageServiceAdapter +
// '}';
// }
//
// //region: Inner class: Format
//
// /**
// * The format of the image.
// */
// public static enum Format {
// UNCHANGE,
// JPEG,
// PNG,
// WEBP,
// }
// //endregion
// }
//
// Path: fastimageloader/src/main/java/com/theartofdev/fastimageloader/ImageServiceAdapter.java
// public interface ImageServiceAdapter {
//
// /**
// * Add to raw image loading URI the required specifications (format/size/etc.) parameters.
// *
// * @param uri the raw image URI to convert
// * @param spec the image loading specification to convert by
// * @return URI with loading specification
// */
// String convert(String uri, ImageLoadSpec spec);
// }
// Path: fastimageloader/src/main/java/com/theartofdev/fastimageloader/adapter/ImgIXAdapter.java
import com.theartofdev.fastimageloader.ImageLoadSpec;
import com.theartofdev.fastimageloader.ImageServiceAdapter;
// "Therefore those skilled at the unorthodox
// are infinite as heaven and earth,
// inexhaustible as the great rivers.
// When they come to an end,
// they begin again,
// like the days and months;
// they die and are reborn,
// like the four seasons."
//
// - Sun Tsu,
// "The Art of War"
package com.theartofdev.fastimageloader.adapter;
/**
* imgIX image service (http://www.imgix.com) adapter.<br>
*/
public class ImgIXAdapter implements ImageServiceAdapter {
@Override | public String convert(String uri, ImageLoadSpec spec) { |
ArthurHub/Android-Fast-Image-Loader | fastimageloader/src/main/java/com/theartofdev/fastimageloader/impl/util/FILLogger.java | // Path: fastimageloader/src/main/java/com/theartofdev/fastimageloader/LoadedFrom.java
// public enum LoadedFrom {
// MEMORY,
// DISK,
// NETWORK
// }
//
// Path: fastimageloader/src/main/java/com/theartofdev/fastimageloader/LogAppender.java
// public interface LogAppender {
//
// /**
// * Write given log entry.
// *
// * @param level the log level ({@link android.util.Log#DEBUG}, {@link android.util.Log#INFO}, etc.)
// * @param tag the log tag string
// * @param message the log message
// * @param error optional: the error logged
// */
// void log(int level, String tag, String message, Throwable error);
//
// /**
// * Image load operation complete.
// *
// * @param url the url of the image
// * @param specKey the spec of the image load request
// * @param from from where the image was loaded (MEMORY/DISK/NETWORK)
// * @param successful was the image load successful
// * @param time the time in milliseconds it took from request to finish
// */
// void imageLoadOperation(String url, String specKey, LoadedFrom from, boolean successful, long time);
//
// /**
// * Image download operation complete.
// *
// * @param url the url of the image
// * @param specKey the spec of the image load request
// * @param responseCode the response code of the download web request
// * @param time the time in milliseconds it took to download the image
// * @param bytes the number of bytes received if download was successful
// * @param error optional: if download failed will contain the error
// */
// void imageDownloadOperation(String url, String specKey, int responseCode, long time, long bytes, Throwable error);
// }
| import com.theartofdev.fastimageloader.LoadedFrom;
import com.theartofdev.fastimageloader.LogAppender;
import android.util.Log; | // "Therefore those skilled at the unorthodox
// are infinite as heaven and earth,
// inexhaustible as the great rivers.
// When they come to an end,
// they begin again,
// like the days and months;
// they die and are reborn,
// like the four seasons."
//
// - Sun Tsu,
// "The Art of War"
package com.theartofdev.fastimageloader.impl.util;
/**
* Logger for Fast Image Loader internal use only.
*/
public final class FILLogger {
/**
* The tag to use for all logs
*/
private static final String TAG = "FastImageLoader";
/**
* If to write logs to logcat.
*/
public static boolean mLogcatEnabled = false;
/**
* Extensibility appender to write the logs to.
*/ | // Path: fastimageloader/src/main/java/com/theartofdev/fastimageloader/LoadedFrom.java
// public enum LoadedFrom {
// MEMORY,
// DISK,
// NETWORK
// }
//
// Path: fastimageloader/src/main/java/com/theartofdev/fastimageloader/LogAppender.java
// public interface LogAppender {
//
// /**
// * Write given log entry.
// *
// * @param level the log level ({@link android.util.Log#DEBUG}, {@link android.util.Log#INFO}, etc.)
// * @param tag the log tag string
// * @param message the log message
// * @param error optional: the error logged
// */
// void log(int level, String tag, String message, Throwable error);
//
// /**
// * Image load operation complete.
// *
// * @param url the url of the image
// * @param specKey the spec of the image load request
// * @param from from where the image was loaded (MEMORY/DISK/NETWORK)
// * @param successful was the image load successful
// * @param time the time in milliseconds it took from request to finish
// */
// void imageLoadOperation(String url, String specKey, LoadedFrom from, boolean successful, long time);
//
// /**
// * Image download operation complete.
// *
// * @param url the url of the image
// * @param specKey the spec of the image load request
// * @param responseCode the response code of the download web request
// * @param time the time in milliseconds it took to download the image
// * @param bytes the number of bytes received if download was successful
// * @param error optional: if download failed will contain the error
// */
// void imageDownloadOperation(String url, String specKey, int responseCode, long time, long bytes, Throwable error);
// }
// Path: fastimageloader/src/main/java/com/theartofdev/fastimageloader/impl/util/FILLogger.java
import com.theartofdev.fastimageloader.LoadedFrom;
import com.theartofdev.fastimageloader.LogAppender;
import android.util.Log;
// "Therefore those skilled at the unorthodox
// are infinite as heaven and earth,
// inexhaustible as the great rivers.
// When they come to an end,
// they begin again,
// like the days and months;
// they die and are reborn,
// like the four seasons."
//
// - Sun Tsu,
// "The Art of War"
package com.theartofdev.fastimageloader.impl.util;
/**
* Logger for Fast Image Loader internal use only.
*/
public final class FILLogger {
/**
* The tag to use for all logs
*/
private static final String TAG = "FastImageLoader";
/**
* If to write logs to logcat.
*/
public static boolean mLogcatEnabled = false;
/**
* Extensibility appender to write the logs to.
*/ | public static LogAppender mAppender; |
ArthurHub/Android-Fast-Image-Loader | fastimageloader/src/main/java/com/theartofdev/fastimageloader/impl/util/FILLogger.java | // Path: fastimageloader/src/main/java/com/theartofdev/fastimageloader/LoadedFrom.java
// public enum LoadedFrom {
// MEMORY,
// DISK,
// NETWORK
// }
//
// Path: fastimageloader/src/main/java/com/theartofdev/fastimageloader/LogAppender.java
// public interface LogAppender {
//
// /**
// * Write given log entry.
// *
// * @param level the log level ({@link android.util.Log#DEBUG}, {@link android.util.Log#INFO}, etc.)
// * @param tag the log tag string
// * @param message the log message
// * @param error optional: the error logged
// */
// void log(int level, String tag, String message, Throwable error);
//
// /**
// * Image load operation complete.
// *
// * @param url the url of the image
// * @param specKey the spec of the image load request
// * @param from from where the image was loaded (MEMORY/DISK/NETWORK)
// * @param successful was the image load successful
// * @param time the time in milliseconds it took from request to finish
// */
// void imageLoadOperation(String url, String specKey, LoadedFrom from, boolean successful, long time);
//
// /**
// * Image download operation complete.
// *
// * @param url the url of the image
// * @param specKey the spec of the image load request
// * @param responseCode the response code of the download web request
// * @param time the time in milliseconds it took to download the image
// * @param bytes the number of bytes received if download was successful
// * @param error optional: if download failed will contain the error
// */
// void imageDownloadOperation(String url, String specKey, int responseCode, long time, long bytes, Throwable error);
// }
| import com.theartofdev.fastimageloader.LoadedFrom;
import com.theartofdev.fastimageloader.LogAppender;
import android.util.Log; | // "Therefore those skilled at the unorthodox
// are infinite as heaven and earth,
// inexhaustible as the great rivers.
// When they come to an end,
// they begin again,
// like the days and months;
// they die and are reborn,
// like the four seasons."
//
// - Sun Tsu,
// "The Art of War"
package com.theartofdev.fastimageloader.impl.util;
/**
* Logger for Fast Image Loader internal use only.
*/
public final class FILLogger {
/**
* The tag to use for all logs
*/
private static final String TAG = "FastImageLoader";
/**
* If to write logs to logcat.
*/
public static boolean mLogcatEnabled = false;
/**
* Extensibility appender to write the logs to.
*/
public static LogAppender mAppender;
/**
* The min log level to write logs at, logs below this level are ignored.
*/
public static int mLogLevel = Log.INFO;
/**
* Image load operation complete.
*
* @param url the url of the image
* @param specKey the spec of the image load request
* @param from from where the image was loaded (MEMORY/DISK/NETWORK)
* @param successful was the image load successful
* @param time the time in milliseconds it took from request to finish
*/ | // Path: fastimageloader/src/main/java/com/theartofdev/fastimageloader/LoadedFrom.java
// public enum LoadedFrom {
// MEMORY,
// DISK,
// NETWORK
// }
//
// Path: fastimageloader/src/main/java/com/theartofdev/fastimageloader/LogAppender.java
// public interface LogAppender {
//
// /**
// * Write given log entry.
// *
// * @param level the log level ({@link android.util.Log#DEBUG}, {@link android.util.Log#INFO}, etc.)
// * @param tag the log tag string
// * @param message the log message
// * @param error optional: the error logged
// */
// void log(int level, String tag, String message, Throwable error);
//
// /**
// * Image load operation complete.
// *
// * @param url the url of the image
// * @param specKey the spec of the image load request
// * @param from from where the image was loaded (MEMORY/DISK/NETWORK)
// * @param successful was the image load successful
// * @param time the time in milliseconds it took from request to finish
// */
// void imageLoadOperation(String url, String specKey, LoadedFrom from, boolean successful, long time);
//
// /**
// * Image download operation complete.
// *
// * @param url the url of the image
// * @param specKey the spec of the image load request
// * @param responseCode the response code of the download web request
// * @param time the time in milliseconds it took to download the image
// * @param bytes the number of bytes received if download was successful
// * @param error optional: if download failed will contain the error
// */
// void imageDownloadOperation(String url, String specKey, int responseCode, long time, long bytes, Throwable error);
// }
// Path: fastimageloader/src/main/java/com/theartofdev/fastimageloader/impl/util/FILLogger.java
import com.theartofdev.fastimageloader.LoadedFrom;
import com.theartofdev.fastimageloader.LogAppender;
import android.util.Log;
// "Therefore those skilled at the unorthodox
// are infinite as heaven and earth,
// inexhaustible as the great rivers.
// When they come to an end,
// they begin again,
// like the days and months;
// they die and are reborn,
// like the four seasons."
//
// - Sun Tsu,
// "The Art of War"
package com.theartofdev.fastimageloader.impl.util;
/**
* Logger for Fast Image Loader internal use only.
*/
public final class FILLogger {
/**
* The tag to use for all logs
*/
private static final String TAG = "FastImageLoader";
/**
* If to write logs to logcat.
*/
public static boolean mLogcatEnabled = false;
/**
* Extensibility appender to write the logs to.
*/
public static LogAppender mAppender;
/**
* The min log level to write logs at, logs below this level are ignored.
*/
public static int mLogLevel = Log.INFO;
/**
* Image load operation complete.
*
* @param url the url of the image
* @param specKey the spec of the image load request
* @param from from where the image was loaded (MEMORY/DISK/NETWORK)
* @param successful was the image load successful
* @param time the time in milliseconds it took from request to finish
*/ | public static void operation(String url, String specKey, LoadedFrom from, boolean successful, long time) { |
ArthurHub/Android-Fast-Image-Loader | demo/src/main/java/com/theartofdev/fastimageloaderdemo/instagram/InstagramFragment.java | // Path: demo/src/main/java/com/theartofdev/fastimageloaderdemo/instagram/service/Feed.java
// public class Feed {
//
// public Item[] data;
// }
| import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.theartofdev.fastimageloaderdemo.R;
import com.theartofdev.fastimageloaderdemo.instagram.service.Feed;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response; | // "Therefore those skilled at the unorthodox
// are infinite as heaven and earth,
// inexhaustible as the great rivers.
// When they come to an end,
// they begin again,
// like the days and months;
// they die and are reborn,
// like the four seasons."
//
// - Sun Tsu,
// "The Art of War"
package com.theartofdev.fastimageloaderdemo.instagram;
public class InstagramFragment extends Fragment {
private Adapter mAdapter;
public InstagramFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_img_ix, container, false);
RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(container.getContext()));
mAdapter = new Adapter();
recyclerView.setAdapter(mAdapter);
loadData();
return view;
}
private void loadData() { | // Path: demo/src/main/java/com/theartofdev/fastimageloaderdemo/instagram/service/Feed.java
// public class Feed {
//
// public Item[] data;
// }
// Path: demo/src/main/java/com/theartofdev/fastimageloaderdemo/instagram/InstagramFragment.java
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.theartofdev.fastimageloaderdemo.R;
import com.theartofdev.fastimageloaderdemo.instagram.service.Feed;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;
// "Therefore those skilled at the unorthodox
// are infinite as heaven and earth,
// inexhaustible as the great rivers.
// When they come to an end,
// they begin again,
// like the days and months;
// they die and are reborn,
// like the four seasons."
//
// - Sun Tsu,
// "The Art of War"
package com.theartofdev.fastimageloaderdemo.instagram;
public class InstagramFragment extends Fragment {
private Adapter mAdapter;
public InstagramFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_img_ix, container, false);
RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(container.getContext()));
mAdapter = new Adapter();
recyclerView.setAdapter(mAdapter);
loadData();
return view;
}
private void loadData() { | mAdapter.loadData(new Callback<Feed>() { |
cmongis/psfj | src/knop/psfj/BeadFrameProcessorTester.java | // Path: src/knop/psfj/utils/MemoryUtils.java
// public class MemoryUtils {
//
// /**
// * Gets the available memory.
// *
// * @return the available memory
// */
// public static long getAvailableMemory() {
//
// Runtime runtime = Runtime.getRuntime();
//
// int max = (int) (runtime.maxMemory() / 1024 / 1024);
// int total = (int) (runtime.totalMemory() / 1024 / 1024);
// int free = (int) (runtime.freeMemory() / 1024 / 1024);
//
// free = free + max - total;
//
// int used = max - free;
//
// return free;
//
// }
//
// /**
// * Gets the total memory.
// *
// * @return the total memory
// */
// public static long getTotalMemory() {
// return Runtime.getRuntime().maxMemory() / 1024 / 1024;
// }
//
// public static long getMaximumMemory() {
// return Runtime.getRuntime().maxMemory() / 1024 / 1024;
// }
//
// public static double getAvailableMemoryFraction() {
// Runtime runtime = Runtime.getRuntime();
//
// long max = runtime.maxMemory();
// long total = runtime.totalMemory();
// long free = runtime.freeMemory();
// free = free + max - total;
// return 1.0 * free / total;
// }
// }
| import ij.ImagePlus;
import knop.psfj.utils.MemoryUtils; | /*
This file is part of PSFj.
PSFj is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
PSFj is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with PSFj. If not, see <http://www.gnu.org/licenses/>.
Copyright 2013,2014 Cyril MONGIS, Patrick Theer, Michael Knop
*/
package knop.psfj;
// TODO: Auto-generated Javadoc
/**
* The Class BeadFrameProcessorTester.
*/
public class BeadFrameProcessorTester extends BeadFrameProcessorAsync {
/** The stats. */
FovDataSet stats = new FovDataSet();
/**
* Instantiates a new bead frame processor tester.
*
* @param list the list
*/
public BeadFrameProcessorTester(BeadFrameList list) {
super(list);
// TODO Auto-generated constructor stub
}
/* (non-Javadoc)
* @see knop.psfj.BeadFrameProcessor#init()
*/
@Override
public void init() {
stats = new FovDataSet();
super.init();
}
/* (non-Javadoc)
* @see knop.psfj.BeadFrameProcessor#refresh()
*/
@Override
public void refresh() {
long now = System.currentTimeMillis();
stats.addValue("t", now-startTime);
stats.addValue("speed", getBeadPerSecond()); | // Path: src/knop/psfj/utils/MemoryUtils.java
// public class MemoryUtils {
//
// /**
// * Gets the available memory.
// *
// * @return the available memory
// */
// public static long getAvailableMemory() {
//
// Runtime runtime = Runtime.getRuntime();
//
// int max = (int) (runtime.maxMemory() / 1024 / 1024);
// int total = (int) (runtime.totalMemory() / 1024 / 1024);
// int free = (int) (runtime.freeMemory() / 1024 / 1024);
//
// free = free + max - total;
//
// int used = max - free;
//
// return free;
//
// }
//
// /**
// * Gets the total memory.
// *
// * @return the total memory
// */
// public static long getTotalMemory() {
// return Runtime.getRuntime().maxMemory() / 1024 / 1024;
// }
//
// public static long getMaximumMemory() {
// return Runtime.getRuntime().maxMemory() / 1024 / 1024;
// }
//
// public static double getAvailableMemoryFraction() {
// Runtime runtime = Runtime.getRuntime();
//
// long max = runtime.maxMemory();
// long total = runtime.totalMemory();
// long free = runtime.freeMemory();
// free = free + max - total;
// return 1.0 * free / total;
// }
// }
// Path: src/knop/psfj/BeadFrameProcessorTester.java
import ij.ImagePlus;
import knop.psfj.utils.MemoryUtils;
/*
This file is part of PSFj.
PSFj is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
PSFj is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with PSFj. If not, see <http://www.gnu.org/licenses/>.
Copyright 2013,2014 Cyril MONGIS, Patrick Theer, Michael Knop
*/
package knop.psfj;
// TODO: Auto-generated Javadoc
/**
* The Class BeadFrameProcessorTester.
*/
public class BeadFrameProcessorTester extends BeadFrameProcessorAsync {
/** The stats. */
FovDataSet stats = new FovDataSet();
/**
* Instantiates a new bead frame processor tester.
*
* @param list the list
*/
public BeadFrameProcessorTester(BeadFrameList list) {
super(list);
// TODO Auto-generated constructor stub
}
/* (non-Javadoc)
* @see knop.psfj.BeadFrameProcessor#init()
*/
@Override
public void init() {
stats = new FovDataSet();
super.init();
}
/* (non-Javadoc)
* @see knop.psfj.BeadFrameProcessor#refresh()
*/
@Override
public void refresh() {
long now = System.currentTimeMillis();
stats.addValue("t", now-startTime);
stats.addValue("speed", getBeadPerSecond()); | stats.addValue("memory",MemoryUtils.getTotalMemory()-MemoryUtils.getAvailableMemory()); |
cmongis/psfj | src/knop/psfj/resolution/ReportSections.java | // Path: src/knop/psfj/graphics/PsfJGraph.java
// public interface PsfJGraph {
//
// /** The normalized. */
// public static int NORMALIZED = 1;
//
// /** The not normalized. */
// public static int NOT_NORMALIZED = 2;
//
// /**
// * Gets the graph.
// *
// * @return the graph
// */
// public ImageProcessor getGraph();
//
// /**
// * Gets the graph.
// *
// * @param normalized the normalized
// * @return the graph
// */
// public ImageProcessor getGraph(int normalized);
//
// /**
// * Gets the title.
// *
// * @return the title
// */
// public String getTitle();
//
// /**
// * Gets the description.
// *
// * @return the description
// */
// public String getDescription();
//
// /**
// * Gets the save id.
// *
// * @return the save id
// */
// public String getSaveId();
//
// /**
// * Gets the short description.
// *
// * @return the short description
// */
// public String getShortDescription();
//
// /**
// * Gets the image icon.
// *
// * @return the image icon
// */
// public ImageIcon getImageIcon();
//
// }
| import ij.ImagePlus;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import knop.psfj.graphics.PsfJGraph;
import com.lowagie.text.BadElementException;
import com.lowagie.text.Chunk;
import com.lowagie.text.Element;
import com.lowagie.text.Font;
import com.lowagie.text.Image;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfTable; | public Paragraph paragraph(String title){
Paragraph paragraph=new Paragraph();
Font font=new Font(Font.HELVETICA, 12, Font.NORMAL);
paragraph.add(new Chunk(title, font));
paragraph.setAlignment(Paragraph.ALIGN_LEFT);
paragraph.setSpacingBefore(15);
return paragraph;
}
public Paragraph littleNote(String note) {
return littleNote(note,Paragraph.ALIGN_CENTER);
}
public Paragraph littleNote(String note,int alignement) {
Paragraph paragraph = new Paragraph();
Font font = new Font(Font.HELVETICA, 10, Font.NORMAL);
paragraph.add(new Chunk(note,font));
paragraph.setAlignment(alignement);
paragraph.setSpacingAfter(0);
return paragraph;
}
/**
* Generates an Image ready to be added to the pdf document, based on an ImagePlus
* @param image the ImagePlus from which the Image object will be generated
* @param zoom the zoom to be applied to the image (0.0-100.0) as a float
* @return an Image ready to be added to the pdf document
*/
| // Path: src/knop/psfj/graphics/PsfJGraph.java
// public interface PsfJGraph {
//
// /** The normalized. */
// public static int NORMALIZED = 1;
//
// /** The not normalized. */
// public static int NOT_NORMALIZED = 2;
//
// /**
// * Gets the graph.
// *
// * @return the graph
// */
// public ImageProcessor getGraph();
//
// /**
// * Gets the graph.
// *
// * @param normalized the normalized
// * @return the graph
// */
// public ImageProcessor getGraph(int normalized);
//
// /**
// * Gets the title.
// *
// * @return the title
// */
// public String getTitle();
//
// /**
// * Gets the description.
// *
// * @return the description
// */
// public String getDescription();
//
// /**
// * Gets the save id.
// *
// * @return the save id
// */
// public String getSaveId();
//
// /**
// * Gets the short description.
// *
// * @return the short description
// */
// public String getShortDescription();
//
// /**
// * Gets the image icon.
// *
// * @return the image icon
// */
// public ImageIcon getImageIcon();
//
// }
// Path: src/knop/psfj/resolution/ReportSections.java
import ij.ImagePlus;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import knop.psfj.graphics.PsfJGraph;
import com.lowagie.text.BadElementException;
import com.lowagie.text.Chunk;
import com.lowagie.text.Element;
import com.lowagie.text.Font;
import com.lowagie.text.Image;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfTable;
public Paragraph paragraph(String title){
Paragraph paragraph=new Paragraph();
Font font=new Font(Font.HELVETICA, 12, Font.NORMAL);
paragraph.add(new Chunk(title, font));
paragraph.setAlignment(Paragraph.ALIGN_LEFT);
paragraph.setSpacingBefore(15);
return paragraph;
}
public Paragraph littleNote(String note) {
return littleNote(note,Paragraph.ALIGN_CENTER);
}
public Paragraph littleNote(String note,int alignement) {
Paragraph paragraph = new Paragraph();
Font font = new Font(Font.HELVETICA, 10, Font.NORMAL);
paragraph.add(new Chunk(note,font));
paragraph.setAlignment(alignement);
paragraph.setSpacingAfter(0);
return paragraph;
}
/**
* Generates an Image ready to be added to the pdf document, based on an ImagePlus
* @param image the ImagePlus from which the Image object will be generated
* @param zoom the zoom to be applied to the image (0.0-100.0) as a float
* @return an Image ready to be added to the pdf document
*/
| public Image imagePlus(PsfJGraph graph, float zoom) { |
kreativekorp/vexillo | main/java/Vexillo/src/com/kreative/vexillo/main/Base64Decode.java | // Path: main/java/Vexillo/src/com/kreative/vexillo/core/Base64InputStream.java
// public class Base64InputStream extends InputStream {
// private final CharacterIterator ci;
// private final InputStream in;
//
// public Base64InputStream(String s) {
// this.ci = new StringCharacterIterator(s);
// this.in = null;
// }
//
// public Base64InputStream(CharacterIterator ci) {
// this.ci = ci;
// this.in = null;
// }
//
// public Base64InputStream(InputStream in) {
// this.ci = null;
// this.in = in;
// }
//
// private int word = 0;
// private int count = 0;
// private boolean eof = false;
//
// @Override
// public int read() throws IOException {
// for (;;) {
// if (count > 0) {
// word <<= 8;
// count--;
// return (word >>> 24);
// }
// if (eof) return -1;
// readWord();
// }
// }
//
// private void readWord() throws IOException {
// for (;;) {
// int c = -1;
// if (ci != null) { c = ci.current(); ci.next(); }
// if (in != null) { c = in.read(); }
// if (c < 0 || c == '=' || c == CharacterIterator.DONE) {
// padWord();
// eof = true;
// return;
// }
// c = b64d(c);
// if (c >= 0) {
// word <<= 6;
// word |= c;
// count++;
// if (count > 3) {
// count = 3;
// return;
// }
// }
// }
// }
//
// private void padWord() {
// if (count > 0) {
// for (int i = count; i <= 3; i++) {
// word <<= 6;
// }
// count--;
// }
// }
//
// private int b64d(int c) {
// switch (c) {
// case 'A': return 0; case 'B': return 1; case 'C': return 2; case 'D': return 3;
// case 'E': return 4; case 'F': return 5; case 'G': return 6; case 'H': return 7;
// case 'I': return 8; case 'J': return 9; case 'K': return 10; case 'L': return 11;
// case 'M': return 12; case 'N': return 13; case 'O': return 14; case 'P': return 15;
// case 'Q': return 16; case 'R': return 17; case 'S': return 18; case 'T': return 19;
// case 'U': return 20; case 'V': return 21; case 'W': return 22; case 'X': return 23;
// case 'Y': return 24; case 'Z': return 25; case 'a': return 26; case 'b': return 27;
// case 'c': return 28; case 'd': return 29; case 'e': return 30; case 'f': return 31;
// case 'g': return 32; case 'h': return 33; case 'i': return 34; case 'j': return 35;
// case 'k': return 36; case 'l': return 37; case 'm': return 38; case 'n': return 39;
// case 'o': return 40; case 'p': return 41; case 'q': return 42; case 'r': return 43;
// case 's': return 44; case 't': return 45; case 'u': return 46; case 'v': return 47;
// case 'w': return 48; case 'x': return 49; case 'y': return 50; case 'z': return 51;
// case '0': return 52; case '1': return 53; case '2': return 54; case '3': return 55;
// case '4': return 56; case '5': return 57; case '6': return 58; case '7': return 59;
// case '8': return 60; case '9': return 61; case '+': return 62; case '/': return 63;
// default: return -1;
// }
// }
//
// @Override
// public void close() throws IOException {
// if (in != null) in.close();
// }
// }
| import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import com.kreative.vexillo.core.Base64InputStream; | package com.kreative.vexillo.main;
public class Base64Decode {
public static void main(String[] args) {
main(Vexillo.arg0(Base64Decode.class), args, 0);
}
public static void main(String arg0, String[] args, int argi) {
boolean written = false;
boolean opts = true;
while (argi < args.length) {
String arg = args[argi++];
if (opts && arg.startsWith("-")) {
if (arg.equals("--")) {
opts = false;
} else if (arg.equals("-I")) {
try {
@SuppressWarnings("resource") | // Path: main/java/Vexillo/src/com/kreative/vexillo/core/Base64InputStream.java
// public class Base64InputStream extends InputStream {
// private final CharacterIterator ci;
// private final InputStream in;
//
// public Base64InputStream(String s) {
// this.ci = new StringCharacterIterator(s);
// this.in = null;
// }
//
// public Base64InputStream(CharacterIterator ci) {
// this.ci = ci;
// this.in = null;
// }
//
// public Base64InputStream(InputStream in) {
// this.ci = null;
// this.in = in;
// }
//
// private int word = 0;
// private int count = 0;
// private boolean eof = false;
//
// @Override
// public int read() throws IOException {
// for (;;) {
// if (count > 0) {
// word <<= 8;
// count--;
// return (word >>> 24);
// }
// if (eof) return -1;
// readWord();
// }
// }
//
// private void readWord() throws IOException {
// for (;;) {
// int c = -1;
// if (ci != null) { c = ci.current(); ci.next(); }
// if (in != null) { c = in.read(); }
// if (c < 0 || c == '=' || c == CharacterIterator.DONE) {
// padWord();
// eof = true;
// return;
// }
// c = b64d(c);
// if (c >= 0) {
// word <<= 6;
// word |= c;
// count++;
// if (count > 3) {
// count = 3;
// return;
// }
// }
// }
// }
//
// private void padWord() {
// if (count > 0) {
// for (int i = count; i <= 3; i++) {
// word <<= 6;
// }
// count--;
// }
// }
//
// private int b64d(int c) {
// switch (c) {
// case 'A': return 0; case 'B': return 1; case 'C': return 2; case 'D': return 3;
// case 'E': return 4; case 'F': return 5; case 'G': return 6; case 'H': return 7;
// case 'I': return 8; case 'J': return 9; case 'K': return 10; case 'L': return 11;
// case 'M': return 12; case 'N': return 13; case 'O': return 14; case 'P': return 15;
// case 'Q': return 16; case 'R': return 17; case 'S': return 18; case 'T': return 19;
// case 'U': return 20; case 'V': return 21; case 'W': return 22; case 'X': return 23;
// case 'Y': return 24; case 'Z': return 25; case 'a': return 26; case 'b': return 27;
// case 'c': return 28; case 'd': return 29; case 'e': return 30; case 'f': return 31;
// case 'g': return 32; case 'h': return 33; case 'i': return 34; case 'j': return 35;
// case 'k': return 36; case 'l': return 37; case 'm': return 38; case 'n': return 39;
// case 'o': return 40; case 'p': return 41; case 'q': return 42; case 'r': return 43;
// case 's': return 44; case 't': return 45; case 'u': return 46; case 'v': return 47;
// case 'w': return 48; case 'x': return 49; case 'y': return 50; case 'z': return 51;
// case '0': return 52; case '1': return 53; case '2': return 54; case '3': return 55;
// case '4': return 56; case '5': return 57; case '6': return 58; case '7': return 59;
// case '8': return 60; case '9': return 61; case '+': return 62; case '/': return 63;
// default: return -1;
// }
// }
//
// @Override
// public void close() throws IOException {
// if (in != null) in.close();
// }
// }
// Path: main/java/Vexillo/src/com/kreative/vexillo/main/Base64Decode.java
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import com.kreative.vexillo.core.Base64InputStream;
package com.kreative.vexillo.main;
public class Base64Decode {
public static void main(String[] args) {
main(Vexillo.arg0(Base64Decode.class), args, 0);
}
public static void main(String arg0, String[] args, int argi) {
boolean written = false;
boolean opts = true;
while (argi < args.length) {
String arg = args[argi++];
if (opts && arg.startsWith("-")) {
if (arg.equals("--")) {
opts = false;
} else if (arg.equals("-I")) {
try {
@SuppressWarnings("resource") | Base64InputStream in = new Base64InputStream(System.in); |
kreativekorp/vexillo | main/java/Vexillo/src/com/kreative/vexillo/font/ImageSVGExporter.java | // Path: main/java/Vexillo/src/com/kreative/vexillo/core/Base64OutputStream.java
// public class Base64OutputStream extends OutputStream {
// private final StringBuffer sb;
// private final OutputStream out;
// private final boolean pad;
//
// public Base64OutputStream(StringBuffer sb) {
// this(sb, true);
// }
//
// public Base64OutputStream(OutputStream out) {
// this(out, true);
// }
//
// public Base64OutputStream(StringBuffer sb, boolean pad) {
// this.sb = sb;
// this.out = null;
// this.pad = pad;
// }
//
// public Base64OutputStream(OutputStream out, boolean pad) {
// this.sb = null;
// this.out = out;
// this.pad = pad;
// }
//
// private int word = 0;
// private int count = 0;
//
// @Override
// public void write(int b) throws IOException {
// word <<= 8;
// word |= (b & 0xFF);
// count++;
// if (count >= 3) {
// writeWord();
// word = 0;
// count = 0;
// }
// }
//
// @Override
// public void flush() throws IOException {
// if (out != null) out.flush();
// }
//
// @Override
// public void close() throws IOException {
// if (count > 0) {
// for (int i = count; i < 3; i++) word <<= 8;
// writeWord();
// }
// word = 0;
// count = 0;
// if (out != null) out.close();
// }
//
// private void writeWord() throws IOException {
// for (int m = 18, i = 0; i <= count; m -= 6, i++) {
// char c = b64e[(word >> m) & 0x3F];
// if (sb != null) sb.append(c);
// if (out != null) out.write(c);
// }
// if (pad) {
// for (int i = count; i < 3; i++) {
// if (sb != null) sb.append('=');
// if (out != null) out.write('=');
// }
// }
// }
//
// private static final char[] b64e = {
// 'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P',
// 'Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f',
// 'g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v',
// 'w','x','y','z','0','1','2','3','4','5','6','7','8','9','+','/',
// };
// }
| import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import javax.imageio.ImageIO;
import com.kreative.vexillo.core.Base64OutputStream; | int x, int y, int w, int h, File file
) throws IOException {
FileOutputStream os = new FileOutputStream(file);
OutputStreamWriter wr = new OutputStreamWriter(os, "UTF-8");
wr.append(exportToString(image, format, mimeType, x, y, w, h));
wr.flush();
wr.close();
}
public static String exportToString(
BufferedImage image, String format, String mimeType,
int x, int y, int w, int h
) throws IOException {
StringBuffer svg = new StringBuffer();
svg.append("<svg id=\"glyph{{{0}}}\"");
svg.append(" xmlns=\"http://www.w3.org/2000/svg\"");
svg.append(" xmlns:xlink=\"http://www.w3.org/1999/xlink\">");
String url = encodeImageDataURL(image, format, mimeType);
svg.append("<image x=\"" + x + "\" y=\"" + y + "\"");
svg.append(" width=\"" + w + "\" height=\"" + h + "\"");
svg.append(" xlink:href=\"" + url + "\"/>");
svg.append("</svg>");
return svg.toString();
}
public static String encodeImageDataURL(
BufferedImage image, String format, String mimeType
) throws IOException {
StringBuffer data = new StringBuffer("data:");
data.append(mimeType); data.append(";base64,"); | // Path: main/java/Vexillo/src/com/kreative/vexillo/core/Base64OutputStream.java
// public class Base64OutputStream extends OutputStream {
// private final StringBuffer sb;
// private final OutputStream out;
// private final boolean pad;
//
// public Base64OutputStream(StringBuffer sb) {
// this(sb, true);
// }
//
// public Base64OutputStream(OutputStream out) {
// this(out, true);
// }
//
// public Base64OutputStream(StringBuffer sb, boolean pad) {
// this.sb = sb;
// this.out = null;
// this.pad = pad;
// }
//
// public Base64OutputStream(OutputStream out, boolean pad) {
// this.sb = null;
// this.out = out;
// this.pad = pad;
// }
//
// private int word = 0;
// private int count = 0;
//
// @Override
// public void write(int b) throws IOException {
// word <<= 8;
// word |= (b & 0xFF);
// count++;
// if (count >= 3) {
// writeWord();
// word = 0;
// count = 0;
// }
// }
//
// @Override
// public void flush() throws IOException {
// if (out != null) out.flush();
// }
//
// @Override
// public void close() throws IOException {
// if (count > 0) {
// for (int i = count; i < 3; i++) word <<= 8;
// writeWord();
// }
// word = 0;
// count = 0;
// if (out != null) out.close();
// }
//
// private void writeWord() throws IOException {
// for (int m = 18, i = 0; i <= count; m -= 6, i++) {
// char c = b64e[(word >> m) & 0x3F];
// if (sb != null) sb.append(c);
// if (out != null) out.write(c);
// }
// if (pad) {
// for (int i = count; i < 3; i++) {
// if (sb != null) sb.append('=');
// if (out != null) out.write('=');
// }
// }
// }
//
// private static final char[] b64e = {
// 'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P',
// 'Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f',
// 'g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v',
// 'w','x','y','z','0','1','2','3','4','5','6','7','8','9','+','/',
// };
// }
// Path: main/java/Vexillo/src/com/kreative/vexillo/font/ImageSVGExporter.java
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import javax.imageio.ImageIO;
import com.kreative.vexillo.core.Base64OutputStream;
int x, int y, int w, int h, File file
) throws IOException {
FileOutputStream os = new FileOutputStream(file);
OutputStreamWriter wr = new OutputStreamWriter(os, "UTF-8");
wr.append(exportToString(image, format, mimeType, x, y, w, h));
wr.flush();
wr.close();
}
public static String exportToString(
BufferedImage image, String format, String mimeType,
int x, int y, int w, int h
) throws IOException {
StringBuffer svg = new StringBuffer();
svg.append("<svg id=\"glyph{{{0}}}\"");
svg.append(" xmlns=\"http://www.w3.org/2000/svg\"");
svg.append(" xmlns:xlink=\"http://www.w3.org/1999/xlink\">");
String url = encodeImageDataURL(image, format, mimeType);
svg.append("<image x=\"" + x + "\" y=\"" + y + "\"");
svg.append(" width=\"" + w + "\" height=\"" + h + "\"");
svg.append(" xlink:href=\"" + url + "\"/>");
svg.append("</svg>");
return svg.toString();
}
public static String encodeImageDataURL(
BufferedImage image, String format, String mimeType
) throws IOException {
StringBuffer data = new StringBuffer("data:");
data.append(mimeType); data.append(";base64,"); | OutputStream out = new Base64OutputStream(data); |
kreativekorp/vexillo | main/java/Vexillo/src/com/kreative/vexillo/ui/FlagFrame.java | // Path: main/java/Vexillo/src/com/kreative/vexillo/core/Flag.java
// public class Flag {
// private String id;
// private String name;
// private PropertySet properties;
// private Dimension fly;
// private Map<String, Dimension> dimensions;
// private Map<String, Color> colors;
// private Map<String, Symbol> symbols;
// private Map<String, Image> images;
// private List<Instruction> instructions;
//
// public Flag() {
// this.id = null;
// this.name = null;
// this.properties = new PropertySet();
// this.fly = new Dimension.Variable("h");
// this.dimensions = new TreeMap<String, Dimension>();
// this.colors = new TreeMap<String, Color>();
// this.symbols = new TreeMap<String, Symbol>();
// this.images = new TreeMap<String, Image>();
// this.instructions = new ArrayList<Instruction>();
// }
//
// public String getId() { return this.id; }
// public void setId(String id) { this.id = id; }
//
// public String getName() { return this.name; }
// public void setName(String name) { this.name = name; }
//
// public PropertySet getProperties() { return this.properties; }
// public void setProperties(PropertySet props) { this.properties = props; }
//
// public Dimension getFly() { return this.fly; }
// public void setFly(Dimension fly) { this.fly = fly; }
//
// public int getWidthFromHeight(int height) {
// return (int)Math.round(getWidthFromHeight2D(height));
// }
//
// public int getHeightFromWidth(int width) {
// return (int)Math.round(getHeightFromWidth2D(width));
// }
//
// public double getWidthFromHeight2D(double height) {
// Map<String, Dimension> ns = new HashMap<String, Dimension>();
// Dimension h = new Dimension.Constant(height);
// ns.put("h", h);
// ns.put("hoist", h);
// ns.put("height", h);
// ns.putAll(dimensions);
// return fly.value(ns);
// }
//
// public double getHeightFromWidth2D(double width) {
// return width / getWidthFromHeight2D(1);
// }
//
// public String getProportionString() {
// int bestDenom = 1;
// double bestNum = getWidthFromHeight2D(1);
// double bestError = Math.abs(bestNum - Math.round(bestNum));
// if (bestError == 0) return bestDenom + ":" + (int)Math.round(bestNum);
// for (int denom = 2; denom < 1000; denom++) {
// double num = getWidthFromHeight2D(denom);
// double error = Math.abs(num - Math.round(num));
// if (error == 0) return denom + ":" + (int)Math.round(num);
// else if (error < bestError) {
// bestDenom = denom;
// bestNum = num;
// bestError = error;
// }
// }
// return bestDenom + ":" + bestNum;
// }
//
// public Map<String, Dimension> dimensions() { return this.dimensions; }
// public Map<String, Color> colors() { return this.colors; }
// public Map<String, Symbol> symbols() { return this.symbols; }
// public Map<String, Image> images() { return this.images; }
// public List<Instruction> instructions() { return this.instructions; }
//
// public Map<String, Dimension> createNamespace(double height, double width) {
// Map<String, Dimension> ns = new HashMap<String, Dimension>();
// Dimension h = new Dimension.Constant(height);
// Dimension w = new Dimension.Constant(width);
// ns.put("h", h);
// ns.put("hoist", h);
// ns.put("height", h);
// ns.put("w", w);
// ns.put("width", w);
// ns.put("f", fly);
// ns.put("fly", fly);
// ns.putAll(dimensions);
// return ns;
// }
// }
| import java.io.File;
import javax.swing.JFrame;
import com.kreative.vexillo.core.Flag; | package com.kreative.vexillo.ui;
public class FlagFrame extends JFrame {
private static final long serialVersionUID = 1L;
private final FlagPanel panel;
| // Path: main/java/Vexillo/src/com/kreative/vexillo/core/Flag.java
// public class Flag {
// private String id;
// private String name;
// private PropertySet properties;
// private Dimension fly;
// private Map<String, Dimension> dimensions;
// private Map<String, Color> colors;
// private Map<String, Symbol> symbols;
// private Map<String, Image> images;
// private List<Instruction> instructions;
//
// public Flag() {
// this.id = null;
// this.name = null;
// this.properties = new PropertySet();
// this.fly = new Dimension.Variable("h");
// this.dimensions = new TreeMap<String, Dimension>();
// this.colors = new TreeMap<String, Color>();
// this.symbols = new TreeMap<String, Symbol>();
// this.images = new TreeMap<String, Image>();
// this.instructions = new ArrayList<Instruction>();
// }
//
// public String getId() { return this.id; }
// public void setId(String id) { this.id = id; }
//
// public String getName() { return this.name; }
// public void setName(String name) { this.name = name; }
//
// public PropertySet getProperties() { return this.properties; }
// public void setProperties(PropertySet props) { this.properties = props; }
//
// public Dimension getFly() { return this.fly; }
// public void setFly(Dimension fly) { this.fly = fly; }
//
// public int getWidthFromHeight(int height) {
// return (int)Math.round(getWidthFromHeight2D(height));
// }
//
// public int getHeightFromWidth(int width) {
// return (int)Math.round(getHeightFromWidth2D(width));
// }
//
// public double getWidthFromHeight2D(double height) {
// Map<String, Dimension> ns = new HashMap<String, Dimension>();
// Dimension h = new Dimension.Constant(height);
// ns.put("h", h);
// ns.put("hoist", h);
// ns.put("height", h);
// ns.putAll(dimensions);
// return fly.value(ns);
// }
//
// public double getHeightFromWidth2D(double width) {
// return width / getWidthFromHeight2D(1);
// }
//
// public String getProportionString() {
// int bestDenom = 1;
// double bestNum = getWidthFromHeight2D(1);
// double bestError = Math.abs(bestNum - Math.round(bestNum));
// if (bestError == 0) return bestDenom + ":" + (int)Math.round(bestNum);
// for (int denom = 2; denom < 1000; denom++) {
// double num = getWidthFromHeight2D(denom);
// double error = Math.abs(num - Math.round(num));
// if (error == 0) return denom + ":" + (int)Math.round(num);
// else if (error < bestError) {
// bestDenom = denom;
// bestNum = num;
// bestError = error;
// }
// }
// return bestDenom + ":" + bestNum;
// }
//
// public Map<String, Dimension> dimensions() { return this.dimensions; }
// public Map<String, Color> colors() { return this.colors; }
// public Map<String, Symbol> symbols() { return this.symbols; }
// public Map<String, Image> images() { return this.images; }
// public List<Instruction> instructions() { return this.instructions; }
//
// public Map<String, Dimension> createNamespace(double height, double width) {
// Map<String, Dimension> ns = new HashMap<String, Dimension>();
// Dimension h = new Dimension.Constant(height);
// Dimension w = new Dimension.Constant(width);
// ns.put("h", h);
// ns.put("hoist", h);
// ns.put("height", h);
// ns.put("w", w);
// ns.put("width", w);
// ns.put("f", fly);
// ns.put("fly", fly);
// ns.putAll(dimensions);
// return ns;
// }
// }
// Path: main/java/Vexillo/src/com/kreative/vexillo/ui/FlagFrame.java
import java.io.File;
import javax.swing.JFrame;
import com.kreative.vexillo.core.Flag;
package com.kreative.vexillo.ui;
public class FlagFrame extends JFrame {
private static final long serialVersionUID = 1L;
private final FlagPanel panel;
| public FlagFrame(String title, File flagFile, File parent, Flag flag) { |
kreativekorp/vexillo | main/java/Vexillo/src/com/kreative/vexillo/main/Base64Encode.java | // Path: main/java/Vexillo/src/com/kreative/vexillo/core/Base64OutputStream.java
// public class Base64OutputStream extends OutputStream {
// private final StringBuffer sb;
// private final OutputStream out;
// private final boolean pad;
//
// public Base64OutputStream(StringBuffer sb) {
// this(sb, true);
// }
//
// public Base64OutputStream(OutputStream out) {
// this(out, true);
// }
//
// public Base64OutputStream(StringBuffer sb, boolean pad) {
// this.sb = sb;
// this.out = null;
// this.pad = pad;
// }
//
// public Base64OutputStream(OutputStream out, boolean pad) {
// this.sb = null;
// this.out = out;
// this.pad = pad;
// }
//
// private int word = 0;
// private int count = 0;
//
// @Override
// public void write(int b) throws IOException {
// word <<= 8;
// word |= (b & 0xFF);
// count++;
// if (count >= 3) {
// writeWord();
// word = 0;
// count = 0;
// }
// }
//
// @Override
// public void flush() throws IOException {
// if (out != null) out.flush();
// }
//
// @Override
// public void close() throws IOException {
// if (count > 0) {
// for (int i = count; i < 3; i++) word <<= 8;
// writeWord();
// }
// word = 0;
// count = 0;
// if (out != null) out.close();
// }
//
// private void writeWord() throws IOException {
// for (int m = 18, i = 0; i <= count; m -= 6, i++) {
// char c = b64e[(word >> m) & 0x3F];
// if (sb != null) sb.append(c);
// if (out != null) out.write(c);
// }
// if (pad) {
// for (int i = count; i < 3; i++) {
// if (sb != null) sb.append('=');
// if (out != null) out.write('=');
// }
// }
// }
//
// private static final char[] b64e = {
// 'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P',
// 'Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f',
// 'g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v',
// 'w','x','y','z','0','1','2','3','4','5','6','7','8','9','+','/',
// };
// }
| import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import com.kreative.vexillo.core.Base64OutputStream; | package com.kreative.vexillo.main;
public class Base64Encode {
public static void main(String[] args) {
main(Vexillo.arg0(Base64Encode.class), args, 0);
}
public static void main(String arg0, String[] args, int argi) {
boolean written = false;
boolean pad = true;
boolean opts = true;
while (argi < args.length) {
String arg = args[argi++];
if (opts && arg.startsWith("-")) {
if (arg.equals("--")) {
opts = false;
} else if (arg.equals("-p")) {
pad = true;
} else if (arg.equals("-P")) {
pad = false;
} else if (arg.equals("-I")) {
try {
@SuppressWarnings("resource") | // Path: main/java/Vexillo/src/com/kreative/vexillo/core/Base64OutputStream.java
// public class Base64OutputStream extends OutputStream {
// private final StringBuffer sb;
// private final OutputStream out;
// private final boolean pad;
//
// public Base64OutputStream(StringBuffer sb) {
// this(sb, true);
// }
//
// public Base64OutputStream(OutputStream out) {
// this(out, true);
// }
//
// public Base64OutputStream(StringBuffer sb, boolean pad) {
// this.sb = sb;
// this.out = null;
// this.pad = pad;
// }
//
// public Base64OutputStream(OutputStream out, boolean pad) {
// this.sb = null;
// this.out = out;
// this.pad = pad;
// }
//
// private int word = 0;
// private int count = 0;
//
// @Override
// public void write(int b) throws IOException {
// word <<= 8;
// word |= (b & 0xFF);
// count++;
// if (count >= 3) {
// writeWord();
// word = 0;
// count = 0;
// }
// }
//
// @Override
// public void flush() throws IOException {
// if (out != null) out.flush();
// }
//
// @Override
// public void close() throws IOException {
// if (count > 0) {
// for (int i = count; i < 3; i++) word <<= 8;
// writeWord();
// }
// word = 0;
// count = 0;
// if (out != null) out.close();
// }
//
// private void writeWord() throws IOException {
// for (int m = 18, i = 0; i <= count; m -= 6, i++) {
// char c = b64e[(word >> m) & 0x3F];
// if (sb != null) sb.append(c);
// if (out != null) out.write(c);
// }
// if (pad) {
// for (int i = count; i < 3; i++) {
// if (sb != null) sb.append('=');
// if (out != null) out.write('=');
// }
// }
// }
//
// private static final char[] b64e = {
// 'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P',
// 'Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f',
// 'g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v',
// 'w','x','y','z','0','1','2','3','4','5','6','7','8','9','+','/',
// };
// }
// Path: main/java/Vexillo/src/com/kreative/vexillo/main/Base64Encode.java
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import com.kreative.vexillo.core.Base64OutputStream;
package com.kreative.vexillo.main;
public class Base64Encode {
public static void main(String[] args) {
main(Vexillo.arg0(Base64Encode.class), args, 0);
}
public static void main(String arg0, String[] args, int argi) {
boolean written = false;
boolean pad = true;
boolean opts = true;
while (argi < args.length) {
String arg = args[argi++];
if (opts && arg.startsWith("-")) {
if (arg.equals("--")) {
opts = false;
} else if (arg.equals("-p")) {
pad = true;
} else if (arg.equals("-P")) {
pad = false;
} else if (arg.equals("-I")) {
try {
@SuppressWarnings("resource") | Base64OutputStream out = new Base64OutputStream(System.out, pad); |
kreativekorp/vexillo | main/java/Vexillo/src/com/kreative/vexillo/ui/FlagPanel.java | // Path: main/java/Vexillo/src/com/kreative/vexillo/core/Flag.java
// public class Flag {
// private String id;
// private String name;
// private PropertySet properties;
// private Dimension fly;
// private Map<String, Dimension> dimensions;
// private Map<String, Color> colors;
// private Map<String, Symbol> symbols;
// private Map<String, Image> images;
// private List<Instruction> instructions;
//
// public Flag() {
// this.id = null;
// this.name = null;
// this.properties = new PropertySet();
// this.fly = new Dimension.Variable("h");
// this.dimensions = new TreeMap<String, Dimension>();
// this.colors = new TreeMap<String, Color>();
// this.symbols = new TreeMap<String, Symbol>();
// this.images = new TreeMap<String, Image>();
// this.instructions = new ArrayList<Instruction>();
// }
//
// public String getId() { return this.id; }
// public void setId(String id) { this.id = id; }
//
// public String getName() { return this.name; }
// public void setName(String name) { this.name = name; }
//
// public PropertySet getProperties() { return this.properties; }
// public void setProperties(PropertySet props) { this.properties = props; }
//
// public Dimension getFly() { return this.fly; }
// public void setFly(Dimension fly) { this.fly = fly; }
//
// public int getWidthFromHeight(int height) {
// return (int)Math.round(getWidthFromHeight2D(height));
// }
//
// public int getHeightFromWidth(int width) {
// return (int)Math.round(getHeightFromWidth2D(width));
// }
//
// public double getWidthFromHeight2D(double height) {
// Map<String, Dimension> ns = new HashMap<String, Dimension>();
// Dimension h = new Dimension.Constant(height);
// ns.put("h", h);
// ns.put("hoist", h);
// ns.put("height", h);
// ns.putAll(dimensions);
// return fly.value(ns);
// }
//
// public double getHeightFromWidth2D(double width) {
// return width / getWidthFromHeight2D(1);
// }
//
// public String getProportionString() {
// int bestDenom = 1;
// double bestNum = getWidthFromHeight2D(1);
// double bestError = Math.abs(bestNum - Math.round(bestNum));
// if (bestError == 0) return bestDenom + ":" + (int)Math.round(bestNum);
// for (int denom = 2; denom < 1000; denom++) {
// double num = getWidthFromHeight2D(denom);
// double error = Math.abs(num - Math.round(num));
// if (error == 0) return denom + ":" + (int)Math.round(num);
// else if (error < bestError) {
// bestDenom = denom;
// bestNum = num;
// bestError = error;
// }
// }
// return bestDenom + ":" + bestNum;
// }
//
// public Map<String, Dimension> dimensions() { return this.dimensions; }
// public Map<String, Color> colors() { return this.colors; }
// public Map<String, Symbol> symbols() { return this.symbols; }
// public Map<String, Image> images() { return this.images; }
// public List<Instruction> instructions() { return this.instructions; }
//
// public Map<String, Dimension> createNamespace(double height, double width) {
// Map<String, Dimension> ns = new HashMap<String, Dimension>();
// Dimension h = new Dimension.Constant(height);
// Dimension w = new Dimension.Constant(width);
// ns.put("h", h);
// ns.put("hoist", h);
// ns.put("height", h);
// ns.put("w", w);
// ns.put("width", w);
// ns.put("f", fly);
// ns.put("fly", fly);
// ns.putAll(dimensions);
// return ns;
// }
// }
| import java.awt.BorderLayout;
import java.io.File;
import javax.swing.JPanel;
import com.kreative.vexillo.core.Flag; | package com.kreative.vexillo.ui;
public class FlagPanel extends JPanel {
private static final long serialVersionUID = 1L;
private final FlagInfoPanel infoPanel;
private final FlagViewer viewer;
| // Path: main/java/Vexillo/src/com/kreative/vexillo/core/Flag.java
// public class Flag {
// private String id;
// private String name;
// private PropertySet properties;
// private Dimension fly;
// private Map<String, Dimension> dimensions;
// private Map<String, Color> colors;
// private Map<String, Symbol> symbols;
// private Map<String, Image> images;
// private List<Instruction> instructions;
//
// public Flag() {
// this.id = null;
// this.name = null;
// this.properties = new PropertySet();
// this.fly = new Dimension.Variable("h");
// this.dimensions = new TreeMap<String, Dimension>();
// this.colors = new TreeMap<String, Color>();
// this.symbols = new TreeMap<String, Symbol>();
// this.images = new TreeMap<String, Image>();
// this.instructions = new ArrayList<Instruction>();
// }
//
// public String getId() { return this.id; }
// public void setId(String id) { this.id = id; }
//
// public String getName() { return this.name; }
// public void setName(String name) { this.name = name; }
//
// public PropertySet getProperties() { return this.properties; }
// public void setProperties(PropertySet props) { this.properties = props; }
//
// public Dimension getFly() { return this.fly; }
// public void setFly(Dimension fly) { this.fly = fly; }
//
// public int getWidthFromHeight(int height) {
// return (int)Math.round(getWidthFromHeight2D(height));
// }
//
// public int getHeightFromWidth(int width) {
// return (int)Math.round(getHeightFromWidth2D(width));
// }
//
// public double getWidthFromHeight2D(double height) {
// Map<String, Dimension> ns = new HashMap<String, Dimension>();
// Dimension h = new Dimension.Constant(height);
// ns.put("h", h);
// ns.put("hoist", h);
// ns.put("height", h);
// ns.putAll(dimensions);
// return fly.value(ns);
// }
//
// public double getHeightFromWidth2D(double width) {
// return width / getWidthFromHeight2D(1);
// }
//
// public String getProportionString() {
// int bestDenom = 1;
// double bestNum = getWidthFromHeight2D(1);
// double bestError = Math.abs(bestNum - Math.round(bestNum));
// if (bestError == 0) return bestDenom + ":" + (int)Math.round(bestNum);
// for (int denom = 2; denom < 1000; denom++) {
// double num = getWidthFromHeight2D(denom);
// double error = Math.abs(num - Math.round(num));
// if (error == 0) return denom + ":" + (int)Math.round(num);
// else if (error < bestError) {
// bestDenom = denom;
// bestNum = num;
// bestError = error;
// }
// }
// return bestDenom + ":" + bestNum;
// }
//
// public Map<String, Dimension> dimensions() { return this.dimensions; }
// public Map<String, Color> colors() { return this.colors; }
// public Map<String, Symbol> symbols() { return this.symbols; }
// public Map<String, Image> images() { return this.images; }
// public List<Instruction> instructions() { return this.instructions; }
//
// public Map<String, Dimension> createNamespace(double height, double width) {
// Map<String, Dimension> ns = new HashMap<String, Dimension>();
// Dimension h = new Dimension.Constant(height);
// Dimension w = new Dimension.Constant(width);
// ns.put("h", h);
// ns.put("hoist", h);
// ns.put("height", h);
// ns.put("w", w);
// ns.put("width", w);
// ns.put("f", fly);
// ns.put("fly", fly);
// ns.putAll(dimensions);
// return ns;
// }
// }
// Path: main/java/Vexillo/src/com/kreative/vexillo/ui/FlagPanel.java
import java.awt.BorderLayout;
import java.io.File;
import javax.swing.JPanel;
import com.kreative.vexillo.core.Flag;
package com.kreative.vexillo.ui;
public class FlagPanel extends JPanel {
private static final long serialVersionUID = 1L;
private final FlagInfoPanel infoPanel;
private final FlagViewer viewer;
| public FlagPanel(File flagFile, File parent, Flag flag) { |
kreativekorp/vexillo | main/java/Vexillo/src/com/kreative/vexillo/main/ASCII85Decode.java | // Path: main/java/Vexillo/src/com/kreative/vexillo/core/ASCII85InputStream.java
// public class ASCII85InputStream extends InputStream {
// private final CharacterIterator ci;
// private final InputStream in;
//
// public ASCII85InputStream(String s) {
// this.ci = new StringCharacterIterator(s);
// this.in = null;
// }
//
// public ASCII85InputStream(CharacterIterator ci) {
// this.ci = ci;
// this.in = null;
// }
//
// public ASCII85InputStream(InputStream in) {
// this.ci = null;
// this.in = in;
// }
//
// private long word = 0;
// private int count = 0;
// private int rbyte = 0;
// private int rcount = 0;
// private boolean eof = false;
//
// @Override
// public int read() throws IOException {
// for (;;) {
// if (count > 0) {
// int b = (int)((word >> 24) & 0xFF);
// word <<= 8;
// count--;
// return b;
// }
// if (rcount > 0) {
// rcount--;
// return rbyte;
// }
// if (eof) return -1;
// readWord();
// }
// }
//
// private void readWord() throws IOException {
// for (;;) {
// int c = -1;
// if (ci != null) { c = ci.current(); ci.next(); }
// if (in != null) { c = in.read(); }
// if (c < 0 || c == '~' || c == CharacterIterator.DONE) {
// padWord();
// eof = true;
// return;
// } else if (c >= 'x' && c <= 'z') {
// padWord();
// switch (c) {
// case 'z': rbyte = 0x00; break;
// case 'y': rbyte = 0x20; break;
// case 'x': rbyte = 0xFF; break;
// }
// rcount = 4;
// return;
// } else if (c > ' ' && c < '~') {
// switch (c) {
// case 'w': c = '\"'; break;
// case 'v': c = '\''; break;
// case '{': c = '<'; break;
// case '}': c = '>'; break;
// case '|': c = '&'; break;
// }
// word *= 85;
// word += (c - '!');
// count++;
// if (count > 4) {
// count = 4;
// return;
// }
// }
// }
// }
//
// private void padWord() {
// if (count > 0) {
// for (int i = count; i <= 4; i++) {
// word *= 85;
// word += 84;
// }
// count--;
// }
// }
//
// @Override
// public void close() throws IOException {
// if (in != null) in.close();
// }
// }
| import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import com.kreative.vexillo.core.ASCII85InputStream; | package com.kreative.vexillo.main;
public class ASCII85Decode {
public static void main(String[] args) {
main(Vexillo.arg0(ASCII85Decode.class), args, 0);
}
public static void main(String arg0, String[] args, int argi) {
boolean written = false;
boolean opts = true;
while (argi < args.length) {
String arg = args[argi++];
if (opts && arg.startsWith("-")) {
if (arg.equals("--")) {
opts = false;
} else if (arg.equals("-I")) {
try {
@SuppressWarnings("resource") | // Path: main/java/Vexillo/src/com/kreative/vexillo/core/ASCII85InputStream.java
// public class ASCII85InputStream extends InputStream {
// private final CharacterIterator ci;
// private final InputStream in;
//
// public ASCII85InputStream(String s) {
// this.ci = new StringCharacterIterator(s);
// this.in = null;
// }
//
// public ASCII85InputStream(CharacterIterator ci) {
// this.ci = ci;
// this.in = null;
// }
//
// public ASCII85InputStream(InputStream in) {
// this.ci = null;
// this.in = in;
// }
//
// private long word = 0;
// private int count = 0;
// private int rbyte = 0;
// private int rcount = 0;
// private boolean eof = false;
//
// @Override
// public int read() throws IOException {
// for (;;) {
// if (count > 0) {
// int b = (int)((word >> 24) & 0xFF);
// word <<= 8;
// count--;
// return b;
// }
// if (rcount > 0) {
// rcount--;
// return rbyte;
// }
// if (eof) return -1;
// readWord();
// }
// }
//
// private void readWord() throws IOException {
// for (;;) {
// int c = -1;
// if (ci != null) { c = ci.current(); ci.next(); }
// if (in != null) { c = in.read(); }
// if (c < 0 || c == '~' || c == CharacterIterator.DONE) {
// padWord();
// eof = true;
// return;
// } else if (c >= 'x' && c <= 'z') {
// padWord();
// switch (c) {
// case 'z': rbyte = 0x00; break;
// case 'y': rbyte = 0x20; break;
// case 'x': rbyte = 0xFF; break;
// }
// rcount = 4;
// return;
// } else if (c > ' ' && c < '~') {
// switch (c) {
// case 'w': c = '\"'; break;
// case 'v': c = '\''; break;
// case '{': c = '<'; break;
// case '}': c = '>'; break;
// case '|': c = '&'; break;
// }
// word *= 85;
// word += (c - '!');
// count++;
// if (count > 4) {
// count = 4;
// return;
// }
// }
// }
// }
//
// private void padWord() {
// if (count > 0) {
// for (int i = count; i <= 4; i++) {
// word *= 85;
// word += 84;
// }
// count--;
// }
// }
//
// @Override
// public void close() throws IOException {
// if (in != null) in.close();
// }
// }
// Path: main/java/Vexillo/src/com/kreative/vexillo/main/ASCII85Decode.java
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import com.kreative.vexillo.core.ASCII85InputStream;
package com.kreative.vexillo.main;
public class ASCII85Decode {
public static void main(String[] args) {
main(Vexillo.arg0(ASCII85Decode.class), args, 0);
}
public static void main(String arg0, String[] args, int argi) {
boolean written = false;
boolean opts = true;
while (argi < args.length) {
String arg = args[argi++];
if (opts && arg.startsWith("-")) {
if (arg.equals("--")) {
opts = false;
} else if (arg.equals("-I")) {
try {
@SuppressWarnings("resource") | ASCII85InputStream in = new ASCII85InputStream(System.in); |
kreativekorp/vexillo | main/java/Vexillo/src/com/kreative/vexillo/core/SVGExporter.java | // Path: main/java/Vexillo/src/com/kreative/vexillo/core/Color.java
// public interface HasRGB {
// public int getRGB();
// }
| import java.awt.BasicStroke;
import java.awt.Shape;
import java.awt.Stroke;
import java.awt.geom.AffineTransform;
import java.awt.geom.Area;
import java.awt.geom.Line2D;
import java.awt.geom.PathIterator;
import java.awt.geom.Rectangle2D;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import com.kreative.vexillo.core.Color.HasRGB; | if (!styleBlock.isEmpty()) {
out.println("<style>");
for (String line : styleBlock) out.println(line);
out.println("</style>");
}
if (!defsBlock.isEmpty()) {
out.println("<defs>");
for (String line : defsBlock) out.println(line);
out.println("</defs>");
}
if (tx != 0 || ty != 0) out.println("<g transform=\"translate(" + tx + " " + ty + ")\">");
if (embeddedMode) out.println("<g clip-path=\"url(#bounds)\">");
if (!groupBlock.isEmpty()) {
out.println("<g>");
for (String line : groupBlock) out.println(line);
out.println("</g>");
}
if (!glazeBlock.isEmpty()) {
out.println("<g>");
for (String line : glazeBlock) out.println(line);
out.println("</g>");
}
if (embeddedMode) out.println("</g>");
if (tx != 0 || ty != 0) out.println("</g>");
if (embeddedMode) out.print("</svg>");
else out.println("</svg>");
}
private void prep(List<String> styleBlock, List<String> defsBlock) {
for (Map.Entry<String, Color> e : flag.colors().entrySet()) { | // Path: main/java/Vexillo/src/com/kreative/vexillo/core/Color.java
// public interface HasRGB {
// public int getRGB();
// }
// Path: main/java/Vexillo/src/com/kreative/vexillo/core/SVGExporter.java
import java.awt.BasicStroke;
import java.awt.Shape;
import java.awt.Stroke;
import java.awt.geom.AffineTransform;
import java.awt.geom.Area;
import java.awt.geom.Line2D;
import java.awt.geom.PathIterator;
import java.awt.geom.Rectangle2D;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import com.kreative.vexillo.core.Color.HasRGB;
if (!styleBlock.isEmpty()) {
out.println("<style>");
for (String line : styleBlock) out.println(line);
out.println("</style>");
}
if (!defsBlock.isEmpty()) {
out.println("<defs>");
for (String line : defsBlock) out.println(line);
out.println("</defs>");
}
if (tx != 0 || ty != 0) out.println("<g transform=\"translate(" + tx + " " + ty + ")\">");
if (embeddedMode) out.println("<g clip-path=\"url(#bounds)\">");
if (!groupBlock.isEmpty()) {
out.println("<g>");
for (String line : groupBlock) out.println(line);
out.println("</g>");
}
if (!glazeBlock.isEmpty()) {
out.println("<g>");
for (String line : glazeBlock) out.println(line);
out.println("</g>");
}
if (embeddedMode) out.println("</g>");
if (tx != 0 || ty != 0) out.println("</g>");
if (embeddedMode) out.print("</svg>");
else out.println("</svg>");
}
private void prep(List<String> styleBlock, List<String> defsBlock) {
for (Map.Entry<String, Color> e : flag.colors().entrySet()) { | if (e.getValue() instanceof Color.HasRGB) { |
kreativekorp/vexillo | main/java/Vexillo/src/com/kreative/vexillo/main/ASCII85Encode.java | // Path: main/java/Vexillo/src/com/kreative/vexillo/core/ASCII85OutputStream.java
// public class ASCII85OutputStream extends OutputStream {
// private final StringBuffer sb;
// private final OutputStream out;
// private final boolean xml, x, y, z;
//
// public ASCII85OutputStream(StringBuffer sb) {
// this(sb, false, false, false, true);
// }
//
// public ASCII85OutputStream(OutputStream out) {
// this(out, false, false, false, true);
// }
//
// public ASCII85OutputStream(StringBuffer sb, boolean xml, boolean x, boolean y, boolean z) {
// this.sb = sb;
// this.out = null;
// this.xml = xml;
// this.x = x;
// this.y = y;
// this.z = z;
// }
//
// public ASCII85OutputStream(OutputStream out, boolean xml, boolean x, boolean y, boolean z) {
// this.sb = null;
// this.out = out;
// this.xml = xml;
// this.x = x;
// this.y = y;
// this.z = z;
// }
//
// private long word = 0;
// private int count = 0;
//
// @Override
// public void write(int b) throws IOException {
// if (count < 0) {
// if (sb != null) sb.append('~');
// if (out != null) out.write('~');
// word = 0;
// count = 0;
// }
// word <<= 8;
// word |= (b & 0xFF);
// count++;
// if (count >= 4) {
// if (word == 0x00000000L && z) {
// if (sb != null) sb.append('z');
// if (out != null) out.write('z');
// } else if (word == 0x20202020L && y) {
// if (sb != null) sb.append('y');
// if (out != null) out.write('y');
// } else if (word == 0xFFFFFFFFL && x) {
// if (sb != null) sb.append('x');
// if (out != null) out.write('x');
// } else {
// writeWord();
// }
// word = 0;
// count = 0;
// }
// }
//
// @Override
// public void flush() throws IOException {
// if (out != null) out.flush();
// }
//
// @Override
// public void close() throws IOException {
// if (count > 0) {
// for (int i = count; i < 4; i++) word <<= 8;
// writeWord();
// }
// word = -1;
// count = -1;
// if (out != null) out.close();
// }
//
// private void writeWord() throws IOException {
// for (int d = 52200625, i = 0; i <= count; d /= 85, i++) {
// char c = (char)('!' + ((word / d) % 85));
// if (xml) {
// switch (c) {
// case '&': c = '|'; break;
// case '<': c = '{'; break;
// case '>': c = '}'; break;
// case '\'': c = 'v'; break;
// case '\"': c = 'w'; break;
// }
// }
// if (sb != null) sb.append(c);
// if (out != null) out.write(c);
// }
// }
// }
| import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import com.kreative.vexillo.core.ASCII85OutputStream; | boolean written = false;
boolean xml = false;
boolean x = false;
boolean y = false;
boolean z = true;
boolean opts = true;
while (argi < args.length) {
String arg = args[argi++];
if (opts && arg.startsWith("-")) {
if (arg.equals("--")) {
opts = false;
} else if (arg.equals("-x")) {
x = true;
} else if (arg.equals("-X")) {
x = false;
} else if (arg.equals("-y")) {
y = true;
} else if (arg.equals("-Y")) {
y = false;
} else if (arg.equals("-z")) {
z = true;
} else if (arg.equals("-Z")) {
z = false;
} else if (arg.equals("-m")) {
xml = true;
} else if (arg.equals("-M")) {
xml = false;
} else if (arg.equals("-I")) {
try {
@SuppressWarnings("resource") | // Path: main/java/Vexillo/src/com/kreative/vexillo/core/ASCII85OutputStream.java
// public class ASCII85OutputStream extends OutputStream {
// private final StringBuffer sb;
// private final OutputStream out;
// private final boolean xml, x, y, z;
//
// public ASCII85OutputStream(StringBuffer sb) {
// this(sb, false, false, false, true);
// }
//
// public ASCII85OutputStream(OutputStream out) {
// this(out, false, false, false, true);
// }
//
// public ASCII85OutputStream(StringBuffer sb, boolean xml, boolean x, boolean y, boolean z) {
// this.sb = sb;
// this.out = null;
// this.xml = xml;
// this.x = x;
// this.y = y;
// this.z = z;
// }
//
// public ASCII85OutputStream(OutputStream out, boolean xml, boolean x, boolean y, boolean z) {
// this.sb = null;
// this.out = out;
// this.xml = xml;
// this.x = x;
// this.y = y;
// this.z = z;
// }
//
// private long word = 0;
// private int count = 0;
//
// @Override
// public void write(int b) throws IOException {
// if (count < 0) {
// if (sb != null) sb.append('~');
// if (out != null) out.write('~');
// word = 0;
// count = 0;
// }
// word <<= 8;
// word |= (b & 0xFF);
// count++;
// if (count >= 4) {
// if (word == 0x00000000L && z) {
// if (sb != null) sb.append('z');
// if (out != null) out.write('z');
// } else if (word == 0x20202020L && y) {
// if (sb != null) sb.append('y');
// if (out != null) out.write('y');
// } else if (word == 0xFFFFFFFFL && x) {
// if (sb != null) sb.append('x');
// if (out != null) out.write('x');
// } else {
// writeWord();
// }
// word = 0;
// count = 0;
// }
// }
//
// @Override
// public void flush() throws IOException {
// if (out != null) out.flush();
// }
//
// @Override
// public void close() throws IOException {
// if (count > 0) {
// for (int i = count; i < 4; i++) word <<= 8;
// writeWord();
// }
// word = -1;
// count = -1;
// if (out != null) out.close();
// }
//
// private void writeWord() throws IOException {
// for (int d = 52200625, i = 0; i <= count; d /= 85, i++) {
// char c = (char)('!' + ((word / d) % 85));
// if (xml) {
// switch (c) {
// case '&': c = '|'; break;
// case '<': c = '{'; break;
// case '>': c = '}'; break;
// case '\'': c = 'v'; break;
// case '\"': c = 'w'; break;
// }
// }
// if (sb != null) sb.append(c);
// if (out != null) out.write(c);
// }
// }
// }
// Path: main/java/Vexillo/src/com/kreative/vexillo/main/ASCII85Encode.java
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import com.kreative.vexillo.core.ASCII85OutputStream;
boolean written = false;
boolean xml = false;
boolean x = false;
boolean y = false;
boolean z = true;
boolean opts = true;
while (argi < args.length) {
String arg = args[argi++];
if (opts && arg.startsWith("-")) {
if (arg.equals("--")) {
opts = false;
} else if (arg.equals("-x")) {
x = true;
} else if (arg.equals("-X")) {
x = false;
} else if (arg.equals("-y")) {
y = true;
} else if (arg.equals("-Y")) {
y = false;
} else if (arg.equals("-z")) {
z = true;
} else if (arg.equals("-Z")) {
z = false;
} else if (arg.equals("-m")) {
xml = true;
} else if (arg.equals("-M")) {
xml = false;
} else if (arg.equals("-I")) {
try {
@SuppressWarnings("resource") | ASCII85OutputStream out = new ASCII85OutputStream(System.out, xml, x, y, z); |
kreativekorp/vexillo | main/java/Vexillo/src/com/kreative/vexillo/main/DefineImage.java | // Path: main/java/Vexillo/src/com/kreative/vexillo/core/ASCII85OutputStream.java
// public class ASCII85OutputStream extends OutputStream {
// private final StringBuffer sb;
// private final OutputStream out;
// private final boolean xml, x, y, z;
//
// public ASCII85OutputStream(StringBuffer sb) {
// this(sb, false, false, false, true);
// }
//
// public ASCII85OutputStream(OutputStream out) {
// this(out, false, false, false, true);
// }
//
// public ASCII85OutputStream(StringBuffer sb, boolean xml, boolean x, boolean y, boolean z) {
// this.sb = sb;
// this.out = null;
// this.xml = xml;
// this.x = x;
// this.y = y;
// this.z = z;
// }
//
// public ASCII85OutputStream(OutputStream out, boolean xml, boolean x, boolean y, boolean z) {
// this.sb = null;
// this.out = out;
// this.xml = xml;
// this.x = x;
// this.y = y;
// this.z = z;
// }
//
// private long word = 0;
// private int count = 0;
//
// @Override
// public void write(int b) throws IOException {
// if (count < 0) {
// if (sb != null) sb.append('~');
// if (out != null) out.write('~');
// word = 0;
// count = 0;
// }
// word <<= 8;
// word |= (b & 0xFF);
// count++;
// if (count >= 4) {
// if (word == 0x00000000L && z) {
// if (sb != null) sb.append('z');
// if (out != null) out.write('z');
// } else if (word == 0x20202020L && y) {
// if (sb != null) sb.append('y');
// if (out != null) out.write('y');
// } else if (word == 0xFFFFFFFFL && x) {
// if (sb != null) sb.append('x');
// if (out != null) out.write('x');
// } else {
// writeWord();
// }
// word = 0;
// count = 0;
// }
// }
//
// @Override
// public void flush() throws IOException {
// if (out != null) out.flush();
// }
//
// @Override
// public void close() throws IOException {
// if (count > 0) {
// for (int i = count; i < 4; i++) word <<= 8;
// writeWord();
// }
// word = -1;
// count = -1;
// if (out != null) out.close();
// }
//
// private void writeWord() throws IOException {
// for (int d = 52200625, i = 0; i <= count; d /= 85, i++) {
// char c = (char)('!' + ((word / d) % 85));
// if (xml) {
// switch (c) {
// case '&': c = '|'; break;
// case '<': c = '{'; break;
// case '>': c = '}'; break;
// case '\'': c = 'v'; break;
// case '\"': c = 'w'; break;
// }
// }
// if (sb != null) sb.append(c);
// if (out != null) out.write(c);
// }
// }
// }
| import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Scanner;
import com.kreative.vexillo.core.ASCII85OutputStream; | }
}
if (anyWritten) System.out.println("\t\t</imgdef>");
}
private static boolean writeRaw(String imageId, boolean anyWritten, File file, String type) throws IOException {
boolean thisWritten = false;
Scanner scan = new Scanner(file);
while (scan.hasNextLine()) {
String line = scan.nextLine();
if (line.trim().length() == 0) continue;
if (!anyWritten) System.out.println("\t\t<imgdef id=\"" + xmlEscape(imageId) + "\">");
if (!thisWritten) {
System.out.println("\t\t\t<imgsrc type=\"" + xmlEscape(type) + "\" enc=\"raw\">");
System.out.println("\t\t\t\t<![CDATA[");
}
System.out.println("\t\t\t\t\t" + line);
thisWritten = true;
anyWritten = true;
}
scan.close();
if (thisWritten) {
System.out.println("\t\t\t\t]]>");
System.out.println("\t\t\t</imgsrc>");
}
return anyWritten;
}
private static boolean writeASCII85(String imageId, boolean anyWritten, File file, String type) throws IOException {
ByteArrayOutputStream bs = new ByteArrayOutputStream(); | // Path: main/java/Vexillo/src/com/kreative/vexillo/core/ASCII85OutputStream.java
// public class ASCII85OutputStream extends OutputStream {
// private final StringBuffer sb;
// private final OutputStream out;
// private final boolean xml, x, y, z;
//
// public ASCII85OutputStream(StringBuffer sb) {
// this(sb, false, false, false, true);
// }
//
// public ASCII85OutputStream(OutputStream out) {
// this(out, false, false, false, true);
// }
//
// public ASCII85OutputStream(StringBuffer sb, boolean xml, boolean x, boolean y, boolean z) {
// this.sb = sb;
// this.out = null;
// this.xml = xml;
// this.x = x;
// this.y = y;
// this.z = z;
// }
//
// public ASCII85OutputStream(OutputStream out, boolean xml, boolean x, boolean y, boolean z) {
// this.sb = null;
// this.out = out;
// this.xml = xml;
// this.x = x;
// this.y = y;
// this.z = z;
// }
//
// private long word = 0;
// private int count = 0;
//
// @Override
// public void write(int b) throws IOException {
// if (count < 0) {
// if (sb != null) sb.append('~');
// if (out != null) out.write('~');
// word = 0;
// count = 0;
// }
// word <<= 8;
// word |= (b & 0xFF);
// count++;
// if (count >= 4) {
// if (word == 0x00000000L && z) {
// if (sb != null) sb.append('z');
// if (out != null) out.write('z');
// } else if (word == 0x20202020L && y) {
// if (sb != null) sb.append('y');
// if (out != null) out.write('y');
// } else if (word == 0xFFFFFFFFL && x) {
// if (sb != null) sb.append('x');
// if (out != null) out.write('x');
// } else {
// writeWord();
// }
// word = 0;
// count = 0;
// }
// }
//
// @Override
// public void flush() throws IOException {
// if (out != null) out.flush();
// }
//
// @Override
// public void close() throws IOException {
// if (count > 0) {
// for (int i = count; i < 4; i++) word <<= 8;
// writeWord();
// }
// word = -1;
// count = -1;
// if (out != null) out.close();
// }
//
// private void writeWord() throws IOException {
// for (int d = 52200625, i = 0; i <= count; d /= 85, i++) {
// char c = (char)('!' + ((word / d) % 85));
// if (xml) {
// switch (c) {
// case '&': c = '|'; break;
// case '<': c = '{'; break;
// case '>': c = '}'; break;
// case '\'': c = 'v'; break;
// case '\"': c = 'w'; break;
// }
// }
// if (sb != null) sb.append(c);
// if (out != null) out.write(c);
// }
// }
// }
// Path: main/java/Vexillo/src/com/kreative/vexillo/main/DefineImage.java
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Scanner;
import com.kreative.vexillo.core.ASCII85OutputStream;
}
}
if (anyWritten) System.out.println("\t\t</imgdef>");
}
private static boolean writeRaw(String imageId, boolean anyWritten, File file, String type) throws IOException {
boolean thisWritten = false;
Scanner scan = new Scanner(file);
while (scan.hasNextLine()) {
String line = scan.nextLine();
if (line.trim().length() == 0) continue;
if (!anyWritten) System.out.println("\t\t<imgdef id=\"" + xmlEscape(imageId) + "\">");
if (!thisWritten) {
System.out.println("\t\t\t<imgsrc type=\"" + xmlEscape(type) + "\" enc=\"raw\">");
System.out.println("\t\t\t\t<![CDATA[");
}
System.out.println("\t\t\t\t\t" + line);
thisWritten = true;
anyWritten = true;
}
scan.close();
if (thisWritten) {
System.out.println("\t\t\t\t]]>");
System.out.println("\t\t\t</imgsrc>");
}
return anyWritten;
}
private static boolean writeASCII85(String imageId, boolean anyWritten, File file, String type) throws IOException {
ByteArrayOutputStream bs = new ByteArrayOutputStream(); | ASCII85OutputStream as = new ASCII85OutputStream(bs, false, false, false, true); |
kreativekorp/vexillo | main/java/Vexillo/src/com/kreative/vexillo/font/FlagFontFamily.java | // Path: main/java/Vexillo/src/com/kreative/vexillo/core/Flag.java
// public class Flag {
// private String id;
// private String name;
// private PropertySet properties;
// private Dimension fly;
// private Map<String, Dimension> dimensions;
// private Map<String, Color> colors;
// private Map<String, Symbol> symbols;
// private Map<String, Image> images;
// private List<Instruction> instructions;
//
// public Flag() {
// this.id = null;
// this.name = null;
// this.properties = new PropertySet();
// this.fly = new Dimension.Variable("h");
// this.dimensions = new TreeMap<String, Dimension>();
// this.colors = new TreeMap<String, Color>();
// this.symbols = new TreeMap<String, Symbol>();
// this.images = new TreeMap<String, Image>();
// this.instructions = new ArrayList<Instruction>();
// }
//
// public String getId() { return this.id; }
// public void setId(String id) { this.id = id; }
//
// public String getName() { return this.name; }
// public void setName(String name) { this.name = name; }
//
// public PropertySet getProperties() { return this.properties; }
// public void setProperties(PropertySet props) { this.properties = props; }
//
// public Dimension getFly() { return this.fly; }
// public void setFly(Dimension fly) { this.fly = fly; }
//
// public int getWidthFromHeight(int height) {
// return (int)Math.round(getWidthFromHeight2D(height));
// }
//
// public int getHeightFromWidth(int width) {
// return (int)Math.round(getHeightFromWidth2D(width));
// }
//
// public double getWidthFromHeight2D(double height) {
// Map<String, Dimension> ns = new HashMap<String, Dimension>();
// Dimension h = new Dimension.Constant(height);
// ns.put("h", h);
// ns.put("hoist", h);
// ns.put("height", h);
// ns.putAll(dimensions);
// return fly.value(ns);
// }
//
// public double getHeightFromWidth2D(double width) {
// return width / getWidthFromHeight2D(1);
// }
//
// public String getProportionString() {
// int bestDenom = 1;
// double bestNum = getWidthFromHeight2D(1);
// double bestError = Math.abs(bestNum - Math.round(bestNum));
// if (bestError == 0) return bestDenom + ":" + (int)Math.round(bestNum);
// for (int denom = 2; denom < 1000; denom++) {
// double num = getWidthFromHeight2D(denom);
// double error = Math.abs(num - Math.round(num));
// if (error == 0) return denom + ":" + (int)Math.round(num);
// else if (error < bestError) {
// bestDenom = denom;
// bestNum = num;
// bestError = error;
// }
// }
// return bestDenom + ":" + bestNum;
// }
//
// public Map<String, Dimension> dimensions() { return this.dimensions; }
// public Map<String, Color> colors() { return this.colors; }
// public Map<String, Symbol> symbols() { return this.symbols; }
// public Map<String, Image> images() { return this.images; }
// public List<Instruction> instructions() { return this.instructions; }
//
// public Map<String, Dimension> createNamespace(double height, double width) {
// Map<String, Dimension> ns = new HashMap<String, Dimension>();
// Dimension h = new Dimension.Constant(height);
// Dimension w = new Dimension.Constant(width);
// ns.put("h", h);
// ns.put("hoist", h);
// ns.put("height", h);
// ns.put("w", w);
// ns.put("width", w);
// ns.put("f", fly);
// ns.put("fly", fly);
// ns.putAll(dimensions);
// return ns;
// }
// }
//
// Path: main/java/Vexillo/src/com/kreative/vexillo/style/Stylizer.java
// public interface Stylizer {
// public BufferedImage stylize(
// FlagRenderer r, int width, int height,
// // The following parameters may be ignored if desired.
// ImageScaler supersampler, int supersample, int glaze
// );
// }
| import java.io.File;
import java.util.Calendar;
import java.util.Collections;
import java.util.GregorianCalendar;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.TreeMap;
import java.util.TreeSet;
import com.kreative.vexillo.core.Flag;
import com.kreative.vexillo.style.Stylizer; | package com.kreative.vexillo.font;
public class FlagFontFamily {
private final Encoding encoding;
private final SortedSet<EncodingNode> nodes; | // Path: main/java/Vexillo/src/com/kreative/vexillo/core/Flag.java
// public class Flag {
// private String id;
// private String name;
// private PropertySet properties;
// private Dimension fly;
// private Map<String, Dimension> dimensions;
// private Map<String, Color> colors;
// private Map<String, Symbol> symbols;
// private Map<String, Image> images;
// private List<Instruction> instructions;
//
// public Flag() {
// this.id = null;
// this.name = null;
// this.properties = new PropertySet();
// this.fly = new Dimension.Variable("h");
// this.dimensions = new TreeMap<String, Dimension>();
// this.colors = new TreeMap<String, Color>();
// this.symbols = new TreeMap<String, Symbol>();
// this.images = new TreeMap<String, Image>();
// this.instructions = new ArrayList<Instruction>();
// }
//
// public String getId() { return this.id; }
// public void setId(String id) { this.id = id; }
//
// public String getName() { return this.name; }
// public void setName(String name) { this.name = name; }
//
// public PropertySet getProperties() { return this.properties; }
// public void setProperties(PropertySet props) { this.properties = props; }
//
// public Dimension getFly() { return this.fly; }
// public void setFly(Dimension fly) { this.fly = fly; }
//
// public int getWidthFromHeight(int height) {
// return (int)Math.round(getWidthFromHeight2D(height));
// }
//
// public int getHeightFromWidth(int width) {
// return (int)Math.round(getHeightFromWidth2D(width));
// }
//
// public double getWidthFromHeight2D(double height) {
// Map<String, Dimension> ns = new HashMap<String, Dimension>();
// Dimension h = new Dimension.Constant(height);
// ns.put("h", h);
// ns.put("hoist", h);
// ns.put("height", h);
// ns.putAll(dimensions);
// return fly.value(ns);
// }
//
// public double getHeightFromWidth2D(double width) {
// return width / getWidthFromHeight2D(1);
// }
//
// public String getProportionString() {
// int bestDenom = 1;
// double bestNum = getWidthFromHeight2D(1);
// double bestError = Math.abs(bestNum - Math.round(bestNum));
// if (bestError == 0) return bestDenom + ":" + (int)Math.round(bestNum);
// for (int denom = 2; denom < 1000; denom++) {
// double num = getWidthFromHeight2D(denom);
// double error = Math.abs(num - Math.round(num));
// if (error == 0) return denom + ":" + (int)Math.round(num);
// else if (error < bestError) {
// bestDenom = denom;
// bestNum = num;
// bestError = error;
// }
// }
// return bestDenom + ":" + bestNum;
// }
//
// public Map<String, Dimension> dimensions() { return this.dimensions; }
// public Map<String, Color> colors() { return this.colors; }
// public Map<String, Symbol> symbols() { return this.symbols; }
// public Map<String, Image> images() { return this.images; }
// public List<Instruction> instructions() { return this.instructions; }
//
// public Map<String, Dimension> createNamespace(double height, double width) {
// Map<String, Dimension> ns = new HashMap<String, Dimension>();
// Dimension h = new Dimension.Constant(height);
// Dimension w = new Dimension.Constant(width);
// ns.put("h", h);
// ns.put("hoist", h);
// ns.put("height", h);
// ns.put("w", w);
// ns.put("width", w);
// ns.put("f", fly);
// ns.put("fly", fly);
// ns.putAll(dimensions);
// return ns;
// }
// }
//
// Path: main/java/Vexillo/src/com/kreative/vexillo/style/Stylizer.java
// public interface Stylizer {
// public BufferedImage stylize(
// FlagRenderer r, int width, int height,
// // The following parameters may be ignored if desired.
// ImageScaler supersampler, int supersample, int glaze
// );
// }
// Path: main/java/Vexillo/src/com/kreative/vexillo/font/FlagFontFamily.java
import java.io.File;
import java.util.Calendar;
import java.util.Collections;
import java.util.GregorianCalendar;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.TreeMap;
import java.util.TreeSet;
import com.kreative.vexillo.core.Flag;
import com.kreative.vexillo.style.Stylizer;
package com.kreative.vexillo.font;
public class FlagFontFamily {
private final Encoding encoding;
private final SortedSet<EncodingNode> nodes; | private final SortedMap<EncodingNode, Flag> flags; |
kreativekorp/vexillo | main/java/Vexillo/src/com/kreative/vexillo/font/FlagFontFamily.java | // Path: main/java/Vexillo/src/com/kreative/vexillo/core/Flag.java
// public class Flag {
// private String id;
// private String name;
// private PropertySet properties;
// private Dimension fly;
// private Map<String, Dimension> dimensions;
// private Map<String, Color> colors;
// private Map<String, Symbol> symbols;
// private Map<String, Image> images;
// private List<Instruction> instructions;
//
// public Flag() {
// this.id = null;
// this.name = null;
// this.properties = new PropertySet();
// this.fly = new Dimension.Variable("h");
// this.dimensions = new TreeMap<String, Dimension>();
// this.colors = new TreeMap<String, Color>();
// this.symbols = new TreeMap<String, Symbol>();
// this.images = new TreeMap<String, Image>();
// this.instructions = new ArrayList<Instruction>();
// }
//
// public String getId() { return this.id; }
// public void setId(String id) { this.id = id; }
//
// public String getName() { return this.name; }
// public void setName(String name) { this.name = name; }
//
// public PropertySet getProperties() { return this.properties; }
// public void setProperties(PropertySet props) { this.properties = props; }
//
// public Dimension getFly() { return this.fly; }
// public void setFly(Dimension fly) { this.fly = fly; }
//
// public int getWidthFromHeight(int height) {
// return (int)Math.round(getWidthFromHeight2D(height));
// }
//
// public int getHeightFromWidth(int width) {
// return (int)Math.round(getHeightFromWidth2D(width));
// }
//
// public double getWidthFromHeight2D(double height) {
// Map<String, Dimension> ns = new HashMap<String, Dimension>();
// Dimension h = new Dimension.Constant(height);
// ns.put("h", h);
// ns.put("hoist", h);
// ns.put("height", h);
// ns.putAll(dimensions);
// return fly.value(ns);
// }
//
// public double getHeightFromWidth2D(double width) {
// return width / getWidthFromHeight2D(1);
// }
//
// public String getProportionString() {
// int bestDenom = 1;
// double bestNum = getWidthFromHeight2D(1);
// double bestError = Math.abs(bestNum - Math.round(bestNum));
// if (bestError == 0) return bestDenom + ":" + (int)Math.round(bestNum);
// for (int denom = 2; denom < 1000; denom++) {
// double num = getWidthFromHeight2D(denom);
// double error = Math.abs(num - Math.round(num));
// if (error == 0) return denom + ":" + (int)Math.round(num);
// else if (error < bestError) {
// bestDenom = denom;
// bestNum = num;
// bestError = error;
// }
// }
// return bestDenom + ":" + bestNum;
// }
//
// public Map<String, Dimension> dimensions() { return this.dimensions; }
// public Map<String, Color> colors() { return this.colors; }
// public Map<String, Symbol> symbols() { return this.symbols; }
// public Map<String, Image> images() { return this.images; }
// public List<Instruction> instructions() { return this.instructions; }
//
// public Map<String, Dimension> createNamespace(double height, double width) {
// Map<String, Dimension> ns = new HashMap<String, Dimension>();
// Dimension h = new Dimension.Constant(height);
// Dimension w = new Dimension.Constant(width);
// ns.put("h", h);
// ns.put("hoist", h);
// ns.put("height", h);
// ns.put("w", w);
// ns.put("width", w);
// ns.put("f", fly);
// ns.put("fly", fly);
// ns.putAll(dimensions);
// return ns;
// }
// }
//
// Path: main/java/Vexillo/src/com/kreative/vexillo/style/Stylizer.java
// public interface Stylizer {
// public BufferedImage stylize(
// FlagRenderer r, int width, int height,
// // The following parameters may be ignored if desired.
// ImageScaler supersampler, int supersample, int glaze
// );
// }
| import java.io.File;
import java.util.Calendar;
import java.util.Collections;
import java.util.GregorianCalendar;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.TreeMap;
import java.util.TreeSet;
import com.kreative.vexillo.core.Flag;
import com.kreative.vexillo.style.Stylizer; | package com.kreative.vexillo.font;
public class FlagFontFamily {
private final Encoding encoding;
private final SortedSet<EncodingNode> nodes;
private final SortedMap<EncodingNode, Flag> flags;
private final SortedMap<EncodingNode, File> parents;
private final SortedMap<EncodingNode, File> flagFiles;
/* Font properties */
public String name = "Kreative Vexillo";
public String copyright = (
"Copyright 2017-" +
new GregorianCalendar().get(Calendar.YEAR) +
" Kreative Software"
);
public String vendorId = "KrKo";
public int emAscent = 900;
public int emDescent = 300;
public int lineAscent = 1200;
public int lineDescent = 400;
/* Glyph properties */
public int spaceWidth = 400;
public int leftBearing = 0;
public int rightBearing = 0;
public int glyphBottom = -100;
public int glyphHeight = 1100;
public int glyphWidth = 1600;
public int bitmapHeight = 88;
public int bitmapWidth = 128;
public int bitmapGlaze = 8; | // Path: main/java/Vexillo/src/com/kreative/vexillo/core/Flag.java
// public class Flag {
// private String id;
// private String name;
// private PropertySet properties;
// private Dimension fly;
// private Map<String, Dimension> dimensions;
// private Map<String, Color> colors;
// private Map<String, Symbol> symbols;
// private Map<String, Image> images;
// private List<Instruction> instructions;
//
// public Flag() {
// this.id = null;
// this.name = null;
// this.properties = new PropertySet();
// this.fly = new Dimension.Variable("h");
// this.dimensions = new TreeMap<String, Dimension>();
// this.colors = new TreeMap<String, Color>();
// this.symbols = new TreeMap<String, Symbol>();
// this.images = new TreeMap<String, Image>();
// this.instructions = new ArrayList<Instruction>();
// }
//
// public String getId() { return this.id; }
// public void setId(String id) { this.id = id; }
//
// public String getName() { return this.name; }
// public void setName(String name) { this.name = name; }
//
// public PropertySet getProperties() { return this.properties; }
// public void setProperties(PropertySet props) { this.properties = props; }
//
// public Dimension getFly() { return this.fly; }
// public void setFly(Dimension fly) { this.fly = fly; }
//
// public int getWidthFromHeight(int height) {
// return (int)Math.round(getWidthFromHeight2D(height));
// }
//
// public int getHeightFromWidth(int width) {
// return (int)Math.round(getHeightFromWidth2D(width));
// }
//
// public double getWidthFromHeight2D(double height) {
// Map<String, Dimension> ns = new HashMap<String, Dimension>();
// Dimension h = new Dimension.Constant(height);
// ns.put("h", h);
// ns.put("hoist", h);
// ns.put("height", h);
// ns.putAll(dimensions);
// return fly.value(ns);
// }
//
// public double getHeightFromWidth2D(double width) {
// return width / getWidthFromHeight2D(1);
// }
//
// public String getProportionString() {
// int bestDenom = 1;
// double bestNum = getWidthFromHeight2D(1);
// double bestError = Math.abs(bestNum - Math.round(bestNum));
// if (bestError == 0) return bestDenom + ":" + (int)Math.round(bestNum);
// for (int denom = 2; denom < 1000; denom++) {
// double num = getWidthFromHeight2D(denom);
// double error = Math.abs(num - Math.round(num));
// if (error == 0) return denom + ":" + (int)Math.round(num);
// else if (error < bestError) {
// bestDenom = denom;
// bestNum = num;
// bestError = error;
// }
// }
// return bestDenom + ":" + bestNum;
// }
//
// public Map<String, Dimension> dimensions() { return this.dimensions; }
// public Map<String, Color> colors() { return this.colors; }
// public Map<String, Symbol> symbols() { return this.symbols; }
// public Map<String, Image> images() { return this.images; }
// public List<Instruction> instructions() { return this.instructions; }
//
// public Map<String, Dimension> createNamespace(double height, double width) {
// Map<String, Dimension> ns = new HashMap<String, Dimension>();
// Dimension h = new Dimension.Constant(height);
// Dimension w = new Dimension.Constant(width);
// ns.put("h", h);
// ns.put("hoist", h);
// ns.put("height", h);
// ns.put("w", w);
// ns.put("width", w);
// ns.put("f", fly);
// ns.put("fly", fly);
// ns.putAll(dimensions);
// return ns;
// }
// }
//
// Path: main/java/Vexillo/src/com/kreative/vexillo/style/Stylizer.java
// public interface Stylizer {
// public BufferedImage stylize(
// FlagRenderer r, int width, int height,
// // The following parameters may be ignored if desired.
// ImageScaler supersampler, int supersample, int glaze
// );
// }
// Path: main/java/Vexillo/src/com/kreative/vexillo/font/FlagFontFamily.java
import java.io.File;
import java.util.Calendar;
import java.util.Collections;
import java.util.GregorianCalendar;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.TreeMap;
import java.util.TreeSet;
import com.kreative.vexillo.core.Flag;
import com.kreative.vexillo.style.Stylizer;
package com.kreative.vexillo.font;
public class FlagFontFamily {
private final Encoding encoding;
private final SortedSet<EncodingNode> nodes;
private final SortedMap<EncodingNode, Flag> flags;
private final SortedMap<EncodingNode, File> parents;
private final SortedMap<EncodingNode, File> flagFiles;
/* Font properties */
public String name = "Kreative Vexillo";
public String copyright = (
"Copyright 2017-" +
new GregorianCalendar().get(Calendar.YEAR) +
" Kreative Software"
);
public String vendorId = "KrKo";
public int emAscent = 900;
public int emDescent = 300;
public int lineAscent = 1200;
public int lineDescent = 400;
/* Glyph properties */
public int spaceWidth = 400;
public int leftBearing = 0;
public int rightBearing = 0;
public int glyphBottom = -100;
public int glyphHeight = 1100;
public int glyphWidth = 1600;
public int bitmapHeight = 88;
public int bitmapWidth = 128;
public int bitmapGlaze = 8; | public Stylizer bitmapStyle = null; |
takahashikzn/indolently | src/main/java/jp/root42/indolently/ref/$bool.java | // Path: src/main/java/jp/root42/indolently/function/Statement.java
// @FunctionalInterface
// public interface Statement
// extends Runnable {
//
// Statement NOP = () -> {};
//
// /**
// * Perform this operation.
// *
// * @throws Exception any exception which this statement would throw
// */
// void exec() throws Exception;
//
// /**
// * Perform this operation.
// */
// @Override
// default void run() {
// try {
// this.exec();
// } catch (final Exception e) {
// Expressive.raise(e);
// }
// }
//
// /**
// * Returns composed statement which execute this statement then execute {@code after}.
// *
// * @param after statement which execute after this statement
// * @return composed statement
// */
// default Statement andThen(final Statement after) {
//
// Objects.requireNonNull(after);
//
// return () -> {
// this.run();
// after.run();
// };
// }
// }
| import java.util.function.Predicate;
import jp.root42.indolently.function.Statement;
import java.util.function.BooleanSupplier; | // Copyright 2014 takahashikzn
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package jp.root42.indolently.ref;
/**
* @author takahashikzn
* @version $Id$
*/
@SuppressWarnings("ComparableImplementedButEqualsNotOverridden")
public class $bool
extends AbstractRef<Boolean, $bool>
implements Comparable<$bool>, BooleanSupplier {
private static final long serialVersionUID = 8087914133902951131L;
/** the value. */
@SuppressWarnings("PublicField")
public boolean $; // NOPMD
/**
* constructor.
*/
protected $bool() { this(false); }
/**
* constructor.
*
* @param $ the value.
*/
protected $bool(final boolean $) { this.$ = $; }
@Override
public void accept(final Boolean $) { this.$ = $; }
/**
* set value then return this instance.
*
* @param $ value
* @return {@code this}
*/
public $bool set(final boolean $) {
this.$ = $;
return this;
}
@Override
public Boolean get() { return this.$; }
@Override
public boolean getAsBoolean() { return this.$; }
@Override
public int compareTo(final $bool that) { return this.compareTo(that.$); }
public int compareTo(final boolean that) { return Boolean.compare(this.$, that); }
/**
* execute the procedure then negate the value if and only if the condition satisfied.
*
* @param cond condition
* @param f a procedure
*/ | // Path: src/main/java/jp/root42/indolently/function/Statement.java
// @FunctionalInterface
// public interface Statement
// extends Runnable {
//
// Statement NOP = () -> {};
//
// /**
// * Perform this operation.
// *
// * @throws Exception any exception which this statement would throw
// */
// void exec() throws Exception;
//
// /**
// * Perform this operation.
// */
// @Override
// default void run() {
// try {
// this.exec();
// } catch (final Exception e) {
// Expressive.raise(e);
// }
// }
//
// /**
// * Returns composed statement which execute this statement then execute {@code after}.
// *
// * @param after statement which execute after this statement
// * @return composed statement
// */
// default Statement andThen(final Statement after) {
//
// Objects.requireNonNull(after);
//
// return () -> {
// this.run();
// after.run();
// };
// }
// }
// Path: src/main/java/jp/root42/indolently/ref/$bool.java
import java.util.function.Predicate;
import jp.root42.indolently.function.Statement;
import java.util.function.BooleanSupplier;
// Copyright 2014 takahashikzn
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package jp.root42.indolently.ref;
/**
* @author takahashikzn
* @version $Id$
*/
@SuppressWarnings("ComparableImplementedButEqualsNotOverridden")
public class $bool
extends AbstractRef<Boolean, $bool>
implements Comparable<$bool>, BooleanSupplier {
private static final long serialVersionUID = 8087914133902951131L;
/** the value. */
@SuppressWarnings("PublicField")
public boolean $; // NOPMD
/**
* constructor.
*/
protected $bool() { this(false); }
/**
* constructor.
*
* @param $ the value.
*/
protected $bool(final boolean $) { this.$ = $; }
@Override
public void accept(final Boolean $) { this.$ = $; }
/**
* set value then return this instance.
*
* @param $ value
* @return {@code this}
*/
public $bool set(final boolean $) {
this.$ = $;
return this;
}
@Override
public Boolean get() { return this.$; }
@Override
public boolean getAsBoolean() { return this.$; }
@Override
public int compareTo(final $bool that) { return this.compareTo(that.$); }
public int compareTo(final boolean that) { return Boolean.compare(this.$, that); }
/**
* execute the procedure then negate the value if and only if the condition satisfied.
*
* @param cond condition
* @param f a procedure
*/ | public void negateIf(final boolean cond, final Statement f) { this.negateIf(x -> x == cond, f); } |
xyxyLiu/PluginM | testhost/src/main/java/com/example/testhost/MyHostInvoker.java | // Path: PluginApi/src/main/java/com/reginald/pluginm/pluginapi/IInvokeCallback.java
// public interface IInvokeCallback {
// /**
// * 函数回调
// * @param params 回调参数
// * @return 回调结果 {@link com.reginald.pluginm.pluginapi.IInvokeResult}
// */
// IInvokeResult onCallback(String params);
// }
//
// Path: PluginApi/src/main/java/com/reginald/pluginm/pluginapi/IInvokeResult.java
// public interface IInvokeResult {
// /**
// * 函数调用结果成功
// */
// int RESULT_OK = 1;
// /**
// * 函数调用结果失败,未找到目标IInvoker
// */
// int RESULT_NOT_FOUND = -1;
// /**
// * 函数调用结果失败,远端服务进程死亡
// */
// int RESULT_REMOTE_ERROR = -2;
// /**
// * 函数调用结果失败,非法或不支持的参数
// */
// int RESULT_INVOKE_INVALID = -10;
// /**
// * 函数调用结果失败,内部错误
// */
// int RESULT_INVOKE_ERROR = -11;
//
// /**
// * 获取调用返回码
// * @return 返回码
// */
// int getResultCode();
//
// /**
// * 获取调用结果,当{@link IInvokeResult#getResultCode()} 为 {@link IInvokeResult#RESULT_OK} 时才有意义。
// * @return 调用结果
// */
// String getResult();
//
// IInvokeResult INVOKERESULT_VOID_OK = new IInvokeResult() {
// @Override
// public int getResultCode() {
// return RESULT_OK;
// }
//
// @Override
// public String getResult() {
// return null;
// }
// };
// }
//
// Path: PluginApi/src/main/java/com/reginald/pluginm/pluginapi/IInvoker.java
// public interface IInvoker {
// /**
// * 提供此IInvoker对外提供的Binder服务
// * @param context
// * @return Binder服务
// */
// IBinder onServiceCreate(Context context);
//
// /**
// * 处理此IInvoker上的函数调用
// * @param context
// * @param methodName 函数名称
// * @param params 函数参数(建议使用json等结构化数据格式)
// * @param callback 回调 {@link IInvokeCallback}
// * @return 结果 {@link IInvokeResult} 不要返回null。
// */
// IInvokeResult onInvoke(Context context, String methodName, String params, IInvokeCallback callback);
// }
| import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import com.reginald.pluginm.demo.pluginsharelib.ITestServiceBinder;
import com.reginald.pluginm.pluginapi.IInvokeCallback;
import com.reginald.pluginm.pluginapi.IInvokeResult;
import com.reginald.pluginm.pluginapi.IInvoker; | package com.example.testhost;
/**
* Created by lxy on 17-9-21.
*/
public class MyHostInvoker implements IInvoker {
private static final String TAG = "MyHostInvoker";
private static final String METHOD_START_MAIN = "start_host_main";
@Override
public IBinder onServiceCreate(final Context context) {
Log.d(TAG, "onServiceCreate()");
return new ITestServiceBinder.Stub() {
@Override
public void test(String url) throws RemoteException {
Log.d(TAG, "BINDER test() url = " + url);
}
};
}
@Override | // Path: PluginApi/src/main/java/com/reginald/pluginm/pluginapi/IInvokeCallback.java
// public interface IInvokeCallback {
// /**
// * 函数回调
// * @param params 回调参数
// * @return 回调结果 {@link com.reginald.pluginm.pluginapi.IInvokeResult}
// */
// IInvokeResult onCallback(String params);
// }
//
// Path: PluginApi/src/main/java/com/reginald/pluginm/pluginapi/IInvokeResult.java
// public interface IInvokeResult {
// /**
// * 函数调用结果成功
// */
// int RESULT_OK = 1;
// /**
// * 函数调用结果失败,未找到目标IInvoker
// */
// int RESULT_NOT_FOUND = -1;
// /**
// * 函数调用结果失败,远端服务进程死亡
// */
// int RESULT_REMOTE_ERROR = -2;
// /**
// * 函数调用结果失败,非法或不支持的参数
// */
// int RESULT_INVOKE_INVALID = -10;
// /**
// * 函数调用结果失败,内部错误
// */
// int RESULT_INVOKE_ERROR = -11;
//
// /**
// * 获取调用返回码
// * @return 返回码
// */
// int getResultCode();
//
// /**
// * 获取调用结果,当{@link IInvokeResult#getResultCode()} 为 {@link IInvokeResult#RESULT_OK} 时才有意义。
// * @return 调用结果
// */
// String getResult();
//
// IInvokeResult INVOKERESULT_VOID_OK = new IInvokeResult() {
// @Override
// public int getResultCode() {
// return RESULT_OK;
// }
//
// @Override
// public String getResult() {
// return null;
// }
// };
// }
//
// Path: PluginApi/src/main/java/com/reginald/pluginm/pluginapi/IInvoker.java
// public interface IInvoker {
// /**
// * 提供此IInvoker对外提供的Binder服务
// * @param context
// * @return Binder服务
// */
// IBinder onServiceCreate(Context context);
//
// /**
// * 处理此IInvoker上的函数调用
// * @param context
// * @param methodName 函数名称
// * @param params 函数参数(建议使用json等结构化数据格式)
// * @param callback 回调 {@link IInvokeCallback}
// * @return 结果 {@link IInvokeResult} 不要返回null。
// */
// IInvokeResult onInvoke(Context context, String methodName, String params, IInvokeCallback callback);
// }
// Path: testhost/src/main/java/com/example/testhost/MyHostInvoker.java
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import com.reginald.pluginm.demo.pluginsharelib.ITestServiceBinder;
import com.reginald.pluginm.pluginapi.IInvokeCallback;
import com.reginald.pluginm.pluginapi.IInvokeResult;
import com.reginald.pluginm.pluginapi.IInvoker;
package com.example.testhost;
/**
* Created by lxy on 17-9-21.
*/
public class MyHostInvoker implements IInvoker {
private static final String TAG = "MyHostInvoker";
private static final String METHOD_START_MAIN = "start_host_main";
@Override
public IBinder onServiceCreate(final Context context) {
Log.d(TAG, "onServiceCreate()");
return new ITestServiceBinder.Stub() {
@Override
public void test(String url) throws RemoteException {
Log.d(TAG, "BINDER test() url = " + url);
}
};
}
@Override | public IInvokeResult onInvoke(Context context, String methodName, String params, IInvokeCallback callback) { |
xyxyLiu/PluginM | testhost/src/main/java/com/example/testhost/MyHostInvoker.java | // Path: PluginApi/src/main/java/com/reginald/pluginm/pluginapi/IInvokeCallback.java
// public interface IInvokeCallback {
// /**
// * 函数回调
// * @param params 回调参数
// * @return 回调结果 {@link com.reginald.pluginm.pluginapi.IInvokeResult}
// */
// IInvokeResult onCallback(String params);
// }
//
// Path: PluginApi/src/main/java/com/reginald/pluginm/pluginapi/IInvokeResult.java
// public interface IInvokeResult {
// /**
// * 函数调用结果成功
// */
// int RESULT_OK = 1;
// /**
// * 函数调用结果失败,未找到目标IInvoker
// */
// int RESULT_NOT_FOUND = -1;
// /**
// * 函数调用结果失败,远端服务进程死亡
// */
// int RESULT_REMOTE_ERROR = -2;
// /**
// * 函数调用结果失败,非法或不支持的参数
// */
// int RESULT_INVOKE_INVALID = -10;
// /**
// * 函数调用结果失败,内部错误
// */
// int RESULT_INVOKE_ERROR = -11;
//
// /**
// * 获取调用返回码
// * @return 返回码
// */
// int getResultCode();
//
// /**
// * 获取调用结果,当{@link IInvokeResult#getResultCode()} 为 {@link IInvokeResult#RESULT_OK} 时才有意义。
// * @return 调用结果
// */
// String getResult();
//
// IInvokeResult INVOKERESULT_VOID_OK = new IInvokeResult() {
// @Override
// public int getResultCode() {
// return RESULT_OK;
// }
//
// @Override
// public String getResult() {
// return null;
// }
// };
// }
//
// Path: PluginApi/src/main/java/com/reginald/pluginm/pluginapi/IInvoker.java
// public interface IInvoker {
// /**
// * 提供此IInvoker对外提供的Binder服务
// * @param context
// * @return Binder服务
// */
// IBinder onServiceCreate(Context context);
//
// /**
// * 处理此IInvoker上的函数调用
// * @param context
// * @param methodName 函数名称
// * @param params 函数参数(建议使用json等结构化数据格式)
// * @param callback 回调 {@link IInvokeCallback}
// * @return 结果 {@link IInvokeResult} 不要返回null。
// */
// IInvokeResult onInvoke(Context context, String methodName, String params, IInvokeCallback callback);
// }
| import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import com.reginald.pluginm.demo.pluginsharelib.ITestServiceBinder;
import com.reginald.pluginm.pluginapi.IInvokeCallback;
import com.reginald.pluginm.pluginapi.IInvokeResult;
import com.reginald.pluginm.pluginapi.IInvoker; | package com.example.testhost;
/**
* Created by lxy on 17-9-21.
*/
public class MyHostInvoker implements IInvoker {
private static final String TAG = "MyHostInvoker";
private static final String METHOD_START_MAIN = "start_host_main";
@Override
public IBinder onServiceCreate(final Context context) {
Log.d(TAG, "onServiceCreate()");
return new ITestServiceBinder.Stub() {
@Override
public void test(String url) throws RemoteException {
Log.d(TAG, "BINDER test() url = " + url);
}
};
}
@Override | // Path: PluginApi/src/main/java/com/reginald/pluginm/pluginapi/IInvokeCallback.java
// public interface IInvokeCallback {
// /**
// * 函数回调
// * @param params 回调参数
// * @return 回调结果 {@link com.reginald.pluginm.pluginapi.IInvokeResult}
// */
// IInvokeResult onCallback(String params);
// }
//
// Path: PluginApi/src/main/java/com/reginald/pluginm/pluginapi/IInvokeResult.java
// public interface IInvokeResult {
// /**
// * 函数调用结果成功
// */
// int RESULT_OK = 1;
// /**
// * 函数调用结果失败,未找到目标IInvoker
// */
// int RESULT_NOT_FOUND = -1;
// /**
// * 函数调用结果失败,远端服务进程死亡
// */
// int RESULT_REMOTE_ERROR = -2;
// /**
// * 函数调用结果失败,非法或不支持的参数
// */
// int RESULT_INVOKE_INVALID = -10;
// /**
// * 函数调用结果失败,内部错误
// */
// int RESULT_INVOKE_ERROR = -11;
//
// /**
// * 获取调用返回码
// * @return 返回码
// */
// int getResultCode();
//
// /**
// * 获取调用结果,当{@link IInvokeResult#getResultCode()} 为 {@link IInvokeResult#RESULT_OK} 时才有意义。
// * @return 调用结果
// */
// String getResult();
//
// IInvokeResult INVOKERESULT_VOID_OK = new IInvokeResult() {
// @Override
// public int getResultCode() {
// return RESULT_OK;
// }
//
// @Override
// public String getResult() {
// return null;
// }
// };
// }
//
// Path: PluginApi/src/main/java/com/reginald/pluginm/pluginapi/IInvoker.java
// public interface IInvoker {
// /**
// * 提供此IInvoker对外提供的Binder服务
// * @param context
// * @return Binder服务
// */
// IBinder onServiceCreate(Context context);
//
// /**
// * 处理此IInvoker上的函数调用
// * @param context
// * @param methodName 函数名称
// * @param params 函数参数(建议使用json等结构化数据格式)
// * @param callback 回调 {@link IInvokeCallback}
// * @return 结果 {@link IInvokeResult} 不要返回null。
// */
// IInvokeResult onInvoke(Context context, String methodName, String params, IInvokeCallback callback);
// }
// Path: testhost/src/main/java/com/example/testhost/MyHostInvoker.java
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import com.reginald.pluginm.demo.pluginsharelib.ITestServiceBinder;
import com.reginald.pluginm.pluginapi.IInvokeCallback;
import com.reginald.pluginm.pluginapi.IInvokeResult;
import com.reginald.pluginm.pluginapi.IInvoker;
package com.example.testhost;
/**
* Created by lxy on 17-9-21.
*/
public class MyHostInvoker implements IInvoker {
private static final String TAG = "MyHostInvoker";
private static final String METHOD_START_MAIN = "start_host_main";
@Override
public IBinder onServiceCreate(final Context context) {
Log.d(TAG, "onServiceCreate()");
return new ITestServiceBinder.Stub() {
@Override
public void test(String url) throws RemoteException {
Log.d(TAG, "BINDER test() url = " + url);
}
};
}
@Override | public IInvokeResult onInvoke(Context context, String methodName, String params, IInvokeCallback callback) { |
xyxyLiu/PluginM | testplugin/src/main/java/com/example/testplugin/MyPluginInvoker.java | // Path: pluginsharelib/src/main/java/com/reginald/pluginm/demo/pluginsharelib/PluginItem.java
// public class PluginItem implements Parcelable{
// public String pluginName;
// public int id;
//
// public PluginItem(String name, int id) {
// this.pluginName = name;
// this.id = id;
// }
//
// protected PluginItem(Parcel in) {
// pluginName = in.readString();
// id = in.readInt();
// }
//
// public static final Creator<PluginItem> CREATOR = new Creator<PluginItem>() {
// @Override
// public PluginItem createFromParcel(Parcel in) {
// return new PluginItem(in);
// }
//
// @Override
// public PluginItem[] newArray(int size) {
// return new PluginItem[size];
// }
// };
//
// public String toString() {
// return String.format("PluginItem[ pluginName = %s, id = %d ]", pluginName, id);
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(Parcel dest, int flags) {
// dest.writeString(pluginName);
// dest.writeInt(id);
// }
// }
//
// Path: PluginApi/src/main/java/com/reginald/pluginm/pluginapi/IInvokeCallback.java
// public interface IInvokeCallback {
// /**
// * 函数回调
// * @param params 回调参数
// * @return 回调结果 {@link com.reginald.pluginm.pluginapi.IInvokeResult}
// */
// IInvokeResult onCallback(String params);
// }
//
// Path: PluginApi/src/main/java/com/reginald/pluginm/pluginapi/IInvokeResult.java
// public interface IInvokeResult {
// /**
// * 函数调用结果成功
// */
// int RESULT_OK = 1;
// /**
// * 函数调用结果失败,未找到目标IInvoker
// */
// int RESULT_NOT_FOUND = -1;
// /**
// * 函数调用结果失败,远端服务进程死亡
// */
// int RESULT_REMOTE_ERROR = -2;
// /**
// * 函数调用结果失败,非法或不支持的参数
// */
// int RESULT_INVOKE_INVALID = -10;
// /**
// * 函数调用结果失败,内部错误
// */
// int RESULT_INVOKE_ERROR = -11;
//
// /**
// * 获取调用返回码
// * @return 返回码
// */
// int getResultCode();
//
// /**
// * 获取调用结果,当{@link IInvokeResult#getResultCode()} 为 {@link IInvokeResult#RESULT_OK} 时才有意义。
// * @return 调用结果
// */
// String getResult();
//
// IInvokeResult INVOKERESULT_VOID_OK = new IInvokeResult() {
// @Override
// public int getResultCode() {
// return RESULT_OK;
// }
//
// @Override
// public String getResult() {
// return null;
// }
// };
// }
//
// Path: PluginApi/src/main/java/com/reginald/pluginm/pluginapi/IInvoker.java
// public interface IInvoker {
// /**
// * 提供此IInvoker对外提供的Binder服务
// * @param context
// * @return Binder服务
// */
// IBinder onServiceCreate(Context context);
//
// /**
// * 处理此IInvoker上的函数调用
// * @param context
// * @param methodName 函数名称
// * @param params 函数参数(建议使用json等结构化数据格式)
// * @param callback 回调 {@link IInvokeCallback}
// * @return 结果 {@link IInvokeResult} 不要返回null。
// */
// IInvokeResult onInvoke(Context context, String methodName, String params, IInvokeCallback callback);
// }
| import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import com.reginald.pluginm.demo.pluginsharelib.ITestPluginBinder;
import com.reginald.pluginm.demo.pluginsharelib.PluginItem;
import com.reginald.pluginm.pluginapi.IInvokeCallback;
import com.reginald.pluginm.pluginapi.IInvokeResult;
import com.reginald.pluginm.pluginapi.IInvoker; | package com.example.testplugin;
/**
* Created by lxy on 17-9-20.
*/
public class MyPluginInvoker implements IInvoker {
private static final String TAG = "MyPluginInvoker";
private static final String METHOD_START_MAIN = "start_main";
private IBinder myBinder = new ITestPluginBinder.Stub() {
@Override | // Path: pluginsharelib/src/main/java/com/reginald/pluginm/demo/pluginsharelib/PluginItem.java
// public class PluginItem implements Parcelable{
// public String pluginName;
// public int id;
//
// public PluginItem(String name, int id) {
// this.pluginName = name;
// this.id = id;
// }
//
// protected PluginItem(Parcel in) {
// pluginName = in.readString();
// id = in.readInt();
// }
//
// public static final Creator<PluginItem> CREATOR = new Creator<PluginItem>() {
// @Override
// public PluginItem createFromParcel(Parcel in) {
// return new PluginItem(in);
// }
//
// @Override
// public PluginItem[] newArray(int size) {
// return new PluginItem[size];
// }
// };
//
// public String toString() {
// return String.format("PluginItem[ pluginName = %s, id = %d ]", pluginName, id);
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(Parcel dest, int flags) {
// dest.writeString(pluginName);
// dest.writeInt(id);
// }
// }
//
// Path: PluginApi/src/main/java/com/reginald/pluginm/pluginapi/IInvokeCallback.java
// public interface IInvokeCallback {
// /**
// * 函数回调
// * @param params 回调参数
// * @return 回调结果 {@link com.reginald.pluginm.pluginapi.IInvokeResult}
// */
// IInvokeResult onCallback(String params);
// }
//
// Path: PluginApi/src/main/java/com/reginald/pluginm/pluginapi/IInvokeResult.java
// public interface IInvokeResult {
// /**
// * 函数调用结果成功
// */
// int RESULT_OK = 1;
// /**
// * 函数调用结果失败,未找到目标IInvoker
// */
// int RESULT_NOT_FOUND = -1;
// /**
// * 函数调用结果失败,远端服务进程死亡
// */
// int RESULT_REMOTE_ERROR = -2;
// /**
// * 函数调用结果失败,非法或不支持的参数
// */
// int RESULT_INVOKE_INVALID = -10;
// /**
// * 函数调用结果失败,内部错误
// */
// int RESULT_INVOKE_ERROR = -11;
//
// /**
// * 获取调用返回码
// * @return 返回码
// */
// int getResultCode();
//
// /**
// * 获取调用结果,当{@link IInvokeResult#getResultCode()} 为 {@link IInvokeResult#RESULT_OK} 时才有意义。
// * @return 调用结果
// */
// String getResult();
//
// IInvokeResult INVOKERESULT_VOID_OK = new IInvokeResult() {
// @Override
// public int getResultCode() {
// return RESULT_OK;
// }
//
// @Override
// public String getResult() {
// return null;
// }
// };
// }
//
// Path: PluginApi/src/main/java/com/reginald/pluginm/pluginapi/IInvoker.java
// public interface IInvoker {
// /**
// * 提供此IInvoker对外提供的Binder服务
// * @param context
// * @return Binder服务
// */
// IBinder onServiceCreate(Context context);
//
// /**
// * 处理此IInvoker上的函数调用
// * @param context
// * @param methodName 函数名称
// * @param params 函数参数(建议使用json等结构化数据格式)
// * @param callback 回调 {@link IInvokeCallback}
// * @return 结果 {@link IInvokeResult} 不要返回null。
// */
// IInvokeResult onInvoke(Context context, String methodName, String params, IInvokeCallback callback);
// }
// Path: testplugin/src/main/java/com/example/testplugin/MyPluginInvoker.java
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import com.reginald.pluginm.demo.pluginsharelib.ITestPluginBinder;
import com.reginald.pluginm.demo.pluginsharelib.PluginItem;
import com.reginald.pluginm.pluginapi.IInvokeCallback;
import com.reginald.pluginm.pluginapi.IInvokeResult;
import com.reginald.pluginm.pluginapi.IInvoker;
package com.example.testplugin;
/**
* Created by lxy on 17-9-20.
*/
public class MyPluginInvoker implements IInvoker {
private static final String TAG = "MyPluginInvoker";
private static final String METHOD_START_MAIN = "start_main";
private IBinder myBinder = new ITestPluginBinder.Stub() {
@Override | public String basicTypes(PluginItem pluginItem) throws RemoteException { |
xyxyLiu/PluginM | testplugin/src/main/java/com/example/testplugin/MyPluginInvoker.java | // Path: pluginsharelib/src/main/java/com/reginald/pluginm/demo/pluginsharelib/PluginItem.java
// public class PluginItem implements Parcelable{
// public String pluginName;
// public int id;
//
// public PluginItem(String name, int id) {
// this.pluginName = name;
// this.id = id;
// }
//
// protected PluginItem(Parcel in) {
// pluginName = in.readString();
// id = in.readInt();
// }
//
// public static final Creator<PluginItem> CREATOR = new Creator<PluginItem>() {
// @Override
// public PluginItem createFromParcel(Parcel in) {
// return new PluginItem(in);
// }
//
// @Override
// public PluginItem[] newArray(int size) {
// return new PluginItem[size];
// }
// };
//
// public String toString() {
// return String.format("PluginItem[ pluginName = %s, id = %d ]", pluginName, id);
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(Parcel dest, int flags) {
// dest.writeString(pluginName);
// dest.writeInt(id);
// }
// }
//
// Path: PluginApi/src/main/java/com/reginald/pluginm/pluginapi/IInvokeCallback.java
// public interface IInvokeCallback {
// /**
// * 函数回调
// * @param params 回调参数
// * @return 回调结果 {@link com.reginald.pluginm.pluginapi.IInvokeResult}
// */
// IInvokeResult onCallback(String params);
// }
//
// Path: PluginApi/src/main/java/com/reginald/pluginm/pluginapi/IInvokeResult.java
// public interface IInvokeResult {
// /**
// * 函数调用结果成功
// */
// int RESULT_OK = 1;
// /**
// * 函数调用结果失败,未找到目标IInvoker
// */
// int RESULT_NOT_FOUND = -1;
// /**
// * 函数调用结果失败,远端服务进程死亡
// */
// int RESULT_REMOTE_ERROR = -2;
// /**
// * 函数调用结果失败,非法或不支持的参数
// */
// int RESULT_INVOKE_INVALID = -10;
// /**
// * 函数调用结果失败,内部错误
// */
// int RESULT_INVOKE_ERROR = -11;
//
// /**
// * 获取调用返回码
// * @return 返回码
// */
// int getResultCode();
//
// /**
// * 获取调用结果,当{@link IInvokeResult#getResultCode()} 为 {@link IInvokeResult#RESULT_OK} 时才有意义。
// * @return 调用结果
// */
// String getResult();
//
// IInvokeResult INVOKERESULT_VOID_OK = new IInvokeResult() {
// @Override
// public int getResultCode() {
// return RESULT_OK;
// }
//
// @Override
// public String getResult() {
// return null;
// }
// };
// }
//
// Path: PluginApi/src/main/java/com/reginald/pluginm/pluginapi/IInvoker.java
// public interface IInvoker {
// /**
// * 提供此IInvoker对外提供的Binder服务
// * @param context
// * @return Binder服务
// */
// IBinder onServiceCreate(Context context);
//
// /**
// * 处理此IInvoker上的函数调用
// * @param context
// * @param methodName 函数名称
// * @param params 函数参数(建议使用json等结构化数据格式)
// * @param callback 回调 {@link IInvokeCallback}
// * @return 结果 {@link IInvokeResult} 不要返回null。
// */
// IInvokeResult onInvoke(Context context, String methodName, String params, IInvokeCallback callback);
// }
| import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import com.reginald.pluginm.demo.pluginsharelib.ITestPluginBinder;
import com.reginald.pluginm.demo.pluginsharelib.PluginItem;
import com.reginald.pluginm.pluginapi.IInvokeCallback;
import com.reginald.pluginm.pluginapi.IInvokeResult;
import com.reginald.pluginm.pluginapi.IInvoker; | package com.example.testplugin;
/**
* Created by lxy on 17-9-20.
*/
public class MyPluginInvoker implements IInvoker {
private static final String TAG = "MyPluginInvoker";
private static final String METHOD_START_MAIN = "start_main";
private IBinder myBinder = new ITestPluginBinder.Stub() {
@Override
public String basicTypes(PluginItem pluginItem) throws RemoteException {
Log.d(TAG, "BINDER basicTypes() pluginItem = " + pluginItem);
return "I'm a binder from plugintest!";
}
};
@Override
public IBinder onServiceCreate(Context context) {
return myBinder;
}
@Override | // Path: pluginsharelib/src/main/java/com/reginald/pluginm/demo/pluginsharelib/PluginItem.java
// public class PluginItem implements Parcelable{
// public String pluginName;
// public int id;
//
// public PluginItem(String name, int id) {
// this.pluginName = name;
// this.id = id;
// }
//
// protected PluginItem(Parcel in) {
// pluginName = in.readString();
// id = in.readInt();
// }
//
// public static final Creator<PluginItem> CREATOR = new Creator<PluginItem>() {
// @Override
// public PluginItem createFromParcel(Parcel in) {
// return new PluginItem(in);
// }
//
// @Override
// public PluginItem[] newArray(int size) {
// return new PluginItem[size];
// }
// };
//
// public String toString() {
// return String.format("PluginItem[ pluginName = %s, id = %d ]", pluginName, id);
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(Parcel dest, int flags) {
// dest.writeString(pluginName);
// dest.writeInt(id);
// }
// }
//
// Path: PluginApi/src/main/java/com/reginald/pluginm/pluginapi/IInvokeCallback.java
// public interface IInvokeCallback {
// /**
// * 函数回调
// * @param params 回调参数
// * @return 回调结果 {@link com.reginald.pluginm.pluginapi.IInvokeResult}
// */
// IInvokeResult onCallback(String params);
// }
//
// Path: PluginApi/src/main/java/com/reginald/pluginm/pluginapi/IInvokeResult.java
// public interface IInvokeResult {
// /**
// * 函数调用结果成功
// */
// int RESULT_OK = 1;
// /**
// * 函数调用结果失败,未找到目标IInvoker
// */
// int RESULT_NOT_FOUND = -1;
// /**
// * 函数调用结果失败,远端服务进程死亡
// */
// int RESULT_REMOTE_ERROR = -2;
// /**
// * 函数调用结果失败,非法或不支持的参数
// */
// int RESULT_INVOKE_INVALID = -10;
// /**
// * 函数调用结果失败,内部错误
// */
// int RESULT_INVOKE_ERROR = -11;
//
// /**
// * 获取调用返回码
// * @return 返回码
// */
// int getResultCode();
//
// /**
// * 获取调用结果,当{@link IInvokeResult#getResultCode()} 为 {@link IInvokeResult#RESULT_OK} 时才有意义。
// * @return 调用结果
// */
// String getResult();
//
// IInvokeResult INVOKERESULT_VOID_OK = new IInvokeResult() {
// @Override
// public int getResultCode() {
// return RESULT_OK;
// }
//
// @Override
// public String getResult() {
// return null;
// }
// };
// }
//
// Path: PluginApi/src/main/java/com/reginald/pluginm/pluginapi/IInvoker.java
// public interface IInvoker {
// /**
// * 提供此IInvoker对外提供的Binder服务
// * @param context
// * @return Binder服务
// */
// IBinder onServiceCreate(Context context);
//
// /**
// * 处理此IInvoker上的函数调用
// * @param context
// * @param methodName 函数名称
// * @param params 函数参数(建议使用json等结构化数据格式)
// * @param callback 回调 {@link IInvokeCallback}
// * @return 结果 {@link IInvokeResult} 不要返回null。
// */
// IInvokeResult onInvoke(Context context, String methodName, String params, IInvokeCallback callback);
// }
// Path: testplugin/src/main/java/com/example/testplugin/MyPluginInvoker.java
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import com.reginald.pluginm.demo.pluginsharelib.ITestPluginBinder;
import com.reginald.pluginm.demo.pluginsharelib.PluginItem;
import com.reginald.pluginm.pluginapi.IInvokeCallback;
import com.reginald.pluginm.pluginapi.IInvokeResult;
import com.reginald.pluginm.pluginapi.IInvoker;
package com.example.testplugin;
/**
* Created by lxy on 17-9-20.
*/
public class MyPluginInvoker implements IInvoker {
private static final String TAG = "MyPluginInvoker";
private static final String METHOD_START_MAIN = "start_main";
private IBinder myBinder = new ITestPluginBinder.Stub() {
@Override
public String basicTypes(PluginItem pluginItem) throws RemoteException {
Log.d(TAG, "BINDER basicTypes() pluginItem = " + pluginItem);
return "I'm a binder from plugintest!";
}
};
@Override
public IBinder onServiceCreate(Context context) {
return myBinder;
}
@Override | public IInvokeResult onInvoke(Context context, String methodName, String params, IInvokeCallback callback) { |
xyxyLiu/PluginM | testplugin/src/main/java/com/example/testplugin/MyPluginInvoker.java | // Path: pluginsharelib/src/main/java/com/reginald/pluginm/demo/pluginsharelib/PluginItem.java
// public class PluginItem implements Parcelable{
// public String pluginName;
// public int id;
//
// public PluginItem(String name, int id) {
// this.pluginName = name;
// this.id = id;
// }
//
// protected PluginItem(Parcel in) {
// pluginName = in.readString();
// id = in.readInt();
// }
//
// public static final Creator<PluginItem> CREATOR = new Creator<PluginItem>() {
// @Override
// public PluginItem createFromParcel(Parcel in) {
// return new PluginItem(in);
// }
//
// @Override
// public PluginItem[] newArray(int size) {
// return new PluginItem[size];
// }
// };
//
// public String toString() {
// return String.format("PluginItem[ pluginName = %s, id = %d ]", pluginName, id);
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(Parcel dest, int flags) {
// dest.writeString(pluginName);
// dest.writeInt(id);
// }
// }
//
// Path: PluginApi/src/main/java/com/reginald/pluginm/pluginapi/IInvokeCallback.java
// public interface IInvokeCallback {
// /**
// * 函数回调
// * @param params 回调参数
// * @return 回调结果 {@link com.reginald.pluginm.pluginapi.IInvokeResult}
// */
// IInvokeResult onCallback(String params);
// }
//
// Path: PluginApi/src/main/java/com/reginald/pluginm/pluginapi/IInvokeResult.java
// public interface IInvokeResult {
// /**
// * 函数调用结果成功
// */
// int RESULT_OK = 1;
// /**
// * 函数调用结果失败,未找到目标IInvoker
// */
// int RESULT_NOT_FOUND = -1;
// /**
// * 函数调用结果失败,远端服务进程死亡
// */
// int RESULT_REMOTE_ERROR = -2;
// /**
// * 函数调用结果失败,非法或不支持的参数
// */
// int RESULT_INVOKE_INVALID = -10;
// /**
// * 函数调用结果失败,内部错误
// */
// int RESULT_INVOKE_ERROR = -11;
//
// /**
// * 获取调用返回码
// * @return 返回码
// */
// int getResultCode();
//
// /**
// * 获取调用结果,当{@link IInvokeResult#getResultCode()} 为 {@link IInvokeResult#RESULT_OK} 时才有意义。
// * @return 调用结果
// */
// String getResult();
//
// IInvokeResult INVOKERESULT_VOID_OK = new IInvokeResult() {
// @Override
// public int getResultCode() {
// return RESULT_OK;
// }
//
// @Override
// public String getResult() {
// return null;
// }
// };
// }
//
// Path: PluginApi/src/main/java/com/reginald/pluginm/pluginapi/IInvoker.java
// public interface IInvoker {
// /**
// * 提供此IInvoker对外提供的Binder服务
// * @param context
// * @return Binder服务
// */
// IBinder onServiceCreate(Context context);
//
// /**
// * 处理此IInvoker上的函数调用
// * @param context
// * @param methodName 函数名称
// * @param params 函数参数(建议使用json等结构化数据格式)
// * @param callback 回调 {@link IInvokeCallback}
// * @return 结果 {@link IInvokeResult} 不要返回null。
// */
// IInvokeResult onInvoke(Context context, String methodName, String params, IInvokeCallback callback);
// }
| import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import com.reginald.pluginm.demo.pluginsharelib.ITestPluginBinder;
import com.reginald.pluginm.demo.pluginsharelib.PluginItem;
import com.reginald.pluginm.pluginapi.IInvokeCallback;
import com.reginald.pluginm.pluginapi.IInvokeResult;
import com.reginald.pluginm.pluginapi.IInvoker; | package com.example.testplugin;
/**
* Created by lxy on 17-9-20.
*/
public class MyPluginInvoker implements IInvoker {
private static final String TAG = "MyPluginInvoker";
private static final String METHOD_START_MAIN = "start_main";
private IBinder myBinder = new ITestPluginBinder.Stub() {
@Override
public String basicTypes(PluginItem pluginItem) throws RemoteException {
Log.d(TAG, "BINDER basicTypes() pluginItem = " + pluginItem);
return "I'm a binder from plugintest!";
}
};
@Override
public IBinder onServiceCreate(Context context) {
return myBinder;
}
@Override | // Path: pluginsharelib/src/main/java/com/reginald/pluginm/demo/pluginsharelib/PluginItem.java
// public class PluginItem implements Parcelable{
// public String pluginName;
// public int id;
//
// public PluginItem(String name, int id) {
// this.pluginName = name;
// this.id = id;
// }
//
// protected PluginItem(Parcel in) {
// pluginName = in.readString();
// id = in.readInt();
// }
//
// public static final Creator<PluginItem> CREATOR = new Creator<PluginItem>() {
// @Override
// public PluginItem createFromParcel(Parcel in) {
// return new PluginItem(in);
// }
//
// @Override
// public PluginItem[] newArray(int size) {
// return new PluginItem[size];
// }
// };
//
// public String toString() {
// return String.format("PluginItem[ pluginName = %s, id = %d ]", pluginName, id);
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(Parcel dest, int flags) {
// dest.writeString(pluginName);
// dest.writeInt(id);
// }
// }
//
// Path: PluginApi/src/main/java/com/reginald/pluginm/pluginapi/IInvokeCallback.java
// public interface IInvokeCallback {
// /**
// * 函数回调
// * @param params 回调参数
// * @return 回调结果 {@link com.reginald.pluginm.pluginapi.IInvokeResult}
// */
// IInvokeResult onCallback(String params);
// }
//
// Path: PluginApi/src/main/java/com/reginald/pluginm/pluginapi/IInvokeResult.java
// public interface IInvokeResult {
// /**
// * 函数调用结果成功
// */
// int RESULT_OK = 1;
// /**
// * 函数调用结果失败,未找到目标IInvoker
// */
// int RESULT_NOT_FOUND = -1;
// /**
// * 函数调用结果失败,远端服务进程死亡
// */
// int RESULT_REMOTE_ERROR = -2;
// /**
// * 函数调用结果失败,非法或不支持的参数
// */
// int RESULT_INVOKE_INVALID = -10;
// /**
// * 函数调用结果失败,内部错误
// */
// int RESULT_INVOKE_ERROR = -11;
//
// /**
// * 获取调用返回码
// * @return 返回码
// */
// int getResultCode();
//
// /**
// * 获取调用结果,当{@link IInvokeResult#getResultCode()} 为 {@link IInvokeResult#RESULT_OK} 时才有意义。
// * @return 调用结果
// */
// String getResult();
//
// IInvokeResult INVOKERESULT_VOID_OK = new IInvokeResult() {
// @Override
// public int getResultCode() {
// return RESULT_OK;
// }
//
// @Override
// public String getResult() {
// return null;
// }
// };
// }
//
// Path: PluginApi/src/main/java/com/reginald/pluginm/pluginapi/IInvoker.java
// public interface IInvoker {
// /**
// * 提供此IInvoker对外提供的Binder服务
// * @param context
// * @return Binder服务
// */
// IBinder onServiceCreate(Context context);
//
// /**
// * 处理此IInvoker上的函数调用
// * @param context
// * @param methodName 函数名称
// * @param params 函数参数(建议使用json等结构化数据格式)
// * @param callback 回调 {@link IInvokeCallback}
// * @return 结果 {@link IInvokeResult} 不要返回null。
// */
// IInvokeResult onInvoke(Context context, String methodName, String params, IInvokeCallback callback);
// }
// Path: testplugin/src/main/java/com/example/testplugin/MyPluginInvoker.java
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import com.reginald.pluginm.demo.pluginsharelib.ITestPluginBinder;
import com.reginald.pluginm.demo.pluginsharelib.PluginItem;
import com.reginald.pluginm.pluginapi.IInvokeCallback;
import com.reginald.pluginm.pluginapi.IInvokeResult;
import com.reginald.pluginm.pluginapi.IInvoker;
package com.example.testplugin;
/**
* Created by lxy on 17-9-20.
*/
public class MyPluginInvoker implements IInvoker {
private static final String TAG = "MyPluginInvoker";
private static final String METHOD_START_MAIN = "start_main";
private IBinder myBinder = new ITestPluginBinder.Stub() {
@Override
public String basicTypes(PluginItem pluginItem) throws RemoteException {
Log.d(TAG, "BINDER basicTypes() pluginItem = " + pluginItem);
return "I'm a binder from plugintest!";
}
};
@Override
public IBinder onServiceCreate(Context context) {
return myBinder;
}
@Override | public IInvokeResult onInvoke(Context context, String methodName, String params, IInvokeCallback callback) { |
xyxyLiu/PluginM | PluginManager/src/main/java/com/reginald/pluginm/reflect/MethodUtils.java | // Path: PluginManager/src/main/java/com/reginald/pluginm/utils/Logger.java
// public class Logger {
// public static final String TAG = "PluginM";
// public static boolean LOG_ENABLED = BuildConfig.DEBUG_LOG;
// public static boolean ALWAYS_SHOW_ERROR = true;
//
// public static void d(String tag, String msg) {
// if (LOG_ENABLED) {
// Log.d(TAG, getLogMsg(tag, msg));
// }
// }
//
// public static void d(String tag, String formatMsg, Object... args) {
// if (LOG_ENABLED) {
// d(tag, String.format(formatMsg, args));
// }
// }
//
// public static void i(String tag, String msg) {
// if (LOG_ENABLED) {
// Log.i(TAG, getLogMsg(tag, msg));
// }
// }
//
// public static void i(String tag, String formatMsg, Object... args) {
// if (LOG_ENABLED) {
// i(tag, String.format(formatMsg, args));
// }
// }
//
// public static void w(String tag, String msg) {
// if (LOG_ENABLED) {
// Log.w(TAG, getLogMsg(tag, msg));
// }
// }
//
// public static void w(String tag, String formatMsg, Object... args) {
// if (LOG_ENABLED) {
// w(tag, String.format(formatMsg, args));
// }
// }
//
// public static void w(String tag, String msg, Throwable e) {
// if (LOG_ENABLED) {
// Log.w(TAG, getLogMsg(tag, msg + " Exception: " + getExceptionMsg(e)));
// }
// }
//
// public static void w(String tag, Throwable e, String formatMsg, Object... args) {
// if (LOG_ENABLED) {
// w(tag, String.format(formatMsg, args), e);
// }
// }
//
// public static void e(String tag, String msg) {
// if (LOG_ENABLED || ALWAYS_SHOW_ERROR) {
// Log.e(TAG, getLogMsg(tag, msg));
// }
// }
//
// public static void e(String tag, String formatMsg, Object... args) {
// if (LOG_ENABLED || ALWAYS_SHOW_ERROR) {
// e(tag, String.format(formatMsg, args));
// }
// }
//
// public static void e(String tag, String msg, Throwable e) {
// if (LOG_ENABLED || ALWAYS_SHOW_ERROR) {
// Log.e(TAG, getLogMsg(tag, msg + " Exception: " + getExceptionMsg(e)));
// }
// }
//
// public static void e(String tag, Throwable e, String formatMsg, Object... args) {
// if (LOG_ENABLED || ALWAYS_SHOW_ERROR) {
// e(tag, String.format(formatMsg, args), e);
// }
// }
//
// private static String getLogMsg(String subTag, String msg) {
// return "[" + subTag + "] " + msg;
// }
//
// private static String getExceptionMsg(Throwable e) {
// StringWriter sw = new StringWriter(1024);
// PrintWriter pw = new PrintWriter(sw);
// e.printStackTrace(pw);
// pw.close();
// return sw.toString();
// }
// }
| import java.util.Map;
import com.reginald.pluginm.utils.Logger;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.HashMap; | synchronized (sMethodCache) {
sMethodCache.put(key, bestMatch);
}
return bestMatch;
}
public static Object invokeMethod(final Object object, final String methodName,
Object[] args, Class<?>[] parameterTypes)
throws NoSuchMethodException, IllegalAccessException,
InvocationTargetException {
parameterTypes = Utils.nullToEmpty(parameterTypes);
args = Utils.nullToEmpty(args);
final Method method = getMatchingAccessibleMethod(object.getClass(),
methodName, parameterTypes);
if (method == null) {
throw new NoSuchMethodException("No such accessible method: "
+ methodName + "() on object: "
+ object.getClass().getName());
}
return method.invoke(object, args);
}
public static Object invokeMethodNoThrow(final Object object, final String methodName,
Object[] args, Class<?>[] parameterTypes) {
parameterTypes = Utils.nullToEmpty(parameterTypes);
args = Utils.nullToEmpty(args);
final Method method = getMatchingAccessibleMethod(object.getClass(),
methodName, parameterTypes);
if (method == null) { | // Path: PluginManager/src/main/java/com/reginald/pluginm/utils/Logger.java
// public class Logger {
// public static final String TAG = "PluginM";
// public static boolean LOG_ENABLED = BuildConfig.DEBUG_LOG;
// public static boolean ALWAYS_SHOW_ERROR = true;
//
// public static void d(String tag, String msg) {
// if (LOG_ENABLED) {
// Log.d(TAG, getLogMsg(tag, msg));
// }
// }
//
// public static void d(String tag, String formatMsg, Object... args) {
// if (LOG_ENABLED) {
// d(tag, String.format(formatMsg, args));
// }
// }
//
// public static void i(String tag, String msg) {
// if (LOG_ENABLED) {
// Log.i(TAG, getLogMsg(tag, msg));
// }
// }
//
// public static void i(String tag, String formatMsg, Object... args) {
// if (LOG_ENABLED) {
// i(tag, String.format(formatMsg, args));
// }
// }
//
// public static void w(String tag, String msg) {
// if (LOG_ENABLED) {
// Log.w(TAG, getLogMsg(tag, msg));
// }
// }
//
// public static void w(String tag, String formatMsg, Object... args) {
// if (LOG_ENABLED) {
// w(tag, String.format(formatMsg, args));
// }
// }
//
// public static void w(String tag, String msg, Throwable e) {
// if (LOG_ENABLED) {
// Log.w(TAG, getLogMsg(tag, msg + " Exception: " + getExceptionMsg(e)));
// }
// }
//
// public static void w(String tag, Throwable e, String formatMsg, Object... args) {
// if (LOG_ENABLED) {
// w(tag, String.format(formatMsg, args), e);
// }
// }
//
// public static void e(String tag, String msg) {
// if (LOG_ENABLED || ALWAYS_SHOW_ERROR) {
// Log.e(TAG, getLogMsg(tag, msg));
// }
// }
//
// public static void e(String tag, String formatMsg, Object... args) {
// if (LOG_ENABLED || ALWAYS_SHOW_ERROR) {
// e(tag, String.format(formatMsg, args));
// }
// }
//
// public static void e(String tag, String msg, Throwable e) {
// if (LOG_ENABLED || ALWAYS_SHOW_ERROR) {
// Log.e(TAG, getLogMsg(tag, msg + " Exception: " + getExceptionMsg(e)));
// }
// }
//
// public static void e(String tag, Throwable e, String formatMsg, Object... args) {
// if (LOG_ENABLED || ALWAYS_SHOW_ERROR) {
// e(tag, String.format(formatMsg, args), e);
// }
// }
//
// private static String getLogMsg(String subTag, String msg) {
// return "[" + subTag + "] " + msg;
// }
//
// private static String getExceptionMsg(Throwable e) {
// StringWriter sw = new StringWriter(1024);
// PrintWriter pw = new PrintWriter(sw);
// e.printStackTrace(pw);
// pw.close();
// return sw.toString();
// }
// }
// Path: PluginManager/src/main/java/com/reginald/pluginm/reflect/MethodUtils.java
import java.util.Map;
import com.reginald.pluginm.utils.Logger;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.HashMap;
synchronized (sMethodCache) {
sMethodCache.put(key, bestMatch);
}
return bestMatch;
}
public static Object invokeMethod(final Object object, final String methodName,
Object[] args, Class<?>[] parameterTypes)
throws NoSuchMethodException, IllegalAccessException,
InvocationTargetException {
parameterTypes = Utils.nullToEmpty(parameterTypes);
args = Utils.nullToEmpty(args);
final Method method = getMatchingAccessibleMethod(object.getClass(),
methodName, parameterTypes);
if (method == null) {
throw new NoSuchMethodException("No such accessible method: "
+ methodName + "() on object: "
+ object.getClass().getName());
}
return method.invoke(object, args);
}
public static Object invokeMethodNoThrow(final Object object, final String methodName,
Object[] args, Class<?>[] parameterTypes) {
parameterTypes = Utils.nullToEmpty(parameterTypes);
args = Utils.nullToEmpty(args);
final Method method = getMatchingAccessibleMethod(object.getClass(),
methodName, parameterTypes);
if (method == null) { | Logger.e(TAG, "invokeMethodNoThrow() method NOT found: " + methodName); |
xyxyLiu/PluginM | PluginManager/src/main/java/com/reginald/pluginm/parser/PackageParser.java | // Path: PluginManager/src/main/java/com/android/common/SystemPropertiesCompat.java
// public class SystemPropertiesCompat {
//
// private static Class<?> sClass;
//
// private static Class getMyClass() throws ClassNotFoundException {
// if (sClass == null) {
// sClass = Class.forName("android.os.SystemProperties");
// }
// return sClass;
// }
//
// private static String getInner(String key, String defaultValue) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, ClassNotFoundException {
// Class clazz = getMyClass();
// return (String) MethodUtils.invokeStaticMethod(clazz, "get", key, defaultValue);
// }
//
// public static String get(String key, String defaultValue) {
// try {
// return getInner(key, defaultValue);
// } catch (Exception e) {
// return defaultValue;
// }
// }
// }
| import android.content.pm.ProviderInfo;
import android.content.pm.ServiceInfo;
import android.content.pm.Signature;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import com.android.common.SystemPropertiesCompat;
import java.io.File;
import java.util.HashSet;
import java.util.List;
import android.content.Context;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.pm.ApplicationInfo;
import android.content.pm.InstrumentationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PermissionGroupInfo;
import android.content.pm.PermissionInfo; | /*
** DroidPlugin Project
**
** Copyright(c) 2015 Andy Zhang <zhangyong232@gmail.com>
**
** This file is part of DroidPlugin.
**
** DroidPlugin is free software: you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License as published by the Free Software Foundation, either
** version 3 of the License, or (at your option) any later version.
**
** DroidPlugin is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
** Lesser General Public License for more details.
**
** You should have received a copy of the GNU Lesser General Public
** License along with DroidPlugin. If not, see <http://www.gnu.org/licenses/lgpl.txt>
**
**/
package com.reginald.pluginm.parser;
/**
* Created by Andy Zhang(zhangyong232@gmail.com) on 2015/2/13.
*/
abstract class PackageParser {
protected Context mContext;
protected Object mPackageParser;
PackageParser(Context context) {
mContext = context;
}
public final static int PARSE_IS_SYSTEM = 1 << 0;
public final static int PARSE_CHATTY = 1 << 1;
public final static int PARSE_MUST_BE_APK = 1 << 2;
public final static int PARSE_IGNORE_PROCESSES = 1 << 3;
public final static int PARSE_FORWARD_LOCK = 1 << 4;
public final static int PARSE_ON_SDCARD = 1 << 5;
public final static int PARSE_IS_SYSTEM_DIR = 1 << 6;
public final static int PARSE_IS_PRIVILEGED = 1 << 7;
public final static int PARSE_COLLECT_CERTIFICATES = 1 << 8;
public final static int PARSE_TRUSTED_OVERLAY = 1 << 9;
public static PackageParser newPluginParser(Context context) throws Exception {
if (VERSION.SDK_INT >= VERSION_CODES.P) {
return new PackageParserApi28(context);
} else if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP_MR1) { | // Path: PluginManager/src/main/java/com/android/common/SystemPropertiesCompat.java
// public class SystemPropertiesCompat {
//
// private static Class<?> sClass;
//
// private static Class getMyClass() throws ClassNotFoundException {
// if (sClass == null) {
// sClass = Class.forName("android.os.SystemProperties");
// }
// return sClass;
// }
//
// private static String getInner(String key, String defaultValue) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, ClassNotFoundException {
// Class clazz = getMyClass();
// return (String) MethodUtils.invokeStaticMethod(clazz, "get", key, defaultValue);
// }
//
// public static String get(String key, String defaultValue) {
// try {
// return getInner(key, defaultValue);
// } catch (Exception e) {
// return defaultValue;
// }
// }
// }
// Path: PluginManager/src/main/java/com/reginald/pluginm/parser/PackageParser.java
import android.content.pm.ProviderInfo;
import android.content.pm.ServiceInfo;
import android.content.pm.Signature;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import com.android.common.SystemPropertiesCompat;
import java.io.File;
import java.util.HashSet;
import java.util.List;
import android.content.Context;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.pm.ApplicationInfo;
import android.content.pm.InstrumentationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PermissionGroupInfo;
import android.content.pm.PermissionInfo;
/*
** DroidPlugin Project
**
** Copyright(c) 2015 Andy Zhang <zhangyong232@gmail.com>
**
** This file is part of DroidPlugin.
**
** DroidPlugin is free software: you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License as published by the Free Software Foundation, either
** version 3 of the License, or (at your option) any later version.
**
** DroidPlugin is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
** Lesser General Public License for more details.
**
** You should have received a copy of the GNU Lesser General Public
** License along with DroidPlugin. If not, see <http://www.gnu.org/licenses/lgpl.txt>
**
**/
package com.reginald.pluginm.parser;
/**
* Created by Andy Zhang(zhangyong232@gmail.com) on 2015/2/13.
*/
abstract class PackageParser {
protected Context mContext;
protected Object mPackageParser;
PackageParser(Context context) {
mContext = context;
}
public final static int PARSE_IS_SYSTEM = 1 << 0;
public final static int PARSE_CHATTY = 1 << 1;
public final static int PARSE_MUST_BE_APK = 1 << 2;
public final static int PARSE_IGNORE_PROCESSES = 1 << 3;
public final static int PARSE_FORWARD_LOCK = 1 << 4;
public final static int PARSE_ON_SDCARD = 1 << 5;
public final static int PARSE_IS_SYSTEM_DIR = 1 << 6;
public final static int PARSE_IS_PRIVILEGED = 1 << 7;
public final static int PARSE_COLLECT_CERTIFICATES = 1 << 8;
public final static int PARSE_TRUSTED_OVERLAY = 1 << 9;
public static PackageParser newPluginParser(Context context) throws Exception {
if (VERSION.SDK_INT >= VERSION_CODES.P) {
return new PackageParserApi28(context);
} else if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP_MR1) { | if ("1".equals(SystemPropertiesCompat.get("ro.build.version.preview_sdk", ""))) { |
xyxyLiu/PluginM | PluginManager/src/main/java/com/android/common/ContextCompat.java | // Path: PluginManager/src/main/java/com/reginald/pluginm/utils/Logger.java
// public class Logger {
// public static final String TAG = "PluginM";
// public static boolean LOG_ENABLED = BuildConfig.DEBUG_LOG;
// public static boolean ALWAYS_SHOW_ERROR = true;
//
// public static void d(String tag, String msg) {
// if (LOG_ENABLED) {
// Log.d(TAG, getLogMsg(tag, msg));
// }
// }
//
// public static void d(String tag, String formatMsg, Object... args) {
// if (LOG_ENABLED) {
// d(tag, String.format(formatMsg, args));
// }
// }
//
// public static void i(String tag, String msg) {
// if (LOG_ENABLED) {
// Log.i(TAG, getLogMsg(tag, msg));
// }
// }
//
// public static void i(String tag, String formatMsg, Object... args) {
// if (LOG_ENABLED) {
// i(tag, String.format(formatMsg, args));
// }
// }
//
// public static void w(String tag, String msg) {
// if (LOG_ENABLED) {
// Log.w(TAG, getLogMsg(tag, msg));
// }
// }
//
// public static void w(String tag, String formatMsg, Object... args) {
// if (LOG_ENABLED) {
// w(tag, String.format(formatMsg, args));
// }
// }
//
// public static void w(String tag, String msg, Throwable e) {
// if (LOG_ENABLED) {
// Log.w(TAG, getLogMsg(tag, msg + " Exception: " + getExceptionMsg(e)));
// }
// }
//
// public static void w(String tag, Throwable e, String formatMsg, Object... args) {
// if (LOG_ENABLED) {
// w(tag, String.format(formatMsg, args), e);
// }
// }
//
// public static void e(String tag, String msg) {
// if (LOG_ENABLED || ALWAYS_SHOW_ERROR) {
// Log.e(TAG, getLogMsg(tag, msg));
// }
// }
//
// public static void e(String tag, String formatMsg, Object... args) {
// if (LOG_ENABLED || ALWAYS_SHOW_ERROR) {
// e(tag, String.format(formatMsg, args));
// }
// }
//
// public static void e(String tag, String msg, Throwable e) {
// if (LOG_ENABLED || ALWAYS_SHOW_ERROR) {
// Log.e(TAG, getLogMsg(tag, msg + " Exception: " + getExceptionMsg(e)));
// }
// }
//
// public static void e(String tag, Throwable e, String formatMsg, Object... args) {
// if (LOG_ENABLED || ALWAYS_SHOW_ERROR) {
// e(tag, String.format(formatMsg, args), e);
// }
// }
//
// private static String getLogMsg(String subTag, String msg) {
// return "[" + subTag + "] " + msg;
// }
//
// private static String getExceptionMsg(Throwable e) {
// StringWriter sw = new StringWriter(1024);
// PrintWriter pw = new PrintWriter(sw);
// e.printStackTrace(pw);
// pw.close();
// return sw.toString();
// }
// }
| import android.content.Context;
import android.content.ContextWrapper;
import com.reginald.pluginm.utils.Logger;
import java.lang.reflect.Method; | package com.android.common;
@SuppressWarnings("NewApi")
public class ContextCompat {
private final static String TAG = "ContextCompat";
private final static boolean DEBUG = true;
private static Class<?> sClassContextImpl;
private static Method sMethodSetOuterContext;
static {
ClassLoader classLoader = ClassLoader.getSystemClassLoader();
try {
sClassContextImpl = classLoader.loadClass("android.app.ContextImpl");
sMethodSetOuterContext = sClassContextImpl.getDeclaredMethod("setOuterContext", Context.class);
sMethodSetOuterContext.setAccessible(true);
} catch (Exception e) {
sClassContextImpl = null;
sMethodSetOuterContext = null;
}
}
public static void setOuterContext(Context context, Context outerContext) {
if (sMethodSetOuterContext != null) {
while (!sClassContextImpl.isInstance(context)) {
if (context instanceof ContextWrapper) {
context = ((ContextWrapper) context).getBaseContext();
} else { | // Path: PluginManager/src/main/java/com/reginald/pluginm/utils/Logger.java
// public class Logger {
// public static final String TAG = "PluginM";
// public static boolean LOG_ENABLED = BuildConfig.DEBUG_LOG;
// public static boolean ALWAYS_SHOW_ERROR = true;
//
// public static void d(String tag, String msg) {
// if (LOG_ENABLED) {
// Log.d(TAG, getLogMsg(tag, msg));
// }
// }
//
// public static void d(String tag, String formatMsg, Object... args) {
// if (LOG_ENABLED) {
// d(tag, String.format(formatMsg, args));
// }
// }
//
// public static void i(String tag, String msg) {
// if (LOG_ENABLED) {
// Log.i(TAG, getLogMsg(tag, msg));
// }
// }
//
// public static void i(String tag, String formatMsg, Object... args) {
// if (LOG_ENABLED) {
// i(tag, String.format(formatMsg, args));
// }
// }
//
// public static void w(String tag, String msg) {
// if (LOG_ENABLED) {
// Log.w(TAG, getLogMsg(tag, msg));
// }
// }
//
// public static void w(String tag, String formatMsg, Object... args) {
// if (LOG_ENABLED) {
// w(tag, String.format(formatMsg, args));
// }
// }
//
// public static void w(String tag, String msg, Throwable e) {
// if (LOG_ENABLED) {
// Log.w(TAG, getLogMsg(tag, msg + " Exception: " + getExceptionMsg(e)));
// }
// }
//
// public static void w(String tag, Throwable e, String formatMsg, Object... args) {
// if (LOG_ENABLED) {
// w(tag, String.format(formatMsg, args), e);
// }
// }
//
// public static void e(String tag, String msg) {
// if (LOG_ENABLED || ALWAYS_SHOW_ERROR) {
// Log.e(TAG, getLogMsg(tag, msg));
// }
// }
//
// public static void e(String tag, String formatMsg, Object... args) {
// if (LOG_ENABLED || ALWAYS_SHOW_ERROR) {
// e(tag, String.format(formatMsg, args));
// }
// }
//
// public static void e(String tag, String msg, Throwable e) {
// if (LOG_ENABLED || ALWAYS_SHOW_ERROR) {
// Log.e(TAG, getLogMsg(tag, msg + " Exception: " + getExceptionMsg(e)));
// }
// }
//
// public static void e(String tag, Throwable e, String formatMsg, Object... args) {
// if (LOG_ENABLED || ALWAYS_SHOW_ERROR) {
// e(tag, String.format(formatMsg, args), e);
// }
// }
//
// private static String getLogMsg(String subTag, String msg) {
// return "[" + subTag + "] " + msg;
// }
//
// private static String getExceptionMsg(Throwable e) {
// StringWriter sw = new StringWriter(1024);
// PrintWriter pw = new PrintWriter(sw);
// e.printStackTrace(pw);
// pw.close();
// return sw.toString();
// }
// }
// Path: PluginManager/src/main/java/com/android/common/ContextCompat.java
import android.content.Context;
import android.content.ContextWrapper;
import com.reginald.pluginm.utils.Logger;
import java.lang.reflect.Method;
package com.android.common;
@SuppressWarnings("NewApi")
public class ContextCompat {
private final static String TAG = "ContextCompat";
private final static boolean DEBUG = true;
private static Class<?> sClassContextImpl;
private static Method sMethodSetOuterContext;
static {
ClassLoader classLoader = ClassLoader.getSystemClassLoader();
try {
sClassContextImpl = classLoader.loadClass("android.app.ContextImpl");
sMethodSetOuterContext = sClassContextImpl.getDeclaredMethod("setOuterContext", Context.class);
sMethodSetOuterContext.setAccessible(true);
} catch (Exception e) {
sClassContextImpl = null;
sMethodSetOuterContext = null;
}
}
public static void setOuterContext(Context context, Context outerContext) {
if (sMethodSetOuterContext != null) {
while (!sClassContextImpl.isInstance(context)) {
if (context instanceof ContextWrapper) {
context = ((ContextWrapper) context).getBaseContext();
} else { | Logger.e(TAG, "setOuterContext error context=" + context); |
xyxyLiu/PluginM | PluginManager/src/main/java/com/reginald/pluginm/comm/invoker/InvokeResult.java | // Path: PluginApi/src/main/java/com/reginald/pluginm/pluginapi/IInvokeResult.java
// public interface IInvokeResult {
// /**
// * 函数调用结果成功
// */
// int RESULT_OK = 1;
// /**
// * 函数调用结果失败,未找到目标IInvoker
// */
// int RESULT_NOT_FOUND = -1;
// /**
// * 函数调用结果失败,远端服务进程死亡
// */
// int RESULT_REMOTE_ERROR = -2;
// /**
// * 函数调用结果失败,非法或不支持的参数
// */
// int RESULT_INVOKE_INVALID = -10;
// /**
// * 函数调用结果失败,内部错误
// */
// int RESULT_INVOKE_ERROR = -11;
//
// /**
// * 获取调用返回码
// * @return 返回码
// */
// int getResultCode();
//
// /**
// * 获取调用结果,当{@link IInvokeResult#getResultCode()} 为 {@link IInvokeResult#RESULT_OK} 时才有意义。
// * @return 调用结果
// */
// String getResult();
//
// IInvokeResult INVOKERESULT_VOID_OK = new IInvokeResult() {
// @Override
// public int getResultCode() {
// return RESULT_OK;
// }
//
// @Override
// public String getResult() {
// return null;
// }
// };
// }
| import android.os.Parcel;
import android.os.Parcelable;
import com.reginald.pluginm.pluginapi.IInvokeResult; | package com.reginald.pluginm.comm.invoker;
/**
* Created by lxy on 17-9-19.
*/
public class InvokeResult implements Parcelable {
private int mResultCode;
private String mResult;
public InvokeResult(int resultCode, String result) {
mResultCode = resultCode;
mResult = result;
}
| // Path: PluginApi/src/main/java/com/reginald/pluginm/pluginapi/IInvokeResult.java
// public interface IInvokeResult {
// /**
// * 函数调用结果成功
// */
// int RESULT_OK = 1;
// /**
// * 函数调用结果失败,未找到目标IInvoker
// */
// int RESULT_NOT_FOUND = -1;
// /**
// * 函数调用结果失败,远端服务进程死亡
// */
// int RESULT_REMOTE_ERROR = -2;
// /**
// * 函数调用结果失败,非法或不支持的参数
// */
// int RESULT_INVOKE_INVALID = -10;
// /**
// * 函数调用结果失败,内部错误
// */
// int RESULT_INVOKE_ERROR = -11;
//
// /**
// * 获取调用返回码
// * @return 返回码
// */
// int getResultCode();
//
// /**
// * 获取调用结果,当{@link IInvokeResult#getResultCode()} 为 {@link IInvokeResult#RESULT_OK} 时才有意义。
// * @return 调用结果
// */
// String getResult();
//
// IInvokeResult INVOKERESULT_VOID_OK = new IInvokeResult() {
// @Override
// public int getResultCode() {
// return RESULT_OK;
// }
//
// @Override
// public String getResult() {
// return null;
// }
// };
// }
// Path: PluginManager/src/main/java/com/reginald/pluginm/comm/invoker/InvokeResult.java
import android.os.Parcel;
import android.os.Parcelable;
import com.reginald.pluginm.pluginapi.IInvokeResult;
package com.reginald.pluginm.comm.invoker;
/**
* Created by lxy on 17-9-19.
*/
public class InvokeResult implements Parcelable {
private int mResultCode;
private String mResult;
public InvokeResult(int resultCode, String result) {
mResultCode = resultCode;
mResult = result;
}
| private InvokeResult(IInvokeResult iInvokeResult) { |
xyxyLiu/PluginM | PluginManager/src/main/java/com/reginald/pluginm/stub/PluginServiceConnection.java | // Path: PluginManager/src/main/java/com/reginald/pluginm/utils/Logger.java
// public class Logger {
// public static final String TAG = "PluginM";
// public static boolean LOG_ENABLED = BuildConfig.DEBUG_LOG;
// public static boolean ALWAYS_SHOW_ERROR = true;
//
// public static void d(String tag, String msg) {
// if (LOG_ENABLED) {
// Log.d(TAG, getLogMsg(tag, msg));
// }
// }
//
// public static void d(String tag, String formatMsg, Object... args) {
// if (LOG_ENABLED) {
// d(tag, String.format(formatMsg, args));
// }
// }
//
// public static void i(String tag, String msg) {
// if (LOG_ENABLED) {
// Log.i(TAG, getLogMsg(tag, msg));
// }
// }
//
// public static void i(String tag, String formatMsg, Object... args) {
// if (LOG_ENABLED) {
// i(tag, String.format(formatMsg, args));
// }
// }
//
// public static void w(String tag, String msg) {
// if (LOG_ENABLED) {
// Log.w(TAG, getLogMsg(tag, msg));
// }
// }
//
// public static void w(String tag, String formatMsg, Object... args) {
// if (LOG_ENABLED) {
// w(tag, String.format(formatMsg, args));
// }
// }
//
// public static void w(String tag, String msg, Throwable e) {
// if (LOG_ENABLED) {
// Log.w(TAG, getLogMsg(tag, msg + " Exception: " + getExceptionMsg(e)));
// }
// }
//
// public static void w(String tag, Throwable e, String formatMsg, Object... args) {
// if (LOG_ENABLED) {
// w(tag, String.format(formatMsg, args), e);
// }
// }
//
// public static void e(String tag, String msg) {
// if (LOG_ENABLED || ALWAYS_SHOW_ERROR) {
// Log.e(TAG, getLogMsg(tag, msg));
// }
// }
//
// public static void e(String tag, String formatMsg, Object... args) {
// if (LOG_ENABLED || ALWAYS_SHOW_ERROR) {
// e(tag, String.format(formatMsg, args));
// }
// }
//
// public static void e(String tag, String msg, Throwable e) {
// if (LOG_ENABLED || ALWAYS_SHOW_ERROR) {
// Log.e(TAG, getLogMsg(tag, msg + " Exception: " + getExceptionMsg(e)));
// }
// }
//
// public static void e(String tag, Throwable e, String formatMsg, Object... args) {
// if (LOG_ENABLED || ALWAYS_SHOW_ERROR) {
// e(tag, String.format(formatMsg, args), e);
// }
// }
//
// private static String getLogMsg(String subTag, String msg) {
// return "[" + subTag + "] " + msg;
// }
//
// private static String getExceptionMsg(Throwable e) {
// StringWriter sw = new StringWriter(1024);
// PrintWriter pw = new PrintWriter(sw);
// e.printStackTrace(pw);
// pw.close();
// return sw.toString();
// }
// }
| import android.content.ComponentName;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;
import com.reginald.pluginm.utils.Logger;
import java.util.HashMap;
import java.util.WeakHashMap; | package com.reginald.pluginm.stub;
/**
* Created by lxy on 16-7-1.
*/
public class PluginServiceConnection implements ServiceConnection {
private static final String TAG = "PluginServiceConnection";
private static WeakHashMap<ServiceConnection, PluginServiceConnection> sConnectionMap = new WeakHashMap<>();
private HashMap<ComponentName, ConnectionInfo> mBinderMap = new HashMap<>();
private ServiceConnection mBase;
public PluginServiceConnection(ServiceConnection serviceConnection) {
mBase = serviceConnection;
}
public static PluginServiceConnection getConnection(ServiceConnection conn) {
synchronized (sConnectionMap) {
PluginServiceConnection pluginConn = sConnectionMap.get(conn); | // Path: PluginManager/src/main/java/com/reginald/pluginm/utils/Logger.java
// public class Logger {
// public static final String TAG = "PluginM";
// public static boolean LOG_ENABLED = BuildConfig.DEBUG_LOG;
// public static boolean ALWAYS_SHOW_ERROR = true;
//
// public static void d(String tag, String msg) {
// if (LOG_ENABLED) {
// Log.d(TAG, getLogMsg(tag, msg));
// }
// }
//
// public static void d(String tag, String formatMsg, Object... args) {
// if (LOG_ENABLED) {
// d(tag, String.format(formatMsg, args));
// }
// }
//
// public static void i(String tag, String msg) {
// if (LOG_ENABLED) {
// Log.i(TAG, getLogMsg(tag, msg));
// }
// }
//
// public static void i(String tag, String formatMsg, Object... args) {
// if (LOG_ENABLED) {
// i(tag, String.format(formatMsg, args));
// }
// }
//
// public static void w(String tag, String msg) {
// if (LOG_ENABLED) {
// Log.w(TAG, getLogMsg(tag, msg));
// }
// }
//
// public static void w(String tag, String formatMsg, Object... args) {
// if (LOG_ENABLED) {
// w(tag, String.format(formatMsg, args));
// }
// }
//
// public static void w(String tag, String msg, Throwable e) {
// if (LOG_ENABLED) {
// Log.w(TAG, getLogMsg(tag, msg + " Exception: " + getExceptionMsg(e)));
// }
// }
//
// public static void w(String tag, Throwable e, String formatMsg, Object... args) {
// if (LOG_ENABLED) {
// w(tag, String.format(formatMsg, args), e);
// }
// }
//
// public static void e(String tag, String msg) {
// if (LOG_ENABLED || ALWAYS_SHOW_ERROR) {
// Log.e(TAG, getLogMsg(tag, msg));
// }
// }
//
// public static void e(String tag, String formatMsg, Object... args) {
// if (LOG_ENABLED || ALWAYS_SHOW_ERROR) {
// e(tag, String.format(formatMsg, args));
// }
// }
//
// public static void e(String tag, String msg, Throwable e) {
// if (LOG_ENABLED || ALWAYS_SHOW_ERROR) {
// Log.e(TAG, getLogMsg(tag, msg + " Exception: " + getExceptionMsg(e)));
// }
// }
//
// public static void e(String tag, Throwable e, String formatMsg, Object... args) {
// if (LOG_ENABLED || ALWAYS_SHOW_ERROR) {
// e(tag, String.format(formatMsg, args), e);
// }
// }
//
// private static String getLogMsg(String subTag, String msg) {
// return "[" + subTag + "] " + msg;
// }
//
// private static String getExceptionMsg(Throwable e) {
// StringWriter sw = new StringWriter(1024);
// PrintWriter pw = new PrintWriter(sw);
// e.printStackTrace(pw);
// pw.close();
// return sw.toString();
// }
// }
// Path: PluginManager/src/main/java/com/reginald/pluginm/stub/PluginServiceConnection.java
import android.content.ComponentName;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;
import com.reginald.pluginm.utils.Logger;
import java.util.HashMap;
import java.util.WeakHashMap;
package com.reginald.pluginm.stub;
/**
* Created by lxy on 16-7-1.
*/
public class PluginServiceConnection implements ServiceConnection {
private static final String TAG = "PluginServiceConnection";
private static WeakHashMap<ServiceConnection, PluginServiceConnection> sConnectionMap = new WeakHashMap<>();
private HashMap<ComponentName, ConnectionInfo> mBinderMap = new HashMap<>();
private ServiceConnection mBase;
public PluginServiceConnection(ServiceConnection serviceConnection) {
mBase = serviceConnection;
}
public static PluginServiceConnection getConnection(ServiceConnection conn) {
synchronized (sConnectionMap) {
PluginServiceConnection pluginConn = sConnectionMap.get(conn); | Logger.d(TAG, String.format("getConnection(%s) return %s", conn, pluginConn)); |
xyxyLiu/PluginM | PluginManager/src/main/java/com/reginald/pluginm/hook/ServiceHook.java | // Path: PluginManager/src/main/java/com/reginald/pluginm/utils/Logger.java
// public class Logger {
// public static final String TAG = "PluginM";
// public static boolean LOG_ENABLED = BuildConfig.DEBUG_LOG;
// public static boolean ALWAYS_SHOW_ERROR = true;
//
// public static void d(String tag, String msg) {
// if (LOG_ENABLED) {
// Log.d(TAG, getLogMsg(tag, msg));
// }
// }
//
// public static void d(String tag, String formatMsg, Object... args) {
// if (LOG_ENABLED) {
// d(tag, String.format(formatMsg, args));
// }
// }
//
// public static void i(String tag, String msg) {
// if (LOG_ENABLED) {
// Log.i(TAG, getLogMsg(tag, msg));
// }
// }
//
// public static void i(String tag, String formatMsg, Object... args) {
// if (LOG_ENABLED) {
// i(tag, String.format(formatMsg, args));
// }
// }
//
// public static void w(String tag, String msg) {
// if (LOG_ENABLED) {
// Log.w(TAG, getLogMsg(tag, msg));
// }
// }
//
// public static void w(String tag, String formatMsg, Object... args) {
// if (LOG_ENABLED) {
// w(tag, String.format(formatMsg, args));
// }
// }
//
// public static void w(String tag, String msg, Throwable e) {
// if (LOG_ENABLED) {
// Log.w(TAG, getLogMsg(tag, msg + " Exception: " + getExceptionMsg(e)));
// }
// }
//
// public static void w(String tag, Throwable e, String formatMsg, Object... args) {
// if (LOG_ENABLED) {
// w(tag, String.format(formatMsg, args), e);
// }
// }
//
// public static void e(String tag, String msg) {
// if (LOG_ENABLED || ALWAYS_SHOW_ERROR) {
// Log.e(TAG, getLogMsg(tag, msg));
// }
// }
//
// public static void e(String tag, String formatMsg, Object... args) {
// if (LOG_ENABLED || ALWAYS_SHOW_ERROR) {
// e(tag, String.format(formatMsg, args));
// }
// }
//
// public static void e(String tag, String msg, Throwable e) {
// if (LOG_ENABLED || ALWAYS_SHOW_ERROR) {
// Log.e(TAG, getLogMsg(tag, msg + " Exception: " + getExceptionMsg(e)));
// }
// }
//
// public static void e(String tag, Throwable e, String formatMsg, Object... args) {
// if (LOG_ENABLED || ALWAYS_SHOW_ERROR) {
// e(tag, String.format(formatMsg, args), e);
// }
// }
//
// private static String getLogMsg(String subTag, String msg) {
// return "[" + subTag + "] " + msg;
// }
//
// private static String getExceptionMsg(Throwable e) {
// StringWriter sw = new StringWriter(1024);
// PrintWriter pw = new PrintWriter(sw);
// e.printStackTrace(pw);
// pw.close();
// return sw.toString();
// }
// }
| import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import com.reginald.pluginm.utils.Logger;
import android.os.SystemClock; | package com.reginald.pluginm.hook;
/**
* Created by lxy on 17-8-16.
*/
public abstract class ServiceHook implements InvocationHandler {
private static final String TAG = "ServiceHook";
private static final boolean HOOK_LOG = true;
protected Object mBase;
protected final Map<String, MethodHandler> mMethodHandlers = new HashMap<String, MethodHandler>(2);
protected MethodHandler mAllMethodHandler;
/**
* 1. replace the host object(mBase) with the new one(Hook)
* 2. init MethodHandlers
* @return
*/
public abstract boolean install();
protected void addMethodHandler(MethodHandler methodHandler) { | // Path: PluginManager/src/main/java/com/reginald/pluginm/utils/Logger.java
// public class Logger {
// public static final String TAG = "PluginM";
// public static boolean LOG_ENABLED = BuildConfig.DEBUG_LOG;
// public static boolean ALWAYS_SHOW_ERROR = true;
//
// public static void d(String tag, String msg) {
// if (LOG_ENABLED) {
// Log.d(TAG, getLogMsg(tag, msg));
// }
// }
//
// public static void d(String tag, String formatMsg, Object... args) {
// if (LOG_ENABLED) {
// d(tag, String.format(formatMsg, args));
// }
// }
//
// public static void i(String tag, String msg) {
// if (LOG_ENABLED) {
// Log.i(TAG, getLogMsg(tag, msg));
// }
// }
//
// public static void i(String tag, String formatMsg, Object... args) {
// if (LOG_ENABLED) {
// i(tag, String.format(formatMsg, args));
// }
// }
//
// public static void w(String tag, String msg) {
// if (LOG_ENABLED) {
// Log.w(TAG, getLogMsg(tag, msg));
// }
// }
//
// public static void w(String tag, String formatMsg, Object... args) {
// if (LOG_ENABLED) {
// w(tag, String.format(formatMsg, args));
// }
// }
//
// public static void w(String tag, String msg, Throwable e) {
// if (LOG_ENABLED) {
// Log.w(TAG, getLogMsg(tag, msg + " Exception: " + getExceptionMsg(e)));
// }
// }
//
// public static void w(String tag, Throwable e, String formatMsg, Object... args) {
// if (LOG_ENABLED) {
// w(tag, String.format(formatMsg, args), e);
// }
// }
//
// public static void e(String tag, String msg) {
// if (LOG_ENABLED || ALWAYS_SHOW_ERROR) {
// Log.e(TAG, getLogMsg(tag, msg));
// }
// }
//
// public static void e(String tag, String formatMsg, Object... args) {
// if (LOG_ENABLED || ALWAYS_SHOW_ERROR) {
// e(tag, String.format(formatMsg, args));
// }
// }
//
// public static void e(String tag, String msg, Throwable e) {
// if (LOG_ENABLED || ALWAYS_SHOW_ERROR) {
// Log.e(TAG, getLogMsg(tag, msg + " Exception: " + getExceptionMsg(e)));
// }
// }
//
// public static void e(String tag, Throwable e, String formatMsg, Object... args) {
// if (LOG_ENABLED || ALWAYS_SHOW_ERROR) {
// e(tag, String.format(formatMsg, args), e);
// }
// }
//
// private static String getLogMsg(String subTag, String msg) {
// return "[" + subTag + "] " + msg;
// }
//
// private static String getExceptionMsg(Throwable e) {
// StringWriter sw = new StringWriter(1024);
// PrintWriter pw = new PrintWriter(sw);
// e.printStackTrace(pw);
// pw.close();
// return sw.toString();
// }
// }
// Path: PluginManager/src/main/java/com/reginald/pluginm/hook/ServiceHook.java
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import com.reginald.pluginm.utils.Logger;
import android.os.SystemClock;
package com.reginald.pluginm.hook;
/**
* Created by lxy on 17-8-16.
*/
public abstract class ServiceHook implements InvocationHandler {
private static final String TAG = "ServiceHook";
private static final boolean HOOK_LOG = true;
protected Object mBase;
protected final Map<String, MethodHandler> mMethodHandlers = new HashMap<String, MethodHandler>(2);
protected MethodHandler mAllMethodHandler;
/**
* 1. replace the host object(mBase) with the new one(Hook)
* 2. init MethodHandlers
* @return
*/
public abstract boolean install();
protected void addMethodHandler(MethodHandler methodHandler) { | Logger.d(TAG, "addMethodHandler " + methodHandler); |
xyxyLiu/PluginM | PluginManager/src/main/java/com/android/common/ContentProviderCompat.java | // Path: PluginManager/src/main/java/android/content/IContentProvider.java
// public interface IContentProvider extends IInterface {
// }
//
// Path: PluginManager/src/main/java/com/reginald/pluginm/utils/Logger.java
// public class Logger {
// public static final String TAG = "PluginM";
// public static boolean LOG_ENABLED = BuildConfig.DEBUG_LOG;
// public static boolean ALWAYS_SHOW_ERROR = true;
//
// public static void d(String tag, String msg) {
// if (LOG_ENABLED) {
// Log.d(TAG, getLogMsg(tag, msg));
// }
// }
//
// public static void d(String tag, String formatMsg, Object... args) {
// if (LOG_ENABLED) {
// d(tag, String.format(formatMsg, args));
// }
// }
//
// public static void i(String tag, String msg) {
// if (LOG_ENABLED) {
// Log.i(TAG, getLogMsg(tag, msg));
// }
// }
//
// public static void i(String tag, String formatMsg, Object... args) {
// if (LOG_ENABLED) {
// i(tag, String.format(formatMsg, args));
// }
// }
//
// public static void w(String tag, String msg) {
// if (LOG_ENABLED) {
// Log.w(TAG, getLogMsg(tag, msg));
// }
// }
//
// public static void w(String tag, String formatMsg, Object... args) {
// if (LOG_ENABLED) {
// w(tag, String.format(formatMsg, args));
// }
// }
//
// public static void w(String tag, String msg, Throwable e) {
// if (LOG_ENABLED) {
// Log.w(TAG, getLogMsg(tag, msg + " Exception: " + getExceptionMsg(e)));
// }
// }
//
// public static void w(String tag, Throwable e, String formatMsg, Object... args) {
// if (LOG_ENABLED) {
// w(tag, String.format(formatMsg, args), e);
// }
// }
//
// public static void e(String tag, String msg) {
// if (LOG_ENABLED || ALWAYS_SHOW_ERROR) {
// Log.e(TAG, getLogMsg(tag, msg));
// }
// }
//
// public static void e(String tag, String formatMsg, Object... args) {
// if (LOG_ENABLED || ALWAYS_SHOW_ERROR) {
// e(tag, String.format(formatMsg, args));
// }
// }
//
// public static void e(String tag, String msg, Throwable e) {
// if (LOG_ENABLED || ALWAYS_SHOW_ERROR) {
// Log.e(TAG, getLogMsg(tag, msg + " Exception: " + getExceptionMsg(e)));
// }
// }
//
// public static void e(String tag, Throwable e, String formatMsg, Object... args) {
// if (LOG_ENABLED || ALWAYS_SHOW_ERROR) {
// e(tag, String.format(formatMsg, args), e);
// }
// }
//
// private static String getLogMsg(String subTag, String msg) {
// return "[" + subTag + "] " + msg;
// }
//
// private static String getExceptionMsg(Throwable e) {
// StringWriter sw = new StringWriter(1024);
// PrintWriter pw = new PrintWriter(sw);
// e.printStackTrace(pw);
// pw.close();
// return sw.toString();
// }
// }
| import android.content.ContentProvider;
import android.content.ContentProviderClient;
import android.content.ContentResolver;
import android.content.IContentProvider;
import android.net.Uri;
import com.reginald.pluginm.utils.Logger;
import java.lang.reflect.Method; | package com.android.common;
/**
* Created by lxy on 16-10-26.
*/
public class ContentProviderCompat {
private static final String TAG = "ContentProviderCompat";
private static Method sAcquireProviderMethod;
private static Method sGetIContentProviderMethod;
static {
try {
Class[] arrayOfClass = new Class[]{Uri.class};
sAcquireProviderMethod = ContentResolver.class.getMethod("acquireProvider",
arrayOfClass);
sGetIContentProviderMethod = ContentProvider.class.getMethod("getIContentProvider");
} catch (Exception e) { | // Path: PluginManager/src/main/java/android/content/IContentProvider.java
// public interface IContentProvider extends IInterface {
// }
//
// Path: PluginManager/src/main/java/com/reginald/pluginm/utils/Logger.java
// public class Logger {
// public static final String TAG = "PluginM";
// public static boolean LOG_ENABLED = BuildConfig.DEBUG_LOG;
// public static boolean ALWAYS_SHOW_ERROR = true;
//
// public static void d(String tag, String msg) {
// if (LOG_ENABLED) {
// Log.d(TAG, getLogMsg(tag, msg));
// }
// }
//
// public static void d(String tag, String formatMsg, Object... args) {
// if (LOG_ENABLED) {
// d(tag, String.format(formatMsg, args));
// }
// }
//
// public static void i(String tag, String msg) {
// if (LOG_ENABLED) {
// Log.i(TAG, getLogMsg(tag, msg));
// }
// }
//
// public static void i(String tag, String formatMsg, Object... args) {
// if (LOG_ENABLED) {
// i(tag, String.format(formatMsg, args));
// }
// }
//
// public static void w(String tag, String msg) {
// if (LOG_ENABLED) {
// Log.w(TAG, getLogMsg(tag, msg));
// }
// }
//
// public static void w(String tag, String formatMsg, Object... args) {
// if (LOG_ENABLED) {
// w(tag, String.format(formatMsg, args));
// }
// }
//
// public static void w(String tag, String msg, Throwable e) {
// if (LOG_ENABLED) {
// Log.w(TAG, getLogMsg(tag, msg + " Exception: " + getExceptionMsg(e)));
// }
// }
//
// public static void w(String tag, Throwable e, String formatMsg, Object... args) {
// if (LOG_ENABLED) {
// w(tag, String.format(formatMsg, args), e);
// }
// }
//
// public static void e(String tag, String msg) {
// if (LOG_ENABLED || ALWAYS_SHOW_ERROR) {
// Log.e(TAG, getLogMsg(tag, msg));
// }
// }
//
// public static void e(String tag, String formatMsg, Object... args) {
// if (LOG_ENABLED || ALWAYS_SHOW_ERROR) {
// e(tag, String.format(formatMsg, args));
// }
// }
//
// public static void e(String tag, String msg, Throwable e) {
// if (LOG_ENABLED || ALWAYS_SHOW_ERROR) {
// Log.e(TAG, getLogMsg(tag, msg + " Exception: " + getExceptionMsg(e)));
// }
// }
//
// public static void e(String tag, Throwable e, String formatMsg, Object... args) {
// if (LOG_ENABLED || ALWAYS_SHOW_ERROR) {
// e(tag, String.format(formatMsg, args), e);
// }
// }
//
// private static String getLogMsg(String subTag, String msg) {
// return "[" + subTag + "] " + msg;
// }
//
// private static String getExceptionMsg(Throwable e) {
// StringWriter sw = new StringWriter(1024);
// PrintWriter pw = new PrintWriter(sw);
// e.printStackTrace(pw);
// pw.close();
// return sw.toString();
// }
// }
// Path: PluginManager/src/main/java/com/android/common/ContentProviderCompat.java
import android.content.ContentProvider;
import android.content.ContentProviderClient;
import android.content.ContentResolver;
import android.content.IContentProvider;
import android.net.Uri;
import com.reginald.pluginm.utils.Logger;
import java.lang.reflect.Method;
package com.android.common;
/**
* Created by lxy on 16-10-26.
*/
public class ContentProviderCompat {
private static final String TAG = "ContentProviderCompat";
private static Method sAcquireProviderMethod;
private static Method sGetIContentProviderMethod;
static {
try {
Class[] arrayOfClass = new Class[]{Uri.class};
sAcquireProviderMethod = ContentResolver.class.getMethod("acquireProvider",
arrayOfClass);
sGetIContentProviderMethod = ContentProvider.class.getMethod("getIContentProvider");
} catch (Exception e) { | Logger.d(TAG, "can not find acquireProvider or getIContentProvider"); |
xyxyLiu/PluginM | PluginManager/src/main/java/com/android/common/ContentProviderCompat.java | // Path: PluginManager/src/main/java/android/content/IContentProvider.java
// public interface IContentProvider extends IInterface {
// }
//
// Path: PluginManager/src/main/java/com/reginald/pluginm/utils/Logger.java
// public class Logger {
// public static final String TAG = "PluginM";
// public static boolean LOG_ENABLED = BuildConfig.DEBUG_LOG;
// public static boolean ALWAYS_SHOW_ERROR = true;
//
// public static void d(String tag, String msg) {
// if (LOG_ENABLED) {
// Log.d(TAG, getLogMsg(tag, msg));
// }
// }
//
// public static void d(String tag, String formatMsg, Object... args) {
// if (LOG_ENABLED) {
// d(tag, String.format(formatMsg, args));
// }
// }
//
// public static void i(String tag, String msg) {
// if (LOG_ENABLED) {
// Log.i(TAG, getLogMsg(tag, msg));
// }
// }
//
// public static void i(String tag, String formatMsg, Object... args) {
// if (LOG_ENABLED) {
// i(tag, String.format(formatMsg, args));
// }
// }
//
// public static void w(String tag, String msg) {
// if (LOG_ENABLED) {
// Log.w(TAG, getLogMsg(tag, msg));
// }
// }
//
// public static void w(String tag, String formatMsg, Object... args) {
// if (LOG_ENABLED) {
// w(tag, String.format(formatMsg, args));
// }
// }
//
// public static void w(String tag, String msg, Throwable e) {
// if (LOG_ENABLED) {
// Log.w(TAG, getLogMsg(tag, msg + " Exception: " + getExceptionMsg(e)));
// }
// }
//
// public static void w(String tag, Throwable e, String formatMsg, Object... args) {
// if (LOG_ENABLED) {
// w(tag, String.format(formatMsg, args), e);
// }
// }
//
// public static void e(String tag, String msg) {
// if (LOG_ENABLED || ALWAYS_SHOW_ERROR) {
// Log.e(TAG, getLogMsg(tag, msg));
// }
// }
//
// public static void e(String tag, String formatMsg, Object... args) {
// if (LOG_ENABLED || ALWAYS_SHOW_ERROR) {
// e(tag, String.format(formatMsg, args));
// }
// }
//
// public static void e(String tag, String msg, Throwable e) {
// if (LOG_ENABLED || ALWAYS_SHOW_ERROR) {
// Log.e(TAG, getLogMsg(tag, msg + " Exception: " + getExceptionMsg(e)));
// }
// }
//
// public static void e(String tag, Throwable e, String formatMsg, Object... args) {
// if (LOG_ENABLED || ALWAYS_SHOW_ERROR) {
// e(tag, String.format(formatMsg, args), e);
// }
// }
//
// private static String getLogMsg(String subTag, String msg) {
// return "[" + subTag + "] " + msg;
// }
//
// private static String getExceptionMsg(Throwable e) {
// StringWriter sw = new StringWriter(1024);
// PrintWriter pw = new PrintWriter(sw);
// e.printStackTrace(pw);
// pw.close();
// return sw.toString();
// }
// }
| import android.content.ContentProvider;
import android.content.ContentProviderClient;
import android.content.ContentResolver;
import android.content.IContentProvider;
import android.net.Uri;
import com.reginald.pluginm.utils.Logger;
import java.lang.reflect.Method; |
static {
try {
Class[] arrayOfClass = new Class[]{Uri.class};
sAcquireProviderMethod = ContentResolver.class.getMethod("acquireProvider",
arrayOfClass);
sGetIContentProviderMethod = ContentProvider.class.getMethod("getIContentProvider");
} catch (Exception e) {
Logger.d(TAG, "can not find acquireProvider or getIContentProvider");
sAcquireProviderMethod = null;
sGetIContentProviderMethod = null;
}
}
public static boolean hasPorvider(ContentResolver cr, Uri uri) {
if (sAcquireProviderMethod != null) {
try {
ContentProviderClient client = cr.acquireContentProviderClient(uri);
if (client != null) {
client.release();
return true;
}
return false;
} catch (Exception localInvocationTargetException) {
// ignore this, will to the final
}
}
return false;
}
| // Path: PluginManager/src/main/java/android/content/IContentProvider.java
// public interface IContentProvider extends IInterface {
// }
//
// Path: PluginManager/src/main/java/com/reginald/pluginm/utils/Logger.java
// public class Logger {
// public static final String TAG = "PluginM";
// public static boolean LOG_ENABLED = BuildConfig.DEBUG_LOG;
// public static boolean ALWAYS_SHOW_ERROR = true;
//
// public static void d(String tag, String msg) {
// if (LOG_ENABLED) {
// Log.d(TAG, getLogMsg(tag, msg));
// }
// }
//
// public static void d(String tag, String formatMsg, Object... args) {
// if (LOG_ENABLED) {
// d(tag, String.format(formatMsg, args));
// }
// }
//
// public static void i(String tag, String msg) {
// if (LOG_ENABLED) {
// Log.i(TAG, getLogMsg(tag, msg));
// }
// }
//
// public static void i(String tag, String formatMsg, Object... args) {
// if (LOG_ENABLED) {
// i(tag, String.format(formatMsg, args));
// }
// }
//
// public static void w(String tag, String msg) {
// if (LOG_ENABLED) {
// Log.w(TAG, getLogMsg(tag, msg));
// }
// }
//
// public static void w(String tag, String formatMsg, Object... args) {
// if (LOG_ENABLED) {
// w(tag, String.format(formatMsg, args));
// }
// }
//
// public static void w(String tag, String msg, Throwable e) {
// if (LOG_ENABLED) {
// Log.w(TAG, getLogMsg(tag, msg + " Exception: " + getExceptionMsg(e)));
// }
// }
//
// public static void w(String tag, Throwable e, String formatMsg, Object... args) {
// if (LOG_ENABLED) {
// w(tag, String.format(formatMsg, args), e);
// }
// }
//
// public static void e(String tag, String msg) {
// if (LOG_ENABLED || ALWAYS_SHOW_ERROR) {
// Log.e(TAG, getLogMsg(tag, msg));
// }
// }
//
// public static void e(String tag, String formatMsg, Object... args) {
// if (LOG_ENABLED || ALWAYS_SHOW_ERROR) {
// e(tag, String.format(formatMsg, args));
// }
// }
//
// public static void e(String tag, String msg, Throwable e) {
// if (LOG_ENABLED || ALWAYS_SHOW_ERROR) {
// Log.e(TAG, getLogMsg(tag, msg + " Exception: " + getExceptionMsg(e)));
// }
// }
//
// public static void e(String tag, Throwable e, String formatMsg, Object... args) {
// if (LOG_ENABLED || ALWAYS_SHOW_ERROR) {
// e(tag, String.format(formatMsg, args), e);
// }
// }
//
// private static String getLogMsg(String subTag, String msg) {
// return "[" + subTag + "] " + msg;
// }
//
// private static String getExceptionMsg(Throwable e) {
// StringWriter sw = new StringWriter(1024);
// PrintWriter pw = new PrintWriter(sw);
// e.printStackTrace(pw);
// pw.close();
// return sw.toString();
// }
// }
// Path: PluginManager/src/main/java/com/android/common/ContentProviderCompat.java
import android.content.ContentProvider;
import android.content.ContentProviderClient;
import android.content.ContentResolver;
import android.content.IContentProvider;
import android.net.Uri;
import com.reginald.pluginm.utils.Logger;
import java.lang.reflect.Method;
static {
try {
Class[] arrayOfClass = new Class[]{Uri.class};
sAcquireProviderMethod = ContentResolver.class.getMethod("acquireProvider",
arrayOfClass);
sGetIContentProviderMethod = ContentProvider.class.getMethod("getIContentProvider");
} catch (Exception e) {
Logger.d(TAG, "can not find acquireProvider or getIContentProvider");
sAcquireProviderMethod = null;
sGetIContentProviderMethod = null;
}
}
public static boolean hasPorvider(ContentResolver cr, Uri uri) {
if (sAcquireProviderMethod != null) {
try {
ContentProviderClient client = cr.acquireContentProviderClient(uri);
if (client != null) {
client.release();
return true;
}
return false;
} catch (Exception localInvocationTargetException) {
// ignore this, will to the final
}
}
return false;
}
| public static IContentProvider getIContentProvider(ContentProvider cp) { |
xyxyLiu/PluginM | PluginManager/src/main/java/com/reginald/pluginm/parser/IntentMatcher.java | // Path: PluginManager/src/main/java/com/reginald/pluginm/utils/Logger.java
// public class Logger {
// public static final String TAG = "PluginM";
// public static boolean LOG_ENABLED = BuildConfig.DEBUG_LOG;
// public static boolean ALWAYS_SHOW_ERROR = true;
//
// public static void d(String tag, String msg) {
// if (LOG_ENABLED) {
// Log.d(TAG, getLogMsg(tag, msg));
// }
// }
//
// public static void d(String tag, String formatMsg, Object... args) {
// if (LOG_ENABLED) {
// d(tag, String.format(formatMsg, args));
// }
// }
//
// public static void i(String tag, String msg) {
// if (LOG_ENABLED) {
// Log.i(TAG, getLogMsg(tag, msg));
// }
// }
//
// public static void i(String tag, String formatMsg, Object... args) {
// if (LOG_ENABLED) {
// i(tag, String.format(formatMsg, args));
// }
// }
//
// public static void w(String tag, String msg) {
// if (LOG_ENABLED) {
// Log.w(TAG, getLogMsg(tag, msg));
// }
// }
//
// public static void w(String tag, String formatMsg, Object... args) {
// if (LOG_ENABLED) {
// w(tag, String.format(formatMsg, args));
// }
// }
//
// public static void w(String tag, String msg, Throwable e) {
// if (LOG_ENABLED) {
// Log.w(TAG, getLogMsg(tag, msg + " Exception: " + getExceptionMsg(e)));
// }
// }
//
// public static void w(String tag, Throwable e, String formatMsg, Object... args) {
// if (LOG_ENABLED) {
// w(tag, String.format(formatMsg, args), e);
// }
// }
//
// public static void e(String tag, String msg) {
// if (LOG_ENABLED || ALWAYS_SHOW_ERROR) {
// Log.e(TAG, getLogMsg(tag, msg));
// }
// }
//
// public static void e(String tag, String formatMsg, Object... args) {
// if (LOG_ENABLED || ALWAYS_SHOW_ERROR) {
// e(tag, String.format(formatMsg, args));
// }
// }
//
// public static void e(String tag, String msg, Throwable e) {
// if (LOG_ENABLED || ALWAYS_SHOW_ERROR) {
// Log.e(TAG, getLogMsg(tag, msg + " Exception: " + getExceptionMsg(e)));
// }
// }
//
// public static void e(String tag, Throwable e, String formatMsg, Object... args) {
// if (LOG_ENABLED || ALWAYS_SHOW_ERROR) {
// e(tag, String.format(formatMsg, args), e);
// }
// }
//
// private static String getLogMsg(String subTag, String msg) {
// return "[" + subTag + "] " + msg;
// }
//
// private static String getExceptionMsg(Throwable e) {
// StringWriter sw = new StringWriter(1024);
// PrintWriter pw = new PrintWriter(sw);
// e.printStackTrace(pw);
// pw.close();
// return sw.toString();
// }
// }
| import android.content.pm.ResolveInfo;
import android.content.pm.ServiceInfo;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import com.reginald.pluginm.utils.Logger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import android.annotation.TargetApi;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ProviderInfo; | if ((flags & PackageManager.MATCH_DEFAULT_ONLY) != 0) {
if (intentFilter.hasCategory(Intent.CATEGORY_DEFAULT)) {
ResolveInfo resolveInfo = newResolveInfo(flagInfo, intentFilter);
resolveInfo.match = match;
resolveInfo.isDefault = true;
outList.add(resolveInfo);
} else {
//只是匹配默认。这里也算匹配不上。
}
} else {
ResolveInfo resolveInfo = newResolveInfo(flagInfo, intentFilter);
resolveInfo.match = match;
resolveInfo.isDefault = false;
outList.add(resolveInfo);
}
}
}
if (outList.size() <= 0) {
//没有在插件包中找到IntentFilter匹配的Service
}
} else {
//该插件包中没有具有IntentFilter的Service
}
}
} else {
//该插件apk包中没有Service
}
}
private static void queryIntentServiceForPackage(Context context, PluginPackageParser packageParser, Intent intent, int flags, List<ResolveInfo> outList) throws Exception { | // Path: PluginManager/src/main/java/com/reginald/pluginm/utils/Logger.java
// public class Logger {
// public static final String TAG = "PluginM";
// public static boolean LOG_ENABLED = BuildConfig.DEBUG_LOG;
// public static boolean ALWAYS_SHOW_ERROR = true;
//
// public static void d(String tag, String msg) {
// if (LOG_ENABLED) {
// Log.d(TAG, getLogMsg(tag, msg));
// }
// }
//
// public static void d(String tag, String formatMsg, Object... args) {
// if (LOG_ENABLED) {
// d(tag, String.format(formatMsg, args));
// }
// }
//
// public static void i(String tag, String msg) {
// if (LOG_ENABLED) {
// Log.i(TAG, getLogMsg(tag, msg));
// }
// }
//
// public static void i(String tag, String formatMsg, Object... args) {
// if (LOG_ENABLED) {
// i(tag, String.format(formatMsg, args));
// }
// }
//
// public static void w(String tag, String msg) {
// if (LOG_ENABLED) {
// Log.w(TAG, getLogMsg(tag, msg));
// }
// }
//
// public static void w(String tag, String formatMsg, Object... args) {
// if (LOG_ENABLED) {
// w(tag, String.format(formatMsg, args));
// }
// }
//
// public static void w(String tag, String msg, Throwable e) {
// if (LOG_ENABLED) {
// Log.w(TAG, getLogMsg(tag, msg + " Exception: " + getExceptionMsg(e)));
// }
// }
//
// public static void w(String tag, Throwable e, String formatMsg, Object... args) {
// if (LOG_ENABLED) {
// w(tag, String.format(formatMsg, args), e);
// }
// }
//
// public static void e(String tag, String msg) {
// if (LOG_ENABLED || ALWAYS_SHOW_ERROR) {
// Log.e(TAG, getLogMsg(tag, msg));
// }
// }
//
// public static void e(String tag, String formatMsg, Object... args) {
// if (LOG_ENABLED || ALWAYS_SHOW_ERROR) {
// e(tag, String.format(formatMsg, args));
// }
// }
//
// public static void e(String tag, String msg, Throwable e) {
// if (LOG_ENABLED || ALWAYS_SHOW_ERROR) {
// Log.e(TAG, getLogMsg(tag, msg + " Exception: " + getExceptionMsg(e)));
// }
// }
//
// public static void e(String tag, Throwable e, String formatMsg, Object... args) {
// if (LOG_ENABLED || ALWAYS_SHOW_ERROR) {
// e(tag, String.format(formatMsg, args), e);
// }
// }
//
// private static String getLogMsg(String subTag, String msg) {
// return "[" + subTag + "] " + msg;
// }
//
// private static String getExceptionMsg(Throwable e) {
// StringWriter sw = new StringWriter(1024);
// PrintWriter pw = new PrintWriter(sw);
// e.printStackTrace(pw);
// pw.close();
// return sw.toString();
// }
// }
// Path: PluginManager/src/main/java/com/reginald/pluginm/parser/IntentMatcher.java
import android.content.pm.ResolveInfo;
import android.content.pm.ServiceInfo;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import com.reginald.pluginm.utils.Logger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import android.annotation.TargetApi;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ProviderInfo;
if ((flags & PackageManager.MATCH_DEFAULT_ONLY) != 0) {
if (intentFilter.hasCategory(Intent.CATEGORY_DEFAULT)) {
ResolveInfo resolveInfo = newResolveInfo(flagInfo, intentFilter);
resolveInfo.match = match;
resolveInfo.isDefault = true;
outList.add(resolveInfo);
} else {
//只是匹配默认。这里也算匹配不上。
}
} else {
ResolveInfo resolveInfo = newResolveInfo(flagInfo, intentFilter);
resolveInfo.match = match;
resolveInfo.isDefault = false;
outList.add(resolveInfo);
}
}
}
if (outList.size() <= 0) {
//没有在插件包中找到IntentFilter匹配的Service
}
} else {
//该插件包中没有具有IntentFilter的Service
}
}
} else {
//该插件apk包中没有Service
}
}
private static void queryIntentServiceForPackage(Context context, PluginPackageParser packageParser, Intent intent, int flags, List<ResolveInfo> outList) throws Exception { | Logger.d(TAG, "queryIntentServiceForPackage() intent = " + intent); |
xyxyLiu/PluginM | PluginManager/src/main/java/com/android/common/ActivityThreadCompat.java | // Path: PluginManager/src/main/java/com/reginald/pluginm/utils/Logger.java
// public class Logger {
// public static final String TAG = "PluginM";
// public static boolean LOG_ENABLED = BuildConfig.DEBUG_LOG;
// public static boolean ALWAYS_SHOW_ERROR = true;
//
// public static void d(String tag, String msg) {
// if (LOG_ENABLED) {
// Log.d(TAG, getLogMsg(tag, msg));
// }
// }
//
// public static void d(String tag, String formatMsg, Object... args) {
// if (LOG_ENABLED) {
// d(tag, String.format(formatMsg, args));
// }
// }
//
// public static void i(String tag, String msg) {
// if (LOG_ENABLED) {
// Log.i(TAG, getLogMsg(tag, msg));
// }
// }
//
// public static void i(String tag, String formatMsg, Object... args) {
// if (LOG_ENABLED) {
// i(tag, String.format(formatMsg, args));
// }
// }
//
// public static void w(String tag, String msg) {
// if (LOG_ENABLED) {
// Log.w(TAG, getLogMsg(tag, msg));
// }
// }
//
// public static void w(String tag, String formatMsg, Object... args) {
// if (LOG_ENABLED) {
// w(tag, String.format(formatMsg, args));
// }
// }
//
// public static void w(String tag, String msg, Throwable e) {
// if (LOG_ENABLED) {
// Log.w(TAG, getLogMsg(tag, msg + " Exception: " + getExceptionMsg(e)));
// }
// }
//
// public static void w(String tag, Throwable e, String formatMsg, Object... args) {
// if (LOG_ENABLED) {
// w(tag, String.format(formatMsg, args), e);
// }
// }
//
// public static void e(String tag, String msg) {
// if (LOG_ENABLED || ALWAYS_SHOW_ERROR) {
// Log.e(TAG, getLogMsg(tag, msg));
// }
// }
//
// public static void e(String tag, String formatMsg, Object... args) {
// if (LOG_ENABLED || ALWAYS_SHOW_ERROR) {
// e(tag, String.format(formatMsg, args));
// }
// }
//
// public static void e(String tag, String msg, Throwable e) {
// if (LOG_ENABLED || ALWAYS_SHOW_ERROR) {
// Log.e(TAG, getLogMsg(tag, msg + " Exception: " + getExceptionMsg(e)));
// }
// }
//
// public static void e(String tag, Throwable e, String formatMsg, Object... args) {
// if (LOG_ENABLED || ALWAYS_SHOW_ERROR) {
// e(tag, String.format(formatMsg, args), e);
// }
// }
//
// private static String getLogMsg(String subTag, String msg) {
// return "[" + subTag + "] " + msg;
// }
//
// private static String getExceptionMsg(Throwable e) {
// StringWriter sw = new StringWriter(1024);
// PrintWriter pw = new PrintWriter(sw);
// e.printStackTrace(pw);
// pw.close();
// return sw.toString();
// }
// }
| import android.content.Context;
import android.content.pm.ProviderInfo;
import android.os.Build;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.VisibleForTesting;
import android.text.TextUtils;
import com.reginald.pluginm.utils.Logger;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List; | package com.android.common;
public class ActivityThreadCompat {
private static final String TAG = "ActivityThreadCompat";
private static final boolean DEBUG = true;
private static Class<?> sClass_ActivityThread;
private static Method sMtd_currentActivityThread;
private static Method sMtd_getProcessName;
private static Method sMtd_currentProcessName;
private static Method sMtd_installContentProviders;
static {
try {
sClass_ActivityThread = Class.forName("android.app.ActivityThread");
} catch (ClassNotFoundException e) { | // Path: PluginManager/src/main/java/com/reginald/pluginm/utils/Logger.java
// public class Logger {
// public static final String TAG = "PluginM";
// public static boolean LOG_ENABLED = BuildConfig.DEBUG_LOG;
// public static boolean ALWAYS_SHOW_ERROR = true;
//
// public static void d(String tag, String msg) {
// if (LOG_ENABLED) {
// Log.d(TAG, getLogMsg(tag, msg));
// }
// }
//
// public static void d(String tag, String formatMsg, Object... args) {
// if (LOG_ENABLED) {
// d(tag, String.format(formatMsg, args));
// }
// }
//
// public static void i(String tag, String msg) {
// if (LOG_ENABLED) {
// Log.i(TAG, getLogMsg(tag, msg));
// }
// }
//
// public static void i(String tag, String formatMsg, Object... args) {
// if (LOG_ENABLED) {
// i(tag, String.format(formatMsg, args));
// }
// }
//
// public static void w(String tag, String msg) {
// if (LOG_ENABLED) {
// Log.w(TAG, getLogMsg(tag, msg));
// }
// }
//
// public static void w(String tag, String formatMsg, Object... args) {
// if (LOG_ENABLED) {
// w(tag, String.format(formatMsg, args));
// }
// }
//
// public static void w(String tag, String msg, Throwable e) {
// if (LOG_ENABLED) {
// Log.w(TAG, getLogMsg(tag, msg + " Exception: " + getExceptionMsg(e)));
// }
// }
//
// public static void w(String tag, Throwable e, String formatMsg, Object... args) {
// if (LOG_ENABLED) {
// w(tag, String.format(formatMsg, args), e);
// }
// }
//
// public static void e(String tag, String msg) {
// if (LOG_ENABLED || ALWAYS_SHOW_ERROR) {
// Log.e(TAG, getLogMsg(tag, msg));
// }
// }
//
// public static void e(String tag, String formatMsg, Object... args) {
// if (LOG_ENABLED || ALWAYS_SHOW_ERROR) {
// e(tag, String.format(formatMsg, args));
// }
// }
//
// public static void e(String tag, String msg, Throwable e) {
// if (LOG_ENABLED || ALWAYS_SHOW_ERROR) {
// Log.e(TAG, getLogMsg(tag, msg + " Exception: " + getExceptionMsg(e)));
// }
// }
//
// public static void e(String tag, Throwable e, String formatMsg, Object... args) {
// if (LOG_ENABLED || ALWAYS_SHOW_ERROR) {
// e(tag, String.format(formatMsg, args), e);
// }
// }
//
// private static String getLogMsg(String subTag, String msg) {
// return "[" + subTag + "] " + msg;
// }
//
// private static String getExceptionMsg(Throwable e) {
// StringWriter sw = new StringWriter(1024);
// PrintWriter pw = new PrintWriter(sw);
// e.printStackTrace(pw);
// pw.close();
// return sw.toString();
// }
// }
// Path: PluginManager/src/main/java/com/android/common/ActivityThreadCompat.java
import android.content.Context;
import android.content.pm.ProviderInfo;
import android.os.Build;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.VisibleForTesting;
import android.text.TextUtils;
import com.reginald.pluginm.utils.Logger;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
package com.android.common;
public class ActivityThreadCompat {
private static final String TAG = "ActivityThreadCompat";
private static final boolean DEBUG = true;
private static Class<?> sClass_ActivityThread;
private static Method sMtd_currentActivityThread;
private static Method sMtd_getProcessName;
private static Method sMtd_currentProcessName;
private static Method sMtd_installContentProviders;
static {
try {
sClass_ActivityThread = Class.forName("android.app.ActivityThread");
} catch (ClassNotFoundException e) { | Logger.w(TAG, "class not found", e); |
xyxyLiu/PluginM | PluginManager/src/main/java/com/reginald/pluginm/comm/invoker/InvokeCallbackWrapper.java | // Path: PluginApi/src/main/java/com/reginald/pluginm/pluginapi/IInvokeCallback.java
// public interface IInvokeCallback {
// /**
// * 函数回调
// * @param params 回调参数
// * @return 回调结果 {@link com.reginald.pluginm.pluginapi.IInvokeResult}
// */
// IInvokeResult onCallback(String params);
// }
//
// Path: PluginApi/src/main/java/com/reginald/pluginm/pluginapi/IInvokeResult.java
// public interface IInvokeResult {
// /**
// * 函数调用结果成功
// */
// int RESULT_OK = 1;
// /**
// * 函数调用结果失败,未找到目标IInvoker
// */
// int RESULT_NOT_FOUND = -1;
// /**
// * 函数调用结果失败,远端服务进程死亡
// */
// int RESULT_REMOTE_ERROR = -2;
// /**
// * 函数调用结果失败,非法或不支持的参数
// */
// int RESULT_INVOKE_INVALID = -10;
// /**
// * 函数调用结果失败,内部错误
// */
// int RESULT_INVOKE_ERROR = -11;
//
// /**
// * 获取调用返回码
// * @return 返回码
// */
// int getResultCode();
//
// /**
// * 获取调用结果,当{@link IInvokeResult#getResultCode()} 为 {@link IInvokeResult#RESULT_OK} 时才有意义。
// * @return 调用结果
// */
// String getResult();
//
// IInvokeResult INVOKERESULT_VOID_OK = new IInvokeResult() {
// @Override
// public int getResultCode() {
// return RESULT_OK;
// }
//
// @Override
// public String getResult() {
// return null;
// }
// };
// }
//
// Path: PluginManager/src/main/java/com/reginald/pluginm/utils/Logger.java
// public class Logger {
// public static final String TAG = "PluginM";
// public static boolean LOG_ENABLED = BuildConfig.DEBUG_LOG;
// public static boolean ALWAYS_SHOW_ERROR = true;
//
// public static void d(String tag, String msg) {
// if (LOG_ENABLED) {
// Log.d(TAG, getLogMsg(tag, msg));
// }
// }
//
// public static void d(String tag, String formatMsg, Object... args) {
// if (LOG_ENABLED) {
// d(tag, String.format(formatMsg, args));
// }
// }
//
// public static void i(String tag, String msg) {
// if (LOG_ENABLED) {
// Log.i(TAG, getLogMsg(tag, msg));
// }
// }
//
// public static void i(String tag, String formatMsg, Object... args) {
// if (LOG_ENABLED) {
// i(tag, String.format(formatMsg, args));
// }
// }
//
// public static void w(String tag, String msg) {
// if (LOG_ENABLED) {
// Log.w(TAG, getLogMsg(tag, msg));
// }
// }
//
// public static void w(String tag, String formatMsg, Object... args) {
// if (LOG_ENABLED) {
// w(tag, String.format(formatMsg, args));
// }
// }
//
// public static void w(String tag, String msg, Throwable e) {
// if (LOG_ENABLED) {
// Log.w(TAG, getLogMsg(tag, msg + " Exception: " + getExceptionMsg(e)));
// }
// }
//
// public static void w(String tag, Throwable e, String formatMsg, Object... args) {
// if (LOG_ENABLED) {
// w(tag, String.format(formatMsg, args), e);
// }
// }
//
// public static void e(String tag, String msg) {
// if (LOG_ENABLED || ALWAYS_SHOW_ERROR) {
// Log.e(TAG, getLogMsg(tag, msg));
// }
// }
//
// public static void e(String tag, String formatMsg, Object... args) {
// if (LOG_ENABLED || ALWAYS_SHOW_ERROR) {
// e(tag, String.format(formatMsg, args));
// }
// }
//
// public static void e(String tag, String msg, Throwable e) {
// if (LOG_ENABLED || ALWAYS_SHOW_ERROR) {
// Log.e(TAG, getLogMsg(tag, msg + " Exception: " + getExceptionMsg(e)));
// }
// }
//
// public static void e(String tag, Throwable e, String formatMsg, Object... args) {
// if (LOG_ENABLED || ALWAYS_SHOW_ERROR) {
// e(tag, String.format(formatMsg, args), e);
// }
// }
//
// private static String getLogMsg(String subTag, String msg) {
// return "[" + subTag + "] " + msg;
// }
//
// private static String getExceptionMsg(Throwable e) {
// StringWriter sw = new StringWriter(1024);
// PrintWriter pw = new PrintWriter(sw);
// e.printStackTrace(pw);
// pw.close();
// return sw.toString();
// }
// }
| import android.os.RemoteException;
import com.reginald.pluginm.pluginapi.IInvokeCallback;
import com.reginald.pluginm.pluginapi.IInvokeResult;
import com.reginald.pluginm.utils.Logger; | package com.reginald.pluginm.comm.invoker;
/**
* Created by lxy on 17-9-21.
*/
public abstract class InvokeCallbackWrapper extends InvokeCallback.Stub {
private static final String TAG = "InvokeCallbackStub";
| // Path: PluginApi/src/main/java/com/reginald/pluginm/pluginapi/IInvokeCallback.java
// public interface IInvokeCallback {
// /**
// * 函数回调
// * @param params 回调参数
// * @return 回调结果 {@link com.reginald.pluginm.pluginapi.IInvokeResult}
// */
// IInvokeResult onCallback(String params);
// }
//
// Path: PluginApi/src/main/java/com/reginald/pluginm/pluginapi/IInvokeResult.java
// public interface IInvokeResult {
// /**
// * 函数调用结果成功
// */
// int RESULT_OK = 1;
// /**
// * 函数调用结果失败,未找到目标IInvoker
// */
// int RESULT_NOT_FOUND = -1;
// /**
// * 函数调用结果失败,远端服务进程死亡
// */
// int RESULT_REMOTE_ERROR = -2;
// /**
// * 函数调用结果失败,非法或不支持的参数
// */
// int RESULT_INVOKE_INVALID = -10;
// /**
// * 函数调用结果失败,内部错误
// */
// int RESULT_INVOKE_ERROR = -11;
//
// /**
// * 获取调用返回码
// * @return 返回码
// */
// int getResultCode();
//
// /**
// * 获取调用结果,当{@link IInvokeResult#getResultCode()} 为 {@link IInvokeResult#RESULT_OK} 时才有意义。
// * @return 调用结果
// */
// String getResult();
//
// IInvokeResult INVOKERESULT_VOID_OK = new IInvokeResult() {
// @Override
// public int getResultCode() {
// return RESULT_OK;
// }
//
// @Override
// public String getResult() {
// return null;
// }
// };
// }
//
// Path: PluginManager/src/main/java/com/reginald/pluginm/utils/Logger.java
// public class Logger {
// public static final String TAG = "PluginM";
// public static boolean LOG_ENABLED = BuildConfig.DEBUG_LOG;
// public static boolean ALWAYS_SHOW_ERROR = true;
//
// public static void d(String tag, String msg) {
// if (LOG_ENABLED) {
// Log.d(TAG, getLogMsg(tag, msg));
// }
// }
//
// public static void d(String tag, String formatMsg, Object... args) {
// if (LOG_ENABLED) {
// d(tag, String.format(formatMsg, args));
// }
// }
//
// public static void i(String tag, String msg) {
// if (LOG_ENABLED) {
// Log.i(TAG, getLogMsg(tag, msg));
// }
// }
//
// public static void i(String tag, String formatMsg, Object... args) {
// if (LOG_ENABLED) {
// i(tag, String.format(formatMsg, args));
// }
// }
//
// public static void w(String tag, String msg) {
// if (LOG_ENABLED) {
// Log.w(TAG, getLogMsg(tag, msg));
// }
// }
//
// public static void w(String tag, String formatMsg, Object... args) {
// if (LOG_ENABLED) {
// w(tag, String.format(formatMsg, args));
// }
// }
//
// public static void w(String tag, String msg, Throwable e) {
// if (LOG_ENABLED) {
// Log.w(TAG, getLogMsg(tag, msg + " Exception: " + getExceptionMsg(e)));
// }
// }
//
// public static void w(String tag, Throwable e, String formatMsg, Object... args) {
// if (LOG_ENABLED) {
// w(tag, String.format(formatMsg, args), e);
// }
// }
//
// public static void e(String tag, String msg) {
// if (LOG_ENABLED || ALWAYS_SHOW_ERROR) {
// Log.e(TAG, getLogMsg(tag, msg));
// }
// }
//
// public static void e(String tag, String formatMsg, Object... args) {
// if (LOG_ENABLED || ALWAYS_SHOW_ERROR) {
// e(tag, String.format(formatMsg, args));
// }
// }
//
// public static void e(String tag, String msg, Throwable e) {
// if (LOG_ENABLED || ALWAYS_SHOW_ERROR) {
// Log.e(TAG, getLogMsg(tag, msg + " Exception: " + getExceptionMsg(e)));
// }
// }
//
// public static void e(String tag, Throwable e, String formatMsg, Object... args) {
// if (LOG_ENABLED || ALWAYS_SHOW_ERROR) {
// e(tag, String.format(formatMsg, args), e);
// }
// }
//
// private static String getLogMsg(String subTag, String msg) {
// return "[" + subTag + "] " + msg;
// }
//
// private static String getExceptionMsg(Throwable e) {
// StringWriter sw = new StringWriter(1024);
// PrintWriter pw = new PrintWriter(sw);
// e.printStackTrace(pw);
// pw.close();
// return sw.toString();
// }
// }
// Path: PluginManager/src/main/java/com/reginald/pluginm/comm/invoker/InvokeCallbackWrapper.java
import android.os.RemoteException;
import com.reginald.pluginm.pluginapi.IInvokeCallback;
import com.reginald.pluginm.pluginapi.IInvokeResult;
import com.reginald.pluginm.utils.Logger;
package com.reginald.pluginm.comm.invoker;
/**
* Created by lxy on 17-9-21.
*/
public abstract class InvokeCallbackWrapper extends InvokeCallback.Stub {
private static final String TAG = "InvokeCallbackStub";
| public static InvokeCallbackWrapper build(final IInvokeCallback iInvokeCallback) { |
ryantenney/metrics-spring | src/main/java/com/ryantenney/metrics/spring/config/annotation/MetricsConfigurationSupport.java | // Path: src/main/java/com/ryantenney/metrics/spring/MetricsBeanPostProcessorFactory.java
// public class MetricsBeanPostProcessorFactory {
//
// private MetricsBeanPostProcessorFactory() {}
//
// public static AdvisingBeanPostProcessor exceptionMetered(final MetricRegistry metricRegistry, final ProxyConfig proxyConfig) {
// return new AdvisingBeanPostProcessor(ExceptionMeteredMethodInterceptor.POINTCUT, ExceptionMeteredMethodInterceptor.adviceFactory(metricRegistry),
// proxyConfig);
// }
//
// public static AdvisingBeanPostProcessor metered(final MetricRegistry metricRegistry, final ProxyConfig proxyConfig) {
// return new AdvisingBeanPostProcessor(MeteredMethodInterceptor.POINTCUT, MeteredMethodInterceptor.adviceFactory(metricRegistry), proxyConfig);
// }
//
// public static AdvisingBeanPostProcessor timed(final MetricRegistry metricRegistry, final ProxyConfig proxyConfig) {
// return new AdvisingBeanPostProcessor(TimedMethodInterceptor.POINTCUT, TimedMethodInterceptor.adviceFactory(metricRegistry), proxyConfig);
// }
//
// public static AdvisingBeanPostProcessor counted(final MetricRegistry metricRegistry, final ProxyConfig proxyConfig) {
// return new AdvisingBeanPostProcessor(CountedMethodInterceptor.POINTCUT, CountedMethodInterceptor.adviceFactory(metricRegistry), proxyConfig);
// }
//
// public static GaugeFieldAnnotationBeanPostProcessor gaugeField(final MetricRegistry metricRegistry) {
// return new GaugeFieldAnnotationBeanPostProcessor(metricRegistry);
// }
//
// public static GaugeMethodAnnotationBeanPostProcessor gaugeMethod(final MetricRegistry metricRegistry) {
// return new GaugeMethodAnnotationBeanPostProcessor(metricRegistry);
// }
//
// public static CachedGaugeAnnotationBeanPostProcessor cachedGauge(final MetricRegistry metricRegistry) {
// return new CachedGaugeAnnotationBeanPostProcessor(metricRegistry);
// }
//
// public static MetricAnnotationBeanPostProcessor metric(final MetricRegistry metricRegistry) {
// return new MetricAnnotationBeanPostProcessor(metricRegistry);
// }
//
// public static HealthCheckBeanPostProcessor healthCheck(final HealthCheckRegistry healthRegistry) {
// return new HealthCheckBeanPostProcessor(healthRegistry);
// }
//
// @Deprecated
// public static AdvisingBeanPostProcessor legacyCounted(final MetricRegistry metricRegistry, final ProxyConfig proxyConfig) {
// return new AdvisingBeanPostProcessor(LegacyCountedMethodInterceptor.POINTCUT, LegacyCountedMethodInterceptor.adviceFactory(metricRegistry), proxyConfig);
// }
//
// @Deprecated
// public static LegacyCachedGaugeAnnotationBeanPostProcessor legacyCachedGauge(final MetricRegistry metricRegistry) {
// return new LegacyCachedGaugeAnnotationBeanPostProcessor(metricRegistry);
// }
//
// @Deprecated
// public static LegacyMetricAnnotationBeanPostProcessor legacyMetric(final MetricRegistry metricRegistry) {
// return new LegacyMetricAnnotationBeanPostProcessor(metricRegistry);
// }
//
// }
| import org.springframework.aop.framework.ProxyConfig;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ImportAware;
import org.springframework.context.annotation.Role;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.util.Assert;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.health.HealthCheckRegistry;
import com.ryantenney.metrics.spring.MetricsBeanPostProcessorFactory; | /**
* Copyright (C) 2012 Ryan W Tenney (ryan@10e.us)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ryantenney.metrics.spring.config.annotation;
/**
* This is the main class providing the configuration behind the Metrics Java config.
* It is typically imported by adding {@link EnableMetrics @EnableMetrics} to an
* application {@link org.springframework.context.annotation.Configuration @Configuration} class.
*
* @see MetricsConfigurer
* @see MetricsConfigurerAdapter
* @author Ryan Tenney
* @since 3.0
*/
public class MetricsConfigurationSupport implements ImportAware {
private final Object lock = new Object();
private volatile MetricRegistry metricRegistry;
private volatile HealthCheckRegistry healthCheckRegistry;
private ProxyConfig proxyConfig;
@Override
public void setImportMetadata(AnnotationMetadata importMetadata) {
final AnnotationAttributes enableMetrics = AnnotationAttributes.fromMap(importMetadata.getAnnotationAttributes(EnableMetrics.class.getName(), false));
Assert.notNull(enableMetrics, "@" + EnableMetrics.class.getSimpleName() + " is not present on importing class " + importMetadata.getClassName());
this.proxyConfig = new ProxyConfig();
this.proxyConfig.setExposeProxy(enableMetrics.getBoolean("exposeProxy"));
this.proxyConfig.setProxyTargetClass(enableMetrics.getBoolean("proxyTargetClass"));
}
@Bean
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
public BeanPostProcessor exceptionMeteredAnnotationBeanPostProcessor() { | // Path: src/main/java/com/ryantenney/metrics/spring/MetricsBeanPostProcessorFactory.java
// public class MetricsBeanPostProcessorFactory {
//
// private MetricsBeanPostProcessorFactory() {}
//
// public static AdvisingBeanPostProcessor exceptionMetered(final MetricRegistry metricRegistry, final ProxyConfig proxyConfig) {
// return new AdvisingBeanPostProcessor(ExceptionMeteredMethodInterceptor.POINTCUT, ExceptionMeteredMethodInterceptor.adviceFactory(metricRegistry),
// proxyConfig);
// }
//
// public static AdvisingBeanPostProcessor metered(final MetricRegistry metricRegistry, final ProxyConfig proxyConfig) {
// return new AdvisingBeanPostProcessor(MeteredMethodInterceptor.POINTCUT, MeteredMethodInterceptor.adviceFactory(metricRegistry), proxyConfig);
// }
//
// public static AdvisingBeanPostProcessor timed(final MetricRegistry metricRegistry, final ProxyConfig proxyConfig) {
// return new AdvisingBeanPostProcessor(TimedMethodInterceptor.POINTCUT, TimedMethodInterceptor.adviceFactory(metricRegistry), proxyConfig);
// }
//
// public static AdvisingBeanPostProcessor counted(final MetricRegistry metricRegistry, final ProxyConfig proxyConfig) {
// return new AdvisingBeanPostProcessor(CountedMethodInterceptor.POINTCUT, CountedMethodInterceptor.adviceFactory(metricRegistry), proxyConfig);
// }
//
// public static GaugeFieldAnnotationBeanPostProcessor gaugeField(final MetricRegistry metricRegistry) {
// return new GaugeFieldAnnotationBeanPostProcessor(metricRegistry);
// }
//
// public static GaugeMethodAnnotationBeanPostProcessor gaugeMethod(final MetricRegistry metricRegistry) {
// return new GaugeMethodAnnotationBeanPostProcessor(metricRegistry);
// }
//
// public static CachedGaugeAnnotationBeanPostProcessor cachedGauge(final MetricRegistry metricRegistry) {
// return new CachedGaugeAnnotationBeanPostProcessor(metricRegistry);
// }
//
// public static MetricAnnotationBeanPostProcessor metric(final MetricRegistry metricRegistry) {
// return new MetricAnnotationBeanPostProcessor(metricRegistry);
// }
//
// public static HealthCheckBeanPostProcessor healthCheck(final HealthCheckRegistry healthRegistry) {
// return new HealthCheckBeanPostProcessor(healthRegistry);
// }
//
// @Deprecated
// public static AdvisingBeanPostProcessor legacyCounted(final MetricRegistry metricRegistry, final ProxyConfig proxyConfig) {
// return new AdvisingBeanPostProcessor(LegacyCountedMethodInterceptor.POINTCUT, LegacyCountedMethodInterceptor.adviceFactory(metricRegistry), proxyConfig);
// }
//
// @Deprecated
// public static LegacyCachedGaugeAnnotationBeanPostProcessor legacyCachedGauge(final MetricRegistry metricRegistry) {
// return new LegacyCachedGaugeAnnotationBeanPostProcessor(metricRegistry);
// }
//
// @Deprecated
// public static LegacyMetricAnnotationBeanPostProcessor legacyMetric(final MetricRegistry metricRegistry) {
// return new LegacyMetricAnnotationBeanPostProcessor(metricRegistry);
// }
//
// }
// Path: src/main/java/com/ryantenney/metrics/spring/config/annotation/MetricsConfigurationSupport.java
import org.springframework.aop.framework.ProxyConfig;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ImportAware;
import org.springframework.context.annotation.Role;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.util.Assert;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.health.HealthCheckRegistry;
import com.ryantenney.metrics.spring.MetricsBeanPostProcessorFactory;
/**
* Copyright (C) 2012 Ryan W Tenney (ryan@10e.us)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ryantenney.metrics.spring.config.annotation;
/**
* This is the main class providing the configuration behind the Metrics Java config.
* It is typically imported by adding {@link EnableMetrics @EnableMetrics} to an
* application {@link org.springframework.context.annotation.Configuration @Configuration} class.
*
* @see MetricsConfigurer
* @see MetricsConfigurerAdapter
* @author Ryan Tenney
* @since 3.0
*/
public class MetricsConfigurationSupport implements ImportAware {
private final Object lock = new Object();
private volatile MetricRegistry metricRegistry;
private volatile HealthCheckRegistry healthCheckRegistry;
private ProxyConfig proxyConfig;
@Override
public void setImportMetadata(AnnotationMetadata importMetadata) {
final AnnotationAttributes enableMetrics = AnnotationAttributes.fromMap(importMetadata.getAnnotationAttributes(EnableMetrics.class.getName(), false));
Assert.notNull(enableMetrics, "@" + EnableMetrics.class.getSimpleName() + " is not present on importing class " + importMetadata.getClassName());
this.proxyConfig = new ProxyConfig();
this.proxyConfig.setExposeProxy(enableMetrics.getBoolean("exposeProxy"));
this.proxyConfig.setProxyTargetClass(enableMetrics.getBoolean("proxyTargetClass"));
}
@Bean
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
public BeanPostProcessor exceptionMeteredAnnotationBeanPostProcessor() { | return MetricsBeanPostProcessorFactory.exceptionMetered(getMetricRegistry(), proxyConfig); |
ryantenney/metrics-spring | src/test/java/com/ryantenney/metrics/spring/MeteredClassTest.java | // Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static CachedGauge<?> forCachedGaugeMethod(MetricRegistry metricRegistry, Class<?> clazz, String methodName) {
// Method method = findMethod(clazz, methodName);
// String metricName = forCachedGauge(clazz, method, method.getAnnotation(com.codahale.metrics.annotation.CachedGauge.class));
// log.info("Looking up cached gauge method named '{}'", metricName);
// return (CachedGauge<?>) metricRegistry.getGauges().get(metricName);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static String forCountedMethod(Class<?> klass, Member member, Counted annotation) {
// return Util.forCountedMethod(klass, member, annotation);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static String forExceptionMeteredMethod(Class<?> klass, Member member, ExceptionMetered annotation) {
// return Util.forExceptionMeteredMethod(klass, member, annotation);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static Gauge<?> forGaugeField(MetricRegistry metricRegistry, Class<?> clazz, String fieldName) {
// Field field = findField(clazz, fieldName);
// String metricName = forGauge(clazz, field, field.getAnnotation(com.codahale.metrics.annotation.Gauge.class));
// log.info("Looking up gauge field named '{}'", metricName);
// return metricRegistry.getGauges().get(metricName);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static Gauge<?> forGaugeMethod(MetricRegistry metricRegistry, Class<?> clazz, String methodName) {
// Method method = findMethod(clazz, methodName);
// String metricName = forGauge(clazz, method, method.getAnnotation(com.codahale.metrics.annotation.Gauge.class));
// log.info("Looking up gauge method named '{}'", metricName);
// return metricRegistry.getGauges().get(metricName);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static String forMeteredMethod(Class<?> klass, Member member, Metered annotation) {
// return Util.forMeteredMethod(klass, member, annotation);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static String forTimedMethod(Class<?> klass, Member member, Timed annotation) {
// return Util.forTimedMethod(klass, member, annotation);
// }
| import static com.ryantenney.metrics.spring.TestUtil.forCachedGaugeMethod;
import static com.ryantenney.metrics.spring.TestUtil.forCountedMethod;
import static com.ryantenney.metrics.spring.TestUtil.forExceptionMeteredMethod;
import static com.ryantenney.metrics.spring.TestUtil.forGaugeField;
import static com.ryantenney.metrics.spring.TestUtil.forGaugeMethod;
import static com.ryantenney.metrics.spring.TestUtil.forMeteredMethod;
import static com.ryantenney.metrics.spring.TestUtil.forTimedMethod;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.codahale.metrics.CachedGauge;
import com.codahale.metrics.Counter;
import com.codahale.metrics.Gauge;
import com.codahale.metrics.Meter;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.RatioGauge;
import com.codahale.metrics.Timer;
import com.codahale.metrics.annotation.Counted;
import com.codahale.metrics.annotation.ExceptionMetered;
import com.codahale.metrics.annotation.Metered;
import com.codahale.metrics.annotation.Timed; | /**
* Copyright (C) 2012 Ryan W Tenney (ryan@10e.us)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ryantenney.metrics.spring;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:metered-class.xml")
public class MeteredClassTest {
@Autowired
MeteredClass meteredClass;
MetricRegistry metricRegistry;
@Autowired
public void setMetricRegistry(MetricRegistry metricRegistry) {
this.metricRegistry = metricRegistry;
this.metricRegistry.addListener(new LoggingMetricRegistryListener());
}
@Test
public void gauges() { | // Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static CachedGauge<?> forCachedGaugeMethod(MetricRegistry metricRegistry, Class<?> clazz, String methodName) {
// Method method = findMethod(clazz, methodName);
// String metricName = forCachedGauge(clazz, method, method.getAnnotation(com.codahale.metrics.annotation.CachedGauge.class));
// log.info("Looking up cached gauge method named '{}'", metricName);
// return (CachedGauge<?>) metricRegistry.getGauges().get(metricName);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static String forCountedMethod(Class<?> klass, Member member, Counted annotation) {
// return Util.forCountedMethod(klass, member, annotation);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static String forExceptionMeteredMethod(Class<?> klass, Member member, ExceptionMetered annotation) {
// return Util.forExceptionMeteredMethod(klass, member, annotation);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static Gauge<?> forGaugeField(MetricRegistry metricRegistry, Class<?> clazz, String fieldName) {
// Field field = findField(clazz, fieldName);
// String metricName = forGauge(clazz, field, field.getAnnotation(com.codahale.metrics.annotation.Gauge.class));
// log.info("Looking up gauge field named '{}'", metricName);
// return metricRegistry.getGauges().get(metricName);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static Gauge<?> forGaugeMethod(MetricRegistry metricRegistry, Class<?> clazz, String methodName) {
// Method method = findMethod(clazz, methodName);
// String metricName = forGauge(clazz, method, method.getAnnotation(com.codahale.metrics.annotation.Gauge.class));
// log.info("Looking up gauge method named '{}'", metricName);
// return metricRegistry.getGauges().get(metricName);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static String forMeteredMethod(Class<?> klass, Member member, Metered annotation) {
// return Util.forMeteredMethod(klass, member, annotation);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static String forTimedMethod(Class<?> klass, Member member, Timed annotation) {
// return Util.forTimedMethod(klass, member, annotation);
// }
// Path: src/test/java/com/ryantenney/metrics/spring/MeteredClassTest.java
import static com.ryantenney.metrics.spring.TestUtil.forCachedGaugeMethod;
import static com.ryantenney.metrics.spring.TestUtil.forCountedMethod;
import static com.ryantenney.metrics.spring.TestUtil.forExceptionMeteredMethod;
import static com.ryantenney.metrics.spring.TestUtil.forGaugeField;
import static com.ryantenney.metrics.spring.TestUtil.forGaugeMethod;
import static com.ryantenney.metrics.spring.TestUtil.forMeteredMethod;
import static com.ryantenney.metrics.spring.TestUtil.forTimedMethod;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.codahale.metrics.CachedGauge;
import com.codahale.metrics.Counter;
import com.codahale.metrics.Gauge;
import com.codahale.metrics.Meter;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.RatioGauge;
import com.codahale.metrics.Timer;
import com.codahale.metrics.annotation.Counted;
import com.codahale.metrics.annotation.ExceptionMetered;
import com.codahale.metrics.annotation.Metered;
import com.codahale.metrics.annotation.Timed;
/**
* Copyright (C) 2012 Ryan W Tenney (ryan@10e.us)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ryantenney.metrics.spring;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:metered-class.xml")
public class MeteredClassTest {
@Autowired
MeteredClass meteredClass;
MetricRegistry metricRegistry;
@Autowired
public void setMetricRegistry(MetricRegistry metricRegistry) {
this.metricRegistry = metricRegistry;
this.metricRegistry.addListener(new LoggingMetricRegistryListener());
}
@Test
public void gauges() { | Gauge<?> gaugedField = forGaugeField(metricRegistry, MeteredClass.class, "gaugedField"); |
ryantenney/metrics-spring | src/test/java/com/ryantenney/metrics/spring/MeteredClassTest.java | // Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static CachedGauge<?> forCachedGaugeMethod(MetricRegistry metricRegistry, Class<?> clazz, String methodName) {
// Method method = findMethod(clazz, methodName);
// String metricName = forCachedGauge(clazz, method, method.getAnnotation(com.codahale.metrics.annotation.CachedGauge.class));
// log.info("Looking up cached gauge method named '{}'", metricName);
// return (CachedGauge<?>) metricRegistry.getGauges().get(metricName);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static String forCountedMethod(Class<?> klass, Member member, Counted annotation) {
// return Util.forCountedMethod(klass, member, annotation);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static String forExceptionMeteredMethod(Class<?> klass, Member member, ExceptionMetered annotation) {
// return Util.forExceptionMeteredMethod(klass, member, annotation);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static Gauge<?> forGaugeField(MetricRegistry metricRegistry, Class<?> clazz, String fieldName) {
// Field field = findField(clazz, fieldName);
// String metricName = forGauge(clazz, field, field.getAnnotation(com.codahale.metrics.annotation.Gauge.class));
// log.info("Looking up gauge field named '{}'", metricName);
// return metricRegistry.getGauges().get(metricName);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static Gauge<?> forGaugeMethod(MetricRegistry metricRegistry, Class<?> clazz, String methodName) {
// Method method = findMethod(clazz, methodName);
// String metricName = forGauge(clazz, method, method.getAnnotation(com.codahale.metrics.annotation.Gauge.class));
// log.info("Looking up gauge method named '{}'", metricName);
// return metricRegistry.getGauges().get(metricName);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static String forMeteredMethod(Class<?> klass, Member member, Metered annotation) {
// return Util.forMeteredMethod(klass, member, annotation);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static String forTimedMethod(Class<?> klass, Member member, Timed annotation) {
// return Util.forTimedMethod(klass, member, annotation);
// }
| import static com.ryantenney.metrics.spring.TestUtil.forCachedGaugeMethod;
import static com.ryantenney.metrics.spring.TestUtil.forCountedMethod;
import static com.ryantenney.metrics.spring.TestUtil.forExceptionMeteredMethod;
import static com.ryantenney.metrics.spring.TestUtil.forGaugeField;
import static com.ryantenney.metrics.spring.TestUtil.forGaugeMethod;
import static com.ryantenney.metrics.spring.TestUtil.forMeteredMethod;
import static com.ryantenney.metrics.spring.TestUtil.forTimedMethod;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.codahale.metrics.CachedGauge;
import com.codahale.metrics.Counter;
import com.codahale.metrics.Gauge;
import com.codahale.metrics.Meter;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.RatioGauge;
import com.codahale.metrics.Timer;
import com.codahale.metrics.annotation.Counted;
import com.codahale.metrics.annotation.ExceptionMetered;
import com.codahale.metrics.annotation.Metered;
import com.codahale.metrics.annotation.Timed; | /**
* Copyright (C) 2012 Ryan W Tenney (ryan@10e.us)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ryantenney.metrics.spring;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:metered-class.xml")
public class MeteredClassTest {
@Autowired
MeteredClass meteredClass;
MetricRegistry metricRegistry;
@Autowired
public void setMetricRegistry(MetricRegistry metricRegistry) {
this.metricRegistry = metricRegistry;
this.metricRegistry.addListener(new LoggingMetricRegistryListener());
}
@Test
public void gauges() {
Gauge<?> gaugedField = forGaugeField(metricRegistry, MeteredClass.class, "gaugedField"); | // Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static CachedGauge<?> forCachedGaugeMethod(MetricRegistry metricRegistry, Class<?> clazz, String methodName) {
// Method method = findMethod(clazz, methodName);
// String metricName = forCachedGauge(clazz, method, method.getAnnotation(com.codahale.metrics.annotation.CachedGauge.class));
// log.info("Looking up cached gauge method named '{}'", metricName);
// return (CachedGauge<?>) metricRegistry.getGauges().get(metricName);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static String forCountedMethod(Class<?> klass, Member member, Counted annotation) {
// return Util.forCountedMethod(klass, member, annotation);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static String forExceptionMeteredMethod(Class<?> klass, Member member, ExceptionMetered annotation) {
// return Util.forExceptionMeteredMethod(klass, member, annotation);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static Gauge<?> forGaugeField(MetricRegistry metricRegistry, Class<?> clazz, String fieldName) {
// Field field = findField(clazz, fieldName);
// String metricName = forGauge(clazz, field, field.getAnnotation(com.codahale.metrics.annotation.Gauge.class));
// log.info("Looking up gauge field named '{}'", metricName);
// return metricRegistry.getGauges().get(metricName);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static Gauge<?> forGaugeMethod(MetricRegistry metricRegistry, Class<?> clazz, String methodName) {
// Method method = findMethod(clazz, methodName);
// String metricName = forGauge(clazz, method, method.getAnnotation(com.codahale.metrics.annotation.Gauge.class));
// log.info("Looking up gauge method named '{}'", metricName);
// return metricRegistry.getGauges().get(metricName);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static String forMeteredMethod(Class<?> klass, Member member, Metered annotation) {
// return Util.forMeteredMethod(klass, member, annotation);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static String forTimedMethod(Class<?> klass, Member member, Timed annotation) {
// return Util.forTimedMethod(klass, member, annotation);
// }
// Path: src/test/java/com/ryantenney/metrics/spring/MeteredClassTest.java
import static com.ryantenney.metrics.spring.TestUtil.forCachedGaugeMethod;
import static com.ryantenney.metrics.spring.TestUtil.forCountedMethod;
import static com.ryantenney.metrics.spring.TestUtil.forExceptionMeteredMethod;
import static com.ryantenney.metrics.spring.TestUtil.forGaugeField;
import static com.ryantenney.metrics.spring.TestUtil.forGaugeMethod;
import static com.ryantenney.metrics.spring.TestUtil.forMeteredMethod;
import static com.ryantenney.metrics.spring.TestUtil.forTimedMethod;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.codahale.metrics.CachedGauge;
import com.codahale.metrics.Counter;
import com.codahale.metrics.Gauge;
import com.codahale.metrics.Meter;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.RatioGauge;
import com.codahale.metrics.Timer;
import com.codahale.metrics.annotation.Counted;
import com.codahale.metrics.annotation.ExceptionMetered;
import com.codahale.metrics.annotation.Metered;
import com.codahale.metrics.annotation.Timed;
/**
* Copyright (C) 2012 Ryan W Tenney (ryan@10e.us)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ryantenney.metrics.spring;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:metered-class.xml")
public class MeteredClassTest {
@Autowired
MeteredClass meteredClass;
MetricRegistry metricRegistry;
@Autowired
public void setMetricRegistry(MetricRegistry metricRegistry) {
this.metricRegistry = metricRegistry;
this.metricRegistry.addListener(new LoggingMetricRegistryListener());
}
@Test
public void gauges() {
Gauge<?> gaugedField = forGaugeField(metricRegistry, MeteredClass.class, "gaugedField"); | Gauge<?> gaugedMethod = forGaugeMethod(metricRegistry, MeteredClass.class, "gaugedMethod"); |
ryantenney/metrics-spring | src/test/java/com/ryantenney/metrics/spring/MeteredClassTest.java | // Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static CachedGauge<?> forCachedGaugeMethod(MetricRegistry metricRegistry, Class<?> clazz, String methodName) {
// Method method = findMethod(clazz, methodName);
// String metricName = forCachedGauge(clazz, method, method.getAnnotation(com.codahale.metrics.annotation.CachedGauge.class));
// log.info("Looking up cached gauge method named '{}'", metricName);
// return (CachedGauge<?>) metricRegistry.getGauges().get(metricName);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static String forCountedMethod(Class<?> klass, Member member, Counted annotation) {
// return Util.forCountedMethod(klass, member, annotation);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static String forExceptionMeteredMethod(Class<?> klass, Member member, ExceptionMetered annotation) {
// return Util.forExceptionMeteredMethod(klass, member, annotation);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static Gauge<?> forGaugeField(MetricRegistry metricRegistry, Class<?> clazz, String fieldName) {
// Field field = findField(clazz, fieldName);
// String metricName = forGauge(clazz, field, field.getAnnotation(com.codahale.metrics.annotation.Gauge.class));
// log.info("Looking up gauge field named '{}'", metricName);
// return metricRegistry.getGauges().get(metricName);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static Gauge<?> forGaugeMethod(MetricRegistry metricRegistry, Class<?> clazz, String methodName) {
// Method method = findMethod(clazz, methodName);
// String metricName = forGauge(clazz, method, method.getAnnotation(com.codahale.metrics.annotation.Gauge.class));
// log.info("Looking up gauge method named '{}'", metricName);
// return metricRegistry.getGauges().get(metricName);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static String forMeteredMethod(Class<?> klass, Member member, Metered annotation) {
// return Util.forMeteredMethod(klass, member, annotation);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static String forTimedMethod(Class<?> klass, Member member, Timed annotation) {
// return Util.forTimedMethod(klass, member, annotation);
// }
| import static com.ryantenney.metrics.spring.TestUtil.forCachedGaugeMethod;
import static com.ryantenney.metrics.spring.TestUtil.forCountedMethod;
import static com.ryantenney.metrics.spring.TestUtil.forExceptionMeteredMethod;
import static com.ryantenney.metrics.spring.TestUtil.forGaugeField;
import static com.ryantenney.metrics.spring.TestUtil.forGaugeMethod;
import static com.ryantenney.metrics.spring.TestUtil.forMeteredMethod;
import static com.ryantenney.metrics.spring.TestUtil.forTimedMethod;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.codahale.metrics.CachedGauge;
import com.codahale.metrics.Counter;
import com.codahale.metrics.Gauge;
import com.codahale.metrics.Meter;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.RatioGauge;
import com.codahale.metrics.Timer;
import com.codahale.metrics.annotation.Counted;
import com.codahale.metrics.annotation.ExceptionMetered;
import com.codahale.metrics.annotation.Metered;
import com.codahale.metrics.annotation.Timed; | /**
* Copyright (C) 2012 Ryan W Tenney (ryan@10e.us)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ryantenney.metrics.spring;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:metered-class.xml")
public class MeteredClassTest {
@Autowired
MeteredClass meteredClass;
MetricRegistry metricRegistry;
@Autowired
public void setMetricRegistry(MetricRegistry metricRegistry) {
this.metricRegistry = metricRegistry;
this.metricRegistry.addListener(new LoggingMetricRegistryListener());
}
@Test
public void gauges() {
Gauge<?> gaugedField = forGaugeField(metricRegistry, MeteredClass.class, "gaugedField");
Gauge<?> gaugedMethod = forGaugeMethod(metricRegistry, MeteredClass.class, "gaugedMethod");
Gauge<?> gaugedGaugeField = forGaugeField(metricRegistry, MeteredClass.class, "gaugedGaugeField"); | // Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static CachedGauge<?> forCachedGaugeMethod(MetricRegistry metricRegistry, Class<?> clazz, String methodName) {
// Method method = findMethod(clazz, methodName);
// String metricName = forCachedGauge(clazz, method, method.getAnnotation(com.codahale.metrics.annotation.CachedGauge.class));
// log.info("Looking up cached gauge method named '{}'", metricName);
// return (CachedGauge<?>) metricRegistry.getGauges().get(metricName);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static String forCountedMethod(Class<?> klass, Member member, Counted annotation) {
// return Util.forCountedMethod(klass, member, annotation);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static String forExceptionMeteredMethod(Class<?> klass, Member member, ExceptionMetered annotation) {
// return Util.forExceptionMeteredMethod(klass, member, annotation);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static Gauge<?> forGaugeField(MetricRegistry metricRegistry, Class<?> clazz, String fieldName) {
// Field field = findField(clazz, fieldName);
// String metricName = forGauge(clazz, field, field.getAnnotation(com.codahale.metrics.annotation.Gauge.class));
// log.info("Looking up gauge field named '{}'", metricName);
// return metricRegistry.getGauges().get(metricName);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static Gauge<?> forGaugeMethod(MetricRegistry metricRegistry, Class<?> clazz, String methodName) {
// Method method = findMethod(clazz, methodName);
// String metricName = forGauge(clazz, method, method.getAnnotation(com.codahale.metrics.annotation.Gauge.class));
// log.info("Looking up gauge method named '{}'", metricName);
// return metricRegistry.getGauges().get(metricName);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static String forMeteredMethod(Class<?> klass, Member member, Metered annotation) {
// return Util.forMeteredMethod(klass, member, annotation);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static String forTimedMethod(Class<?> klass, Member member, Timed annotation) {
// return Util.forTimedMethod(klass, member, annotation);
// }
// Path: src/test/java/com/ryantenney/metrics/spring/MeteredClassTest.java
import static com.ryantenney.metrics.spring.TestUtil.forCachedGaugeMethod;
import static com.ryantenney.metrics.spring.TestUtil.forCountedMethod;
import static com.ryantenney.metrics.spring.TestUtil.forExceptionMeteredMethod;
import static com.ryantenney.metrics.spring.TestUtil.forGaugeField;
import static com.ryantenney.metrics.spring.TestUtil.forGaugeMethod;
import static com.ryantenney.metrics.spring.TestUtil.forMeteredMethod;
import static com.ryantenney.metrics.spring.TestUtil.forTimedMethod;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.codahale.metrics.CachedGauge;
import com.codahale.metrics.Counter;
import com.codahale.metrics.Gauge;
import com.codahale.metrics.Meter;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.RatioGauge;
import com.codahale.metrics.Timer;
import com.codahale.metrics.annotation.Counted;
import com.codahale.metrics.annotation.ExceptionMetered;
import com.codahale.metrics.annotation.Metered;
import com.codahale.metrics.annotation.Timed;
/**
* Copyright (C) 2012 Ryan W Tenney (ryan@10e.us)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ryantenney.metrics.spring;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:metered-class.xml")
public class MeteredClassTest {
@Autowired
MeteredClass meteredClass;
MetricRegistry metricRegistry;
@Autowired
public void setMetricRegistry(MetricRegistry metricRegistry) {
this.metricRegistry = metricRegistry;
this.metricRegistry.addListener(new LoggingMetricRegistryListener());
}
@Test
public void gauges() {
Gauge<?> gaugedField = forGaugeField(metricRegistry, MeteredClass.class, "gaugedField");
Gauge<?> gaugedMethod = forGaugeMethod(metricRegistry, MeteredClass.class, "gaugedMethod");
Gauge<?> gaugedGaugeField = forGaugeField(metricRegistry, MeteredClass.class, "gaugedGaugeField"); | CachedGauge<?> cachedGaugedMethod = forCachedGaugeMethod(metricRegistry, MeteredClass.class, "cachedGaugedMethod"); |
ryantenney/metrics-spring | src/test/java/com/ryantenney/metrics/spring/MeteredClassTest.java | // Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static CachedGauge<?> forCachedGaugeMethod(MetricRegistry metricRegistry, Class<?> clazz, String methodName) {
// Method method = findMethod(clazz, methodName);
// String metricName = forCachedGauge(clazz, method, method.getAnnotation(com.codahale.metrics.annotation.CachedGauge.class));
// log.info("Looking up cached gauge method named '{}'", metricName);
// return (CachedGauge<?>) metricRegistry.getGauges().get(metricName);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static String forCountedMethod(Class<?> klass, Member member, Counted annotation) {
// return Util.forCountedMethod(klass, member, annotation);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static String forExceptionMeteredMethod(Class<?> klass, Member member, ExceptionMetered annotation) {
// return Util.forExceptionMeteredMethod(klass, member, annotation);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static Gauge<?> forGaugeField(MetricRegistry metricRegistry, Class<?> clazz, String fieldName) {
// Field field = findField(clazz, fieldName);
// String metricName = forGauge(clazz, field, field.getAnnotation(com.codahale.metrics.annotation.Gauge.class));
// log.info("Looking up gauge field named '{}'", metricName);
// return metricRegistry.getGauges().get(metricName);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static Gauge<?> forGaugeMethod(MetricRegistry metricRegistry, Class<?> clazz, String methodName) {
// Method method = findMethod(clazz, methodName);
// String metricName = forGauge(clazz, method, method.getAnnotation(com.codahale.metrics.annotation.Gauge.class));
// log.info("Looking up gauge method named '{}'", metricName);
// return metricRegistry.getGauges().get(metricName);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static String forMeteredMethod(Class<?> klass, Member member, Metered annotation) {
// return Util.forMeteredMethod(klass, member, annotation);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static String forTimedMethod(Class<?> klass, Member member, Timed annotation) {
// return Util.forTimedMethod(klass, member, annotation);
// }
| import static com.ryantenney.metrics.spring.TestUtil.forCachedGaugeMethod;
import static com.ryantenney.metrics.spring.TestUtil.forCountedMethod;
import static com.ryantenney.metrics.spring.TestUtil.forExceptionMeteredMethod;
import static com.ryantenney.metrics.spring.TestUtil.forGaugeField;
import static com.ryantenney.metrics.spring.TestUtil.forGaugeMethod;
import static com.ryantenney.metrics.spring.TestUtil.forMeteredMethod;
import static com.ryantenney.metrics.spring.TestUtil.forTimedMethod;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.codahale.metrics.CachedGauge;
import com.codahale.metrics.Counter;
import com.codahale.metrics.Gauge;
import com.codahale.metrics.Meter;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.RatioGauge;
import com.codahale.metrics.Timer;
import com.codahale.metrics.annotation.Counted;
import com.codahale.metrics.annotation.ExceptionMetered;
import com.codahale.metrics.annotation.Metered;
import com.codahale.metrics.annotation.Timed; |
assertEquals(1000, gaugedField.getValue());
assertEquals(1000, gaugedMethod.getValue());
assertEquals(999, cachedGaugedMethod.getValue());
assertEquals(0.5, gaugedGaugeField.getValue());
}
@Test
public void timedMethod() throws Throwable {
Timer timedMethod = forTimedMethod(metricRegistry, MeteredClass.class, "timedMethod");
assertEquals(0, timedMethod.getCount());
meteredClass.timedMethod(false);
assertEquals(1, timedMethod.getCount());
// getCount increments even when the method throws an exception
try {
meteredClass.timedMethod(true);
fail();
}
catch (Throwable e) {
assertTrue(e instanceof BogusException);
}
assertEquals(2, timedMethod.getCount());
}
@Test
public void meteredMethod() throws Throwable { | // Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static CachedGauge<?> forCachedGaugeMethod(MetricRegistry metricRegistry, Class<?> clazz, String methodName) {
// Method method = findMethod(clazz, methodName);
// String metricName = forCachedGauge(clazz, method, method.getAnnotation(com.codahale.metrics.annotation.CachedGauge.class));
// log.info("Looking up cached gauge method named '{}'", metricName);
// return (CachedGauge<?>) metricRegistry.getGauges().get(metricName);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static String forCountedMethod(Class<?> klass, Member member, Counted annotation) {
// return Util.forCountedMethod(klass, member, annotation);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static String forExceptionMeteredMethod(Class<?> klass, Member member, ExceptionMetered annotation) {
// return Util.forExceptionMeteredMethod(klass, member, annotation);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static Gauge<?> forGaugeField(MetricRegistry metricRegistry, Class<?> clazz, String fieldName) {
// Field field = findField(clazz, fieldName);
// String metricName = forGauge(clazz, field, field.getAnnotation(com.codahale.metrics.annotation.Gauge.class));
// log.info("Looking up gauge field named '{}'", metricName);
// return metricRegistry.getGauges().get(metricName);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static Gauge<?> forGaugeMethod(MetricRegistry metricRegistry, Class<?> clazz, String methodName) {
// Method method = findMethod(clazz, methodName);
// String metricName = forGauge(clazz, method, method.getAnnotation(com.codahale.metrics.annotation.Gauge.class));
// log.info("Looking up gauge method named '{}'", metricName);
// return metricRegistry.getGauges().get(metricName);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static String forMeteredMethod(Class<?> klass, Member member, Metered annotation) {
// return Util.forMeteredMethod(klass, member, annotation);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static String forTimedMethod(Class<?> klass, Member member, Timed annotation) {
// return Util.forTimedMethod(klass, member, annotation);
// }
// Path: src/test/java/com/ryantenney/metrics/spring/MeteredClassTest.java
import static com.ryantenney.metrics.spring.TestUtil.forCachedGaugeMethod;
import static com.ryantenney.metrics.spring.TestUtil.forCountedMethod;
import static com.ryantenney.metrics.spring.TestUtil.forExceptionMeteredMethod;
import static com.ryantenney.metrics.spring.TestUtil.forGaugeField;
import static com.ryantenney.metrics.spring.TestUtil.forGaugeMethod;
import static com.ryantenney.metrics.spring.TestUtil.forMeteredMethod;
import static com.ryantenney.metrics.spring.TestUtil.forTimedMethod;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.codahale.metrics.CachedGauge;
import com.codahale.metrics.Counter;
import com.codahale.metrics.Gauge;
import com.codahale.metrics.Meter;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.RatioGauge;
import com.codahale.metrics.Timer;
import com.codahale.metrics.annotation.Counted;
import com.codahale.metrics.annotation.ExceptionMetered;
import com.codahale.metrics.annotation.Metered;
import com.codahale.metrics.annotation.Timed;
assertEquals(1000, gaugedField.getValue());
assertEquals(1000, gaugedMethod.getValue());
assertEquals(999, cachedGaugedMethod.getValue());
assertEquals(0.5, gaugedGaugeField.getValue());
}
@Test
public void timedMethod() throws Throwable {
Timer timedMethod = forTimedMethod(metricRegistry, MeteredClass.class, "timedMethod");
assertEquals(0, timedMethod.getCount());
meteredClass.timedMethod(false);
assertEquals(1, timedMethod.getCount());
// getCount increments even when the method throws an exception
try {
meteredClass.timedMethod(true);
fail();
}
catch (Throwable e) {
assertTrue(e instanceof BogusException);
}
assertEquals(2, timedMethod.getCount());
}
@Test
public void meteredMethod() throws Throwable { | Meter meteredMethod = forMeteredMethod(metricRegistry, MeteredClass.class, "meteredMethod"); |
ryantenney/metrics-spring | src/test/java/com/ryantenney/metrics/spring/MeteredClassTest.java | // Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static CachedGauge<?> forCachedGaugeMethod(MetricRegistry metricRegistry, Class<?> clazz, String methodName) {
// Method method = findMethod(clazz, methodName);
// String metricName = forCachedGauge(clazz, method, method.getAnnotation(com.codahale.metrics.annotation.CachedGauge.class));
// log.info("Looking up cached gauge method named '{}'", metricName);
// return (CachedGauge<?>) metricRegistry.getGauges().get(metricName);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static String forCountedMethod(Class<?> klass, Member member, Counted annotation) {
// return Util.forCountedMethod(klass, member, annotation);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static String forExceptionMeteredMethod(Class<?> klass, Member member, ExceptionMetered annotation) {
// return Util.forExceptionMeteredMethod(klass, member, annotation);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static Gauge<?> forGaugeField(MetricRegistry metricRegistry, Class<?> clazz, String fieldName) {
// Field field = findField(clazz, fieldName);
// String metricName = forGauge(clazz, field, field.getAnnotation(com.codahale.metrics.annotation.Gauge.class));
// log.info("Looking up gauge field named '{}'", metricName);
// return metricRegistry.getGauges().get(metricName);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static Gauge<?> forGaugeMethod(MetricRegistry metricRegistry, Class<?> clazz, String methodName) {
// Method method = findMethod(clazz, methodName);
// String metricName = forGauge(clazz, method, method.getAnnotation(com.codahale.metrics.annotation.Gauge.class));
// log.info("Looking up gauge method named '{}'", metricName);
// return metricRegistry.getGauges().get(metricName);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static String forMeteredMethod(Class<?> klass, Member member, Metered annotation) {
// return Util.forMeteredMethod(klass, member, annotation);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static String forTimedMethod(Class<?> klass, Member member, Timed annotation) {
// return Util.forTimedMethod(klass, member, annotation);
// }
| import static com.ryantenney.metrics.spring.TestUtil.forCachedGaugeMethod;
import static com.ryantenney.metrics.spring.TestUtil.forCountedMethod;
import static com.ryantenney.metrics.spring.TestUtil.forExceptionMeteredMethod;
import static com.ryantenney.metrics.spring.TestUtil.forGaugeField;
import static com.ryantenney.metrics.spring.TestUtil.forGaugeMethod;
import static com.ryantenney.metrics.spring.TestUtil.forMeteredMethod;
import static com.ryantenney.metrics.spring.TestUtil.forTimedMethod;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.codahale.metrics.CachedGauge;
import com.codahale.metrics.Counter;
import com.codahale.metrics.Gauge;
import com.codahale.metrics.Meter;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.RatioGauge;
import com.codahale.metrics.Timer;
import com.codahale.metrics.annotation.Counted;
import com.codahale.metrics.annotation.ExceptionMetered;
import com.codahale.metrics.annotation.Metered;
import com.codahale.metrics.annotation.Timed; | Timer timedMethod = forTimedMethod(metricRegistry, MeteredClass.class, "timedMethod");
assertEquals(0, timedMethod.getCount());
meteredClass.timedMethod(false);
assertEquals(1, timedMethod.getCount());
// getCount increments even when the method throws an exception
try {
meteredClass.timedMethod(true);
fail();
}
catch (Throwable e) {
assertTrue(e instanceof BogusException);
}
assertEquals(2, timedMethod.getCount());
}
@Test
public void meteredMethod() throws Throwable {
Meter meteredMethod = forMeteredMethod(metricRegistry, MeteredClass.class, "meteredMethod");
assertEquals(0, meteredMethod.getCount());
meteredClass.meteredMethod();
assertEquals(1, meteredMethod.getCount());
}
@Test
public void exceptionMeteredMethod() throws Throwable { | // Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static CachedGauge<?> forCachedGaugeMethod(MetricRegistry metricRegistry, Class<?> clazz, String methodName) {
// Method method = findMethod(clazz, methodName);
// String metricName = forCachedGauge(clazz, method, method.getAnnotation(com.codahale.metrics.annotation.CachedGauge.class));
// log.info("Looking up cached gauge method named '{}'", metricName);
// return (CachedGauge<?>) metricRegistry.getGauges().get(metricName);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static String forCountedMethod(Class<?> klass, Member member, Counted annotation) {
// return Util.forCountedMethod(klass, member, annotation);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static String forExceptionMeteredMethod(Class<?> klass, Member member, ExceptionMetered annotation) {
// return Util.forExceptionMeteredMethod(klass, member, annotation);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static Gauge<?> forGaugeField(MetricRegistry metricRegistry, Class<?> clazz, String fieldName) {
// Field field = findField(clazz, fieldName);
// String metricName = forGauge(clazz, field, field.getAnnotation(com.codahale.metrics.annotation.Gauge.class));
// log.info("Looking up gauge field named '{}'", metricName);
// return metricRegistry.getGauges().get(metricName);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static Gauge<?> forGaugeMethod(MetricRegistry metricRegistry, Class<?> clazz, String methodName) {
// Method method = findMethod(clazz, methodName);
// String metricName = forGauge(clazz, method, method.getAnnotation(com.codahale.metrics.annotation.Gauge.class));
// log.info("Looking up gauge method named '{}'", metricName);
// return metricRegistry.getGauges().get(metricName);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static String forMeteredMethod(Class<?> klass, Member member, Metered annotation) {
// return Util.forMeteredMethod(klass, member, annotation);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static String forTimedMethod(Class<?> klass, Member member, Timed annotation) {
// return Util.forTimedMethod(klass, member, annotation);
// }
// Path: src/test/java/com/ryantenney/metrics/spring/MeteredClassTest.java
import static com.ryantenney.metrics.spring.TestUtil.forCachedGaugeMethod;
import static com.ryantenney.metrics.spring.TestUtil.forCountedMethod;
import static com.ryantenney.metrics.spring.TestUtil.forExceptionMeteredMethod;
import static com.ryantenney.metrics.spring.TestUtil.forGaugeField;
import static com.ryantenney.metrics.spring.TestUtil.forGaugeMethod;
import static com.ryantenney.metrics.spring.TestUtil.forMeteredMethod;
import static com.ryantenney.metrics.spring.TestUtil.forTimedMethod;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.codahale.metrics.CachedGauge;
import com.codahale.metrics.Counter;
import com.codahale.metrics.Gauge;
import com.codahale.metrics.Meter;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.RatioGauge;
import com.codahale.metrics.Timer;
import com.codahale.metrics.annotation.Counted;
import com.codahale.metrics.annotation.ExceptionMetered;
import com.codahale.metrics.annotation.Metered;
import com.codahale.metrics.annotation.Timed;
Timer timedMethod = forTimedMethod(metricRegistry, MeteredClass.class, "timedMethod");
assertEquals(0, timedMethod.getCount());
meteredClass.timedMethod(false);
assertEquals(1, timedMethod.getCount());
// getCount increments even when the method throws an exception
try {
meteredClass.timedMethod(true);
fail();
}
catch (Throwable e) {
assertTrue(e instanceof BogusException);
}
assertEquals(2, timedMethod.getCount());
}
@Test
public void meteredMethod() throws Throwable {
Meter meteredMethod = forMeteredMethod(metricRegistry, MeteredClass.class, "meteredMethod");
assertEquals(0, meteredMethod.getCount());
meteredClass.meteredMethod();
assertEquals(1, meteredMethod.getCount());
}
@Test
public void exceptionMeteredMethod() throws Throwable { | Meter exceptionMeteredMethod = forExceptionMeteredMethod(metricRegistry, MeteredClass.class, "exceptionMeteredMethod"); |
ryantenney/metrics-spring | src/test/java/com/ryantenney/metrics/spring/MeteredClassTest.java | // Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static CachedGauge<?> forCachedGaugeMethod(MetricRegistry metricRegistry, Class<?> clazz, String methodName) {
// Method method = findMethod(clazz, methodName);
// String metricName = forCachedGauge(clazz, method, method.getAnnotation(com.codahale.metrics.annotation.CachedGauge.class));
// log.info("Looking up cached gauge method named '{}'", metricName);
// return (CachedGauge<?>) metricRegistry.getGauges().get(metricName);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static String forCountedMethod(Class<?> klass, Member member, Counted annotation) {
// return Util.forCountedMethod(klass, member, annotation);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static String forExceptionMeteredMethod(Class<?> klass, Member member, ExceptionMetered annotation) {
// return Util.forExceptionMeteredMethod(klass, member, annotation);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static Gauge<?> forGaugeField(MetricRegistry metricRegistry, Class<?> clazz, String fieldName) {
// Field field = findField(clazz, fieldName);
// String metricName = forGauge(clazz, field, field.getAnnotation(com.codahale.metrics.annotation.Gauge.class));
// log.info("Looking up gauge field named '{}'", metricName);
// return metricRegistry.getGauges().get(metricName);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static Gauge<?> forGaugeMethod(MetricRegistry metricRegistry, Class<?> clazz, String methodName) {
// Method method = findMethod(clazz, methodName);
// String metricName = forGauge(clazz, method, method.getAnnotation(com.codahale.metrics.annotation.Gauge.class));
// log.info("Looking up gauge method named '{}'", metricName);
// return metricRegistry.getGauges().get(metricName);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static String forMeteredMethod(Class<?> klass, Member member, Metered annotation) {
// return Util.forMeteredMethod(klass, member, annotation);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static String forTimedMethod(Class<?> klass, Member member, Timed annotation) {
// return Util.forTimedMethod(klass, member, annotation);
// }
| import static com.ryantenney.metrics.spring.TestUtil.forCachedGaugeMethod;
import static com.ryantenney.metrics.spring.TestUtil.forCountedMethod;
import static com.ryantenney.metrics.spring.TestUtil.forExceptionMeteredMethod;
import static com.ryantenney.metrics.spring.TestUtil.forGaugeField;
import static com.ryantenney.metrics.spring.TestUtil.forGaugeMethod;
import static com.ryantenney.metrics.spring.TestUtil.forMeteredMethod;
import static com.ryantenney.metrics.spring.TestUtil.forTimedMethod;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.codahale.metrics.CachedGauge;
import com.codahale.metrics.Counter;
import com.codahale.metrics.Gauge;
import com.codahale.metrics.Meter;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.RatioGauge;
import com.codahale.metrics.Timer;
import com.codahale.metrics.annotation.Counted;
import com.codahale.metrics.annotation.ExceptionMetered;
import com.codahale.metrics.annotation.Metered;
import com.codahale.metrics.annotation.Timed; |
assertEquals(0, exceptionMeteredMethod.getCount());
// doesn't throw an exception
meteredClass.exceptionMeteredMethod(null);
assertEquals(0, exceptionMeteredMethod.getCount());
// throws the wrong exception
try {
meteredClass.exceptionMeteredMethod(RuntimeException.class);
fail();
}
catch (Throwable t) {
assertTrue(t instanceof RuntimeException);
}
assertEquals(0, exceptionMeteredMethod.getCount());
// throws the right exception
try {
meteredClass.exceptionMeteredMethod(BogusException.class);
fail();
}
catch (Throwable t) {
assertTrue(t instanceof BogusException);
}
assertEquals(1, exceptionMeteredMethod.getCount());
}
@Test
public void countedMethod() throws Throwable { | // Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static CachedGauge<?> forCachedGaugeMethod(MetricRegistry metricRegistry, Class<?> clazz, String methodName) {
// Method method = findMethod(clazz, methodName);
// String metricName = forCachedGauge(clazz, method, method.getAnnotation(com.codahale.metrics.annotation.CachedGauge.class));
// log.info("Looking up cached gauge method named '{}'", metricName);
// return (CachedGauge<?>) metricRegistry.getGauges().get(metricName);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static String forCountedMethod(Class<?> klass, Member member, Counted annotation) {
// return Util.forCountedMethod(klass, member, annotation);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static String forExceptionMeteredMethod(Class<?> klass, Member member, ExceptionMetered annotation) {
// return Util.forExceptionMeteredMethod(klass, member, annotation);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static Gauge<?> forGaugeField(MetricRegistry metricRegistry, Class<?> clazz, String fieldName) {
// Field field = findField(clazz, fieldName);
// String metricName = forGauge(clazz, field, field.getAnnotation(com.codahale.metrics.annotation.Gauge.class));
// log.info("Looking up gauge field named '{}'", metricName);
// return metricRegistry.getGauges().get(metricName);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static Gauge<?> forGaugeMethod(MetricRegistry metricRegistry, Class<?> clazz, String methodName) {
// Method method = findMethod(clazz, methodName);
// String metricName = forGauge(clazz, method, method.getAnnotation(com.codahale.metrics.annotation.Gauge.class));
// log.info("Looking up gauge method named '{}'", metricName);
// return metricRegistry.getGauges().get(metricName);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static String forMeteredMethod(Class<?> klass, Member member, Metered annotation) {
// return Util.forMeteredMethod(klass, member, annotation);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static String forTimedMethod(Class<?> klass, Member member, Timed annotation) {
// return Util.forTimedMethod(klass, member, annotation);
// }
// Path: src/test/java/com/ryantenney/metrics/spring/MeteredClassTest.java
import static com.ryantenney.metrics.spring.TestUtil.forCachedGaugeMethod;
import static com.ryantenney.metrics.spring.TestUtil.forCountedMethod;
import static com.ryantenney.metrics.spring.TestUtil.forExceptionMeteredMethod;
import static com.ryantenney.metrics.spring.TestUtil.forGaugeField;
import static com.ryantenney.metrics.spring.TestUtil.forGaugeMethod;
import static com.ryantenney.metrics.spring.TestUtil.forMeteredMethod;
import static com.ryantenney.metrics.spring.TestUtil.forTimedMethod;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.codahale.metrics.CachedGauge;
import com.codahale.metrics.Counter;
import com.codahale.metrics.Gauge;
import com.codahale.metrics.Meter;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.RatioGauge;
import com.codahale.metrics.Timer;
import com.codahale.metrics.annotation.Counted;
import com.codahale.metrics.annotation.ExceptionMetered;
import com.codahale.metrics.annotation.Metered;
import com.codahale.metrics.annotation.Timed;
assertEquals(0, exceptionMeteredMethod.getCount());
// doesn't throw an exception
meteredClass.exceptionMeteredMethod(null);
assertEquals(0, exceptionMeteredMethod.getCount());
// throws the wrong exception
try {
meteredClass.exceptionMeteredMethod(RuntimeException.class);
fail();
}
catch (Throwable t) {
assertTrue(t instanceof RuntimeException);
}
assertEquals(0, exceptionMeteredMethod.getCount());
// throws the right exception
try {
meteredClass.exceptionMeteredMethod(BogusException.class);
fail();
}
catch (Throwable t) {
assertTrue(t instanceof BogusException);
}
assertEquals(1, exceptionMeteredMethod.getCount());
}
@Test
public void countedMethod() throws Throwable { | final Counter countedMethod = forCountedMethod(metricRegistry, MeteredClass.class, "countedMethod"); |
ryantenney/metrics-spring | src/test/java/com/ryantenney/metrics/spring/reporter/FakeReporterElementParser.java | // Path: src/test/java/com/ryantenney/metrics/spring/reporter/FakeReporterFactoryBean.java
// public class FakeReporterFactoryBean extends AbstractScheduledReporterFactoryBean<FakeReporter> {
//
// // Required
// public static final String PERIOD = "period";
// public static final String DURATION_UNIT = "duration-unit";
// public static final String RATE_UNIT = "rate-unit";
//
// @Override
// public Class<FakeReporter> getObjectType() {
// return FakeReporter.class;
// }
//
// @Override
// protected FakeReporter createInstance() {
// TimeUnit durationUnit = getProperty(DURATION_UNIT, TimeUnit.class);
// TimeUnit rateUnit = getProperty(RATE_UNIT, TimeUnit.class);
//
// return new FakeReporter(getMetricRegistry(), getMetricFilter(), getPrefix(), rateUnit, durationUnit);
// }
//
// @Override
// protected long getPeriod() {
// return convertDurationString(getProperty(PERIOD));
// }
//
// }
| import static com.ryantenney.metrics.spring.reporter.FakeReporterFactoryBean.*; | /**
* Copyright (C) 2012 Ryan W Tenney (ryan@10e.us)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ryantenney.metrics.spring.reporter;
public class FakeReporterElementParser extends AbstractReporterElementParser {
@Override
public String getType() {
return "fake";
}
@Override
protected Class<?> getBeanClass() { | // Path: src/test/java/com/ryantenney/metrics/spring/reporter/FakeReporterFactoryBean.java
// public class FakeReporterFactoryBean extends AbstractScheduledReporterFactoryBean<FakeReporter> {
//
// // Required
// public static final String PERIOD = "period";
// public static final String DURATION_UNIT = "duration-unit";
// public static final String RATE_UNIT = "rate-unit";
//
// @Override
// public Class<FakeReporter> getObjectType() {
// return FakeReporter.class;
// }
//
// @Override
// protected FakeReporter createInstance() {
// TimeUnit durationUnit = getProperty(DURATION_UNIT, TimeUnit.class);
// TimeUnit rateUnit = getProperty(RATE_UNIT, TimeUnit.class);
//
// return new FakeReporter(getMetricRegistry(), getMetricFilter(), getPrefix(), rateUnit, durationUnit);
// }
//
// @Override
// protected long getPeriod() {
// return convertDurationString(getProperty(PERIOD));
// }
//
// }
// Path: src/test/java/com/ryantenney/metrics/spring/reporter/FakeReporterElementParser.java
import static com.ryantenney.metrics.spring.reporter.FakeReporterFactoryBean.*;
/**
* Copyright (C) 2012 Ryan W Tenney (ryan@10e.us)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ryantenney.metrics.spring.reporter;
public class FakeReporterElementParser extends AbstractReporterElementParser {
@Override
public String getType() {
return "fake";
}
@Override
protected Class<?> getBeanClass() { | return FakeReporterFactoryBean.class; |
ryantenney/metrics-spring | src/main/java/com/ryantenney/metrics/spring/reporter/GangliaReporterElementParser.java | // Path: src/main/java/com/ryantenney/metrics/spring/reporter/GangliaReporterFactoryBean.java
// public class GangliaReporterFactoryBean extends AbstractScheduledReporterFactoryBean<GangliaReporter> {
//
// // Required
// public static final String GROUP = "group";
// public static final String PORT = "port";
// public static final String UDP_MODE = "udp-mode";
// public static final String TTL = "ttl";
// public static final String PERIOD = "period";
//
// // Optional
// public static final String DURATION_UNIT = "duration-unit";
// public static final String RATE_UNIT = "rate-unit";
// public static final String PROTOCOL = "protocol";
// public static final String UUID = "uuid";
// public static final String SPOOF = "spoof";
// public static final String DMAX = "dmax";
// public static final String TMAX = "tmax";
//
// @Override
// public Class<GangliaReporter> getObjectType() {
// return GangliaReporter.class;
// }
//
// @SuppressWarnings("resource")
// @Override
// protected GangliaReporter createInstance() throws Exception {
// final GangliaReporter.Builder reporter = GangliaReporter.forRegistry(getMetricRegistry());
//
// if (hasProperty(DURATION_UNIT)) {
// reporter.convertDurationsTo(getProperty(DURATION_UNIT, TimeUnit.class));
// }
//
// if (hasProperty(RATE_UNIT)) {
// reporter.convertRatesTo(getProperty(RATE_UNIT, TimeUnit.class));
// }
//
// reporter.filter(getMetricFilter());
// reporter.prefixedWith(getPrefix());
//
// if (hasProperty(DMAX)) {
// reporter.withDMax(getProperty(DMAX, Integer.TYPE));
// }
//
// if (hasProperty(TMAX)) {
// reporter.withTMax(getProperty(TMAX, Integer.TYPE));
// }
//
// final GMetric gMetric = new GMetric(getProperty(GROUP), getProperty(PORT, Integer.TYPE), getProperty(UDP_MODE, UDPAddressingMode.class), getProperty(
// TTL, Integer.TYPE), !hasProperty(PROTOCOL) || getProperty(PROTOCOL).contains("3.1"),
// hasProperty(UUID) ? java.util.UUID.fromString(getProperty(UUID)) : null, getProperty(SPOOF));
//
// return reporter.build(gMetric);
// }
//
// @Override
// protected long getPeriod() {
// return convertDurationString(getProperty(PERIOD));
// }
//
// }
| import static com.ryantenney.metrics.spring.reporter.GangliaReporterFactoryBean.*; | /**
* Copyright (C) 2012 Ryan W Tenney (ryan@10e.us)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ryantenney.metrics.spring.reporter;
public class GangliaReporterElementParser extends AbstractReporterElementParser {
private static final String UUID_STRING_REGEX = "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$";
@Override
public String getType() {
return "ganglia";
}
@Override
protected Class<?> getBeanClass() { | // Path: src/main/java/com/ryantenney/metrics/spring/reporter/GangliaReporterFactoryBean.java
// public class GangliaReporterFactoryBean extends AbstractScheduledReporterFactoryBean<GangliaReporter> {
//
// // Required
// public static final String GROUP = "group";
// public static final String PORT = "port";
// public static final String UDP_MODE = "udp-mode";
// public static final String TTL = "ttl";
// public static final String PERIOD = "period";
//
// // Optional
// public static final String DURATION_UNIT = "duration-unit";
// public static final String RATE_UNIT = "rate-unit";
// public static final String PROTOCOL = "protocol";
// public static final String UUID = "uuid";
// public static final String SPOOF = "spoof";
// public static final String DMAX = "dmax";
// public static final String TMAX = "tmax";
//
// @Override
// public Class<GangliaReporter> getObjectType() {
// return GangliaReporter.class;
// }
//
// @SuppressWarnings("resource")
// @Override
// protected GangliaReporter createInstance() throws Exception {
// final GangliaReporter.Builder reporter = GangliaReporter.forRegistry(getMetricRegistry());
//
// if (hasProperty(DURATION_UNIT)) {
// reporter.convertDurationsTo(getProperty(DURATION_UNIT, TimeUnit.class));
// }
//
// if (hasProperty(RATE_UNIT)) {
// reporter.convertRatesTo(getProperty(RATE_UNIT, TimeUnit.class));
// }
//
// reporter.filter(getMetricFilter());
// reporter.prefixedWith(getPrefix());
//
// if (hasProperty(DMAX)) {
// reporter.withDMax(getProperty(DMAX, Integer.TYPE));
// }
//
// if (hasProperty(TMAX)) {
// reporter.withTMax(getProperty(TMAX, Integer.TYPE));
// }
//
// final GMetric gMetric = new GMetric(getProperty(GROUP), getProperty(PORT, Integer.TYPE), getProperty(UDP_MODE, UDPAddressingMode.class), getProperty(
// TTL, Integer.TYPE), !hasProperty(PROTOCOL) || getProperty(PROTOCOL).contains("3.1"),
// hasProperty(UUID) ? java.util.UUID.fromString(getProperty(UUID)) : null, getProperty(SPOOF));
//
// return reporter.build(gMetric);
// }
//
// @Override
// protected long getPeriod() {
// return convertDurationString(getProperty(PERIOD));
// }
//
// }
// Path: src/main/java/com/ryantenney/metrics/spring/reporter/GangliaReporterElementParser.java
import static com.ryantenney.metrics.spring.reporter.GangliaReporterFactoryBean.*;
/**
* Copyright (C) 2012 Ryan W Tenney (ryan@10e.us)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ryantenney.metrics.spring.reporter;
public class GangliaReporterElementParser extends AbstractReporterElementParser {
private static final String UUID_STRING_REGEX = "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$";
@Override
public String getType() {
return "ganglia";
}
@Override
protected Class<?> getBeanClass() { | return GangliaReporterFactoryBean.class; |
ryantenney/metrics-spring | src/test/java/com/ryantenney/metrics/spring/LegacyMetricAnnotationTest.java | // Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// @Deprecated
// static String forLegacyMetricField(Class<?> klass, Member member, com.ryantenney.metrics.annotation.Metric annotation) {
// return Util.forMetricField(klass, member, annotation);
// }
| import com.codahale.metrics.Timer;
import com.codahale.metrics.UniformReservoir;
import com.ryantenney.metrics.annotation.Metric;
import static com.ryantenney.metrics.spring.TestUtil.forLegacyMetricField;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.codahale.metrics.Counter;
import com.codahale.metrics.Histogram;
import com.codahale.metrics.Meter;
import com.codahale.metrics.MetricRegistry; | /**
* Copyright (C) 2012 Ryan W Tenney (ryan@10e.us)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ryantenney.metrics.spring;
@SuppressWarnings("deprecation")
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:legacy-metric-annotation.xml")
public class LegacyMetricAnnotationTest {
@Autowired
@Qualifier("target1")
LegacyMetricAnnotationTest.Target target;
@Autowired
@Qualifier("target2")
LegacyMetricAnnotationTest.Target target2;
@Autowired
MetricRegistry metricRegistry;
@Test
public void targetIsNotNull() throws Exception {
assertNotNull(target);
assertNotNull(target2);
assertNotNull(target.theNameForTheMeter);
assertNotNull(target2.theNameForTheMeter); | // Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// @Deprecated
// static String forLegacyMetricField(Class<?> klass, Member member, com.ryantenney.metrics.annotation.Metric annotation) {
// return Util.forMetricField(klass, member, annotation);
// }
// Path: src/test/java/com/ryantenney/metrics/spring/LegacyMetricAnnotationTest.java
import com.codahale.metrics.Timer;
import com.codahale.metrics.UniformReservoir;
import com.ryantenney.metrics.annotation.Metric;
import static com.ryantenney.metrics.spring.TestUtil.forLegacyMetricField;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.codahale.metrics.Counter;
import com.codahale.metrics.Histogram;
import com.codahale.metrics.Meter;
import com.codahale.metrics.MetricRegistry;
/**
* Copyright (C) 2012 Ryan W Tenney (ryan@10e.us)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ryantenney.metrics.spring;
@SuppressWarnings("deprecation")
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:legacy-metric-annotation.xml")
public class LegacyMetricAnnotationTest {
@Autowired
@Qualifier("target1")
LegacyMetricAnnotationTest.Target target;
@Autowired
@Qualifier("target2")
LegacyMetricAnnotationTest.Target target2;
@Autowired
MetricRegistry metricRegistry;
@Test
public void targetIsNotNull() throws Exception {
assertNotNull(target);
assertNotNull(target2);
assertNotNull(target.theNameForTheMeter);
assertNotNull(target2.theNameForTheMeter); | Meter meter = (Meter) forLegacyMetricField(metricRegistry, LegacyMetricAnnotationTest.Target.class, "theNameForTheMeter"); |
ryantenney/metrics-spring | src/main/java/com/ryantenney/metrics/spring/reporter/GraphiteReporterElementParser.java | // Path: src/main/java/com/ryantenney/metrics/spring/reporter/GraphiteReporterFactoryBean.java
// public class GraphiteReporterFactoryBean extends AbstractScheduledReporterFactoryBean<GraphiteReporter> {
//
// // Required
// public static final String HOST = "host";
// public static final String PORT = "port";
// public static final String PERIOD = "period";
//
// // Optional
// public static final String TRANSPORT = "transport";
// public static final String CHARSET = "charset";
// public static final String CLOCK_REF = "clock-ref";
// public static final String DURATION_UNIT = "duration-unit";
// public static final String RATE_UNIT = "rate-unit";
//
// // Pickle Optional
// public static final String BATCH_SIZE = "batch-size";
//
// // RabbitMQ Required
// public static final String CONNECTION_FACTORY_REF = "connection-factory-ref";
// public static final String EXCHANGE = "exchange";
//
// @Override
// public Class<GraphiteReporter> getObjectType() {
// return GraphiteReporter.class;
// }
//
// @SuppressWarnings("resource")
// @Override
// protected GraphiteReporter createInstance() {
// final GraphiteReporter.Builder reporter = GraphiteReporter.forRegistry(getMetricRegistry());
//
// if (hasProperty(CLOCK_REF)) {
// reporter.withClock(getPropertyRef(CLOCK_REF, Clock.class));
// }
//
// if (hasProperty(DURATION_UNIT)) {
// reporter.convertDurationsTo(getProperty(DURATION_UNIT, TimeUnit.class));
// }
//
// if (hasProperty(RATE_UNIT)) {
// reporter.convertRatesTo(getProperty(RATE_UNIT, TimeUnit.class));
// }
//
// reporter.filter(getMetricFilter());
// reporter.prefixedWith(getPrefix());
//
// final String transport = getProperty(TRANSPORT, "tcp");
// final Charset charset = Charset.forName(getProperty(CHARSET, "UTF-8"));
// final GraphiteSender graphite;
//
// if ("rabbitmq".equals(transport)) {
// ConnectionFactory connectionFactory = getPropertyRef(CONNECTION_FACTORY_REF, ConnectionFactory.class);
// String exchange = getProperty(EXCHANGE);
// graphite = new GraphiteRabbitMQ(connectionFactory, exchange);
// }
// else {
// final String hostname = getProperty(HOST);
// final int port = getProperty(PORT, Integer.TYPE);
//
// if ("tcp".equals(transport)) {
// graphite = new Graphite(hostname, port, SocketFactory.getDefault(), charset);
// }
// else if ("udp".equals(transport)) {
// graphite = new GraphiteUDP(hostname, port);
// }
// else if ("pickle".equals(transport)) {
// graphite = new PickledGraphite(hostname, port, SocketFactory.getDefault(), charset, getProperty(BATCH_SIZE, Integer.TYPE, 100));
// }
// else {
// throw new IllegalArgumentException("Invalid graphite transport: " + transport);
// }
// }
//
// return reporter.build(graphite);
// }
//
// @Override
// protected long getPeriod() {
// return convertDurationString(getProperty(PERIOD));
// }
//
// }
| import static com.ryantenney.metrics.spring.reporter.GraphiteReporterFactoryBean.*; | /**
* Copyright (C) 2012 Ryan W Tenney (ryan@10e.us)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ryantenney.metrics.spring.reporter;
public class GraphiteReporterElementParser extends AbstractReporterElementParser {
@Override
public String getType() {
return "graphite";
}
@Override
protected Class<?> getBeanClass() { | // Path: src/main/java/com/ryantenney/metrics/spring/reporter/GraphiteReporterFactoryBean.java
// public class GraphiteReporterFactoryBean extends AbstractScheduledReporterFactoryBean<GraphiteReporter> {
//
// // Required
// public static final String HOST = "host";
// public static final String PORT = "port";
// public static final String PERIOD = "period";
//
// // Optional
// public static final String TRANSPORT = "transport";
// public static final String CHARSET = "charset";
// public static final String CLOCK_REF = "clock-ref";
// public static final String DURATION_UNIT = "duration-unit";
// public static final String RATE_UNIT = "rate-unit";
//
// // Pickle Optional
// public static final String BATCH_SIZE = "batch-size";
//
// // RabbitMQ Required
// public static final String CONNECTION_FACTORY_REF = "connection-factory-ref";
// public static final String EXCHANGE = "exchange";
//
// @Override
// public Class<GraphiteReporter> getObjectType() {
// return GraphiteReporter.class;
// }
//
// @SuppressWarnings("resource")
// @Override
// protected GraphiteReporter createInstance() {
// final GraphiteReporter.Builder reporter = GraphiteReporter.forRegistry(getMetricRegistry());
//
// if (hasProperty(CLOCK_REF)) {
// reporter.withClock(getPropertyRef(CLOCK_REF, Clock.class));
// }
//
// if (hasProperty(DURATION_UNIT)) {
// reporter.convertDurationsTo(getProperty(DURATION_UNIT, TimeUnit.class));
// }
//
// if (hasProperty(RATE_UNIT)) {
// reporter.convertRatesTo(getProperty(RATE_UNIT, TimeUnit.class));
// }
//
// reporter.filter(getMetricFilter());
// reporter.prefixedWith(getPrefix());
//
// final String transport = getProperty(TRANSPORT, "tcp");
// final Charset charset = Charset.forName(getProperty(CHARSET, "UTF-8"));
// final GraphiteSender graphite;
//
// if ("rabbitmq".equals(transport)) {
// ConnectionFactory connectionFactory = getPropertyRef(CONNECTION_FACTORY_REF, ConnectionFactory.class);
// String exchange = getProperty(EXCHANGE);
// graphite = new GraphiteRabbitMQ(connectionFactory, exchange);
// }
// else {
// final String hostname = getProperty(HOST);
// final int port = getProperty(PORT, Integer.TYPE);
//
// if ("tcp".equals(transport)) {
// graphite = new Graphite(hostname, port, SocketFactory.getDefault(), charset);
// }
// else if ("udp".equals(transport)) {
// graphite = new GraphiteUDP(hostname, port);
// }
// else if ("pickle".equals(transport)) {
// graphite = new PickledGraphite(hostname, port, SocketFactory.getDefault(), charset, getProperty(BATCH_SIZE, Integer.TYPE, 100));
// }
// else {
// throw new IllegalArgumentException("Invalid graphite transport: " + transport);
// }
// }
//
// return reporter.build(graphite);
// }
//
// @Override
// protected long getPeriod() {
// return convertDurationString(getProperty(PERIOD));
// }
//
// }
// Path: src/main/java/com/ryantenney/metrics/spring/reporter/GraphiteReporterElementParser.java
import static com.ryantenney.metrics.spring.reporter.GraphiteReporterFactoryBean.*;
/**
* Copyright (C) 2012 Ryan W Tenney (ryan@10e.us)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ryantenney.metrics.spring.reporter;
public class GraphiteReporterElementParser extends AbstractReporterElementParser {
@Override
public String getType() {
return "graphite";
}
@Override
protected Class<?> getBeanClass() { | return GraphiteReporterFactoryBean.class; |
ryantenney/metrics-spring | src/test/java/com/ryantenney/metrics/spring/EnableMetricsTest.java | // Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static CachedGauge<?> forCachedGaugeMethod(MetricRegistry metricRegistry, Class<?> clazz, String methodName) {
// Method method = findMethod(clazz, methodName);
// String metricName = forCachedGauge(clazz, method, method.getAnnotation(com.codahale.metrics.annotation.CachedGauge.class));
// log.info("Looking up cached gauge method named '{}'", metricName);
// return (CachedGauge<?>) metricRegistry.getGauges().get(metricName);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static String forCountedMethod(Class<?> klass, Member member, Counted annotation) {
// return Util.forCountedMethod(klass, member, annotation);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static String forExceptionMeteredMethod(Class<?> klass, Member member, ExceptionMetered annotation) {
// return Util.forExceptionMeteredMethod(klass, member, annotation);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static Gauge<?> forGaugeField(MetricRegistry metricRegistry, Class<?> clazz, String fieldName) {
// Field field = findField(clazz, fieldName);
// String metricName = forGauge(clazz, field, field.getAnnotation(com.codahale.metrics.annotation.Gauge.class));
// log.info("Looking up gauge field named '{}'", metricName);
// return metricRegistry.getGauges().get(metricName);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static Gauge<?> forGaugeMethod(MetricRegistry metricRegistry, Class<?> clazz, String methodName) {
// Method method = findMethod(clazz, methodName);
// String metricName = forGauge(clazz, method, method.getAnnotation(com.codahale.metrics.annotation.Gauge.class));
// log.info("Looking up gauge method named '{}'", metricName);
// return metricRegistry.getGauges().get(metricName);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static String forMeteredMethod(Class<?> klass, Member member, Metered annotation) {
// return Util.forMeteredMethod(klass, member, annotation);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static String forTimedMethod(Class<?> klass, Member member, Timed annotation) {
// return Util.forTimedMethod(klass, member, annotation);
// }
//
// Path: src/main/java/com/ryantenney/metrics/spring/config/annotation/MetricsConfigurer.java
// public interface MetricsConfigurer {
//
// /**
// * Configure reporters.
// * @param metricRegistry
// */
// void configureReporters(MetricRegistry metricRegistry);
//
// /**
// * Override this method to provide a custom {@code MetricRegistry}.
// * @return
// */
// MetricRegistry getMetricRegistry();
//
// /**
// * Override this method to provide a custom {@code HealthCheckRegistry}.
// * @return
// */
// HealthCheckRegistry getHealthCheckRegistry();
//
// }
| import static com.ryantenney.metrics.spring.TestUtil.forCachedGaugeMethod;
import static com.ryantenney.metrics.spring.TestUtil.forCountedMethod;
import static com.ryantenney.metrics.spring.TestUtil.forExceptionMeteredMethod;
import static com.ryantenney.metrics.spring.TestUtil.forGaugeField;
import static com.ryantenney.metrics.spring.TestUtil.forGaugeMethod;
import static com.ryantenney.metrics.spring.TestUtil.forMeteredMethod;
import static com.ryantenney.metrics.spring.TestUtil.forTimedMethod;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThat;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.aop.support.AopUtils;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.codahale.metrics.CachedGauge;
import com.codahale.metrics.Counter;
import com.codahale.metrics.Gauge;
import com.codahale.metrics.Meter;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.Timer;
import com.codahale.metrics.annotation.Counted;
import com.codahale.metrics.annotation.ExceptionMetered;
import com.codahale.metrics.annotation.Metered;
import com.codahale.metrics.annotation.Timed;
import com.codahale.metrics.health.HealthCheckRegistry;
import com.ryantenney.metrics.spring.config.annotation.EnableMetrics;
import com.ryantenney.metrics.spring.config.annotation.MetricsConfigurer; | public static void afterClass() {
if (applicationContext != null) {
applicationContext.close();
}
}
@Test
public void customRegistries() throws Throwable {
// Assert that the custom registries were used
assertSame(metricRegistry, applicationContext.getBean(MetricRegistry.class));
assertSame(healthCheckRegistry, applicationContext.getBean(HealthCheckRegistry.class));
}
@Test
public void configureReportersInvoked() throws Throwable {
// Verify that the configureReporters method was invoked
assertThat(MetricsConfig.isConfigureReportersInvoked, is(true));
}
@Test
public void beanIsProxied() throws Throwable {
// Assert that the bean has been proxied
TestBean testBean = applicationContext.getBean(TestBean.class);
assertNotNull(testBean);
assertThat(AopUtils.isAopProxy(testBean), is(true));
}
@Test
public void gaugeField() throws Throwable {
// Verify that the Gauge field's value is returned | // Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static CachedGauge<?> forCachedGaugeMethod(MetricRegistry metricRegistry, Class<?> clazz, String methodName) {
// Method method = findMethod(clazz, methodName);
// String metricName = forCachedGauge(clazz, method, method.getAnnotation(com.codahale.metrics.annotation.CachedGauge.class));
// log.info("Looking up cached gauge method named '{}'", metricName);
// return (CachedGauge<?>) metricRegistry.getGauges().get(metricName);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static String forCountedMethod(Class<?> klass, Member member, Counted annotation) {
// return Util.forCountedMethod(klass, member, annotation);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static String forExceptionMeteredMethod(Class<?> klass, Member member, ExceptionMetered annotation) {
// return Util.forExceptionMeteredMethod(klass, member, annotation);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static Gauge<?> forGaugeField(MetricRegistry metricRegistry, Class<?> clazz, String fieldName) {
// Field field = findField(clazz, fieldName);
// String metricName = forGauge(clazz, field, field.getAnnotation(com.codahale.metrics.annotation.Gauge.class));
// log.info("Looking up gauge field named '{}'", metricName);
// return metricRegistry.getGauges().get(metricName);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static Gauge<?> forGaugeMethod(MetricRegistry metricRegistry, Class<?> clazz, String methodName) {
// Method method = findMethod(clazz, methodName);
// String metricName = forGauge(clazz, method, method.getAnnotation(com.codahale.metrics.annotation.Gauge.class));
// log.info("Looking up gauge method named '{}'", metricName);
// return metricRegistry.getGauges().get(metricName);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static String forMeteredMethod(Class<?> klass, Member member, Metered annotation) {
// return Util.forMeteredMethod(klass, member, annotation);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static String forTimedMethod(Class<?> klass, Member member, Timed annotation) {
// return Util.forTimedMethod(klass, member, annotation);
// }
//
// Path: src/main/java/com/ryantenney/metrics/spring/config/annotation/MetricsConfigurer.java
// public interface MetricsConfigurer {
//
// /**
// * Configure reporters.
// * @param metricRegistry
// */
// void configureReporters(MetricRegistry metricRegistry);
//
// /**
// * Override this method to provide a custom {@code MetricRegistry}.
// * @return
// */
// MetricRegistry getMetricRegistry();
//
// /**
// * Override this method to provide a custom {@code HealthCheckRegistry}.
// * @return
// */
// HealthCheckRegistry getHealthCheckRegistry();
//
// }
// Path: src/test/java/com/ryantenney/metrics/spring/EnableMetricsTest.java
import static com.ryantenney.metrics.spring.TestUtil.forCachedGaugeMethod;
import static com.ryantenney.metrics.spring.TestUtil.forCountedMethod;
import static com.ryantenney.metrics.spring.TestUtil.forExceptionMeteredMethod;
import static com.ryantenney.metrics.spring.TestUtil.forGaugeField;
import static com.ryantenney.metrics.spring.TestUtil.forGaugeMethod;
import static com.ryantenney.metrics.spring.TestUtil.forMeteredMethod;
import static com.ryantenney.metrics.spring.TestUtil.forTimedMethod;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThat;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.aop.support.AopUtils;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.codahale.metrics.CachedGauge;
import com.codahale.metrics.Counter;
import com.codahale.metrics.Gauge;
import com.codahale.metrics.Meter;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.Timer;
import com.codahale.metrics.annotation.Counted;
import com.codahale.metrics.annotation.ExceptionMetered;
import com.codahale.metrics.annotation.Metered;
import com.codahale.metrics.annotation.Timed;
import com.codahale.metrics.health.HealthCheckRegistry;
import com.ryantenney.metrics.spring.config.annotation.EnableMetrics;
import com.ryantenney.metrics.spring.config.annotation.MetricsConfigurer;
public static void afterClass() {
if (applicationContext != null) {
applicationContext.close();
}
}
@Test
public void customRegistries() throws Throwable {
// Assert that the custom registries were used
assertSame(metricRegistry, applicationContext.getBean(MetricRegistry.class));
assertSame(healthCheckRegistry, applicationContext.getBean(HealthCheckRegistry.class));
}
@Test
public void configureReportersInvoked() throws Throwable {
// Verify that the configureReporters method was invoked
assertThat(MetricsConfig.isConfigureReportersInvoked, is(true));
}
@Test
public void beanIsProxied() throws Throwable {
// Assert that the bean has been proxied
TestBean testBean = applicationContext.getBean(TestBean.class);
assertNotNull(testBean);
assertThat(AopUtils.isAopProxy(testBean), is(true));
}
@Test
public void gaugeField() throws Throwable {
// Verify that the Gauge field's value is returned | Gauge<Integer> fieldGauge = (Gauge<Integer>) forGaugeField(metricRegistry, TestBean.class, "intGaugeField"); |
ryantenney/metrics-spring | src/test/java/com/ryantenney/metrics/spring/ReporterTest.java | // Path: src/test/java/com/ryantenney/metrics/spring/reporter/FakeReporter.java
// public class FakeReporter extends ScheduledReporter {
//
// private final MetricRegistry registry;
// private final MetricFilter filter;
// private final String prefix;
//
// private long period;
// private int calls = 0;
// private boolean running = false;
//
// public FakeReporter(MetricRegistry registry, MetricFilter filter, String prefix, TimeUnit rateUnit, TimeUnit durationUnit) {
// super(registry, "test-reporter", filter, rateUnit, durationUnit);
// this.registry = registry;
// this.filter = filter;
// this.prefix = prefix;
// }
//
// public MetricRegistry getRegistry() {
// return registry;
// }
//
// public MetricFilter getFilter() {
// return filter;
// }
//
// public String getPrefix() {
// return prefix;
// }
//
// @Override
// public String getRateUnit() {
// return super.getRateUnit();
// }
//
// @Override
// public String getDurationUnit() {
// return super.getDurationUnit();
// }
//
// public long getPeriod() {
// return period;
// }
//
// public int getCalls() {
// return calls;
// }
//
// public boolean isRunning() {
// return running;
// }
//
// @Override
// public void start(final long period, final TimeUnit unit) {
// super.start(period, unit);
// this.period = unit.toNanos(period);
// this.running = true;
// }
//
// @Override
// public void stop() {
// super.stop();
// this.running = false;
// }
//
// @Override
// @SuppressWarnings("rawtypes")
// public void report(SortedMap<String, Gauge> gauges, SortedMap<String, Counter> counters, SortedMap<String, Histogram> histograms,
// SortedMap<String, Meter> meters, SortedMap<String, Timer> timers) {
// calls++;
// }
//
// }
//
// Path: src/main/java/com/ryantenney/metrics/spring/reporter/MetricPrefixSupplier.java
// public interface MetricPrefixSupplier {
//
// String getPrefix();
//
// }
| import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.Collection;
import com.palominolabs.metrics.newrelic.NewRelicReporter;
import org.coursera.metrics.datadog.DatadogReporter;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.codahale.metrics.ConsoleReporter;
import com.codahale.metrics.CsvReporter;
import com.codahale.metrics.JmxReporter;
import com.codahale.metrics.Metric;
import com.codahale.metrics.MetricFilter;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.SharedMetricRegistries;
import com.codahale.metrics.Slf4jReporter;
import com.codahale.metrics.ganglia.GangliaReporter;
import com.codahale.metrics.graphite.GraphiteReporter;
import com.ryantenney.metrics.spring.reporter.FakeReporter;
import com.ryantenney.metrics.spring.reporter.MetricPrefixSupplier;
import static org.hamcrest.Matchers.*; | /**
* Copyright (C) 2012 Ryan W Tenney (ryan@10e.us)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ryantenney.metrics.spring;
public class ReporterTest {
private static final String TEST_PREFIX = "test.i-001a391f";
@SuppressWarnings("resource")
@Test
public void fakeReporters() throws Throwable {
ClassPathXmlApplicationContext ctx = null; | // Path: src/test/java/com/ryantenney/metrics/spring/reporter/FakeReporter.java
// public class FakeReporter extends ScheduledReporter {
//
// private final MetricRegistry registry;
// private final MetricFilter filter;
// private final String prefix;
//
// private long period;
// private int calls = 0;
// private boolean running = false;
//
// public FakeReporter(MetricRegistry registry, MetricFilter filter, String prefix, TimeUnit rateUnit, TimeUnit durationUnit) {
// super(registry, "test-reporter", filter, rateUnit, durationUnit);
// this.registry = registry;
// this.filter = filter;
// this.prefix = prefix;
// }
//
// public MetricRegistry getRegistry() {
// return registry;
// }
//
// public MetricFilter getFilter() {
// return filter;
// }
//
// public String getPrefix() {
// return prefix;
// }
//
// @Override
// public String getRateUnit() {
// return super.getRateUnit();
// }
//
// @Override
// public String getDurationUnit() {
// return super.getDurationUnit();
// }
//
// public long getPeriod() {
// return period;
// }
//
// public int getCalls() {
// return calls;
// }
//
// public boolean isRunning() {
// return running;
// }
//
// @Override
// public void start(final long period, final TimeUnit unit) {
// super.start(period, unit);
// this.period = unit.toNanos(period);
// this.running = true;
// }
//
// @Override
// public void stop() {
// super.stop();
// this.running = false;
// }
//
// @Override
// @SuppressWarnings("rawtypes")
// public void report(SortedMap<String, Gauge> gauges, SortedMap<String, Counter> counters, SortedMap<String, Histogram> histograms,
// SortedMap<String, Meter> meters, SortedMap<String, Timer> timers) {
// calls++;
// }
//
// }
//
// Path: src/main/java/com/ryantenney/metrics/spring/reporter/MetricPrefixSupplier.java
// public interface MetricPrefixSupplier {
//
// String getPrefix();
//
// }
// Path: src/test/java/com/ryantenney/metrics/spring/ReporterTest.java
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.Collection;
import com.palominolabs.metrics.newrelic.NewRelicReporter;
import org.coursera.metrics.datadog.DatadogReporter;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.codahale.metrics.ConsoleReporter;
import com.codahale.metrics.CsvReporter;
import com.codahale.metrics.JmxReporter;
import com.codahale.metrics.Metric;
import com.codahale.metrics.MetricFilter;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.SharedMetricRegistries;
import com.codahale.metrics.Slf4jReporter;
import com.codahale.metrics.ganglia.GangliaReporter;
import com.codahale.metrics.graphite.GraphiteReporter;
import com.ryantenney.metrics.spring.reporter.FakeReporter;
import com.ryantenney.metrics.spring.reporter.MetricPrefixSupplier;
import static org.hamcrest.Matchers.*;
/**
* Copyright (C) 2012 Ryan W Tenney (ryan@10e.us)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ryantenney.metrics.spring;
public class ReporterTest {
private static final String TEST_PREFIX = "test.i-001a391f";
@SuppressWarnings("resource")
@Test
public void fakeReporters() throws Throwable {
ClassPathXmlApplicationContext ctx = null; | FakeReporter one = null; |
ryantenney/metrics-spring | src/test/java/com/ryantenney/metrics/spring/ReporterTest.java | // Path: src/test/java/com/ryantenney/metrics/spring/reporter/FakeReporter.java
// public class FakeReporter extends ScheduledReporter {
//
// private final MetricRegistry registry;
// private final MetricFilter filter;
// private final String prefix;
//
// private long period;
// private int calls = 0;
// private boolean running = false;
//
// public FakeReporter(MetricRegistry registry, MetricFilter filter, String prefix, TimeUnit rateUnit, TimeUnit durationUnit) {
// super(registry, "test-reporter", filter, rateUnit, durationUnit);
// this.registry = registry;
// this.filter = filter;
// this.prefix = prefix;
// }
//
// public MetricRegistry getRegistry() {
// return registry;
// }
//
// public MetricFilter getFilter() {
// return filter;
// }
//
// public String getPrefix() {
// return prefix;
// }
//
// @Override
// public String getRateUnit() {
// return super.getRateUnit();
// }
//
// @Override
// public String getDurationUnit() {
// return super.getDurationUnit();
// }
//
// public long getPeriod() {
// return period;
// }
//
// public int getCalls() {
// return calls;
// }
//
// public boolean isRunning() {
// return running;
// }
//
// @Override
// public void start(final long period, final TimeUnit unit) {
// super.start(period, unit);
// this.period = unit.toNanos(period);
// this.running = true;
// }
//
// @Override
// public void stop() {
// super.stop();
// this.running = false;
// }
//
// @Override
// @SuppressWarnings("rawtypes")
// public void report(SortedMap<String, Gauge> gauges, SortedMap<String, Counter> counters, SortedMap<String, Histogram> histograms,
// SortedMap<String, Meter> meters, SortedMap<String, Timer> timers) {
// calls++;
// }
//
// }
//
// Path: src/main/java/com/ryantenney/metrics/spring/reporter/MetricPrefixSupplier.java
// public interface MetricPrefixSupplier {
//
// String getPrefix();
//
// }
| import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.Collection;
import com.palominolabs.metrics.newrelic.NewRelicReporter;
import org.coursera.metrics.datadog.DatadogReporter;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.codahale.metrics.ConsoleReporter;
import com.codahale.metrics.CsvReporter;
import com.codahale.metrics.JmxReporter;
import com.codahale.metrics.Metric;
import com.codahale.metrics.MetricFilter;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.SharedMetricRegistries;
import com.codahale.metrics.Slf4jReporter;
import com.codahale.metrics.ganglia.GangliaReporter;
import com.codahale.metrics.graphite.GraphiteReporter;
import com.ryantenney.metrics.spring.reporter.FakeReporter;
import com.ryantenney.metrics.spring.reporter.MetricPrefixSupplier;
import static org.hamcrest.Matchers.*; | try {
ctx = new ClassPathXmlApplicationContext("classpath:reporter-placeholder-test.xml");
@SuppressWarnings("resource")
FakeReporter reporter = ctx.getBean(FakeReporter.class);
Assert.assertEquals("nanoseconds", reporter.getDurationUnit());
Assert.assertEquals("hour", reporter.getRateUnit());
Assert.assertEquals(100000000, reporter.getPeriod());
Assert.assertSame(ctx.getBean(BarFilter.class), reporter.getFilter());
}
finally {
if (ctx != null) {
ctx.close();
}
}
}
public static PrintStream testPrintStream() {
return new PrintStream(new ByteArrayOutputStream());
}
public static class BarFilter implements MetricFilter {
@Override
public boolean matches(String name, Metric metric) {
return false;
}
}
| // Path: src/test/java/com/ryantenney/metrics/spring/reporter/FakeReporter.java
// public class FakeReporter extends ScheduledReporter {
//
// private final MetricRegistry registry;
// private final MetricFilter filter;
// private final String prefix;
//
// private long period;
// private int calls = 0;
// private boolean running = false;
//
// public FakeReporter(MetricRegistry registry, MetricFilter filter, String prefix, TimeUnit rateUnit, TimeUnit durationUnit) {
// super(registry, "test-reporter", filter, rateUnit, durationUnit);
// this.registry = registry;
// this.filter = filter;
// this.prefix = prefix;
// }
//
// public MetricRegistry getRegistry() {
// return registry;
// }
//
// public MetricFilter getFilter() {
// return filter;
// }
//
// public String getPrefix() {
// return prefix;
// }
//
// @Override
// public String getRateUnit() {
// return super.getRateUnit();
// }
//
// @Override
// public String getDurationUnit() {
// return super.getDurationUnit();
// }
//
// public long getPeriod() {
// return period;
// }
//
// public int getCalls() {
// return calls;
// }
//
// public boolean isRunning() {
// return running;
// }
//
// @Override
// public void start(final long period, final TimeUnit unit) {
// super.start(period, unit);
// this.period = unit.toNanos(period);
// this.running = true;
// }
//
// @Override
// public void stop() {
// super.stop();
// this.running = false;
// }
//
// @Override
// @SuppressWarnings("rawtypes")
// public void report(SortedMap<String, Gauge> gauges, SortedMap<String, Counter> counters, SortedMap<String, Histogram> histograms,
// SortedMap<String, Meter> meters, SortedMap<String, Timer> timers) {
// calls++;
// }
//
// }
//
// Path: src/main/java/com/ryantenney/metrics/spring/reporter/MetricPrefixSupplier.java
// public interface MetricPrefixSupplier {
//
// String getPrefix();
//
// }
// Path: src/test/java/com/ryantenney/metrics/spring/ReporterTest.java
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.Collection;
import com.palominolabs.metrics.newrelic.NewRelicReporter;
import org.coursera.metrics.datadog.DatadogReporter;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.codahale.metrics.ConsoleReporter;
import com.codahale.metrics.CsvReporter;
import com.codahale.metrics.JmxReporter;
import com.codahale.metrics.Metric;
import com.codahale.metrics.MetricFilter;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.SharedMetricRegistries;
import com.codahale.metrics.Slf4jReporter;
import com.codahale.metrics.ganglia.GangliaReporter;
import com.codahale.metrics.graphite.GraphiteReporter;
import com.ryantenney.metrics.spring.reporter.FakeReporter;
import com.ryantenney.metrics.spring.reporter.MetricPrefixSupplier;
import static org.hamcrest.Matchers.*;
try {
ctx = new ClassPathXmlApplicationContext("classpath:reporter-placeholder-test.xml");
@SuppressWarnings("resource")
FakeReporter reporter = ctx.getBean(FakeReporter.class);
Assert.assertEquals("nanoseconds", reporter.getDurationUnit());
Assert.assertEquals("hour", reporter.getRateUnit());
Assert.assertEquals(100000000, reporter.getPeriod());
Assert.assertSame(ctx.getBean(BarFilter.class), reporter.getFilter());
}
finally {
if (ctx != null) {
ctx.close();
}
}
}
public static PrintStream testPrintStream() {
return new PrintStream(new ByteArrayOutputStream());
}
public static class BarFilter implements MetricFilter {
@Override
public boolean matches(String name, Metric metric) {
return false;
}
}
| public static class TestMetricPrefixSupplier implements MetricPrefixSupplier { |
ryantenney/metrics-spring | src/test/java/com/ryantenney/metrics/spring/MetricAnnotationTest.java | // Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static String forMetricField(Class<?> klass, Member member, Metric annotation) {
// return Util.forMetricField(klass, member, annotation);
// }
| import com.codahale.metrics.Timer;
import com.codahale.metrics.UniformReservoir;
import com.codahale.metrics.annotation.Metric;
import static com.ryantenney.metrics.spring.TestUtil.forMetricField;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.codahale.metrics.Counter;
import com.codahale.metrics.Histogram;
import com.codahale.metrics.Meter;
import com.codahale.metrics.MetricRegistry; | /**
* Copyright (C) 2012 Ryan W Tenney (ryan@10e.us)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ryantenney.metrics.spring;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:metric-annotation.xml")
public class MetricAnnotationTest {
@Autowired
@Qualifier("target1")
MetricAnnotationTest.Target target;
@Autowired
@Qualifier("target2")
MetricAnnotationTest.Target target2;
@Autowired
MetricRegistry metricRegistry;
@Test
public void targetIsNotNull() throws Exception {
assertNotNull(target);
assertNotNull(target2);
assertNotNull(target.theNameForTheMeter);
assertNotNull(target2.theNameForTheMeter); | // Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static String forMetricField(Class<?> klass, Member member, Metric annotation) {
// return Util.forMetricField(klass, member, annotation);
// }
// Path: src/test/java/com/ryantenney/metrics/spring/MetricAnnotationTest.java
import com.codahale.metrics.Timer;
import com.codahale.metrics.UniformReservoir;
import com.codahale.metrics.annotation.Metric;
import static com.ryantenney.metrics.spring.TestUtil.forMetricField;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.codahale.metrics.Counter;
import com.codahale.metrics.Histogram;
import com.codahale.metrics.Meter;
import com.codahale.metrics.MetricRegistry;
/**
* Copyright (C) 2012 Ryan W Tenney (ryan@10e.us)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ryantenney.metrics.spring;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:metric-annotation.xml")
public class MetricAnnotationTest {
@Autowired
@Qualifier("target1")
MetricAnnotationTest.Target target;
@Autowired
@Qualifier("target2")
MetricAnnotationTest.Target target2;
@Autowired
MetricRegistry metricRegistry;
@Test
public void targetIsNotNull() throws Exception {
assertNotNull(target);
assertNotNull(target2);
assertNotNull(target.theNameForTheMeter);
assertNotNull(target2.theNameForTheMeter); | Meter meter = (Meter) forMetricField(metricRegistry, MetricAnnotationTest.Target.class, "theNameForTheMeter"); |
ryantenney/metrics-spring | src/main/java/com/ryantenney/metrics/spring/reporter/Slf4jReporterElementParser.java | // Path: src/main/java/com/ryantenney/metrics/spring/reporter/Slf4jReporterFactoryBean.java
// public class Slf4jReporterFactoryBean extends AbstractScheduledReporterFactoryBean<Slf4jReporter> {
//
// // Required
// public static final String PERIOD = "period";
//
// // Optional
// public static final String DURATION_UNIT = "duration-unit";
// public static final String RATE_UNIT = "rate-unit";
// public static final String MARKER = "marker";
// public static final String LOGGER = "logger";
// public static final String LEVEL = "level";
//
// @Override
// public Class<Slf4jReporter> getObjectType() {
// return Slf4jReporter.class;
// }
//
// @Override
// protected Slf4jReporter createInstance() {
// final Slf4jReporter.Builder reporter = Slf4jReporter.forRegistry(getMetricRegistry());
//
// if (hasProperty(DURATION_UNIT)) {
// reporter.convertDurationsTo(getProperty(DURATION_UNIT, TimeUnit.class));
// }
//
// if (hasProperty(RATE_UNIT)) {
// reporter.convertRatesTo(getProperty(RATE_UNIT, TimeUnit.class));
// }
//
// reporter.filter(getMetricFilter());
// reporter.prefixedWith(getPrefix());
//
// if (hasProperty(MARKER)) {
// reporter.markWith(MarkerFactory.getMarker(getProperty(MARKER)));
// }
//
// if (hasProperty(LOGGER)) {
// reporter.outputTo(LoggerFactory.getLogger(getProperty(LOGGER)));
// }
//
// if (hasProperty(LEVEL)) {
// reporter.withLoggingLevel(getProperty(LEVEL, LoggingLevel.class));
// }
//
// return reporter.build();
// }
//
// @Override
// protected long getPeriod() {
// return convertDurationString(getProperty(PERIOD));
// }
//
// }
| import static com.ryantenney.metrics.spring.reporter.Slf4jReporterFactoryBean.*; | /**
* Copyright (C) 2012 Ryan W Tenney (ryan@10e.us)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ryantenney.metrics.spring.reporter;
public class Slf4jReporterElementParser extends AbstractReporterElementParser {
protected static final String LOG_LEVEL_STRING_REGEX = "^(?:TRACE|DEBUG|INFO|WARN|ERROR)$";
@Override
public String getType() {
return "slf4j";
}
@Override
protected Class<?> getBeanClass() { | // Path: src/main/java/com/ryantenney/metrics/spring/reporter/Slf4jReporterFactoryBean.java
// public class Slf4jReporterFactoryBean extends AbstractScheduledReporterFactoryBean<Slf4jReporter> {
//
// // Required
// public static final String PERIOD = "period";
//
// // Optional
// public static final String DURATION_UNIT = "duration-unit";
// public static final String RATE_UNIT = "rate-unit";
// public static final String MARKER = "marker";
// public static final String LOGGER = "logger";
// public static final String LEVEL = "level";
//
// @Override
// public Class<Slf4jReporter> getObjectType() {
// return Slf4jReporter.class;
// }
//
// @Override
// protected Slf4jReporter createInstance() {
// final Slf4jReporter.Builder reporter = Slf4jReporter.forRegistry(getMetricRegistry());
//
// if (hasProperty(DURATION_UNIT)) {
// reporter.convertDurationsTo(getProperty(DURATION_UNIT, TimeUnit.class));
// }
//
// if (hasProperty(RATE_UNIT)) {
// reporter.convertRatesTo(getProperty(RATE_UNIT, TimeUnit.class));
// }
//
// reporter.filter(getMetricFilter());
// reporter.prefixedWith(getPrefix());
//
// if (hasProperty(MARKER)) {
// reporter.markWith(MarkerFactory.getMarker(getProperty(MARKER)));
// }
//
// if (hasProperty(LOGGER)) {
// reporter.outputTo(LoggerFactory.getLogger(getProperty(LOGGER)));
// }
//
// if (hasProperty(LEVEL)) {
// reporter.withLoggingLevel(getProperty(LEVEL, LoggingLevel.class));
// }
//
// return reporter.build();
// }
//
// @Override
// protected long getPeriod() {
// return convertDurationString(getProperty(PERIOD));
// }
//
// }
// Path: src/main/java/com/ryantenney/metrics/spring/reporter/Slf4jReporterElementParser.java
import static com.ryantenney.metrics.spring.reporter.Slf4jReporterFactoryBean.*;
/**
* Copyright (C) 2012 Ryan W Tenney (ryan@10e.us)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ryantenney.metrics.spring.reporter;
public class Slf4jReporterElementParser extends AbstractReporterElementParser {
protected static final String LOG_LEVEL_STRING_REGEX = "^(?:TRACE|DEBUG|INFO|WARN|ERROR)$";
@Override
public String getType() {
return "slf4j";
}
@Override
protected Class<?> getBeanClass() { | return Slf4jReporterFactoryBean.class; |
ryantenney/metrics-spring | src/test/java/com/ryantenney/metrics/spring/MeteredClassImpementsInterfaceTest.java | // Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static String forCountedMethod(Class<?> klass, Member member, Counted annotation) {
// return Util.forCountedMethod(klass, member, annotation);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static String forMeteredMethod(Class<?> klass, Member member, Metered annotation) {
// return Util.forMeteredMethod(klass, member, annotation);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static String forTimedMethod(Class<?> klass, Member member, Timed annotation) {
// return Util.forTimedMethod(klass, member, annotation);
// }
| import com.codahale.metrics.Timer;
import com.codahale.metrics.annotation.Counted;
import com.codahale.metrics.annotation.ExceptionMetered;
import com.codahale.metrics.annotation.Metered;
import com.codahale.metrics.annotation.Timed;
import static com.ryantenney.metrics.spring.TestUtil.forCountedMethod;
import static com.ryantenney.metrics.spring.TestUtil.forMeteredMethod;
import static com.ryantenney.metrics.spring.TestUtil.forTimedMethod;
import static org.junit.Assert.assertEquals;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.codahale.metrics.Counter;
import com.codahale.metrics.Meter;
import com.codahale.metrics.MetricRegistry; | public void testTimedMethod() {
ctx.getBean(MeteredClassInterface.class).timedMethod();
Assert.assertFalse("Metrics should be registered", this.metricRegistry.getTimers().isEmpty());
}
@Test
public void testMeteredMethod() {
ctx.getBean(MeteredClassInterface.class).meteredMethod();
Assert.assertFalse("Metrics should be registered", this.metricRegistry.getMeters().isEmpty());
}
@Test
public void testCountedMethod() {
ctx.getBean(MeteredClassInterface.class).countedMethod(null);
Assert.assertFalse("Metrics should be registered", this.metricRegistry.getCounters().isEmpty());
}
@Test(expected = BogusException.class)
public void testExceptionMeteredMethod() throws Throwable {
try {
ctx.getBean(MeteredClassInterface.class).exceptionMeteredMethod();
}
catch (Throwable t) {
Assert.assertFalse("Metrics should be registered", this.metricRegistry.getMeters().isEmpty());
throw t;
}
}
@Test
public void timedMethod() throws Throwable { | // Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static String forCountedMethod(Class<?> klass, Member member, Counted annotation) {
// return Util.forCountedMethod(klass, member, annotation);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static String forMeteredMethod(Class<?> klass, Member member, Metered annotation) {
// return Util.forMeteredMethod(klass, member, annotation);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static String forTimedMethod(Class<?> klass, Member member, Timed annotation) {
// return Util.forTimedMethod(klass, member, annotation);
// }
// Path: src/test/java/com/ryantenney/metrics/spring/MeteredClassImpementsInterfaceTest.java
import com.codahale.metrics.Timer;
import com.codahale.metrics.annotation.Counted;
import com.codahale.metrics.annotation.ExceptionMetered;
import com.codahale.metrics.annotation.Metered;
import com.codahale.metrics.annotation.Timed;
import static com.ryantenney.metrics.spring.TestUtil.forCountedMethod;
import static com.ryantenney.metrics.spring.TestUtil.forMeteredMethod;
import static com.ryantenney.metrics.spring.TestUtil.forTimedMethod;
import static org.junit.Assert.assertEquals;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.codahale.metrics.Counter;
import com.codahale.metrics.Meter;
import com.codahale.metrics.MetricRegistry;
public void testTimedMethod() {
ctx.getBean(MeteredClassInterface.class).timedMethod();
Assert.assertFalse("Metrics should be registered", this.metricRegistry.getTimers().isEmpty());
}
@Test
public void testMeteredMethod() {
ctx.getBean(MeteredClassInterface.class).meteredMethod();
Assert.assertFalse("Metrics should be registered", this.metricRegistry.getMeters().isEmpty());
}
@Test
public void testCountedMethod() {
ctx.getBean(MeteredClassInterface.class).countedMethod(null);
Assert.assertFalse("Metrics should be registered", this.metricRegistry.getCounters().isEmpty());
}
@Test(expected = BogusException.class)
public void testExceptionMeteredMethod() throws Throwable {
try {
ctx.getBean(MeteredClassInterface.class).exceptionMeteredMethod();
}
catch (Throwable t) {
Assert.assertFalse("Metrics should be registered", this.metricRegistry.getMeters().isEmpty());
throw t;
}
}
@Test
public void timedMethod() throws Throwable { | Timer timedMethod = forTimedMethod(metricRegistry, MeteredClassImpl.class, "timedMethod"); |
ryantenney/metrics-spring | src/test/java/com/ryantenney/metrics/spring/MeteredClassImpementsInterfaceTest.java | // Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static String forCountedMethod(Class<?> klass, Member member, Counted annotation) {
// return Util.forCountedMethod(klass, member, annotation);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static String forMeteredMethod(Class<?> klass, Member member, Metered annotation) {
// return Util.forMeteredMethod(klass, member, annotation);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static String forTimedMethod(Class<?> klass, Member member, Timed annotation) {
// return Util.forTimedMethod(klass, member, annotation);
// }
| import com.codahale.metrics.Timer;
import com.codahale.metrics.annotation.Counted;
import com.codahale.metrics.annotation.ExceptionMetered;
import com.codahale.metrics.annotation.Metered;
import com.codahale.metrics.annotation.Timed;
import static com.ryantenney.metrics.spring.TestUtil.forCountedMethod;
import static com.ryantenney.metrics.spring.TestUtil.forMeteredMethod;
import static com.ryantenney.metrics.spring.TestUtil.forTimedMethod;
import static org.junit.Assert.assertEquals;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.codahale.metrics.Counter;
import com.codahale.metrics.Meter;
import com.codahale.metrics.MetricRegistry; |
@Test
public void testCountedMethod() {
ctx.getBean(MeteredClassInterface.class).countedMethod(null);
Assert.assertFalse("Metrics should be registered", this.metricRegistry.getCounters().isEmpty());
}
@Test(expected = BogusException.class)
public void testExceptionMeteredMethod() throws Throwable {
try {
ctx.getBean(MeteredClassInterface.class).exceptionMeteredMethod();
}
catch (Throwable t) {
Assert.assertFalse("Metrics should be registered", this.metricRegistry.getMeters().isEmpty());
throw t;
}
}
@Test
public void timedMethod() throws Throwable {
Timer timedMethod = forTimedMethod(metricRegistry, MeteredClassImpl.class, "timedMethod");
assertEquals(0, timedMethod.getCount());
meteredClass.timedMethod();
assertEquals(1, timedMethod.getCount());
}
@Test
public void meteredMethod() throws Throwable { | // Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static String forCountedMethod(Class<?> klass, Member member, Counted annotation) {
// return Util.forCountedMethod(klass, member, annotation);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static String forMeteredMethod(Class<?> klass, Member member, Metered annotation) {
// return Util.forMeteredMethod(klass, member, annotation);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static String forTimedMethod(Class<?> klass, Member member, Timed annotation) {
// return Util.forTimedMethod(klass, member, annotation);
// }
// Path: src/test/java/com/ryantenney/metrics/spring/MeteredClassImpementsInterfaceTest.java
import com.codahale.metrics.Timer;
import com.codahale.metrics.annotation.Counted;
import com.codahale.metrics.annotation.ExceptionMetered;
import com.codahale.metrics.annotation.Metered;
import com.codahale.metrics.annotation.Timed;
import static com.ryantenney.metrics.spring.TestUtil.forCountedMethod;
import static com.ryantenney.metrics.spring.TestUtil.forMeteredMethod;
import static com.ryantenney.metrics.spring.TestUtil.forTimedMethod;
import static org.junit.Assert.assertEquals;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.codahale.metrics.Counter;
import com.codahale.metrics.Meter;
import com.codahale.metrics.MetricRegistry;
@Test
public void testCountedMethod() {
ctx.getBean(MeteredClassInterface.class).countedMethod(null);
Assert.assertFalse("Metrics should be registered", this.metricRegistry.getCounters().isEmpty());
}
@Test(expected = BogusException.class)
public void testExceptionMeteredMethod() throws Throwable {
try {
ctx.getBean(MeteredClassInterface.class).exceptionMeteredMethod();
}
catch (Throwable t) {
Assert.assertFalse("Metrics should be registered", this.metricRegistry.getMeters().isEmpty());
throw t;
}
}
@Test
public void timedMethod() throws Throwable {
Timer timedMethod = forTimedMethod(metricRegistry, MeteredClassImpl.class, "timedMethod");
assertEquals(0, timedMethod.getCount());
meteredClass.timedMethod();
assertEquals(1, timedMethod.getCount());
}
@Test
public void meteredMethod() throws Throwable { | Meter meteredMethod = forMeteredMethod(metricRegistry, MeteredClassImpl.class, "meteredMethod"); |
ryantenney/metrics-spring | src/test/java/com/ryantenney/metrics/spring/MeteredClassImpementsInterfaceTest.java | // Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static String forCountedMethod(Class<?> klass, Member member, Counted annotation) {
// return Util.forCountedMethod(klass, member, annotation);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static String forMeteredMethod(Class<?> klass, Member member, Metered annotation) {
// return Util.forMeteredMethod(klass, member, annotation);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static String forTimedMethod(Class<?> klass, Member member, Timed annotation) {
// return Util.forTimedMethod(klass, member, annotation);
// }
| import com.codahale.metrics.Timer;
import com.codahale.metrics.annotation.Counted;
import com.codahale.metrics.annotation.ExceptionMetered;
import com.codahale.metrics.annotation.Metered;
import com.codahale.metrics.annotation.Timed;
import static com.ryantenney.metrics.spring.TestUtil.forCountedMethod;
import static com.ryantenney.metrics.spring.TestUtil.forMeteredMethod;
import static com.ryantenney.metrics.spring.TestUtil.forTimedMethod;
import static org.junit.Assert.assertEquals;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.codahale.metrics.Counter;
import com.codahale.metrics.Meter;
import com.codahale.metrics.MetricRegistry; | ctx.getBean(MeteredClassInterface.class).exceptionMeteredMethod();
}
catch (Throwable t) {
Assert.assertFalse("Metrics should be registered", this.metricRegistry.getMeters().isEmpty());
throw t;
}
}
@Test
public void timedMethod() throws Throwable {
Timer timedMethod = forTimedMethod(metricRegistry, MeteredClassImpl.class, "timedMethod");
assertEquals(0, timedMethod.getCount());
meteredClass.timedMethod();
assertEquals(1, timedMethod.getCount());
}
@Test
public void meteredMethod() throws Throwable {
Meter meteredMethod = forMeteredMethod(metricRegistry, MeteredClassImpl.class, "meteredMethod");
assertEquals(0, meteredMethod.getCount());
meteredClass.meteredMethod();
assertEquals(1, meteredMethod.getCount());
}
@Test
public void countedMethod() throws Throwable { | // Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static String forCountedMethod(Class<?> klass, Member member, Counted annotation) {
// return Util.forCountedMethod(klass, member, annotation);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static String forMeteredMethod(Class<?> klass, Member member, Metered annotation) {
// return Util.forMeteredMethod(klass, member, annotation);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// static String forTimedMethod(Class<?> klass, Member member, Timed annotation) {
// return Util.forTimedMethod(klass, member, annotation);
// }
// Path: src/test/java/com/ryantenney/metrics/spring/MeteredClassImpementsInterfaceTest.java
import com.codahale.metrics.Timer;
import com.codahale.metrics.annotation.Counted;
import com.codahale.metrics.annotation.ExceptionMetered;
import com.codahale.metrics.annotation.Metered;
import com.codahale.metrics.annotation.Timed;
import static com.ryantenney.metrics.spring.TestUtil.forCountedMethod;
import static com.ryantenney.metrics.spring.TestUtil.forMeteredMethod;
import static com.ryantenney.metrics.spring.TestUtil.forTimedMethod;
import static org.junit.Assert.assertEquals;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.codahale.metrics.Counter;
import com.codahale.metrics.Meter;
import com.codahale.metrics.MetricRegistry;
ctx.getBean(MeteredClassInterface.class).exceptionMeteredMethod();
}
catch (Throwable t) {
Assert.assertFalse("Metrics should be registered", this.metricRegistry.getMeters().isEmpty());
throw t;
}
}
@Test
public void timedMethod() throws Throwable {
Timer timedMethod = forTimedMethod(metricRegistry, MeteredClassImpl.class, "timedMethod");
assertEquals(0, timedMethod.getCount());
meteredClass.timedMethod();
assertEquals(1, timedMethod.getCount());
}
@Test
public void meteredMethod() throws Throwable {
Meter meteredMethod = forMeteredMethod(metricRegistry, MeteredClassImpl.class, "meteredMethod");
assertEquals(0, meteredMethod.getCount());
meteredClass.meteredMethod();
assertEquals(1, meteredMethod.getCount());
}
@Test
public void countedMethod() throws Throwable { | final Counter countedMethod = forCountedMethod(metricRegistry, MeteredClassImpl.class, "countedMethod"); |
ryantenney/metrics-spring | src/main/java/com/ryantenney/metrics/spring/config/AnnotationDrivenBeanDefinitionParser.java | // Path: src/main/java/com/ryantenney/metrics/spring/MetricsBeanPostProcessorFactory.java
// public class MetricsBeanPostProcessorFactory {
//
// private MetricsBeanPostProcessorFactory() {}
//
// public static AdvisingBeanPostProcessor exceptionMetered(final MetricRegistry metricRegistry, final ProxyConfig proxyConfig) {
// return new AdvisingBeanPostProcessor(ExceptionMeteredMethodInterceptor.POINTCUT, ExceptionMeteredMethodInterceptor.adviceFactory(metricRegistry),
// proxyConfig);
// }
//
// public static AdvisingBeanPostProcessor metered(final MetricRegistry metricRegistry, final ProxyConfig proxyConfig) {
// return new AdvisingBeanPostProcessor(MeteredMethodInterceptor.POINTCUT, MeteredMethodInterceptor.adviceFactory(metricRegistry), proxyConfig);
// }
//
// public static AdvisingBeanPostProcessor timed(final MetricRegistry metricRegistry, final ProxyConfig proxyConfig) {
// return new AdvisingBeanPostProcessor(TimedMethodInterceptor.POINTCUT, TimedMethodInterceptor.adviceFactory(metricRegistry), proxyConfig);
// }
//
// public static AdvisingBeanPostProcessor counted(final MetricRegistry metricRegistry, final ProxyConfig proxyConfig) {
// return new AdvisingBeanPostProcessor(CountedMethodInterceptor.POINTCUT, CountedMethodInterceptor.adviceFactory(metricRegistry), proxyConfig);
// }
//
// public static GaugeFieldAnnotationBeanPostProcessor gaugeField(final MetricRegistry metricRegistry) {
// return new GaugeFieldAnnotationBeanPostProcessor(metricRegistry);
// }
//
// public static GaugeMethodAnnotationBeanPostProcessor gaugeMethod(final MetricRegistry metricRegistry) {
// return new GaugeMethodAnnotationBeanPostProcessor(metricRegistry);
// }
//
// public static CachedGaugeAnnotationBeanPostProcessor cachedGauge(final MetricRegistry metricRegistry) {
// return new CachedGaugeAnnotationBeanPostProcessor(metricRegistry);
// }
//
// public static MetricAnnotationBeanPostProcessor metric(final MetricRegistry metricRegistry) {
// return new MetricAnnotationBeanPostProcessor(metricRegistry);
// }
//
// public static HealthCheckBeanPostProcessor healthCheck(final HealthCheckRegistry healthRegistry) {
// return new HealthCheckBeanPostProcessor(healthRegistry);
// }
//
// @Deprecated
// public static AdvisingBeanPostProcessor legacyCounted(final MetricRegistry metricRegistry, final ProxyConfig proxyConfig) {
// return new AdvisingBeanPostProcessor(LegacyCountedMethodInterceptor.POINTCUT, LegacyCountedMethodInterceptor.adviceFactory(metricRegistry), proxyConfig);
// }
//
// @Deprecated
// public static LegacyCachedGaugeAnnotationBeanPostProcessor legacyCachedGauge(final MetricRegistry metricRegistry) {
// return new LegacyCachedGaugeAnnotationBeanPostProcessor(metricRegistry);
// }
//
// @Deprecated
// public static LegacyMetricAnnotationBeanPostProcessor legacyMetric(final MetricRegistry metricRegistry) {
// return new LegacyMetricAnnotationBeanPostProcessor(metricRegistry);
// }
//
// }
| import com.ryantenney.metrics.spring.MetricsBeanPostProcessorFactory;
import static org.springframework.beans.factory.config.BeanDefinition.ROLE_APPLICATION;
import static org.springframework.beans.factory.config.BeanDefinition.ROLE_INFRASTRUCTURE;
import org.springframework.aop.framework.ProxyConfig;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.parsing.BeanComponentDefinition;
import org.springframework.beans.factory.parsing.CompositeComponentDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.xml.BeanDefinitionParser;
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.util.StringUtils;
import org.w3c.dom.Element;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.health.HealthCheckRegistry; | /**
* Copyright (C) 2012 Ryan W Tenney (ryan@10e.us)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ryantenney.metrics.spring.config;
class AnnotationDrivenBeanDefinitionParser implements BeanDefinitionParser {
@Override
public BeanDefinition parse(Element element, ParserContext parserContext) {
final Object source = parserContext.extractSource(element);
final CompositeComponentDefinition compDefinition = new CompositeComponentDefinition(element.getTagName(), source);
parserContext.pushContainingComponent(compDefinition);
String metricsBeanName = element.getAttribute("metric-registry");
if (!StringUtils.hasText(metricsBeanName)) {
metricsBeanName = registerComponent(parserContext, build(MetricRegistry.class, source, ROLE_APPLICATION));
}
String healthCheckBeanName = element.getAttribute("health-check-registry");
if (!StringUtils.hasText(healthCheckBeanName)) {
healthCheckBeanName = registerComponent(parserContext, build(HealthCheckRegistry.class, source, ROLE_APPLICATION));
}
final ProxyConfig proxyConfig = new ProxyConfig();
if (StringUtils.hasText(element.getAttribute("expose-proxy"))) {
proxyConfig.setExposeProxy(Boolean.valueOf(element.getAttribute("expose-proxy")));
}
if (StringUtils.hasText(element.getAttribute("proxy-target-class"))) {
proxyConfig.setProxyTargetClass(Boolean.valueOf(element.getAttribute("proxy-target-class")));
}
//@formatter:off
registerComponent(parserContext, | // Path: src/main/java/com/ryantenney/metrics/spring/MetricsBeanPostProcessorFactory.java
// public class MetricsBeanPostProcessorFactory {
//
// private MetricsBeanPostProcessorFactory() {}
//
// public static AdvisingBeanPostProcessor exceptionMetered(final MetricRegistry metricRegistry, final ProxyConfig proxyConfig) {
// return new AdvisingBeanPostProcessor(ExceptionMeteredMethodInterceptor.POINTCUT, ExceptionMeteredMethodInterceptor.adviceFactory(metricRegistry),
// proxyConfig);
// }
//
// public static AdvisingBeanPostProcessor metered(final MetricRegistry metricRegistry, final ProxyConfig proxyConfig) {
// return new AdvisingBeanPostProcessor(MeteredMethodInterceptor.POINTCUT, MeteredMethodInterceptor.adviceFactory(metricRegistry), proxyConfig);
// }
//
// public static AdvisingBeanPostProcessor timed(final MetricRegistry metricRegistry, final ProxyConfig proxyConfig) {
// return new AdvisingBeanPostProcessor(TimedMethodInterceptor.POINTCUT, TimedMethodInterceptor.adviceFactory(metricRegistry), proxyConfig);
// }
//
// public static AdvisingBeanPostProcessor counted(final MetricRegistry metricRegistry, final ProxyConfig proxyConfig) {
// return new AdvisingBeanPostProcessor(CountedMethodInterceptor.POINTCUT, CountedMethodInterceptor.adviceFactory(metricRegistry), proxyConfig);
// }
//
// public static GaugeFieldAnnotationBeanPostProcessor gaugeField(final MetricRegistry metricRegistry) {
// return new GaugeFieldAnnotationBeanPostProcessor(metricRegistry);
// }
//
// public static GaugeMethodAnnotationBeanPostProcessor gaugeMethod(final MetricRegistry metricRegistry) {
// return new GaugeMethodAnnotationBeanPostProcessor(metricRegistry);
// }
//
// public static CachedGaugeAnnotationBeanPostProcessor cachedGauge(final MetricRegistry metricRegistry) {
// return new CachedGaugeAnnotationBeanPostProcessor(metricRegistry);
// }
//
// public static MetricAnnotationBeanPostProcessor metric(final MetricRegistry metricRegistry) {
// return new MetricAnnotationBeanPostProcessor(metricRegistry);
// }
//
// public static HealthCheckBeanPostProcessor healthCheck(final HealthCheckRegistry healthRegistry) {
// return new HealthCheckBeanPostProcessor(healthRegistry);
// }
//
// @Deprecated
// public static AdvisingBeanPostProcessor legacyCounted(final MetricRegistry metricRegistry, final ProxyConfig proxyConfig) {
// return new AdvisingBeanPostProcessor(LegacyCountedMethodInterceptor.POINTCUT, LegacyCountedMethodInterceptor.adviceFactory(metricRegistry), proxyConfig);
// }
//
// @Deprecated
// public static LegacyCachedGaugeAnnotationBeanPostProcessor legacyCachedGauge(final MetricRegistry metricRegistry) {
// return new LegacyCachedGaugeAnnotationBeanPostProcessor(metricRegistry);
// }
//
// @Deprecated
// public static LegacyMetricAnnotationBeanPostProcessor legacyMetric(final MetricRegistry metricRegistry) {
// return new LegacyMetricAnnotationBeanPostProcessor(metricRegistry);
// }
//
// }
// Path: src/main/java/com/ryantenney/metrics/spring/config/AnnotationDrivenBeanDefinitionParser.java
import com.ryantenney.metrics.spring.MetricsBeanPostProcessorFactory;
import static org.springframework.beans.factory.config.BeanDefinition.ROLE_APPLICATION;
import static org.springframework.beans.factory.config.BeanDefinition.ROLE_INFRASTRUCTURE;
import org.springframework.aop.framework.ProxyConfig;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.parsing.BeanComponentDefinition;
import org.springframework.beans.factory.parsing.CompositeComponentDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.xml.BeanDefinitionParser;
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.util.StringUtils;
import org.w3c.dom.Element;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.health.HealthCheckRegistry;
/**
* Copyright (C) 2012 Ryan W Tenney (ryan@10e.us)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ryantenney.metrics.spring.config;
class AnnotationDrivenBeanDefinitionParser implements BeanDefinitionParser {
@Override
public BeanDefinition parse(Element element, ParserContext parserContext) {
final Object source = parserContext.extractSource(element);
final CompositeComponentDefinition compDefinition = new CompositeComponentDefinition(element.getTagName(), source);
parserContext.pushContainingComponent(compDefinition);
String metricsBeanName = element.getAttribute("metric-registry");
if (!StringUtils.hasText(metricsBeanName)) {
metricsBeanName = registerComponent(parserContext, build(MetricRegistry.class, source, ROLE_APPLICATION));
}
String healthCheckBeanName = element.getAttribute("health-check-registry");
if (!StringUtils.hasText(healthCheckBeanName)) {
healthCheckBeanName = registerComponent(parserContext, build(HealthCheckRegistry.class, source, ROLE_APPLICATION));
}
final ProxyConfig proxyConfig = new ProxyConfig();
if (StringUtils.hasText(element.getAttribute("expose-proxy"))) {
proxyConfig.setExposeProxy(Boolean.valueOf(element.getAttribute("expose-proxy")));
}
if (StringUtils.hasText(element.getAttribute("proxy-target-class"))) {
proxyConfig.setProxyTargetClass(Boolean.valueOf(element.getAttribute("proxy-target-class")));
}
//@formatter:off
registerComponent(parserContext, | build(MetricsBeanPostProcessorFactory.class, source, ROLE_INFRASTRUCTURE) |
ryantenney/metrics-spring | src/test/java/com/ryantenney/metrics/spring/LegacyAnnotationMeteredClassTest.java | // Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// @Deprecated
// static CachedGauge<?> forLegacyCachedGaugeMethod(MetricRegistry metricRegistry, Class<?> clazz, String methodName) {
// Method method = findMethod(clazz, methodName);
// String metricName = forLegacyCachedGauge(clazz, method, method.getAnnotation(com.ryantenney.metrics.annotation.CachedGauge.class));
// log.info("Looking up cached gauge method named '{}'", metricName);
// return (CachedGauge<?>) metricRegistry.getGauges().get(metricName);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// @Deprecated
// static String forLegacyCountedMethod(Class<?> klass, Member member, com.ryantenney.metrics.annotation.Counted annotation) {
// return Util.forCountedMethod(klass, member, annotation);
// }
| import com.ryantenney.metrics.annotation.Counted;
import static com.ryantenney.metrics.spring.TestUtil.forLegacyCachedGaugeMethod;
import static com.ryantenney.metrics.spring.TestUtil.forLegacyCountedMethod;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.codahale.metrics.CachedGauge;
import com.codahale.metrics.Counter;
import com.codahale.metrics.MetricRegistry; | /**
* Copyright (C) 2012 Ryan W Tenney (ryan@10e.us)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ryantenney.metrics.spring;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:legacy-annotation-metered-class.xml")
@SuppressWarnings("deprecation")
public class LegacyAnnotationMeteredClassTest {
@Autowired
LegacyMeteredClass meteredClass;
MetricRegistry metricRegistry;
@Autowired
public void setMetricRegistry(MetricRegistry metricRegistry) {
this.metricRegistry = metricRegistry;
this.metricRegistry.addListener(new LoggingMetricRegistryListener());
}
@Test
public void gauges() { | // Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// @Deprecated
// static CachedGauge<?> forLegacyCachedGaugeMethod(MetricRegistry metricRegistry, Class<?> clazz, String methodName) {
// Method method = findMethod(clazz, methodName);
// String metricName = forLegacyCachedGauge(clazz, method, method.getAnnotation(com.ryantenney.metrics.annotation.CachedGauge.class));
// log.info("Looking up cached gauge method named '{}'", metricName);
// return (CachedGauge<?>) metricRegistry.getGauges().get(metricName);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// @Deprecated
// static String forLegacyCountedMethod(Class<?> klass, Member member, com.ryantenney.metrics.annotation.Counted annotation) {
// return Util.forCountedMethod(klass, member, annotation);
// }
// Path: src/test/java/com/ryantenney/metrics/spring/LegacyAnnotationMeteredClassTest.java
import com.ryantenney.metrics.annotation.Counted;
import static com.ryantenney.metrics.spring.TestUtil.forLegacyCachedGaugeMethod;
import static com.ryantenney.metrics.spring.TestUtil.forLegacyCountedMethod;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.codahale.metrics.CachedGauge;
import com.codahale.metrics.Counter;
import com.codahale.metrics.MetricRegistry;
/**
* Copyright (C) 2012 Ryan W Tenney (ryan@10e.us)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ryantenney.metrics.spring;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:legacy-annotation-metered-class.xml")
@SuppressWarnings("deprecation")
public class LegacyAnnotationMeteredClassTest {
@Autowired
LegacyMeteredClass meteredClass;
MetricRegistry metricRegistry;
@Autowired
public void setMetricRegistry(MetricRegistry metricRegistry) {
this.metricRegistry = metricRegistry;
this.metricRegistry.addListener(new LoggingMetricRegistryListener());
}
@Test
public void gauges() { | CachedGauge<?> cachedGaugedMethod = forLegacyCachedGaugeMethod(metricRegistry, LegacyMeteredClass.class, "cachedGaugedMethod"); |
ryantenney/metrics-spring | src/test/java/com/ryantenney/metrics/spring/LegacyAnnotationMeteredClassTest.java | // Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// @Deprecated
// static CachedGauge<?> forLegacyCachedGaugeMethod(MetricRegistry metricRegistry, Class<?> clazz, String methodName) {
// Method method = findMethod(clazz, methodName);
// String metricName = forLegacyCachedGauge(clazz, method, method.getAnnotation(com.ryantenney.metrics.annotation.CachedGauge.class));
// log.info("Looking up cached gauge method named '{}'", metricName);
// return (CachedGauge<?>) metricRegistry.getGauges().get(metricName);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// @Deprecated
// static String forLegacyCountedMethod(Class<?> klass, Member member, com.ryantenney.metrics.annotation.Counted annotation) {
// return Util.forCountedMethod(klass, member, annotation);
// }
| import com.ryantenney.metrics.annotation.Counted;
import static com.ryantenney.metrics.spring.TestUtil.forLegacyCachedGaugeMethod;
import static com.ryantenney.metrics.spring.TestUtil.forLegacyCountedMethod;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.codahale.metrics.CachedGauge;
import com.codahale.metrics.Counter;
import com.codahale.metrics.MetricRegistry; | /**
* Copyright (C) 2012 Ryan W Tenney (ryan@10e.us)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ryantenney.metrics.spring;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:legacy-annotation-metered-class.xml")
@SuppressWarnings("deprecation")
public class LegacyAnnotationMeteredClassTest {
@Autowired
LegacyMeteredClass meteredClass;
MetricRegistry metricRegistry;
@Autowired
public void setMetricRegistry(MetricRegistry metricRegistry) {
this.metricRegistry = metricRegistry;
this.metricRegistry.addListener(new LoggingMetricRegistryListener());
}
@Test
public void gauges() {
CachedGauge<?> cachedGaugedMethod = forLegacyCachedGaugeMethod(metricRegistry, LegacyMeteredClass.class, "cachedGaugedMethod");
assertEquals(999, cachedGaugedMethod.getValue());
meteredClass.setGaugedField(1000);
assertEquals(999, cachedGaugedMethod.getValue());
}
@Test
public void countedMethod() throws Throwable { | // Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// @Deprecated
// static CachedGauge<?> forLegacyCachedGaugeMethod(MetricRegistry metricRegistry, Class<?> clazz, String methodName) {
// Method method = findMethod(clazz, methodName);
// String metricName = forLegacyCachedGauge(clazz, method, method.getAnnotation(com.ryantenney.metrics.annotation.CachedGauge.class));
// log.info("Looking up cached gauge method named '{}'", metricName);
// return (CachedGauge<?>) metricRegistry.getGauges().get(metricName);
// }
//
// Path: src/test/java/com/ryantenney/metrics/spring/TestUtil.java
// @Deprecated
// static String forLegacyCountedMethod(Class<?> klass, Member member, com.ryantenney.metrics.annotation.Counted annotation) {
// return Util.forCountedMethod(klass, member, annotation);
// }
// Path: src/test/java/com/ryantenney/metrics/spring/LegacyAnnotationMeteredClassTest.java
import com.ryantenney.metrics.annotation.Counted;
import static com.ryantenney.metrics.spring.TestUtil.forLegacyCachedGaugeMethod;
import static com.ryantenney.metrics.spring.TestUtil.forLegacyCountedMethod;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.codahale.metrics.CachedGauge;
import com.codahale.metrics.Counter;
import com.codahale.metrics.MetricRegistry;
/**
* Copyright (C) 2012 Ryan W Tenney (ryan@10e.us)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ryantenney.metrics.spring;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:legacy-annotation-metered-class.xml")
@SuppressWarnings("deprecation")
public class LegacyAnnotationMeteredClassTest {
@Autowired
LegacyMeteredClass meteredClass;
MetricRegistry metricRegistry;
@Autowired
public void setMetricRegistry(MetricRegistry metricRegistry) {
this.metricRegistry = metricRegistry;
this.metricRegistry.addListener(new LoggingMetricRegistryListener());
}
@Test
public void gauges() {
CachedGauge<?> cachedGaugedMethod = forLegacyCachedGaugeMethod(metricRegistry, LegacyMeteredClass.class, "cachedGaugedMethod");
assertEquals(999, cachedGaugedMethod.getValue());
meteredClass.setGaugedField(1000);
assertEquals(999, cachedGaugedMethod.getValue());
}
@Test
public void countedMethod() throws Throwable { | final Counter countedMethod = forLegacyCountedMethod(metricRegistry, LegacyMeteredClass.class, "countedMethod"); |
ryantenney/metrics-spring | src/main/java/com/ryantenney/metrics/spring/reporter/CsvReporterElementParser.java | // Path: src/main/java/com/ryantenney/metrics/spring/reporter/CsvReporterFactoryBean.java
// public class CsvReporterFactoryBean extends AbstractScheduledReporterFactoryBean<CsvReporter> {
//
// // Required
// public static final String PERIOD = "period";
//
// // Optional
// public static final String CLOCK_REF = "clock-ref";
// public static final String DIRECTORY = "directory";
// public static final String LOCALE = "locale";
// public static final String DURATION_UNIT = "duration-unit";
// public static final String RATE_UNIT = "rate-unit";
//
// @Override
// public Class<CsvReporter> getObjectType() {
// return CsvReporter.class;
// }
//
// @Override
// protected CsvReporter createInstance() {
// final CsvReporter.Builder reporter = CsvReporter.forRegistry(getMetricRegistry());
//
// if (hasProperty(DURATION_UNIT)) {
// reporter.convertDurationsTo(getProperty(DURATION_UNIT, TimeUnit.class));
// }
//
// if (hasProperty(RATE_UNIT)) {
// reporter.convertRatesTo(getProperty(RATE_UNIT, TimeUnit.class));
// }
//
// reporter.filter(getMetricFilter());
//
// if (hasProperty(CLOCK_REF)) {
// reporter.withClock(getPropertyRef(CLOCK_REF, Clock.class));
// }
//
// if (hasProperty(LOCALE)) {
// reporter.formatFor(parseLocale(getProperty(LOCALE)));
// }
//
// File dir = new File(getProperty(DIRECTORY));
// if (!dir.mkdirs() && !dir.isDirectory()) {
// throw new IllegalArgumentException("Directory doesn't exist or couldn't be created");
// }
//
// return reporter.build(dir);
// }
//
// @Override
// protected long getPeriod() {
// return convertDurationString(getProperty(PERIOD));
// }
//
// protected Locale parseLocale(String localeString) {
// final int underscore = localeString.indexOf('_');
// if (underscore == -1) {
// return new Locale(localeString);
// }
// else {
// return new Locale(localeString.substring(0, underscore), localeString.substring(underscore + 1));
// }
// }
//
// }
| import static com.ryantenney.metrics.spring.reporter.CsvReporterFactoryBean.*; | /**
* Copyright (C) 2012 Ryan W Tenney (ryan@10e.us)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ryantenney.metrics.spring.reporter;
public class CsvReporterElementParser extends AbstractReporterElementParser {
private static final String LOCALE_STRING_REGEX = "^[a-z]{2}(_[A-Z]{2})?$";
@Override
public String getType() {
return "csv";
}
@Override
protected Class<?> getBeanClass() { | // Path: src/main/java/com/ryantenney/metrics/spring/reporter/CsvReporterFactoryBean.java
// public class CsvReporterFactoryBean extends AbstractScheduledReporterFactoryBean<CsvReporter> {
//
// // Required
// public static final String PERIOD = "period";
//
// // Optional
// public static final String CLOCK_REF = "clock-ref";
// public static final String DIRECTORY = "directory";
// public static final String LOCALE = "locale";
// public static final String DURATION_UNIT = "duration-unit";
// public static final String RATE_UNIT = "rate-unit";
//
// @Override
// public Class<CsvReporter> getObjectType() {
// return CsvReporter.class;
// }
//
// @Override
// protected CsvReporter createInstance() {
// final CsvReporter.Builder reporter = CsvReporter.forRegistry(getMetricRegistry());
//
// if (hasProperty(DURATION_UNIT)) {
// reporter.convertDurationsTo(getProperty(DURATION_UNIT, TimeUnit.class));
// }
//
// if (hasProperty(RATE_UNIT)) {
// reporter.convertRatesTo(getProperty(RATE_UNIT, TimeUnit.class));
// }
//
// reporter.filter(getMetricFilter());
//
// if (hasProperty(CLOCK_REF)) {
// reporter.withClock(getPropertyRef(CLOCK_REF, Clock.class));
// }
//
// if (hasProperty(LOCALE)) {
// reporter.formatFor(parseLocale(getProperty(LOCALE)));
// }
//
// File dir = new File(getProperty(DIRECTORY));
// if (!dir.mkdirs() && !dir.isDirectory()) {
// throw new IllegalArgumentException("Directory doesn't exist or couldn't be created");
// }
//
// return reporter.build(dir);
// }
//
// @Override
// protected long getPeriod() {
// return convertDurationString(getProperty(PERIOD));
// }
//
// protected Locale parseLocale(String localeString) {
// final int underscore = localeString.indexOf('_');
// if (underscore == -1) {
// return new Locale(localeString);
// }
// else {
// return new Locale(localeString.substring(0, underscore), localeString.substring(underscore + 1));
// }
// }
//
// }
// Path: src/main/java/com/ryantenney/metrics/spring/reporter/CsvReporterElementParser.java
import static com.ryantenney.metrics.spring.reporter.CsvReporterFactoryBean.*;
/**
* Copyright (C) 2012 Ryan W Tenney (ryan@10e.us)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ryantenney.metrics.spring.reporter;
public class CsvReporterElementParser extends AbstractReporterElementParser {
private static final String LOCALE_STRING_REGEX = "^[a-z]{2}(_[A-Z]{2})?$";
@Override
public String getType() {
return "csv";
}
@Override
protected Class<?> getBeanClass() { | return CsvReporterFactoryBean.class; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.